boolean>}
*/
const OPERATOR_EVALUATORS = {
'>=': (breakpointValue, width) => width >= breakpointValue,
'<': (breakpointValue, width) => width < breakpointValue
};
const ViewportMatchWidthContext = (0,external_wp_element_namespaceObject.createContext)( /** @type {null | number} */null);
/**
* Returns true if the viewport matches the given query, or false otherwise.
*
* @param {WPBreakpoint} breakpoint Breakpoint size name.
* @param {WPViewportOperator} [operator=">="] Viewport operator.
*
* @example
*
* ```js
* useViewportMatch( 'huge', '<' );
* useViewportMatch( 'medium' );
* ```
*
* @return {boolean} Whether viewport matches query.
*/
const useViewportMatch = (breakpoint, operator = '>=') => {
const simulatedWidth = (0,external_wp_element_namespaceObject.useContext)(ViewportMatchWidthContext);
const mediaQuery = !simulatedWidth && `(${CONDITIONS[operator]}: ${BREAKPOINTS[breakpoint]}px)`;
const mediaQueryResult = useMediaQuery(mediaQuery || undefined);
if (simulatedWidth) {
return OPERATOR_EVALUATORS[operator](BREAKPOINTS[breakpoint], simulatedWidth);
}
return mediaQueryResult;
};
useViewportMatch.__experimentalWidthProvider = ViewportMatchWidthContext.Provider;
/* harmony default export */ const use_viewport_match = (useViewportMatch);
;// CONCATENATED MODULE: ./node_modules/@wordpress/compose/build-module/hooks/use-resize-observer/index.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
// This of course could've been more streamlined with internal state instead of
// refs, but then host hooks / components could not opt out of renders.
// This could've been exported to its own module, but the current build doesn't
// seem to work with module imports and I had no more time to spend on this...
function useResolvedElement(subscriber, refOrElement) {
const callbackRefElement = (0,external_wp_element_namespaceObject.useRef)(null);
const lastReportRef = (0,external_wp_element_namespaceObject.useRef)(null);
const cleanupRef = (0,external_wp_element_namespaceObject.useRef)();
const callSubscriber = (0,external_wp_element_namespaceObject.useCallback)(() => {
let element = null;
if (callbackRefElement.current) {
element = callbackRefElement.current;
} else if (refOrElement) {
if (refOrElement instanceof HTMLElement) {
element = refOrElement;
} else {
element = refOrElement.current;
}
}
if (lastReportRef.current && lastReportRef.current.element === element && lastReportRef.current.reporter === callSubscriber) {
return;
}
if (cleanupRef.current) {
cleanupRef.current();
// Making sure the cleanup is not called accidentally multiple times.
cleanupRef.current = null;
}
lastReportRef.current = {
reporter: callSubscriber,
element
};
// Only calling the subscriber, if there's an actual element to report.
if (element) {
cleanupRef.current = subscriber(element);
}
}, [refOrElement, subscriber]);
// On each render, we check whether a ref changed, or if we got a new raw
// element.
(0,external_wp_element_namespaceObject.useEffect)(() => {
// With this we're *technically* supporting cases where ref objects' current value changes, but only if there's a
// render accompanying that change as well.
// To guarantee we always have the right element, one must use the ref callback provided instead, but we support
// RefObjects to make the hook API more convenient in certain cases.
callSubscriber();
}, [callSubscriber]);
return (0,external_wp_element_namespaceObject.useCallback)(element => {
callbackRefElement.current = element;
callSubscriber();
}, [callSubscriber]);
}
// We're only using the first element of the size sequences, until future versions of the spec solidify on how
// exactly it'll be used for fragments in multi-column scenarios:
// From the spec:
// > The box size properties are exposed as FrozenArray in order to support elements that have multiple fragments,
// > which occur in multi-column scenarios. However the current definitions of content rect and border box do not
// > mention how those boxes are affected by multi-column layout. In this spec, there will only be a single
// > ResizeObserverSize returned in the FrozenArray, which will correspond to the dimensions of the first column.
// > A future version of this spec will extend the returned FrozenArray to contain the per-fragment size information.
// (https://drafts.csswg.org/resize-observer/#resize-observer-entry-interface)
//
// Also, testing these new box options revealed that in both Chrome and FF everything is returned in the callback,
// regardless of the "box" option.
// The spec states the following on this:
// > This does not have any impact on which box dimensions are returned to the defined callback when the event
// > is fired, it solely defines which box the author wishes to observe layout changes on.
// (https://drafts.csswg.org/resize-observer/#resize-observer-interface)
// I'm not exactly clear on what this means, especially when you consider a later section stating the following:
// > This section is non-normative. An author may desire to observe more than one CSS box.
// > In this case, author will need to use multiple ResizeObservers.
// (https://drafts.csswg.org/resize-observer/#resize-observer-interface)
// Which is clearly not how current browser implementations behave, and seems to contradict the previous quote.
// For this reason I decided to only return the requested size,
// even though it seems we have access to results for all box types.
// This also means that we get to keep the current api, being able to return a simple { width, height } pair,
// regardless of box option.
const extractSize = (entry, boxProp, sizeType) => {
if (!entry[boxProp]) {
if (boxProp === 'contentBoxSize') {
// The dimensions in `contentBoxSize` and `contentRect` are equivalent according to the spec.
// See the 6th step in the description for the RO algorithm:
// https://drafts.csswg.org/resize-observer/#create-and-populate-resizeobserverentry-h
// > Set this.contentRect to logical this.contentBoxSize given target and observedBox of "content-box".
// In real browser implementations of course these objects differ, but the width/height values should be equivalent.
return entry.contentRect[sizeType === 'inlineSize' ? 'width' : 'height'];
}
return undefined;
}
// A couple bytes smaller than calling Array.isArray() and just as effective here.
return entry[boxProp][0] ? entry[boxProp][0][sizeType] :
// TS complains about this, because the RO entry type follows the spec and does not reflect Firefox's current
// behaviour of returning objects instead of arrays for `borderBoxSize` and `contentBoxSize`.
// @ts-ignore
entry[boxProp][sizeType];
};
function useResizeObserver(opts = {}) {
// Saving the callback as a ref. With this, I don't need to put onResize in the
// effect dep array, and just passing in an anonymous function without memoising
// will not reinstantiate the hook's ResizeObserver.
const onResize = opts.onResize;
const onResizeRef = (0,external_wp_element_namespaceObject.useRef)(undefined);
onResizeRef.current = onResize;
const round = opts.round || Math.round;
// Using a single instance throughout the hook's lifetime
const resizeObserverRef = (0,external_wp_element_namespaceObject.useRef)();
const [size, setSize] = (0,external_wp_element_namespaceObject.useState)({
width: undefined,
height: undefined
});
// In certain edge cases the RO might want to report a size change just after
// the component unmounted.
const didUnmount = (0,external_wp_element_namespaceObject.useRef)(false);
(0,external_wp_element_namespaceObject.useEffect)(() => {
didUnmount.current = false;
return () => {
didUnmount.current = true;
};
}, []);
// Using a ref to track the previous width / height to avoid unnecessary renders.
const previous = (0,external_wp_element_namespaceObject.useRef)({
width: undefined,
height: undefined
});
// This block is kinda like a useEffect, only it's called whenever a new
// element could be resolved based on the ref option. It also has a cleanup
// function.
const refCallback = useResolvedElement((0,external_wp_element_namespaceObject.useCallback)(element => {
// We only use a single Resize Observer instance, and we're instantiating it on demand, only once there's something to observe.
// This instance is also recreated when the `box` option changes, so that a new observation is fired if there was a previously observed element with a different box option.
if (!resizeObserverRef.current || resizeObserverRef.current.box !== opts.box || resizeObserverRef.current.round !== round) {
resizeObserverRef.current = {
box: opts.box,
round,
instance: new ResizeObserver(entries => {
const entry = entries[0];
let boxProp = 'borderBoxSize';
if (opts.box === 'border-box') {
boxProp = 'borderBoxSize';
} else {
boxProp = opts.box === 'device-pixel-content-box' ? 'devicePixelContentBoxSize' : 'contentBoxSize';
}
const reportedWidth = extractSize(entry, boxProp, 'inlineSize');
const reportedHeight = extractSize(entry, boxProp, 'blockSize');
const newWidth = reportedWidth ? round(reportedWidth) : undefined;
const newHeight = reportedHeight ? round(reportedHeight) : undefined;
if (previous.current.width !== newWidth || previous.current.height !== newHeight) {
const newSize = {
width: newWidth,
height: newHeight
};
previous.current.width = newWidth;
previous.current.height = newHeight;
if (onResizeRef.current) {
onResizeRef.current(newSize);
} else if (!didUnmount.current) {
setSize(newSize);
}
}
})
};
}
resizeObserverRef.current.instance.observe(element, {
box: opts.box
});
return () => {
if (resizeObserverRef.current) {
resizeObserverRef.current.instance.unobserve(element);
}
};
}, [opts.box, round]), opts.ref);
return (0,external_wp_element_namespaceObject.useMemo)(() => ({
ref: refCallback,
width: size.width,
height: size.height
}), [refCallback, size ? size.width : null, size ? size.height : null]);
}
/**
* Hook which allows to listen the resize event of any target element when it changes sizes.
* _Note: `useResizeObserver` will report `null` until after first render.
*
* @example
*
* ```js
* const App = () => {
* const [ resizeListener, sizes ] = useResizeObserver();
*
* return (
*
* { resizeListener }
* Your content here
*
* );
* };
* ```
*/
function useResizeAware() {
const {
ref,
width,
height
} = useResizeObserver();
const sizes = (0,external_wp_element_namespaceObject.useMemo)(() => {
return {
width: width !== null && width !== void 0 ? width : null,
height: height !== null && height !== void 0 ? height : null
};
}, [width, height]);
const resizeListener = (0,external_React_namespaceObject.createElement)("div", {
style: {
position: 'absolute',
top: 0,
left: 0,
right: 0,
bottom: 0,
pointerEvents: 'none',
opacity: 0,
overflow: 'hidden',
zIndex: -1
},
"aria-hidden": "true",
ref: ref
});
return [resizeListener, sizes];
}
;// CONCATENATED MODULE: external ["wp","priorityQueue"]
const external_wp_priorityQueue_namespaceObject = window["wp"]["priorityQueue"];
;// CONCATENATED MODULE: ./node_modules/@wordpress/compose/build-module/hooks/use-async-list/index.js
/**
* WordPress dependencies
*/
/**
* Returns the first items from list that are present on state.
*
* @param list New array.
* @param state Current state.
* @return First items present iin state.
*/
function getFirstItemsPresentInState(list, state) {
const firstItems = [];
for (let i = 0; i < list.length; i++) {
const item = list[i];
if (!state.includes(item)) {
break;
}
firstItems.push(item);
}
return firstItems;
}
/**
* React hook returns an array which items get asynchronously appended from a source array.
* This behavior is useful if we want to render a list of items asynchronously for performance reasons.
*
* @param list Source array.
* @param config Configuration object.
*
* @return Async array.
*/
function useAsyncList(list, config = {
step: 1
}) {
const {
step = 1
} = config;
const [current, setCurrent] = (0,external_wp_element_namespaceObject.useState)([]);
(0,external_wp_element_namespaceObject.useEffect)(() => {
// On reset, we keep the first items that were previously rendered.
let firstItems = getFirstItemsPresentInState(list, current);
if (firstItems.length < step) {
firstItems = firstItems.concat(list.slice(firstItems.length, step));
}
setCurrent(firstItems);
const asyncQueue = (0,external_wp_priorityQueue_namespaceObject.createQueue)();
for (let i = firstItems.length; i < list.length; i += step) {
asyncQueue.add({}, () => {
(0,external_wp_element_namespaceObject.flushSync)(() => {
setCurrent(state => [...state, ...list.slice(i, i + step)]);
});
});
}
return () => asyncQueue.reset();
}, [list]);
return current;
}
/* harmony default export */ const use_async_list = (useAsyncList);
;// CONCATENATED MODULE: ./node_modules/@wordpress/compose/build-module/hooks/use-warn-on-change/index.js
/**
* Internal dependencies
*/
// Disable reason: Object and object are distinctly different types in TypeScript and we mean the lowercase object in thise case
// but eslint wants to force us to use `Object`. See https://stackoverflow.com/questions/49464634/difference-between-object-and-object-in-typescript
/* eslint-disable jsdoc/check-types */
/**
* Hook that performs a shallow comparison between the preview value of an object
* and the new one, if there's a difference, it prints it to the console.
* this is useful in performance related work, to check why a component re-renders.
*
* @example
*
* ```jsx
* function MyComponent(props) {
* useWarnOnChange(props);
*
* return "Something";
* }
* ```
*
* @param {object} object Object which changes to compare.
* @param {string} prefix Just a prefix to show when console logging.
*/
function useWarnOnChange(object, prefix = 'Change detection') {
const previousValues = usePrevious(object);
Object.entries(previousValues !== null && previousValues !== void 0 ? previousValues : []).forEach(([key, value]) => {
if (value !== object[( /** @type {keyof typeof object} */key)]) {
// eslint-disable-next-line no-console
console.warn(`${prefix}: ${key} key changed:`, value, object[( /** @type {keyof typeof object} */key)]
/* eslint-enable jsdoc/check-types */);
}
});
}
/* harmony default export */ const use_warn_on_change = (useWarnOnChange);
;// CONCATENATED MODULE: ./node_modules/use-memo-one/dist/use-memo-one.esm.js
function areInputsEqual(newInputs, lastInputs) {
if (newInputs.length !== lastInputs.length) {
return false;
}
for (var i = 0; i < newInputs.length; i++) {
if (newInputs[i] !== lastInputs[i]) {
return false;
}
}
return true;
}
function useMemoOne(getResult, inputs) {
var initial = (0,external_React_namespaceObject.useState)(function () {
return {
inputs: inputs,
result: getResult()
};
})[0];
var isFirstRun = (0,external_React_namespaceObject.useRef)(true);
var committed = (0,external_React_namespaceObject.useRef)(initial);
var useCache = isFirstRun.current || Boolean(inputs && committed.current.inputs && areInputsEqual(inputs, committed.current.inputs));
var cache = useCache ? committed.current : {
inputs: inputs,
result: getResult()
};
(0,external_React_namespaceObject.useEffect)(function () {
isFirstRun.current = false;
committed.current = cache;
}, [cache]);
return cache.result;
}
function useCallbackOne(callback, inputs) {
return useMemoOne(function () {
return callback;
}, inputs);
}
var useMemo = (/* unused pure expression or super */ null && (useMemoOne));
var useCallback = (/* unused pure expression or super */ null && (useCallbackOne));
;// CONCATENATED MODULE: ./node_modules/@wordpress/compose/build-module/hooks/use-debounce/index.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/**
* Debounces a function similar to Lodash's `debounce`. A new debounced function will
* be returned and any scheduled calls cancelled if any of the arguments change,
* including the function to debounce, so please wrap functions created on
* render in components in `useCallback`.
*
* @see https://docs-lodash.com/v4/debounce/
*
* @template {(...args: any[]) => void} TFunc
*
* @param {TFunc} fn The function to debounce.
* @param {number} [wait] The number of milliseconds to delay.
* @param {import('../../utils/debounce').DebounceOptions} [options] The options object.
* @return {import('../../utils/debounce').DebouncedFunc} Debounced function.
*/
function useDebounce(fn, wait, options) {
const debounced = useMemoOne(() => debounce(fn, wait !== null && wait !== void 0 ? wait : 0, options), [fn, wait, options]);
(0,external_wp_element_namespaceObject.useEffect)(() => () => debounced.cancel(), [debounced]);
return debounced;
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/compose/build-module/hooks/use-debounced-input/index.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/**
* Helper hook for input fields that need to debounce the value before using it.
*
* @param {any} defaultValue The default value to use.
* @return {[string, Function, string]} The input value, the setter and the debounced input value.
*/
function useDebouncedInput(defaultValue = '') {
const [input, setInput] = (0,external_wp_element_namespaceObject.useState)(defaultValue);
const [debouncedInput, setDebouncedState] = (0,external_wp_element_namespaceObject.useState)(defaultValue);
const setDebouncedInput = useDebounce(setDebouncedState, 250);
(0,external_wp_element_namespaceObject.useEffect)(() => {
setDebouncedInput(input);
}, [input]);
return [input, setInput, debouncedInput];
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/compose/build-module/hooks/use-throttle/index.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/**
* Throttles a function similar to Lodash's `throttle`. A new throttled function will
* be returned and any scheduled calls cancelled if any of the arguments change,
* including the function to throttle, so please wrap functions created on
* render in components in `useCallback`.
*
* @see https://docs-lodash.com/v4/throttle/
*
* @template {(...args: any[]) => void} TFunc
*
* @param {TFunc} fn The function to throttle.
* @param {number} [wait] The number of milliseconds to throttle invocations to.
* @param {import('../../utils/throttle').ThrottleOptions} [options] The options object. See linked documentation for details.
* @return {import('../../utils/debounce').DebouncedFunc} Throttled function.
*/
function useThrottle(fn, wait, options) {
const throttled = useMemoOne(() => throttle(fn, wait !== null && wait !== void 0 ? wait : 0, options), [fn, wait, options]);
(0,external_wp_element_namespaceObject.useEffect)(() => () => throttled.cancel(), [throttled]);
return throttled;
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/compose/build-module/hooks/use-drop-zone/index.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/* eslint-disable jsdoc/valid-types */
/**
* @template T
* @param {T} value
* @return {import('react').MutableRefObject} A ref with the value.
*/
function useFreshRef(value) {
/* eslint-enable jsdoc/valid-types */
/* eslint-disable jsdoc/no-undefined-types */
/** @type {import('react').MutableRefObject} */
/* eslint-enable jsdoc/no-undefined-types */
// Disable reason: We're doing something pretty JavaScript-y here where the
// ref will always have a current value that is not null or undefined but it
// needs to start as undefined. We don't want to change the return type so
// it's easier to just ts-ignore this specific line that's complaining about
// undefined not being part of T.
// @ts-ignore
const ref = (0,external_wp_element_namespaceObject.useRef)();
ref.current = value;
return ref;
}
/**
* A hook to facilitate drag and drop handling.
*
* @param {Object} props Named parameters.
* @param {?HTMLElement} [props.dropZoneElement] Optional element to be used as the drop zone.
* @param {boolean} [props.isDisabled] Whether or not to disable the drop zone.
* @param {(e: DragEvent) => void} [props.onDragStart] Called when dragging has started.
* @param {(e: DragEvent) => void} [props.onDragEnter] Called when the zone is entered.
* @param {(e: DragEvent) => void} [props.onDragOver] Called when the zone is moved within.
* @param {(e: DragEvent) => void} [props.onDragLeave] Called when the zone is left.
* @param {(e: MouseEvent) => void} [props.onDragEnd] Called when dragging has ended.
* @param {(e: DragEvent) => void} [props.onDrop] Called when dropping in the zone.
*
* @return {import('react').RefCallback} Ref callback to be passed to the drop zone element.
*/
function useDropZone({
dropZoneElement,
isDisabled,
onDrop: _onDrop,
onDragStart: _onDragStart,
onDragEnter: _onDragEnter,
onDragLeave: _onDragLeave,
onDragEnd: _onDragEnd,
onDragOver: _onDragOver
}) {
const onDropRef = useFreshRef(_onDrop);
const onDragStartRef = useFreshRef(_onDragStart);
const onDragEnterRef = useFreshRef(_onDragEnter);
const onDragLeaveRef = useFreshRef(_onDragLeave);
const onDragEndRef = useFreshRef(_onDragEnd);
const onDragOverRef = useFreshRef(_onDragOver);
return useRefEffect(elem => {
if (isDisabled) {
return;
}
// If a custom dropZoneRef is passed, use that instead of the element.
// This allows the dropzone to cover an expanded area, rather than
// be restricted to the area of the ref returned by this hook.
const element = dropZoneElement !== null && dropZoneElement !== void 0 ? dropZoneElement : elem;
let isDragging = false;
const {
ownerDocument
} = element;
/**
* Checks if an element is in the drop zone.
*
* @param {EventTarget|null} targetToCheck
*
* @return {boolean} True if in drop zone, false if not.
*/
function isElementInZone(targetToCheck) {
const {
defaultView
} = ownerDocument;
if (!targetToCheck || !defaultView || !(targetToCheck instanceof defaultView.HTMLElement) || !element.contains(targetToCheck)) {
return false;
}
/** @type {HTMLElement|null} */
let elementToCheck = targetToCheck;
do {
if (elementToCheck.dataset.isDropZone) {
return elementToCheck === element;
}
} while (elementToCheck = elementToCheck.parentElement);
return false;
}
function maybeDragStart( /** @type {DragEvent} */event) {
if (isDragging) {
return;
}
isDragging = true;
// Note that `dragend` doesn't fire consistently for file and
// HTML drag events where the drag origin is outside the browser
// window. In Firefox it may also not fire if the originating
// node is removed.
ownerDocument.addEventListener('dragend', maybeDragEnd);
ownerDocument.addEventListener('mousemove', maybeDragEnd);
if (onDragStartRef.current) {
onDragStartRef.current(event);
}
}
function onDragEnter( /** @type {DragEvent} */event) {
event.preventDefault();
// The `dragenter` event will also fire when entering child
// elements, but we only want to call `onDragEnter` when
// entering the drop zone, which means the `relatedTarget`
// (element that has been left) should be outside the drop zone.
if (element.contains( /** @type {Node} */event.relatedTarget)) {
return;
}
if (onDragEnterRef.current) {
onDragEnterRef.current(event);
}
}
function onDragOver( /** @type {DragEvent} */event) {
// Only call onDragOver for the innermost hovered drop zones.
if (!event.defaultPrevented && onDragOverRef.current) {
onDragOverRef.current(event);
}
// Prevent the browser default while also signalling to parent
// drop zones that `onDragOver` is already handled.
event.preventDefault();
}
function onDragLeave( /** @type {DragEvent} */event) {
// The `dragleave` event will also fire when leaving child
// elements, but we only want to call `onDragLeave` when
// leaving the drop zone, which means the `relatedTarget`
// (element that has been entered) should be outside the drop
// zone.
// Note: This is not entirely reliable in Safari due to this bug
// https://bugs.webkit.org/show_bug.cgi?id=66547
if (isElementInZone(event.relatedTarget)) {
return;
}
if (onDragLeaveRef.current) {
onDragLeaveRef.current(event);
}
}
function onDrop( /** @type {DragEvent} */event) {
// Don't handle drop if an inner drop zone already handled it.
if (event.defaultPrevented) {
return;
}
// Prevent the browser default while also signalling to parent
// drop zones that `onDrop` is already handled.
event.preventDefault();
// This seemingly useless line has been shown to resolve a
// Safari issue where files dragged directly from the dock are
// not recognized.
// eslint-disable-next-line no-unused-expressions
event.dataTransfer && event.dataTransfer.files.length;
if (onDropRef.current) {
onDropRef.current(event);
}
maybeDragEnd(event);
}
function maybeDragEnd( /** @type {MouseEvent} */event) {
if (!isDragging) {
return;
}
isDragging = false;
ownerDocument.removeEventListener('dragend', maybeDragEnd);
ownerDocument.removeEventListener('mousemove', maybeDragEnd);
if (onDragEndRef.current) {
onDragEndRef.current(event);
}
}
element.dataset.isDropZone = 'true';
element.addEventListener('drop', onDrop);
element.addEventListener('dragenter', onDragEnter);
element.addEventListener('dragover', onDragOver);
element.addEventListener('dragleave', onDragLeave);
// The `dragstart` event doesn't fire if the drag started outside
// the document.
ownerDocument.addEventListener('dragenter', maybeDragStart);
return () => {
delete element.dataset.isDropZone;
element.removeEventListener('drop', onDrop);
element.removeEventListener('dragenter', onDragEnter);
element.removeEventListener('dragover', onDragOver);
element.removeEventListener('dragleave', onDragLeave);
ownerDocument.removeEventListener('dragend', maybeDragEnd);
ownerDocument.removeEventListener('mousemove', maybeDragEnd);
ownerDocument.removeEventListener('dragenter', maybeDragStart);
};
}, [isDisabled, dropZoneElement] // Refresh when the passed in dropZoneElement changes.
);
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/compose/build-module/hooks/use-focusable-iframe/index.js
/**
* External dependencies
*/
/**
* Internal dependencies
*/
/**
* Dispatches a bubbling focus event when the iframe receives focus. Use
* `onFocus` as usual on the iframe or a parent element.
*
* @return Ref to pass to the iframe.
*/
function useFocusableIframe() {
return useRefEffect(element => {
const {
ownerDocument
} = element;
if (!ownerDocument) return;
const {
defaultView
} = ownerDocument;
if (!defaultView) return;
/**
* Checks whether the iframe is the activeElement, inferring that it has
* then received focus, and dispatches a focus event.
*/
function checkFocus() {
if (ownerDocument && ownerDocument.activeElement === element) {
element.focus();
}
}
defaultView.addEventListener('blur', checkFocus);
return () => {
defaultView.removeEventListener('blur', checkFocus);
};
}, []);
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/compose/build-module/hooks/use-fixed-window-list/index.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const DEFAULT_INIT_WINDOW_SIZE = 30;
/**
* @typedef {Object} WPFixedWindowList
*
* @property {number} visibleItems Items visible in the current viewport
* @property {number} start Start index of the window
* @property {number} end End index of the window
* @property {(index:number)=>boolean} itemInView Returns true if item is in the window
*/
/**
* @typedef {Object} WPFixedWindowListOptions
*
* @property {number} [windowOverscan] Renders windowOverscan number of items before and after the calculated visible window.
* @property {boolean} [useWindowing] When false avoids calculating the window size
* @property {number} [initWindowSize] Initial window size to use on first render before we can calculate the window size.
* @property {any} [expandedState] Used to recalculate the window size when the expanded state of a list changes.
*/
/**
*
* @param {import('react').RefObject} elementRef Used to find the closest scroll container that contains element.
* @param { number } itemHeight Fixed item height in pixels
* @param { number } totalItems Total items in list
* @param { WPFixedWindowListOptions } [options] Options object
* @return {[ WPFixedWindowList, setFixedListWindow:(nextWindow:WPFixedWindowList)=>void]} Array with the fixed window list and setter
*/
function useFixedWindowList(elementRef, itemHeight, totalItems, options) {
var _options$initWindowSi, _options$useWindowing;
const initWindowSize = (_options$initWindowSi = options?.initWindowSize) !== null && _options$initWindowSi !== void 0 ? _options$initWindowSi : DEFAULT_INIT_WINDOW_SIZE;
const useWindowing = (_options$useWindowing = options?.useWindowing) !== null && _options$useWindowing !== void 0 ? _options$useWindowing : true;
const [fixedListWindow, setFixedListWindow] = (0,external_wp_element_namespaceObject.useState)({
visibleItems: initWindowSize,
start: 0,
end: initWindowSize,
itemInView: ( /** @type {number} */index) => {
return index >= 0 && index <= initWindowSize;
}
});
(0,external_wp_element_namespaceObject.useLayoutEffect)(() => {
if (!useWindowing) {
return;
}
const scrollContainer = (0,external_wp_dom_namespaceObject.getScrollContainer)(elementRef.current);
const measureWindow = ( /** @type {boolean | undefined} */initRender) => {
var _options$windowOversc;
if (!scrollContainer) {
return;
}
const visibleItems = Math.ceil(scrollContainer.clientHeight / itemHeight);
// Aim to keep opening list view fast, afterward we can optimize for scrolling.
const windowOverscan = initRender ? visibleItems : (_options$windowOversc = options?.windowOverscan) !== null && _options$windowOversc !== void 0 ? _options$windowOversc : visibleItems;
const firstViewableIndex = Math.floor(scrollContainer.scrollTop / itemHeight);
const start = Math.max(0, firstViewableIndex - windowOverscan);
const end = Math.min(totalItems - 1, firstViewableIndex + visibleItems + windowOverscan);
setFixedListWindow(lastWindow => {
const nextWindow = {
visibleItems,
start,
end,
itemInView: ( /** @type {number} */index) => {
return start <= index && index <= end;
}
};
if (lastWindow.start !== nextWindow.start || lastWindow.end !== nextWindow.end || lastWindow.visibleItems !== nextWindow.visibleItems) {
return nextWindow;
}
return lastWindow;
});
};
measureWindow(true);
const debounceMeasureList = debounce(() => {
measureWindow();
}, 16);
scrollContainer?.addEventListener('scroll', debounceMeasureList);
scrollContainer?.ownerDocument?.defaultView?.addEventListener('resize', debounceMeasureList);
scrollContainer?.ownerDocument?.defaultView?.addEventListener('resize', debounceMeasureList);
return () => {
scrollContainer?.removeEventListener('scroll', debounceMeasureList);
scrollContainer?.ownerDocument?.defaultView?.removeEventListener('resize', debounceMeasureList);
};
}, [itemHeight, elementRef, totalItems, options?.expandedState, options?.windowOverscan, useWindowing]);
(0,external_wp_element_namespaceObject.useLayoutEffect)(() => {
if (!useWindowing) {
return;
}
const scrollContainer = (0,external_wp_dom_namespaceObject.getScrollContainer)(elementRef.current);
const handleKeyDown = ( /** @type {KeyboardEvent} */event) => {
switch (event.keyCode) {
case external_wp_keycodes_namespaceObject.HOME:
{
return scrollContainer?.scrollTo({
top: 0
});
}
case external_wp_keycodes_namespaceObject.END:
{
return scrollContainer?.scrollTo({
top: totalItems * itemHeight
});
}
case external_wp_keycodes_namespaceObject.PAGEUP:
{
return scrollContainer?.scrollTo({
top: scrollContainer.scrollTop - fixedListWindow.visibleItems * itemHeight
});
}
case external_wp_keycodes_namespaceObject.PAGEDOWN:
{
return scrollContainer?.scrollTo({
top: scrollContainer.scrollTop + fixedListWindow.visibleItems * itemHeight
});
}
}
};
scrollContainer?.ownerDocument?.defaultView?.addEventListener('keydown', handleKeyDown);
return () => {
scrollContainer?.ownerDocument?.defaultView?.removeEventListener('keydown', handleKeyDown);
};
}, [totalItems, itemHeight, elementRef, fixedListWindow.visibleItems, useWindowing, options?.expandedState]);
return [fixedListWindow, setFixedListWindow];
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/compose/build-module/index.js
// The `createHigherOrderComponent` helper and helper types.
// The `debounce` helper and its types.
// The `throttle` helper and its types.
// The `compose` and `pipe` helpers (inspired by `flowRight` and `flow` from Lodash).
// Higher-order components.
// Hooks.
})();
(window.wp = window.wp || {}).compose = __webpack_exports__;
/******/ })()
;