reactdesk-core
Version:
A powerful React-based desktop environment library for creating Windows 11-like desktop interfaces with window management, taskbar, themes, and more
14,360 lines • 460 kB
JavaScript
import { jsxs, jsx, Fragment } from "react/jsx-runtime";
import * as React from "react";
import React__default, { createContext, memo, useContext as useContext$a, useState, useEffect, useRef, useCallback as useCallback$1, forwardRef, useMemo as useMemo$1, useLayoutEffect as useLayoutEffect$1, useInsertionEffect, createElement, useId, cloneElement, Children, isValidElement, lazy } from "react";
import styled, { useTheme, css, ThemeProvider } from "styled-components";
import require$$2, { unstable_batchedUpdates, flushSync } from "react-dom";
const contextFactory = (useContextState, ContextComponent) => {
const Context = createContext(/* @__PURE__ */ Object.create(null));
return {
Context,
Provider: memo(({ children, ...props }) => /* @__PURE__ */ jsxs(Context.Provider, { value: useContextState(props), children: [
children,
ContextComponent
] })),
useContext: () => useContext$a(Context)
};
};
var commonjsGlobal = typeof globalThis !== "undefined" ? globalThis : typeof window !== "undefined" ? window : typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : {};
function getDefaultExportFromCjs(x) {
return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, "default") ? x["default"] : x;
}
function getAugmentedNamespace(n) {
if (n.__esModule) return n;
var f = n.default;
if (typeof f == "function") {
var a = function a2() {
if (this instanceof a2) {
return Reflect.construct(f, arguments, this.constructor);
}
return f.apply(this, arguments);
};
a.prototype = f.prototype;
} else a = {};
Object.defineProperty(a, "__esModule", { value: true });
Object.keys(n).forEach(function(k) {
var d = Object.getOwnPropertyDescriptor(n, k);
Object.defineProperty(a, k, d.get ? d : {
enumerable: true,
get: function() {
return n[k];
}
});
});
return a;
}
function assertPath(path) {
if (typeof path !== "string") {
throw new TypeError("Path must be a string. Received " + JSON.stringify(path));
}
}
function normalizeStringPosix(path, allowAboveRoot) {
var res = "";
var lastSegmentLength = 0;
var lastSlash = -1;
var dots = 0;
var code;
for (var i = 0; i <= path.length; ++i) {
if (i < path.length)
code = path.charCodeAt(i);
else if (code === 47)
break;
else
code = 47;
if (code === 47) {
if (lastSlash === i - 1 || dots === 1) ;
else if (lastSlash !== i - 1 && dots === 2) {
if (res.length < 2 || lastSegmentLength !== 2 || res.charCodeAt(res.length - 1) !== 46 || res.charCodeAt(res.length - 2) !== 46) {
if (res.length > 2) {
var lastSlashIndex = res.lastIndexOf("/");
if (lastSlashIndex !== res.length - 1) {
if (lastSlashIndex === -1) {
res = "";
lastSegmentLength = 0;
} else {
res = res.slice(0, lastSlashIndex);
lastSegmentLength = res.length - 1 - res.lastIndexOf("/");
}
lastSlash = i;
dots = 0;
continue;
}
} else if (res.length === 2 || res.length === 1) {
res = "";
lastSegmentLength = 0;
lastSlash = i;
dots = 0;
continue;
}
}
if (allowAboveRoot) {
if (res.length > 0)
res += "/..";
else
res = "..";
lastSegmentLength = 2;
}
} else {
if (res.length > 0)
res += "/" + path.slice(lastSlash + 1, i);
else
res = path.slice(lastSlash + 1, i);
lastSegmentLength = i - lastSlash - 1;
}
lastSlash = i;
dots = 0;
} else if (code === 46 && dots !== -1) {
++dots;
} else {
dots = -1;
}
}
return res;
}
function _format(sep, pathObject) {
var dir = pathObject.dir || pathObject.root;
var base = pathObject.base || (pathObject.name || "") + (pathObject.ext || "");
if (!dir) {
return base;
}
if (dir === pathObject.root) {
return dir + base;
}
return dir + sep + base;
}
var posix = {
// path.resolve([from ...], to)
resolve: function resolve() {
var resolvedPath = "";
var resolvedAbsolute = false;
var cwd;
for (var i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) {
var path;
if (i >= 0)
path = arguments[i];
else {
if (cwd === void 0)
cwd = process.cwd();
path = cwd;
}
assertPath(path);
if (path.length === 0) {
continue;
}
resolvedPath = path + "/" + resolvedPath;
resolvedAbsolute = path.charCodeAt(0) === 47;
}
resolvedPath = normalizeStringPosix(resolvedPath, !resolvedAbsolute);
if (resolvedAbsolute) {
if (resolvedPath.length > 0)
return "/" + resolvedPath;
else
return "/";
} else if (resolvedPath.length > 0) {
return resolvedPath;
} else {
return ".";
}
},
normalize: function normalize(path) {
assertPath(path);
if (path.length === 0) return ".";
var isAbsolute2 = path.charCodeAt(0) === 47;
var trailingSeparator = path.charCodeAt(path.length - 1) === 47;
path = normalizeStringPosix(path, !isAbsolute2);
if (path.length === 0 && !isAbsolute2) path = ".";
if (path.length > 0 && trailingSeparator) path += "/";
if (isAbsolute2) return "/" + path;
return path;
},
isAbsolute: function isAbsolute(path) {
assertPath(path);
return path.length > 0 && path.charCodeAt(0) === 47;
},
join: function join() {
if (arguments.length === 0)
return ".";
var joined;
for (var i = 0; i < arguments.length; ++i) {
var arg = arguments[i];
assertPath(arg);
if (arg.length > 0) {
if (joined === void 0)
joined = arg;
else
joined += "/" + arg;
}
}
if (joined === void 0)
return ".";
return posix.normalize(joined);
},
relative: function relative(from, to) {
assertPath(from);
assertPath(to);
if (from === to) return "";
from = posix.resolve(from);
to = posix.resolve(to);
if (from === to) return "";
var fromStart = 1;
for (; fromStart < from.length; ++fromStart) {
if (from.charCodeAt(fromStart) !== 47)
break;
}
var fromEnd = from.length;
var fromLen = fromEnd - fromStart;
var toStart = 1;
for (; toStart < to.length; ++toStart) {
if (to.charCodeAt(toStart) !== 47)
break;
}
var toEnd = to.length;
var toLen = toEnd - toStart;
var length = fromLen < toLen ? fromLen : toLen;
var lastCommonSep = -1;
var i = 0;
for (; i <= length; ++i) {
if (i === length) {
if (toLen > length) {
if (to.charCodeAt(toStart + i) === 47) {
return to.slice(toStart + i + 1);
} else if (i === 0) {
return to.slice(toStart + i);
}
} else if (fromLen > length) {
if (from.charCodeAt(fromStart + i) === 47) {
lastCommonSep = i;
} else if (i === 0) {
lastCommonSep = 0;
}
}
break;
}
var fromCode = from.charCodeAt(fromStart + i);
var toCode = to.charCodeAt(toStart + i);
if (fromCode !== toCode)
break;
else if (fromCode === 47)
lastCommonSep = i;
}
var out = "";
for (i = fromStart + lastCommonSep + 1; i <= fromEnd; ++i) {
if (i === fromEnd || from.charCodeAt(i) === 47) {
if (out.length === 0)
out += "..";
else
out += "/..";
}
}
if (out.length > 0)
return out + to.slice(toStart + lastCommonSep);
else {
toStart += lastCommonSep;
if (to.charCodeAt(toStart) === 47)
++toStart;
return to.slice(toStart);
}
},
_makeLong: function _makeLong(path) {
return path;
},
dirname: function dirname(path) {
assertPath(path);
if (path.length === 0) return ".";
var code = path.charCodeAt(0);
var hasRoot = code === 47;
var end2 = -1;
var matchedSlash = true;
for (var i = path.length - 1; i >= 1; --i) {
code = path.charCodeAt(i);
if (code === 47) {
if (!matchedSlash) {
end2 = i;
break;
}
} else {
matchedSlash = false;
}
}
if (end2 === -1) return hasRoot ? "/" : ".";
if (hasRoot && end2 === 1) return "//";
return path.slice(0, end2);
},
basename: function basename(path, ext) {
if (ext !== void 0 && typeof ext !== "string") throw new TypeError('"ext" argument must be a string');
assertPath(path);
var start2 = 0;
var end2 = -1;
var matchedSlash = true;
var i;
if (ext !== void 0 && ext.length > 0 && ext.length <= path.length) {
if (ext.length === path.length && ext === path) return "";
var extIdx = ext.length - 1;
var firstNonSlashEnd = -1;
for (i = path.length - 1; i >= 0; --i) {
var code = path.charCodeAt(i);
if (code === 47) {
if (!matchedSlash) {
start2 = i + 1;
break;
}
} else {
if (firstNonSlashEnd === -1) {
matchedSlash = false;
firstNonSlashEnd = i + 1;
}
if (extIdx >= 0) {
if (code === ext.charCodeAt(extIdx)) {
if (--extIdx === -1) {
end2 = i;
}
} else {
extIdx = -1;
end2 = firstNonSlashEnd;
}
}
}
}
if (start2 === end2) end2 = firstNonSlashEnd;
else if (end2 === -1) end2 = path.length;
return path.slice(start2, end2);
} else {
for (i = path.length - 1; i >= 0; --i) {
if (path.charCodeAt(i) === 47) {
if (!matchedSlash) {
start2 = i + 1;
break;
}
} else if (end2 === -1) {
matchedSlash = false;
end2 = i + 1;
}
}
if (end2 === -1) return "";
return path.slice(start2, end2);
}
},
extname: function extname(path) {
assertPath(path);
var startDot = -1;
var startPart = 0;
var end2 = -1;
var matchedSlash = true;
var preDotState = 0;
for (var i = path.length - 1; i >= 0; --i) {
var code = path.charCodeAt(i);
if (code === 47) {
if (!matchedSlash) {
startPart = i + 1;
break;
}
continue;
}
if (end2 === -1) {
matchedSlash = false;
end2 = i + 1;
}
if (code === 46) {
if (startDot === -1)
startDot = i;
else if (preDotState !== 1)
preDotState = 1;
} else if (startDot !== -1) {
preDotState = -1;
}
}
if (startDot === -1 || end2 === -1 || // We saw a non-dot character immediately before the dot
preDotState === 0 || // The (right-most) trimmed path component is exactly '..'
preDotState === 1 && startDot === end2 - 1 && startDot === startPart + 1) {
return "";
}
return path.slice(startDot, end2);
},
format: function format(pathObject) {
if (pathObject === null || typeof pathObject !== "object") {
throw new TypeError('The "pathObject" argument must be of type Object. Received type ' + typeof pathObject);
}
return _format("/", pathObject);
},
parse: function parse(path) {
assertPath(path);
var ret = { root: "", dir: "", base: "", ext: "", name: "" };
if (path.length === 0) return ret;
var code = path.charCodeAt(0);
var isAbsolute2 = code === 47;
var start2;
if (isAbsolute2) {
ret.root = "/";
start2 = 1;
} else {
start2 = 0;
}
var startDot = -1;
var startPart = 0;
var end2 = -1;
var matchedSlash = true;
var i = path.length - 1;
var preDotState = 0;
for (; i >= start2; --i) {
code = path.charCodeAt(i);
if (code === 47) {
if (!matchedSlash) {
startPart = i + 1;
break;
}
continue;
}
if (end2 === -1) {
matchedSlash = false;
end2 = i + 1;
}
if (code === 46) {
if (startDot === -1) startDot = i;
else if (preDotState !== 1) preDotState = 1;
} else if (startDot !== -1) {
preDotState = -1;
}
}
if (startDot === -1 || end2 === -1 || // We saw a non-dot character immediately before the dot
preDotState === 0 || // The (right-most) trimmed path component is exactly '..'
preDotState === 1 && startDot === end2 - 1 && startDot === startPart + 1) {
if (end2 !== -1) {
if (startPart === 0 && isAbsolute2) ret.base = ret.name = path.slice(1, end2);
else ret.base = ret.name = path.slice(startPart, end2);
}
} else {
if (startPart === 0 && isAbsolute2) {
ret.name = path.slice(1, startDot);
ret.base = path.slice(1, end2);
} else {
ret.name = path.slice(startPart, startDot);
ret.base = path.slice(startPart, end2);
}
ret.ext = path.slice(startDot, end2);
}
if (startPart > 0) ret.dir = path.slice(0, startPart - 1);
else if (isAbsolute2) ret.dir = "/";
return ret;
},
sep: "/",
delimiter: ":",
win32: null,
posix: null
};
posix.posix = posix;
var pathBrowserify = posix;
const DEFAULT_CLOCK_SOURCE = "local";
const DEFAULT_THEME = "win11";
const DEFAULT_WALLPAPER_FIT = "fill";
const CLOCK_CANVAS_BASE_WIDTH = 68;
const DEFAULT_WINDOW_SIZE = {
height: 510,
width: 640
};
const FOCUSABLE_ELEMENT = { tabIndex: -1 };
const DIV_BUTTON_PROPS = {
as: "div",
role: "button",
...FOCUSABLE_ELEMENT
};
const HOME = "/Users/Public";
const PEEK_MAX_WIDTH = 200;
const HEIF_IMAGE_FORMATS = /* @__PURE__ */ new Set([
".heic",
".heics",
".heif",
".heifs",
".avci",
".avcs"
]);
const TIFF_IMAGE_FORMATS = /* @__PURE__ */ new Set([
".cr2",
".dng",
".nef",
".tif",
".tiff"
]);
const IMAGE_FILE_EXTENSIONS = /* @__PURE__ */ new Set([
...HEIF_IMAGE_FORMATS,
...TIFF_IMAGE_FORMATS,
".ani",
".apng",
".avif",
".bmp",
".cur",
".gif",
".ico",
".jfif",
".jif",
".jpe",
".jpeg",
".jpg",
".jxl",
".pjp",
".pjpeg",
".png",
".svg",
".qoi",
".webp",
".xbm"
]);
/* @__PURE__ */ new Set([
...HEIF_IMAGE_FORMATS,
...TIFF_IMAGE_FORMATS,
".jxl",
".qoi",
".svg"
]);
const MENU_SEPERATOR = { separator: true };
const MILLISECONDS_IN_SECOND = 1e3;
const ONE_TIME_PASSIVE_EVENT = {
once: true,
passive: true
};
const PREVENT_SCROLL = { preventScroll: true };
const TRANSITIONS_IN_MILLISECONDS = {
DOUBLE_CLICK: 500,
LONG_PRESS: 500,
MOUSE_IN_OUT: 300,
TASKBAR_ITEM: 400,
WINDOW: 200
};
const TRANSITIONS_IN_SECONDS = {
TASKBAR_ITEM: TRANSITIONS_IN_MILLISECONDS.TASKBAR_ITEM / MILLISECONDS_IN_SECOND,
WINDOW: TRANSITIONS_IN_MILLISECONDS.WINDOW / MILLISECONDS_IN_SECOND
};
const LONG_PRESS_DELAY_MS = 750;
const AUDIO_FILE_EXTENSIONS = /* @__PURE__ */ new Set([".aac", ".oga", ".wav"]);
const AUDIO_PLAYLIST_EXTENSIONS = /* @__PURE__ */ new Set([".asx", ".m3u", ".pls"]);
const VIDEO_FILE_EXTENSIONS = /* @__PURE__ */ new Set([
".m4v",
".mkv",
".mov",
".mp4",
".ogg",
".ogm",
".ogv",
".webm"
]);
/* @__PURE__ */ new Set([
...AUDIO_FILE_EXTENSIONS,
...AUDIO_PLAYLIST_EXTENSIONS,
...IMAGE_FILE_EXTENSIONS,
...TIFF_IMAGE_FORMATS,
...VIDEO_FILE_EXTENSIONS,
".ani",
".exe",
".mp3",
".sav",
".whtml"
]);
const SYSTEM_PATH = "/System";
const ICON_PATH = `${SYSTEM_PATH}/Icons`;
const USER_ICON_PATH = `${HOME}/Icons`;
const ICON_CACHE = `${USER_ICON_PATH}/Cache`;
const ICON_RES_MAP = {
64: 96
};
const MAX_RES_ICON_OVERRIDE = {
desktop: [16, 32],
document: [16, 32],
folder: [16, 16],
mounted: [16, 16],
music: [16, 32],
pc: [16, 16],
pictures: [16, 32],
user: [16, 16],
videos: [16, 32]
};
const SUPPORTED_ICON_PIXEL_RATIOS = [3, 2, 1];
const SUPPORTED_ICON_SIZES = [16, 32, 48, 96, 144];
const MAX_ICON_SIZE = 144;
const DEFAULT_SCROLLBAR_WIDTH = 17;
const WIN_TASKBAR_HEIGHT = 48;
const HIGH_PRIORITY_ELEMENT = {
fetchpriority: "high"
};
let dpi;
const getDpi = () => {
if (typeof dpi === "number") return dpi;
dpi = Math.min(Math.ceil(window.devicePixelRatio), 3);
return dpi;
};
let visibleWindows = [];
const toggleShowDesktop = (windows, stackOrder, minimize) => {
const restoreWindows = stackOrder.length > 0 && !stackOrder.some((wid) => {
var _a;
return !((_a = windows[wid]) == null ? void 0 : _a.minimized);
});
const allWindows = restoreWindows ? [...stackOrder].reverse() : stackOrder;
if (!restoreWindows) visibleWindows = [];
allWindows.forEach((wid) => {
var _a;
if (restoreWindows) {
if (visibleWindows.includes(wid)) minimize(wid);
} else if (!((_a = windows[wid]) == null ? void 0 : _a.minimized)) {
visibleWindows.push(wid);
minimize(wid);
}
});
if (restoreWindows) {
requestAnimationFrame(
() => {
var _a, _b;
return (_b = (_a = windows[stackOrder[0]]) == null ? void 0 : _a.componentWindow) == null ? void 0 : _b.focus(PREVENT_SCROLL);
}
);
}
};
const imageSrc = (imagePath, size, ratio, extension) => {
const imageName = pathBrowserify.basename(imagePath, ".webp");
const [expectedSize, maxIconSize] = MAX_RES_ICON_OVERRIDE[imageName] || [];
const ratioSize = size * ratio;
const imageSize = Math.min(
MAX_ICON_SIZE,
expectedSize === size ? Math.min(maxIconSize, ratioSize) : ratioSize
);
return `${pathBrowserify.join(
pathBrowserify.dirname(imagePath),
`${ICON_RES_MAP[imageSize] || imageSize}x${ICON_RES_MAP[imageSize] || imageSize}`,
`${imageName}${extension}`
).replace(/\\/g, "/")}${ratio > 1 ? ` ${ratio}x` : ""}`;
};
const imageSrcs = (imagePath, size, extension, failedUrls = []) => {
const srcs = [
imageSrc(imagePath, size, 1, extension),
imageSrc(imagePath, size, 2, extension),
imageSrc(imagePath, size, 3, extension)
].filter(
(url) => failedUrls.length === 0 || failedUrls.includes(url.split(" ")[0])
).join(", ");
return (failedUrls == null ? void 0 : failedUrls.includes(srcs)) ? "" : srcs;
};
const createFallbackSrcSet = (src, failedUrls) => {
const failedSizes = new Set(
new Set(
failedUrls.map((failedUrl) => {
const fileName = pathBrowserify.basename(src, pathBrowserify.extname(src));
return Number(
failedUrl.replace(`${ICON_PATH}/`, "").replace(`${USER_ICON_PATH}/`, "").replace(`/${fileName}.png`, "").replace(`/${fileName}.webp`, "").split("x")[0]
);
})
)
);
const possibleSizes = SUPPORTED_ICON_SIZES.filter(
(size) => !failedSizes.has(size)
);
return possibleSizes.map((size) => imageSrc(src, size, 1, pathBrowserify.extname(src))).reverse().join(", ");
};
const cleanUpBufferUrl = (url) => URL.revokeObjectURL(url);
const pxToNum = (value = 0) => typeof value === "number" ? value : Number.parseFloat(value);
const viewHeight = () => window.innerHeight;
const viewWidth = () => window.innerWidth;
const getElementSize = (element) => ({
width: element.clientWidth,
height: element.clientHeight
});
const calcInitialPosition = ({ offsetHeight }, { right = 0, left = 0, top = 0, bottom = 0 } = {}, { width = 0, height = 0 } = {}) => {
const [vh2, vw2] = [viewHeight(), viewWidth()];
return {
x: pxToNum(width) >= vw2 ? 0 : left || vw2 - right,
y: pxToNum(height) + WIN_TASKBAR_HEIGHT >= vh2 ? 0 : top || vh2 - bottom - offsetHeight
};
};
const isCanvasDrawn = (canvas) => {
var _a;
if (!(canvas instanceof HTMLCanvasElement)) return false;
if (canvas.width === 0 || canvas.height === 0) return false;
const { data: pixels = [] } = ((_a = canvas.getContext("2d", { willReadFrequently: true })) == null ? void 0 : _a.getImageData(0, 0, canvas.width, canvas.height)) || {};
if (pixels.length === 0) return false;
const bwPixels = { 0: 0, 255: 0 };
for (const pixel of pixels) {
if (pixel !== 0 && pixel !== 255) return true;
bwPixels[pixel] += 1;
}
const isBlankCanvas = bwPixels[0] === pixels.length || bwPixels[255] === pixels.length || bwPixels[255] + bwPixels[0] === pixels.length && bwPixels[0] / 3 === bwPixels[255];
return !isBlankCanvas;
};
let IS_FIREFOX;
const isFirefox = () => {
if (typeof window === "undefined") return false;
if (IS_FIREFOX ?? false) return IS_FIREFOX;
IS_FIREFOX = /firefox/i.test(window.navigator.userAgent);
return IS_FIREFOX;
};
let IS_SAFARI;
const isSafari = () => {
if (typeof window === "undefined") return false;
if (IS_SAFARI ?? false) return IS_SAFARI;
IS_SAFARI = /^(?:(?!chrome|android).)*safari/i.test(
window.navigator.userAgent
);
return IS_SAFARI;
};
const haltEvent = (event) => {
try {
if (event.cancelable) {
event.preventDefault();
event.stopPropagation();
}
} catch {
}
};
const label = (value) => ({
"aria-label": value,
title: value
});
function generateOddNumber() {
return Math.floor(Date.now() * Math.random());
}
const isDynamicIcon = (icon) => typeof icon === "string" && (icon.startsWith(ICON_PATH) || icon.startsWith(USER_ICON_PATH) && !icon.startsWith(ICON_CACHE));
const FULLSCREEN_LOCKED_KEYS = ["MetaLeft", "MetaRight", "Escape"];
const enterFullscreen = async (element, options) => {
try {
if (element.requestFullscreen) {
await element.requestFullscreen(options);
} else if (element.mozRequestFullScreen) {
await element.mozRequestFullScreen(options);
} else if (element.webkitRequestFullscreen) {
await element.webkitRequestFullscreen(options);
}
} catch {
}
};
const exitFullscreen = async () => {
const fullscreenDocument = document;
try {
if (fullscreenDocument.exitFullscreen) {
await fullscreenDocument.exitFullscreen();
} else if (fullscreenDocument.mozCancelFullScreen) {
await fullscreenDocument.mozCancelFullScreen();
} else if (fullscreenDocument.webkitExitFullscreen) {
await fullscreenDocument.webkitExitFullscreen();
}
} catch {
}
};
const toggleKeyboardLock = async (fullscreenElement) => {
var _a, _b, _c, _d;
try {
if (fullscreenElement === document.documentElement) {
await ((_b = (_a = navigator == null ? void 0 : navigator.keyboard) == null ? void 0 : _a.lock) == null ? void 0 : _b.call(
_a,
FULLSCREEN_LOCKED_KEYS
));
} else {
(_d = (_c = navigator == null ? void 0 : navigator.keyboard) == null ? void 0 : _c.unlock) == null ? void 0 : _d.call(_c);
}
} catch {
}
};
const useViewportContextState = () => {
const [fullscreenElement, setFullscreenElement] = useState(
null
);
const toggleFullscreen = async (element, navigationUI) => {
if (fullscreenElement && (!element || element === fullscreenElement)) {
await exitFullscreen();
} else {
if (fullscreenElement && (isFirefox() || isSafari())) {
await exitFullscreen();
}
await enterFullscreen(element || document.documentElement, {
navigationUI: navigationUI || "hide"
});
}
};
useEffect(() => {
const onFullscreenChange = () => {
const { mozFullScreenElement, webkitFullscreenElement } = document;
const currentFullscreenElement = document.fullscreenElement || mozFullScreenElement || webkitFullscreenElement;
toggleKeyboardLock(currentFullscreenElement).then(
() => setFullscreenElement(currentFullscreenElement)
);
};
document.addEventListener("fullscreenchange", onFullscreenChange, {
passive: true
});
return () => document.removeEventListener("fullscreenchange", onFullscreenChange);
}, []);
return { fullscreenElement, toggleFullscreen };
};
const { Provider: Provider$a, useContext: useContext$9 } = contextFactory(useViewportContextState);
let getRandomValues;
const rnds8 = new Uint8Array(16);
function rng() {
if (!getRandomValues) {
getRandomValues = typeof crypto !== "undefined" && crypto.getRandomValues && crypto.getRandomValues.bind(crypto);
if (!getRandomValues) {
throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");
}
}
return getRandomValues(rnds8);
}
const byteToHex = [];
for (let i = 0; i < 256; ++i) {
byteToHex.push((i + 256).toString(16).slice(1));
}
function unsafeStringify(arr, offset3 = 0) {
return byteToHex[arr[offset3 + 0]] + byteToHex[arr[offset3 + 1]] + byteToHex[arr[offset3 + 2]] + byteToHex[arr[offset3 + 3]] + "-" + byteToHex[arr[offset3 + 4]] + byteToHex[arr[offset3 + 5]] + "-" + byteToHex[arr[offset3 + 6]] + byteToHex[arr[offset3 + 7]] + "-" + byteToHex[arr[offset3 + 8]] + byteToHex[arr[offset3 + 9]] + "-" + byteToHex[arr[offset3 + 10]] + byteToHex[arr[offset3 + 11]] + byteToHex[arr[offset3 + 12]] + byteToHex[arr[offset3 + 13]] + byteToHex[arr[offset3 + 14]] + byteToHex[arr[offset3 + 15]];
}
const randomUUID = typeof crypto !== "undefined" && crypto.randomUUID && crypto.randomUUID.bind(crypto);
const native = {
randomUUID
};
function v4(options, buf, offset3) {
if (native.randomUUID && !buf && !options) {
return native.randomUUID();
}
options = options || {};
const rnds = options.random || (options.rng || rng)();
rnds[6] = rnds[6] & 15 | 64;
rnds[8] = rnds[8] & 63 | 128;
return unsafeStringify(rnds);
}
const EventsSignals = () => {
const eventsCache = {};
const patternCache = {};
const onEmitCallbacks = [];
const eventQueue = {};
const eventQueueTimeout = {};
const clearEventQueueAfterDelay = (event) => {
if (eventQueueTimeout[event]) {
clearTimeout(eventQueueTimeout[event]);
}
eventQueueTimeout[event] = setTimeout(() => {
delete eventQueue[event];
delete eventQueueTimeout[event];
}, 5e3);
};
const addToQueueWithTimeout = (event, timeout, ...args) => {
if (!eventQueue[event]) {
eventQueue[event] = [];
}
eventQueue[event].push(args);
setTimeout(() => {
handleTimeout(event);
}, timeout);
};
const handleTimeout = (event) => {
const getEvent = eventsCache[event];
if (getEvent) {
eventQueue[event].forEach((args) => {
Object.keys(getEvent).forEach((eventID) => {
const { once, func } = getEvent[eventID];
func(...args);
if (once) {
delete getEvent[eventID];
}
});
});
delete eventQueue[event];
}
};
const Events = {
emit(eventNames, ...args) {
const events = Array.isArray(eventNames) ? eventNames : [eventNames];
events.forEach((event) => {
if (onEmitCallbacks.length > 0) {
onEmitCallbacks.forEach((fn) => fn(event, ...args));
}
const getEvent = eventsCache[event];
const patternMatches = Object.keys(patternCache).filter((pattern) => patternCache[pattern].regex.test(event));
if (getEvent || patternMatches.length > 0) {
if (getEvent) {
Object.keys(getEvent).forEach((eventID) => {
const { once, func } = getEvent[eventID];
func(...args);
if (once) {
delete getEvent[eventID];
}
});
}
patternMatches.forEach((pattern) => {
Object.keys(patternCache[pattern].ids).forEach((eventID) => {
const { once, func } = patternCache[pattern].ids[eventID];
func(...args);
if (once) {
delete patternCache[pattern].ids[eventID];
}
});
});
} else {
if (!eventQueue[event]) {
eventQueue[event] = [];
}
eventQueue[event].push(args);
}
});
},
on(event, callback) {
const newID = v4();
const handler = { func: callback };
if (event.includes("*")) {
const regexPattern = new RegExp("^" + event.replace("*", ".*") + "$");
if (!patternCache[event]) {
patternCache[event] = { regex: regexPattern, ids: {} };
}
patternCache[event].ids[newID] = handler;
} else {
if (!eventsCache[event]) {
eventsCache[event] = {};
}
eventsCache[event][newID] = handler;
}
if (eventQueue[event]) {
const queuedEvents = [...eventQueue[event]];
delete eventQueue[event];
queuedEvents.forEach((args) => callback(...args));
clearEventQueueAfterDelay(event);
}
return newID;
},
once(event, callback) {
const newID = v4();
const handler = { once: true, func: callback };
if (event.includes("*")) {
const regexPattern = new RegExp("^" + event.replace("*", ".*") + "$");
if (!patternCache[event]) {
patternCache[event] = { regex: regexPattern, ids: {} };
}
patternCache[event].ids[newID] = handler;
} else {
if (!eventsCache[event]) {
eventsCache[event] = {};
}
eventsCache[event][newID] = handler;
}
if (eventQueue[event]) {
const queuedEvents = [...eventQueue[event]];
delete eventQueue[event];
queuedEvents.forEach((args) => callback(...args));
clearEventQueueAfterDelay(event);
}
return newID;
},
off(event, callback) {
if (event.includes("*")) {
const getPattern = patternCache[event];
if (!getPattern) return false;
Object.keys(getPattern.ids).forEach((eventID) => {
if (getPattern.ids[eventID].func === callback) {
delete getPattern.ids[eventID];
}
});
} else {
const getEvent = eventsCache[event];
if (!getEvent) return false;
Object.keys(getEvent).forEach((eventID) => {
if (getEvent[eventID].func === callback) {
delete getEvent[eventID];
}
});
}
return true;
},
removeListenerByID(id) {
Object.keys(eventsCache).forEach((eventName) => {
return Events.removeListenerByEventAndID(eventName, id);
});
Object.keys(patternCache).forEach((pattern) => {
Events.removeListenerByEventAndID(pattern, id);
});
return true;
},
removeListenerByEventAndID(event, id) {
if (event.includes("*")) {
const getPattern = patternCache[event];
if (!getPattern) return true;
delete getPattern.ids[id];
} else {
const getEvent = eventsCache[event];
if (!getEvent) return true;
delete getEvent[id];
}
return true;
},
onEmit(callback) {
onEmitCallbacks.push(callback);
},
addToQueueWithTimeout,
handleTimeout
};
return { ...Events, eventsCache, patternCache, eventQueue };
};
const useSignalRefs = () => {
const eventsEmitterRef = useRef(EventsSignals());
const actionsEmitterRef = useRef(EventsSignals());
return {
events: eventsEmitterRef.current,
actions: actionsEmitterRef.current
};
};
const { Provider: Provider$9, useContext: useContext$8 } = contextFactory(useSignalRefs);
const useElementsContextState = () => {
const [elementsState, setElements] = useState(
/* @__PURE__ */ Object.create(null)
);
const [elementsSize, setElementsSize] = useState(/* @__PURE__ */ Object.create(null));
const elementsSizesRef = useRef(/* @__PURE__ */ Object.create(null));
const { events: RD_Events } = useContext$8();
const resizeObserversRef = useRef(/* @__PURE__ */ Object.create(null));
const linkElement = useCallback$1(
(name, element) => {
var _a;
const resizeObservers = resizeObserversRef.current;
if (resizeObservers[name]) {
(_a = resizeObservers[name]) == null ? void 0 : _a.unobserve(element);
}
const observer = new ResizeObserver(() => {
const newSize = getElementSize(element);
elementsSizesRef.current[name + "Size"] = newSize;
setElementsSize((prevSizes) => ({
...prevSizes,
[name + "Size"]: newSize
}));
RD_Events.emit("event:elements/resize/windowsview", newSize);
});
observer.observe(element);
const initialSize = getElementSize(element);
elementsSizesRef.current[name + "Size"] = initialSize;
setElementsSize((prevSizes) => ({
...prevSizes,
[name + "Size"]: initialSize
}));
resizeObserversRef.current = { ...resizeObservers, [name]: observer };
setElements((prevElements) => ({
...prevElements,
[name]: element
}));
},
[RD_Events]
);
const getLatestSize = useCallback$1((name) => {
return elementsSizesRef.current[name + "Size"];
}, []);
return {
...elementsState,
...elementsSize,
linkElement,
elementsSizesRef,
getLatestSize
};
};
const { Provider: Provider$8, useContext: useContext$7 } = contextFactory(useElementsContextState);
const ChevronRight = memo(({ className }) => /* @__PURE__ */ jsx(
"svg",
{
className,
viewBox: "0 0 32 32",
xmlns: "http://www.w3.org/2000/svg",
children: /* @__PURE__ */ jsx("path", { d: "M8.047 30.547L22.578 16 8.047 1.453 9.453.047 25.422 16 9.453 31.953l-1.406-1.406z" })
}
));
const Checkmark = memo(({ className }) => {
const { colors: colors2 } = useTheme();
return /* @__PURE__ */ jsx(
"svg",
{
className,
viewBox: "0 0 32 32",
xmlns: "http://www.w3.org/2000/svg",
children: /* @__PURE__ */ jsx(
"path",
{
d: "M28.703 8.703l-16.703 16.719-8.703-8.719 1.406-1.406 7.297 7.281 15.297-15.281z",
stroke: colors2.text,
strokeWidth: "2"
}
)
}
);
});
const Circle = memo(({ className }) => /* @__PURE__ */ jsx(
"svg",
{
className,
viewBox: "0 0 32 32",
xmlns: "http://www.w3.org/2000/svg",
children: /* @__PURE__ */ jsx("path", { d: "M16 10q1.234 0 2.328.469t1.914 1.289 1.289 1.914T22 16q0 1.25-.469 2.336t-1.289 1.906-1.914 1.289T16 22q-1.25 0-2.336-.469t-1.906-1.289-1.289-1.906T10 16q0-1.234.469-2.328t1.289-1.914 1.906-1.289T16 10z" })
}
));
memo(() => /* @__PURE__ */ jsx("svg", { viewBox: "0 0 32 32", xmlns: "http://www.w3.org/2000/svg", children: /* @__PURE__ */ jsx("path", { d: "M22 24l2-2v6h-24v-20h2v18h20v-2zM20 16q-2 0-3.914 0.398t-3.695 1.172-3.398 1.891-2.992 2.539v-2q0-1.938 0.5-3.727t1.414-3.344 2.188-2.828 2.828-2.188 3.344-1.414 3.727-0.5v-6l11 11-11 11v-6zM21.578 8q-0.875 0-1.641 0.016t-1.516 0.102-1.5 0.281-1.594 0.539q-1.359 0.563-2.523 1.438t-2.078 1.992-1.547 2.422-0.93 2.742q2.625-1.75 5.609-2.641t6.141-0.891h2v3.172l6.172-6.172-6.172-6.172v3.172h-0.422z" }) }));
const defaultStyles = css`
border: 0px;
box-sizing: border-box;
font-variant-numeric: tabular-nums;
margin: 0px;
outline: 0px;
padding: 0px;
text-rendering: optimizelegibility;
`;
const onKeyDown = (event) => {
if (!(event.target instanceof HTMLTextAreaElement)) event.preventDefault();
};
const Button = styled.button.attrs(({ as }) => ({
onKeyDown,
type: !as || as === "button" ? "button" : void 0
}))`
${defaultStyles}
background-color: transparent;
font-family: inherit;
max-width: ${({ $short }) => $short ? "31px" : void 0};
width: 100%;
`;
const StyledIcon = styled.img.attrs(
({ $eager = false, $height, $width }) => ({
decoding: "async",
draggable: false,
fetchpriority: $eager ? "high" : void 0,
height: $height,
loading: $eager ? "eager" : "lazy",
width: $width
})
)`
${defaultStyles}
aspect-ratio: 1;
user-select: none;
left: ${({ $offset }) => $offset || void 0};
max-height: ${({ $height }) => $height}px;
max-width: ${({ $width }) => $width}px;
min-height: ${({ $height }) => $height}px;
min-width: ${({ $width }) => $width}px;
object-fit: contain;
opacity: ${({ $moving }) => $moving ? "50%" : "100%"};
pointer-events: none;
top: ${({ $offset }) => $offset || void 0};
visibility: ${({ $loaded }) => $loaded ? "visible" : "hidden"};
`;
const Icon = forwardRef((props, ref2) => {
const [loaded, setLoaded] = useState(false);
const { displaySize = 0, imgSize = 0, src = "", ...componentProps } = props;
const isDynamic = isDynamicIcon(src);
const dimensionProps = useMemo$1(() => {
const size = displaySize > imgSize ? imgSize : displaySize || imgSize;
const $offset = displaySize > imgSize ? `${displaySize - imgSize}px` : 0;
return {
$height: size,
$offset,
$width: size
};
}, [displaySize, imgSize]);
const [failedUrls, setFailedUrls] = useState([]);
useEffect(
() => () => {
if (loaded && src.startsWith("blob:")) cleanUpBufferUrl(src);
},
[loaded, src]
);
const RenderedIcon = /* @__PURE__ */ jsx(
StyledIcon,
{
ref: ref2,
$loaded: loaded,
onError: ({ target }) => {
const { currentSrc = "" } = target || {};
try {
const { pathname } = new URL(currentSrc);
if (pathname && !failedUrls.includes(pathname)) {
setFailedUrls((currentFailedUrls) => [
...currentFailedUrls,
pathname
]);
}
} catch {
}
},
onLoad: () => setLoaded(true),
src: isDynamic ? imageSrc(src, imgSize, 1, ".png") : src || void 0,
srcSet: isDynamic ? imageSrcs(src, imgSize, ".png", failedUrls) || (failedUrls.length === 0 ? "" : createFallbackSrcSet(src, failedUrls)) : void 0,
...componentProps,
...dimensionProps
}
);
return /* @__PURE__ */ jsxs("picture", { children: [
isDynamic && SUPPORTED_ICON_PIXEL_RATIOS.map((ratio) => {
const srcSet = imageSrc(src, imgSize, ratio, ".webp");
const mediaRatio = ratio - 0.99;
if (failedUrls.length > 0 && failedUrls.includes(srcSet.split(" ")[0])) {
return null;
}
return /* @__PURE__ */ jsx(
"source",
{
media: ratio > 1 ? `(min-resolution: ${mediaRatio}x), (-webkit-min-device-pixel-ratio: ${mediaRatio})` : void 0,
srcSet,
type: "image/webp"
},
ratio
);
}),
RenderedIcon
] });
});
const Icon$1 = memo(Icon);
const MenuItemEntry = ({
action,
checked,
disabled,
icon,
isSubMenu,
label: label2,
menu,
primary,
resetMenu,
separator,
SvgIcon,
toggle,
tooltip
}) => {
const entryRef = useRef(null);
const [subMenuOffset, setSubMenuOffset] = useState(topLeftPosition);
const [showSubMenu, setShowSubMenu] = useState(false);
const { sizes: sizes2 } = useTheme();
const showSubMenuTimerRef = useRef(0);
const [mouseOver, setMouseOver] = useState(false);
const canMouseOver = useMemo$1(
() => window.matchMedia("(hover: hover)").matches,
[]
);
const setDelayedShowSubMenu = useCallback$1((show) => {
if (showSubMenuTimerRef.current) {
window.clearTimeout(showSubMenuTimerRef.current);
showSubMenuTimerRef.current = 0;
}
showSubMenuTimerRef.current = window.setTimeout(
() => setShowSubMenu(show),
TRANSITIONS_IN_MILLISECONDS.MOUSE_IN_OUT
);
}, []);
const onMouseEnter = () => {
setMouseOver(true);
if (menu) setDelayedShowSubMenu(true);
};
const onMouseLeave = ({ relatedTarget, type }) => {
var _a;
if (!(relatedTarget instanceof HTMLElement) || !((_a = entryRef.current) == null ? void 0 : _a.contains(relatedTarget))) {
setMouseOver(false);
if (type === "mouseleave") {
setDelayedShowSubMenu(false);
} else {
setShowSubMenu(false);
}
}
};
const subMenuEvents = menu ? {
onBlur: onMouseLeave,
onMouseEnter,
onMouseLeave
} : {};
const triggerAction = useCallback$1(
(event) => {
haltEvent(event);
if (menu) setShowSubMenu(true);
else {
action == null ? void 0 : action();
resetMenu();
}
},
[action, menu, resetMenu]
);
useEffect(() => {
const menuEntryElement = entryRef.current;
const showBaseMenu = !isSubMenu && menu && !showSubMenu;
const touchListener = (event) => {
if (showBaseMenu) {
haltEvent(event);
menuEntryElement == null ? void 0 : menuEntryElement.focus(PREVENT_SCROLL);
}
if (menu) setShowSubMenu(true);
};
menuEntryElement == null ? void 0 : menuEntryElement.addEventListener("touchstart", touchListener, {
passive: !showBaseMenu
});
return () => menuEntryElement == null ? void 0 : menuEntryElement.removeEventListener("touchstart", touchListener);
}, [isSubMenu, menu, showSubMenu]);
useLayoutEffect$1(() => {
if (menu && entryRef.current) {
const { height, width } = entryRef.current.getBoundingClientRect();
setSubMenuOffset({
x: width - sizes2.contextMenu.subMenuOffset,
y: 0 - height - sizes2.contextMenu.subMenuOffset
});
}
}, [menu, sizes2.contextMenu.subMenuOffset]);
return /* @__PURE__ */ jsxs(
"li",
{
ref: entryRef,
className: disabled ? "disabled" : void 0,
title: tooltip,
...FOCUSABLE_ELEMENT,
...menu && subMenuEvents,
children: [
separator ? /* @__PURE__ */ jsx("hr", {}) : /* @__PURE__ */ jsxs(
Button,
{
"aria-label": label2,
className: showSubMenu && (!canMouseOver || mouseOver) ? "active" : void 0,
onMouseUp: triggerAction,
...DIV_BUTTON_PROPS,
children: [
icon && (new RegExp("\\p{Emoji_Presentation}", "u").test(icon) ? /* @__PURE__ */ jsx("span", { children: icon }) : /* @__PURE__ */ jsx(Icon$1, { alt: label2, imgSize: 16, src: icon })),
checked && /* @__PURE__ */ jsx(Checkmark, { className: "left" }),
toggle && /* @__PURE__ */ jsx(Circle, { className: "left" }),
SvgIcon && /* @__PURE__ */ jsx("div", { className: "icon", children: /* @__PURE__ */ jsx(SvgIcon, {}) }),
/* @__PURE__ */ jsx("figcaption", { className: primary ? "primary" : void 0, children: label2 }),
menu && /* @__PURE__ */ jsx(ChevronRight, { className: "right" })
]
}
),
showSubMenu && menu && /* @__PURE__ */ jsx(Menu, { subMenu: { items: menu, ...subMenuOffset } })
]
}
);
};
const MotionConfigContext = createContext({
transformPagePoint: (p) => p,
isStatic: false,
reducedMotion: "never"
});
const MotionContext = createContext({});
const PresenceContext = createContext(null);
const isBrowser = typeof document !== "undefined";
const useIsomorphicLayoutEffect$2 = isBrowser ? useLayoutEffect$1 : useEffect;
const LazyContext = createContext({ strict: false });
const camelToDash = (str) => str.replace(/([a-z])([A-Z])/g, "$1-$2").toLowerCase();
const optimizedAppearDataId = "framerAppearId";
const optimizedAppearDataAttribute = "data-" + camelToDash(optimizedAppearDataId);
function useVisualElement(Component, visualState, props, createVisualElement) {
const { visualElement: parent } = useContext$a(MotionContext);
const lazyContext = useContext$a(LazyContext);
const presenceContext = useContext$a(PresenceContext);
const reducedMotionConfig = useContext$a(MotionConfigContext).reducedMotion;
const visualElementRef = useRef();
createVisualElement = createVisualElement || lazyContext.renderer;
if (!visualElementRef.current && createVisualElement) {
visualElementRef.current = createVisualElement(Component, {
visualState,
parent,
props,
presenceContext,
blockInitialAnimation: presenceContext ? presenceContext.initial === false : false,
reducedMotionConfig
});
}
const visualElement = visualElementRef.current;
useInsertionEffect(() => {
visualElement && visualElement.update(props, presenceContext);
});
const wantsHandoff = useRef(Boolean(props[optimizedAppearDataAttribute] && !window.HandoffComplete));
useIsomorphicLayoutEffect$2(() => {
if (!visualElement)
return;
visualElement.render();
if (wantsHandoff.current && visualElement.animationState) {
visualElement.animationState.animateChanges();
}
});
useEffect(() => {
if (!visualElement)
return;
visualElement.updateFeatures();
if (!wantsHandoff.current && visualElement.animationState) {
visualElement.animationState.animateChanges();
}
if (wantsHandoff.current) {
wantsHandoff.current = false;
window.HandoffComplete = true;
}
});
return visualElement;
}
function isRefObject(ref2) {
return ref2 && typeof ref2 === "object" && Object.prototype.hasOwnProperty.call(ref2, "current");
}
function useMotionRef(visualState, visualElement, externalRef) {
return useCallback$1(
(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 (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]
);
}
function isVariantLabel(v) {
return typeof v === "string" || Array.isArray(v);
}
function isAnimationControls(v) {
return v !== null && typeof v === "object" && typeof v.start === "function";
}
const variantPriorityOrder = [
"animate",
"whileInView",
"whileFocus",
"whileHover",
"whileTap",
"whileDrag",
"exit"
];
const variantProps = ["initial", ...variantPriorityOrder];
function isControllingVariants(props) {
return isAnimationControls(props.animate) || variantProps.some((name) => isVariantLabel(props[name]));
}
function isVariantNode(props) {
return Boolean(isControllingVariants(props) || props.variants);
}
function getCurrentTreeVariants(props, context) {
if (isControllingVariants(props)) {
const { initial, animate } = props;
return {
initial: initial === false || isVariantLabel(initial) ? initial : void 0,
animate: isVariantLabel(animate) ? animate : void 0
};
}
return props.inherit !== false ? context : {};
}
function useCreateMotionContext(props) {
const { initial, animate } = getCurrentTreeVariants(props, useContext$a(MotionContext));
return useMemo$1(() => ({ initial, animate }), [variantLabelsAsDependency(initial), variantLabelsAsDependency(animate)]);
}
function variantLabelsAsDependency(prop) {
return Array.isArray(prop) ? prop.join(" ") : prop;
}
const featureProps = {
animation: [
"animate",
"variants",
"whileHover",
"whileTap",
"exit",
"whileInView",
"whileFocus",
"whileDrag"
],
exit: ["exit"],
drag: ["drag", "dragControls"],
focus: ["whileFocus"],
hover: ["whileHover", "onHoverStart", "onHoverEnd"],
tap: ["whileTap", "onTap", "onTapStart", "onTapCancel"],
pan: ["onPan", "onPanStart", "onPanSessionStart", "onPanEnd"],
inView: ["whileInView", "onViewportEnter", "onViewportLeave"],
layout: ["layout", "layoutId"]
};
const featureDefinitions = {};
for (const key in featureProps) {
featureDefinitions[key] = {
isEnabled: (props) => featureProps[key].some((name) => !!props[name])
};
}
function loadFeatures(features) {
for (const key in features) {
featureDefinitions[key] = {
...featureDefinitions[key],
...features[key]
};
}
}
const LayoutGroupContext = createContext({});
const SwitchLayoutGroupContext = createContext({});
const motionComponentSymbol = Symbol.for("motionComponentSymbol");
function createMotionComponent({ preloadedFeatures, createVisualElement, useRender, useVisualState, Component }) {
preloadedFeatures && loadFeatures(preloadedFeatures);
function MotionComponent(props, externalRef) {
let MeasureLayout;
const configAndProps = {
...useContext$a(MotionConfigContext),
...props,
layoutId: useLayoutId(props)
};
const { isStatic } = configAndProps;
const context = useCreateMotionContext(props);
const visualState = useVisualState(props, isStatic);
if (!isStatic && isBrowser) {
context.visualElement = useVisualElement(Component, visualState, configAndProps, createVisualElement);
const initialLayoutGroupConfig = useContext$a(SwitchLayoutGroupContext);
const isStrict = useContext$a(LazyContext).strict;
if (context.visualElement) {
MeasureLayout = context.visualElement.loadFeatures(
// Note: Pass the full new combined props to correctly re-render dynamic feature components.
configAndProps,
isStrict,
preloadedFeatures,
initialLayoutGroupConfig
);
}
}
return React.createElement(
MotionContext.Provider,
{ value: context },
MeasureLayout && context.visualElement ? React.createElement(MeasureLayout, { visualElement: context.visualElement, ...configAndProps }) : null,
useRender(Component, props, useMotionRef(visualState, context.visualElement, externalRef), visualState, isStatic, context.visualElement)
);
}
const ForwardRefComponent = forwardRef(MotionComponent);
ForwardRefComponent[motionComponentSymbol] = Component;
return ForwardRefComponent;
}
function useLayoutId({ layoutId }) {
const layoutGroupId = useContext$a(LayoutGroupContext).id;
return layoutGroupId && layoutId !== void 0 ? layoutGroupId + "-" + layoutId : layoutId;
}
function createMotionProxy(createConfig) {
function custom(Component, customMotionComponentConfig = {}) {
return createMotionComponent(createConfig(Component, customMotionComponentConfig));
}
if (typeof Proxy === "undefined") {
return custom;
}
const componentCache = /* @__PURE__ */ 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 (!componentCache.has(key)) {
componentCache.set(key, custom(key));
}
return componentCache.get(key);
}
});
}
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"
];
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;
}
const scaleCorrectors = {};
const transformPropOrder = [
"transformPerspective",
"x",
"y",
"z",
"translateX",
"translateY",
"translateZ",
"scale",
"scaleX",
"scaleY",
"rotate",
"rotateX",
"rotateY",
"rotateZ",
"skew",
"skewX",
"skewY"
];
const transformProps = new Set(transformPropOrder);
function isForcedMotionValue(key, { layout, layoutId }) {
return transformProps.has(key) || key.startsWith("origin") || (layout || layoutId !== void 0) && (!!scaleCorrectors[key] || key === "opacity");
}
const isMotionValue = (value) => Boolean(value && value.getVelocity);
const translateAlias = {
x: "translateX",
y: "translateY",
z: "translateZ",
transformPerspective: "perspective"
};
const numTransforms = transformPropOrder.length;
function buildTransform(transform, { enableHardwareAcceleration = true, allowTransformNone = true }, transformIsDefault, transformTemplate) {
let transformString = "";
for (let i = 0; i < numTransforms; i++) {
const key = transformPropOrder[i];
if (transform[key] !== void 0) {
const transformName = translateAlias[key] || key;
transformString += `${transformName}(${transform[key]}) `;
}
}
if (enableHardwareAcceleration && !transform.z) {
transformString += "translateZ(0)";
}
transformString = transformString.trim();
if (transformTemplate) {
transformString = transformTemplate(transform, transformIsDefault ? "" : transformString);
} else if (allowTransformNone && transformIsDefault) {
transformString = "none";
}
return transformString;
}
const checkStringStartsWith = (token) => (key) => typeof key === "string" && key.startsWith(token);
const isCSSVariableName = checkStringStartsWith("--");
const isCSSVariableToken = checkStringStartsWith("var(--");
const cssVariableRegex = /var\s*\(\s*--[\w-]+(\s*,\s*(?:(?:[^)(]|\((?:[^)(]+|\([^)(]*\))*\))*)+)?\s*\)/g;
const getValueAsType = (value, type) => {
return type && typeof value === "number" ? type.transform(value) : value;
};
const clamp = (min, max, v) => Math.min(Math.max(v, min), max);
const number = {
test: (v) => typeof v === "number",
parse: parseFloat,
transform: (v) => v
};
const alpha = {
...number,
transform: (v) => clamp(0, 1, v)
};
const scale = {
...number,
default: 1
};
const sanitize = (v) => Math.round(v * 1e5) / 1e5;
const floatRegex = /(-)?([\d]*\.?[\d])+/g;
const colorRegex = /(#[0-9a-f]{3,8}|(rgb|hsl)a?\((-?[\d\.]+%?[,\s]+){2}(-?[\d\.]+%?)\s*[\,\/]?\s*[\d\.]*%?\))/gi;
const singleColorRegex = /^(#[0-9a-f]{3,8}|(rgb|hsl)a?\((-?[\d\.]+%?[,\s]+){2}(-?[\d\.]+%?)\s*[\,\/]?\s*[\d\.]*%?\))$/i;
function isString(v) {
return typeof v === "string";
}
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)
};
const int = {
...number,
transform: Math.round
};
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,
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: int,
// SVG
fillOpacity: alpha,
strokeOpacity: alpha,
numOctaves: int
};
function buildHTMLStyles(state, latestValues, options, transformTemplate) {
const { style: style2, vars, transform, transformOrigin } = state;
let hasTransform = false;
let hasTransformOrigin = false;
let transformIsNone = true;
for (const key in latestValues) {
const value = latestValues[key];
if (isCSSVariableName(key)) {
vars[key] = value;
continue;
}
const valueType = numberValueTypes[key];
const valueAsType = getValueAsType(value, valueType);
if (transformProps.has(key)) {
hasTransform = true;
transform[key] = valueAsType;
if (!transformIsNone)
continue;
if (value !== (valueType.default || 0))
transformIsNone = false;
} else if (key.startsWith("origin")) {
hasTransformOrigin = true;
transformOrigin[key] = valueAsType;
} else {
style2[key] = valueAsType;
}
}
if (!latestValues.transform) {
if (hasTransform || transformTemplate) {
style2.transform = buildTransform(state.transform, options, transformIsNone, transformTemplate);
} else if (style2.transform) {
style2.transform = "none";
}
}
if (hasTransformOrigin) {
const { originX = "50%", originY = "50%", originZ = 0 } = transformOrigin;
style2.transformOrigin = `${originX} ${originY} ${originZ}`;
}
}
const createHtmlRenderState = () => ({
style: {},
transform: {},
transformOrigin: {},
vars: {}
});
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 useMemo$1(() => {
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 style2 = {};
copyRawValuesOnly(style2, styleProp, props);
Object.assign(style2, useInitialMotionValues(props, visualState, isStatic));
return props.transformValues ? props.transformValues(style2) : style2;
}
function useHTMLProps(props, visualState, isStatic) {
const htmlProps = {};
const style2 = useStyle(props, visualState, isStatic);
if (props.drag && props.dragListener !== false) {
htmlProps.draggable = false;
style2.userSelect = style2.WebkitUserSelect = style2.WebkitTouchCallout = "none";
style2.touchAction = props.drag === true ? "none" : `pan-${props.drag === "x" ? "y" : "x"}`;
}
if (props.tabIndex === void 0 && (props.onTap || props.onTapStart || props.whileTap)) {
htmlProps.tabIndex = 0;
}
htmlProps.style = style2;
return htmlProps;
}
const validMotionProps = /* @__PURE__ */ new Set([
"animate",
"exit",
"variants",
"initial",
"style",
"values",
"variants",
"transition",
"transformTemplate",
"transformValues",
"custom",
"inherit",
"onBeforeLayoutMeasure",
"onAnimationStart",
"onAnimationComplete",
"onUpdate",
"onDragStart",
"onDrag",
"onDragEnd",
"onMeasureDragConstraints",
"onDirectionLock",
"onDragTransitionEnd",
"_dragX",
"_dragY",
"onHoverStart",
"onHoverEnd",
"onViewportEnter",
"onViewportLeave",
"globalTapTarget",
"ignoreStrict",
"viewport"
]);
function isValidMotionProp(key) {
return key.startsWith("while") || key.startsWith("drag") && key !== "draggable" || key.startsWith("layout") || key.startsWith("onTap") || key.startsWith("onPan") || key.startsWith("onLayout") || validMotionProps.has(key);
}
let shouldForward = (key) => !isValidMotionProp(key);
function loadExternalIsValidProp(isValidProp) {
if (!isValidProp)
return;
shouldForward = (key) => key.startsWith("on") ? !isValidMotionProp(key) : isValidProp(key);
}
try {
loadExternalIsValidProp(require("@emotion/is-prop-valid").default);
} catch (_a) {
}
function filterProps(props, isDom, forwardMotionProps) {
const filteredProps = {};
for (const key in props) {
if (key === "values" && typeof props.values === "object")
continue;
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;
}
function calcOrigin(origin2, offset3, size) {
return typeof origin2 === "string" ? origin2 : px.transform(offset3 + size * origin2);
}
function calcSVGTransformOrigin(dimensions, originX, originY) {
const pxOriginX = calcOrigin(originX, dimensions.x, dimensions.width);
const pxOriginY = calcOrigin(originY, dimensions.y, dimensions.height);
return `${pxOriginX} ${pxOriginY}`;
}
const dashKeys = {
offset: "stroke-dashoffset",
array: "stroke-dasharray"
};
const camelKeys = {
offset: "strokeDashoffset",
array: "strokeDasharray"
};
function buildSVGPath(attrs, length, spacing = 1, offset3 = 0, useDashCase = true) {
attrs.pathLength = 1;
const keys = useDashCase ? dashKeys : camelKeys;
attrs[keys.offset] = px.transform(-offset3);
const pathLength = px.transform(length);
const pathSpacing = px.transform(spacing);
attrs[keys.array] = `${pathLength} ${pathSpacing}`;
}
function buildSVGAttrs(state, {
attrX,
attrY,
attrScale,
originX,
originY,
pathLength,
pathSpacing = 1,
pathOffset = 0,
// This is object creation, which we try to avoid per-frame.
...latest
}, options, isSVGTag2, transformTemplate) {
buildHTMLStyles(state, latest, options, transformTemplate);
if (isSVGTag2) {
if (state.style.viewBox) {
state.attrs.viewBox = state.style.viewBox;
}
return;
}
state.attrs = state.style;
state.style = {};
const { attrs, style: style2, dimensions } = state;
if (attrs.transform) {
if (dimensions)
style2.transform = attrs.transform;
delete attrs.transform;
}
if (dimensions && (originX !== void 0 || originY !== void 0 || style2.transform)) {
style2.transformOrigin = calcSVGTransformOrigin(dimensions, originX !== void 0 ? originX : 0.5, originY !== void 0 ? originY : 0.5);
}
if (attrX !== void 0)
attrs.x = attrX;
if (attrY !== void 0)
attrs.y = attrY;
if (attrScale !== void 0)
attrs.scale = attrScale;
if (pathLength !== void 0) {
buildSVGPath(attrs, pathLength, pathSpacing, pathOffset, false);
}
}
const createSvgRenderState = () => ({
...createHtmlRenderState(),
attrs: {}
});
const isSVGTag = (tag) => typeof tag === "string" && tag.toLowerCase() === "svg";
function useSVGProps(props, visualState, _isStatic, Component) {
const visualProps = useMemo$1(() => {
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;
}
function createUseRender(forwardMotionProps = false) {
const useRender = (Component, props, ref2, { 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: ref2
};
const { children } = props;
const renderedChildren = useMemo$1(() => isMotionValue(children) ? children.get() : children, [children]);
return createElement(Component, {
...elementProps,
children: renderedChildren
});
};
return useRender;
}
function renderHTML(element, { style: style2, vars }, styleProp, projection) {
Object.assign(element.style, style2, projection && projection.getProjectionStyles(styleProp));
for (const key in vars) {
element.style.setProperty(key, vars[key]);
}
}
const camelCaseAttributes = /* @__PURE__ */ 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"
]);
function renderSVG(element, renderState, _styleProp, projection) {
renderHTML(element, renderState, void 0, projection);
for (const key in renderState.attrs) {
element.setAttribute(!camelCaseAttributes.has(key) ? camelToDash(key) : key, renderState.attrs[key]);
}
}
function scrapeMotionValuesFromProps$1(props, prevProps) {
const { style: style2 } = props;
const newValues = {};
for (const key in style2) {
if (isMotionValue(style2[key]) || prevProps.style && isMotionValue(prevProps.style[key]) || isForcedMotionValue(key, props)) {
newValues[key] = style2[key];
}
}
return newValues;
}
function scrapeMotionValuesFromProps(props, prevProps) {
const newValues = scrapeMotionValuesFromProps$1(props, prevProps);
for (const key in props) {
if (isMotionValue(props[key]) || isMotionValue(prevProps[key])) {
const targetKey = transformPropOrder.indexOf(key) !== -1 ? "attr" + key.charAt(0).toUpperCase() + key.substring(1) : key;
newValues[targetKey] = props[key];
}
}
return newValues;
}
function resolveVariantFromProps(props, definition, custom, currentValues = {}, currentVelocity = {}) {
if (typeof definition === "function") {
definition = definition(custom !== void 0 ? custom : props.custom, currentValues, currentVelocity);
}
if (typeof definition === "string") {
definition = props.variants && props.variants[definition];
}
if (typeof definition === "function") {
definition = definition(custom !== void 0 ? custom : props.custom, currentValues, currentVelocity);
}
return definition;
}
function useConstant(init) {
const ref2 = useRef(null);
if (ref2.current === null) {
ref2.current = init();
}
return ref2.current;
}
const isKeyframesTarget = (v) => {
return Array.isArray(v);
};
const isCustomValue = (v) => {
return Boolean(v && typeof v === "object" && v.mix && v.toValue);
};
const resolveFinalValueInKeyframes = (v) => {
return isKeyframesTarget(v) ? v[v.length - 1] || 0 : v;
};
function resolveMotionValue(value) {
const unwrappedValue = isMotionValue(value) ? value.get() : value;
return isCustomValue(unwrappedValue) ? unwrappedValue.toValue() : unwrappedValue;
}
function makeState({ scrapeMotionValuesFromProps: scrapeMotionValuesFromProps2, createRenderState, onMount }, props, context, presenceContext) {
const state = {
latestValues: makeLatestValues(props, context, presenceContext, scrapeMotionValuesFromProps2),
renderState: createRenderState()
};
if (onMount) {
state.mount = (instance) => onMount(props, instance, state);
}
return state;
}
const makeUseVisualState = (config) => (props, isStatic) => {
const context = useContext$a(MotionContext);
const presenceContext = useContext$a(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 === void 0)
initial = context.initial;
if (animate === void 0)
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)) {
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;
}
const noop$3 = (any) => any;
class Queue {
constructor() {
this.order = [];
this.scheduled = /* @__PURE__ */ new Set();
}
add(process2) {
if (!this.scheduled.has(process2)) {
this.scheduled.add(process2);
this.order.push(process2);
return true;
}
}
remove(process2) {
const index = this.order.indexOf(process2);
if (index !== -1) {
this.order.splice(index, 1);
this.scheduled.delete(process2);
}
}
clear() {
this.order.length = 0;
this.scheduled.clear();
}
}
function createRenderStep(runNextFrame) {
let thisFrame = new Queue();
let nextFrame = new Queue();
let numToRun = 0;
let isProcessing = false;
let flushNextFrame = false;
const toKeepAlive = /* @__PURE__ */ new WeakSet();
const step = {
/**
* Schedule a process to run on the next frame.
*/
schedule: (callback, keepAlive = false, immediate2 = false) => {
const addToCurrentFrame = immediate2 && isProcessing;
const queue = addToCurrentFrame ? thisFrame : nextFrame;
if (keepAlive)
toKeepAlive.add(callback);
if (queue.add(callback) && addToCurrentFrame && isProcessing) {
numToRun = thisFrame.order.length;
}
return callback;
},
/**
* Cancel the provided callback from running on the next frame.
*/
cancel: (callback) => {
nextFrame.remove(callback);
toKeepAlive.delete(callback);
},
/**
* Execute all schedule callbacks.
*/
process: (frameData2) => {
if (isProcessing) {
flushNextFrame = true;
return;
}
isProcessing = true;
[thisFrame, nextFrame] = [nextFrame, thisFrame];
nextFrame.clear();
numToRun = thisFrame.order.length;
if (numToRun) {
for (let i = 0; i < numToRun; i++) {
const callback = thisFrame.order[i];
callback(frameData2);
if (toKeepAlive.has(callback)) {
step.schedule(callback);
runNextFrame();
}
}
}
isProcessing = false;
if (flushNextFrame) {
flushNextFrame = false;
step.process(frameData2);
}
}
};
return step;
}
const stepsOrder = [
"prepare",
"read",
"update",
"preRender",
"render",
"postRender"
];
const maxElapsed = 40;
function createRenderBatcher(scheduleNextBatch, allowKeepAlive) {
let runNextFrame = false;
let useDefaultElapsed = true;
const state = {
delta: 0,
timestamp: 0,
isProcessing: false
};
const steps2 = stepsOrder.reduce((acc, key) => {
acc[key] = createRenderStep(() => runNextFrame = true);
return acc;
}, {});
const processStep = (stepId) => steps2[stepId].process(state);
const processBatch = () => {
const timestamp = performance.now();
runNextFrame = false;
state.delta = useDefaultElapsed ? 1e3 / 60 : Math.max(Math.min(timestamp - state.timestamp, maxElapsed), 1);
state.timestamp = timestamp;
state.isProcessing = true;
stepsOrder.forEach(processStep);
state.isProcessing = false;
if (runNextFrame && allowKeepAlive) {
useDefaultElapsed = false;
scheduleNextBatch(processBatch);
}
};
const wake = () => {
runNextFrame = true;
useDefaultElapsed = true;
if (!state.isProcessing) {
scheduleNextBatch(processBatch);
}
};
const schedule = stepsOrder.reduce((acc, key) => {
const step = steps2[key];
acc[key] = (process2, keepAlive = false, immediate2 = false) => {
if (!runNextFrame)
wake();
return step.schedule(process2, keepAlive, immediate2);
};
return acc;
}, {});
const cancel = (process2) => stepsOrder.forEach((key) => steps2[key].cancel(process2));
return { schedule, cancel, state, steps: steps2 };
}
const { schedule: frame, cancel: cancelFrame, state: frameData, steps } = createRenderBatcher(typeof requestAnimationFrame !== "undefined" ? requestAnimationFrame : noop$3, true);
const svgMotionConfig = {
useVisualState: makeUseVisualState({
scrapeMotionValuesFromProps,
createRenderState: createSvgRenderState,
onMount: (props, instance, { renderState, latestValues }) => {
frame.read(() => {
try {
renderState.dimensions = typeof instance.getBBox === "function" ? instance.getBBox() : instance.getBoundingClientRect();
} catch (e) {
renderState.dimensions = {
x: 0,
y: 0,
width: 0,
height: 0
};
}
});
frame.render(() => {
buildSVGAttrs(renderState, latestValues, { enableHardwareAcceleration: false }, isSVGTag(instance.tagName), props.transformTemplate);
renderSVG(instance, renderState);
});
}
})
};
const htmlMotionConfig = {
useVisualState: makeUseVisualState({
scrapeMotionValuesFromProps: scrapeMotionValuesFromProps$1,
createRenderState: createHtmlRenderState
})
};
function createDomMotionConfig(Component, { forwardMotionProps = false }, preloadedFeatures, createVisualElement) {
const baseConfig = isSVGComponent(Component) ? svgMotionConfig : htmlMotionConfig;
return {
...baseConfig,
preloadedFeatures,
useRender: createUseRender(forwardMotionProps),
createVisualElement,
Component
};
}
let warning$2 = noop$3;
let invariant$2 = noop$3;
if (process.env.NODE_ENV !== "production") {
warning$2 = (check, message) => {
if (!check && typeof console !== "undefined") {
console.warn(message);
}
};
invariant$2 = (check, message) => {
if (!check) {
throw new Error(message);
}
};
}
const m = createMotionProxy(createDomMotionConfig);
function useIsMounted() {
const isMounted = useRef(false);
useIsomorphicLayoutEffect$2(() => {
isMounted.current = true;
return () => {
isMounted.current = false;
};
}, []);
return isMounted;
}
function useForceUpdate() {
const isMounted = useIsMounted();
const [forcedRenderCount, setForcedRenderCount] = useState(0);
const forceRender = useCallback$1(() => {
isMounted.current && setForcedRenderCount(forcedRenderCount + 1);
}, [forcedRenderCount]);
const deferredForceRender = useCallback$1(() => frame.postRender(forceRender), [forceRender]);
return [deferredForceRender, forcedRenderCount];
}
class PopChildMeasure extends 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 = useId();
const ref2 = useRef(null);
const size = useRef({
width: 0,
height: 0,
top: 0,
left: 0
});
useInsertionEffect(() => {
const { width, height, top, left } = size.current;
if (isPresent || !ref2.current || !width || !height)
return;
ref2.current.dataset.motionPopId = id;
const style2 = document.createElement("style");
document.head.appendChild(style2);
if (style2.sheet) {
style2.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(style2);
};
}, [isPresent]);
return React.createElement(PopChildMeasure, { isPresent, childRef: ref2, sizeRef: size }, React.cloneElement(children, { ref: ref2 }));
}
const PresenceChild = ({ children, initial, isPresent, onExitComplete, custom, presenceAffectsLayout, mode }) => {
const presenceChildren = useConstant(newChildrenMap);
const id = useId();
const context = useMemo$1(
() => ({
id,
initial,
isPresent,
custom,
onExitComplete: (childId) => {
presenceChildren.set(childId, true);
for (const isComplete of presenceChildren.values()) {
if (!isComplete)
return;
}
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 ? void 0 : [isPresent]
);
useMemo$1(() => {
presenceChildren.forEach((_, key) => presenceChildren.set(key, false));
}, [isPresent]);
React.useEffect(() => {
!isPresent && !presenceChildren.size && onExitComplete && onExitComplete();
}, [isPresent]);
if (mode === "popLayout") {
children = React.createElement(PopChild, { isPresent }, children);
}
return React.createElement(PresenceContext.Provider, { value: context }, children);
};
function newChildrenMap() {
return /* @__PURE__ */ new Map();
}
function useUnmountEffect(callback) {
return useEffect(() => () => callback(), []);
}
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 = [];
Children.forEach(children, (child) => {
if (isValidElement(child))
filtered.push(child);
});
return filtered;
}
const AnimatePresence = ({ children, custom, initial = true, onExitComplete, exitBeforeEnter, presenceAffectsLayout = true, mode = "sync" }) => {
invariant$2(!exitBeforeEnter, "Replace exitBeforeEnter with mode='wait'");
const forceRender = useContext$a(LayoutGroupContext).forceRender || useForceUpdate()[0];
const isMounted = useIsMounted();
const filteredChildren = onlyElements(children);
let childrenToRender = filteredChildren;
const exitingChildren = useRef(/* @__PURE__ */ new Map()).current;
const presentChildren = useRef(childrenToRender);
const allChildren = useRef(/* @__PURE__ */ new Map()).current;
const isInitialRender = useRef(true);
useIsomorphicLayoutEffect$2(() => {
isInitialRender.current = false;
updateChildLookup(filteredChildren, allChildren);
presentChildren.current = childrenToRender;
});
useUnmountEffect(() => {
isInitialRender.current = true;
allChildren.clear();
exitingChildren.clear();
});
if (isInitialRender.current) {
return React.createElement(React.Fragment, null, childrenToRender.map((child) => React.createElement(PresenceChild, { key: getChildKey(child), isPresent: true, initial: initial ? void 0 : false, presenceAffectsLayout, mode }, child)));
}
childrenToRender = [...childrenToRender];
const presentKeys = presentChildren.current.map(getChildKey);
const targetKeys = filteredChildren.map(getChildKey);
const numPresent = presentKeys.length;
for (let i = 0; i < numPresent; i++) {
const key = presentKeys[i];
if (targetKeys.indexOf(key) === -1 && !exitingChildren.has(key)) {
exitingChildren.set(key, void 0);
}
}
if (mode === "wait" && exitingChildren.size) {
childrenToRender = [];
}
exitingChildren.forEach((component, key) => {
if (targetKeys.indexOf(key) !== -1)
return;
const child = allChildren.get(key);
if (!child)
return;
const insertionIndex = presentKeys.indexOf(key);
let exitingComponent = component;
if (!exitingComponent) {
const onExit = () => {
exitingChildren.delete(key);
const leftOverKeys = Array.from(allChildren.keys()).filter((childKey) => !targetKeys.includes(childKey));
leftOverKeys.forEach((leftOverKey) => allChildren.delete(leftOverKey));
presentChildren.current = filteredChildren.filter((presentChild) => {
const presentChildKey = getChildKey(presentChild);
return (
// filter out the node exiting
presentChildKey === key || // filter out the leftover children
leftOverKeys.includes(presentChildKey)
);
});
if (!exitingChildren.size) {
if (isMounted.current === false)
return;
forceRender();
onExitComplete && onExitComplete();
}
};
exitingComponent = React.createElement(PresenceChild, { key: getChildKey(child), isPresent: false, onExitComplete: onExit, custom, presenceAffectsLayout, mode }, child);
exitingChildren.set(key, exitingComponent);
}
childrenToRender.splice(insertionIndex, 0, exitingComponent);
});
childrenToRender = childrenToRender.map((child) => {
const key = child.key;
return exitingChildren.has(key) ? child : React.createElement(PresenceChild, { key: getChildKey(child), isPresent: true, presenceAffectsLayout, mode }, child);
});
if (process.env.NODE_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 React.createElement(React.Fragment, null, exitingChildren.size ? childrenToRender : childrenToRender.map((child) => cloneElement(child)));
};
function LazyMotion({ children, features, strict = false }) {
const [, setIsLoaded] = useState(!isLazyBundle(features));
const loadedRenderer = useRef(void 0);
if (!isLazyBundle(features)) {
const { renderer, ...loadedFeatures } = features;
loadedRenderer.current = renderer;
loadFeatures(loadedFeatures);
}
useEffect(() => {
if (isLazyBundle(features)) {
features().then(({ renderer, ...loadedFeatures }) => {
loadFeatures(loadedFeatures);
loadedRenderer.current = renderer;
setIsLoaded(true);
});
}
}, []);
return React.createElement(LazyContext.Provider, { value: { renderer: loadedRenderer.current, strict } }, children);
}
function isLazyBundle(features) {
return typeof features === "function";
}
const StyledMenu = styled(m.nav).attrs(({ $x, $y }) => ({
style: {
transform: `translate(${$x}px, ${$y}px)`
}
}))`
${defaultStyles}
background-color: rgb(43, 43, 43);
border: 1px solid rgb(160, 160, 160);
box-shadow:
1px 1px 1px hsla(0, 0%, 20%, 70%),
2px 2px 2px hsla(0, 0%, 10%, 70%);
color: rgb(255, 255, 255);
contain: layout;
font-size: 12px;
max-height: fit-content;
max-width: fit-content;
padding: 4px 2px;
position: fixed;
width: max-content;
z-index: ${({ $isSubMenu }) => 1e4 + ($isSubMenu ? 1 : 0)};
ol {
list-style: none; /* Remove list style */
cursor: pointer;
padding: 0;
margin: 0;
li.disabled {
color: rgb(110, 110, 110);
pointer-events: none;
}
hr {
background-color: rgb(128, 128, 128);
height: 1px;
margin: 3px 8px;
}
li > div {
display: flex;
padding: 3px 0;
&:hover,
&.active {
background-color: rgb(65, 65, 65);
}
figcaption {
display: flex;
height: 16px;
line-height: 16px;
margin-left: 32px;
margin-right: 64px;
place-items: center;
position: relative;
top: -1px;
white-space: nowrap;
width: max-content;
&.primary {
font-weight: 700;
}
}
picture {
margin: 0 -24px 0 8px;
}
span {
margin: -1px -24px 0 8px;
}
svg {
fill: #fff;
height: 13px;
margin-top: 1px;
position: absolute;
width: 13px;
&.left {
left: 8px;
}
&.right {
right: 8px;
}
}
.icon > svg {
height: 15px;
left: 10px;
width: 15px;
}
}
}
`;
const menuTransition = {
animate: { opacity: 1 },
initial: { opacity: 0 },
transition: {
duration: TRANSITIONS_IN_SECONDS.WINDOW
}
};
const topLeftPosition = () => ({
x: 0,
y: 0
});
const Menu = ({ subMenu }) => {
const { menu: baseMenu = {}, setMenu } = useContext$6();
const {
items,
staticX = 0,
staticY = 0,
x = 0,
y = 0
} = subMenu || baseMenu || {};
const [offset3, setOffset] = useState(topLeftPosition());
const menuRef = useRef(null);
const { WindowsViewArea, WindowsViewAreaSize } = useContext$7();
const resetMenu = useCallback$1(
({ relatedTarget } = {}) => {
var _a;
if (!(relatedTarget instanceof HTMLElement) || !((_a = menuRef.current) == null ? void 0 : _a.contains(relatedTarget))) {
setMenu(/* @__PURE__ */ Object.create(null));
}
},
[setMenu]
);
const isSubMenu = Boolean(subMenu);
const offsetCalculated = useRef({});
const calculateOffset = useCallback$1(() => {
var _a;
if (!menuRef.current || offsetCalculated.current.x === x && offsetCalculated.current.y === y) {
return;
}
offsetCalculated.current = { x, y };
let {
height = 0,
width = 0,
// eslint-disable-next-line prefer-const
x: menuX = 0,
// eslint-disable-next-line prefer-const
y: menuY = 0
} = ((_a = menuRef.current) == null ? void 0 : _a.getBoundingClientRect()) || {};
let { height: vh2, width: vw2 } = WindowsViewArea ? getElementSize(WindowsViewArea) : WindowsViewAreaSize;
const newOffset = { x: 0, y: 0 };
height = pxToNum(height);
width = pxToNum(width);
vw2 = pxToNum(vw2);
vh2 = pxToNum(vh2);
if (!staticX) {
const subMenuOffscreenX = Boolean(subMenu) && menuX + width > vw2;
newOffset.x = Math.round(Math.max(0, x + width - vw2)) + (subMenuOffscreenX ? Math.round(width + ((subMenu == null ? void 0 : subMenu.x) || 0)) : 0);
const adjustedOffsetX = subMenuOffscreenX && menuX - newOffset.x < 0 ? newOffset.x - (newOffset.x - menuX) : 0;
if (adjustedOffsetX > 0) newOffset.x = adjustedOffsetX;
}
if (!staticY) {
const bottomOffset = y + height > vh2 ? vh2 - y : 0;
const topAdjustedBottomOffset = bottomOffset + height > vh2 ? 0 : bottomOffset;
const subMenuOffscreenY = Boolean(subMenu) && menuY + height > vh2;
newOffset.y = Math.round(Math.max(0, y + height - (vh2 - topAdjustedBottomOffset))) + (subMenuOffscreenY ? Math.round(height + ((subMenu == null ? void 0 : subMenu.y) || 0)) : 0);
}
setOffset(newOffset);
}, [staticX, staticY, subMenu, x, y, WindowsViewArea]);
const menuCallbackRef = useCallback$1(
(ref2) => {
menuRef.current = ref2;
calculateOffset();
},
[calculateOffset]
);
useEffect(() => {
var _a;
if (((_a = subMenu || baseMenu) == null ? void 0 : _a.items) && (x || y)) calculateOffset();
}, [baseMenu, calculateOffset, subMenu, x, y]);
useEffect(() => {
var _a;
if (items && !subMenu) {
const focusedElement = document.activeElement;
if (focusedElement instanceof HTMLElement && focusedElement !== document.body) {
const options = {
capture: true,
...ONE_TIME_PASSIVE_EVENT
};
const menuUnfocused = ({
relatedTarget,
type
}) => {
var _a2;
if (!(relatedTarget instanceof HTMLElement) || !((_a2 = menuRef.current) == null ? void 0 : _a2.contains(relatedTarget))) {
resetMenu();
}
focusedElement.removeEventListener(
type === "click" ? "blur" : "click",
menuUnfocused,
{ capture: true }
);
};
focusedElement.addEventListener("click", menuUnfocused, options);
focusedElement.addEventListener("blur", menuUnfocused, options);
} else {
(_a = menuRef.current) == null ? void 0 : _a.focus(PREVENT_SCROLL);
}
}
}, [items, resetMenu, subMenu]);
useEffect(() => {
if (!items) offsetCalculated.current = {};
}, [items, offset3.x, offset3.y, subMenu]);
useEffect(() => {
const resetOnEscape = ({ key }) => {
if (key === "Escape") resetMenu();
};
if (items) {
window.addEventListener("keydown", resetOnEscape, { passive: true });
}
return () => window.removeEventListener("keydown", resetOnEscape);
}, [items, resetMenu]);
return items ? /* @__PURE__ */ jsx(
StyledMenu,
{
ref: menuCallbackRef,
$isSubMenu: isSubMenu,
$x: staticX || x - offset3.x,
$y: staticY || y - offset3.y,
onBlurCapture: resetMenu,
onContextMenu: haltEvent,
...menuTransition,
...FOCUSABLE_ELEMENT,
children: /* @__PURE__ */ jsx("ol", { children: items.map((item, index) => /* @__PURE__ */ jsx(
MenuItemEntry,
{
isSubMenu,
resetMenu,
...item
},
`${item.label || "item"}-${index}`
)) })
}
) : null;
};
const useMenuContextState = () => {
const [menu, setMenu] = useState(/* @__PURE__ */ Object.create(null));
const touchTimer = useRef(0);
const touchEvent = useRef();
const contextMenu = useCallback$1(
(getItems) => {
const onContextMenuCapture = (event, domRect, options) => {
const { staticX, staticY } = options || {};
let x = 0;
let y = 0;
if (event) {
if (event.cancelable) event.preventDefault();
if ("touches" in event) {
const touch = event.touches[0];
x = touch.pageX;
y = touch.pageY;
} else {
x = event.pageX;
y = event.pageY;
}
const { scrollX, scrollY } = window;
x += scrollX;
y += scrollY;
} else if (domRect) {
const { height, x: inputX, y: inputY } = domRect;
x = inputX;
y = inputY + height;
const { scrollX, scrollY } = window;
x += scrollX;
y += scrollY;
}
const items = getItems(event);
setMenu({
items: items.length > 0 ? items : void 0,
staticX,
staticY,
x,
y
});
};
return {
onContextMenuCapture,
...isSafari() && {
onTouchEnd: (event) => {
if (touchEvent.current) {
event.preventDefault();
onContextMenuCapture(touchEvent.current);
touchEvent.current = void 0;
}
window.clearTimeout(touchTimer.current);
},
onTouchMove: () => {
touchEvent.current = void 0;
window.clearTimeout(touchTimer.current);
},
onTouchStart: (event) => {
window.clearTimeout(touchTimer.current);
touchTimer.current = window.setTimeout(() => {
touchEvent.current = event;
}, TRANSITIONS_IN_MILLISECONDS.LONG_PRESS);
}
}
};
},
[]
);
return { contextMenu, menu, setMenu };
};
const { Provider: Provider$7, useContext: useContext$6 } = contextFactory(useMenuContextState, /* @__PURE__ */ jsx(Menu, {}));
const closeProcess = (processId, RD_Actions) => (currentProcesses) => {
var _a;
const { [processId]: _closedProcess, ...remainingProcesses } = currentProcesses;
if (_closedProcess.windowIDs && _closedProcess.windowIDs.length > 0) {
(_a = _closedProcess.windowIDs) == null ? void 0 : _a.forEach(
(windowID) => RD_Actions.emit("action:windows/close_transition", windowID)
);
}
return remainingProcesses;
};
const createNewProcess = (newProcessID, processObj) => (currentProcesses) => {
return {
...currentProcesses,
[newProcessID]: {
id: newProcessID,
...processObj
}
};
};
const useProcessContextState = () => {
const [processes, setProcesses] = useState(
/* @__PURE__ */ Object.create(null)
);
const { events: RD_Events, actions: RD_Actions } = useContext$8();
const close = useCallback$1(
(id) => {
setProcesses(closeProcess(id, RD_Actions));
},
[RD_Actions]
);
const createProcess = useCallback$1(
(processInfo) => {
const newProcessID = generateOddNumber().toString();
setProcesses(createNewProcess(newProcessID, processInfo));
RD_Events.emit("event:processes/new_process", {
id: newProcessID,
...processInfo
});
return newProcessID;
},
[RD_Events]
);
const addWindowIDToProcess = useCallback$1(
(id, windowID) => {
},
[]
);
const removeWindowIDFromProcess = useCallback$1(
(id, windowID) => {
},
[]
);
useEffect(() => {
const registeredEvents = [
RD_Actions.on("action:processes/create_process", createProcess)
];
return () => {
registeredEvents.forEach(
(eventID) => RD_Actions.removeListenerByID(eventID)
);
};
}, [RD_Actions, createProcess]);
return {
processes,
// Functions:
close,
createProcess,
addWindowIDToProcess,
removeWindowIDFromProcess
};
};
const { Provider: Provider$6, useContext: useContext$5 } = contextFactory(useProcessContextState);
var lodash_merge = { exports: {} };
lodash_merge.exports;
(function(module, exports) {
var LARGE_ARRAY_SIZE = 200;
var HASH_UNDEFINED = "__lodash_hash_undefined__";
var HOT_COUNT = 800, HOT_SPAN = 16;
var MAX_SAFE_INTEGER = 9007199254740991;
var argsTag = "[object Arguments]", arrayTag = "[object Array]", asyncTag = "[object AsyncFunction]", boolTag = "[object Boolean]", dateTag = "[object Date]", errorTag = "[object Error]", funcTag = "[object Function]", genTag = "[object GeneratorFunction]", mapTag = "[object Map]", numberTag = "[object Number]", nullTag = "[object Null]", objectTag = "[object Object]", proxyTag = "[object Proxy]", regexpTag = "[object RegExp]", setTag = "[object Set]", stringTag = "[object String]", undefinedTag = "[object Undefined]", weakMapTag = "[object WeakMap]";
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]";
var reRegExpChar = /[\\^$.*+?()[\]{}|]/g;
var reIsHostCtor = /^\[object .+?Constructor\]$/;
var reIsUint = /^(?:0|[1-9]\d*)$/;
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;
var freeGlobal = typeof commonjsGlobal == "object" && commonjsGlobal && commonjsGlobal.Object === Object && commonjsGlobal;
var freeSelf = typeof self == "object" && self && self.Object === Object && self;
var root = freeGlobal || freeSelf || Function("return this")();
var freeExports = exports && !exports.nodeType && exports;
var freeModule = freeExports && true && module && !module.nodeType && module;
var moduleExports = freeModule && freeModule.exports === freeExports;
var freeProcess = moduleExports && freeGlobal.process;
var nodeUtil = function() {
try {
var types = freeModule && freeModule.require && freeModule.require("util").types;
if (types) {
return types;
}
return freeProcess && freeProcess.binding && freeProcess.binding("util");
} catch (e) {
}
}();
var nodeIsTypedArray = nodeUtil && nodeUtil.isTypedArray;
function apply2(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);
}
function baseTimes(n, iteratee) {
var index = -1, result = Array(n);
while (++index < n) {
result[index] = iteratee(index);
}
return result;
}
function baseUnary(func) {
return function(value) {
return func(value);
};
}
function getValue2(object, key) {
return object == null ? void 0 : object[key];
}
function overArg(func, transform) {
return function(arg) {
return func(transform(arg));
};
}
var arrayProto = Array.prototype, funcProto = Function.prototype, objectProto = Object.prototype;
var coreJsData = root["__core-js_shared__"];
var funcToString = funcProto.toString;
var hasOwnProperty = objectProto.hasOwnProperty;
var maskSrcKey = function() {
var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || "");
return uid ? "Symbol(src)_1." + uid : "";
}();
var nativeObjectToString = objectProto.toString;
var objectCtorString = funcToString.call(Object);
var reIsNative = RegExp(
"^" + funcToString.call(hasOwnProperty).replace(reRegExpChar, "\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, "$1.*?") + "$"
);
var Buffer = moduleExports ? root.Buffer : void 0, Symbol2 = root.Symbol, Uint8Array2 = root.Uint8Array;
Buffer ? Buffer.allocUnsafe : void 0;
var getPrototype = overArg(Object.getPrototypeOf, Object), objectCreate = Object.create, propertyIsEnumerable = objectProto.propertyIsEnumerable, splice = arrayProto.splice, symToStringTag = Symbol2 ? Symbol2.toStringTag : void 0;
var defineProperty2 = function() {
try {
var func = getNative(Object, "defineProperty");
func({}, "", {});
return func;
} catch (e) {
}
}();
var nativeIsBuffer = Buffer ? Buffer.isBuffer : void 0, nativeMax = Math.max, nativeNow = Date.now;
var Map2 = getNative(root, "Map"), nativeCreate = getNative(Object, "create");
var baseCreate = /* @__PURE__ */ function() {
function object() {
}
return function(proto) {
if (!isObject(proto)) {
return {};
}
if (objectCreate) {
return objectCreate(proto);
}
object.prototype = proto;
var result = new object();
object.prototype = void 0;
return result;
};
}();
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]);
}
}
function hashClear() {
this.__data__ = nativeCreate ? nativeCreate(null) : {};
this.size = 0;
}
function hashDelete(key) {
var result = this.has(key) && delete this.__data__[key];
this.size -= result ? 1 : 0;
return result;
}
function hashGet(key) {
var data = this.__data__;
if (nativeCreate) {
var result = data[key];
return result === HASH_UNDEFINED ? void 0 : result;
}
return hasOwnProperty.call(data, key) ? data[key] : void 0;
}
function hashHas(key) {
var data = this.__data__;
return nativeCreate ? data[key] !== void 0 : hasOwnProperty.call(data, key);
}
function hashSet(key, value) {
var data = this.__data__;
this.size += this.has(key) ? 0 : 1;
data[key] = nativeCreate && value === void 0 ? HASH_UNDEFINED : value;
return this;
}
Hash.prototype.clear = hashClear;
Hash.prototype["delete"] = hashDelete;
Hash.prototype.get = hashGet;
Hash.prototype.has = hashHas;
Hash.prototype.set = hashSet;
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]);
}
}
function listCacheClear() {
this.__data__ = [];
this.size = 0;
}
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;
}
function listCacheGet(key) {
var data = this.__data__, index = assocIndexOf(data, key);
return index < 0 ? void 0 : data[index][1];
}
function listCacheHas(key) {
return assocIndexOf(this.__data__, key) > -1;
}
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;
}
ListCache.prototype.clear = listCacheClear;
ListCache.prototype["delete"] = listCacheDelete;
ListCache.prototype.get = listCacheGet;
ListCache.prototype.has = listCacheHas;
ListCache.prototype.set = listCacheSet;
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]);
}
}
function mapCacheClear() {
this.size = 0;
this.__data__ = {
"hash": new Hash(),
"map": new (Map2 || ListCache)(),
"string": new Hash()
};
}
function mapCacheDelete(key) {
var result = getMapData(this, key)["delete"](key);
this.size -= result ? 1 : 0;
return result;
}
function mapCacheGet(key) {
return getMapData(this, key).get(key);
}
function mapCacheHas(key) {
return getMapData(this, key).has(key);
}
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;
}
MapCache.prototype.clear = mapCacheClear;
MapCache.prototype["delete"] = mapCacheDelete;
MapCache.prototype.get = mapCacheGet;
MapCache.prototype.has = mapCacheHas;
MapCache.prototype.set = mapCacheSet;
function Stack(entries) {
var data = this.__data__ = new ListCache(entries);
this.size = data.size;
}
function stackClear() {
this.__data__ = new ListCache();
this.size = 0;
}
function stackDelete(key) {
var data = this.__data__, result = data["delete"](key);
this.size = data.size;
return result;
}
function stackGet(key) {
return this.__data__.get(key);
}
function stackHas(key) {
return this.__data__.has(key);
}
function stackSet(key, value) {
var data = this.__data__;
if (data instanceof ListCache) {
var pairs = data.__data__;
if (!Map2 || 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;
}
Stack.prototype.clear = stackClear;
Stack.prototype["delete"] = stackDelete;
Stack.prototype.get = stackGet;
Stack.prototype.has = stackHas;
Stack.prototype.set = stackSet;
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 (!(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;
}
function assignMergeValue(object, key, value) {
if (value !== void 0 && !eq(object[key], value) || value === void 0 && !(key in object)) {
baseAssignValue(object, key, value);
}
}
function assignValue(object, key, value) {
var objValue = object[key];
if (!(hasOwnProperty.call(object, key) && eq(objValue, value)) || value === void 0 && !(key in object)) {
baseAssignValue(object, key, value);
}
}
function assocIndexOf(array, key) {
var length = array.length;
while (length--) {
if (eq(array[length][0], key)) {
return length;
}
}
return -1;
}
function baseAssignValue(object, key, value) {
if (key == "__proto__" && defineProperty2) {
defineProperty2(object, key, {
"configurable": true,
"enumerable": true,
"value": value,
"writable": true
});
} else {
object[key] = value;
}
}
var baseFor = createBaseFor();
function baseGetTag(value) {
if (value == null) {
return value === void 0 ? undefinedTag : nullTag;
}
return symToStringTag && symToStringTag in Object(value) ? getRawTag(value) : objectToString(value);
}
function baseIsArguments(value) {
return isObjectLike(value) && baseGetTag(value) == argsTag;
}
function baseIsNative(value) {
if (!isObject(value) || isMasked(value)) {
return false;
}
var pattern = isFunction(value) ? reIsNative : reIsHostCtor;
return pattern.test(toSource(value));
}
function baseIsTypedArray(value) {
return isObjectLike(value) && isLength(value.length) && !!typedArrayTags[baseGetTag(value)];
}
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;
}
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) : void 0;
if (newValue === void 0) {
newValue = srcValue;
}
assignMergeValue(object, key, newValue);
}
}, keysIn);
}
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) : void 0;
var isCommon = newValue === void 0;
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);
} else if (isTyped) {
isCommon = false;
newValue = cloneTypedArray(srcValue);
} else {
newValue = [];
}
} else if (isPlainObject2(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) {
stack.set(srcValue, newValue);
mergeFunc(newValue, srcValue, srcIndex, customizer, stack);
stack["delete"](srcValue);
}
assignMergeValue(object, key, newValue);
}
function baseRest(func, start2) {
return setToString(overRest(func, start2, identity), func + "");
}
var baseSetToString = !defineProperty2 ? identity : function(func, string) {
return defineProperty2(func, "toString", {
"configurable": true,
"enumerable": false,
"value": constant(string),
"writable": true
});
};
function cloneBuffer(buffer, isDeep) {
{
return buffer.slice();
}
}
function cloneArrayBuffer(arrayBuffer) {
var result = new arrayBuffer.constructor(arrayBuffer.byteLength);
new Uint8Array2(result).set(new Uint8Array2(arrayBuffer));
return result;
}
function cloneTypedArray(typedArray, isDeep) {
var buffer = cloneArrayBuffer(typedArray.buffer);
return new typedArray.constructor(buffer, typedArray.byteOffset, typedArray.length);
}
function copyArray(source, array) {
var index = -1, length = source.length;
array || (array = Array(length));
while (++index < length) {
array[index] = source[index];
}
return array;
}
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 = void 0;
if (newValue === void 0) {
newValue = source[key];
}
if (isNew) {
baseAssignValue(object, key, newValue);
} else {
assignValue(object, key, newValue);
}
}
return object;
}
function createAssigner(assigner) {
return baseRest(function(object, sources) {
var index = -1, length = sources.length, customizer = length > 1 ? sources[length - 1] : void 0, guard = length > 2 ? sources[2] : void 0;
customizer = assigner.length > 3 && typeof customizer == "function" ? (length--, customizer) : void 0;
if (guard && isIterateeCall(sources[0], sources[1], guard)) {
customizer = length < 3 ? void 0 : customizer;
length = 1;
}
object = Object(object);
while (++index < length) {
var source = sources[index];
if (source) {
assigner(object, source, index, customizer);
}
}
return object;
});
}
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[++index];
if (iteratee(iterable[key], key, iterable) === false) {
break;
}
}
return object;
};
}
function getMapData(map, key) {
var data = map.__data__;
return isKeyable(key) ? data[typeof key == "string" ? "string" : "hash"] : data.map;
}
function getNative(object, key) {
var value = getValue2(object, key);
return baseIsNative(value) ? value : void 0;
}
function getRawTag(value) {
var isOwn = hasOwnProperty.call(value, symToStringTag), tag = value[symToStringTag];
try {
value[symToStringTag] = void 0;
var unmasked = true;
} catch (e) {
}
var result = nativeObjectToString.call(value);
if (unmasked) {
if (isOwn) {
value[symToStringTag] = tag;
} else {
delete value[symToStringTag];
}
}
return result;
}
function initCloneObject(object) {
return typeof object.constructor == "function" && !isPrototype(object) ? baseCreate(getPrototype(object)) : {};
}
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);
}
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;
}
function isKeyable(value) {
var type = typeof value;
return type == "string" || type == "number" || type == "symbol" || type == "boolean" ? value !== "__proto__" : value === null;
}
function isMasked(func) {
return !!maskSrcKey && maskSrcKey in func;
}
function isPrototype(value) {
var Ctor = value && value.constructor, proto = typeof Ctor == "function" && Ctor.prototype || objectProto;
return value === proto;
}
function nativeKeysIn(object) {
var result = [];
if (object != null) {
for (var key in Object(object)) {
result.push(key);
}
}
return result;
}
function objectToString(value) {
return nativeObjectToString.call(value);
}
function overRest(func, start2, transform) {
start2 = nativeMax(start2 === void 0 ? func.length - 1 : start2, 0);
return function() {
var args = arguments, index = -1, length = nativeMax(args.length - start2, 0), array = Array(length);
while (++index < length) {
array[index] = args[start2 + index];
}
index = -1;
var otherArgs = Array(start2 + 1);
while (++index < start2) {
otherArgs[index] = args[index];
}
otherArgs[start2] = transform(array);
return apply2(func, this, otherArgs);
};
}
function safeGet(object, key) {
if (key === "constructor" && typeof object[key] === "function") {
return;
}
if (key == "__proto__") {
return;
}
return object[key];
}
var setToString = shortOut(baseSetToString);
function shortOut(func) {
var count2 = 0, lastCalled = 0;
return function() {
var stamp = nativeNow(), remaining = HOT_SPAN - (stamp - lastCalled);
lastCalled = stamp;
if (remaining > 0) {
if (++count2 >= HOT_COUNT) {
return arguments[0];
}
} else {
count2 = 0;
}
return func.apply(void 0, arguments);
};
}
function toSource(func) {
if (func != null) {
try {
return funcToString.call(func);
} catch (e) {
}
try {
return func + "";
} catch (e) {
}
}
return "";
}
function eq(value, other) {
return value === other || value !== value && other !== other;
}
var isArguments = baseIsArguments(/* @__PURE__ */ function() {
return arguments;
}()) ? baseIsArguments : function(value) {
return isObjectLike(value) && hasOwnProperty.call(value, "callee") && !propertyIsEnumerable.call(value, "callee");
};
var isArray = Array.isArray;
function isArrayLike(value) {
return value != null && isLength(value.length) && !isFunction(value);
}
function isArrayLikeObject(value) {
return isObjectLike(value) && isArrayLike(value);
}
var isBuffer = nativeIsBuffer || stubFalse;
function isFunction(value) {
if (!isObject(value)) {
return false;
}
var tag = baseGetTag(value);
return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag;
}
function isLength(value) {
return typeof value == "number" && value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;
}
function isObject(value) {
var type = typeof value;
return value != null && (type == "object" || type == "function");
}
function isObjectLike(value) {
return value != null && typeof value == "object";
}
function isPlainObject2(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;
}
var isTypedArray = nodeIsTypedArray ? baseUnary(nodeIsTypedArray) : baseIsTypedArray;
function toPlainObject(value) {
return copyObject(value, keysIn(value));
}
function keysIn(object) {
return isArrayLike(object) ? arrayLikeKeys(object) : baseKeysIn(object);
}
var merge2 = createAssigner(function(object, source, srcIndex) {
baseMerge(object, source, srcIndex);
});
function constant(value) {
return function() {
return value;
};
}
function identity(value) {
return value;
}
function stubFalse() {
return false;
}
module.exports = merge2;
})(lodash_merge, lodash_merge.exports);
var lodash_mergeExports = lodash_merge.exports;
const merge = /* @__PURE__ */ getDefaultExportFromCjs(lodash_mergeExports);
const setWindowSetting = (windowID, settings, deepCopy = true) => (currentWindows) => {
const { ...newWindows } = currentWindows;
if (newWindows[windowID]) {
if (deepCopy) {
newWindows[windowID] = merge(newWindows[windowID], settings);
} else {
newWindows[windowID] = {
...newWindows[windowID],
...settings
};
}
}
return newWindows;
};
const closeWindow = (windowID, closing, removeWindowIDFromProcess) => (currentWindows) => {
if (closing) {
return setWindowSetting(windowID, { closing })(currentWindows);
}
const { [windowID]: _closedWindow, ...remainingWindows } = currentWindows;
if (_closedWindow) {
if (_closedWindow.process && removeWindowIDFromProcess) {
removeWindowIDFromProcess(_closedWindow.process.pid, windowID);
}
}
return remainingWindows;
};
const maximizeWindow = (windowID) => (currentWindows) => {
var _a;
const newMaximizedState = !((_a = currentWindows[windowID]) == null ? void 0 : _a.maximized);
if (newMaximizedState) {
const { componentWindow } = currentWindows[windowID];
requestAnimationFrame(() => componentWindow == null ? void 0 : componentWindow.focus(PREVENT_SCROLL));
}
return setWindowSetting(windowID, {
maximized: newMaximizedState
})(currentWindows);
};
const minimizeWindow = (windowID) => (currentWindows) => {
var _a;
return setWindowSetting(windowID, {
minimized: !((_a = currentWindows[windowID]) == null ? void 0 : _a.minimized)
})(currentWindows);
};
const setIcon = (windowID, icon) => (currentWindows) => setWindowSetting(windowID, { icon })(currentWindows);
const setTitle = (windowID, title) => (currentWindows) => setWindowSetting(windowID, { title })(currentWindows);
const setWindowElement = (windowID, name, element) => (currentWindows) => setWindowSetting(windowID, { [name]: element })(currentWindows);
const createNewWindow = (newWindowID, windowObj) => (currentWindows) => {
let Component;
if (React__default.isValidElement(windowObj.Component)) {
Component = () => windowObj.Component;
} else {
Component = windowObj.Component;
}
return {
...currentWindows,
[newWindowID]: {
...windowObj,
id: newWindowID,
Component
}
};
};
const useWindowsContextState = () => {
const [windows, setWindows] = useState(
/* @__PURE__ */ Object.create(null)
);
const [sequence, setSequence] = useState(
[]
);
const { addWindowIDToProcess, removeWindowIDFromProcess } = useContext$5();
const { events: RD_Events, actions: RD_Actions } = useContext$8();
const close = useCallback$1(
(id, closing) => setWindows(closeWindow(id, closing, removeWindowIDFromProcess)),
[removeWindowIDFromProcess]
);
const linkElement = useCallback$1(
(id, name, element) => setWindows(setWindowElement(id, name, element)),
[]
);
const icon = useCallback$1(
(id, newIcon) => setWindows(setIcon(id, newIcon)),
[]
);
const update2 = useCallback$1(
(windowID, settings, deepCopy = true) => setWindows(setWindowSetting(windowID, settings, deepCopy)),
[]
);
const setSnap = useCallback$1(
(id, snapStatus) => setWindows(setWindowSetting(id, { snap: snapStatus })),
[]
);
const maximize = useCallback$1(
(id) => setWindows(maximizeWindow(id)),
[]
);
const minimize = useCallback$1(
(id) => setWindows(minimizeWindow(id)),
[]
);
const title = useCallback$1(
(id, newTitle) => setWindows(setTitle(id, newTitle)),
[]
);
const createWindow = useCallback$1(
(windowObj) => {
const newWindowID = generateOddNumber().toString();
setWindows(createNewWindow(newWindowID, windowObj));
setSequence((prevSequence) => [...prevSequence, newWindowID]);
if (windowObj.process && windowObj.process.pid) {
addWindowIDToProcess(windowObj.process.pid, newWindowID);
}
const { Component: _Component, ...windowObjWithoutComponent } = windowObj;
RD_Events.emit("event:windows/new_window", {
id: newWindowID,
...windowObjWithoutComponent
});
return newWindowID;
},
[addWindowIDToProcess, RD_Events]
);
const closeWithTransition = useCallback$1(
(id) => {
close(id, true);
window.setTimeout(() => {
close(id);
RD_Events.emit("event:windows/close", id);
}, TRANSITIONS_IN_MILLISECONDS.WINDOW);
RD_Events.emit("event:windows/close_transition", id);
},
[close, RD_Events]
);
useEffect(() => {
const registeredEvents = [
RD_Actions.on("action:windows/create_window", createWindow)
];
return () => {
registeredEvents.forEach(RD_Actions.removeListenerByID);
};
}, [RD_Actions, createWindow]);
useEffect(() => {
const registeredEvents = [
RD_Actions.on("action:windows/close", close),
RD_Actions.on("action:windows/close_transition", closeWithTransition)
];
return () => {
registeredEvents.forEach(RD_Actions.removeListenerByID);
};
}, [RD_Actions, closeWithTransition, close]);
return {
update: update2,
linkElement,
closeWithTransition,
maximize,
minimize,
setSnap,
createWindow,
close,
icon,
title,
// State:
windows
};
};
const { Provider: Provider$5, useContext: useContext$4 } = contextFactory(useWindowsContextState);
const useSyscallContextState = () => {
const { createProcess } = useContext$5();
const { createWindow, maximize } = useContext$4();
const openAppByName = useCallback$1((name) => {
}, []);
const openApp = useCallback$1(
(appConfig) => {
const { name: appName, icon: appIcon, ...otherAppInfo } = appConfig;
const newProcessPID = createProcess({
name: appName,
icon: appIcon
});
if ((!!otherAppInfo.showWindow || otherAppInfo.windowContent) && otherAppInfo.windowContent) {
let Component;
if (React__default.isValidElement(otherAppInfo.windowContent)) {
Component = () => otherAppInfo.windowContent;
} else {
Component = otherAppInfo.windowContent;
}
let windowArguments = {
icon: appIcon,
title: appName,
Component,
process: {
pid: newProcessPID
}
};
if (otherAppInfo.windowConfig) {
windowArguments = {
...windowArguments,
...otherAppInfo.windowConfig
};
}
createWindow(windowArguments);
}
},
[createProcess, createWindow, maximize]
);
return {
// Functions:
openAppByName,
openApp
};
};
const { Provider: Provider$4, useContext: useContext$3 } = contextFactory(useSyscallContextState);
const useConfigContextState = ({ config }) => {
const [applications, setApplications] = useState([]);
const { openApp } = useContext$3();
const updateApplications = useCallback$1(
(newApplications) => {
setApplications((prevApps) => {
const newAppsMap = new Map(newApplications.map((app) => [app.name, app]));
const updatedApps = prevApps.map((app) => {
const newApp = newAppsMap.get(app.name);
if (newApp) {
console.log("Updating existing app:", app.name);
return newApp;
}
return app;
});
const newUniqueApps = newApplications.filter(
(app) => !prevApps.some((prevApp) => prevApp.name === app.name)
);
newUniqueApps.forEach((newApp, index) => {
if (newApp.runOnStart) {
console.log("Running on start:", newApp.name);
setTimeout(() => openApp(newApp), index * 1e3);
}
});
return [...updatedApps, ...newUniqueApps];
});
},
[openApp]
);
useEffect(() => {
if (config == null ? void 0 : config.applications) {
updateApplications(config == null ? void 0 : config.applications);
}
}, [config == null ? void 0 : config.applications, updateApplications]);
return {
...config,
taskbarPlacement: config.taskbarPlacement || "bottom",
applications
};
};
const { Provider: Provider$3, useContext: useContext$2 } = contextFactory(useConfigContextState);
const useWindowContextState = ({
rd_window_id
}) => {
const {
icon: setWindowIcon,
title: setWindowTitle,
closeWithTransition,
update: update2
// windows: { [id]: currentWindow },
} = useContext$4();
const eventEmitterRef = useRef(
EventsSignals()
);
const setWindowIconReady = useCallback$1(
(newIcon) => setWindowIcon(rd_window_id, newIcon),
[setWindowIcon, rd_window_id]
);
const setWindowTitleReady = useCallback$1(
(newTitle) => setWindowTitle(rd_window_id, newTitle),
[setWindowTitle, rd_window_id]
);
const closeThisWindow = useCallback$1(
() => closeWithTransition(rd_window_id),
[rd_window_id, closeWithTransition]
);
const updateThisWindow = useCallback$1(
(settings, deepCopy = true) => update2(rd_window_id, settings, deepCopy),
[]
);
const contextValue = useMemo$1(
() => ({
id: rd_window_id,
setWindowIcon: setWindowIconReady,
setWindowTitle: setWindowTitleReady,
close: closeThisWindow,
update: updateThisWindow,
Events: eventEmitterRef.current
}),
[rd_window_id, setWindowIconReady, setWindowTitleReady, closeThisWindow]
);
return contextValue;
};
const { Provider: Provider$2, useContext: useContext$1 } = contextFactory(useWindowContextState);
const useSessionContextState = (data) => {
const [sessionLoaded, setSessionLoaded] = useState(false);
const [previewID, setPreviewID] = useState(false);
const [foregroundId, setForegroundId] = useState("");
const [stackOrder, setStackOrder] = useState([]);
const [themeName, setThemeName] = useState(DEFAULT_THEME);
const [clockSource, setClockSource] = useState(DEFAULT_CLOCK_SOURCE);
const [cursor, setCursor] = useState("");
const [windowStates, setWindowStates] = useState(
/* @__PURE__ */ Object.create(null)
);
const [wallpaperFit, setWallpaperFit] = useState(DEFAULT_WALLPAPER_FIT);
const [wallpaperData, setWallpaperData] = useState(false);
const prependToStack = useCallback$1(
(id) => setStackOrder(
(currentStackOrder) => currentStackOrder[0] === id ? currentStackOrder : [id, ...currentStackOrder.filter((stackId) => stackId !== id)]
),
[]
);
const removeFromStack = useCallback$1(
(id) => setStackOrder(
(currentStackOrder) => currentStackOrder.filter((stackId) => stackId !== id)
),
[]
);
const setWallpaper = useCallback$1(
(newWallpaperData, fit) => {
if (fit) setWallpaperFit(fit);
setWallpaperData(newWallpaperData);
},
[]
);
const [haltSession, setHaltSession] = useState(false);
const loadingDebounceRef = useRef(0);
useEffect(() => {
if (!loadingDebounceRef.current && sessionLoaded && !haltSession) {
const updateSessionFile = () => {
};
if ("requestIdleCallback" in window && typeof window.requestIdleCallback === "function") {
requestIdleCallback(updateSessionFile);
}
}
}, [
clockSource,
cursor,
haltSession,
sessionLoaded,
themeName,
wallpaperFit,
wallpaperData,
windowStates
]);
return {
clockSource,
cursor,
previewID,
foregroundId,
prependToStack,
removeFromStack,
stackOrder,
themeName,
wallpaperFit,
wallpaper: wallpaperData,
windowStates,
sessionLoaded,
//---------------
// Functions:
setClockSource,
setCursor,
setPreviewID,
setForegroundId,
setHaltSession,
setThemeName,
setWallpaper,
setWindowStates
};
};
const { Provider: Provider$1, useContext } = contextFactory(useSessionContextState);
const ProcessLogic = () => {
const { processes } = useContext$5();
return /* @__PURE__ */ jsx(Fragment, { children: Object.entries(processes).map(
([id, { Component }]) => id && Component && /* @__PURE__ */ jsx(Component, {}, id)
) });
};
const ProcessesContainer = memo(ProcessLogic);
const colors = {
background: "#000",
fileEntry: {
background: "hsla(207, 30%, 72%, 25%)",
backgroundFocused: "hsla(207, 60%, 72%, 35%)",
backgroundFocusedHover: "hsla(207, 90%, 72%, 30%)",
border: "hsla(207, 30%, 72%, 30%)",
borderFocused: "hsla(207, 60%, 72%, 35%)",
borderFocusedHover: "hsla(207, 90%, 72%, 40%)",
text: "#FFF",
textShadow: `
0 0 1px rgba(0, 0, 0, 75%),
0 0 2px rgba(0, 0, 0, 50%),
0 1px 1px rgba(0, 0, 0, 75%),
0 1px 2px rgba(0, 0, 0, 50%),
0 2px 1px rgba(0, 0, 0, 75%),
0 2px 2px rgba(0, 0, 0, 50%)`
},
highlight: "hsla(207, 100%, 72%, 90%)",
progress: "hsla(113, 78%, 56%, 90%)",
progressBackground: "hsla(104, 22%, 45%, 70%)",
progressBarRgb: "rgb(6, 176, 37)",
selectionHighlight: "hsla(207, 100%, 45%, 90%)",
selectionHighlightBackground: "hsla(207, 100%, 45%, 30%)",
taskbar: {
active: "hsla(0, 0%, 20%, 70%)",
activeForeground: "hsla(0, 0%, 40%, 70%)",
background: "hsla(0, 0%, 10%, 70%)",
button: {
color: "#FFF"
},
foreground: "hsla(0, 0%, 35%, 70%)",
foregroundHover: "hsla(0, 0%, 45%, 70%)",
foregroundProgress: "hsla(104, 22%, 45%, 30%)",
hover: "hsla(0, 0%, 25%, 70%)",
peekBorder: "hsla(0, 0%, 50%, 50%)"
},
text: "rgba(255, 255, 255, 90%)",
titleBar: {
background: "rgb(0, 0, 0)",
backgroundHover: "rgb(26, 26, 26)",
backgroundInactive: "rgb(40, 40, 40)",
buttonInactive: "rgb(128, 128, 128)",
closeHover: "rgb(232, 17, 35)",
text: "rgb(255, 255, 255)",
textInactive: "rgb(170, 170, 170)"
},
window: {
background: "#808080",
outline: "hsla(0, 0%, 25%, 75%)",
outlineInactive: "hsla(0, 0%, 30%, 100%)",
shadow: "0 0 14px 0 rgba(0, 0, 0, 50%)",
shadowInactive: "0 0 10px 0 rgba(0, 0, 0, 45%)"
}
};
const formats = {
dateModified: {
hour: "numeric",
hour12: true,
minute: "2-digit"
}
};
const sizes = {
calendar: {
maxHeight: 357
},
clock: {
fontSize: "12px",
padding: 5
},
contextMenu: {
subMenuOffset: 3
},
fileEntry: {
fontSize: "12px",
iconSize: "48px",
maxIconTextDisplayWidth: 72,
maxListTextDisplayWidth: 102,
renamePadding: 5,
renameWidth: 75
},
fileExplorer: {
navBarHeight: "38px",
navInputHeight: 24,
statusBarHeight: "23px"
},
fileManager: {
columnGap: "1px",
gridEntryHeight: "70px",
gridEntryWidth: "74px",
padding: "5px 0",
rowGap: "28px"
},
search: {
headerHeight: 52,
inputHeight: 40,
maxHeight: 415,
size: 600
},
startMenu: {
maxHeight: 390,
sideBar: {
buttonHeight: 48,
expandedWidth: "228px",
iconSize: "16px",
width: 48
},
size: 320
},
taskbar: {
blur: "5px",
button: {
iconSize: "15px",
width: 36
},
entry: {
borderSize: "2px",
fontSize: "12px",
iconSize: "24px",
maxWidth: "160px",
peekControlsHeight: 36,
peekImage: {
height: 82,
margin: 8
}
},
panelBlur: "12px"
},
titleBar: {
buttonIconWidth: "10px",
buttonWidth: "45px",
fontSize: "12px",
height: 30,
iconMarginRight: "4px",
iconSize: "16px"
},
window: {
cascadeOffset: 26,
outline: "2px"
}
};
const win11Theme = {
name: "Win11",
systemFont: `-apple-system, BlinkMacSystemFont, "Segoe UI", "Roboto", "Oxygen",
"Ubuntu", "Cantarell", "Fira Sans", "Droid Sans", "Helvetica Neue",
sans-serif`,
colors,
formats,
sizes
};
const macOSTheme = {
...win11Theme
};
const themes = { win11: win11Theme, macOS: macOSTheme };
const motionFeatures = async () => (await import(
/* webpackMode: "eager" */
"./motionFeatures-fPgnC-rR.js"
)).default;
const StyledApp = ({ children }) => {
const { themeName } = useContext();
return /* @__PURE__ */ jsx(ThemeProvider, { theme: themes[themeName] || themes[DEFAULT_THEME], children: /* @__PURE__ */ jsx(LazyMotion, { features: motionFeatures, strict: true, children }) });
};
const StyledApp$1 = memo(StyledApp);
const StyledMainContainer = styled.div`
${defaultStyles}
width: 100%;
height: 100%;
display: flex;
flex-direction: column;
position: relative;
background-color: #000;
font-family: ${({ theme }) => theme.systemFont};
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
font-synthesis: none;
text-rendering: optimizeLegibility;
text-size-adjust: none;
inset: 0px;
overflow: hidden;
overscroll-behavior: none;
&,
&::before,
&::after {
border: 0px;
box-sizing: border-box;
font-variant-numeric: tabular-nums;
margin: 0px;
outline: 0px;
padding: 0px;
text-rendering: optimizelegibility;
}
`;
const Win11Layout = {
bottom: ["wintaskbar"]
};
const macOSLayout = {
bottom: ["macos-dock"]
};
const DefaultLayout = {};
const StyledWinTaskbar = styled.nav`
${defaultStyles}
backdrop-filter: saturate(3) blur(22px);
background-color: rgba(32, 32, 32, .75);
width: 100%;
height: ${WIN_TASKBAR_HEIGHT}px;
contain: size layout;
display: flex;
flex-direction: row;
justify-content: space-between;
z-index: 1003;
`;
const taskbarIcon = "data:image/png;base64,EP8Vmf0mAJCLx0iLTCQwSDPM6CklJQBIi1wkYEiLdCRoSIPEQF/DzEiJXCQIV0iD7CBIi/oz20iJGujFwf//SIkH6wSLXCQ4i8NIi1wkMEiDxCBfw8zMzEyL3EmJWxhJiXMgV0iD7EBIiwWZgy4ASDPESIlEJDBIi/JJg2PgAEiLSThIiwFJunAjUHCBNjmZTY1D4EiNFXVhKABIiwD/Ffz8JgCL+IXAdUlIi1wkKEiJXCQgSIsDSbpwsFUcOL/9nEiL1kiLy0iLQFD/Fc/8JgCL+EiF23QbSIsDSbpw2tcYMD/E/UiLy0iLQBD/Fa78JgCQi8dIi0wkMEgzzOg+JCUASItcJGBIi3QkaEiDxEBfw8zMTIvcSYlbGEmJcyBXSIPsQEiLBd2CLgBIM8RIiUQkMEiL8kmDY+AASItJOEiLAUm6cCNQcIE2OZlNjUPgSI0VuWAoAEiLAP8VQPwmAIv4hcB1SUiLXCQoSIlcJCBIiwNJunDT3To9ByDWSIvWSIvLSItAYP8VE/wmAIv4SIXbdBtIiwNJunDa1xgwP8T9SIvLSItAEP8V8vsmAJCLx0iLTCQwSDPM6IIjJQBIi1wkYEiLdCRoSIPEQF/DzMxMi9xJiVsYSYlzIFdIg+xASIsFIYIuAEgzxEiJRCQwi/JJg2PgAEiLSThIiwFJunAjUHCBNjmZTY1D4EiNFf5fKABIiwD/FYX7JgCL+IXAdUtIi1wkKEiJXCQgSIsDSbpwS1haRwfwrYvWSIvLSIuA2AAAAP8VVvsmAIv4SIXbdBtIiwNJunDa1xgwP8T9SIvLSItAEP8VNfsmAJCLx0iLTCQwSDPM6MUiJQBIi1wkYEiLdCRoSIPEQF/DzEyL3EmJWxhJiXMgV0iD7EBIiwVlgS4ASDPESIlEJDBIi/JJg2PgAEiLSThIiwFJunAjUHCBNjmZTY1D4EiNFUFfKABIiwD/Fcj6JgCL+IXAdUxIi1wkKEiJXCQgSIsDSbpw2916KIY5kkiL1kiLy0iLgIAAAAD/FZj6JgCL+EiF23QbSIsDSbpw2tcYMD/E/UiLy0iLQBD/FXf6JgCQi8dIi0wkMEgzzOgHIiUASItcJGBIi3QkaEiDxEBfw8zMzEyL3EmJWxhJiXMgV0iD7EBIiwWlgC4ASDPESIlEJDBIi/pJg2PgAEiLSThIiwFJunAjUHCBNjmZTY1D4EiNFYFeKABIiwD/FQj6JgCL8IXAdUxIi1wkKEiJXCQgSIsDSbpwMNdwTYYV8UiL10iLy0iLgGABAAD/Fdj5JgCL8EiF23QbSIsDSbpw2tcYMD/E/UiLy0iLQBD/Fbf5JgCQi8ZIi0wkMEgzzOhHISUASItcJGBIi3QkaEiDxEBfw8zMzEyL3EmJWxhJiXMgV0iD7EBIiwXlfy4ASDPESIlEJDBIi/JJg2PgAEiLSThIiwFJunAjUHCBNjmZTY1D4EiNFcFdKABIiwD/FUj5JgCL+IXAdUxIi1wkKEiJXCQgSIsDSbpwi1ISyL5Z9UiL1kiLy0iLgAABAAD/FRj5JgCL+EiF23QbSIsDSbpw2tcYMD/E/UiLy0iLQBD/Fff4JgCQi8dIi0wkMEgzzOiHICUASItcJGBIi3QkaEiDxEBfw8zMzEyL3EmJWxhJiXMgV0iD7EBIiwUlfy4ASDPESIlEJDCL8kmDY+AASItJOEiLAUm6cCNQcIE2OZlNjUPgSI0VAl0oAEiLAP8VifgmAIv4hcB1SEiLXCQoSIlcJCBIiwNJunDK2lhrFpioi9ZIi8tIi0B4/xVd+CYAi/hIhdt0G0iLA0m6cNrXGDA/xP1Ii8tIi0AQ/xU8+CYAkIvHSItMJDBIM8zozB8lAEiLXCRgSIt0JGhIg8RAX8NIiVwkEFVWV0iD7HAPKXQkYEiLBWx+LgBIM8RIiUQkWEmL6UmL8GZID27ySINkJFAASItJOEiLAUm6cCNQcIE2OZlMjUQkUEiNFf5cKABIiwD/FcX3JgCL+IXAdVxIi1wkUEiJXCQwSIsDDxAG8w9/RCRASbpwOFIwyo9ckEyLzUyNRCRAZkgPfvJIi8tIi0BA/xWF9yYAi/hIhdt0G0iLA0m6cNrXGDA/xP1Ii8tIi0AQ/xVk9yYAkIvHSItMJFhIM8zo9B4lAEiLnCSYAAAADyh0JGBIg8RwX15dw8zMzEyL3EmJWxhJiXMgV0iD7EBIiwWNfS4ASDPESIlEJDBIi/JJg2PgAEiLSThIiwFJunAjUHCBNjmZTY1D4EiNFWlbKABIiwD/FfD2JgCL+IXAdUxIi1wkKEiJXCQgSIsDSbpwqd1yyCcNmUiL1kiLy0iLgOgAAAD/FcD2JgCL+EiF23QbSIsDSbpw2tcYMD/E/UiLy0iLQBD/FZ/2JgCQi8dIi0wkMEgzzOgvHiUASItcJGBIi3QkaEiDxEBfw8zMzEiJXCQgVVZXSIPsQEiLBdF8LgBIM8RIiUQkMEmL6EiL8kiDZCQoAEiLSThIiwFJunAjUHCBNjmZTI1EJChIjRWoWigASIsA/xUv9iYAi/iFwHVPSItcJChIiVwkIEiLA0m6cBDbFp2eyM1Mi8VIi9ZIi8tIi4BYAQAA/xX89SYAi/hIhdt0G0iLA0m6cNrXGDA/xP1Ii8tIi0AQ/xXb9SYAkIvHSItMJDBIM8zoax0lAEiLXCR4SIPEQF9eXcPMzEyL3EmJWxhJiXMgV0iD7EBIiwUNfC4ASDPESIlEJDBIi/JJg2PgAEiLSThIiwFJunAjUHCBNjmZTY1D4EiNFelZKABIiwD/FXD1JgCL+IXAdUxIi1wkKEiJXCQgSIsDSbpweNwcZo7gz0iL1kiLy0iLgEABAAD/FUD1JgCL+EiF23QbSIsDSbpw2tcYMD/E/UiLy0iLQBD/FR/1JgCQi8dIi0wkMEgzzOivHCUASItcJGBIi3QkaEiDxEBfw8zMzEBTSIPsIEiLmVABAABIhdt0GkiLC0iLQQhJunCa1xQcPqn4SIvL/xXQ9CYASIlcJDBIg2QkMABIi8NIg8QgW8NIg+woSIsJSIXJdBhIiwFJunDa1xgwP8T9SItAEP8VmfQmAJBIg8Qow8zMzMzMzMzMzMzMcThTFJa/WdlIiVwkEEiJdCQgV0iD7CBIi/JIhcl1BDPb6yNIi1k4SIXbdBpIiwNJunCa1xQcPqn4SIvLSItACP8VQvQmAEiJXCQwSIs9VtwxAEiF/3QaSIsHSbpwmtcUHD6p+EiLz0iLQAj/FRf0JgBIiXwkQEyLxkiL10iLy+ikDwAAkEiF/3QbSIsHSbpw2tcYMD/E/UiLz0iLQBD/FeTzJgCQSIXbdBpIiwNJunDa1xgwP8T9SIvLSItAEP8VxPMmAEiLXCQ4SIt0JEhIg8QgX8PMzMzMzMzMzMzMzMxxa9F6JD6M5UBTSIPsIDPbSIsBSbpwOFMUlr9Z2UiLgAgBAAD/FX7zJgCQ6wSLXCQwi8NIg8QgW8PMzMzMzMzMcahTMMk34PpIiVwkIFVWV0iD7CBIhcl1BDPb6yNIi1k4SIXbdBpIiwNJunCa1xQcPqn4SIvLSItACP8VKPMmAEiJXCRISIs9PNsxAEiF/3QaSIsHSbpwmtcUHD6p+EiLz0iL";
const StyledFigure = styled.figure`
align-items: center;
display: flex;
justify-items: center;
justify-content: center;
position: relative;
picture {
width: 24px;
height: 24px;
}`;
const StartButtonIcon = memo(() => /* @__PURE__ */ jsx(StyledFigure, { children: /* @__PURE__ */ jsx(Icon$1, { alt: "Start", imgSize: 24, src: taskbarIcon }) }));
const StyledTaskbarButton = styled(Button)`
background-color: ${({ $active, $highlight, theme }) => $active && ($highlight ? theme.colors.taskbar.foreground : "hsla(0, 0%, 25%, 50%)")};
display: flex;
fill: ${({ theme }) => theme.colors.taskbar.button.color};
height: 100%;
place-content: center;
place-items: center;
&& {
width: ${({ theme }) => theme.sizes.taskbar.button.width}px;
}
svg {
height: ${({ theme }) => theme.sizes.taskbar.button.iconSize};
}
&:hover {
background-color: ${({ $active, theme }) => $active ? theme.colors.taskbar.foreground : theme.colors.taskbar.hover};
svg {
fill: ${({ $highlight, theme }) => $highlight ? theme.colors.highlight : void 0};
}
}
&:active {
background-color: hsla(0, 0%, 20%, 70%);
svg {
fill: ${({ $highlight }) => $highlight ? "hsla(207, 100%, 60%, 80%)" : void 0};
}
}
`;
const START_BUTTON_TITLE = "Start";
const useWindowsRef = () => {
const { windows } = useContext$4();
const windowsRef = useRef({});
useEffect(() => {
windowsRef.current = windows;
}, [windows]);
return windowsRef;
};
const useTaskbarContextMenu = (onStartButton = false) => {
const { contextMenu } = useContext$6();
const { minimize } = useContext$4();
const { stackOrder } = useContext();
const windowsRef = useWindowsRef();
const { fullscreenElement, toggleFullscreen } = useContext$9();
const open = (..._args) => {
};
return useMemo$1(
() => contextMenu == null ? void 0 : contextMenu(() => {
const processArray = Object.entries(windowsRef.current);
const allWindowsMinimized = processArray.length > 0 && !processArray.some(([, { minimized }]) => !minimized);
const toggleLabel = allWindowsMinimized ? "Show open windows" : "Show the desktop";
const menuItems = [
{
action: () => toggleShowDesktop(windowsRef.current, stackOrder, minimize),
label: onStartButton ? "Desktop" : toggleLabel
}
];
if (onStartButton) {
menuItems.unshift(
{
action: () => open("Terminal"),
label: "Terminal"
},
MENU_SEPERATOR,
{
action: () => open("FileExplorer"),
label: "File Explorer"
},
{
action: () => open("Run"),
label: "Run"
},
MENU_SEPERATOR
);
} else {
menuItems.unshift(
{
action: () => toggleFullscreen(),
label: fullscreenElement === document.documentElement ? "Exit full screen" : "Enter full screen"
},
MENU_SEPERATOR
);
}
return menuItems;
}),
[
contextMenu,
fullscreenElement,
minimize,
onStartButton,
open,
windowsRef,
stackOrder,
toggleFullscreen
]
);
};
const StartButton = ({
startMenuVisible,
toggleStartMenu
}) => {
const [preloaded, setPreloaded] = useState(false);
const { taskbarStartIcon } = useContext$2();
const initalizedPreload = useRef(false);
const preloadIcons = useCallback$1(async () => {
if (initalizedPreload.current) return;
initalizedPreload.current = true;
const supportsImageSrcSet = Object.prototype.hasOwnProperty.call(
HTMLLinkElement.prototype,
"imageSrcset"
);
const preloadedLinks = [
...document.querySelectorAll("link[rel=preload]")
];
const startMenuIcons = [];
startMenuIcons == null ? void 0 : startMenuIcons.forEach((icon) => {
const link = document.createElement("link");
link.as = "image";
link.fetchPriority = "high";
link.rel = "preload";
link.type = "image/webp";
if (isDynamicIcon(icon)) {
if (supportsImageSrcSet) {
link.imageSrcset = imageSrcs(icon, 48, ".webp");
} else {
const [href] = imageSrc(icon, 48, getDpi(), ".webp").split(" ");
link.href = href;
}
} else {
link.href = icon;
}
if (!preloadedLinks.some(
(preloadedLink) => {
var _a, _b;
return link.imageSrcset && ((_a = preloadedLink == null ? void 0 : preloadedLink.imageSrcset) == null ? void 0 : _a.endsWith(link.imageSrcset)) || link.href && ((_b = preloadedLink == null ? void 0 : preloadedLink.href) == null ? void 0 : _b.endsWith(link.href));
}
)) {
document.head.append(link);
}
});
setPreloaded(true);
}, []);
const onClick = useCallback$1(
async ({ ctrlKey, shiftKey }) => {
if (!preloaded) preloadIcons();
toggleStartMenu();
},
[preloadIcons, preloaded, toggleStartMenu]
);
const renderIcon = useMemo$1(() => {
if (!taskbarStartIcon) return /* @__PURE__ */ jsx(StartButtonIcon, {});
if (typeof taskbarStartIcon === "string") {
return /* @__PURE__ */ jsx(StyledFigure, { children: /* @__PURE__ */ jsx(Icon$1, { alt: "Start", imgSize: 24, src: taskbarStartIcon }) });
} else if (isValidElement(taskbarStartIcon)) {
return /* @__PURE__ */ jsx("div", { className: "icon", children: taskbarStartIcon });
} else if (typeof taskbarStartIcon === "function") {
const IconComponent = taskbarStartIcon;
return /* @__PURE__ */ jsx("div", { className: "icon", children: /* @__PURE__ */ jsx(IconComponent, {}) });
}
}, [taskbarStartIcon]);
return /* @__PURE__ */ jsx(
StyledTaskbarButton,
{
$active: startMenuVisible,
onClick,
onMouseOver: preloaded ? void 0 : preloadIcons,
$highlight: true,
"data-rd-type": "rd_start_button",
...DIV_BUTTON_PROPS,
...label(START_BUTTON_TITLE),
...useTaskbarContextMenu(true),
children: renderIcon
}
);
};
const StyledTaskbarEntries = styled.ol`
column-gap: 1px;
display: flex;
height: 100%;
margin: 0 3px;
padding: 0px;
position: relative;
overflow: hidden;
justify-items: center;
justify-content: center;
`;
function _typeof(o) {
"@babel/helpers - typeof";
return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(o2) {
return typeof o2;
} : function(o2) {
return o2 && "function" == typeof Symbol && o2.constructor === Symbol && o2 !== Symbol.prototype ? "symbol" : typeof o2;
}, _typeof(o);
}
function toPrimitive(t, r) {
if ("object" != _typeof(t) || !t) return t;
var e = t[Symbol.toPrimitive];
if (void 0 !== e) {
var i = e.call(t, r || "default");
if ("object" != _typeof(i)) return i;
throw new TypeError("@@toPrimitive must return a primitive value.");
}
return ("string" === r ? String : Number)(t);
}
function toPropertyKey(t) {
var i = toPrimitive(t, "string");
return "symbol" == _typeof(i) ? i : i + "";
}
function _defineProperty(e, r, t) {
return (r = toPropertyKey(r)) in e ? Object.defineProperty(e, r, {
value: t,
enumerable: true,
configurable: true,
writable: true
}) : e[r] = t, e;
}
function ownKeys(e, r) {
var t = Object.keys(e);
if (Object.getOwnPropertySymbols) {
var o = Object.getOwnPropertySymbols(e);
r && (o = o.filter(function(r2) {
return Object.getOwnPropertyDescriptor(e, r2).enumerable;
})), t.push.apply(t, o);
}
return t;
}
function _objectSpread2(e) {
for (var r = 1; r < arguments.length; r++) {
var t = null != arguments[r] ? arguments[r] : {};
r % 2 ? ownKeys(Object(t), true).forEach(function(r2) {
_defineProperty(e, r2, t[r2]);
}) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function(r2) {
Object.defineProperty(e, r2, Object.getOwnPropertyDescriptor(t, r2));
});
}
return e;
}
function formatProdErrorMessage(code) {
return "Minified Redux error #" + code + "; visit https://redux.js.org/Errors?code=" + code + " for the full message or use the non-minified dev environment for full errors. ";
}
var $$observable = function() {
return typeof Symbol === "function" && Symbol.observable || "@@observable";
}();
var randomString = function randomString2() {
return Math.random().toString(36).substring(7).split("").join(".");
};
var ActionTypes = {
INIT: "@@redux/INIT" + randomString(),
REPLACE: "@@redux/REPLACE" + randomString(),
PROBE_UNKNOWN_ACTION: function PROBE_UNKNOWN_ACTION() {
return "@@redux/PROBE_UNKNOWN_ACTION" + randomString();
}
};
function isPlainObject$1(obj) {
if (typeof obj !== "object" || obj === null) return false;
var proto = obj;
while (Object.getPrototypeOf(proto) !== null) {
proto = Object.getPrototypeOf(proto);
}
return Object.getPrototypeOf(obj) === proto;
}
function miniKindOf(val) {
if (val === void 0) return "undefined";
if (val === null) return "null";
var type = typeof val;
switch (type) {
case "boolean":
case "string":
case "number":
case "symbol":
case "function": {
return type;
}
}
if (Array.isArray(val)) return "array";
if (isDate(val)) return "date";
if (isError(val)) return "error";
var constructorName = ctorName(val);
switch (constructorName) {
case "Symbol":
case "Promise":
case "WeakMap":
case "WeakSet":
case "Map":
case "Set":
return constructorName;
}
return type.slice(8, -1).toLowerCase().replace(/\s/g, "");
}
function ctorName(val) {
return typeof val.constructor === "function" ? val.constructor.name : null;
}
function isError(val) {
return val instanceof Error || typeof val.message === "string" && val.constructor && typeof val.constructor.stackTraceLimit === "number";
}
function isDate(val) {
if (val instanceof Date) return true;
return typeof val.toDateString === "function" && typeof val.getDate === "function" && typeof val.setDate === "function";
}
function kindOf(val) {
var typeOfVal = typeof val;
if (process.env.NODE_ENV !== "production") {
typeOfVal = miniKindOf(val);
}
return typeOfVal;
}
function createStore$1(reducer2, preloadedState, enhancer) {
var _ref2;
if (typeof preloadedState === "function" && typeof enhancer === "function" || typeof enhancer === "function" && typeof arguments[3] === "function") {
throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(0) : "It looks like you are passing several store enhancers to createStore(). This is not supported. Instead, compose them together to a single function. See https://redux.js.org/tutorials/fundamentals/part-4-store#creating-a-store-with-enhancers for an example.");
}
if (typeof preloadedState === "function" && typeof enhancer === "undefined") {
enhancer = preloadedState;
preloadedState = void 0;
}
if (typeof enhancer !== "undefined") {
if (typeof enhancer !== "function") {
throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(1) : "Expected the enhancer to be a function. Instead, received: '" + kindOf(enhancer) + "'");
}
return enhancer(createStore$1)(reducer2, preloadedState);
}
if (typeof reducer2 !== "function") {
throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(2) : "Expected the root reducer to be a function. Instead, received: '" + kindOf(reducer2) + "'");
}
var currentReducer = reducer2;
var currentState = preloadedState;
var currentListeners = [];
var nextListeners = currentListeners;
var isDispatching = false;
function ensureCanMutateNextListeners() {
if (nextListeners === currentListeners) {
nextListeners = currentListeners.slice();
}
}
function getState() {
if (isDispatching) {
throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(3) : "You may not call store.getState() while the reducer is executing. The reducer has already received the state as an argument. Pass it down from the top reducer instead of reading it from the store.");
}
return currentState;
}
function subscribe(listener) {
if (typeof listener !== "function") {
throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(4) : "Expected the listener to be a function. Instead, received: '" + kindOf(listener) + "'");
}
if (isDispatching) {
throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(5) : "You may not call store.subscribe() while the reducer is executing. If you would like to be notified after the store has been updated, subscribe from a component and invoke store.getState() in the callback to access the latest state. See https://redux.js.org/api/store#subscribelistener for more details.");
}
var isSubscribed = true;
ensureCanMutateNextListeners();
nextListeners.push(listener);
return function unsubscribe() {
if (!isSubscribed) {
return;
}
if (isDispatching) {
throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(6) : "You may not unsubscribe from a store listener while the reducer is executing. See https://redux.js.org/api/store#subscribelistener for more details.");
}
isSubscribed = false;
ensureCanMutateNextListeners();
var index = nextListeners.indexOf(listener);
nextListeners.splice(index, 1);
currentListeners = null;
};
}
function dispatch(action) {
if (!isPlainObject$1(action)) {
throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(7) : "Actions must be plain objects. Instead, the actual type was: '" + kindOf(action) + "'. You may need to add middleware to your store setup to handle dispatching other values, such as 'redux-thunk' to handle dispatching functions. See https://redux.js.org/tutorials/fundamentals/part-4-store#middleware and https://redux.js.org/tutorials/fundamentals/part-6-async-logic#using-the-redux-thunk-middleware for examples.");
}
if (typeof action.type === "undefined") {
throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(8) : 'Actions may not have an undefined "type" property. You may have misspelled an action type string constant.');
}
if (isDispatching) {
throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(9) : "Reducers may not dispatch actions.");
}
try {
isDispatching = true;
currentState = currentReducer(currentState, action);
} finally {
isDispatching = false;
}
var listeners = currentListeners = nextListeners;
for (var i = 0; i < listeners.length; i++) {
var listener = listeners[i];
listener();
}
return action;
}
function replaceReducer(nextReducer) {
if (typeof nextReducer !== "function") {
throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(10) : "Expected the nextReducer to be a function. Instead, received: '" + kindOf(nextReducer));
}
currentReducer = nextReducer;
dispatch({
type: ActionTypes.REPLACE
});
}
function observable() {
var _ref;
var outerSubscribe = subscribe;
return _ref = {
/**
* The minimal observable subscription method.
* @param {Object} observer Any object that can be used as an observer.
* The observer object should have a `next` method.
* @returns {subscription} An object with an `unsubscribe` method that can
* be used to unsubscribe the observable from the store, and prevent further
* emission of values from the observable.
*/
subscribe: function subscribe2(observer) {
if (typeof observer !== "object" || observer === null) {
throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(11) : "Expected the observer to be an object. Instead, received: '" + kindOf(observer) + "'");
}
function observeState() {
if (observer.next) {
observer.next(getState());
}
}
observeState();
var unsubscribe = outerSubscribe(observeState);
return {
unsubscribe
};
}
}, _ref[$$observable] = function() {
return this;
}, _ref;
}
dispatch({
type: ActionTypes.INIT
});
return _ref2 = {
dispatch,
subscribe,
getState,
replaceReducer
}, _ref2[$$observable] = observable, _ref2;
}
function bindActionCreator(actionCreator, dispatch) {
return function() {
return dispatch(actionCreator.apply(this, arguments));
};
}
function bindActionCreators$1(actionCreators, dispatch) {
if (typeof actionCreators === "function") {
return bindActionCreator(actionCreators, dispatch);
}
if (typeof actionCreators !== "object" || actionCreators === null) {
throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(16) : "bindActionCreators expected an object or a function, but instead received: '" + kindOf(actionCreators) + `'. Did you write "import ActionCreators from" instead of "import * as ActionCreators from"?`);
}
var boundActionCreators = {};
for (var key in actionCreators) {
var actionCreator = actionCreators[key];
if (typeof actionCreator === "function") {
boundActionCreators[key] = bindActionCreator(actionCreator, dispatch);
}
}
return boundActionCreators;
}
function compose() {
for (var _len = arguments.length, funcs = new Array(_len), _key = 0; _key < _len; _key++) {
funcs[_key] = arguments[_key];
}
if (funcs.length === 0) {
return function(arg) {
return arg;
};
}
if (funcs.length === 1) {
return funcs[0];
}
return funcs.reduce(function(a, b) {
return function() {
return a(b.apply(void 0, arguments));
};
});
}
function applyMiddleware() {
for (var _len = arguments.length, middlewares = new Array(_len), _key = 0; _key < _len; _key++) {
middlewares[_key] = arguments[_key];
}
return function(createStore2) {
return function() {
var store = createStore2.apply(void 0, arguments);
var _dispatch = function dispatch() {
throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(15) : "Dispatching while constructing your middleware is not allowed. Other middleware would not be applied to this dispatch.");
};
var middlewareAPI = {
getState: store.getState,
dispatch: function dispatch() {
return _dispatch.apply(void 0, arguments);
}
};
var chain = middlewares.map(function(middleware) {
return middleware(middlewareAPI);
});
_dispatch = compose.apply(void 0, chain)(store.dispatch);
return _objectSpread2(_objectSpread2({}, store), {}, {
dispatch: _dispatch
});
};
};
}
var shim = { exports: {} };
var useSyncExternalStoreShim_production = {};
/**
* @license React
* use-sync-external-store-shim.production.js
*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
var hasRequiredUseSyncExternalStoreShim_production;
function requireUseSyncExternalStoreShim_production() {
if (hasRequiredUseSyncExternalStoreShim_production) return useSyncExternalStoreShim_production;
hasRequiredUseSyncExternalStoreShim_production = 1;
var React2 = React__default;
function is2(x, y) {
return x === y && (0 !== x || 1 / x === 1 / y) || x !== x && y !== y;
}
var objectIs = "function" === typeof Object.is ? Object.is : is2, useState2 = React2.useState, useEffect2 = React2.useEffect, useLayoutEffect2 = React2.useLayoutEffect, useDebugValue = React2.useDebugValue;
function useSyncExternalStore$2(subscribe, getSnapshot) {
var value = getSnapshot(), _useState = useState2({ inst: { value, getSnapshot } }), inst = _useState[0].inst, forceUpdate = _useState[1];
useLayoutEffect2(
function() {
inst.value = value;
inst.getSnapshot = getSnapshot;
checkIfSnapshotChanged(inst) && forceUpdate({ inst });
},
[subscribe, value, getSnapshot]
);
useEffect2(
function() {
checkIfSnapshotChanged(inst) && forceUpdate({ inst });
return subscribe(function() {
checkIfSnapshotChanged(inst) && forceUpdate({ inst });
});
},
[subscribe]
);
useDebugValue(value);
return value;
}
function checkIfSnapshotChanged(inst) {
var latestGetSnapshot = inst.getSnapshot;
inst = inst.value;
try {
var nextValue = latestGetSnapshot();
return !objectIs(inst, nextValue);
} catch (error2) {
return true;
}
}
function useSyncExternalStore$1(subscribe, getSnapshot) {
return getSnapshot();
}
var shim2 = "undefined" === typeof window || "undefined" === typeof window.document || "undefined" === typeof window.document.createElement ? useSyncExternalStore$1 : useSyncExternalStore$2;
useSyncExternalStoreShim_production.useSyncExternalStore = void 0 !== React2.useSyncExternalStore ? React2.useSyncExternalStore : shim2;
return useSyncExternalStoreShim_production;
}
var useSyncExternalStoreShim_development = {};
/**
* @license React
* use-sync-external-store-shim.development.js
*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
var hasRequiredUseSyncExternalStoreShim_development;
function requireUseSyncExternalStoreShim_development() {
if (hasRequiredUseSyncExternalStoreShim_development) return useSyncExternalStoreShim_development;
hasRequiredUseSyncExternalStoreShim_development = 1;
"production" !== process.env.NODE_ENV && function() {
function is2(x, y) {
return x === y && (0 !== x || 1 / x === 1 / y) || x !== x && y !== y;
}
function useSyncExternalStore$2(subscribe, getSnapshot) {
didWarnOld18Alpha || void 0 === React2.startTransition || (didWarnOld18Alpha = true, console.error(
"You are using an outdated, pre-release alpha of React 18 that does not support useSyncExternalStore. The use-sync-external-store shim will not work correctly. Upgrade to a newer pre-release."
));
var value = getSnapshot();
if (!didWarnUncachedGetSnapshot) {
var cachedValue = getSnapshot();
objectIs(value, cachedValue) || (console.error(
"The result of getSnapshot should be cached to avoid an infinite loop"
), didWarnUncachedGetSnapshot = true);
}
cachedValue = useState2({
inst: { value, getSnapshot }
});
var inst = cachedValue[0].inst, forceUpdate = cachedValue[1];
useLayoutEffect2(
function() {
inst.value = value;
inst.getSnapshot = getSnapshot;
checkIfSnapshotChanged(inst) && forceUpdate({ inst });
},
[subscribe, value, getSnapshot]
);
useEffect2(
function() {
checkIfSnapshotChanged(inst) && forceUpdate({ inst });
return subscribe(function() {
checkIfSnapshotChanged(inst) && forceUpdate({ inst });
});
},
[subscribe]
);
useDebugValue(value);
return value;
}
function checkIfSnapshotChanged(inst) {
var latestGetSnapshot = inst.getSnapshot;
inst = inst.value;
try {
var nextValue = latestGetSnapshot();
return !objectIs(inst, nextValue);
} catch (error2) {
return true;
}
}
function useSyncExternalStore$1(subscribe, getSnapshot) {
return getSnapshot();
}
"undefined" !== typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ && "function" === typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart && __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(Error());
var React2 = React__default, objectIs = "function" === typeof Object.is ? Object.is : is2, useState2 = React2.useState, useEffect2 = React2.useEffect, useLayoutEffect2 = React2.useLayoutEffect, useDebugValue = React2.useDebugValue, didWarnOld18Alpha = false, didWarnUncachedGetSnapshot = false, shim2 = "undefined" === typeof window || "undefined" === typeof window.document || "undefined" === typeof window.document.createElement ? useSyncExternalStore$1 : useSyncExternalStore$2;
useSyncExternalStoreShim_development.useSyncExternalStore = void 0 !== React2.useSyncExternalStore ? React2.useSyncExternalStore : shim2;
"undefined" !== typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ && "function" === typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop && __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(Error());
}();
return useSyncExternalStoreShim_development;
}
if (process.env.NODE_ENV === "production") {
shim.exports = requireUseSyncExternalStoreShim_production();
} else {
shim.exports = requireUseSyncExternalStoreShim_development();
}
var shimExports = shim.exports;
var withSelector_production = {};
/**
* @license React
* use-sync-external-store-shim/with-selector.production.js
*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
var hasRequiredWithSelector_production;
function requireWithSelector_production() {
if (hasRequiredWithSelector_production) return withSelector_production;
hasRequiredWithSelector_production = 1;
var React2 = React__default, shim2 = shimExports;
function is2(x, y) {
return x === y && (0 !== x || 1 / x === 1 / y) || x !== x && y !== y;
}
var objectIs = "function" === typeof Object.is ? Object.is : is2, useSyncExternalStore2 = shim2.useSyncExternalStore, useRef2 = React2.useRef, useEffect2 = React2.useEffect, useMemo2 = React2.useMemo, useDebugValue = React2.useDebugValue;
withSelector_production.useSyncExternalStoreWithSelector = function(subscribe, getSnapshot, getServerSnapshot, selector, isEqual2) {
var instRef = useRef2(null);
if (null === instRef.current) {
var inst = { hasValue: false, value: null };
instRef.current = inst;
} else inst = instRef.current;
instRef = useMemo2(
function() {
function memoizedSelector(nextSnapshot) {
if (!hasMemo) {
hasMemo = true;
memoizedSnapshot = nextSnapshot;
nextSnapshot = selector(nextSnapshot);
if (void 0 !== isEqual2 && inst.hasValue) {
var currentSelection = inst.value;
if (isEqual2(currentSelection, nextSnapshot))
return memoizedSelection = currentSelection;
}
return memoizedSelection = nextSnapshot;
}
currentSelection = memoizedSelection;
if (objectIs(memoizedSnapshot, nextSnapshot)) return currentSelection;
var nextSelection = selector(nextSnapshot);
if (void 0 !== isEqual2 && isEqual2(currentSelection, nextSelection))
return memoizedSnapshot = nextSnapshot, currentSelection;
memoizedSnapshot = nextSnapshot;
return memoizedSelection = nextSelection;
}
var hasMemo = false, memoizedSnapshot, memoizedSelection, maybeGetServerSnapshot = void 0 === getServerSnapshot ? null : getServerSnapshot;
return [
function() {
return memoizedSelector(getSnapshot());
},
null === maybeGetServerSnapshot ? void 0 : function() {
return memoizedSelector(maybeGetServerSnapshot());
}
];
},
[getSnapshot, getServerSnapshot, selector, isEqual2]
);
var value = useSyncExternalStore2(subscribe, instRef[0], instRef[1]);
useEffect2(
function() {
inst.hasValue = true;
inst.value = value;
},
[value]
);
useDebugValue(value);
return value;
};
return withSelector_production;
}
var withSelector_development = {};
/**
* @license React
* use-sync-external-store-shim/with-selector.development.js
*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
var hasRequiredWithSelector_development;
function requireWithSelector_development() {
if (hasRequiredWithSelector_development) return withSelector_development;
hasRequiredWithSelector_development = 1;
"production" !== process.env.NODE_ENV && function() {
function is2(x, y) {
return x === y && (0 !== x || 1 / x === 1 / y) || x !== x && y !== y;
}
"undefined" !== typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ && "function" === typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart && __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(Error());
var React2 = React__default, shim2 = shimExports, objectIs = "function" === typeof Object.is ? Object.is : is2, useSyncExternalStore2 = shim2.useSyncExternalStore, useRef2 = React2.useRef, useEffect2 = React2.useEffect, useMemo2 = React2.useMemo, useDebugValue = React2.useDebugValue;
withSelector_development.useSyncExternalStoreWithSelector = function(subscribe, getSnapshot, getServerSnapshot, selector, isEqual2) {
var instRef = useRef2(null);
if (null === instRef.current) {
var inst = { hasValue: false, value: null };
instRef.current = inst;
} else inst = instRef.current;
instRef = useMemo2(
function() {
function memoizedSelector(nextSnapshot) {
if (!hasMemo) {
hasMemo = true;
memoizedSnapshot = nextSnapshot;
nextSnapshot = selector(nextSnapshot);
if (void 0 !== isEqual2 && inst.hasValue) {
var currentSelection = inst.value;
if (isEqual2(currentSelection, nextSnapshot))
return memoizedSelection = currentSelection;
}
return memoizedSelection = nextSnapshot;
}
currentSelection = memoizedSelection;
if (objectIs(memoizedSnapshot, nextSnapshot))
return currentSelection;
var nextSelection = selector(nextSnapshot);
if (void 0 !== isEqual2 && isEqual2(currentSelection, nextSelection))
return memoizedSnapshot = nextSnapshot, currentSelection;
memoizedSnapshot = nextSnapshot;
return memoizedSelection = nextSelection;
}
var hasMemo = false, memoizedSnapshot, memoizedSelection, maybeGetServerSnapshot = void 0 === getServerSnapshot ? null : getServerSnapshot;
return [
function() {
return memoizedSelector(getSnapshot());
},
null === maybeGetServerSnapshot ? void 0 : function() {
return memoizedSelector(maybeGetServerSnapshot());
}
];
},
[getSnapshot, getServerSnapshot, selector, isEqual2]
);
var value = useSyncExternalStore2(subscribe, instRef[0], instRef[1]);
useEffect2(
function() {
inst.hasValue = true;
inst.value = value;
},
[value]
);
useDebugValue(value);
return value;
};
"undefined" !== typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ && "function" === typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop && __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(Error());
}();
return withSelector_development;
}
if (process.env.NODE_ENV === "production") {
requireWithSelector_production();
} else {
requireWithSelector_development();
}
function defaultNoopBatch(callback) {
callback();
}
let batch = defaultNoopBatch;
const setBatch = (newBatch) => batch = newBatch;
const getBatch = () => batch;
const ContextKey = Symbol.for(`react-redux-context`);
const gT = typeof globalThis !== "undefined" ? globalThis : (
/* fall back to a per-module scope (pre-8.1 behaviour) if `globalThis` is not available */
{}
);
function getContext() {
var _gT$ContextKey;
if (!React.createContext) return {};
const contextMap = (_gT$ContextKey = gT[ContextKey]) != null ? _gT$ContextKey : gT[ContextKey] = /* @__PURE__ */ new Map();
let realContext = contextMap.get(React.createContext);
if (!realContext) {
realContext = React.createContext(null);
if (process.env.NODE_ENV !== "production") {
realContext.displayName = "ReactRedux";
}
contextMap.set(React.createContext, realContext);
}
return realContext;
}
const ReactReduxContext = /* @__PURE__ */ getContext();
const notInitialized = () => {
throw new Error("uSES not initialized!");
};
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);
}
function _objectWithoutPropertiesLoose(r, e) {
if (null == r) return {};
var t = {};
for (var n in r) if ({}.hasOwnProperty.call(r, n)) {
if (-1 !== e.indexOf(n)) continue;
t[n] = r[n];
}
return t;
}
var reactIs$2 = { exports: {} };
var reactIs_production_min$1 = {};
/** @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 hasRequiredReactIs_production_min$1;
function requireReactIs_production_min$1() {
if (hasRequiredReactIs_production_min$1) return reactIs_production_min$1;
hasRequiredReactIs_production_min$1 = 1;
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, m2 = 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 m2:
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) === m2;
}
reactIs_production_min$1.AsyncMode = l;
reactIs_production_min$1.ConcurrentMode = m2;
reactIs_production_min$1.ContextConsumer = k;
reactIs_production_min$1.ContextProvider = h;
reactIs_production_min$1.Element = c;
reactIs_production_min$1.ForwardRef = n;
reactIs_production_min$1.Fragment = e;
reactIs_production_min$1.Lazy = t;
reactIs_production_min$1.Memo = r;
reactIs_production_min$1.Portal = d;
reactIs_production_min$1.Profiler = g;
reactIs_production_min$1.StrictMode = f;
reactIs_production_min$1.Suspense = p;
reactIs_production_min$1.isAsyncMode = function(a) {
return A(a) || z(a) === l;
};
reactIs_production_min$1.isConcurrentMode = A;
reactIs_production_min$1.isContextConsumer = function(a) {
return z(a) === k;
};
reactIs_production_min$1.isContextProvider = function(a) {
return z(a) === h;
};
reactIs_production_min$1.isElement = function(a) {
return "object" === typeof a && null !== a && a.$$typeof === c;
};
reactIs_production_min$1.isForwardRef = function(a) {
return z(a) === n;
};
reactIs_production_min$1.isFragment = function(a) {
return z(a) === e;
};
reactIs_production_min$1.isLazy = function(a) {
return z(a) === t;
};
reactIs_production_min$1.isMemo = function(a) {
return z(a) === r;
};
reactIs_production_min$1.isPortal = function(a) {
return z(a) === d;
};
reactIs_production_min$1.isProfiler = function(a) {
return z(a) === g;
};
reactIs_production_min$1.isStrictMode = function(a) {
return z(a) === f;
};
reactIs_production_min$1.isSuspense = function(a) {
return z(a) === p;
};
reactIs_production_min$1.isValidElementType = function(a) {
return "string" === typeof a || "function" === typeof a || a === e || a === m2 || 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);
};
reactIs_production_min$1.typeOf = z;
return reactIs_production_min$1;
}
var reactIs_development$1 = {};
/** @license React v16.13.1
* react-is.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.
*/
var hasRequiredReactIs_development$1;
function requireReactIs_development$1() {
if (hasRequiredReactIs_development$1) return reactIs_development$1;
hasRequiredReactIs_development$1 = 1;
if (process.env.NODE_ENV !== "production") {
(function() {
var hasSymbol = typeof Symbol === "function" && Symbol.for;
var REACT_ELEMENT_TYPE = hasSymbol ? Symbol.for("react.element") : 60103;
var REACT_PORTAL_TYPE = hasSymbol ? Symbol.for("react.portal") : 60106;
var REACT_FRAGMENT_TYPE = hasSymbol ? Symbol.for("react.fragment") : 60107;
var REACT_STRICT_MODE_TYPE = hasSymbol ? Symbol.for("react.strict_mode") : 60108;
var REACT_PROFILER_TYPE = hasSymbol ? Symbol.for("react.profiler") : 60114;
var REACT_PROVIDER_TYPE = hasSymbol ? Symbol.for("react.provider") : 60109;
var REACT_CONTEXT_TYPE = hasSymbol ? Symbol.for("react.context") : 60110;
var REACT_ASYNC_MODE_TYPE = hasSymbol ? Symbol.for("react.async_mode") : 60111;
var REACT_CONCURRENT_MODE_TYPE = hasSymbol ? Symbol.for("react.concurrent_mode") : 60111;
var REACT_FORWARD_REF_TYPE = hasSymbol ? Symbol.for("react.forward_ref") : 60112;
var REACT_SUSPENSE_TYPE = hasSymbol ? Symbol.for("react.suspense") : 60113;
var REACT_SUSPENSE_LIST_TYPE = hasSymbol ? Symbol.for("react.suspense_list") : 60120;
var REACT_MEMO_TYPE = hasSymbol ? Symbol.for("react.memo") : 60115;
var REACT_LAZY_TYPE = hasSymbol ? Symbol.for("react.lazy") : 60116;
var REACT_BLOCK_TYPE = hasSymbol ? Symbol.for("react.block") : 60121;
var REACT_FUNDAMENTAL_TYPE = hasSymbol ? Symbol.for("react.fundamental") : 60117;
var REACT_RESPONDER_TYPE = hasSymbol ? Symbol.for("react.responder") : 60118;
var REACT_SCOPE_TYPE = hasSymbol ? Symbol.for("react.scope") : 60119;
function isValidElementType(type) {
return typeof type === "string" || typeof type === "function" || // Note: its typeof might be other than 'symbol' or 'number' if it's a polyfill.
type === REACT_FRAGMENT_TYPE || type === REACT_CONCURRENT_MODE_TYPE || type === REACT_PROFILER_TYPE || type === REACT_STRICT_MODE_TYPE || type === REACT_SUSPENSE_TYPE || type === REACT_SUSPENSE_LIST_TYPE || typeof type === "object" && type !== null && (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 || type.$$typeof === REACT_FUNDAMENTAL_TYPE || type.$$typeof === REACT_RESPONDER_TYPE || type.$$typeof === REACT_SCOPE_TYPE || type.$$typeof === REACT_BLOCK_TYPE);
}
function typeOf(object) {
if (typeof object === "object" && object !== null) {
var $$typeof = object.$$typeof;
switch ($$typeof) {
case REACT_ELEMENT_TYPE:
var type = object.type;
switch (type) {
case REACT_ASYNC_MODE_TYPE:
case REACT_CONCURRENT_MODE_TYPE:
case REACT_FRAGMENT_TYPE:
case REACT_PROFILER_TYPE:
case REACT_STRICT_MODE_TYPE:
case REACT_SUSPENSE_TYPE:
return type;
default:
var $$typeofType = type && type.$$typeof;
switch ($$typeofType) {
case REACT_CONTEXT_TYPE:
case REACT_FORWARD_REF_TYPE:
case REACT_LAZY_TYPE:
case REACT_MEMO_TYPE:
case REACT_PROVIDER_TYPE:
return $$typeofType;
default:
return $$typeof;
}
}
case REACT_PORTAL_TYPE:
return $$typeof;
}
}
return void 0;
}
var AsyncMode = REACT_ASYNC_MODE_TYPE;
var ConcurrentMode = REACT_CONCURRENT_MODE_TYPE;
var ContextConsumer = REACT_CONTEXT_TYPE;
var ContextProvider = REACT_PROVIDER_TYPE;
var Element2 = REACT_ELEMENT_TYPE;
var ForwardRef = REACT_FORWARD_REF_TYPE;
var Fragment2 = REACT_FRAGMENT_TYPE;
var Lazy = REACT_LAZY_TYPE;
var Memo = REACT_MEMO_TYPE;
var Portal = REACT_PORTAL_TYPE;
var Profiler = REACT_PROFILER_TYPE;
var StrictMode = REACT_STRICT_MODE_TYPE;
var Suspense = REACT_SUSPENSE_TYPE;
var hasWarnedAboutDeprecatedIsAsyncMode = false;
function isAsyncMode(object) {
{
if (!hasWarnedAboutDeprecatedIsAsyncMode) {
hasWarnedAboutDeprecatedIsAsyncMode = true;
console["warn"]("The ReactIs.isAsyncMode() alias has been deprecated, and will be removed in React 17+. Update your code to use ReactIs.isConcurrentMode() instead. It has the exact same API.");
}
}
return isConcurrentMode(object) || typeOf(object) === REACT_ASYNC_MODE_TYPE;
}
function isConcurrentMode(object) {
return typeOf(object) === REACT_CONCURRENT_MODE_TYPE;
}
function isContextConsumer(object) {
return typeOf(object) === REACT_CONTEXT_TYPE;
}
function isContextProvider(object) {
return typeOf(object) === REACT_PROVIDER_TYPE;
}
function isElement2(object) {
return typeof object === "object" && object !== null && object.$$typeof === REACT_ELEMENT_TYPE;
}
function isForwardRef(object) {
return typeOf(object) === REACT_FORWARD_REF_TYPE;
}
function isFragment(object) {
return typeOf(object) === REACT_FRAGMENT_TYPE;
}
function isLazy(object) {
return typeOf(object) === REACT_LAZY_TYPE;
}
function isMemo(object) {
return typeOf(object) === REACT_MEMO_TYPE;
}
function isPortal(object) {
return typeOf(object) === REACT_PORTAL_TYPE;
}
function isProfiler(object) {
return typeOf(object) === REACT_PROFILER_TYPE;
}
function isStrictMode(object) {
return typeOf(object) === REACT_STRICT_MODE_TYPE;
}
function isSuspense(object) {
return typeOf(object) === REACT_SUSPENSE_TYPE;
}
reactIs_development$1.AsyncMode = AsyncMode;
reactIs_development$1.ConcurrentMode = ConcurrentMode;
reactIs_development$1.ContextConsumer = ContextConsumer;
reactIs_development$1.ContextProvider = ContextProvider;
reactIs_development$1.Element = Element2;
reactIs_development$1.ForwardRef = ForwardRef;
reactIs_development$1.Fragment = Fragment2;
reactIs_development$1.Lazy = Lazy;
reactIs_development$1.Memo = Memo;
reactIs_development$1.Portal = Portal;
reactIs_development$1.Profiler = Profiler;
reactIs_development$1.StrictMode = StrictMode;
reactIs_development$1.Suspense = Suspense;
reactIs_development$1.isAsyncMode = isAsyncMode;
reactIs_development$1.isConcurrentMode = isConcurrentMode;
reactIs_development$1.isContextConsumer = isContextConsumer;
reactIs_development$1.isContextProvider = isContextProvider;
reactIs_development$1.isElement = isElement2;
reactIs_development$1.isForwardRef = isForwardRef;
reactIs_development$1.isFragment = isFragment;
reactIs_development$1.isLazy = isLazy;
reactIs_development$1.isMemo = isMemo;
reactIs_development$1.isPortal = isPortal;
reactIs_development$1.isProfiler = isProfiler;
reactIs_development$1.isStrictMode = isStrictMode;
reactIs_development$1.isSuspense = isSuspense;
reactIs_development$1.isValidElementType = isValidElementType;
reactIs_development$1.typeOf = typeOf;
})();
}
return reactIs_development$1;
}
if (process.env.NODE_ENV === "production") {
reactIs$2.exports = requireReactIs_production_min$1();
} else {
reactIs$2.exports = requireReactIs_development$1();
}
var reactIsExports$1 = reactIs$2.exports;
var reactIs$1 = reactIsExports$1;
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$1.ForwardRef] = FORWARD_REF_STATICS;
TYPE_STATICS[reactIs$1.Memo] = MEMO_STATICS;
function getStatics(component) {
if (reactIs$1.isMemo(component)) {
return MEMO_STATICS;
}
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") {
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 {
defineProperty(targetComponent, key, descriptor);
} catch (e) {
}
}
}
}
return targetComponent;
}
var hoistNonReactStatics_cjs = hoistNonReactStatics;
const hoistStatics = /* @__PURE__ */ getDefaultExportFromCjs(hoistNonReactStatics_cjs);
var reactIs = { exports: {} };
var reactIs_production_min = {};
/**
* @license React
* 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 hasRequiredReactIs_production_min;
function requireReactIs_production_min() {
if (hasRequiredReactIs_production_min) return reactIs_production_min;
hasRequiredReactIs_production_min = 1;
var b = Symbol.for("react.element"), c = Symbol.for("react.portal"), d = Symbol.for("react.fragment"), e = Symbol.for("react.strict_mode"), f = Symbol.for("react.profiler"), g = Symbol.for("react.provider"), h = Symbol.for("react.context"), k = Symbol.for("react.server_context"), l = Symbol.for("react.forward_ref"), m2 = Symbol.for("react.suspense"), n = Symbol.for("react.suspense_list"), p = Symbol.for("react.memo"), q = Symbol.for("react.lazy"), t = Symbol.for("react.offscreen"), u;
u = Symbol.for("react.module.reference");
function v(a) {
if ("object" === typeof a && null !== a) {
var r = a.$$typeof;
switch (r) {
case b:
switch (a = a.type, a) {
case d:
case f:
case e:
case m2:
case n:
return a;
default:
switch (a = a && a.$$typeof, a) {
case k:
case h:
case l:
case q:
case p:
case g:
return a;
default:
return r;
}
}
case c:
return r;
}
}
}
reactIs_production_min.ContextConsumer = h;
reactIs_production_min.ContextProvider = g;
reactIs_production_min.Element = b;
reactIs_production_min.ForwardRef = l;
reactIs_production_min.Fragment = d;
reactIs_production_min.Lazy = q;
reactIs_production_min.Memo = p;
reactIs_production_min.Portal = c;
reactIs_production_min.Profiler = f;
reactIs_production_min.StrictMode = e;
reactIs_production_min.Suspense = m2;
reactIs_production_min.SuspenseList = n;
reactIs_production_min.isAsyncMode = function() {
return false;
};
reactIs_production_min.isConcurrentMode = function() {
return false;
};
reactIs_production_min.isContextConsumer = function(a) {
return v(a) === h;
};
reactIs_production_min.isContextProvider = function(a) {
return v(a) === g;
};
reactIs_production_min.isElement = function(a) {
return "object" === typeof a && null !== a && a.$$typeof === b;
};
reactIs_production_min.isForwardRef = function(a) {
return v(a) === l;
};
reactIs_production_min.isFragment = function(a) {
return v(a) === d;
};
reactIs_production_min.isLazy = function(a) {
return v(a) === q;
};
reactIs_production_min.isMemo = function(a) {
return v(a) === p;
};
reactIs_production_min.isPortal = function(a) {
return v(a) === c;
};
reactIs_production_min.isProfiler = function(a) {
return v(a) === f;
};
reactIs_production_min.isStrictMode = function(a) {
return v(a) === e;
};
reactIs_production_min.isSuspense = function(a) {
return v(a) === m2;
};
reactIs_production_min.isSuspenseList = function(a) {
return v(a) === n;
};
reactIs_production_min.isValidElementType = function(a) {
return "string" === typeof a || "function" === typeof a || a === d || a === f || a === e || a === m2 || a === n || a === t || "object" === typeof a && null !== a && (a.$$typeof === q || a.$$typeof === p || a.$$typeof === g || a.$$typeof === h || a.$$typeof === l || a.$$typeof === u || void 0 !== a.getModuleId) ? true : false;
};
reactIs_production_min.typeOf = v;
return reactIs_production_min;
}
var reactIs_development = {};
/**
* @license React
* react-is.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.
*/
var hasRequiredReactIs_development;
function requireReactIs_development() {
if (hasRequiredReactIs_development) return reactIs_development;
hasRequiredReactIs_development = 1;
if (process.env.NODE_ENV !== "production") {
(function() {
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_SERVER_CONTEXT_TYPE = Symbol.for("react.server_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 enableScopeAPI = false;
var enableCacheElement = false;
var enableTransitionTracing = false;
var enableLegacyHidden = false;
var enableDebugTracing = false;
var REACT_MODULE_REFERENCE;
{
REACT_MODULE_REFERENCE = Symbol.for("react.module.reference");
}
function isValidElementType(type) {
if (typeof type === "string" || typeof type === "function") {
return true;
}
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 !== void 0) {
return true;
}
}
return false;
}
function typeOf(object) {
if (typeof object === "object" && object !== null) {
var $$typeof = object.$$typeof;
switch ($$typeof) {
case REACT_ELEMENT_TYPE:
var type = object.type;
switch (type) {
case REACT_FRAGMENT_TYPE:
case REACT_PROFILER_TYPE:
case REACT_STRICT_MODE_TYPE:
case REACT_SUSPENSE_TYPE:
case REACT_SUSPENSE_LIST_TYPE:
return type;
default:
var $$typeofType = type && type.$$typeof;
switch ($$typeofType) {
case REACT_SERVER_CONTEXT_TYPE:
case REACT_CONTEXT_TYPE:
case REACT_FORWARD_REF_TYPE:
case REACT_LAZY_TYPE:
case REACT_MEMO_TYPE:
case REACT_PROVIDER_TYPE:
return $$typeofType;
default:
return $$typeof;
}
}
case REACT_PORTAL_TYPE:
return $$typeof;
}
}
return void 0;
}
var ContextConsumer = REACT_CONTEXT_TYPE;
var ContextProvider = REACT_PROVIDER_TYPE;
var Element2 = REACT_ELEMENT_TYPE;
var ForwardRef = REACT_FORWARD_REF_TYPE;
var Fragment2 = REACT_FRAGMENT_TYPE;
var Lazy = REACT_LAZY_TYPE;
var Memo = REACT_MEMO_TYPE;
var Portal = REACT_PORTAL_TYPE;
var Profiler = REACT_PROFILER_TYPE;
var StrictMode = REACT_STRICT_MODE_TYPE;
var Suspense = REACT_SUSPENSE_TYPE;
var SuspenseList = REACT_SUSPENSE_LIST_TYPE;
var hasWarnedAboutDeprecatedIsAsyncMode = false;
var hasWarnedAboutDeprecatedIsConcurrentMode = false;
function isAsyncMode(object) {
{
if (!hasWarnedAboutDeprecatedIsAsyncMode) {
hasWarnedAboutDeprecatedIsAsyncMode = true;
console["warn"]("The ReactIs.isAsyncMode() alias has been deprecated, and will be removed in React 18+.");
}
}
return false;
}
function isConcurrentMode(object) {
{
if (!hasWarnedAboutDeprecatedIsConcurrentMode) {
hasWarnedAboutDeprecatedIsConcurrentMode = true;
console["warn"]("The ReactIs.isConcurrentMode() alias has been deprecated, and will be removed in React 18+.");
}
}
return false;
}
function isContextConsumer(object) {
return typeOf(object) === REACT_CONTEXT_TYPE;
}
function isContextProvider(object) {
return typeOf(object) === REACT_PROVIDER_TYPE;
}
function isElement2(object) {
return typeof object === "object" && object !== null && object.$$typeof === REACT_ELEMENT_TYPE;
}
function isForwardRef(object) {
return typeOf(object) === REACT_FORWARD_REF_TYPE;
}
function isFragment(object) {
return typeOf(object) === REACT_FRAGMENT_TYPE;
}
function isLazy(object) {
return typeOf(object) === REACT_LAZY_TYPE;
}
function isMemo(object) {
return typeOf(object) === REACT_MEMO_TYPE;
}
function isPortal(object) {
return typeOf(object) === REACT_PORTAL_TYPE;
}
function isProfiler(object) {
return typeOf(object) === REACT_PROFILER_TYPE;
}
function isStrictMode(object) {
return typeOf(object) === REACT_STRICT_MODE_TYPE;
}
function isSuspense(object) {
return typeOf(object) === REACT_SUSPENSE_TYPE;
}
function isSuspenseList(object) {
return typeOf(object) === REACT_SUSPENSE_LIST_TYPE;
}
reactIs_development.ContextConsumer = ContextConsumer;
reactIs_development.ContextProvider = ContextProvider;
reactIs_development.Element = Element2;
reactIs_development.ForwardRef = ForwardRef;
reactIs_development.Fragment = Fragment2;
reactIs_development.Lazy = Lazy;
reactIs_development.Memo = Memo;
reactIs_development.Portal = Portal;
reactIs_development.Profiler = Profiler;
reactIs_development.StrictMode = StrictMode;
reactIs_development.Suspense = Suspense;
reactIs_development.SuspenseList = SuspenseList;
reactIs_development.isAsyncMode = isAsyncMode;
reactIs_development.isConcurrentMode = isConcurrentMode;
reactIs_development.isContextConsumer = isContextConsumer;
reactIs_development.isContextProvider = isContextProvider;
reactIs_development.isElement = isElement2;
reactIs_development.isForwardRef = isForwardRef;
reactIs_development.isFragment = isFragment;
reactIs_development.isLazy = isLazy;
reactIs_development.isMemo = isMemo;
reactIs_development.isPortal = isPortal;
reactIs_development.isProfiler = isProfiler;
reactIs_development.isStrictMode = isStrictMode;
reactIs_development.isSuspense = isSuspense;
reactIs_development.isSuspenseList = isSuspenseList;
reactIs_development.isValidElementType = isValidElementType;
reactIs_development.typeOf = typeOf;
})();
}
return reactIs_development;
}
if (process.env.NODE_ENV === "production") {
reactIs.exports = requireReactIs_production_min();
} else {
reactIs.exports = requireReactIs_development();
}
var reactIsExports = reactIs.exports;
function warning$1(message) {
if (typeof console !== "undefined" && typeof console.error === "function") {
console.error(message);
}
try {
throw new Error(message);
} catch (e) {
}
}
function verify(selector, methodName) {
if (!selector) {
throw new Error(`Unexpected value for ${methodName} in connect.`);
} else if (methodName === "mapStateToProps" || methodName === "mapDispatchToProps") {
if (!Object.prototype.hasOwnProperty.call(selector, "dependsOnOwnProps")) {
warning$1(`The selector for ${methodName} of connect did not specify a value for dependsOnOwnProps.`);
}
}
}
function verifySubselectors(mapStateToProps, mapDispatchToProps2, mergeProps) {
verify(mapStateToProps, "mapStateToProps");
verify(mapDispatchToProps2, "mapDispatchToProps");
verify(mergeProps, "mergeProps");
}
const _excluded$1 = ["initMapStateToProps", "initMapDispatchToProps", "initMergeProps"];
function pureFinalPropsSelectorFactory(mapStateToProps, mapDispatchToProps2, mergeProps, dispatch, {
areStatesEqual,
areOwnPropsEqual,
areStatePropsEqual
}) {
let hasRunAtLeastOnce = false;
let state;
let ownProps;
let stateProps;
let dispatchProps;
let mergedProps;
function handleFirstCall(firstState, firstOwnProps) {
state = firstState;
ownProps = firstOwnProps;
stateProps = mapStateToProps(state, ownProps);
dispatchProps = mapDispatchToProps2(dispatch, ownProps);
mergedProps = mergeProps(stateProps, dispatchProps, ownProps);
hasRunAtLeastOnce = true;
return mergedProps;
}
function handleNewPropsAndNewState() {
stateProps = mapStateToProps(state, ownProps);
if (mapDispatchToProps2.dependsOnOwnProps) dispatchProps = mapDispatchToProps2(dispatch, ownProps);
mergedProps = mergeProps(stateProps, dispatchProps, ownProps);
return mergedProps;
}
function handleNewProps() {
if (mapStateToProps.dependsOnOwnProps) stateProps = mapStateToProps(state, ownProps);
if (mapDispatchToProps2.dependsOnOwnProps) dispatchProps = mapDispatchToProps2(dispatch, ownProps);
mergedProps = mergeProps(stateProps, dispatchProps, ownProps);
return mergedProps;
}
function handleNewState() {
const nextStateProps = mapStateToProps(state, ownProps);
const statePropsChanged = !areStatePropsEqual(nextStateProps, stateProps);
stateProps = nextStateProps;
if (statePropsChanged) mergedProps = mergeProps(stateProps, dispatchProps, ownProps);
return mergedProps;
}
function handleSubsequentCalls(nextState, nextOwnProps) {
const propsChanged = !areOwnPropsEqual(nextOwnProps, ownProps);
const stateChanged = !areStatesEqual(nextState, state, nextOwnProps, ownProps);
state = nextState;
ownProps = nextOwnProps;
if (propsChanged && stateChanged) return handleNewPropsAndNewState();
if (propsChanged) return handleNewProps();
if (stateChanged) return handleNewState();
return mergedProps;
}
return function pureFinalPropsSelector(nextState, nextOwnProps) {
return hasRunAtLeastOnce ? handleSubsequentCalls(nextState, nextOwnProps) : handleFirstCall(nextState, nextOwnProps);
};
}
function finalPropsSelectorFactory(dispatch, _ref) {
let {
initMapStateToProps,
initMapDispatchToProps,
initMergeProps
} = _ref, options = _objectWithoutPropertiesLoose(_ref, _excluded$1);
const mapStateToProps = initMapStateToProps(dispatch, options);
const mapDispatchToProps2 = initMapDispatchToProps(dispatch, options);
const mergeProps = initMergeProps(dispatch, options);
if (process.env.NODE_ENV !== "production") {
verifySubselectors(mapStateToProps, mapDispatchToProps2, mergeProps);
}
return pureFinalPropsSelectorFactory(mapStateToProps, mapDispatchToProps2, mergeProps, dispatch, options);
}
function bindActionCreators(actionCreators, dispatch) {
const boundActionCreators = {};
for (const key in actionCreators) {
const actionCreator = actionCreators[key];
if (typeof actionCreator === "function") {
boundActionCreators[key] = (...args) => dispatch(actionCreator(...args));
}
}
return boundActionCreators;
}
function isPlainObject(obj) {
if (typeof obj !== "object" || obj === null) return false;
let proto = Object.getPrototypeOf(obj);
if (proto === null) return true;
let baseProto = proto;
while (Object.getPrototypeOf(baseProto) !== null) {
baseProto = Object.getPrototypeOf(baseProto);
}
return proto === baseProto;
}
function verifyPlainObject(value, displayName, methodName) {
if (!isPlainObject(value)) {
warning$1(`${methodName}() in ${displayName} must return a plain object. Instead received ${value}.`);
}
}
function wrapMapToPropsConstant(getConstant) {
return function initConstantSelector(dispatch) {
const constant = getConstant(dispatch);
function constantSelector() {
return constant;
}
constantSelector.dependsOnOwnProps = false;
return constantSelector;
};
}
function getDependsOnOwnProps(mapToProps) {
return mapToProps.dependsOnOwnProps ? Boolean(mapToProps.dependsOnOwnProps) : mapToProps.length !== 1;
}
function wrapMapToPropsFunc(mapToProps, methodName) {
return function initProxySelector(dispatch, {
displayName
}) {
const proxy = function mapToPropsProxy(stateOrDispatch, ownProps) {
return proxy.dependsOnOwnProps ? proxy.mapToProps(stateOrDispatch, ownProps) : proxy.mapToProps(stateOrDispatch, void 0);
};
proxy.dependsOnOwnProps = true;
proxy.mapToProps = function detectFactoryAndVerify(stateOrDispatch, ownProps) {
proxy.mapToProps = mapToProps;
proxy.dependsOnOwnProps = getDependsOnOwnProps(mapToProps);
let props = proxy(stateOrDispatch, ownProps);
if (typeof props === "function") {
proxy.mapToProps = props;
proxy.dependsOnOwnProps = getDependsOnOwnProps(props);
props = proxy(stateOrDispatch, ownProps);
}
if (process.env.NODE_ENV !== "production") verifyPlainObject(props, displayName, methodName);
return props;
};
return proxy;
};
}
function createInvalidArgFactory(arg, name) {
return (dispatch, options) => {
throw new Error(`Invalid value of type ${typeof arg} for ${name} argument when connecting component ${options.wrappedComponentName}.`);
};
}
function mapDispatchToPropsFactory(mapDispatchToProps2) {
return mapDispatchToProps2 && typeof mapDispatchToProps2 === "object" ? wrapMapToPropsConstant((dispatch) => (
// @ts-ignore
bindActionCreators(mapDispatchToProps2, dispatch)
)) : !mapDispatchToProps2 ? wrapMapToPropsConstant((dispatch) => ({
dispatch
})) : typeof mapDispatchToProps2 === "function" ? (
// @ts-ignore
wrapMapToPropsFunc(mapDispatchToProps2, "mapDispatchToProps")
) : createInvalidArgFactory(mapDispatchToProps2, "mapDispatchToProps");
}
function mapStateToPropsFactory(mapStateToProps) {
return !mapStateToProps ? wrapMapToPropsConstant(() => ({})) : typeof mapStateToProps === "function" ? (
// @ts-ignore
wrapMapToPropsFunc(mapStateToProps, "mapStateToProps")
) : createInvalidArgFactory(mapStateToProps, "mapStateToProps");
}
function defaultMergeProps(stateProps, dispatchProps, ownProps) {
return _extends({}, ownProps, stateProps, dispatchProps);
}
function wrapMergePropsFunc(mergeProps) {
return function initMergePropsProxy(dispatch, {
displayName,
areMergedPropsEqual
}) {
let hasRunOnce = false;
let mergedProps;
return function mergePropsProxy(stateProps, dispatchProps, ownProps) {
const nextMergedProps = mergeProps(stateProps, dispatchProps, ownProps);
if (hasRunOnce) {
if (!areMergedPropsEqual(nextMergedProps, mergedProps)) mergedProps = nextMergedProps;
} else {
hasRunOnce = true;
mergedProps = nextMergedProps;
if (process.env.NODE_ENV !== "production") verifyPlainObject(mergedProps, displayName, "mergeProps");
}
return mergedProps;
};
};
}
function mergePropsFactory(mergeProps) {
return !mergeProps ? () => defaultMergeProps : typeof mergeProps === "function" ? wrapMergePropsFunc(mergeProps) : createInvalidArgFactory(mergeProps, "mergeProps");
}
function createListenerCollection() {
const batch2 = getBatch();
let first = null;
let last = null;
return {
clear() {
first = null;
last = null;
},
notify() {
batch2(() => {
let listener = first;
while (listener) {
listener.callback();
listener = listener.next;
}
});
},
get() {
let listeners = [];
let listener = first;
while (listener) {
listeners.push(listener);
listener = listener.next;
}
return listeners;
},
subscribe(callback) {
let isSubscribed = true;
let listener = last = {
callback,
next: null,
prev: last
};
if (listener.prev) {
listener.prev.next = listener;
} else {
first = listener;
}
return function unsubscribe() {
if (!isSubscribed || first === null) return;
isSubscribed = false;
if (listener.next) {
listener.next.prev = listener.prev;
} else {
last = listener.prev;
}
if (listener.prev) {
listener.prev.next = listener.next;
} else {
first = listener.next;
}
};
}
};
}
const nullListeners = {
notify() {
},
get: () => []
};
function createSubscription(store, parentSub) {
let unsubscribe;
let listeners = nullListeners;
let subscriptionsAmount = 0;
let selfSubscribed = false;
function addNestedSub(listener) {
trySubscribe();
const cleanupListener = listeners.subscribe(listener);
let removed = false;
return () => {
if (!removed) {
removed = true;
cleanupListener();
tryUnsubscribe();
}
};
}
function notifyNestedSubs() {
listeners.notify();
}
function handleChangeWrapper() {
if (subscription.onStateChange) {
subscription.onStateChange();
}
}
function isSubscribed() {
return selfSubscribed;
}
function trySubscribe() {
subscriptionsAmount++;
if (!unsubscribe) {
unsubscribe = parentSub ? parentSub.addNestedSub(handleChangeWrapper) : store.subscribe(handleChangeWrapper);
listeners = createListenerCollection();
}
}
function tryUnsubscribe() {
subscriptionsAmount--;
if (unsubscribe && subscriptionsAmount === 0) {
unsubscribe();
unsubscribe = void 0;
listeners.clear();
listeners = nullListeners;
}
}
function trySubscribeSelf() {
if (!selfSubscribed) {
selfSubscribed = true;
trySubscribe();
}
}
function tryUnsubscribeSelf() {
if (selfSubscribed) {
selfSubscribed = false;
tryUnsubscribe();
}
}
const subscription = {
addNestedSub,
notifyNestedSubs,
handleChangeWrapper,
isSubscribed,
trySubscribe: trySubscribeSelf,
tryUnsubscribe: tryUnsubscribeSelf,
getListeners: () => listeners
};
return subscription;
}
const canUseDOM = !!(typeof window !== "undefined" && typeof window.document !== "undefined" && typeof window.document.createElement !== "undefined");
const useIsomorphicLayoutEffect$1 = canUseDOM ? React.useLayoutEffect : React.useEffect;
function is(x, y) {
if (x === y) {
return x !== 0 || y !== 0 || 1 / x === 1 / y;
} else {
return x !== x && y !== y;
}
}
function shallowEqual(objA, objB) {
if (is(objA, objB)) return true;
if (typeof objA !== "object" || objA === null || typeof objB !== "object" || objB === null) {
return false;
}
const keysA = Object.keys(objA);
const keysB = Object.keys(objB);
if (keysA.length !== keysB.length) return false;
for (let i = 0; i < keysA.length; i++) {
if (!Object.prototype.hasOwnProperty.call(objB, keysA[i]) || !is(objA[keysA[i]], objB[keysA[i]])) {
return false;
}
}
return true;
}
const _excluded = ["reactReduxForwardedRef"];
let useSyncExternalStore = notInitialized;
const initializeConnect = (fn) => {
useSyncExternalStore = fn;
};
const NO_SUBSCRIPTION_ARRAY = [null, null];
const stringifyComponent = (Comp) => {
try {
return JSON.stringify(Comp);
} catch (err) {
return String(Comp);
}
};
function useIsomorphicLayoutEffectWithArgs(effectFunc, effectArgs, dependencies) {
useIsomorphicLayoutEffect$1(() => effectFunc(...effectArgs), dependencies);
}
function captureWrapperProps(lastWrapperProps, lastChildProps, renderIsScheduled, wrapperProps, childPropsFromStoreUpdate, notifyNestedSubs) {
lastWrapperProps.current = wrapperProps;
renderIsScheduled.current = false;
if (childPropsFromStoreUpdate.current) {
childPropsFromStoreUpdate.current = null;
notifyNestedSubs();
}
}
function subscribeUpdates(shouldHandleStateChanges, store, subscription, childPropsSelector, lastWrapperProps, lastChildProps, renderIsScheduled, isMounted, childPropsFromStoreUpdate, notifyNestedSubs, additionalSubscribeListener) {
if (!shouldHandleStateChanges) return () => {
};
let didUnsubscribe = false;
let lastThrownError = null;
const checkForUpdates = () => {
if (didUnsubscribe || !isMounted.current) {
return;
}
const latestStoreState = store.getState();
let newChildProps, error2;
try {
newChildProps = childPropsSelector(latestStoreState, lastWrapperProps.current);
} catch (e) {
error2 = e;
lastThrownError = e;
}
if (!error2) {
lastThrownError = null;
}
if (newChildProps === lastChildProps.current) {
if (!renderIsScheduled.current) {
notifyNestedSubs();
}
} else {
lastChildProps.current = newChildProps;
childPropsFromStoreUpdate.current = newChildProps;
renderIsScheduled.current = true;
additionalSubscribeListener();
}
};
subscription.onStateChange = checkForUpdates;
subscription.trySubscribe();
checkForUpdates();
const unsubscribeWrapper = () => {
didUnsubscribe = true;
subscription.tryUnsubscribe();
subscription.onStateChange = null;
if (lastThrownError) {
throw lastThrownError;
}
};
return unsubscribeWrapper;
}
function strictEqual(a, b) {
return a === b;
}
let hasWarnedAboutDeprecatedPureOption = false;
function connect(mapStateToProps, mapDispatchToProps2, mergeProps, {
// The `pure` option has been removed, so TS doesn't like us destructuring this to check its existence.
// @ts-ignore
pure,
areStatesEqual = strictEqual,
areOwnPropsEqual = shallowEqual,
areStatePropsEqual = shallowEqual,
areMergedPropsEqual = shallowEqual,
// use React's forwardRef to expose a ref of the wrapped component
forwardRef: forwardRef2 = false,
// the context consumer to use
context = ReactReduxContext
} = {}) {
if (process.env.NODE_ENV !== "production") {
if (pure !== void 0 && !hasWarnedAboutDeprecatedPureOption) {
hasWarnedAboutDeprecatedPureOption = true;
warning$1('The `pure` option has been removed. `connect` is now always a "pure/memoized" component');
}
}
const Context = context;
const initMapStateToProps = mapStateToPropsFactory(mapStateToProps);
const initMapDispatchToProps = mapDispatchToPropsFactory(mapDispatchToProps2);
const initMergeProps = mergePropsFactory(mergeProps);
const shouldHandleStateChanges = Boolean(mapStateToProps);
const wrapWithConnect = (WrappedComponent) => {
if (process.env.NODE_ENV !== "production" && !reactIsExports.isValidElementType(WrappedComponent)) {
throw new Error(`You must pass a component to the function returned by connect. Instead received ${stringifyComponent(WrappedComponent)}`);
}
const wrappedComponentName = WrappedComponent.displayName || WrappedComponent.name || "Component";
const displayName = `Connect(${wrappedComponentName})`;
const selectorFactoryOptions = {
shouldHandleStateChanges,
displayName,
wrappedComponentName,
WrappedComponent,
// @ts-ignore
initMapStateToProps,
// @ts-ignore
initMapDispatchToProps,
initMergeProps,
areStatesEqual,
areStatePropsEqual,
areOwnPropsEqual,
areMergedPropsEqual
};
function ConnectFunction(props) {
const [propsContext, reactReduxForwardedRef, wrapperProps] = React.useMemo(() => {
const {
reactReduxForwardedRef: reactReduxForwardedRef2
} = props, wrapperProps2 = _objectWithoutPropertiesLoose(props, _excluded);
return [props.context, reactReduxForwardedRef2, wrapperProps2];
}, [props]);
const ContextToUse = React.useMemo(() => {
return propsContext && propsContext.Consumer && // @ts-ignore
reactIsExports.isContextConsumer(/* @__PURE__ */ React.createElement(propsContext.Consumer, null)) ? propsContext : Context;
}, [propsContext, Context]);
const contextValue = React.useContext(ContextToUse);
const didStoreComeFromProps = Boolean(props.store) && Boolean(props.store.getState) && Boolean(props.store.dispatch);
const didStoreComeFromContext = Boolean(contextValue) && Boolean(contextValue.store);
if (process.env.NODE_ENV !== "production" && !didStoreComeFromProps && !didStoreComeFromContext) {
throw new Error(`Could not find "store" in the context of "${displayName}". Either wrap the root component in a <Provider>, or pass a custom React context provider to <Provider> and the corresponding React context consumer to ${displayName} in connect options.`);
}
const store = didStoreComeFromProps ? props.store : contextValue.store;
const getServerState = didStoreComeFromContext ? contextValue.getServerState : store.getState;
const childPropsSelector = React.useMemo(() => {
return finalPropsSelectorFactory(store.dispatch, selectorFactoryOptions);
}, [store]);
const [subscription, notifyNestedSubs] = React.useMemo(() => {
if (!shouldHandleStateChanges) return NO_SUBSCRIPTION_ARRAY;
const subscription2 = createSubscription(store, didStoreComeFromProps ? void 0 : contextValue.subscription);
const notifyNestedSubs2 = subscription2.notifyNestedSubs.bind(subscription2);
return [subscription2, notifyNestedSubs2];
}, [store, didStoreComeFromProps, contextValue]);
const overriddenContextValue = React.useMemo(() => {
if (didStoreComeFromProps) {
return contextValue;
}
return _extends({}, contextValue, {
subscription
});
}, [didStoreComeFromProps, contextValue, subscription]);
const lastChildProps = React.useRef();
const lastWrapperProps = React.useRef(wrapperProps);
const childPropsFromStoreUpdate = React.useRef();
const renderIsScheduled = React.useRef(false);
React.useRef(false);
const isMounted = React.useRef(false);
const latestSubscriptionCallbackError = React.useRef();
useIsomorphicLayoutEffect$1(() => {
isMounted.current = true;
return () => {
isMounted.current = false;
};
}, []);
const actualChildPropsSelector = React.useMemo(() => {
const selector = () => {
if (childPropsFromStoreUpdate.current && wrapperProps === lastWrapperProps.current) {
return childPropsFromStoreUpdate.current;
}
return childPropsSelector(store.getState(), wrapperProps);
};
return selector;
}, [store, wrapperProps]);
const subscribeForReact = React.useMemo(() => {
const subscribe = (reactListener) => {
if (!subscription) {
return () => {
};
}
return subscribeUpdates(
shouldHandleStateChanges,
store,
subscription,
// @ts-ignore
childPropsSelector,
lastWrapperProps,
lastChildProps,
renderIsScheduled,
isMounted,
childPropsFromStoreUpdate,
notifyNestedSubs,
reactListener
);
};
return subscribe;
}, [subscription]);
useIsomorphicLayoutEffectWithArgs(captureWrapperProps, [lastWrapperProps, lastChildProps, renderIsScheduled, wrapperProps, childPropsFromStoreUpdate, notifyNestedSubs]);
let actualChildProps;
try {
actualChildProps = useSyncExternalStore(
// TODO We're passing through a big wrapper that does a bunch of extra side effects besides subscribing
subscribeForReact,
// TODO This is incredibly hacky. We've already processed the store update and calculated new child props,
// TODO and we're just passing that through so it triggers a re-render for us rather than relying on `uSES`.
actualChildPropsSelector,
getServerState ? () => childPropsSelector(getServerState(), wrapperProps) : actualChildPropsSelector
);
} catch (err) {
if (latestSubscriptionCallbackError.current) {
err.message += `
The error may be correlated with this previous error:
${latestSubscriptionCallbackError.current.stack}
`;
}
throw err;
}
useIsomorphicLayoutEffect$1(() => {
latestSubscriptionCallbackError.current = void 0;
childPropsFromStoreUpdate.current = void 0;
lastChildProps.current = actualChildProps;
});
const renderedWrappedComponent = React.useMemo(() => {
return (
// @ts-ignore
/* @__PURE__ */ React.createElement(WrappedComponent, _extends({}, actualChildProps, {
ref: reactReduxForwardedRef
}))
);
}, [reactReduxForwardedRef, WrappedComponent, actualChildProps]);
const renderedChild = React.useMemo(() => {
if (shouldHandleStateChanges) {
return /* @__PURE__ */ React.createElement(ContextToUse.Provider, {
value: overriddenContextValue
}, renderedWrappedComponent);
}
return renderedWrappedComponent;
}, [ContextToUse, renderedWrappedComponent, overriddenContextValue]);
return renderedChild;
}
const _Connect = React.memo(ConnectFunction);
const Connect = _Connect;
Connect.WrappedComponent = WrappedComponent;
Connect.displayName = ConnectFunction.displayName = displayName;
if (forwardRef2) {
const _forwarded = React.forwardRef(function forwardConnectRef(props, ref2) {
return /* @__PURE__ */ React.createElement(Connect, _extends({}, props, {
reactReduxForwardedRef: ref2
}));
});
const forwarded = _forwarded;
forwarded.displayName = displayName;
forwarded.WrappedComponent = WrappedComponent;
return hoistStatics(forwarded, WrappedComponent);
}
return hoistStatics(Connect, WrappedComponent);
};
return wrapWithConnect;
}
function Provider({
store,
context,
children,
serverState,
stabilityCheck = "once",
noopCheck = "once"
}) {
const contextValue = React.useMemo(() => {
const subscription = createSubscription(store);
return {
store,
subscription,
getServerState: serverState ? () => serverState : void 0,
stabilityCheck,
noopCheck
};
}, [store, serverState, stabilityCheck, noopCheck]);
const previousState = React.useMemo(() => store.getState(), [store]);
useIsomorphicLayoutEffect$1(() => {
const {
subscription
} = contextValue;
subscription.onStateChange = subscription.notifyNestedSubs;
subscription.trySubscribe();
if (previousState !== store.getState()) {
subscription.notifyNestedSubs();
}
return () => {
subscription.tryUnsubscribe();
subscription.onStateChange = void 0;
};
}, [contextValue, previousState]);
const Context = context || ReactReduxContext;
return /* @__PURE__ */ React.createElement(Context.Provider, {
value: contextValue
}, children);
}
initializeConnect(shimExports.useSyncExternalStore);
setBatch(unstable_batchedUpdates);
function areInputsEqual$1(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 = useState(function() {
return {
inputs,
result: getResult()
};
})[0];
var isFirstRun = useRef(true);
var committed = useRef(initial);
var useCache = isFirstRun.current || Boolean(inputs && committed.current.inputs && areInputsEqual$1(inputs, committed.current.inputs));
var cache = useCache ? committed.current : {
inputs,
result: getResult()
};
useEffect(function() {
isFirstRun.current = false;
committed.current = cache;
}, [cache]);
return cache.result;
}
function useCallbackOne(callback, inputs) {
return useMemoOne(function() {
return callback;
}, inputs);
}
var useMemo = useMemoOne;
var useCallback = useCallbackOne;
var isProduction$2 = process.env.NODE_ENV === "production";
var prefix$2 = "Invariant failed";
function invariant$1(condition, message) {
if (isProduction$2) {
throw new Error(prefix$2);
}
var provided = typeof message === "function" ? message() : message;
var value = provided ? "".concat(prefix$2, ": ").concat(provided) : prefix$2;
throw new Error(value);
}
var getRect = function getRect2(_ref) {
var top = _ref.top, right = _ref.right, bottom = _ref.bottom, left = _ref.left;
var width = right - left;
var height = bottom - top;
var rect = {
top,
right,
bottom,
left,
width,
height,
x: left,
y: top,
center: {
x: (right + left) / 2,
y: (bottom + top) / 2
}
};
return rect;
};
var expand = function expand2(target, expandBy) {
return {
top: target.top - expandBy.top,
left: target.left - expandBy.left,
bottom: target.bottom + expandBy.bottom,
right: target.right + expandBy.right
};
};
var shrink = function shrink2(target, shrinkBy) {
return {
top: target.top + shrinkBy.top,
left: target.left + shrinkBy.left,
bottom: target.bottom - shrinkBy.bottom,
right: target.right - shrinkBy.right
};
};
var shift = function shift2(target, shiftBy) {
return {
top: target.top + shiftBy.y,
left: target.left + shiftBy.x,
bottom: target.bottom + shiftBy.y,
right: target.right + shiftBy.x
};
};
var noSpacing$1 = {
top: 0,
right: 0,
bottom: 0,
left: 0
};
var createBox = function createBox2(_ref2) {
var borderBox = _ref2.borderBox, _ref2$margin = _ref2.margin, margin = _ref2$margin === void 0 ? noSpacing$1 : _ref2$margin, _ref2$border = _ref2.border, border = _ref2$border === void 0 ? noSpacing$1 : _ref2$border, _ref2$padding = _ref2.padding, padding = _ref2$padding === void 0 ? noSpacing$1 : _ref2$padding;
var marginBox = getRect(expand(borderBox, margin));
var paddingBox = getRect(shrink(borderBox, border));
var contentBox = getRect(shrink(paddingBox, padding));
return {
marginBox,
borderBox: getRect(borderBox),
paddingBox,
contentBox,
margin,
border,
padding
};
};
var parse2 = function parse3(raw) {
var value = raw.slice(0, -2);
var suffix2 = raw.slice(-2);
if (suffix2 !== "px") {
return 0;
}
var result = Number(value);
!!isNaN(result) ? process.env.NODE_ENV !== "production" ? invariant$1(false, "Could not parse value [raw: " + raw + ", without suffix: " + value + "]") : invariant$1() : void 0;
return result;
};
var getWindowScroll$1 = function getWindowScroll() {
return {
x: window.pageXOffset,
y: window.pageYOffset
};
};
var offset = function offset2(original, change) {
var borderBox = original.borderBox, border = original.border, margin = original.margin, padding = original.padding;
var shifted = shift(borderBox, change);
return createBox({
borderBox: shifted,
border,
margin,
padding
});
};
var withScroll = function withScroll2(original, scroll2) {
if (scroll2 === void 0) {
scroll2 = getWindowScroll$1();
}
return offset(original, scroll2);
};
var calculateBox = function calculateBox2(borderBox, styles) {
var margin = {
top: parse2(styles.marginTop),
right: parse2(styles.marginRight),
bottom: parse2(styles.marginBottom),
left: parse2(styles.marginLeft)
};
var padding = {
top: parse2(styles.paddingTop),
right: parse2(styles.paddingRight),
bottom: parse2(styles.paddingBottom),
left: parse2(styles.paddingLeft)
};
var border = {
top: parse2(styles.borderTopWidth),
right: parse2(styles.borderRightWidth),
bottom: parse2(styles.borderBottomWidth),
left: parse2(styles.borderLeftWidth)
};
return createBox({
borderBox,
margin,
padding,
border
});
};
var getBox = function getBox2(el) {
var borderBox = el.getBoundingClientRect();
var styles = window.getComputedStyle(el);
return calculateBox(borderBox, styles);
};
var safeIsNaN = Number.isNaN || function ponyfill(value) {
return typeof value === "number" && value !== value;
};
function isEqual$2(first, second) {
if (first === second) {
return true;
}
if (safeIsNaN(first) && safeIsNaN(second)) {
return true;
}
return false;
}
function areInputsEqual(newInputs, lastInputs) {
if (newInputs.length !== lastInputs.length) {
return false;
}
for (var i = 0; i < newInputs.length; i++) {
if (!isEqual$2(newInputs[i], lastInputs[i])) {
return false;
}
}
return true;
}
function memoizeOne(resultFn, isEqual2) {
if (isEqual2 === void 0) {
isEqual2 = areInputsEqual;
}
var cache = null;
function memoized() {
var newArgs = [];
for (var _i = 0; _i < arguments.length; _i++) {
newArgs[_i] = arguments[_i];
}
if (cache && cache.lastThis === this && isEqual2(newArgs, cache.lastArgs)) {
return cache.lastResult;
}
var lastResult = resultFn.apply(this, newArgs);
cache = {
lastResult,
lastArgs: newArgs,
lastThis: this
};
return lastResult;
}
memoized.clear = function clear() {
cache = null;
};
return memoized;
}
var rafSchd = function rafSchd2(fn) {
var lastArgs = [];
var frameId = null;
var wrapperFn = function wrapperFn2() {
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
lastArgs = args;
if (frameId) {
return;
}
frameId = requestAnimationFrame(function() {
frameId = null;
fn.apply(void 0, lastArgs);
});
};
wrapperFn.cancel = function() {
if (!frameId) {
return;
}
cancelAnimationFrame(frameId);
frameId = null;
};
return wrapperFn;
};
const isProduction$1 = process.env.NODE_ENV === "production";
const spacesAndTabs = /[ \t]{2,}/g;
const lineStartWithSpaces = /^[ \t]*/gm;
const clean$2 = (value) => value.replace(spacesAndTabs, " ").replace(lineStartWithSpaces, "").trim();
const getDevMessage = (message) => clean$2(`
%c@hello-pangea/dnd
%c${clean$2(message)}
%c👷 This is a development only message. It will be removed in production builds.
`);
const getFormattedMessage = (message) => [getDevMessage(message), "color: #00C584; font-size: 1.2em; font-weight: bold;", "line-height: 1.5", "color: #723874;"];
const isDisabledFlag = "__@hello-pangea/dnd-disable-dev-warnings";
function log(type, message) {
if (isProduction$1) {
return;
}
if (typeof window !== "undefined" && window[isDisabledFlag]) {
return;
}
console[type](...getFormattedMessage(message));
}
const warning = log.bind(null, "warn");
const error = log.bind(null, "error");
function noop$2() {
}
function getOptions(shared2, fromBinding) {
return {
...shared2,
...fromBinding
};
}
function bindEvents(el, bindings, sharedOptions) {
const unbindings = bindings.map((binding) => {
const options = getOptions(sharedOptions, binding.options);
el.addEventListener(binding.eventName, binding.fn, options);
return function unbind() {
el.removeEventListener(binding.eventName, binding.fn, options);
};
});
return function unbindAll() {
unbindings.forEach((unbind) => {
unbind();
});
};
}
const isProduction = process.env.NODE_ENV === "production";
const prefix$1 = "Invariant failed";
class RbdInvariant extends Error {
}
RbdInvariant.prototype.toString = function toString() {
return this.message;
};
function invariant(condition, message) {
if (isProduction) {
throw new RbdInvariant(prefix$1);
} else {
throw new RbdInvariant(`${prefix$1}: ${message || ""}`);
}
}
class ErrorBoundary extends React__default.Component {
constructor(...args) {
super(...args);
this.callbacks = null;
this.unbind = noop$2;
this.onWindowError = (event) => {
const callbacks = this.getCallbacks();
if (callbacks.isDragging()) {
callbacks.tryAbort();
process.env.NODE_ENV !== "production" ? warning(`
An error was caught by our window 'error' event listener while a drag was occurring.
The active drag has been aborted.
`) : void 0;
}
const err = event.error;
if (err instanceof RbdInvariant) {
event.preventDefault();
if (process.env.NODE_ENV !== "production") {
error(err.message);
}
}
};
this.getCallbacks = () => {
if (!this.callbacks) {
throw new Error("Unable to find AppCallbacks in <ErrorBoundary/>");
}
return this.callbacks;
};
this.setCallbacks = (callbacks) => {
this.callbacks = callbacks;
};
}
componentDidMount() {
this.unbind = bindEvents(window, [{
eventName: "error",
fn: this.onWindowError
}]);
}
componentDidCatch(err) {
if (err instanceof RbdInvariant) {
if (process.env.NODE_ENV !== "production") {
error(err.message);
}
this.setState({});
return;
}
throw err;
}
componentWillUnmount() {
this.unbind();
}
render() {
return this.props.children(this.setCallbacks);
}
}
const dragHandleUsageInstructions = `
Press space bar to start a drag.
When dragging you can use the arrow keys to move the item around and escape to cancel.
Some screen readers may require you to be in focus mode or to use your pass through key
`;
const position = (index) => index + 1;
const onDragStart = (start2) => `
You have lifted an item in position ${position(start2.source.index)}
`;
const withLocation = (source, destination) => {
const isInHomeList = source.droppableId === destination.droppableId;
const startPosition = position(source.index);
const endPosition = position(destination.index);
if (isInHomeList) {
return `
You have moved the item from position ${startPosition}
to position ${endPosition}
`;
}
return `
You have moved the item from position ${startPosition}
in list ${source.droppableId}
to list ${destination.droppableId}
in position ${endPosition}
`;
};
const withCombine = (id, source, combine2) => {
const inHomeList = source.droppableId === combine2.droppableId;
if (inHomeList) {
return `
The item ${id}
has been combined with ${combine2.draggableId}`;
}
return `
The item ${id}
in list ${source.droppableId}
has been combined with ${combine2.draggableId}
in list ${combine2.droppableId}
`;
};
const onDragUpdate = (update2) => {
const location = update2.destination;
if (location) {
return withLocation(update2.source, location);
}
const combine2 = update2.combine;
if (combine2) {
return withCombine(update2.draggableId, update2.source, combine2);
}
return "You are over an area that cannot be dropped on";
};
const returnedToStart = (source) => `
The item has returned to its starting position
of ${position(source.index)}
`;
const onDragEnd = (result) => {
if (result.reason === "CANCEL") {
return `
Movement cancelled.
${returnedToStart(result.source)}
`;
}
const location = result.destination;
const combine2 = result.combine;
if (location) {
return `
You have dropped the item.
${withLocation(result.source, location)}
`;
}
if (combine2) {
return `
You have dropped the item.
${withCombine(result.draggableId, result.source, combine2)}
`;
}
return `
The item has been dropped while not over a drop area.
${returnedToStart(result.source)}
`;
};
const preset = {
dragHandleUsageInstructions,
onDragStart,
onDragUpdate,
onDragEnd
};
var preset$1 = preset;
const origin = {
x: 0,
y: 0
};
const add = (point1, point2) => ({
x: point1.x + point2.x,
y: point1.y + point2.y
});
const subtract = (point1, point2) => ({
x: point1.x - point2.x,
y: point1.y - point2.y
});
const isEqual$1 = (point1, point2) => point1.x === point2.x && point1.y === point2.y;
const negate = (point) => ({
x: point.x !== 0 ? -point.x : 0,
y: point.y !== 0 ? -point.y : 0
});
const patch = (line, value, otherValue = 0) => {
if (line === "x") {
return {
x: value,
y: otherValue
};
}
return {
x: otherValue,
y: value
};
};
const distance = (point1, point2) => Math.sqrt((point2.x - point1.x) ** 2 + (point2.y - point1.y) ** 2);
const closest$1 = (target, points) => Math.min(...points.map((point) => distance(target, point)));
const apply = (fn) => (point) => ({
x: fn(point.x),
y: fn(point.y)
});
var executeClip = (frame2, subject) => {
const result = getRect({
top: Math.max(subject.top, frame2.top),
right: Math.min(subject.right, frame2.right),
bottom: Math.min(subject.bottom, frame2.bottom),
left: Math.max(subject.left, frame2.left)
});
if (result.width <= 0 || result.height <= 0) {
return null;
}
return result;
};
const offsetByPosition = (spacing, point) => ({
top: spacing.top + point.y,
left: spacing.left + point.x,
bottom: spacing.bottom + point.y,
right: spacing.right + point.x
});
const getCorners = (spacing) => [{
x: spacing.left,
y: spacing.top
}, {
x: spacing.right,
y: spacing.top
}, {
x: spacing.left,
y: spacing.bottom
}, {
x: spacing.right,
y: spacing.bottom
}];
const noSpacing = {
top: 0,
right: 0,
bottom: 0,
left: 0
};
const scroll$1 = (target, frame2) => {
if (!frame2) {
return target;
}
return offsetByPosition(target, frame2.scroll.diff.displacement);
};
const increase = (target, axis, withPlaceholder) => {
if (withPlaceholder && withPlaceholder.increasedBy) {
return {
...target,
[axis.end]: target[axis.end] + withPlaceholder.increasedBy[axis.line]
};
}
return target;
};
const clip = (target, frame2) => {
if (frame2 && frame2.shouldClipSubject) {
return executeClip(frame2.pageMarginBox, target);
}
return getRect(target);
};
var getSubject = ({
page,
withPlaceholder,
axis,
frame: frame2
}) => {
const scrolled = scroll$1(page.marginBox, frame2);
const increased = increase(scrolled, axis, withPlaceholder);
const clipped = clip(increased, frame2);
return {
page,
withPlaceholder,
active: clipped
};
};
var scrollDroppable = (droppable2, newScroll) => {
!droppable2.frame ? process.env.NODE_ENV !== "production" ? invariant() : invariant() : void 0;
const scrollable = droppable2.frame;
const scrollDiff = subtract(newScroll, scrollable.scroll.initial);
const scrollDisplacement = negate(scrollDiff);
const frame2 = {
...scrollable,
scroll: {
initial: scrollable.scroll.initial,
current: newScroll,
diff: {
value: scrollDiff,
displacement: scrollDisplacement
},
max: scrollable.scroll.max
}
};
const subject = getSubject({
page: droppable2.subject.page,
withPlaceholder: droppable2.subject.withPlaceholder,
axis: droppable2.axis,
frame: frame2
});
const result = {
...droppable2,
frame: frame2,
subject
};
return result;
};
const toDroppableMap = memoizeOne((droppables) => droppables.reduce((previous, current) => {
previous[current.descriptor.id] = current;
return previous;
}, {}));
const toDraggableMap = memoizeOne((draggables) => draggables.reduce((previous, current) => {
previous[current.descriptor.id] = current;
return previous;
}, {}));
const toDroppableList = memoizeOne((droppables) => Object.values(droppables));
const toDraggableList = memoizeOne((draggables) => Object.values(draggables));
var getDraggablesInsideDroppable = memoizeOne((droppableId, draggables) => {
const result = toDraggableList(draggables).filter((draggable2) => droppableId === draggable2.descriptor.droppableId).sort((a, b) => a.descriptor.index - b.descriptor.index);
return result;
});
function tryGetDestination(impact) {
if (impact.at && impact.at.type === "REORDER") {
return impact.at.destination;
}
return null;
}
function tryGetCombine(impact) {
if (impact.at && impact.at.type === "COMBINE") {
return impact.at.combine;
}
return null;
}
var removeDraggableFromList = memoizeOne((remove, list) => list.filter((item) => item.descriptor.id !== remove.descriptor.id));
var moveToNextCombine = ({
isMovingForward,
draggable: draggable2,
destination,
insideDestination,
previousImpact
}) => {
if (!destination.isCombineEnabled) {
return null;
}
const location = tryGetDestination(previousImpact);
if (!location) {
return null;
}
function getImpact(target) {
const at = {
type: "COMBINE",
combine: {
draggableId: target,
droppableId: destination.descriptor.id
}
};
return {
...previousImpact,
at
};
}
const all = previousImpact.displaced.all;
const closestId = all.length ? all[0] : null;
if (isMovingForward) {
return closestId ? getImpact(closestId) : null;
}
const withoutDraggable = removeDraggableFromList(draggable2, insideDestination);
if (!closestId) {
if (!withoutDraggable.length) {
return null;
}
const last = withoutDraggable[withoutDraggable.length - 1];
return getImpact(last.descriptor.id);
}
const indexOfClosest = withoutDraggable.findIndex((d) => d.descriptor.id === closestId);
!(indexOfClosest !== -1) ? process.env.NODE_ENV !== "production" ? invariant(false, "Could not find displaced item in set") : invariant() : void 0;
const proposedIndex = indexOfClosest - 1;
if (proposedIndex < 0) {
return null;
}
const before = withoutDraggable[proposedIndex];
return getImpact(before.descriptor.id);
};
var isHomeOf = (draggable2, destination) => draggable2.descriptor.droppableId === destination.descriptor.id;
const noDisplacedBy = {
point: origin,
value: 0
};
const emptyGroups = {
invisible: {},
visible: {},
all: []
};
const noImpact = {
displaced: emptyGroups,
displacedBy: noDisplacedBy,
at: null
};
var noImpact$1 = noImpact;
var isWithin = (lowerBound, upperBound) => (value) => lowerBound <= value && value <= upperBound;
var isPartiallyVisibleThroughFrame = (frame2) => {
const isWithinVertical = isWithin(frame2.top, frame2.bottom);
const isWithinHorizontal = isWithin(frame2.left, frame2.right);
return (subject) => {
const isContained = isWithinVertical(subject.top) && isWithinVertical(subject.bottom) && isWithinHorizontal(subject.left) && isWithinHorizontal(subject.right);
if (isContained) {
return true;
}
const isPartiallyVisibleVertically = isWithinVertical(subject.top) || isWithinVertical(subject.bottom);
const isPartiallyVisibleHorizontally = isWithinHorizontal(subject.left) || isWithinHorizontal(subject.right);
const isPartiallyContained = isPartiallyVisibleVertically && isPartiallyVisibleHorizontally;
if (isPartiallyContained) {
return true;
}
const isBiggerVertically = subject.top < frame2.top && subject.bottom > frame2.bottom;
const isBiggerHorizontally = subject.left < frame2.left && subject.right > frame2.right;
const isTargetBiggerThanFrame = isBiggerVertically && isBiggerHorizontally;
if (isTargetBiggerThanFrame) {
return true;
}
const isTargetBiggerOnOneAxis = isBiggerVertically && isPartiallyVisibleHorizontally || isBiggerHorizontally && isPartiallyVisibleVertically;
return isTargetBiggerOnOneAxis;
};
};
var isTotallyVisibleThroughFrame = (frame2) => {
const isWithinVertical = isWithin(frame2.top, frame2.bottom);
const isWithinHorizontal = isWithin(frame2.left, frame2.right);
return (subject) => {
const isContained = isWithinVertical(subject.top) && isWithinVertical(subject.bottom) && isWithinHorizontal(subject.left) && isWithinHorizontal(subject.right);
return isContained;
};
};
const vertical = {
direction: "vertical",
line: "y",
crossAxisLine: "x",
start: "top",
end: "bottom",
size: "height",
crossAxisStart: "left",
crossAxisEnd: "right",
crossAxisSize: "width"
};
const horizontal = {
direction: "horizontal",
line: "x",
crossAxisLine: "y",
start: "left",
end: "right",
size: "width",
crossAxisStart: "top",
crossAxisEnd: "bottom",
crossAxisSize: "height"
};
var isTotallyVisibleThroughFrameOnAxis = (axis) => (frame2) => {
const isWithinVertical = isWithin(frame2.top, frame2.bottom);
const isWithinHorizontal = isWithin(frame2.left, frame2.right);
return (subject) => {
if (axis === vertical) {
return isWithinVertical(subject.top) && isWithinVertical(subject.bottom);
}
return isWithinHorizontal(subject.left) && isWithinHorizontal(subject.right);
};
};
const getDroppableDisplaced = (target, destination) => {
const displacement = destination.frame ? destination.frame.scroll.diff.displacement : origin;
return offsetByPosition(target, displacement);
};
const isVisibleInDroppable = (target, destination, isVisibleThroughFrameFn) => {
if (!destination.subject.active) {
return false;
}
return isVisibleThroughFrameFn(destination.subject.active)(target);
};
const isVisibleInViewport = (target, viewport, isVisibleThroughFrameFn) => isVisibleThroughFrameFn(viewport)(target);
const isVisible$1 = ({
target: toBeDisplaced,
destination,
viewport,
withDroppableDisplacement: withDroppableDisplacement2,
isVisibleThroughFrameFn
}) => {
const displacedTarget = withDroppableDisplacement2 ? getDroppableDisplaced(toBeDisplaced, destination) : toBeDisplaced;
return isVisibleInDroppable(displacedTarget, destination, isVisibleThroughFrameFn) && isVisibleInViewport(displacedTarget, viewport, isVisibleThroughFrameFn);
};
const isPartiallyVisible = (args) => isVisible$1({
...args,
isVisibleThroughFrameFn: isPartiallyVisibleThroughFrame
});
const isTotallyVisible = (args) => isVisible$1({
...args,
isVisibleThroughFrameFn: isTotallyVisibleThroughFrame
});
const isTotallyVisibleOnAxis = (args) => isVisible$1({
...args,
isVisibleThroughFrameFn: isTotallyVisibleThroughFrameOnAxis(args.destination.axis)
});
const getShouldAnimate = (id, last, forceShouldAnimate) => {
if (typeof forceShouldAnimate === "boolean") {
return forceShouldAnimate;
}
if (!last) {
return true;
}
const {
invisible,
visible
} = last;
if (invisible[id]) {
return false;
}
const previous = visible[id];
return previous ? previous.shouldAnimate : true;
};
function getTarget(draggable2, displacedBy) {
const marginBox = draggable2.page.marginBox;
const expandBy = {
top: displacedBy.point.y,
right: 0,
bottom: 0,
left: displacedBy.point.x
};
return getRect(expand(marginBox, expandBy));
}
function getDisplacementGroups({
afterDragging,
destination,
displacedBy,
viewport,
forceShouldAnimate,
last
}) {
return afterDragging.reduce(function process2(groups, draggable2) {
const target = getTarget(draggable2, displacedBy);
const id = draggable2.descriptor.id;
groups.all.push(id);
const isVisible2 = isPartiallyVisible({
target,
destination,
viewport,
withDroppableDisplacement: true
});
if (!isVisible2) {
groups.invisible[draggable2.descriptor.id] = true;
return groups;
}
const shouldAnimate = getShouldAnimate(id, last, forceShouldAnimate);
const displacement = {
draggableId: id,
shouldAnimate
};
groups.visible[id] = displacement;
return groups;
}, {
all: [],
visible: {},
invisible: {}
});
}
function getIndexOfLastItem(draggables, options) {
if (!draggables.length) {
return 0;
}
const indexOfLastItem = draggables[draggables.length - 1].descriptor.index;
return options.inHomeList ? indexOfLastItem : indexOfLastItem + 1;
}
function goAtEnd({
insideDestination,
inHomeList,
displacedBy,
destination
}) {
const newIndex = getIndexOfLastItem(insideDestination, {
inHomeList
});
return {
displaced: emptyGroups,
displacedBy,
at: {
type: "REORDER",
destination: {
droppableId: destination.descriptor.id,
index: newIndex
}
}
};
}
function calculateReorderImpact({
draggable: draggable2,
insideDestination,
destination,
viewport,
displacedBy,
last,
index,
forceShouldAnimate
}) {
const inHomeList = isHomeOf(draggable2, destination);
if (index == null) {
return goAtEnd({
insideDestination,
inHomeList,
displacedBy,
destination
});
}
const match = insideDestination.find((item) => item.descriptor.index === index);
if (!match) {
return goAtEnd({
insideDestination,
inHomeList,
displacedBy,
destination
});
}
const withoutDragging = removeDraggableFromList(draggable2, insideDestination);
const sliceFrom = insideDestination.indexOf(match);
const impacted = withoutDragging.slice(sliceFrom);
const displaced = getDisplacementGroups({
afterDragging: impacted,
destination,
displacedBy,
last,
viewport: viewport.frame,
forceShouldAnimate
});
return {
displaced,
displacedBy,
at: {
type: "REORDER",
destination: {
droppableId: destination.descriptor.id,
index
}
}
};
}
function didStartAfterCritical(draggableId, afterCritical) {
return Boolean(afterCritical.effected[draggableId]);
}
var fromCombine = ({
isMovingForward,
destination,
draggables,
combine: combine2,
afterCritical
}) => {
if (!destination.isCombineEnabled) {
return null;
}
const combineId = combine2.draggableId;
const combineWith = draggables[combineId];
const combineWithIndex = combineWith.descriptor.index;
const didCombineWithStartAfterCritical = didStartAfterCritical(combineId, afterCritical);
if (didCombineWithStartAfterCritical) {
if (isMovingForward) {
return combineWithIndex;
}
return combineWithIndex - 1;
}
if (isMovingForward) {
return combineWithIndex + 1;
}
return combineWithIndex;
};
var fromReorder = ({
isMovingForward,
isInHomeList,
insideDestination,
location
}) => {
if (!insideDestination.length) {
return null;
}
const currentIndex = location.index;
const proposedIndex = isMovingForward ? currentIndex + 1 : currentIndex - 1;
const firstIndex = insideDestination[0].descriptor.index;
const lastIndex = insideDestination[insideDestination.length - 1].descriptor.index;
const upperBound = isInHomeList ? lastIndex : lastIndex + 1;
if (proposedIndex < firstIndex) {
return null;
}
if (proposedIndex > upperBound) {
return null;
}
return proposedIndex;
};
var moveToNextIndex = ({
isMovingForward,
isInHomeList,
draggable: draggable2,
draggables,
destination,
insideDestination,
previousImpact,
viewport,
afterCritical
}) => {
const wasAt = previousImpact.at;
!wasAt ? process.env.NODE_ENV !== "production" ? invariant(false, "Cannot move in direction without previous impact location") : invariant() : void 0;
if (wasAt.type === "REORDER") {
const newIndex2 = fromReorder({
isMovingForward,
isInHomeList,
location: wasAt.destination,
insideDestination
});
if (newIndex2 == null) {
return null;
}
return calculateReorderImpact({
draggable: draggable2,
insideDestination,
destination,
viewport,
last: previousImpact.displaced,
displacedBy: previousImpact.displacedBy,
index: newIndex2
});
}
const newIndex = fromCombine({
isMovingForward,
destination,
displaced: previousImpact.displaced,
draggables,
combine: wasAt.combine,
afterCritical
});
if (newIndex == null) {
return null;
}
return calculateReorderImpact({
draggable: draggable2,
insideDestination,
destination,
viewport,
last: previousImpact.displaced,
displacedBy: previousImpact.displacedBy,
index: newIndex
});
};
var getCombinedItemDisplacement = ({
displaced,
afterCritical,
combineWith,
displacedBy
}) => {
const isDisplaced = Boolean(displaced.visible[combineWith] || displaced.invisible[combineWith]);
if (didStartAfterCritical(combineWith, afterCritical)) {
return isDisplaced ? origin : negate(displacedBy.point);
}
return isDisplaced ? displacedBy.point : origin;
};
var whenCombining = ({
afterCritical,
impact,
draggables
}) => {
const combine2 = tryGetCombine(impact);
!combine2 ? process.env.NODE_ENV !== "production" ? invariant() : invariant() : void 0;
const combineWith = combine2.draggableId;
const center = draggables[combineWith].page.borderBox.center;
const displaceBy = getCombinedItemDisplacement({
displaced: impact.displaced,
afterCritical,
combineWith,
displacedBy: impact.displacedBy
});
return add(center, displaceBy);
};
const distanceFromStartToBorderBoxCenter = (axis, box) => box.margin[axis.start] + box.borderBox[axis.size] / 2;
const distanceFromEndToBorderBoxCenter = (axis, box) => box.margin[axis.end] + box.borderBox[axis.size] / 2;
const getCrossAxisBorderBoxCenter = (axis, target, isMoving) => target[axis.crossAxisStart] + isMoving.margin[axis.crossAxisStart] + isMoving.borderBox[axis.crossAxisSize] / 2;
const goAfter = ({
axis,
moveRelativeTo,
isMoving
}) => patch(axis.line, moveRelativeTo.marginBox[axis.end] + distanceFromStartToBorderBoxCenter(axis, isMoving), getCrossAxisBorderBoxCenter(axis, moveRelativeTo.marginBox, isMoving));
const goBefore = ({
axis,
moveRelativeTo,
isMoving
}) => patch(axis.line, moveRelativeTo.marginBox[axis.start] - distanceFromEndToBorderBoxCenter(axis, isMoving), getCrossAxisBorderBoxCenter(axis, moveRelativeTo.marginBox, isMoving));
const goIntoStart = ({
axis,
moveInto,
isMoving
}) => patch(axis.line, moveInto.contentBox[axis.start] + distanceFromStartToBorderBoxCenter(axis, isMoving), getCrossAxisBorderBoxCenter(axis, moveInto.contentBox, isMoving));
var whenReordering = ({
impact,
draggable: draggable2,
draggables,
droppable: droppable2,
afterCritical
}) => {
const insideDestination = getDraggablesInsideDroppable(droppable2.descriptor.id, draggables);
const draggablePage = draggable2.page;
const axis = droppable2.axis;
if (!insideDestination.length) {
return goIntoStart({
axis,
moveInto: droppable2.page,
isMoving: draggablePage
});
}
const {
displaced,
displacedBy
} = impact;
const closestAfter = displaced.all[0];
if (closestAfter) {
const closest2 = draggables[closestAfter];
if (didStartAfterCritical(closestAfter, afterCritical)) {
return goBefore({
axis,
moveRelativeTo: closest2.page,
isMoving: draggablePage
});
}
const withDisplacement = offset(closest2.page, displacedBy.point);
return goBefore({
axis,
moveRelativeTo: withDisplacement,
isMoving: draggablePage
});
}
const last = insideDestination[insideDestination.length - 1];
if (last.descriptor.id === draggable2.descriptor.id) {
return draggablePage.borderBox.center;
}
if (didStartAfterCritical(last.descriptor.id, afterCritical)) {
const page = offset(last.page, negate(afterCritical.displacedBy.point));
return goAfter({
axis,
moveRelativeTo: page,
isMoving: draggablePage
});
}
return goAfter({
axis,
moveRelativeTo: last.page,
isMoving: draggablePage
});
};
var withDroppableDisplacement = (droppable2, point) => {
const frame2 = droppable2.frame;
if (!frame2) {
return point;
}
return add(point, frame2.scroll.diff.displacement);
};
const getResultWithoutDroppableDisplacement = ({
impact,
draggable: draggable2,
droppable: droppable2,
draggables,
afterCritical
}) => {
const original = draggable2.page.borderBox.center;
const at = impact.at;
if (!droppable2) {
return original;
}
if (!at) {
return original;
}
if (at.type === "REORDER") {
return whenReordering({
impact,
draggable: draggable2,
draggables,
droppable: droppable2,
afterCritical
});
}
return whenCombining({
impact,
draggables,
afterCritical
});
};
var getPageBorderBoxCenterFromImpact = (args) => {
const withoutDisplacement = getResultWithoutDroppableDisplacement(args);
const droppable2 = args.droppable;
const withDisplacement = droppable2 ? withDroppableDisplacement(droppable2, withoutDisplacement) : withoutDisplacement;
return withDisplacement;
};
var scrollViewport = (viewport, newScroll) => {
const diff = subtract(newScroll, viewport.scroll.initial);
const displacement = negate(diff);
const frame2 = getRect({
top: newScroll.y,
bottom: newScroll.y + viewport.frame.height,
left: newScroll.x,
right: newScroll.x + viewport.frame.width
});
const updated = {
frame: frame2,
scroll: {
initial: viewport.scroll.initial,
max: viewport.scroll.max,
current: newScroll,
diff: {
value: diff,
displacement
}
}
};
return updated;
};
function getDraggables$1(ids, draggables) {
return ids.map((id) => draggables[id]);
}
function tryGetVisible(id, groups) {
for (let i = 0; i < groups.length; i++) {
const displacement = groups[i].visible[id];
if (displacement) {
return displacement;
}
}
return null;
}
var speculativelyIncrease = ({
impact,
viewport,
destination,
draggables,
maxScrollChange
}) => {
const scrolledViewport = scrollViewport(viewport, add(viewport.scroll.current, maxScrollChange));
const scrolledDroppable = destination.frame ? scrollDroppable(destination, add(destination.frame.scroll.current, maxScrollChange)) : destination;
const last = impact.displaced;
const withViewportScroll = getDisplacementGroups({
afterDragging: getDraggables$1(last.all, draggables),
destination,
displacedBy: impact.displacedBy,
viewport: scrolledViewport.frame,
last,
forceShouldAnimate: false
});
const withDroppableScroll2 = getDisplacementGroups({
afterDragging: getDraggables$1(last.all, draggables),
destination: scrolledDroppable,
displacedBy: impact.displacedBy,
viewport: viewport.frame,
last,
forceShouldAnimate: false
});
const invisible = {};
const visible = {};
const groups = [last, withViewportScroll, withDroppableScroll2];
last.all.forEach((id) => {
const displacement = tryGetVisible(id, groups);
if (displacement) {
visible[id] = displacement;
return;
}
invisible[id] = true;
});
const newImpact = {
...impact,
displaced: {
all: last.all,
invisible,
visible
}
};
return newImpact;
};
var withViewportDisplacement = (viewport, point) => add(viewport.scroll.diff.displacement, point);
var getClientFromPageBorderBoxCenter = ({
pageBorderBoxCenter,
draggable: draggable2,
viewport
}) => {
const withoutPageScrollChange = withViewportDisplacement(viewport, pageBorderBoxCenter);
const offset3 = subtract(withoutPageScrollChange, draggable2.page.borderBox.center);
return add(draggable2.client.borderBox.center, offset3);
};
var isTotallyVisibleInNewLocation = ({
draggable: draggable2,
destination,
newPageBorderBoxCenter,
viewport,
withDroppableDisplacement: withDroppableDisplacement2,
onlyOnMainAxis = false
}) => {
const changeNeeded = subtract(newPageBorderBoxCenter, draggable2.page.borderBox.center);
const shifted = offsetByPosition(draggable2.page.borderBox, changeNeeded);
const args = {
target: shifted,
destination,
withDroppableDisplacement: withDroppableDisplacement2,
viewport
};
return onlyOnMainAxis ? isTotallyVisibleOnAxis(args) : isTotallyVisible(args);
};
var moveToNextPlace = ({
isMovingForward,
draggable: draggable2,
destination,
draggables,
previousImpact,
viewport,
previousPageBorderBoxCenter,
previousClientSelection,
afterCritical
}) => {
if (!destination.isEnabled) {
return null;
}
const insideDestination = getDraggablesInsideDroppable(destination.descriptor.id, draggables);
const isInHomeList = isHomeOf(draggable2, destination);
const impact = moveToNextCombine({
isMovingForward,
draggable: draggable2,
destination,
insideDestination,
previousImpact
}) || moveToNextIndex({
isMovingForward,
isInHomeList,
draggable: draggable2,
draggables,
destination,
insideDestination,
previousImpact,
viewport,
afterCritical
});
if (!impact) {
return null;
}
const pageBorderBoxCenter = getPageBorderBoxCenterFromImpact({
impact,
draggable: draggable2,
droppable: destination,
draggables,
afterCritical
});
const isVisibleInNewLocation = isTotallyVisibleInNewLocation({
draggable: draggable2,
destination,
newPageBorderBoxCenter: pageBorderBoxCenter,
viewport: viewport.frame,
withDroppableDisplacement: false,
onlyOnMainAxis: true
});
if (isVisibleInNewLocation) {
const clientSelection = getClientFromPageBorderBoxCenter({
pageBorderBoxCenter,
draggable: draggable2,
viewport
});
return {
clientSelection,
impact,
scrollJumpRequest: null
};
}
const distance2 = subtract(pageBorderBoxCenter, previousPageBorderBoxCenter);
const cautious = speculativelyIncrease({
impact,
viewport,
destination,
draggables,
maxScrollChange: distance2
});
return {
clientSelection: previousClientSelection,
impact: cautious,
scrollJumpRequest: distance2
};
};
const getKnownActive = (droppable2) => {
const rect = droppable2.subject.active;
!rect ? process.env.NODE_ENV !== "production" ? invariant(false, "Cannot get clipped area from droppable") : invariant() : void 0;
return rect;
};
var getBestCrossAxisDroppable = ({
isMovingForward,
pageBorderBoxCenter,
source,
droppables,
viewport
}) => {
const active = source.subject.active;
if (!active) {
return null;
}
const axis = source.axis;
const isBetweenSourceClipped = isWithin(active[axis.start], active[axis.end]);
const candidates = toDroppableList(droppables).filter((droppable2) => droppable2 !== source).filter((droppable2) => droppable2.isEnabled).filter((droppable2) => Boolean(droppable2.subject.active)).filter((droppable2) => isPartiallyVisibleThroughFrame(viewport.frame)(getKnownActive(droppable2))).filter((droppable2) => {
const activeOfTarget = getKnownActive(droppable2);
if (isMovingForward) {
return active[axis.crossAxisEnd] < activeOfTarget[axis.crossAxisEnd];
}
return activeOfTarget[axis.crossAxisStart] < active[axis.crossAxisStart];
}).filter((droppable2) => {
const activeOfTarget = getKnownActive(droppable2);
const isBetweenDestinationClipped = isWithin(activeOfTarget[axis.start], activeOfTarget[axis.end]);
return isBetweenSourceClipped(activeOfTarget[axis.start]) || isBetweenSourceClipped(activeOfTarget[axis.end]) || isBetweenDestinationClipped(active[axis.start]) || isBetweenDestinationClipped(active[axis.end]);
}).sort((a, b) => {
const first = getKnownActive(a)[axis.crossAxisStart];
const second = getKnownActive(b)[axis.crossAxisStart];
if (isMovingForward) {
return first - second;
}
return second - first;
}).filter((droppable2, index, array) => getKnownActive(droppable2)[axis.crossAxisStart] === getKnownActive(array[0])[axis.crossAxisStart]);
if (!candidates.length) {
return null;
}
if (candidates.length === 1) {
return candidates[0];
}
const contains = candidates.filter((droppable2) => {
const isWithinDroppable = isWithin(getKnownActive(droppable2)[axis.start], getKnownActive(droppable2)[axis.end]);
return isWithinDroppable(pageBorderBoxCenter[axis.line]);
});
if (contains.length === 1) {
return contains[0];
}
if (contains.length > 1) {
return contains.sort((a, b) => getKnownActive(a)[axis.start] - getKnownActive(b)[axis.start])[0];
}
return candidates.sort((a, b) => {
const first = closest$1(pageBorderBoxCenter, getCorners(getKnownActive(a)));
const second = closest$1(pageBorderBoxCenter, getCorners(getKnownActive(b)));
if (first !== second) {
return first - second;
}
return getKnownActive(a)[axis.start] - getKnownActive(b)[axis.start];
})[0];
};
const getCurrentPageBorderBoxCenter = (draggable2, afterCritical) => {
const original = draggable2.page.borderBox.center;
return didStartAfterCritical(draggable2.descriptor.id, afterCritical) ? subtract(original, afterCritical.displacedBy.point) : original;
};
const getCurrentPageBorderBox = (draggable2, afterCritical) => {
const original = draggable2.page.borderBox;
return didStartAfterCritical(draggable2.descriptor.id, afterCritical) ? offsetByPosition(original, negate(afterCritical.displacedBy.point)) : original;
};
var getClosestDraggable = ({
pageBorderBoxCenter,
viewport,
destination,
insideDestination,
afterCritical
}) => {
const sorted = insideDestination.filter((draggable2) => isTotallyVisible({
target: getCurrentPageBorderBox(draggable2, afterCritical),
destination,
viewport: viewport.frame,
withDroppableDisplacement: true
})).sort((a, b) => {
const distanceToA = distance(pageBorderBoxCenter, withDroppableDisplacement(destination, getCurrentPageBorderBoxCenter(a, afterCritical)));
const distanceToB = distance(pageBorderBoxCenter, withDroppableDisplacement(destination, getCurrentPageBorderBoxCenter(b, afterCritical)));
if (distanceToA < distanceToB) {
return -1;
}
if (distanceToB < distanceToA) {
return 1;
}
return a.descriptor.index - b.descriptor.index;
});
return sorted[0] || null;
};
var getDisplacedBy = memoizeOne(function getDisplacedBy2(axis, displaceBy) {
const displacement = displaceBy[axis.line];
return {
value: displacement,
point: patch(axis.line, displacement)
};
});
const getRequiredGrowthForPlaceholder = (droppable2, placeholderSize, draggables) => {
const axis = droppable2.axis;
if (droppable2.descriptor.mode === "virtual") {
return patch(axis.line, placeholderSize[axis.line]);
}
const availableSpace = droppable2.subject.page.contentBox[axis.size];
const insideDroppable = getDraggablesInsideDroppable(droppable2.descriptor.id, draggables);
const spaceUsed = insideDroppable.reduce((sum, dimension) => sum + dimension.client.marginBox[axis.size], 0);
const requiredSpace = spaceUsed + placeholderSize[axis.line];
const needsToGrowBy = requiredSpace - availableSpace;
if (needsToGrowBy <= 0) {
return null;
}
return patch(axis.line, needsToGrowBy);
};
const withMaxScroll = (frame2, max) => ({
...frame2,
scroll: {
...frame2.scroll,
max
}
});
const addPlaceholder = (droppable2, draggable2, draggables) => {
const frame2 = droppable2.frame;
!!isHomeOf(draggable2, droppable2) ? process.env.NODE_ENV !== "production" ? invariant(false, "Should not add placeholder space to home list") : invariant() : void 0;
!!droppable2.subject.withPlaceholder ? process.env.NODE_ENV !== "production" ? invariant(false, "Cannot add placeholder size to a subject when it already has one") : invariant() : void 0;
const placeholderSize = getDisplacedBy(droppable2.axis, draggable2.displaceBy).point;
const requiredGrowth = getRequiredGrowthForPlaceholder(droppable2, placeholderSize, draggables);
const added = {
placeholderSize,
increasedBy: requiredGrowth,
oldFrameMaxScroll: droppable2.frame ? droppable2.frame.scroll.max : null
};
if (!frame2) {
const subject2 = getSubject({
page: droppable2.subject.page,
withPlaceholder: added,
axis: droppable2.axis,
frame: droppable2.frame
});
return {
...droppable2,
subject: subject2
};
}
const maxScroll = requiredGrowth ? add(frame2.scroll.max, requiredGrowth) : frame2.scroll.max;
const newFrame = withMaxScroll(frame2, maxScroll);
const subject = getSubject({
page: droppable2.subject.page,
withPlaceholder: added,
axis: droppable2.axis,
frame: newFrame
});
return {
...droppable2,
subject,
frame: newFrame
};
};
const removePlaceholder = (droppable2) => {
const added = droppable2.subject.withPlaceholder;
!added ? process.env.NODE_ENV !== "production" ? invariant(false, "Cannot remove placeholder form subject when there was none") : invariant() : void 0;
const frame2 = droppable2.frame;
if (!frame2) {
const subject2 = getSubject({
page: droppable2.subject.page,
axis: droppable2.axis,
frame: null,
withPlaceholder: null
});
return {
...droppable2,
subject: subject2
};
}
const oldMaxScroll = added.oldFrameMaxScroll;
!oldMaxScroll ? process.env.NODE_ENV !== "production" ? invariant(false, "Expected droppable with frame to have old max frame scroll when removing placeholder") : invariant() : void 0;
const newFrame = withMaxScroll(frame2, oldMaxScroll);
const subject = getSubject({
page: droppable2.subject.page,
axis: droppable2.axis,
frame: newFrame,
withPlaceholder: null
});
return {
...droppable2,
subject,
frame: newFrame
};
};
var moveToNewDroppable = ({
previousPageBorderBoxCenter,
moveRelativeTo,
insideDestination,
draggable: draggable2,
draggables,
destination,
viewport,
afterCritical
}) => {
if (!moveRelativeTo) {
if (insideDestination.length) {
return null;
}
const proposed = {
displaced: emptyGroups,
displacedBy: noDisplacedBy,
at: {
type: "REORDER",
destination: {
droppableId: destination.descriptor.id,
index: 0
}
}
};
const proposedPageBorderBoxCenter = getPageBorderBoxCenterFromImpact({
impact: proposed,
draggable: draggable2,
droppable: destination,
draggables,
afterCritical
});
const withPlaceholder = isHomeOf(draggable2, destination) ? destination : addPlaceholder(destination, draggable2, draggables);
const isVisibleInNewLocation = isTotallyVisibleInNewLocation({
draggable: draggable2,
destination: withPlaceholder,
newPageBorderBoxCenter: proposedPageBorderBoxCenter,
viewport: viewport.frame,
withDroppableDisplacement: false,
onlyOnMainAxis: true
});
return isVisibleInNewLocation ? proposed : null;
}
const isGoingBeforeTarget = Boolean(previousPageBorderBoxCenter[destination.axis.line] <= moveRelativeTo.page.borderBox.center[destination.axis.line]);
const proposedIndex = (() => {
const relativeTo = moveRelativeTo.descriptor.index;
if (moveRelativeTo.descriptor.id === draggable2.descriptor.id) {
return relativeTo;
}
if (isGoingBeforeTarget) {
return relativeTo;
}
return relativeTo + 1;
})();
const displacedBy = getDisplacedBy(destination.axis, draggable2.displaceBy);
return calculateReorderImpact({
draggable: draggable2,
insideDestination,
destination,
viewport,
displacedBy,
last: emptyGroups,
index: proposedIndex
});
};
var moveCrossAxis = ({
isMovingForward,
previousPageBorderBoxCenter,
draggable: draggable2,
isOver,
draggables,
droppables,
viewport,
afterCritical
}) => {
const destination = getBestCrossAxisDroppable({
isMovingForward,
pageBorderBoxCenter: previousPageBorderBoxCenter,
source: isOver,
droppables,
viewport
});
if (!destination) {
return null;
}
const insideDestination = getDraggablesInsideDroppable(destination.descriptor.id, draggables);
const moveRelativeTo = getClosestDraggable({
pageBorderBoxCenter: previousPageBorderBoxCenter,
viewport,
destination,
insideDestination,
afterCritical
});
const impact = moveToNewDroppable({
previousPageBorderBoxCenter,
destination,
draggable: draggable2,
draggables,
moveRelativeTo,
insideDestination,
viewport,
afterCritical
});
if (!impact) {
return null;
}
const pageBorderBoxCenter = getPageBorderBoxCenterFromImpact({
impact,
draggable: draggable2,
droppable: destination,
draggables,
afterCritical
});
const clientSelection = getClientFromPageBorderBoxCenter({
pageBorderBoxCenter,
draggable: draggable2,
viewport
});
return {
clientSelection,
impact,
scrollJumpRequest: null
};
};
var whatIsDraggedOver = (impact) => {
const at = impact.at;
if (!at) {
return null;
}
if (at.type === "REORDER") {
return at.destination.droppableId;
}
return at.combine.droppableId;
};
const getDroppableOver$1 = (impact, droppables) => {
const id = whatIsDraggedOver(impact);
return id ? droppables[id] : null;
};
var moveInDirection = ({
state,
type
}) => {
const isActuallyOver = getDroppableOver$1(state.impact, state.dimensions.droppables);
const isMainAxisMovementAllowed = Boolean(isActuallyOver);
const home2 = state.dimensions.droppables[state.critical.droppable.id];
const isOver = isActuallyOver || home2;
const direction = isOver.axis.direction;
const isMovingOnMainAxis = direction === "vertical" && (type === "MOVE_UP" || type === "MOVE_DOWN") || direction === "horizontal" && (type === "MOVE_LEFT" || type === "MOVE_RIGHT");
if (isMovingOnMainAxis && !isMainAxisMovementAllowed) {
return null;
}
const isMovingForward = type === "MOVE_DOWN" || type === "MOVE_RIGHT";
const draggable2 = state.dimensions.draggables[state.critical.draggable.id];
const previousPageBorderBoxCenter = state.current.page.borderBoxCenter;
const {
draggables,
droppables
} = state.dimensions;
return isMovingOnMainAxis ? moveToNextPlace({
isMovingForward,
previousPageBorderBoxCenter,
draggable: draggable2,
destination: isOver,
draggables,
viewport: state.viewport,
previousClientSelection: state.current.client.selection,
previousImpact: state.impact,
afterCritical: state.afterCritical
}) : moveCrossAxis({
isMovingForward,
previousPageBorderBoxCenter,
draggable: draggable2,
isOver,
draggables,
droppables,
viewport: state.viewport,
afterCritical: state.afterCritical
});
};
function isMovementAllowed(state) {
return state.phase === "DRAGGING" || state.phase === "COLLECTING";
}
function isPositionInFrame(frame2) {
const isWithinVertical = isWithin(frame2.top, frame2.bottom);
const isWithinHorizontal = isWithin(frame2.left, frame2.right);
return function run(point) {
return isWithinVertical(point.y) && isWithinHorizontal(point.x);
};
}
function getHasOverlap(first, second) {
return first.left < second.right && first.right > second.left && first.top < second.bottom && first.bottom > second.top;
}
function getFurthestAway({
pageBorderBox,
draggable: draggable2,
candidates
}) {
const startCenter = draggable2.page.borderBox.center;
const sorted = candidates.map((candidate) => {
const axis = candidate.axis;
const target = patch(candidate.axis.line, pageBorderBox.center[axis.line], candidate.page.borderBox.center[axis.crossAxisLine]);
return {
id: candidate.descriptor.id,
distance: distance(startCenter, target)
};
}).sort((a, b) => b.distance - a.distance);
return sorted[0] ? sorted[0].id : null;
}
function getDroppableOver({
pageBorderBox,
draggable: draggable2,
droppables
}) {
const candidates = toDroppableList(droppables).filter((item) => {
if (!item.isEnabled) {
return false;
}
const active = item.subject.active;
if (!active) {
return false;
}
if (!getHasOverlap(pageBorderBox, active)) {
return false;
}
if (isPositionInFrame(active)(pageBorderBox.center)) {
return true;
}
const axis = item.axis;
const childCenter = active.center[axis.crossAxisLine];
const crossAxisStart = pageBorderBox[axis.crossAxisStart];
const crossAxisEnd = pageBorderBox[axis.crossAxisEnd];
const isContained = isWithin(active[axis.crossAxisStart], active[axis.crossAxisEnd]);
const isStartContained = isContained(crossAxisStart);
const isEndContained = isContained(crossAxisEnd);
if (!isStartContained && !isEndContained) {
return true;
}
if (isStartContained) {
return crossAxisStart < childCenter;
}
return crossAxisEnd > childCenter;
});
if (!candidates.length) {
return null;
}
if (candidates.length === 1) {
return candidates[0].descriptor.id;
}
return getFurthestAway({
pageBorderBox,
draggable: draggable2,
candidates
});
}
const offsetRectByPosition = (rect, point) => getRect(offsetByPosition(rect, point));
var withDroppableScroll = (droppable2, area) => {
const frame2 = droppable2.frame;
if (!frame2) {
return area;
}
return offsetRectByPosition(area, frame2.scroll.diff.value);
};
function getIsDisplaced({
displaced,
id
}) {
return Boolean(displaced.visible[id] || displaced.invisible[id]);
}
function atIndex({
draggable: draggable2,
closest: closest2,
inHomeList
}) {
if (!closest2) {
return null;
}
if (!inHomeList) {
return closest2.descriptor.index;
}
if (closest2.descriptor.index > draggable2.descriptor.index) {
return closest2.descriptor.index - 1;
}
return closest2.descriptor.index;
}
var getReorderImpact = ({
pageBorderBoxWithDroppableScroll: targetRect,
draggable: draggable2,
destination,
insideDestination,
last,
viewport,
afterCritical
}) => {
const axis = destination.axis;
const displacedBy = getDisplacedBy(destination.axis, draggable2.displaceBy);
const displacement = displacedBy.value;
const targetStart = targetRect[axis.start];
const targetEnd = targetRect[axis.end];
const withoutDragging = removeDraggableFromList(draggable2, insideDestination);
const closest2 = withoutDragging.find((child) => {
const id = child.descriptor.id;
const childCenter = child.page.borderBox.center[axis.line];
const didStartAfterCritical$1 = didStartAfterCritical(id, afterCritical);
const isDisplaced = getIsDisplaced({
displaced: last,
id
});
if (didStartAfterCritical$1) {
if (isDisplaced) {
return targetEnd <= childCenter;
}
return targetStart < childCenter - displacement;
}
if (isDisplaced) {
return targetEnd <= childCenter + displacement;
}
return targetStart < childCenter;
}) || null;
const newIndex = atIndex({
draggable: draggable2,
closest: closest2,
inHomeList: isHomeOf(draggable2, destination)
});
return calculateReorderImpact({
draggable: draggable2,
insideDestination,
destination,
viewport,
last,
displacedBy,
index: newIndex
});
};
const combineThresholdDivisor = 4;
var getCombineImpact = ({
draggable: draggable2,
pageBorderBoxWithDroppableScroll: targetRect,
previousImpact,
destination,
insideDestination,
afterCritical
}) => {
if (!destination.isCombineEnabled) {
return null;
}
const axis = destination.axis;
const displacedBy = getDisplacedBy(destination.axis, draggable2.displaceBy);
const displacement = displacedBy.value;
const targetStart = targetRect[axis.start];
const targetEnd = targetRect[axis.end];
const withoutDragging = removeDraggableFromList(draggable2, insideDestination);
const combineWith = withoutDragging.find((child) => {
const id = child.descriptor.id;
const childRect = child.page.borderBox;
const childSize = childRect[axis.size];
const threshold = childSize / combineThresholdDivisor;
const didStartAfterCritical$1 = didStartAfterCritical(id, afterCritical);
const isDisplaced = getIsDisplaced({
displaced: previousImpact.displaced,
id
});
if (didStartAfterCritical$1) {
if (isDisplaced) {
return targetEnd > childRect[axis.start] + threshold && targetEnd < childRect[axis.end] - threshold;
}
return targetStart > childRect[axis.start] - displacement + threshold && targetStart < childRect[axis.end] - displacement - threshold;
}
if (isDisplaced) {
return targetEnd > childRect[axis.start] + displacement + threshold && targetEnd < childRect[axis.end] + displacement - threshold;
}
return targetStart > childRect[axis.start] + threshold && targetStart < childRect[axis.end] - threshold;
});
if (!combineWith) {
return null;
}
const impact = {
displacedBy,
displaced: previousImpact.displaced,
at: {
type: "COMBINE",
combine: {
draggableId: combineWith.descriptor.id,
droppableId: destination.descriptor.id
}
}
};
return impact;
};
var getDragImpact = ({
pageOffset,
draggable: draggable2,
draggables,
droppables,
previousImpact,
viewport,
afterCritical
}) => {
const pageBorderBox = offsetRectByPosition(draggable2.page.borderBox, pageOffset);
const destinationId = getDroppableOver({
pageBorderBox,
draggable: draggable2,
droppables
});
if (!destinationId) {
return noImpact$1;
}
const destination = droppables[destinationId];
const insideDestination = getDraggablesInsideDroppable(destination.descriptor.id, draggables);
const pageBorderBoxWithDroppableScroll = withDroppableScroll(destination, pageBorderBox);
return getCombineImpact({
pageBorderBoxWithDroppableScroll,
draggable: draggable2,
previousImpact,
destination,
insideDestination,
afterCritical
}) || getReorderImpact({
pageBorderBoxWithDroppableScroll,
draggable: draggable2,
destination,
insideDestination,
last: previousImpact.displaced,
viewport,
afterCritical
});
};
var patchDroppableMap = (droppables, updated) => ({
...droppables,
[updated.descriptor.id]: updated
});
const clearUnusedPlaceholder = ({
previousImpact,
impact,
droppables
}) => {
const last = whatIsDraggedOver(previousImpact);
const now = whatIsDraggedOver(impact);
if (!last) {
return droppables;
}
if (last === now) {
return droppables;
}
const lastDroppable = droppables[last];
if (!lastDroppable.subject.withPlaceholder) {
return droppables;
}
const updated = removePlaceholder(lastDroppable);
return patchDroppableMap(droppables, updated);
};
var recomputePlaceholders = ({
draggable: draggable2,
draggables,
droppables,
previousImpact,
impact
}) => {
const cleaned = clearUnusedPlaceholder({
previousImpact,
impact,
droppables
});
const isOver = whatIsDraggedOver(impact);
if (!isOver) {
return cleaned;
}
const droppable2 = droppables[isOver];
if (isHomeOf(draggable2, droppable2)) {
return cleaned;
}
if (droppable2.subject.withPlaceholder) {
return cleaned;
}
const patched = addPlaceholder(droppable2, draggable2, draggables);
return patchDroppableMap(cleaned, patched);
};
var update = ({
state,
clientSelection: forcedClientSelection,
dimensions: forcedDimensions,
viewport: forcedViewport,
impact: forcedImpact,
scrollJumpRequest
}) => {
const viewport = forcedViewport || state.viewport;
const dimensions = forcedDimensions || state.dimensions;
const clientSelection = forcedClientSelection || state.current.client.selection;
const offset3 = subtract(clientSelection, state.initial.client.selection);
const client = {
offset: offset3,
selection: clientSelection,
borderBoxCenter: add(state.initial.client.borderBoxCenter, offset3)
};
const page = {
selection: add(client.selection, viewport.scroll.current),
borderBoxCenter: add(client.borderBoxCenter, viewport.scroll.current),
offset: add(client.offset, viewport.scroll.diff.value)
};
const current = {
client,
page
};
if (state.phase === "COLLECTING") {
return {
...state,
dimensions,
viewport,
current
};
}
const draggable2 = dimensions.draggables[state.critical.draggable.id];
const newImpact = forcedImpact || getDragImpact({
pageOffset: page.offset,
draggable: draggable2,
draggables: dimensions.draggables,
droppables: dimensions.droppables,
previousImpact: state.impact,
viewport,
afterCritical: state.afterCritical
});
const withUpdatedPlaceholders = recomputePlaceholders({
draggable: draggable2,
impact: newImpact,
previousImpact: state.impact,
draggables: dimensions.draggables,
droppables: dimensions.droppables
});
const result = {
...state,
current,
dimensions: {
draggables: dimensions.draggables,
droppables: withUpdatedPlaceholders
},
impact: newImpact,
viewport,
scrollJumpRequest: scrollJumpRequest || null,
forceShouldAnimate: scrollJumpRequest ? false : null
};
return result;
};
function getDraggables(ids, draggables) {
return ids.map((id) => draggables[id]);
}
var recompute = ({
impact,
viewport,
draggables,
destination,
forceShouldAnimate
}) => {
const last = impact.displaced;
const afterDragging = getDraggables(last.all, draggables);
const displaced = getDisplacementGroups({
afterDragging,
destination,
displacedBy: impact.displacedBy,
viewport: viewport.frame,
forceShouldAnimate,
last
});
return {
...impact,
displaced
};
};
var getClientBorderBoxCenter = ({
impact,
draggable: draggable2,
droppable: droppable2,
draggables,
viewport,
afterCritical
}) => {
const pageBorderBoxCenter = getPageBorderBoxCenterFromImpact({
impact,
draggable: draggable2,
draggables,
droppable: droppable2,
afterCritical
});
return getClientFromPageBorderBoxCenter({
pageBorderBoxCenter,
draggable: draggable2,
viewport
});
};
var refreshSnap = ({
state,
dimensions: forcedDimensions,
viewport: forcedViewport
}) => {
!(state.movementMode === "SNAP") ? process.env.NODE_ENV !== "production" ? invariant() : invariant() : void 0;
const needsVisibilityCheck = state.impact;
const viewport = forcedViewport || state.viewport;
const dimensions = forcedDimensions || state.dimensions;
const {
draggables,
droppables
} = dimensions;
const draggable2 = draggables[state.critical.draggable.id];
const isOver = whatIsDraggedOver(needsVisibilityCheck);
!isOver ? process.env.NODE_ENV !== "production" ? invariant(false, "Must be over a destination in SNAP movement mode") : invariant() : void 0;
const destination = droppables[isOver];
const impact = recompute({
impact: needsVisibilityCheck,
viewport,
destination,
draggables
});
const clientSelection = getClientBorderBoxCenter({
impact,
draggable: draggable2,
droppable: destination,
draggables,
viewport,
afterCritical: state.afterCritical
});
return update({
impact,
clientSelection,
state,
dimensions,
viewport
});
};
var getHomeLocation = (descriptor) => ({
index: descriptor.index,
droppableId: descriptor.droppableId
});
var getLiftEffect = ({
draggable: draggable2,
home: home2,
draggables,
viewport
}) => {
const displacedBy = getDisplacedBy(home2.axis, draggable2.displaceBy);
const insideHome = getDraggablesInsideDroppable(home2.descriptor.id, draggables);
const rawIndex = insideHome.indexOf(draggable2);
!(rawIndex !== -1) ? process.env.NODE_ENV !== "production" ? invariant(false, "Expected draggable to be inside home list") : invariant() : void 0;
const afterDragging = insideHome.slice(rawIndex + 1);
const effected = afterDragging.reduce((previous, item) => {
previous[item.descriptor.id] = true;
return previous;
}, {});
const afterCritical = {
inVirtualList: home2.descriptor.mode === "virtual",
displacedBy,
effected
};
const displaced = getDisplacementGroups({
afterDragging,
destination: home2,
displacedBy,
last: null,
viewport: viewport.frame,
forceShouldAnimate: false
});
const impact = {
displaced,
displacedBy,
at: {
type: "REORDER",
destination: getHomeLocation(draggable2.descriptor)
}
};
return {
impact,
afterCritical
};
};
var patchDimensionMap = (dimensions, updated) => ({
draggables: dimensions.draggables,
droppables: patchDroppableMap(dimensions.droppables, updated)
});
const start = (key) => {
if (process.env.NODE_ENV !== "production") {
{
return;
}
}
};
const finish = (key) => {
if (process.env.NODE_ENV !== "production") {
{
return;
}
}
};
var offsetDraggable = ({
draggable: draggable2,
offset: offset$1,
initialWindowScroll
}) => {
const client = offset(draggable2.client, offset$1);
const page = withScroll(client, initialWindowScroll);
const moved = {
...draggable2,
placeholder: {
...draggable2.placeholder,
client
},
client,
page
};
return moved;
};
var getFrame = (droppable2) => {
const frame2 = droppable2.frame;
!frame2 ? process.env.NODE_ENV !== "production" ? invariant(false, "Expected Droppable to have a frame") : invariant() : void 0;
return frame2;
};
var adjustAdditionsForScrollChanges = ({
additions,
updatedDroppables,
viewport
}) => {
const windowScrollChange = viewport.scroll.diff.value;
return additions.map((draggable2) => {
const droppableId = draggable2.descriptor.droppableId;
const modified = updatedDroppables[droppableId];
const frame2 = getFrame(modified);
const droppableScrollChange = frame2.scroll.diff.value;
const totalChange = add(windowScrollChange, droppableScrollChange);
const moved = offsetDraggable({
draggable: draggable2,
offset: totalChange,
initialWindowScroll: viewport.scroll.initial
});
return moved;
});
};
var publishWhileDraggingInVirtual = ({
state,
published
}) => {
start();
const withScrollChange = published.modified.map((update2) => {
const existing = state.dimensions.droppables[update2.droppableId];
const scrolled = scrollDroppable(existing, update2.scroll);
return scrolled;
});
const droppables = {
...state.dimensions.droppables,
...toDroppableMap(withScrollChange)
};
const updatedAdditions = toDraggableMap(adjustAdditionsForScrollChanges({
additions: published.additions,
updatedDroppables: droppables,
viewport: state.viewport
}));
const draggables = {
...state.dimensions.draggables,
...updatedAdditions
};
published.removals.forEach((id) => {
delete draggables[id];
});
const dimensions = {
droppables,
draggables
};
const wasOverId = whatIsDraggedOver(state.impact);
const wasOver = wasOverId ? dimensions.droppables[wasOverId] : null;
const draggable2 = dimensions.draggables[state.critical.draggable.id];
const home2 = dimensions.droppables[state.critical.droppable.id];
const {
impact: onLiftImpact,
afterCritical
} = getLiftEffect({
draggable: draggable2,
home: home2,
draggables,
viewport: state.viewport
});
const previousImpact = wasOver && wasOver.isCombineEnabled ? state.impact : onLiftImpact;
const impact = getDragImpact({
pageOffset: state.current.page.offset,
draggable: dimensions.draggables[state.critical.draggable.id],
draggables: dimensions.draggables,
droppables: dimensions.droppables,
previousImpact,
viewport: state.viewport,
afterCritical
});
finish();
const draggingState = {
...state,
phase: "DRAGGING",
impact,
onLiftImpact,
dimensions,
afterCritical,
forceShouldAnimate: false
};
if (state.phase === "COLLECTING") {
return draggingState;
}
const dropPending2 = {
...draggingState,
phase: "DROP_PENDING",
reason: state.reason,
isWaiting: false
};
return dropPending2;
};
const isSnapping = (state) => state.movementMode === "SNAP";
const postDroppableChange = (state, updated, isEnabledChanging) => {
const dimensions = patchDimensionMap(state.dimensions, updated);
if (!isSnapping(state) || isEnabledChanging) {
return update({
state,
dimensions
});
}
return refreshSnap({
state,
dimensions
});
};
function removeScrollJumpRequest(state) {
if (state.isDragging && state.movementMode === "SNAP") {
return {
...state,
scrollJumpRequest: null
};
}
return state;
}
const idle$2 = {
phase: "IDLE",
completed: null,
shouldFlush: false
};
var reducer = (state = idle$2, action) => {
if (action.type === "FLUSH") {
return {
...idle$2,
shouldFlush: true
};
}
if (action.type === "INITIAL_PUBLISH") {
!(state.phase === "IDLE") ? process.env.NODE_ENV !== "production" ? invariant(false, "INITIAL_PUBLISH must come after a IDLE phase") : invariant() : void 0;
const {
critical,
clientSelection,
viewport,
dimensions,
movementMode
} = action.payload;
const draggable2 = dimensions.draggables[critical.draggable.id];
const home2 = dimensions.droppables[critical.droppable.id];
const client = {
selection: clientSelection,
borderBoxCenter: draggable2.client.borderBox.center,
offset: origin
};
const initial = {
client,
page: {
selection: add(client.selection, viewport.scroll.initial),
borderBoxCenter: add(client.selection, viewport.scroll.initial),
offset: add(client.selection, viewport.scroll.diff.value)
}
};
const isWindowScrollAllowed = toDroppableList(dimensions.droppables).every((item) => !item.isFixedOnPage);
const {
impact,
afterCritical
} = getLiftEffect({
draggable: draggable2,
home: home2,
draggables: dimensions.draggables,
viewport
});
const result = {
phase: "DRAGGING",
isDragging: true,
critical,
movementMode,
dimensions,
initial,
current: initial,
isWindowScrollAllowed,
impact,
afterCritical,
onLiftImpact: impact,
viewport,
scrollJumpRequest: null,
forceShouldAnimate: null
};
return result;
}
if (action.type === "COLLECTION_STARTING") {
if (state.phase === "COLLECTING" || state.phase === "DROP_PENDING") {
return state;
}
!(state.phase === "DRAGGING") ? process.env.NODE_ENV !== "production" ? invariant(false, `Collection cannot start from phase ${state.phase}`) : invariant() : void 0;
const result = {
...state,
phase: "COLLECTING"
};
return result;
}
if (action.type === "PUBLISH_WHILE_DRAGGING") {
!(state.phase === "COLLECTING" || state.phase === "DROP_PENDING") ? process.env.NODE_ENV !== "production" ? invariant(false, `Unexpected ${action.type} received in phase ${state.phase}`) : invariant() : void 0;
return publishWhileDraggingInVirtual({
state,
published: action.payload
});
}
if (action.type === "MOVE") {
if (state.phase === "DROP_PENDING") {
return state;
}
!isMovementAllowed(state) ? process.env.NODE_ENV !== "production" ? invariant(false, `${action.type} not permitted in phase ${state.phase}`) : invariant() : void 0;
const {
client: clientSelection
} = action.payload;
if (isEqual$1(clientSelection, state.current.client.selection)) {
return state;
}
return update({
state,
clientSelection,
impact: isSnapping(state) ? state.impact : null
});
}
if (action.type === "UPDATE_DROPPABLE_SCROLL") {
if (state.phase === "DROP_PENDING") {
return removeScrollJumpRequest(state);
}
if (state.phase === "COLLECTING") {
return removeScrollJumpRequest(state);
}
!isMovementAllowed(state) ? process.env.NODE_ENV !== "production" ? invariant(false, `${action.type} not permitted in phase ${state.phase}`) : invariant() : void 0;
const {
id,
newScroll
} = action.payload;
const target = state.dimensions.droppables[id];
if (!target) {
return state;
}
const scrolled = scrollDroppable(target, newScroll);
return postDroppableChange(state, scrolled, false);
}
if (action.type === "UPDATE_DROPPABLE_IS_ENABLED") {
if (state.phase === "DROP_PENDING") {
return state;
}
!isMovementAllowed(state) ? process.env.NODE_ENV !== "production" ? invariant(false, `Attempting to move in an unsupported phase ${state.phase}`) : invariant() : void 0;
const {
id,
isEnabled
} = action.payload;
const target = state.dimensions.droppables[id];
!target ? process.env.NODE_ENV !== "production" ? invariant(false, `Cannot find Droppable[id: ${id}] to toggle its enabled state`) : invariant() : void 0;
!(target.isEnabled !== isEnabled) ? process.env.NODE_ENV !== "production" ? invariant(false, `Trying to set droppable isEnabled to ${String(isEnabled)}
but it is already ${String(target.isEnabled)}`) : invariant() : void 0;
const updated = {
...target,
isEnabled
};
return postDroppableChange(state, updated, true);
}
if (action.type === "UPDATE_DROPPABLE_IS_COMBINE_ENABLED") {
if (state.phase === "DROP_PENDING") {
return state;
}
!isMovementAllowed(state) ? process.env.NODE_ENV !== "production" ? invariant(false, `Attempting to move in an unsupported phase ${state.phase}`) : invariant() : void 0;
const {
id,
isCombineEnabled
} = action.payload;
const target = state.dimensions.droppables[id];
!target ? process.env.NODE_ENV !== "production" ? invariant(false, `Cannot find Droppable[id: ${id}] to toggle its isCombineEnabled state`) : invariant() : void 0;
!(target.isCombineEnabled !== isCombineEnabled) ? process.env.NODE_ENV !== "production" ? invariant(false, `Trying to set droppable isCombineEnabled to ${String(isCombineEnabled)}
but it is already ${String(target.isCombineEnabled)}`) : invariant() : void 0;
const updated = {
...target,
isCombineEnabled
};
return postDroppableChange(state, updated, true);
}
if (action.type === "MOVE_BY_WINDOW_SCROLL") {
if (state.phase === "DROP_PENDING" || state.phase === "DROP_ANIMATING") {
return state;
}
!isMovementAllowed(state) ? process.env.NODE_ENV !== "production" ? invariant(false, `Cannot move by window in phase ${state.phase}`) : invariant() : void 0;
!state.isWindowScrollAllowed ? process.env.NODE_ENV !== "production" ? invariant(false, "Window scrolling is currently not supported for fixed lists") : invariant() : void 0;
const newScroll = action.payload.newScroll;
if (isEqual$1(state.viewport.scroll.current, newScroll)) {
return removeScrollJumpRequest(state);
}
const viewport = scrollViewport(state.viewport, newScroll);
if (isSnapping(state)) {
return refreshSnap({
state,
viewport
});
}
return update({
state,
viewport
});
}
if (action.type === "UPDATE_VIEWPORT_MAX_SCROLL") {
if (!isMovementAllowed(state)) {
return state;
}
const maxScroll = action.payload.maxScroll;
if (isEqual$1(maxScroll, state.viewport.scroll.max)) {
return state;
}
const withMaxScroll2 = {
...state.viewport,
scroll: {
...state.viewport.scroll,
max: maxScroll
}
};
return {
...state,
viewport: withMaxScroll2
};
}
if (action.type === "MOVE_UP" || action.type === "MOVE_DOWN" || action.type === "MOVE_LEFT" || action.type === "MOVE_RIGHT") {
if (state.phase === "COLLECTING" || state.phase === "DROP_PENDING") {
return state;
}
!(state.phase === "DRAGGING") ? process.env.NODE_ENV !== "production" ? invariant(false, `${action.type} received while not in DRAGGING phase`) : invariant() : void 0;
const result = moveInDirection({
state,
type: action.type
});
if (!result) {
return state;
}
return update({
state,
impact: result.impact,
clientSelection: result.clientSelection,
scrollJumpRequest: result.scrollJumpRequest
});
}
if (action.type === "DROP_PENDING") {
const reason = action.payload.reason;
!(state.phase === "COLLECTING") ? process.env.NODE_ENV !== "production" ? invariant(false, "Can only move into the DROP_PENDING phase from the COLLECTING phase") : invariant() : void 0;
const newState = {
...state,
phase: "DROP_PENDING",
isWaiting: true,
reason
};
return newState;
}
if (action.type === "DROP_ANIMATE") {
const {
completed,
dropDuration,
newHomeClientOffset
} = action.payload;
!(state.phase === "DRAGGING" || state.phase === "DROP_PENDING") ? process.env.NODE_ENV !== "production" ? invariant(false, `Cannot animate drop from phase ${state.phase}`) : invariant() : void 0;
const result = {
phase: "DROP_ANIMATING",
completed,
dropDuration,
newHomeClientOffset,
dimensions: state.dimensions
};
return result;
}
if (action.type === "DROP_COMPLETE") {
const {
completed
} = action.payload;
return {
phase: "IDLE",
completed,
shouldFlush: false
};
}
return state;
};
const beforeInitialCapture = (args) => ({
type: "BEFORE_INITIAL_CAPTURE",
payload: args
});
const lift$1 = (args) => ({
type: "LIFT",
payload: args
});
const initialPublish = (args) => ({
type: "INITIAL_PUBLISH",
payload: args
});
const publishWhileDragging = (args) => ({
type: "PUBLISH_WHILE_DRAGGING",
payload: args
});
const collectionStarting = () => ({
type: "COLLECTION_STARTING",
payload: null
});
const updateDroppableScroll = (args) => ({
type: "UPDATE_DROPPABLE_SCROLL",
payload: args
});
const updateDroppableIsEnabled = (args) => ({
type: "UPDATE_DROPPABLE_IS_ENABLED",
payload: args
});
const updateDroppableIsCombineEnabled = (args) => ({
type: "UPDATE_DROPPABLE_IS_COMBINE_ENABLED",
payload: args
});
const move = (args) => ({
type: "MOVE",
payload: args
});
const moveByWindowScroll = (args) => ({
type: "MOVE_BY_WINDOW_SCROLL",
payload: args
});
const updateViewportMaxScroll = (args) => ({
type: "UPDATE_VIEWPORT_MAX_SCROLL",
payload: args
});
const moveUp = () => ({
type: "MOVE_UP",
payload: null
});
const moveDown = () => ({
type: "MOVE_DOWN",
payload: null
});
const moveRight = () => ({
type: "MOVE_RIGHT",
payload: null
});
const moveLeft = () => ({
type: "MOVE_LEFT",
payload: null
});
const flush = () => ({
type: "FLUSH",
payload: null
});
const animateDrop = (args) => ({
type: "DROP_ANIMATE",
payload: args
});
const completeDrop = (args) => ({
type: "DROP_COMPLETE",
payload: args
});
const drop$1 = (args) => ({
type: "DROP",
payload: args
});
const dropPending = (args) => ({
type: "DROP_PENDING",
payload: args
});
const dropAnimationFinished = () => ({
type: "DROP_ANIMATION_FINISHED",
payload: null
});
function checkIndexes(insideDestination) {
if (insideDestination.length <= 1) {
return;
}
const indexes = insideDestination.map((d) => d.descriptor.index);
const errors = {};
for (let i = 1; i < indexes.length; i++) {
const current = indexes[i];
const previous = indexes[i - 1];
if (current !== previous + 1) {
errors[current] = true;
}
}
if (!Object.keys(errors).length) {
return;
}
const formatted = indexes.map((index) => {
const hasError = Boolean(errors[index]);
return hasError ? `[🔥${index}]` : `${index}`;
}).join(", ");
process.env.NODE_ENV !== "production" ? warning(`
Detected non-consecutive <Draggable /> indexes.
(This can cause unexpected bugs)
${formatted}
`) : void 0;
}
function validateDimensions(critical, dimensions) {
if (process.env.NODE_ENV !== "production") {
const insideDestination = getDraggablesInsideDroppable(critical.droppable.id, dimensions.draggables);
checkIndexes(insideDestination);
}
}
var lift = (marshal) => ({
getState,
dispatch
}) => (next) => (action) => {
if (action.type !== "LIFT") {
next(action);
return;
}
const {
id,
clientSelection,
movementMode
} = action.payload;
const initial = getState();
if (initial.phase === "DROP_ANIMATING") {
dispatch(completeDrop({
completed: initial.completed
}));
}
!(getState().phase === "IDLE") ? process.env.NODE_ENV !== "production" ? invariant(false, "Unexpected phase to start a drag") : invariant() : void 0;
dispatch(flush());
dispatch(beforeInitialCapture({
draggableId: id,
movementMode
}));
const scrollOptions = {
shouldPublishImmediately: movementMode === "SNAP"
};
const request = {
draggableId: id,
scrollOptions
};
const {
critical,
dimensions,
viewport
} = marshal.startPublishing(request);
validateDimensions(critical, dimensions);
dispatch(initialPublish({
critical,
dimensions,
clientSelection,
movementMode,
viewport
}));
};
var style = (marshal) => () => (next) => (action) => {
if (action.type === "INITIAL_PUBLISH") {
marshal.dragging();
}
if (action.type === "DROP_ANIMATE") {
marshal.dropping(action.payload.completed.result.reason);
}
if (action.type === "FLUSH" || action.type === "DROP_COMPLETE") {
marshal.resting();
}
next(action);
};
const curves = {
outOfTheWay: "cubic-bezier(0.2, 0, 0, 1)",
drop: "cubic-bezier(.2,1,.1,1)"
};
const combine = {
opacity: {
drop: 0,
combining: 0.7
},
scale: {
drop: 0.75
}
};
const timings = {
outOfTheWay: 0.2,
minDropTime: 0.33,
maxDropTime: 0.55
};
const outOfTheWayTiming = `${timings.outOfTheWay}s ${curves.outOfTheWay}`;
const transitions = {
fluid: `opacity ${outOfTheWayTiming}`,
snap: `transform ${outOfTheWayTiming}, opacity ${outOfTheWayTiming}`,
drop: (duration) => {
const timing = `${duration}s ${curves.drop}`;
return `transform ${timing}, opacity ${timing}`;
},
outOfTheWay: `transform ${outOfTheWayTiming}`,
placeholder: `height ${outOfTheWayTiming}, width ${outOfTheWayTiming}, margin ${outOfTheWayTiming}`
};
const moveTo = (offset3) => isEqual$1(offset3, origin) ? void 0 : `translate(${offset3.x}px, ${offset3.y}px)`;
const transforms = {
moveTo,
drop: (offset3, isCombining) => {
const translate = moveTo(offset3);
if (!translate) {
return void 0;
}
if (!isCombining) {
return translate;
}
return `${translate} scale(${combine.scale.drop})`;
}
};
const {
minDropTime,
maxDropTime
} = timings;
const dropTimeRange = maxDropTime - minDropTime;
const maxDropTimeAtDistance = 1500;
const cancelDropModifier = 0.6;
var getDropDuration = ({
current,
destination,
reason
}) => {
const distance$1 = distance(current, destination);
if (distance$1 <= 0) {
return minDropTime;
}
if (distance$1 >= maxDropTimeAtDistance) {
return maxDropTime;
}
const percentage = distance$1 / maxDropTimeAtDistance;
const duration = minDropTime + dropTimeRange * percentage;
const withDuration = reason === "CANCEL" ? duration * cancelDropModifier : duration;
return Number(withDuration.toFixed(2));
};
var getNewHomeClientOffset = ({
impact,
draggable: draggable2,
dimensions,
viewport,
afterCritical
}) => {
const {
draggables,
droppables
} = dimensions;
const droppableId = whatIsDraggedOver(impact);
const destination = droppableId ? droppables[droppableId] : null;
const home2 = droppables[draggable2.descriptor.droppableId];
const newClientCenter = getClientBorderBoxCenter({
impact,
draggable: draggable2,
draggables,
afterCritical,
droppable: destination || home2,
viewport
});
const offset3 = subtract(newClientCenter, draggable2.client.borderBox.center);
return offset3;
};
var getDropImpact = ({
draggables,
reason,
lastImpact,
home: home2,
viewport,
onLiftImpact
}) => {
if (!lastImpact.at || reason !== "DROP") {
const recomputedHomeImpact = recompute({
draggables,
impact: onLiftImpact,
destination: home2,
viewport,
forceShouldAnimate: true
});
return {
impact: recomputedHomeImpact,
didDropInsideDroppable: false
};
}
if (lastImpact.at.type === "REORDER") {
return {
impact: lastImpact,
didDropInsideDroppable: true
};
}
const withoutMovement = {
...lastImpact,
displaced: emptyGroups
};
return {
impact: withoutMovement,
didDropInsideDroppable: true
};
};
const dropMiddleware = ({
getState,
dispatch
}) => (next) => (action) => {
if (action.type !== "DROP") {
next(action);
return;
}
const state = getState();
const reason = action.payload.reason;
if (state.phase === "COLLECTING") {
dispatch(dropPending({
reason
}));
return;
}
if (state.phase === "IDLE") {
return;
}
const isWaitingForDrop = state.phase === "DROP_PENDING" && state.isWaiting;
!!isWaitingForDrop ? process.env.NODE_ENV !== "production" ? invariant(false, "A DROP action occurred while DROP_PENDING and still waiting") : invariant() : void 0;
!(state.phase === "DRAGGING" || state.phase === "DROP_PENDING") ? process.env.NODE_ENV !== "production" ? invariant(false, `Cannot drop in phase: ${state.phase}`) : invariant() : void 0;
const critical = state.critical;
const dimensions = state.dimensions;
const draggable2 = dimensions.draggables[state.critical.draggable.id];
const {
impact,
didDropInsideDroppable
} = getDropImpact({
reason,
lastImpact: state.impact,
afterCritical: state.afterCritical,
onLiftImpact: state.onLiftImpact,
home: state.dimensions.droppables[state.critical.droppable.id],
viewport: state.viewport,
draggables: state.dimensions.draggables
});
const destination = didDropInsideDroppable ? tryGetDestination(impact) : null;
const combine2 = didDropInsideDroppable ? tryGetCombine(impact) : null;
const source = {
index: critical.draggable.index,
droppableId: critical.droppable.id
};
const result = {
draggableId: draggable2.descriptor.id,
type: draggable2.descriptor.type,
source,
reason,
mode: state.movementMode,
destination,
combine: combine2
};
const newHomeClientOffset = getNewHomeClientOffset({
impact,
draggable: draggable2,
dimensions,
viewport: state.viewport,
afterCritical: state.afterCritical
});
const completed = {
critical: state.critical,
afterCritical: state.afterCritical,
result,
impact
};
const isAnimationRequired = !isEqual$1(state.current.client.offset, newHomeClientOffset) || Boolean(result.combine);
if (!isAnimationRequired) {
dispatch(completeDrop({
completed
}));
return;
}
const dropDuration = getDropDuration({
current: state.current.client.offset,
destination: newHomeClientOffset,
reason
});
const args = {
newHomeClientOffset,
dropDuration,
completed
};
dispatch(animateDrop(args));
};
var drop = dropMiddleware;
var getWindowScroll2 = () => ({
x: window.pageXOffset,
y: window.pageYOffset
});
function getWindowScrollBinding(update2) {
return {
eventName: "scroll",
options: {
passive: true,
capture: false
},
fn: (event) => {
if (event.target !== window && event.target !== window.document) {
return;
}
update2();
}
};
}
function getScrollListener({
onWindowScroll
}) {
function updateScroll() {
onWindowScroll(getWindowScroll2());
}
const scheduled = rafSchd(updateScroll);
const binding = getWindowScrollBinding(scheduled);
let unbind = noop$2;
function isActive2() {
return unbind !== noop$2;
}
function start2() {
!!isActive2() ? process.env.NODE_ENV !== "production" ? invariant(false, "Cannot start scroll listener when already active") : invariant() : void 0;
unbind = bindEvents(window, [binding]);
}
function stop() {
!isActive2() ? process.env.NODE_ENV !== "production" ? invariant(false, "Cannot stop scroll listener when not active") : invariant() : void 0;
scheduled.cancel();
unbind();
unbind = noop$2;
}
return {
start: start2,
stop,
isActive: isActive2
};
}
const shouldEnd = (action) => action.type === "DROP_COMPLETE" || action.type === "DROP_ANIMATE" || action.type === "FLUSH";
const scrollListener = (store) => {
const listener = getScrollListener({
onWindowScroll: (newScroll) => {
store.dispatch(moveByWindowScroll({
newScroll
}));
}
});
return (next) => (action) => {
if (!listener.isActive() && action.type === "INITIAL_PUBLISH") {
listener.start();
}
if (listener.isActive() && shouldEnd(action)) {
listener.stop();
}
next(action);
};
};
var scrollListener$1 = scrollListener;
var getExpiringAnnounce = (announce) => {
let wasCalled = false;
let isExpired = false;
const timeoutId = setTimeout(() => {
isExpired = true;
});
const result = (message) => {
if (wasCalled) {
process.env.NODE_ENV !== "production" ? warning("Announcement already made. Not making a second announcement") : void 0;
return;
}
if (isExpired) {
process.env.NODE_ENV !== "production" ? warning(`
Announcements cannot be made asynchronously.
Default message has already been announced.
`) : void 0;
return;
}
wasCalled = true;
announce(message);
clearTimeout(timeoutId);
};
result.wasCalled = () => wasCalled;
return result;
};
var getAsyncMarshal = () => {
const entries = [];
const execute2 = (timerId) => {
const index = entries.findIndex((item) => item.timerId === timerId);
!(index !== -1) ? process.env.NODE_ENV !== "production" ? invariant(false, "Could not find timer") : invariant() : void 0;
const [entry] = entries.splice(index, 1);
entry.callback();
};
const add2 = (fn) => {
const timerId = setTimeout(() => execute2(timerId));
const entry = {
timerId,
callback: fn
};
entries.push(entry);
};
const flush2 = () => {
if (!entries.length) {
return;
}
const shallow = [...entries];
entries.length = 0;
shallow.forEach((entry) => {
clearTimeout(entry.timerId);
entry.callback();
});
};
return {
add: add2,
flush: flush2
};
};
const areLocationsEqual = (first, second) => {
if (first == null && second == null) {
return true;
}
if (first == null || second == null) {
return false;
}
return first.droppableId === second.droppableId && first.index === second.index;
};
const isCombineEqual = (first, second) => {
if (first == null && second == null) {
return true;
}
if (first == null || second == null) {
return false;
}
return first.draggableId === second.draggableId && first.droppableId === second.droppableId;
};
const isCriticalEqual = (first, second) => {
if (first === second) {
return true;
}
const isDraggableEqual = first.draggable.id === second.draggable.id && first.draggable.droppableId === second.draggable.droppableId && first.draggable.type === second.draggable.type && first.draggable.index === second.draggable.index;
const isDroppableEqual = first.droppable.id === second.droppable.id && first.droppable.type === second.droppable.type;
return isDraggableEqual && isDroppableEqual;
};
const withTimings = (key, fn) => {
start();
fn();
finish();
};
const getDragStart = (critical, mode) => ({
draggableId: critical.draggable.id,
type: critical.droppable.type,
source: {
droppableId: critical.droppable.id,
index: critical.draggable.index
},
mode
});
function execute(responder, data, announce, getDefaultMessage) {
if (!responder) {
announce(getDefaultMessage(data));
return;
}
const willExpire = getExpiringAnnounce(announce);
const provided = {
announce: willExpire
};
responder(data, provided);
if (!willExpire.wasCalled()) {
announce(getDefaultMessage(data));
}
}
var getPublisher = (getResponders, announce) => {
const asyncMarshal = getAsyncMarshal();
let dragging = null;
const beforeCapture = (draggableId, mode) => {
!!dragging ? process.env.NODE_ENV !== "production" ? invariant(false, "Cannot fire onBeforeCapture as a drag start has already been published") : invariant() : void 0;
withTimings("onBeforeCapture", () => {
const fn = getResponders().onBeforeCapture;
if (fn) {
const before = {
draggableId,
mode
};
fn(before);
}
});
};
const beforeStart = (critical, mode) => {
!!dragging ? process.env.NODE_ENV !== "production" ? invariant(false, "Cannot fire onBeforeDragStart as a drag start has already been published") : invariant() : void 0;
withTimings("onBeforeDragStart", () => {
const fn = getResponders().onBeforeDragStart;
if (fn) {
fn(getDragStart(critical, mode));
}
});
};
const start2 = (critical, mode) => {
!!dragging ? process.env.NODE_ENV !== "production" ? invariant(false, "Cannot fire onBeforeDragStart as a drag start has already been published") : invariant() : void 0;
const data = getDragStart(critical, mode);
dragging = {
mode,
lastCritical: critical,
lastLocation: data.source,
lastCombine: null
};
asyncMarshal.add(() => {
withTimings("onDragStart", () => execute(getResponders().onDragStart, data, announce, preset$1.onDragStart));
});
};
const update2 = (critical, impact) => {
const location = tryGetDestination(impact);
const combine2 = tryGetCombine(impact);
!dragging ? process.env.NODE_ENV !== "production" ? invariant(false, "Cannot fire onDragMove when onDragStart has not been called") : invariant() : void 0;
const hasCriticalChanged = !isCriticalEqual(critical, dragging.lastCritical);
if (hasCriticalChanged) {
dragging.lastCritical = critical;
}
const hasLocationChanged = !areLocationsEqual(dragging.lastLocation, location);
if (hasLocationChanged) {
dragging.lastLocation = location;
}
const hasGroupingChanged = !isCombineEqual(dragging.lastCombine, combine2);
if (hasGroupingChanged) {
dragging.lastCombine = combine2;
}
if (!hasCriticalChanged && !hasLocationChanged && !hasGroupingChanged) {
return;
}
const data = {
...getDragStart(critical, dragging.mode),
combine: combine2,
destination: location
};
asyncMarshal.add(() => {
withTimings("onDragUpdate", () => execute(getResponders().onDragUpdate, data, announce, preset$1.onDragUpdate));
});
};
const flush2 = () => {
!dragging ? process.env.NODE_ENV !== "production" ? invariant(false, "Can only flush responders while dragging") : invariant() : void 0;
asyncMarshal.flush();
};
const drop2 = (result) => {
!dragging ? process.env.NODE_ENV !== "production" ? invariant(false, "Cannot fire onDragEnd when there is no matching onDragStart") : invariant() : void 0;
dragging = null;
withTimings("onDragEnd", () => execute(getResponders().onDragEnd, result, announce, preset$1.onDragEnd));
};
const abort = () => {
if (!dragging) {
return;
}
const result = {
...getDragStart(dragging.lastCritical, dragging.mode),
combine: null,
destination: null,
reason: "CANCEL"
};
drop2(result);
};
return {
beforeCapture,
beforeStart,
start: start2,
update: update2,
flush: flush2,
drop: drop2,
abort
};
};
var responders = (getResponders, announce) => {
const publisher = getPublisher(getResponders, announce);
return (store) => (next) => (action) => {
if (action.type === "BEFORE_INITIAL_CAPTURE") {
publisher.beforeCapture(action.payload.draggableId, action.payload.movementMode);
return;
}
if (action.type === "INITIAL_PUBLISH") {
const critical = action.payload.critical;
publisher.beforeStart(critical, action.payload.movementMode);
next(action);
publisher.start(critical, action.payload.movementMode);
return;
}
if (action.type === "DROP_COMPLETE") {
const result = action.payload.completed.result;
publisher.flush();
next(action);
publisher.drop(result);
return;
}
next(action);
if (action.type === "FLUSH") {
publisher.abort();
return;
}
const state = store.getState();
if (state.phase === "DRAGGING") {
publisher.update(state.critical, state.impact);
}
};
};
const dropAnimationFinishMiddleware = (store) => (next) => (action) => {
if (action.type !== "DROP_ANIMATION_FINISHED") {
next(action);
return;
}
const state = store.getState();
!(state.phase === "DROP_ANIMATING") ? process.env.NODE_ENV !== "production" ? invariant(false, "Cannot finish a drop animating when no drop is occurring") : invariant() : void 0;
store.dispatch(completeDrop({
completed: state.completed
}));
};
var dropAnimationFinish = dropAnimationFinishMiddleware;
const dropAnimationFlushOnScrollMiddleware = (store) => {
let unbind = null;
let frameId = null;
function clear() {
if (frameId) {
cancelAnimationFrame(frameId);
frameId = null;
}
if (unbind) {
unbind();
unbind = null;
}
}
return (next) => (action) => {
if (action.type === "FLUSH" || action.type === "DROP_COMPLETE" || action.type === "DROP_ANIMATION_FINISHED") {
clear();
}
next(action);
if (action.type !== "DROP_ANIMATE") {
return;
}
const binding = {
eventName: "scroll",
options: {
capture: true,
passive: false,
once: true
},
fn: function flushDropAnimation() {
const state = store.getState();
if (state.phase === "DROP_ANIMATING") {
store.dispatch(dropAnimationFinished());
}
}
};
frameId = requestAnimationFrame(() => {
frameId = null;
unbind = bindEvents(window, [binding]);
});
};
};
var dropAnimationFlushOnScroll = dropAnimationFlushOnScrollMiddleware;
var dimensionMarshalStopper = (marshal) => () => (next) => (action) => {
if (action.type === "DROP_COMPLETE" || action.type === "FLUSH" || action.type === "DROP_ANIMATE") {
marshal.stopPublishing();
}
next(action);
};
var focus = (marshal) => {
let isWatching = false;
return () => (next) => (action) => {
if (action.type === "INITIAL_PUBLISH") {
isWatching = true;
marshal.tryRecordFocus(action.payload.critical.draggable.id);
next(action);
marshal.tryRestoreFocusRecorded();
return;
}
next(action);
if (!isWatching) {
return;
}
if (action.type === "FLUSH") {
isWatching = false;
marshal.tryRestoreFocusRecorded();
return;
}
if (action.type === "DROP_COMPLETE") {
isWatching = false;
const result = action.payload.completed.result;
if (result.combine) {
marshal.tryShiftRecord(result.draggableId, result.combine.draggableId);
}
marshal.tryRestoreFocusRecorded();
}
};
};
const shouldStop = (action) => action.type === "DROP_COMPLETE" || action.type === "DROP_ANIMATE" || action.type === "FLUSH";
var autoScroll = (autoScroller) => (store) => (next) => (action) => {
if (shouldStop(action)) {
autoScroller.stop();
next(action);
return;
}
if (action.type === "INITIAL_PUBLISH") {
next(action);
const state = store.getState();
!(state.phase === "DRAGGING") ? process.env.NODE_ENV !== "production" ? invariant(false, "Expected phase to be DRAGGING after INITIAL_PUBLISH") : invariant() : void 0;
autoScroller.start(state);
return;
}
next(action);
autoScroller.scroll(store.getState());
};
const pendingDrop = (store) => (next) => (action) => {
next(action);
if (action.type !== "PUBLISH_WHILE_DRAGGING") {
return;
}
const postActionState = store.getState();
if (postActionState.phase !== "DROP_PENDING") {
return;
}
if (postActionState.isWaiting) {
return;
}
store.dispatch(drop$1({
reason: postActionState.reason
}));
};
var pendingDrop$1 = pendingDrop;
const composeEnhancers = process.env.NODE_ENV !== "production" && typeof window !== "undefined" && window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ ? window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__({
name: "@hello-pangea/dnd"
}) : compose;
var createStore = ({
dimensionMarshal,
focusMarshal,
styleMarshal,
getResponders,
announce,
autoScroller
}) => createStore$1(reducer, composeEnhancers(applyMiddleware(style(styleMarshal), dimensionMarshalStopper(dimensionMarshal), lift(dimensionMarshal), drop, dropAnimationFinish, dropAnimationFlushOnScroll, pendingDrop$1, autoScroll(autoScroller), scrollListener$1, focus(focusMarshal), responders(getResponders, announce))));
const clean$1 = () => ({
additions: {},
removals: {},
modified: {}
});
function createPublisher({
registry,
callbacks
}) {
let staging = clean$1();
let frameId = null;
const collect = () => {
if (frameId) {
return;
}
callbacks.collectionStarting();
frameId = requestAnimationFrame(() => {
frameId = null;
start();
const {
additions,
removals,
modified
} = staging;
const added = Object.keys(additions).map((id) => registry.draggable.getById(id).getDimension(origin)).sort((a, b) => a.descriptor.index - b.descriptor.index);
const updated = Object.keys(modified).map((id) => {
const entry = registry.droppable.getById(id);
const scroll2 = entry.callbacks.getScrollWhileDragging();
return {
droppableId: id,
scroll: scroll2
};
});
const result = {
additions: added,
removals: Object.keys(removals),
modified: updated
};
staging = clean$1();
finish();
callbacks.publish(result);
});
};
const add2 = (entry) => {
const id = entry.descriptor.id;
staging.additions[id] = entry;
staging.modified[entry.descriptor.droppableId] = true;
if (staging.removals[id]) {
delete staging.removals[id];
}
collect();
};
const remove = (entry) => {
const descriptor = entry.descriptor;
staging.removals[descriptor.id] = true;
staging.modified[descriptor.droppableId] = true;
if (staging.additions[descriptor.id]) {
delete staging.additions[descriptor.id];
}
collect();
};
const stop = () => {
if (!frameId) {
return;
}
cancelAnimationFrame(frameId);
frameId = null;
staging = clean$1();
};
return {
add: add2,
remove,
stop
};
}
var getMaxScroll = ({
scrollHeight,
scrollWidth,
height,
width
}) => {
const maxScroll = subtract({
x: scrollWidth,
y: scrollHeight
}, {
x: width,
y: height
});
const adjustedMaxScroll = {
x: Math.max(0, maxScroll.x),
y: Math.max(0, maxScroll.y)
};
return adjustedMaxScroll;
};
var getDocumentElement = () => {
const doc = document.documentElement;
!doc ? process.env.NODE_ENV !== "production" ? invariant(false, "Cannot find document.documentElement") : invariant() : void 0;
return doc;
};
var getMaxWindowScroll = () => {
const doc = getDocumentElement();
const maxScroll = getMaxScroll({
scrollHeight: doc.scrollHeight,
scrollWidth: doc.scrollWidth,
width: doc.clientWidth,
height: doc.clientHeight
});
return maxScroll;
};
var getViewport = () => {
const scroll2 = getWindowScroll2();
const maxScroll = getMaxWindowScroll();
const top = scroll2.y;
const left = scroll2.x;
const doc = getDocumentElement();
const width = doc.clientWidth;
const height = doc.clientHeight;
const right = left + width;
const bottom = top + height;
const frame2 = getRect({
top,
left,
right,
bottom
});
const viewport = {
frame: frame2,
scroll: {
initial: scroll2,
current: scroll2,
max: maxScroll,
diff: {
value: origin,
displacement: origin
}
}
};
return viewport;
};
var getInitialPublish = ({
critical,
scrollOptions,
registry
}) => {
start();
const viewport = getViewport();
const windowScroll = viewport.scroll.current;
const home2 = critical.droppable;
const droppables = registry.droppable.getAllByType(home2.type).map((entry) => entry.callbacks.getDimensionAndWatchScroll(windowScroll, scrollOptions));
const draggables = registry.draggable.getAllByType(critical.draggable.type).map((entry) => entry.getDimension(windowScroll));
const dimensions = {
draggables: toDraggableMap(draggables),
droppables: toDroppableMap(droppables)
};
finish();
const result = {
dimensions,
critical,
viewport
};
return result;
};
function shouldPublishUpdate(registry, dragging, entry) {
if (entry.descriptor.id === dragging.id) {
return false;
}
if (entry.descriptor.type !== dragging.type) {
return false;
}
const home2 = registry.droppable.getById(entry.descriptor.droppableId);
if (home2.descriptor.mode !== "virtual") {
process.env.NODE_ENV !== "production" ? warning(`
You are attempting to add or remove a Draggable [id: ${entry.descriptor.id}]
while a drag is occurring. This is only supported for virtual lists.
See https://github.com/hello-pangea/dnd/blob/main/docs/patterns/virtual-lists.md
`) : void 0;
return false;
}
return true;
}
var createDimensionMarshal = (registry, callbacks) => {
let collection = null;
const publisher = createPublisher({
callbacks: {
publish: callbacks.publishWhileDragging,
collectionStarting: callbacks.collectionStarting
},
registry
});
const updateDroppableIsEnabled2 = (id, isEnabled) => {
!registry.droppable.exists(id) ? process.env.NODE_ENV !== "production" ? invariant(false, `Cannot update is enabled flag of Droppable ${id} as it is not registered`) : invariant() : void 0;
if (!collection) {
return;
}
callbacks.updateDroppableIsEnabled({
id,
isEnabled
});
};
const updateDroppableIsCombineEnabled2 = (id, isCombineEnabled) => {
if (!collection) {
return;
}
!registry.droppable.exists(id) ? process.env.NODE_ENV !== "production" ? invariant(false, `Cannot update isCombineEnabled flag of Droppable ${id} as it is not registered`) : invariant() : void 0;
callbacks.updateDroppableIsCombineEnabled({
id,
isCombineEnabled
});
};
const updateDroppableScroll2 = (id, newScroll) => {
if (!collection) {
return;
}
!registry.droppable.exists(id) ? process.env.NODE_ENV !== "production" ? invariant(false, `Cannot update the scroll on Droppable ${id} as it is not registered`) : invariant() : void 0;
callbacks.updateDroppableScroll({
id,
newScroll
});
};
const scrollDroppable2 = (id, change) => {
if (!collection) {
return;
}
registry.droppable.getById(id).callbacks.scroll(change);
};
const stopPublishing = () => {
if (!collection) {
return;
}
publisher.stop();
const home2 = collection.critical.droppable;
registry.droppable.getAllByType(home2.type).forEach((entry) => entry.callbacks.dragStopped());
collection.unsubscribe();
collection = null;
};
const subscriber = (event) => {
!collection ? process.env.NODE_ENV !== "production" ? invariant(false, "Should only be subscribed when a collection is occurring") : invariant() : void 0;
const dragging = collection.critical.draggable;
if (event.type === "ADDITION") {
if (shouldPublishUpdate(registry, dragging, event.value)) {
publisher.add(event.value);
}
}
if (event.type === "REMOVAL") {
if (shouldPublishUpdate(registry, dragging, event.value)) {
publisher.remove(event.value);
}
}
};
const startPublishing = (request) => {
!!collection ? process.env.NODE_ENV !== "production" ? invariant(false, "Cannot start capturing critical dimensions as there is already a collection") : invariant() : void 0;
const entry = registry.draggable.getById(request.draggableId);
const home2 = registry.droppable.getById(entry.descriptor.droppableId);
const critical = {
draggable: entry.descriptor,
droppable: home2.descriptor
};
const unsubscribe = registry.subscribe(subscriber);
collection = {
critical,
unsubscribe
};
return getInitialPublish({
critical,
registry,
scrollOptions: request.scrollOptions
});
};
const marshal = {
updateDroppableIsEnabled: updateDroppableIsEnabled2,
updateDroppableIsCombineEnabled: updateDroppableIsCombineEnabled2,
scrollDroppable: scrollDroppable2,
updateDroppableScroll: updateDroppableScroll2,
startPublishing,
stopPublishing
};
return marshal;
};
var canStartDrag = (state, id) => {
if (state.phase === "IDLE") {
return true;
}
if (state.phase !== "DROP_ANIMATING") {
return false;
}
if (state.completed.result.draggableId === id) {
return false;
}
return state.completed.result.reason === "DROP";
};
var scrollWindow = (change) => {
window.scrollBy(change.x, change.y);
};
const getScrollableDroppables = memoizeOne((droppables) => toDroppableList(droppables).filter((droppable2) => {
if (!droppable2.isEnabled) {
return false;
}
if (!droppable2.frame) {
return false;
}
return true;
}));
const getScrollableDroppableOver = (target, droppables) => {
const maybe = getScrollableDroppables(droppables).find((droppable2) => {
!droppable2.frame ? process.env.NODE_ENV !== "production" ? invariant(false, "Invalid result") : invariant() : void 0;
return isPositionInFrame(droppable2.frame.pageMarginBox)(target);
}) || null;
return maybe;
};
var getBestScrollableDroppable = ({
center,
destination,
droppables
}) => {
if (destination) {
const dimension2 = droppables[destination];
if (!dimension2.frame) {
return null;
}
return dimension2;
}
const dimension = getScrollableDroppableOver(center, droppables);
return dimension;
};
const defaultAutoScrollerOptions = {
startFromPercentage: 0.25,
maxScrollAtPercentage: 0.05,
maxPixelScroll: 28,
ease: (percentage) => percentage ** 2,
durationDampening: {
stopDampeningAt: 1200,
accelerateAt: 360
},
disabled: false
};
var getDistanceThresholds = (container, axis, getAutoScrollerOptions = () => defaultAutoScrollerOptions) => {
const autoScrollerOptions = getAutoScrollerOptions();
const startScrollingFrom = container[axis.size] * autoScrollerOptions.startFromPercentage;
const maxScrollValueAt = container[axis.size] * autoScrollerOptions.maxScrollAtPercentage;
const thresholds = {
startScrollingFrom,
maxScrollValueAt
};
return thresholds;
};
var getPercentage = ({
startOfRange,
endOfRange,
current
}) => {
const range = endOfRange - startOfRange;
if (range === 0) {
process.env.NODE_ENV !== "production" ? warning(`
Detected distance range of 0 in the fluid auto scroller
This is unexpected and would cause a divide by 0 issue.
Not allowing an auto scroll
`) : void 0;
return 0;
}
const currentInRange = current - startOfRange;
const percentage = currentInRange / range;
return percentage;
};
var minScroll = 1;
var getValueFromDistance = (distanceToEdge, thresholds, getAutoScrollerOptions = () => defaultAutoScrollerOptions) => {
const autoScrollerOptions = getAutoScrollerOptions();
if (distanceToEdge > thresholds.startScrollingFrom) {
return 0;
}
if (distanceToEdge <= thresholds.maxScrollValueAt) {
return autoScrollerOptions.maxPixelScroll;
}
if (distanceToEdge === thresholds.startScrollingFrom) {
return minScroll;
}
const percentageFromMaxScrollValueAt = getPercentage({
startOfRange: thresholds.maxScrollValueAt,
endOfRange: thresholds.startScrollingFrom,
current: distanceToEdge
});
const percentageFromStartScrollingFrom = 1 - percentageFromMaxScrollValueAt;
const scroll2 = autoScrollerOptions.maxPixelScroll * autoScrollerOptions.ease(percentageFromStartScrollingFrom);
return Math.ceil(scroll2);
};
var dampenValueByTime = (proposedScroll, dragStartTime, getAutoScrollerOptions) => {
const autoScrollerOptions = getAutoScrollerOptions();
const accelerateAt = autoScrollerOptions.durationDampening.accelerateAt;
const stopAt = autoScrollerOptions.durationDampening.stopDampeningAt;
const startOfRange = dragStartTime;
const endOfRange = stopAt;
const now = Date.now();
const runTime = now - startOfRange;
if (runTime >= stopAt) {
return proposedScroll;
}
if (runTime < accelerateAt) {
return minScroll;
}
const betweenAccelerateAtAndStopAtPercentage = getPercentage({
startOfRange: accelerateAt,
endOfRange,
current: runTime
});
const scroll2 = proposedScroll * autoScrollerOptions.ease(betweenAccelerateAtAndStopAtPercentage);
return Math.ceil(scroll2);
};
var getValue = ({
distanceToEdge,
thresholds,
dragStartTime,
shouldUseTimeDampening,
getAutoScrollerOptions
}) => {
const scroll2 = getValueFromDistance(distanceToEdge, thresholds, getAutoScrollerOptions);
if (scroll2 === 0) {
return 0;
}
if (!shouldUseTimeDampening) {
return scroll2;
}
return Math.max(dampenValueByTime(scroll2, dragStartTime, getAutoScrollerOptions), minScroll);
};
var getScrollOnAxis = ({
container,
distanceToEdges,
dragStartTime,
axis,
shouldUseTimeDampening,
getAutoScrollerOptions
}) => {
const thresholds = getDistanceThresholds(container, axis, getAutoScrollerOptions);
const isCloserToEnd = distanceToEdges[axis.end] < distanceToEdges[axis.start];
if (isCloserToEnd) {
return getValue({
distanceToEdge: distanceToEdges[axis.end],
thresholds,
dragStartTime,
shouldUseTimeDampening,
getAutoScrollerOptions
});
}
return -1 * getValue({
distanceToEdge: distanceToEdges[axis.start],
thresholds,
dragStartTime,
shouldUseTimeDampening,
getAutoScrollerOptions
});
};
var adjustForSizeLimits = ({
container,
subject,
proposedScroll
}) => {
const isTooBigVertically = subject.height > container.height;
const isTooBigHorizontally = subject.width > container.width;
if (!isTooBigHorizontally && !isTooBigVertically) {
return proposedScroll;
}
if (isTooBigHorizontally && isTooBigVertically) {
return null;
}
return {
x: isTooBigHorizontally ? 0 : proposedScroll.x,
y: isTooBigVertically ? 0 : proposedScroll.y
};
};
const clean = apply((value) => value === 0 ? 0 : value);
var getScroll$1 = ({
dragStartTime,
container,
subject,
center,
shouldUseTimeDampening,
getAutoScrollerOptions
}) => {
const distanceToEdges = {
top: center.y - container.top,
right: container.right - center.x,
bottom: container.bottom - center.y,
left: center.x - container.left
};
const y = getScrollOnAxis({
container,
distanceToEdges,
dragStartTime,
axis: vertical,
shouldUseTimeDampening,
getAutoScrollerOptions
});
const x = getScrollOnAxis({
container,
distanceToEdges,
dragStartTime,
axis: horizontal,
shouldUseTimeDampening,
getAutoScrollerOptions
});
const required2 = clean({
x,
y
});
if (isEqual$1(required2, origin)) {
return null;
}
const limited = adjustForSizeLimits({
container,
subject,
proposedScroll: required2
});
if (!limited) {
return null;
}
return isEqual$1(limited, origin) ? null : limited;
};
const smallestSigned = apply((value) => {
if (value === 0) {
return 0;
}
return value > 0 ? 1 : -1;
});
const getOverlap = /* @__PURE__ */ (() => {
const getRemainder = (target, max) => {
if (target < 0) {
return target;
}
if (target > max) {
return target - max;
}
return 0;
};
return ({
current,
max,
change
}) => {
const targetScroll = add(current, change);
const overlap = {
x: getRemainder(targetScroll.x, max.x),
y: getRemainder(targetScroll.y, max.y)
};
if (isEqual$1(overlap, origin)) {
return null;
}
return overlap;
};
})();
const canPartiallyScroll = ({
max: rawMax,
current,
change
}) => {
const max = {
x: Math.max(current.x, rawMax.x),
y: Math.max(current.y, rawMax.y)
};
const smallestChange = smallestSigned(change);
const overlap = getOverlap({
max,
current,
change: smallestChange
});
if (!overlap) {
return true;
}
if (smallestChange.x !== 0 && overlap.x === 0) {
return true;
}
if (smallestChange.y !== 0 && overlap.y === 0) {
return true;
}
return false;
};
const canScrollWindow = (viewport, change) => canPartiallyScroll({
current: viewport.scroll.current,
max: viewport.scroll.max,
change
});
const getWindowOverlap = (viewport, change) => {
if (!canScrollWindow(viewport, change)) {
return null;
}
const max = viewport.scroll.max;
const current = viewport.scroll.current;
return getOverlap({
current,
max,
change
});
};
const canScrollDroppable = (droppable2, change) => {
const frame2 = droppable2.frame;
if (!frame2) {
return false;
}
return canPartiallyScroll({
current: frame2.scroll.current,
max: frame2.scroll.max,
change
});
};
const getDroppableOverlap = (droppable2, change) => {
const frame2 = droppable2.frame;
if (!frame2) {
return null;
}
if (!canScrollDroppable(droppable2, change)) {
return null;
}
return getOverlap({
current: frame2.scroll.current,
max: frame2.scroll.max,
change
});
};
var getWindowScrollChange = ({
viewport,
subject,
center,
dragStartTime,
shouldUseTimeDampening,
getAutoScrollerOptions
}) => {
const scroll2 = getScroll$1({
dragStartTime,
container: viewport.frame,
subject,
center,
shouldUseTimeDampening,
getAutoScrollerOptions
});
return scroll2 && canScrollWindow(viewport, scroll2) ? scroll2 : null;
};
var getDroppableScrollChange = ({
droppable: droppable2,
subject,
center,
dragStartTime,
shouldUseTimeDampening,
getAutoScrollerOptions
}) => {
const frame2 = droppable2.frame;
if (!frame2) {
return null;
}
const scroll2 = getScroll$1({
dragStartTime,
container: frame2.pageMarginBox,
subject,
center,
shouldUseTimeDampening,
getAutoScrollerOptions
});
return scroll2 && canScrollDroppable(droppable2, scroll2) ? scroll2 : null;
};
var scroll = ({
state,
dragStartTime,
shouldUseTimeDampening,
scrollWindow: scrollWindow2,
scrollDroppable: scrollDroppable2,
getAutoScrollerOptions
}) => {
const center = state.current.page.borderBoxCenter;
const draggable2 = state.dimensions.draggables[state.critical.draggable.id];
const subject = draggable2.page.marginBox;
if (state.isWindowScrollAllowed) {
const viewport = state.viewport;
const change2 = getWindowScrollChange({
dragStartTime,
viewport,
subject,
center,
shouldUseTimeDampening,
getAutoScrollerOptions
});
if (change2) {
scrollWindow2(change2);
return;
}
}
const droppable2 = getBestScrollableDroppable({
center,
destination: whatIsDraggedOver(state.impact),
droppables: state.dimensions.droppables
});
if (!droppable2) {
return;
}
const change = getDroppableScrollChange({
dragStartTime,
droppable: droppable2,
subject,
center,
shouldUseTimeDampening,
getAutoScrollerOptions
});
if (change) {
scrollDroppable2(droppable2.descriptor.id, change);
}
};
var createFluidScroller = ({
scrollWindow: scrollWindow2,
scrollDroppable: scrollDroppable2,
getAutoScrollerOptions = () => defaultAutoScrollerOptions
}) => {
const scheduleWindowScroll = rafSchd(scrollWindow2);
const scheduleDroppableScroll = rafSchd(scrollDroppable2);
let dragging = null;
const tryScroll = (state) => {
!dragging ? process.env.NODE_ENV !== "production" ? invariant(false, "Cannot fluid scroll if not dragging") : invariant() : void 0;
const {
shouldUseTimeDampening,
dragStartTime
} = dragging;
scroll({
state,
scrollWindow: scheduleWindowScroll,
scrollDroppable: scheduleDroppableScroll,
dragStartTime,
shouldUseTimeDampening,
getAutoScrollerOptions
});
};
const start$1 = (state) => {
start();
!!dragging ? process.env.NODE_ENV !== "production" ? invariant(false, "Cannot start auto scrolling when already started") : invariant() : void 0;
const dragStartTime = Date.now();
let wasScrollNeeded = false;
const fakeScrollCallback = () => {
wasScrollNeeded = true;
};
scroll({
state,
dragStartTime: 0,
shouldUseTimeDampening: false,
scrollWindow: fakeScrollCallback,
scrollDroppable: fakeScrollCallback,
getAutoScrollerOptions
});
dragging = {
dragStartTime,
shouldUseTimeDampening: wasScrollNeeded
};
finish();
if (wasScrollNeeded) {
tryScroll(state);
}
};
const stop = () => {
if (!dragging) {
return;
}
scheduleWindowScroll.cancel();
scheduleDroppableScroll.cancel();
dragging = null;
};
return {
start: start$1,
stop,
scroll: tryScroll
};
};
var createJumpScroller = ({
move: move2,
scrollDroppable: scrollDroppable2,
scrollWindow: scrollWindow2
}) => {
const moveByOffset = (state, offset3) => {
const client = add(state.current.client.selection, offset3);
move2({
client
});
};
const scrollDroppableAsMuchAsItCan = (droppable2, change) => {
if (!canScrollDroppable(droppable2, change)) {
return change;
}
const overlap = getDroppableOverlap(droppable2, change);
if (!overlap) {
scrollDroppable2(droppable2.descriptor.id, change);
return null;
}
const whatTheDroppableCanScroll = subtract(change, overlap);
scrollDroppable2(droppable2.descriptor.id, whatTheDroppableCanScroll);
const remainder = subtract(change, whatTheDroppableCanScroll);
return remainder;
};
const scrollWindowAsMuchAsItCan = (isWindowScrollAllowed, viewport, change) => {
if (!isWindowScrollAllowed) {
return change;
}
if (!canScrollWindow(viewport, change)) {
return change;
}
const overlap = getWindowOverlap(viewport, change);
if (!overlap) {
scrollWindow2(change);
return null;
}
const whatTheWindowCanScroll = subtract(change, overlap);
scrollWindow2(whatTheWindowCanScroll);
const remainder = subtract(change, whatTheWindowCanScroll);
return remainder;
};
const jumpScroller = (state) => {
const request = state.scrollJumpRequest;
if (!request) {
return;
}
const destination = whatIsDraggedOver(state.impact);
!destination ? process.env.NODE_ENV !== "production" ? invariant(false, "Cannot perform a jump scroll when there is no destination") : invariant() : void 0;
const droppableRemainder = scrollDroppableAsMuchAsItCan(state.dimensions.droppables[destination], request);
if (!droppableRemainder) {
return;
}
const viewport = state.viewport;
const windowRemainder = scrollWindowAsMuchAsItCan(state.isWindowScrollAllowed, viewport, droppableRemainder);
if (!windowRemainder) {
return;
}
moveByOffset(state, windowRemainder);
};
return jumpScroller;
};
var createAutoScroller = ({
scrollDroppable: scrollDroppable2,
scrollWindow: scrollWindow2,
move: move2,
getAutoScrollerOptions
}) => {
const fluidScroller = createFluidScroller({
scrollWindow: scrollWindow2,
scrollDroppable: scrollDroppable2,
getAutoScrollerOptions
});
const jumpScroll = createJumpScroller({
move: move2,
scrollWindow: scrollWindow2,
scrollDroppable: scrollDroppable2
});
const scroll2 = (state) => {
const autoScrollerOptions = getAutoScrollerOptions();
if (autoScrollerOptions.disabled || state.phase !== "DRAGGING") {
return;
}
if (state.movementMode === "FLUID") {
fluidScroller.scroll(state);
return;
}
if (!state.scrollJumpRequest) {
return;
}
jumpScroll(state);
};
const scroller = {
scroll: scroll2,
start: fluidScroller.start,
stop: fluidScroller.stop
};
return scroller;
};
const prefix = "data-rfd";
const dragHandle = (() => {
const base = `${prefix}-drag-handle`;
return {
base,
draggableId: `${base}-draggable-id`,
contextId: `${base}-context-id`
};
})();
const draggable = (() => {
const base = `${prefix}-draggable`;
return {
base,
contextId: `${base}-context-id`,
id: `${base}-id`
};
})();
const droppable = (() => {
const base = `${prefix}-droppable`;
return {
base,
contextId: `${base}-context-id`,
id: `${base}-id`
};
})();
const scrollContainer = {
contextId: `${prefix}-scroll-container-context-id`
};
const makeGetSelector = (context) => (attribute) => `[${attribute}="${context}"]`;
const getStyles = (rules, property) => rules.map((rule) => {
const value = rule.styles[property];
if (!value) {
return "";
}
return `${rule.selector} { ${value} }`;
}).join(" ");
const noPointerEvents = "pointer-events: none;";
var getStyles$1 = (contextId) => {
const getSelector2 = makeGetSelector(contextId);
const dragHandle$1 = (() => {
const grabCursor = `
cursor: -webkit-grab;
cursor: grab;
`;
return {
selector: getSelector2(dragHandle.contextId),
styles: {
always: `
-webkit-touch-callout: none;
-webkit-tap-highlight-color: rgba(0,0,0,0);
touch-action: manipulation;
`,
resting: grabCursor,
dragging: noPointerEvents,
dropAnimating: grabCursor
}
};
})();
const draggable$1 = (() => {
const transition = `
transition: ${transitions.outOfTheWay};
`;
return {
selector: getSelector2(draggable.contextId),
styles: {
dragging: transition,
dropAnimating: transition,
userCancel: transition
}
};
})();
const droppable$1 = {
selector: getSelector2(droppable.contextId),
styles: {
always: `overflow-anchor: none;`
}
};
const body = {
selector: "body",
styles: {
dragging: `
cursor: grabbing;
cursor: -webkit-grabbing;
user-select: none;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
overflow-anchor: none;
`
}
};
const rules = [draggable$1, dragHandle$1, droppable$1, body];
return {
always: getStyles(rules, "always"),
resting: getStyles(rules, "resting"),
dragging: getStyles(rules, "dragging"),
dropAnimating: getStyles(rules, "dropAnimating"),
userCancel: getStyles(rules, "userCancel")
};
};
const useIsomorphicLayoutEffect = typeof window !== "undefined" && typeof window.document !== "undefined" && typeof window.document.createElement !== "undefined" ? useLayoutEffect$1 : useEffect;
var useLayoutEffect = useIsomorphicLayoutEffect;
const getHead = () => {
const head = document.querySelector("head");
!head ? process.env.NODE_ENV !== "production" ? invariant(false, "Cannot find the head to append a style to") : invariant() : void 0;
return head;
};
const createStyleEl = (nonce) => {
const el = document.createElement("style");
if (nonce) {
el.setAttribute("nonce", nonce);
}
el.type = "text/css";
return el;
};
function useStyleMarshal(contextId, nonce) {
const styles = useMemo(() => getStyles$1(contextId), [contextId]);
const alwaysRef = useRef(null);
const dynamicRef = useRef(null);
const setDynamicStyle = useCallback(memoizeOne((proposed) => {
const el = dynamicRef.current;
!el ? process.env.NODE_ENV !== "production" ? invariant(false, "Cannot set dynamic style element if it is not set") : invariant() : void 0;
el.textContent = proposed;
}), []);
const setAlwaysStyle = useCallback((proposed) => {
const el = alwaysRef.current;
!el ? process.env.NODE_ENV !== "production" ? invariant(false, "Cannot set dynamic style element if it is not set") : invariant() : void 0;
el.textContent = proposed;
}, []);
useLayoutEffect(() => {
!(!alwaysRef.current && !dynamicRef.current) ? process.env.NODE_ENV !== "production" ? invariant(false, "style elements already mounted") : invariant() : void 0;
const always = createStyleEl(nonce);
const dynamic = createStyleEl(nonce);
alwaysRef.current = always;
dynamicRef.current = dynamic;
always.setAttribute(`${prefix}-always`, contextId);
dynamic.setAttribute(`${prefix}-dynamic`, contextId);
getHead().appendChild(always);
getHead().appendChild(dynamic);
setAlwaysStyle(styles.always);
setDynamicStyle(styles.resting);
return () => {
const remove = (ref2) => {
const current = ref2.current;
!current ? process.env.NODE_ENV !== "production" ? invariant(false, "Cannot unmount ref as it is not set") : invariant() : void 0;
getHead().removeChild(current);
ref2.current = null;
};
remove(alwaysRef);
remove(dynamicRef);
};
}, [nonce, setAlwaysStyle, setDynamicStyle, styles.always, styles.resting, contextId]);
const dragging = useCallback(() => setDynamicStyle(styles.dragging), [setDynamicStyle, styles.dragging]);
const dropping = useCallback((reason) => {
if (reason === "DROP") {
setDynamicStyle(styles.dropAnimating);
return;
}
setDynamicStyle(styles.userCancel);
}, [setDynamicStyle, styles.dropAnimating, styles.userCancel]);
const resting = useCallback(() => {
if (!dynamicRef.current) {
return;
}
setDynamicStyle(styles.resting);
}, [setDynamicStyle, styles.resting]);
const marshal = useMemo(() => ({
dragging,
dropping,
resting
}), [dragging, dropping, resting]);
return marshal;
}
function querySelectorAll(parentNode, selector) {
return Array.from(parentNode.querySelectorAll(selector));
}
var getWindowFromEl = (el) => {
if (el && el.ownerDocument && el.ownerDocument.defaultView) {
return el.ownerDocument.defaultView;
}
return window;
};
function isHtmlElement(el) {
return el instanceof getWindowFromEl(el).HTMLElement;
}
function findDragHandle(contextId, draggableId) {
const selector = `[${dragHandle.contextId}="${contextId}"]`;
const possible = querySelectorAll(document, selector);
if (!possible.length) {
process.env.NODE_ENV !== "production" ? warning(`Unable to find any drag handles in the context "${contextId}"`) : void 0;
return null;
}
const handle = possible.find((el) => {
return el.getAttribute(dragHandle.draggableId) === draggableId;
});
if (!handle) {
process.env.NODE_ENV !== "production" ? warning(`Unable to find drag handle with id "${draggableId}" as no handle with a matching id was found`) : void 0;
return null;
}
if (!isHtmlElement(handle)) {
process.env.NODE_ENV !== "production" ? warning("drag handle needs to be a HTMLElement") : void 0;
return null;
}
return handle;
}
function useFocusMarshal(contextId) {
const entriesRef = useRef({});
const recordRef = useRef(null);
const restoreFocusFrameRef = useRef(null);
const isMountedRef = useRef(false);
const register = useCallback(function register2(id, focus2) {
const entry = {
id,
focus: focus2
};
entriesRef.current[id] = entry;
return function unregister() {
const entries = entriesRef.current;
const current = entries[id];
if (current !== entry) {
delete entries[id];
}
};
}, []);
const tryGiveFocus = useCallback(function tryGiveFocus2(tryGiveFocusTo) {
const handle = findDragHandle(contextId, tryGiveFocusTo);
if (handle && handle !== document.activeElement) {
handle.focus();
}
}, [contextId]);
const tryShiftRecord = useCallback(function tryShiftRecord2(previous, redirectTo) {
if (recordRef.current === previous) {
recordRef.current = redirectTo;
}
}, []);
const tryRestoreFocusRecorded = useCallback(function tryRestoreFocusRecorded2() {
if (restoreFocusFrameRef.current) {
return;
}
if (!isMountedRef.current) {
return;
}
restoreFocusFrameRef.current = requestAnimationFrame(() => {
restoreFocusFrameRef.current = null;
const record = recordRef.current;
if (record) {
tryGiveFocus(record);
}
});
}, [tryGiveFocus]);
const tryRecordFocus = useCallback(function tryRecordFocus2(id) {
recordRef.current = null;
const focused = document.activeElement;
if (!focused) {
return;
}
if (focused.getAttribute(dragHandle.draggableId) !== id) {
return;
}
recordRef.current = id;
}, []);
useLayoutEffect(() => {
isMountedRef.current = true;
return function clearFrameOnUnmount() {
isMountedRef.current = false;
const frameId = restoreFocusFrameRef.current;
if (frameId) {
cancelAnimationFrame(frameId);
}
};
}, []);
const marshal = useMemo(() => ({
register,
tryRecordFocus,
tryRestoreFocusRecorded,
tryShiftRecord
}), [register, tryRecordFocus, tryRestoreFocusRecorded, tryShiftRecord]);
return marshal;
}
function createRegistry() {
const entries = {
draggables: {},
droppables: {}
};
const subscribers = [];
function subscribe(cb) {
subscribers.push(cb);
return function unsubscribe() {
const index = subscribers.indexOf(cb);
if (index === -1) {
return;
}
subscribers.splice(index, 1);
};
}
function notify(event) {
if (subscribers.length) {
subscribers.forEach((cb) => cb(event));
}
}
function findDraggableById(id) {
return entries.draggables[id] || null;
}
function getDraggableById(id) {
const entry = findDraggableById(id);
!entry ? process.env.NODE_ENV !== "production" ? invariant(false, `Cannot find draggable entry with id [${id}]`) : invariant() : void 0;
return entry;
}
const draggableAPI = {
register: (entry) => {
entries.draggables[entry.descriptor.id] = entry;
notify({
type: "ADDITION",
value: entry
});
},
update: (entry, last) => {
const current = entries.draggables[last.descriptor.id];
if (!current) {
return;
}
if (current.uniqueId !== entry.uniqueId) {
return;
}
delete entries.draggables[last.descriptor.id];
entries.draggables[entry.descriptor.id] = entry;
},
unregister: (entry) => {
const draggableId = entry.descriptor.id;
const current = findDraggableById(draggableId);
if (!current) {
return;
}
if (entry.uniqueId !== current.uniqueId) {
return;
}
delete entries.draggables[draggableId];
if (entries.droppables[entry.descriptor.droppableId]) {
notify({
type: "REMOVAL",
value: entry
});
}
},
getById: getDraggableById,
findById: findDraggableById,
exists: (id) => Boolean(findDraggableById(id)),
getAllByType: (type) => Object.values(entries.draggables).filter((entry) => entry.descriptor.type === type)
};
function findDroppableById(id) {
return entries.droppables[id] || null;
}
function getDroppableById(id) {
const entry = findDroppableById(id);
!entry ? process.env.NODE_ENV !== "production" ? invariant(false, `Cannot find droppable entry with id [${id}]`) : invariant() : void 0;
return entry;
}
const droppableAPI = {
register: (entry) => {
entries.droppables[entry.descriptor.id] = entry;
},
unregister: (entry) => {
const current = findDroppableById(entry.descriptor.id);
if (!current) {
return;
}
if (entry.uniqueId !== current.uniqueId) {
return;
}
delete entries.droppables[entry.descriptor.id];
},
getById: getDroppableById,
findById: findDroppableById,
exists: (id) => Boolean(findDroppableById(id)),
getAllByType: (type) => Object.values(entries.droppables).filter((entry) => entry.descriptor.type === type)
};
function clean2() {
entries.draggables = {};
entries.droppables = {};
subscribers.length = 0;
}
return {
draggable: draggableAPI,
droppable: droppableAPI,
subscribe,
clean: clean2
};
}
function useRegistry() {
const registry = useMemo(createRegistry, []);
useEffect(() => {
return function unmount() {
if (React__default.version.startsWith("16") || React__default.version.startsWith("17")) {
requestAnimationFrame(registry.clean);
} else {
registry.clean();
}
};
}, [registry]);
return registry;
}
var StoreContext = React__default.createContext(null);
var getBodyElement = () => {
const body = document.body;
!body ? process.env.NODE_ENV !== "production" ? invariant(false, "Cannot find document.body") : invariant() : void 0;
return body;
};
const visuallyHidden = {
position: "absolute",
width: "1px",
height: "1px",
margin: "-1px",
border: "0",
padding: "0",
overflow: "hidden",
clip: "rect(0 0 0 0)",
"clip-path": "inset(100%)"
};
var visuallyHidden$1 = visuallyHidden;
const getId = (contextId) => `rfd-announcement-${contextId}`;
function useAnnouncer(contextId) {
const id = useMemo(() => getId(contextId), [contextId]);
const ref2 = useRef(null);
useEffect(function setup() {
const el = document.createElement("div");
ref2.current = el;
el.id = id;
el.setAttribute("aria-live", "assertive");
el.setAttribute("aria-atomic", "true");
_extends(el.style, visuallyHidden$1);
getBodyElement().appendChild(el);
return function cleanup() {
setTimeout(function remove() {
const body = getBodyElement();
if (body.contains(el)) {
body.removeChild(el);
}
if (el === ref2.current) {
ref2.current = null;
}
});
};
}, [id]);
const announce = useCallback((message) => {
const el = ref2.current;
if (el) {
el.textContent = message;
return;
}
process.env.NODE_ENV !== "production" ? warning(`
A screen reader message was trying to be announced but it was unable to do so.
This can occur if you unmount your <DragDropContext /> in your onDragEnd.
Consider calling provided.announce() before the unmount so that the instruction will
not be lost for users relying on a screen reader.
Message not passed to screen reader:
"${message}"
`) : void 0;
}, []);
return announce;
}
let count$1 = 0;
const defaults = {
separator: "::"
};
function useDeprecatedUniqueId(prefix2, options = defaults) {
return useMemo(() => `${prefix2}${options.separator}${count$1++}`, [options.separator, prefix2]);
}
function useUniqueId(prefix2, options = defaults) {
const id = React__default.useId();
return useMemo(() => `${prefix2}${options.separator}${id}`, [options.separator, prefix2, id]);
}
var useUniqueId$1 = "useId" in React__default ? useUniqueId : useDeprecatedUniqueId;
function getElementId({
contextId,
uniqueId
}) {
return `rfd-hidden-text-${contextId}-${uniqueId}`;
}
function useHiddenTextElement({
contextId,
text
}) {
const uniqueId = useUniqueId$1("hidden-text", {
separator: "-"
});
const id = useMemo(() => getElementId({
contextId,
uniqueId
}), [uniqueId, contextId]);
useEffect(function mount() {
const el = document.createElement("div");
el.id = id;
el.textContent = text;
el.style.display = "none";
getBodyElement().appendChild(el);
return function unmount() {
const body = getBodyElement();
if (body.contains(el)) {
body.removeChild(el);
}
};
}, [id, text]);
return id;
}
var AppContext = React__default.createContext(null);
var peerDependencies = {
react: "^16.8.5 || ^17.0.0 || ^18.0.0",
"react-dom": "^16.8.5 || ^17.0.0 || ^18.0.0"
};
const semver = /(\d+)\.(\d+)\.(\d+)/;
const getVersion = (value) => {
const result = semver.exec(value);
!(result != null) ? process.env.NODE_ENV !== "production" ? invariant(false, `Unable to parse React version ${value}`) : invariant() : void 0;
const major = Number(result[1]);
const minor = Number(result[2]);
const patch2 = Number(result[3]);
return {
major,
minor,
patch: patch2,
raw: value
};
};
const isSatisfied = (expected, actual) => {
if (actual.major > expected.major) {
return true;
}
if (actual.major < expected.major) {
return false;
}
if (actual.minor > expected.minor) {
return true;
}
if (actual.minor < expected.minor) {
return false;
}
return actual.patch >= expected.patch;
};
var checkReactVersion = (peerDepValue, actualValue) => {
const peerDep = getVersion(peerDepValue);
const actual = getVersion(actualValue);
if (isSatisfied(peerDep, actual)) {
return;
}
process.env.NODE_ENV !== "production" ? warning(`
React version: [${actual.raw}]
does not satisfy expected peer dependency version: [${peerDep.raw}]
This can result in run time bugs, and even fatal crashes
`) : void 0;
};
const suffix = `
We expect a html5 doctype: <!doctype html>
This is to ensure consistent browser layout and measurement
More information: https://github.com/hello-pangea/dnd/blob/main/docs/guides/doctype.md
`;
var checkDoctype = (doc) => {
const doctype = doc.doctype;
if (!doctype) {
process.env.NODE_ENV !== "production" ? warning(`
No <!doctype html> found.
${suffix}
`) : void 0;
return;
}
if (doctype.name.toLowerCase() !== "html") {
process.env.NODE_ENV !== "production" ? warning(`
Unexpected <!doctype> found: (${doctype.name})
${suffix}
`) : void 0;
}
if (doctype.publicId !== "") {
process.env.NODE_ENV !== "production" ? warning(`
Unexpected <!doctype> publicId found: (${doctype.publicId})
A html5 doctype does not have a publicId
${suffix}
`) : void 0;
}
};
function useDev(useHook) {
if (process.env.NODE_ENV !== "production") {
useHook();
}
}
function useDevSetupWarning(fn, inputs) {
useDev(() => {
useEffect(() => {
try {
fn();
} catch (e) {
error(`
A setup problem was encountered.
> ${e.message}
`);
}
}, inputs);
});
}
function useStartupValidation() {
useDevSetupWarning(() => {
checkReactVersion(peerDependencies.react, React__default.version);
checkDoctype(document);
}, []);
}
function usePrevious(current) {
const ref2 = useRef(current);
useEffect(() => {
ref2.current = current;
});
return ref2;
}
function create() {
let lock = null;
function isClaimed() {
return Boolean(lock);
}
function isActive2(value) {
return value === lock;
}
function claim(abandon) {
!!lock ? process.env.NODE_ENV !== "production" ? invariant(false, "Cannot claim lock as it is already claimed") : invariant() : void 0;
const newLock = {
abandon
};
lock = newLock;
return newLock;
}
function release() {
!lock ? process.env.NODE_ENV !== "production" ? invariant(false, "Cannot release lock when there is no lock") : invariant() : void 0;
lock = null;
}
function tryAbandon() {
if (lock) {
lock.abandon();
release();
}
}
return {
isClaimed,
isActive: isActive2,
claim,
release,
tryAbandon
};
}
function isDragging(state) {
if (state.phase === "IDLE" || state.phase === "DROP_ANIMATING") {
return false;
}
return state.isDragging;
}
const tab = 9;
const enter = 13;
const escape = 27;
const space = 32;
const pageUp = 33;
const pageDown = 34;
const end = 35;
const home = 36;
const arrowLeft = 37;
const arrowUp = 38;
const arrowRight = 39;
const arrowDown = 40;
const preventedKeys = {
[enter]: true,
[tab]: true
};
var preventStandardKeyEvents = (event) => {
if (preventedKeys[event.keyCode]) {
event.preventDefault();
}
};
const supportedEventName = (() => {
const base = "visibilitychange";
if (typeof document === "undefined") {
return base;
}
const candidates = [base, `ms${base}`, `webkit${base}`, `moz${base}`, `o${base}`];
const supported = candidates.find((eventName) => `on${eventName}` in document);
return supported || base;
})();
var supportedPageVisibilityEventName = supportedEventName;
const primaryButton = 0;
const sloppyClickThreshold = 5;
function isSloppyClickThresholdExceeded(original, current) {
return Math.abs(current.x - original.x) >= sloppyClickThreshold || Math.abs(current.y - original.y) >= sloppyClickThreshold;
}
const idle$1 = {
type: "IDLE"
};
function getCaptureBindings({
cancel,
completed,
getPhase,
setPhase
}) {
return [{
eventName: "mousemove",
fn: (event) => {
const {
button,
clientX,
clientY
} = event;
if (button !== primaryButton) {
return;
}
const point = {
x: clientX,
y: clientY
};
const phase = getPhase();
if (phase.type === "DRAGGING") {
event.preventDefault();
phase.actions.move(point);
return;
}
!(phase.type === "PENDING") ? process.env.NODE_ENV !== "production" ? invariant(false, "Cannot be IDLE") : invariant() : void 0;
const pending = phase.point;
if (!isSloppyClickThresholdExceeded(pending, point)) {
return;
}
event.preventDefault();
const actions = phase.actions.fluidLift(point);
setPhase({
type: "DRAGGING",
actions
});
}
}, {
eventName: "mouseup",
fn: (event) => {
const phase = getPhase();
if (phase.type !== "DRAGGING") {
cancel();
return;
}
event.preventDefault();
phase.actions.drop({
shouldBlockNextClick: true
});
completed();
}
}, {
eventName: "mousedown",
fn: (event) => {
if (getPhase().type === "DRAGGING") {
event.preventDefault();
}
cancel();
}
}, {
eventName: "keydown",
fn: (event) => {
const phase = getPhase();
if (phase.type === "PENDING") {
cancel();
return;
}
if (event.keyCode === escape) {
event.preventDefault();
cancel();
return;
}
preventStandardKeyEvents(event);
}
}, {
eventName: "resize",
fn: cancel
}, {
eventName: "scroll",
options: {
passive: true,
capture: false
},
fn: () => {
if (getPhase().type === "PENDING") {
cancel();
}
}
}, {
eventName: "webkitmouseforcedown",
fn: (event) => {
const phase = getPhase();
!(phase.type !== "IDLE") ? process.env.NODE_ENV !== "production" ? invariant(false, "Unexpected phase") : invariant() : void 0;
if (phase.actions.shouldRespectForcePress()) {
cancel();
return;
}
event.preventDefault();
}
}, {
eventName: supportedPageVisibilityEventName,
fn: cancel
}];
}
function useMouseSensor(api) {
const phaseRef = useRef(idle$1);
const unbindEventsRef = useRef(noop$2);
const startCaptureBinding = useMemo(() => ({
eventName: "mousedown",
fn: function onMouseDown(event) {
if (event.defaultPrevented) {
return;
}
if (event.button !== primaryButton) {
return;
}
if (event.ctrlKey || event.metaKey || event.shiftKey || event.altKey) {
return;
}
const draggableId = api.findClosestDraggableId(event);
if (!draggableId) {
return;
}
const actions = api.tryGetLock(draggableId, stop, {
sourceEvent: event
});
if (!actions) {
return;
}
event.preventDefault();
const point = {
x: event.clientX,
y: event.clientY
};
unbindEventsRef.current();
startPendingDrag(actions, point);
}
}), [api]);
const preventForcePressBinding = useMemo(() => ({
eventName: "webkitmouseforcewillbegin",
fn: (event) => {
if (event.defaultPrevented) {
return;
}
const id = api.findClosestDraggableId(event);
if (!id) {
return;
}
const options = api.findOptionsForDraggable(id);
if (!options) {
return;
}
if (options.shouldRespectForcePress) {
return;
}
if (!api.canGetLock(id)) {
return;
}
event.preventDefault();
}
}), [api]);
const listenForCapture = useCallback(function listenForCapture2() {
const options = {
passive: false,
capture: true
};
unbindEventsRef.current = bindEvents(window, [preventForcePressBinding, startCaptureBinding], options);
}, [preventForcePressBinding, startCaptureBinding]);
const stop = useCallback(() => {
const current = phaseRef.current;
if (current.type === "IDLE") {
return;
}
phaseRef.current = idle$1;
unbindEventsRef.current();
listenForCapture();
}, [listenForCapture]);
const cancel = useCallback(() => {
const phase = phaseRef.current;
stop();
if (phase.type === "DRAGGING") {
phase.actions.cancel({
shouldBlockNextClick: true
});
}
if (phase.type === "PENDING") {
phase.actions.abort();
}
}, [stop]);
const bindCapturingEvents = useCallback(function bindCapturingEvents2() {
const options = {
capture: true,
passive: false
};
const bindings = getCaptureBindings({
cancel,
completed: stop,
getPhase: () => phaseRef.current,
setPhase: (phase) => {
phaseRef.current = phase;
}
});
unbindEventsRef.current = bindEvents(window, bindings, options);
}, [cancel, stop]);
const startPendingDrag = useCallback(function startPendingDrag2(actions, point) {
!(phaseRef.current.type === "IDLE") ? process.env.NODE_ENV !== "production" ? invariant(false, "Expected to move from IDLE to PENDING drag") : invariant() : void 0;
phaseRef.current = {
type: "PENDING",
point,
actions
};
bindCapturingEvents();
}, [bindCapturingEvents]);
useLayoutEffect(function mount() {
listenForCapture();
return function unmount() {
unbindEventsRef.current();
};
}, [listenForCapture]);
}
function noop$1() {
}
const scrollJumpKeys = {
[pageDown]: true,
[pageUp]: true,
[home]: true,
[end]: true
};
function getDraggingBindings(actions, stop) {
function cancel() {
stop();
actions.cancel();
}
function drop2() {
stop();
actions.drop();
}
return [{
eventName: "keydown",
fn: (event) => {
if (event.keyCode === escape) {
event.preventDefault();
cancel();
return;
}
if (event.keyCode === space) {
event.preventDefault();
drop2();
return;
}
if (event.keyCode === arrowDown) {
event.preventDefault();
actions.moveDown();
return;
}
if (event.keyCode === arrowUp) {
event.preventDefault();
actions.moveUp();
return;
}
if (event.keyCode === arrowRight) {
event.preventDefault();
actions.moveRight();
return;
}
if (event.keyCode === arrowLeft) {
event.preventDefault();
actions.moveLeft();
return;
}
if (scrollJumpKeys[event.keyCode]) {
event.preventDefault();
return;
}
preventStandardKeyEvents(event);
}
}, {
eventName: "mousedown",
fn: cancel
}, {
eventName: "mouseup",
fn: cancel
}, {
eventName: "click",
fn: cancel
}, {
eventName: "touchstart",
fn: cancel
}, {
eventName: "resize",
fn: cancel
}, {
eventName: "wheel",
fn: cancel,
options: {
passive: true
}
}, {
eventName: supportedPageVisibilityEventName,
fn: cancel
}];
}
function useKeyboardSensor(api) {
const unbindEventsRef = useRef(noop$1);
const startCaptureBinding = useMemo(() => ({
eventName: "keydown",
fn: function onKeyDown2(event) {
if (event.defaultPrevented) {
return;
}
if (event.keyCode !== space) {
return;
}
const draggableId = api.findClosestDraggableId(event);
if (!draggableId) {
return;
}
const preDrag = api.tryGetLock(draggableId, stop, {
sourceEvent: event
});
if (!preDrag) {
return;
}
event.preventDefault();
let isCapturing = true;
const actions = preDrag.snapLift();
unbindEventsRef.current();
function stop() {
!isCapturing ? process.env.NODE_ENV !== "production" ? invariant(false, "Cannot stop capturing a keyboard drag when not capturing") : invariant() : void 0;
isCapturing = false;
unbindEventsRef.current();
listenForCapture();
}
unbindEventsRef.current = bindEvents(window, getDraggingBindings(actions, stop), {
capture: true,
passive: false
});
}
}), [api]);
const listenForCapture = useCallback(function tryStartCapture() {
const options = {
passive: false,
capture: true
};
unbindEventsRef.current = bindEvents(window, [startCaptureBinding], options);
}, [startCaptureBinding]);
useLayoutEffect(function mount() {
listenForCapture();
return function unmount() {
unbindEventsRef.current();
};
}, [listenForCapture]);
}
const idle = {
type: "IDLE"
};
const timeForLongPress = 120;
const forcePressThreshold = 0.15;
function getWindowBindings({
cancel,
getPhase
}) {
return [{
eventName: "orientationchange",
fn: cancel
}, {
eventName: "resize",
fn: cancel
}, {
eventName: "contextmenu",
fn: (event) => {
event.preventDefault();
}
}, {
eventName: "keydown",
fn: (event) => {
if (getPhase().type !== "DRAGGING") {
cancel();
return;
}
if (event.keyCode === escape) {
event.preventDefault();
}
cancel();
}
}, {
eventName: supportedPageVisibilityEventName,
fn: cancel
}];
}
function getHandleBindings({
cancel,
completed,
getPhase
}) {
return [{
eventName: "touchmove",
options: {
capture: false
},
fn: (event) => {
const phase = getPhase();
if (phase.type !== "DRAGGING") {
cancel();
return;
}
phase.hasMoved = true;
const {
clientX,
clientY
} = event.touches[0];
const point = {
x: clientX,
y: clientY
};
event.preventDefault();
phase.actions.move(point);
}
}, {
eventName: "touchend",
fn: (event) => {
const phase = getPhase();
if (phase.type !== "DRAGGING") {
cancel();
return;
}
event.preventDefault();
phase.actions.drop({
shouldBlockNextClick: true
});
completed();
}
}, {
eventName: "touchcancel",
fn: (event) => {
if (getPhase().type !== "DRAGGING") {
cancel();
return;
}
event.preventDefault();
cancel();
}
}, {
eventName: "touchforcechange",
fn: (event) => {
const phase = getPhase();
!(phase.type !== "IDLE") ? process.env.NODE_ENV !== "production" ? invariant() : invariant() : void 0;
const touch = event.touches[0];
if (!touch) {
return;
}
const isForcePress = touch.force >= forcePressThreshold;
if (!isForcePress) {
return;
}
const shouldRespect = phase.actions.shouldRespectForcePress();
if (phase.type === "PENDING") {
if (shouldRespect) {
cancel();
}
return;
}
if (shouldRespect) {
if (phase.hasMoved) {
event.preventDefault();
return;
}
cancel();
return;
}
event.preventDefault();
}
}, {
eventName: supportedPageVisibilityEventName,
fn: cancel
}];
}
function useTouchSensor(api) {
const phaseRef = useRef(idle);
const unbindEventsRef = useRef(noop$2);
const getPhase = useCallback(function getPhase2() {
return phaseRef.current;
}, []);
const setPhase = useCallback(function setPhase2(phase) {
phaseRef.current = phase;
}, []);
const startCaptureBinding = useMemo(() => ({
eventName: "touchstart",
fn: function onTouchStart(event) {
if (event.defaultPrevented) {
return;
}
const draggableId = api.findClosestDraggableId(event);
if (!draggableId) {
return;
}
const actions = api.tryGetLock(draggableId, stop, {
sourceEvent: event
});
if (!actions) {
return;
}
const touch = event.touches[0];
const {
clientX,
clientY
} = touch;
const point = {
x: clientX,
y: clientY
};
unbindEventsRef.current();
startPendingDrag(actions, point);
}
}), [api]);
const listenForCapture = useCallback(function listenForCapture2() {
const options = {
capture: true,
passive: false
};
unbindEventsRef.current = bindEvents(window, [startCaptureBinding], options);
}, [startCaptureBinding]);
const stop = useCallback(() => {
const current = phaseRef.current;
if (current.type === "IDLE") {
return;
}
if (current.type === "PENDING") {
clearTimeout(current.longPressTimerId);
}
setPhase(idle);
unbindEventsRef.current();
listenForCapture();
}, [listenForCapture, setPhase]);
const cancel = useCallback(() => {
const phase = phaseRef.current;
stop();
if (phase.type === "DRAGGING") {
phase.actions.cancel({
shouldBlockNextClick: true
});
}
if (phase.type === "PENDING") {
phase.actions.abort();
}
}, [stop]);
const bindCapturingEvents = useCallback(function bindCapturingEvents2() {
const options = {
capture: true,
passive: false
};
const args = {
cancel,
completed: stop,
getPhase
};
const unbindTarget = bindEvents(window, getHandleBindings(args), options);
const unbindWindow = bindEvents(window, getWindowBindings(args), options);
unbindEventsRef.current = function unbindAll() {
unbindTarget();
unbindWindow();
};
}, [cancel, getPhase, stop]);
const startDragging = useCallback(function startDragging2() {
const phase = getPhase();
!(phase.type === "PENDING") ? process.env.NODE_ENV !== "production" ? invariant(false, `Cannot start dragging from phase ${phase.type}`) : invariant() : void 0;
const actions = phase.actions.fluidLift(phase.point);
setPhase({
type: "DRAGGING",
actions,
hasMoved: false
});
}, [getPhase, setPhase]);
const startPendingDrag = useCallback(function startPendingDrag2(actions, point) {
!(getPhase().type === "IDLE") ? process.env.NODE_ENV !== "production" ? invariant(false, "Expected to move from IDLE to PENDING drag") : invariant() : void 0;
const longPressTimerId = setTimeout(startDragging, timeForLongPress);
setPhase({
type: "PENDING",
point,
actions,
longPressTimerId
});
bindCapturingEvents();
}, [bindCapturingEvents, getPhase, setPhase, startDragging]);
useLayoutEffect(function mount() {
listenForCapture();
return function unmount() {
unbindEventsRef.current();
const phase = getPhase();
if (phase.type === "PENDING") {
clearTimeout(phase.longPressTimerId);
setPhase(idle);
}
};
}, [getPhase, listenForCapture, setPhase]);
useLayoutEffect(function webkitHack() {
const unbind = bindEvents(window, [{
eventName: "touchmove",
fn: () => {
},
options: {
capture: false,
passive: false
}
}]);
return unbind;
}, []);
}
function useValidateSensorHooks(sensorHooks) {
useDev(() => {
const previousRef = usePrevious(sensorHooks);
useDevSetupWarning(() => {
!(previousRef.current.length === sensorHooks.length) ? process.env.NODE_ENV !== "production" ? invariant(false, "Cannot change the amount of sensor hooks after mounting") : invariant(false) : void 0;
});
});
}
const interactiveTagNames = ["input", "button", "textarea", "select", "option", "optgroup", "video", "audio"];
function isAnInteractiveElement(parent, current) {
if (current == null) {
return false;
}
const hasAnInteractiveTag = interactiveTagNames.includes(current.tagName.toLowerCase());
if (hasAnInteractiveTag) {
return true;
}
const attribute = current.getAttribute("contenteditable");
if (attribute === "true" || attribute === "") {
return true;
}
if (current === parent) {
return false;
}
return isAnInteractiveElement(parent, current.parentElement);
}
function isEventInInteractiveElement(draggable2, event) {
const target = event.target;
if (!isHtmlElement(target)) {
return false;
}
return isAnInteractiveElement(draggable2, target);
}
var getBorderBoxCenterPosition = (el) => getRect(el.getBoundingClientRect()).center;
function isElement(el) {
return el instanceof getWindowFromEl(el).Element;
}
const supportedMatchesName = (() => {
const base = "matches";
if (typeof document === "undefined") {
return base;
}
const candidates = [base, "msMatchesSelector", "webkitMatchesSelector"];
const value = candidates.find((name) => name in Element.prototype);
return value || base;
})();
function closestPonyfill(el, selector) {
if (el == null) {
return null;
}
if (el[supportedMatchesName](selector)) {
return el;
}
return closestPonyfill(el.parentElement, selector);
}
function closest(el, selector) {
if (el.closest) {
return el.closest(selector);
}
return closestPonyfill(el, selector);
}
function getSelector(contextId) {
return `[${dragHandle.contextId}="${contextId}"]`;
}
function findClosestDragHandleFromEvent(contextId, event) {
const target = event.target;
if (!isElement(target)) {
process.env.NODE_ENV !== "production" ? warning("event.target must be a Element") : void 0;
return null;
}
const selector = getSelector(contextId);
const handle = closest(target, selector);
if (!handle) {
return null;
}
if (!isHtmlElement(handle)) {
process.env.NODE_ENV !== "production" ? warning("drag handle must be a HTMLElement") : void 0;
return null;
}
return handle;
}
function tryGetClosestDraggableIdFromEvent(contextId, event) {
const handle = findClosestDragHandleFromEvent(contextId, event);
if (!handle) {
return null;
}
return handle.getAttribute(dragHandle.draggableId);
}
function findDraggable(contextId, draggableId) {
const selector = `[${draggable.contextId}="${contextId}"]`;
const possible = querySelectorAll(document, selector);
const draggable$1 = possible.find((el) => {
return el.getAttribute(draggable.id) === draggableId;
});
if (!draggable$1) {
return null;
}
if (!isHtmlElement(draggable$1)) {
process.env.NODE_ENV !== "production" ? warning("Draggable element is not a HTMLElement") : void 0;
return null;
}
return draggable$1;
}
function preventDefault(event) {
event.preventDefault();
}
function isActive({
expected,
phase,
isLockActive,
shouldWarn
}) {
if (!isLockActive()) {
if (shouldWarn) {
process.env.NODE_ENV !== "production" ? warning(`
Cannot perform action.
The sensor no longer has an action lock.
Tips:
- Throw away your action handlers when forceStop() is called
- Check actions.isActive() if you really need to
`) : void 0;
}
return false;
}
if (expected !== phase) {
if (shouldWarn) {
process.env.NODE_ENV !== "production" ? warning(`
Cannot perform action.
The actions you used belong to an outdated phase
Current phase: ${expected}
You called an action from outdated phase: ${phase}
Tips:
- Do not use preDragActions actions after calling preDragActions.lift()
`) : void 0;
}
return false;
}
return true;
}
function canStart({
lockAPI,
store,
registry,
draggableId
}) {
if (lockAPI.isClaimed()) {
return false;
}
const entry = registry.draggable.findById(draggableId);
if (!entry) {
process.env.NODE_ENV !== "production" ? warning(`Unable to find draggable with id: ${draggableId}`) : void 0;
return false;
}
if (!entry.options.isEnabled) {
return false;
}
if (!canStartDrag(store.getState(), draggableId)) {
return false;
}
return true;
}
function tryStart({
lockAPI,
contextId,
store,
registry,
draggableId,
forceSensorStop,
sourceEvent
}) {
const shouldStart = canStart({
lockAPI,
store,
registry,
draggableId
});
if (!shouldStart) {
return null;
}
const entry = registry.draggable.getById(draggableId);
const el = findDraggable(contextId, entry.descriptor.id);
if (!el) {
process.env.NODE_ENV !== "production" ? warning(`Unable to find draggable element with id: ${draggableId}`) : void 0;
return null;
}
if (sourceEvent && !entry.options.canDragInteractiveElements && isEventInInteractiveElement(el, sourceEvent)) {
return null;
}
const lock = lockAPI.claim(forceSensorStop || noop$2);
let phase = "PRE_DRAG";
function getShouldRespectForcePress() {
return entry.options.shouldRespectForcePress;
}
function isLockActive() {
return lockAPI.isActive(lock);
}
function tryDispatch(expected, getAction) {
if (isActive({
expected,
phase,
isLockActive,
shouldWarn: true
})) {
store.dispatch(getAction());
}
}
const tryDispatchWhenDragging = tryDispatch.bind(null, "DRAGGING");
function lift2(args) {
function completed() {
lockAPI.release();
phase = "COMPLETED";
}
if (phase !== "PRE_DRAG") {
completed();
process.env.NODE_ENV !== "production" ? invariant(false, `Cannot lift in phase ${phase}`) : invariant();
}
store.dispatch(lift$1(args.liftActionArgs));
phase = "DRAGGING";
function finish2(reason, options = {
shouldBlockNextClick: false
}) {
args.cleanup();
if (options.shouldBlockNextClick) {
const unbind = bindEvents(window, [{
eventName: "click",
fn: preventDefault,
options: {
once: true,
passive: false,
capture: true
}
}]);
setTimeout(unbind);
}
completed();
store.dispatch(drop$1({
reason
}));
}
return {
isActive: () => isActive({
expected: "DRAGGING",
phase,
isLockActive,
shouldWarn: false
}),
shouldRespectForcePress: getShouldRespectForcePress,
drop: (options) => finish2("DROP", options),
cancel: (options) => finish2("CANCEL", options),
...args.actions
};
}
function fluidLift(clientSelection) {
const move$1 = rafSchd((client) => {
tryDispatchWhenDragging(() => move({
client
}));
});
const api = lift2({
liftActionArgs: {
id: draggableId,
clientSelection,
movementMode: "FLUID"
},
cleanup: () => move$1.cancel(),
actions: {
move: move$1
}
});
return {
...api,
move: move$1
};
}
function snapLift() {
const actions = {
moveUp: () => tryDispatchWhenDragging(moveUp),
moveRight: () => tryDispatchWhenDragging(moveRight),
moveDown: () => tryDispatchWhenDragging(moveDown),
moveLeft: () => tryDispatchWhenDragging(moveLeft)
};
return lift2({
liftActionArgs: {
id: draggableId,
clientSelection: getBorderBoxCenterPosition(el),
movementMode: "SNAP"
},
cleanup: noop$2,
actions
});
}
function abortPreDrag() {
const shouldRelease = isActive({
expected: "PRE_DRAG",
phase,
isLockActive,
shouldWarn: true
});
if (shouldRelease) {
lockAPI.release();
}
}
const preDrag = {
isActive: () => isActive({
expected: "PRE_DRAG",
phase,
isLockActive,
shouldWarn: false
}),
shouldRespectForcePress: getShouldRespectForcePress,
fluidLift,
snapLift,
abort: abortPreDrag
};
return preDrag;
}
const defaultSensors = [useMouseSensor, useKeyboardSensor, useTouchSensor];
function useSensorMarshal({
contextId,
store,
registry,
customSensors,
enableDefaultSensors
}) {
const useSensors = [...enableDefaultSensors ? defaultSensors : [], ...customSensors || []];
const lockAPI = useState(() => create())[0];
const tryAbandonLock = useCallback(function tryAbandonLock2(previous, current) {
if (isDragging(previous) && !isDragging(current)) {
lockAPI.tryAbandon();
}
}, [lockAPI]);
useLayoutEffect(function listenToStore() {
let previous = store.getState();
const unsubscribe = store.subscribe(() => {
const current = store.getState();
tryAbandonLock(previous, current);
previous = current;
});
return unsubscribe;
}, [lockAPI, store, tryAbandonLock]);
useLayoutEffect(() => {
return lockAPI.tryAbandon;
}, [lockAPI.tryAbandon]);
const canGetLock = useCallback((draggableId) => {
return canStart({
lockAPI,
registry,
store,
draggableId
});
}, [lockAPI, registry, store]);
const tryGetLock = useCallback((draggableId, forceStop, options) => tryStart({
lockAPI,
registry,
contextId,
store,
draggableId,
forceSensorStop: forceStop || null,
sourceEvent: options && options.sourceEvent ? options.sourceEvent : null
}), [contextId, lockAPI, registry, store]);
const findClosestDraggableId = useCallback((event) => tryGetClosestDraggableIdFromEvent(contextId, event), [contextId]);
const findOptionsForDraggable = useCallback((id) => {
const entry = registry.draggable.findById(id);
return entry ? entry.options : null;
}, [registry.draggable]);
const tryReleaseLock = useCallback(function tryReleaseLock2() {
if (!lockAPI.isClaimed()) {
return;
}
lockAPI.tryAbandon();
if (store.getState().phase !== "IDLE") {
store.dispatch(flush());
}
}, [lockAPI, store]);
const isLockClaimed = useCallback(() => lockAPI.isClaimed(), [lockAPI]);
const api = useMemo(() => ({
canGetLock,
tryGetLock,
findClosestDraggableId,
findOptionsForDraggable,
tryReleaseLock,
isLockClaimed
}), [canGetLock, tryGetLock, findClosestDraggableId, findOptionsForDraggable, tryReleaseLock, isLockClaimed]);
useValidateSensorHooks(useSensors);
for (let i = 0; i < useSensors.length; i++) {
useSensors[i](api);
}
}
const createResponders = (props) => ({
onBeforeCapture: (t) => {
const onBeforeCapureCallback = () => {
if (props.onBeforeCapture) {
props.onBeforeCapture(t);
}
};
if (React__default.version.startsWith("16") || React__default.version.startsWith("17")) {
onBeforeCapureCallback();
} else {
flushSync(onBeforeCapureCallback);
}
},
onBeforeDragStart: props.onBeforeDragStart,
onDragStart: props.onDragStart,
onDragEnd: props.onDragEnd,
onDragUpdate: props.onDragUpdate
});
const createAutoScrollerOptions = (props) => ({
...defaultAutoScrollerOptions,
...props.autoScrollerOptions,
durationDampening: {
...defaultAutoScrollerOptions.durationDampening,
...props.autoScrollerOptions
}
});
function getStore(lazyRef) {
!lazyRef.current ? process.env.NODE_ENV !== "production" ? invariant(false, "Could not find store from lazy ref") : invariant() : void 0;
return lazyRef.current;
}
function App(props) {
const {
contextId,
setCallbacks,
sensors,
nonce,
dragHandleUsageInstructions: dragHandleUsageInstructions2
} = props;
const lazyStoreRef = useRef(null);
useStartupValidation();
const lastPropsRef = usePrevious(props);
const getResponders = useCallback(() => {
return createResponders(lastPropsRef.current);
}, [lastPropsRef]);
const getAutoScrollerOptions = useCallback(() => {
return createAutoScrollerOptions(lastPropsRef.current);
}, [lastPropsRef]);
const announce = useAnnouncer(contextId);
const dragHandleUsageInstructionsId = useHiddenTextElement({
contextId,
text: dragHandleUsageInstructions2
});
const styleMarshal = useStyleMarshal(contextId, nonce);
const lazyDispatch = useCallback((action) => {
getStore(lazyStoreRef).dispatch(action);
}, []);
const marshalCallbacks = useMemo(() => bindActionCreators$1({
publishWhileDragging,
updateDroppableScroll,
updateDroppableIsEnabled,
updateDroppableIsCombineEnabled,
collectionStarting
}, lazyDispatch), [lazyDispatch]);
const registry = useRegistry();
const dimensionMarshal = useMemo(() => {
return createDimensionMarshal(registry, marshalCallbacks);
}, [registry, marshalCallbacks]);
const autoScroller = useMemo(() => createAutoScroller({
scrollWindow,
scrollDroppable: dimensionMarshal.scrollDroppable,
getAutoScrollerOptions,
...bindActionCreators$1({
move
}, lazyDispatch)
}), [dimensionMarshal.scrollDroppable, lazyDispatch, getAutoScrollerOptions]);
const focusMarshal = useFocusMarshal(contextId);
const store = useMemo(() => createStore({
announce,
autoScroller,
dimensionMarshal,
focusMarshal,
getResponders,
styleMarshal
}), [announce, autoScroller, dimensionMarshal, focusMarshal, getResponders, styleMarshal]);
if (process.env.NODE_ENV !== "production") {
if (lazyStoreRef.current && lazyStoreRef.current !== store) {
process.env.NODE_ENV !== "production" ? warning("unexpected store change") : void 0;
}
}
lazyStoreRef.current = store;
const tryResetStore = useCallback(() => {
const current = getStore(lazyStoreRef);
const state = current.getState();
if (state.phase !== "IDLE") {
current.dispatch(flush());
}
}, []);
const isDragging2 = useCallback(() => {
const state = getStore(lazyStoreRef).getState();
if (state.phase === "DROP_ANIMATING") {
return true;
}
if (state.phase === "IDLE") {
return false;
}
return state.isDragging;
}, []);
const appCallbacks = useMemo(() => ({
isDragging: isDragging2,
tryAbort: tryResetStore
}), [isDragging2, tryResetStore]);
setCallbacks(appCallbacks);
const getCanLift = useCallback((id) => canStartDrag(getStore(lazyStoreRef).getState(), id), []);
const getIsMovementAllowed = useCallback(() => isMovementAllowed(getStore(lazyStoreRef).getState()), []);
const appContext = useMemo(() => ({
marshal: dimensionMarshal,
focus: focusMarshal,
contextId,
canLift: getCanLift,
isMovementAllowed: getIsMovementAllowed,
dragHandleUsageInstructionsId,
registry
}), [contextId, dimensionMarshal, dragHandleUsageInstructionsId, focusMarshal, getCanLift, getIsMovementAllowed, registry]);
useSensorMarshal({
contextId,
store,
registry,
customSensors: sensors || null,
enableDefaultSensors: props.enableDefaultSensors !== false
});
useEffect(() => {
return tryResetStore;
}, [tryResetStore]);
return React__default.createElement(AppContext.Provider, {
value: appContext
}, React__default.createElement(Provider, {
context: StoreContext,
store
}, props.children));
}
let count = 0;
function useDeprecatedUniqueContextId() {
return useMemo(() => `${count++}`, []);
}
function useUniqueContextId() {
return React__default.useId();
}
var useUniqueContextId$1 = "useId" in React__default ? useUniqueContextId : useDeprecatedUniqueContextId;
function DragDropContext(props) {
const contextId = useUniqueContextId$1();
const dragHandleUsageInstructions2 = props.dragHandleUsageInstructions || preset$1.dragHandleUsageInstructions;
return React__default.createElement(ErrorBoundary, null, (setCallbacks) => React__default.createElement(App, {
nonce: props.nonce,
contextId,
setCallbacks,
dragHandleUsageInstructions: dragHandleUsageInstructions2,
enableDefaultSensors: props.enableDefaultSensors,
sensors: props.sensors,
onBeforeCapture: props.onBeforeCapture,
onBeforeDragStart: props.onBeforeDragStart,
onDragStart: props.onDragStart,
onDragUpdate: props.onDragUpdate,
onDragEnd: props.onDragEnd,
autoScrollerOptions: props.autoScrollerOptions
}, props.children));
}
const zIndexOptions = {
dragging: 5e3,
dropAnimating: 4500
};
const getDraggingTransition = (shouldAnimateDragMovement, dropping) => {
if (dropping) {
return transitions.drop(dropping.duration);
}
if (shouldAnimateDragMovement) {
return transitions.snap;
}
return transitions.fluid;
};
const getDraggingOpacity = (isCombining, isDropAnimating) => {
if (!isCombining) {
return void 0;
}
return isDropAnimating ? combine.opacity.drop : combine.opacity.combining;
};
const getShouldDraggingAnimate = (dragging) => {
if (dragging.forceShouldAnimate != null) {
return dragging.forceShouldAnimate;
}
return dragging.mode === "SNAP";
};
function getDraggingStyle(dragging) {
const dimension = dragging.dimension;
const box = dimension.client;
const {
offset: offset3,
combineWith,
dropping
} = dragging;
const isCombining = Boolean(combineWith);
const shouldAnimate = getShouldDraggingAnimate(dragging);
const isDropAnimating = Boolean(dropping);
const transform = isDropAnimating ? transforms.drop(offset3, isCombining) : transforms.moveTo(offset3);
const style2 = {
position: "fixed",
top: box.marginBox.top,
left: box.marginBox.left,
boxSizing: "border-box",
width: box.borderBox.width,
height: box.borderBox.height,
transition: getDraggingTransition(shouldAnimate, dropping),
transform,
opacity: getDraggingOpacity(isCombining, isDropAnimating),
zIndex: isDropAnimating ? zIndexOptions.dropAnimating : zIndexOptions.dragging,
pointerEvents: "none"
};
return style2;
}
function getSecondaryStyle(secondary) {
return {
transform: transforms.moveTo(secondary.offset),
transition: secondary.shouldAnimateDisplacement ? void 0 : "none"
};
}
function getStyle$1(mapped) {
return mapped.type === "DRAGGING" ? getDraggingStyle(mapped) : getSecondaryStyle(mapped);
}
function getDimension$1(descriptor, el, windowScroll = origin) {
const computedStyles = window.getComputedStyle(el);
const borderBox = el.getBoundingClientRect();
const client = calculateBox(borderBox, computedStyles);
const page = withScroll(client, windowScroll);
const placeholder2 = {
client,
tagName: el.tagName.toLowerCase(),
display: computedStyles.display
};
const displaceBy = {
x: client.marginBox.width,
y: client.marginBox.height
};
const dimension = {
descriptor,
placeholder: placeholder2,
displaceBy,
client,
page
};
return dimension;
}
function useDraggablePublisher(args) {
const uniqueId = useUniqueId$1("draggable");
const {
descriptor,
registry,
getDraggableRef,
canDragInteractiveElements,
shouldRespectForcePress,
isEnabled
} = args;
const options = useMemo(() => ({
canDragInteractiveElements,
shouldRespectForcePress,
isEnabled
}), [canDragInteractiveElements, isEnabled, shouldRespectForcePress]);
const getDimension2 = useCallback((windowScroll) => {
const el = getDraggableRef();
!el ? process.env.NODE_ENV !== "production" ? invariant(false, "Cannot get dimension when no ref is set") : invariant() : void 0;
return getDimension$1(descriptor, el, windowScroll);
}, [descriptor, getDraggableRef]);
const entry = useMemo(() => ({
uniqueId,
descriptor,
options,
getDimension: getDimension2
}), [descriptor, getDimension2, options, uniqueId]);
const publishedRef = useRef(entry);
const isFirstPublishRef = useRef(true);
useLayoutEffect(() => {
registry.draggable.register(publishedRef.current);
return () => registry.draggable.unregister(publishedRef.current);
}, [registry.draggable]);
useLayoutEffect(() => {
if (isFirstPublishRef.current) {
isFirstPublishRef.current = false;
return;
}
const last = publishedRef.current;
publishedRef.current = entry;
registry.draggable.update(entry, last);
}, [entry, registry.draggable]);
}
var DroppableContext = React__default.createContext(null);
function checkIsValidInnerRef(el) {
!(el && isHtmlElement(el)) ? process.env.NODE_ENV !== "production" ? invariant(false, `
provided.innerRef has not been provided with a HTMLElement.
You can find a guide on using the innerRef callback functions at:
https://github.com/hello-pangea/dnd/blob/main/docs/guides/using-inner-ref.md
`) : invariant() : void 0;
}
function useValidation$1(props, contextId, getRef) {
useDevSetupWarning(() => {
function prefix2(id2) {
return `Draggable[id: ${id2}]: `;
}
const id = props.draggableId;
!id ? process.env.NODE_ENV !== "production" ? invariant(false, "Draggable requires a draggableId") : invariant(false) : void 0;
!(typeof id === "string") ? process.env.NODE_ENV !== "production" ? invariant(false, `Draggable requires a [string] draggableId.
Provided: [type: ${typeof id}] (value: ${id})`) : invariant(false) : void 0;
!Number.isInteger(props.index) ? process.env.NODE_ENV !== "production" ? invariant(false, `${prefix2(id)} requires an integer index prop`) : invariant(false) : void 0;
if (props.mapped.type === "DRAGGING") {
return;
}
checkIsValidInnerRef(getRef());
if (props.isEnabled) {
!findDragHandle(contextId, id) ? process.env.NODE_ENV !== "production" ? invariant(false, `${prefix2(id)} Unable to find drag handle`) : invariant(false) : void 0;
}
});
}
function useClonePropValidation(isClone) {
useDev(() => {
const initialRef = useRef(isClone);
useDevSetupWarning(() => {
!(isClone === initialRef.current) ? process.env.NODE_ENV !== "production" ? invariant(false, "Draggable isClone prop value changed during component life") : invariant(false) : void 0;
}, [isClone]);
});
}
function useRequiredContext(Context) {
const result = useContext$a(Context);
!result ? process.env.NODE_ENV !== "production" ? invariant(false, "Could not find required context") : invariant() : void 0;
return result;
}
function preventHtml5Dnd(event) {
event.preventDefault();
}
const Draggable = (props) => {
const ref2 = useRef(null);
const setRef = useCallback((el = null) => {
ref2.current = el;
}, []);
const getRef = useCallback(() => ref2.current, []);
const {
contextId,
dragHandleUsageInstructionsId,
registry
} = useRequiredContext(AppContext);
const {
type,
droppableId
} = useRequiredContext(DroppableContext);
const descriptor = useMemo(() => ({
id: props.draggableId,
index: props.index,
type,
droppableId
}), [props.draggableId, props.index, type, droppableId]);
const {
children,
draggableId,
isEnabled,
shouldRespectForcePress,
canDragInteractiveElements,
isClone,
mapped,
dropAnimationFinished: dropAnimationFinishedAction
} = props;
useValidation$1(props, contextId, getRef);
useClonePropValidation(isClone);
if (!isClone) {
const forPublisher = useMemo(() => ({
descriptor,
registry,
getDraggableRef: getRef,
canDragInteractiveElements,
shouldRespectForcePress,
isEnabled
}), [descriptor, registry, getRef, canDragInteractiveElements, shouldRespectForcePress, isEnabled]);
useDraggablePublisher(forPublisher);
}
const dragHandleProps = useMemo(() => isEnabled ? {
tabIndex: 0,
role: "button",
"aria-describedby": dragHandleUsageInstructionsId,
"data-rfd-drag-handle-draggable-id": draggableId,
"data-rfd-drag-handle-context-id": contextId,
draggable: false,
onDragStart: preventHtml5Dnd
} : null, [contextId, dragHandleUsageInstructionsId, draggableId, isEnabled]);
const onMoveEnd = useCallback((event) => {
if (mapped.type !== "DRAGGING") {
return;
}
if (!mapped.dropping) {
return;
}
if (event.propertyName !== "transform") {
return;
}
if (React__default.version.startsWith("16") || React__default.version.startsWith("17")) {
dropAnimationFinishedAction();
} else {
flushSync(dropAnimationFinishedAction);
}
}, [dropAnimationFinishedAction, mapped]);
const provided = useMemo(() => {
const style2 = getStyle$1(mapped);
const onTransitionEnd = mapped.type === "DRAGGING" && mapped.dropping ? onMoveEnd : void 0;
const result = {
innerRef: setRef,
draggableProps: {
"data-rfd-draggable-context-id": contextId,
"data-rfd-draggable-id": draggableId,
style: style2,
onTransitionEnd
},
dragHandleProps
};
return result;
}, [contextId, dragHandleProps, draggableId, mapped, onMoveEnd, setRef]);
const rubric = useMemo(() => ({
draggableId: descriptor.id,
type: descriptor.type,
source: {
index: descriptor.index,
droppableId: descriptor.droppableId
}
}), [descriptor.droppableId, descriptor.id, descriptor.index, descriptor.type]);
return React__default.createElement(React__default.Fragment, null, children(provided, mapped.snapshot, rubric));
};
var Draggable$1 = Draggable;
var isStrictEqual = (a, b) => a === b;
var whatIsDraggedOverFromResult = (result) => {
const {
combine: combine2,
destination
} = result;
if (destination) {
return destination.droppableId;
}
if (combine2) {
return combine2.droppableId;
}
return null;
};
const getCombineWithFromResult = (result) => {
return result.combine ? result.combine.draggableId : null;
};
const getCombineWithFromImpact = (impact) => {
return impact.at && impact.at.type === "COMBINE" ? impact.at.combine.draggableId : null;
};
function getDraggableSelector() {
const memoizedOffset = memoizeOne((x, y) => ({
x,
y
}));
const getMemoizedSnapshot = memoizeOne((mode, isClone, draggingOver = null, combineWith = null, dropping = null) => ({
isDragging: true,
isClone,
isDropAnimating: Boolean(dropping),
dropAnimation: dropping,
mode,
draggingOver,
combineWith,
combineTargetFor: null
}));
const getMemoizedProps = memoizeOne((offset3, mode, dimension, isClone, draggingOver = null, combineWith = null, forceShouldAnimate = null) => ({
mapped: {
type: "DRAGGING",
dropping: null,
draggingOver,
combineWith,
mode,
offset: offset3,
dimension,
forceShouldAnimate,
snapshot: getMemoizedSnapshot(mode, isClone, draggingOver, combineWith, null)
}
}));
const selector = (state, ownProps) => {
if (isDragging(state)) {
if (state.critical.draggable.id !== ownProps.draggableId) {
return null;
}
const offset3 = state.current.client.offset;
const dimension = state.dimensions.draggables[ownProps.draggableId];
const draggingOver = whatIsDraggedOver(state.impact);
const combineWith = getCombineWithFromImpact(state.impact);
const forceShouldAnimate = state.forceShouldAnimate;
return getMemoizedProps(memoizedOffset(offset3.x, offset3.y), state.movementMode, dimension, ownProps.isClone, draggingOver, combineWith, forceShouldAnimate);
}
if (state.phase === "DROP_ANIMATING") {
const completed = state.completed;
if (completed.result.draggableId !== ownProps.draggableId) {
return null;
}
const isClone = ownProps.isClone;
const dimension = state.dimensions.draggables[ownProps.draggableId];
const result = completed.result;
const mode = result.mode;
const draggingOver = whatIsDraggedOverFromResult(result);
const combineWith = getCombineWithFromResult(result);
const duration = state.dropDuration;
const dropping = {
duration,
curve: curves.drop,
moveTo: state.newHomeClientOffset,
opacity: combineWith ? combine.opacity.drop : null,
scale: combineWith ? combine.scale.drop : null
};
return {
mapped: {
type: "DRAGGING",
offset: state.newHomeClientOffset,
dimension,
dropping,
draggingOver,
combineWith,
mode,
forceShouldAnimate: null,
snapshot: getMemoizedSnapshot(mode, isClone, draggingOver, combineWith, dropping)
}
};
}
return null;
};
return selector;
}
function getSecondarySnapshot(combineTargetFor = null) {
return {
isDragging: false,
isDropAnimating: false,
isClone: false,
dropAnimation: null,
mode: null,
draggingOver: null,
combineTargetFor,
combineWith: null
};
}
const atRest = {
mapped: {
type: "SECONDARY",
offset: origin,
combineTargetFor: null,
shouldAnimateDisplacement: true,
snapshot: getSecondarySnapshot(null)
}
};
function getSecondarySelector() {
const memoizedOffset = memoizeOne((x, y) => ({
x,
y
}));
const getMemoizedSnapshot = memoizeOne(getSecondarySnapshot);
const getMemoizedProps = memoizeOne((offset3, combineTargetFor = null, shouldAnimateDisplacement) => ({
mapped: {
type: "SECONDARY",
offset: offset3,
combineTargetFor,
shouldAnimateDisplacement,
snapshot: getMemoizedSnapshot(combineTargetFor)
}
}));
const getFallback = (combineTargetFor) => {
return combineTargetFor ? getMemoizedProps(origin, combineTargetFor, true) : null;
};
const getProps = (ownId, draggingId, impact, afterCritical) => {
const visualDisplacement = impact.displaced.visible[ownId];
const isAfterCriticalInVirtualList = Boolean(afterCritical.inVirtualList && afterCritical.effected[ownId]);
const combine2 = tryGetCombine(impact);
const combineTargetFor = combine2 && combine2.draggableId === ownId ? draggingId : null;
if (!visualDisplacement) {
if (!isAfterCriticalInVirtualList) {
return getFallback(combineTargetFor);
}
if (impact.displaced.invisible[ownId]) {
return null;
}
const change = negate(afterCritical.displacedBy.point);
const offset4 = memoizedOffset(change.x, change.y);
return getMemoizedProps(offset4, combineTargetFor, true);
}
if (isAfterCriticalInVirtualList) {
return getFallback(combineTargetFor);
}
const displaceBy = impact.displacedBy.point;
const offset3 = memoizedOffset(displaceBy.x, displaceBy.y);
return getMemoizedProps(offset3, combineTargetFor, visualDisplacement.shouldAnimate);
};
const selector = (state, ownProps) => {
if (isDragging(state)) {
if (state.critical.draggable.id === ownProps.draggableId) {
return null;
}
return getProps(ownProps.draggableId, state.critical.draggable.id, state.impact, state.afterCritical);
}
if (state.phase === "DROP_ANIMATING") {
const completed = state.completed;
if (completed.result.draggableId === ownProps.draggableId) {
return null;
}
return getProps(ownProps.draggableId, completed.result.draggableId, completed.impact, completed.afterCritical);
}
return null;
};
return selector;
}
const makeMapStateToProps$1 = () => {
const draggingSelector = getDraggableSelector();
const secondarySelector = getSecondarySelector();
const selector = (state, ownProps) => draggingSelector(state, ownProps) || secondarySelector(state, ownProps) || atRest;
return selector;
};
const mapDispatchToProps$1 = {
dropAnimationFinished
};
const ConnectedDraggable = connect(makeMapStateToProps$1, mapDispatchToProps$1, null, {
context: StoreContext,
areStatePropsEqual: isStrictEqual
})(Draggable$1);
var ConnectedDraggable$1 = ConnectedDraggable;
function PrivateDraggable(props) {
const droppableContext = useRequiredContext(DroppableContext);
const isUsingCloneFor = droppableContext.isUsingCloneFor;
if (isUsingCloneFor === props.draggableId && !props.isClone) {
return null;
}
return React__default.createElement(ConnectedDraggable$1, props);
}
function PublicDraggable(props) {
const isEnabled = typeof props.isDragDisabled === "boolean" ? !props.isDragDisabled : true;
const canDragInteractiveElements = Boolean(props.disableInteractiveElementBlocking);
const shouldRespectForcePress = Boolean(props.shouldRespectForcePress);
return React__default.createElement(PrivateDraggable, _extends({}, props, {
isClone: false,
isEnabled,
canDragInteractiveElements,
shouldRespectForcePress
}));
}
const isEqual = (base) => (value) => base === value;
const isScroll = isEqual("scroll");
const isAuto = isEqual("auto");
const isVisible = isEqual("visible");
const isEither = (overflow, fn) => fn(overflow.overflowX) || fn(overflow.overflowY);
const isBoth = (overflow, fn) => fn(overflow.overflowX) && fn(overflow.overflowY);
const isElementScrollable = (el) => {
const style2 = window.getComputedStyle(el);
const overflow = {
overflowX: style2.overflowX,
overflowY: style2.overflowY
};
return isEither(overflow, isScroll) || isEither(overflow, isAuto);
};
const isBodyScrollable = () => {
if (process.env.NODE_ENV === "production") {
return false;
}
const body = getBodyElement();
const html = document.documentElement;
!html ? process.env.NODE_ENV !== "production" ? invariant() : invariant() : void 0;
if (!isElementScrollable(body)) {
return false;
}
const htmlStyle = window.getComputedStyle(html);
const htmlOverflow = {
overflowX: htmlStyle.overflowX,
overflowY: htmlStyle.overflowY
};
if (isBoth(htmlOverflow, isVisible)) {
return false;
}
process.env.NODE_ENV !== "production" ? warning(`
We have detected that your <body> element might be a scroll container.
We have found no reliable way of detecting whether the <body> element is a scroll container.
Under most circumstances a <body> scroll bar will be on the <html> element (document.documentElement)
Because we cannot determine if the <body> is a scroll container, and generally it is not one,
we will be treating the <body> as *not* a scroll container
More information: https://github.com/hello-pangea/dnd/blob/main/docs/guides/how-we-detect-scroll-containers.md
`) : void 0;
return false;
};
const getClosestScrollable = (el) => {
if (el == null) {
return null;
}
if (el === document.body) {
return isBodyScrollable() ? el : null;
}
if (el === document.documentElement) {
return null;
}
if (!isElementScrollable(el)) {
return getClosestScrollable(el.parentElement);
}
return el;
};
var checkForNestedScrollContainers = (scrollable) => {
if (!scrollable) {
return;
}
const anotherScrollParent = getClosestScrollable(scrollable.parentElement);
if (!anotherScrollParent) {
return;
}
process.env.NODE_ENV !== "production" ? warning(`
Droppable: unsupported nested scroll container detected.
A Droppable can only have one scroll parent (which can be itself)
Nested scroll containers are currently not supported.
We hope to support nested scroll containers soon: https://github.com/atlassian/react-beautiful-dnd/issues/131
`) : void 0;
};
var getScroll = (el) => ({
x: el.scrollLeft,
y: el.scrollTop
});
const getIsFixed = (el) => {
if (!el) {
return false;
}
const style2 = window.getComputedStyle(el);
if (style2.position === "fixed") {
return true;
}
return getIsFixed(el.parentElement);
};
var getEnv = (start2) => {
const closestScrollable = getClosestScrollable(start2);
const isFixedOnPage = getIsFixed(start2);
return {
closestScrollable,
isFixedOnPage
};
};
var getDroppableDimension = ({
descriptor,
isEnabled,
isCombineEnabled,
isFixedOnPage,
direction,
client,
page,
closest: closest2
}) => {
const frame2 = (() => {
if (!closest2) {
return null;
}
const {
scrollSize,
client: frameClient
} = closest2;
const maxScroll = getMaxScroll({
scrollHeight: scrollSize.scrollHeight,
scrollWidth: scrollSize.scrollWidth,
height: frameClient.paddingBox.height,
width: frameClient.paddingBox.width
});
return {
pageMarginBox: closest2.page.marginBox,
frameClient,
scrollSize,
shouldClipSubject: closest2.shouldClipSubject,
scroll: {
initial: closest2.scroll,
current: closest2.scroll,
max: maxScroll,
diff: {
value: origin,
displacement: origin
}
}
};
})();
const axis = direction === "vertical" ? vertical : horizontal;
const subject = getSubject({
page,
withPlaceholder: null,
axis,
frame: frame2
});
const dimension = {
descriptor,
isCombineEnabled,
isFixedOnPage,
axis,
isEnabled,
client,
page,
frame: frame2,
subject
};
return dimension;
};
const getClient = (targetRef, closestScrollable) => {
const base = getBox(targetRef);
if (!closestScrollable) {
return base;
}
if (targetRef !== closestScrollable) {
return base;
}
const top = base.paddingBox.top - closestScrollable.scrollTop;
const left = base.paddingBox.left - closestScrollable.scrollLeft;
const bottom = top + closestScrollable.scrollHeight;
const right = left + closestScrollable.scrollWidth;
const paddingBox = {
top,
right,
bottom,
left
};
const borderBox = expand(paddingBox, base.border);
const client = createBox({
borderBox,
margin: base.margin,
border: base.border,
padding: base.padding
});
return client;
};
var getDimension = ({
ref: ref2,
descriptor,
env,
windowScroll,
direction,
isDropDisabled,
isCombineEnabled,
shouldClipSubject
}) => {
const closestScrollable = env.closestScrollable;
const client = getClient(ref2, closestScrollable);
const page = withScroll(client, windowScroll);
const closest2 = (() => {
if (!closestScrollable) {
return null;
}
const frameClient = getBox(closestScrollable);
const scrollSize = {
scrollHeight: closestScrollable.scrollHeight,
scrollWidth: closestScrollable.scrollWidth
};
return {
client: frameClient,
page: withScroll(frameClient, windowScroll),
scroll: getScroll(closestScrollable),
scrollSize,
shouldClipSubject
};
})();
const dimension = getDroppableDimension({
descriptor,
isEnabled: !isDropDisabled,
isCombineEnabled,
isFixedOnPage: env.isFixedOnPage,
direction,
client,
page,
closest: closest2
});
return dimension;
};
const immediate = {
passive: false
};
const delayed = {
passive: true
};
var getListenerOptions = (options) => options.shouldPublishImmediately ? immediate : delayed;
const getClosestScrollableFromDrag = (dragging) => dragging && dragging.env.closestScrollable || null;
function useDroppablePublisher(args) {
const whileDraggingRef = useRef(null);
const appContext = useRequiredContext(AppContext);
const uniqueId = useUniqueId$1("droppable");
const {
registry,
marshal
} = appContext;
const previousRef = usePrevious(args);
const descriptor = useMemo(() => ({
id: args.droppableId,
type: args.type,
mode: args.mode
}), [args.droppableId, args.mode, args.type]);
const publishedDescriptorRef = useRef(descriptor);
const memoizedUpdateScroll = useMemo(() => memoizeOne((x, y) => {
!whileDraggingRef.current ? process.env.NODE_ENV !== "production" ? invariant(false, "Can only update scroll when dragging") : invariant() : void 0;
const scroll3 = {
x,
y
};
marshal.updateDroppableScroll(descriptor.id, scroll3);
}), [descriptor.id, marshal]);
const getClosestScroll = useCallback(() => {
const dragging = whileDraggingRef.current;
if (!dragging || !dragging.env.closestScrollable) {
return origin;
}
return getScroll(dragging.env.closestScrollable);
}, []);
const updateScroll = useCallback(() => {
const scroll3 = getClosestScroll();
memoizedUpdateScroll(scroll3.x, scroll3.y);
}, [getClosestScroll, memoizedUpdateScroll]);
const scheduleScrollUpdate = useMemo(() => rafSchd(updateScroll), [updateScroll]);
const onClosestScroll = useCallback(() => {
const dragging = whileDraggingRef.current;
const closest2 = getClosestScrollableFromDrag(dragging);
!(dragging && closest2) ? process.env.NODE_ENV !== "production" ? invariant(false, "Could not find scroll options while scrolling") : invariant() : void 0;
const options = dragging.scrollOptions;
if (options.shouldPublishImmediately) {
updateScroll();
return;
}
scheduleScrollUpdate();
}, [scheduleScrollUpdate, updateScroll]);
const getDimensionAndWatchScroll = useCallback((windowScroll, options) => {
!!whileDraggingRef.current ? process.env.NODE_ENV !== "production" ? invariant(false, "Cannot collect a droppable while a drag is occurring") : invariant() : void 0;
const previous = previousRef.current;
const ref2 = previous.getDroppableRef();
!ref2 ? process.env.NODE_ENV !== "production" ? invariant(false, "Cannot collect without a droppable ref") : invariant() : void 0;
const env = getEnv(ref2);
const dragging = {
ref: ref2,
descriptor,
env,
scrollOptions: options
};
whileDraggingRef.current = dragging;
const dimension = getDimension({
ref: ref2,
descriptor,
env,
windowScroll,
direction: previous.direction,
isDropDisabled: previous.isDropDisabled,
isCombineEnabled: previous.isCombineEnabled,
shouldClipSubject: !previous.ignoreContainerClipping
});
const scrollable = env.closestScrollable;
if (scrollable) {
scrollable.setAttribute(scrollContainer.contextId, appContext.contextId);
scrollable.addEventListener("scroll", onClosestScroll, getListenerOptions(dragging.scrollOptions));
if (process.env.NODE_ENV !== "production") {
checkForNestedScrollContainers(scrollable);
}
}
return dimension;
}, [appContext.contextId, descriptor, onClosestScroll, previousRef]);
const getScrollWhileDragging = useCallback(() => {
const dragging = whileDraggingRef.current;
const closest2 = getClosestScrollableFromDrag(dragging);
!(dragging && closest2) ? process.env.NODE_ENV !== "production" ? invariant(false, "Can only recollect Droppable client for Droppables that have a scroll container") : invariant() : void 0;
return getScroll(closest2);
}, []);
const dragStopped = useCallback(() => {
const dragging = whileDraggingRef.current;
!dragging ? process.env.NODE_ENV !== "production" ? invariant(false, "Cannot stop drag when no active drag") : invariant() : void 0;
const closest2 = getClosestScrollableFromDrag(dragging);
whileDraggingRef.current = null;
if (!closest2) {
return;
}
scheduleScrollUpdate.cancel();
closest2.removeAttribute(scrollContainer.contextId);
closest2.removeEventListener("scroll", onClosestScroll, getListenerOptions(dragging.scrollOptions));
}, [onClosestScroll, scheduleScrollUpdate]);
const scroll2 = useCallback((change) => {
const dragging = whileDraggingRef.current;
!dragging ? process.env.NODE_ENV !== "production" ? invariant(false, "Cannot scroll when there is no drag") : invariant() : void 0;
const closest2 = getClosestScrollableFromDrag(dragging);
!closest2 ? process.env.NODE_ENV !== "production" ? invariant(false, "Cannot scroll a droppable with no closest scrollable") : invariant() : void 0;
closest2.scrollTop += change.y;
closest2.scrollLeft += change.x;
}, []);
const callbacks = useMemo(() => {
return {
getDimensionAndWatchScroll,
getScrollWhileDragging,
dragStopped,
scroll: scroll2
};
}, [dragStopped, getDimensionAndWatchScroll, getScrollWhileDragging, scroll2]);
const entry = useMemo(() => ({
uniqueId,
descriptor,
callbacks
}), [callbacks, descriptor, uniqueId]);
useLayoutEffect(() => {
publishedDescriptorRef.current = entry.descriptor;
registry.droppable.register(entry);
return () => {
if (whileDraggingRef.current) {
process.env.NODE_ENV !== "production" ? warning("Unsupported: changing the droppableId or type of a Droppable during a drag") : void 0;
dragStopped();
}
registry.droppable.unregister(entry);
};
}, [callbacks, descriptor, dragStopped, entry, marshal, registry.droppable]);
useLayoutEffect(() => {
if (!whileDraggingRef.current) {
return;
}
marshal.updateDroppableIsEnabled(publishedDescriptorRef.current.id, !args.isDropDisabled);
}, [args.isDropDisabled, marshal]);
useLayoutEffect(() => {
if (!whileDraggingRef.current) {
return;
}
marshal.updateDroppableIsCombineEnabled(publishedDescriptorRef.current.id, args.isCombineEnabled);
}, [args.isCombineEnabled, marshal]);
}
function noop() {
}
const empty = {
width: 0,
height: 0,
margin: noSpacing
};
const getSize = ({
isAnimatingOpenOnMount,
placeholder: placeholder2,
animate
}) => {
if (isAnimatingOpenOnMount) {
return empty;
}
if (animate === "close") {
return empty;
}
return {
height: placeholder2.client.borderBox.height,
width: placeholder2.client.borderBox.width,
margin: placeholder2.client.margin
};
};
const getStyle = ({
isAnimatingOpenOnMount,
placeholder: placeholder2,
animate
}) => {
const size = getSize({
isAnimatingOpenOnMount,
placeholder: placeholder2,
animate
});
return {
display: placeholder2.display,
boxSizing: "border-box",
width: size.width,
height: size.height,
marginTop: size.margin.top,
marginRight: size.margin.right,
marginBottom: size.margin.bottom,
marginLeft: size.margin.left,
flexShrink: "0",
flexGrow: "0",
pointerEvents: "none",
transition: animate !== "none" ? transitions.placeholder : null
};
};
const Placeholder = (props) => {
const animateOpenTimerRef = useRef(null);
const tryClearAnimateOpenTimer = useCallback(() => {
if (!animateOpenTimerRef.current) {
return;
}
clearTimeout(animateOpenTimerRef.current);
animateOpenTimerRef.current = null;
}, []);
const {
animate,
onTransitionEnd,
onClose,
contextId
} = props;
const [isAnimatingOpenOnMount, setIsAnimatingOpenOnMount] = useState(props.animate === "open");
useEffect(() => {
if (!isAnimatingOpenOnMount) {
return noop;
}
if (animate !== "open") {
tryClearAnimateOpenTimer();
setIsAnimatingOpenOnMount(false);
return noop;
}
if (animateOpenTimerRef.current) {
return noop;
}
animateOpenTimerRef.current = setTimeout(() => {
animateOpenTimerRef.current = null;
setIsAnimatingOpenOnMount(false);
});
return tryClearAnimateOpenTimer;
}, [animate, isAnimatingOpenOnMount, tryClearAnimateOpenTimer]);
const onSizeChangeEnd = useCallback((event) => {
if (event.propertyName !== "height") {
return;
}
onTransitionEnd();
if (animate === "close") {
onClose();
}
}, [animate, onClose, onTransitionEnd]);
const style2 = getStyle({
isAnimatingOpenOnMount,
animate: props.animate,
placeholder: props.placeholder
});
return React__default.createElement(props.placeholder.tagName, {
style: style2,
"data-rfd-placeholder-context-id": contextId,
onTransitionEnd: onSizeChangeEnd,
ref: props.innerRef
});
};
var Placeholder$1 = React__default.memo(Placeholder);
function isBoolean(value) {
return typeof value === "boolean";
}
function runChecks(args, checks) {
checks.forEach((check) => check(args));
}
const shared = [function required({
props
}) {
!props.droppableId ? process.env.NODE_ENV !== "production" ? invariant(false, "A Droppable requires a droppableId prop") : invariant() : void 0;
!(typeof props.droppableId === "string") ? process.env.NODE_ENV !== "production" ? invariant(false, `A Droppable requires a [string] droppableId. Provided: [${typeof props.droppableId}]`) : invariant() : void 0;
}, function boolean({
props
}) {
!isBoolean(props.isDropDisabled) ? process.env.NODE_ENV !== "production" ? invariant(false, "isDropDisabled must be a boolean") : invariant() : void 0;
!isBoolean(props.isCombineEnabled) ? process.env.NODE_ENV !== "production" ? invariant(false, "isCombineEnabled must be a boolean") : invariant() : void 0;
!isBoolean(props.ignoreContainerClipping) ? process.env.NODE_ENV !== "production" ? invariant(false, "ignoreContainerClipping must be a boolean") : invariant() : void 0;
}, function ref({
getDroppableRef
}) {
checkIsValidInnerRef(getDroppableRef());
}];
const standard = [function placeholder({
props,
getPlaceholderRef
}) {
if (!props.placeholder) {
return;
}
const ref2 = getPlaceholderRef();
if (ref2) {
return;
}
process.env.NODE_ENV !== "production" ? warning(`
Droppable setup issue [droppableId: "${props.droppableId}"]:
DroppableProvided > placeholder could not be found.
Please be sure to add the {provided.placeholder} React Node as a child of your Droppable.
More information: https://github.com/hello-pangea/dnd/blob/main/docs/api/droppable.md
`) : void 0;
}];
const virtual = [function hasClone({
props
}) {
!props.renderClone ? process.env.NODE_ENV !== "production" ? invariant(false, "Must provide a clone render function (renderClone) for virtual lists") : invariant() : void 0;
}, function hasNoPlaceholder({
getPlaceholderRef
}) {
!!getPlaceholderRef() ? process.env.NODE_ENV !== "production" ? invariant(false, "Expected virtual list to not have a placeholder") : invariant() : void 0;
}];
function useValidation(args) {
useDevSetupWarning(() => {
runChecks(args, shared);
if (args.props.mode === "standard") {
runChecks(args, standard);
}
if (args.props.mode === "virtual") {
runChecks(args, virtual);
}
});
}
class AnimateInOut extends React__default.PureComponent {
constructor(...args) {
super(...args);
this.state = {
isVisible: Boolean(this.props.on),
data: this.props.on,
animate: this.props.shouldAnimate && this.props.on ? "open" : "none"
};
this.onClose = () => {
if (this.state.animate !== "close") {
return;
}
this.setState({
isVisible: false
});
};
}
static getDerivedStateFromProps(props, state) {
if (!props.shouldAnimate) {
return {
isVisible: Boolean(props.on),
data: props.on,
animate: "none"
};
}
if (props.on) {
return {
isVisible: true,
data: props.on,
animate: "open"
};
}
if (state.isVisible) {
return {
isVisible: true,
data: state.data,
animate: "close"
};
}
return {
isVisible: false,
animate: "close",
data: null
};
}
render() {
if (!this.state.isVisible) {
return null;
}
const provided = {
onClose: this.onClose,
data: this.state.data,
animate: this.state.animate
};
return this.props.children(provided);
}
}
const Droppable = (props) => {
const appContext = useContext$a(AppContext);
!appContext ? process.env.NODE_ENV !== "production" ? invariant(false, "Could not find app context") : invariant() : void 0;
const {
contextId,
isMovementAllowed: isMovementAllowed2
} = appContext;
const droppableRef = useRef(null);
const placeholderRef = useRef(null);
const {
children,
droppableId,
type,
mode,
direction,
ignoreContainerClipping,
isDropDisabled,
isCombineEnabled,
snapshot,
useClone,
updateViewportMaxScroll: updateViewportMaxScroll2,
getContainerForClone
} = props;
const getDroppableRef = useCallback(() => droppableRef.current, []);
const setDroppableRef = useCallback((value = null) => {
droppableRef.current = value;
}, []);
const getPlaceholderRef = useCallback(() => placeholderRef.current, []);
const setPlaceholderRef = useCallback((value = null) => {
placeholderRef.current = value;
}, []);
useValidation({
props,
getDroppableRef,
getPlaceholderRef
});
const onPlaceholderTransitionEnd = useCallback(() => {
if (isMovementAllowed2()) {
updateViewportMaxScroll2({
maxScroll: getMaxWindowScroll()
});
}
}, [isMovementAllowed2, updateViewportMaxScroll2]);
useDroppablePublisher({
droppableId,
type,
mode,
direction,
isDropDisabled,
isCombineEnabled,
ignoreContainerClipping,
getDroppableRef
});
const placeholder2 = useMemo(() => React__default.createElement(AnimateInOut, {
on: props.placeholder,
shouldAnimate: props.shouldAnimatePlaceholder
}, ({
onClose,
data,
animate
}) => React__default.createElement(Placeholder$1, {
placeholder: data,
onClose,
innerRef: setPlaceholderRef,
animate,
contextId,
onTransitionEnd: onPlaceholderTransitionEnd
})), [contextId, onPlaceholderTransitionEnd, props.placeholder, props.shouldAnimatePlaceholder, setPlaceholderRef]);
const provided = useMemo(() => ({
innerRef: setDroppableRef,
placeholder: placeholder2,
droppableProps: {
"data-rfd-droppable-id": droppableId,
"data-rfd-droppable-context-id": contextId
}
}), [contextId, droppableId, placeholder2, setDroppableRef]);
const isUsingCloneFor = useClone ? useClone.dragging.draggableId : null;
const droppableContext = useMemo(() => ({
droppableId,
type,
isUsingCloneFor
}), [droppableId, isUsingCloneFor, type]);
function getClone() {
if (!useClone) {
return null;
}
const {
dragging,
render
} = useClone;
const node = React__default.createElement(PrivateDraggable, {
draggableId: dragging.draggableId,
index: dragging.source.index,
isClone: true,
isEnabled: true,
shouldRespectForcePress: false,
canDragInteractiveElements: true
}, (draggableProvided, draggableSnapshot) => render(draggableProvided, draggableSnapshot, dragging));
return require$$2.createPortal(node, getContainerForClone());
}
return React__default.createElement(DroppableContext.Provider, {
value: droppableContext
}, children(provided, snapshot), getClone());
};
var Droppable$1 = Droppable;
function getBody() {
!document.body ? process.env.NODE_ENV !== "production" ? invariant(false, "document.body is not ready") : invariant() : void 0;
return document.body;
}
const defaultProps = {
mode: "standard",
type: "DEFAULT",
direction: "vertical",
isDropDisabled: false,
isCombineEnabled: false,
ignoreContainerClipping: false,
renderClone: null,
getContainerForClone: getBody
};
const attachDefaultPropsToOwnProps = (ownProps) => {
let mergedProps = {
...ownProps
};
let defaultPropKey;
for (defaultPropKey in defaultProps) {
if (ownProps[defaultPropKey] === void 0) {
mergedProps = {
...mergedProps,
[defaultPropKey]: defaultProps[defaultPropKey]
};
}
}
return mergedProps;
};
const isMatchingType = (type, critical) => type === critical.droppable.type;
const getDraggable = (critical, dimensions) => dimensions.draggables[critical.draggable.id];
const makeMapStateToProps = () => {
const idleWithAnimation = {
placeholder: null,
shouldAnimatePlaceholder: true,
snapshot: {
isDraggingOver: false,
draggingOverWith: null,
draggingFromThisWith: null,
isUsingPlaceholder: false
},
useClone: null
};
const idleWithoutAnimation = {
...idleWithAnimation,
shouldAnimatePlaceholder: false
};
const getDraggableRubric = memoizeOne((descriptor) => ({
draggableId: descriptor.id,
type: descriptor.type,
source: {
index: descriptor.index,
droppableId: descriptor.droppableId
}
}));
const getMapProps = memoizeOne((id, isEnabled, isDraggingOverForConsumer, isDraggingOverForImpact, dragging, renderClone) => {
const draggableId = dragging.descriptor.id;
const isHome = dragging.descriptor.droppableId === id;
if (isHome) {
const useClone = renderClone ? {
render: renderClone,
dragging: getDraggableRubric(dragging.descriptor)
} : null;
const snapshot2 = {
isDraggingOver: isDraggingOverForConsumer,
draggingOverWith: isDraggingOverForConsumer ? draggableId : null,
draggingFromThisWith: draggableId,
isUsingPlaceholder: true
};
return {
placeholder: dragging.placeholder,
shouldAnimatePlaceholder: false,
snapshot: snapshot2,
useClone
};
}
if (!isEnabled) {
return idleWithoutAnimation;
}
if (!isDraggingOverForImpact) {
return idleWithAnimation;
}
const snapshot = {
isDraggingOver: isDraggingOverForConsumer,
draggingOverWith: draggableId,
draggingFromThisWith: null,
isUsingPlaceholder: true
};
return {
placeholder: dragging.placeholder,
shouldAnimatePlaceholder: true,
snapshot,
useClone: null
};
});
const selector = (state, ownProps) => {
const ownPropsWithDefaultProps = attachDefaultPropsToOwnProps(ownProps);
const id = ownPropsWithDefaultProps.droppableId;
const type = ownPropsWithDefaultProps.type;
const isEnabled = !ownPropsWithDefaultProps.isDropDisabled;
const renderClone = ownPropsWithDefaultProps.renderClone;
if (isDragging(state)) {
const critical = state.critical;
if (!isMatchingType(type, critical)) {
return idleWithoutAnimation;
}
const dragging = getDraggable(critical, state.dimensions);
const isDraggingOver = whatIsDraggedOver(state.impact) === id;
return getMapProps(id, isEnabled, isDraggingOver, isDraggingOver, dragging, renderClone);
}
if (state.phase === "DROP_ANIMATING") {
const completed = state.completed;
if (!isMatchingType(type, completed.critical)) {
return idleWithoutAnimation;
}
const dragging = getDraggable(completed.critical, state.dimensions);
return getMapProps(id, isEnabled, whatIsDraggedOverFromResult(completed.result) === id, whatIsDraggedOver(completed.impact) === id, dragging, renderClone);
}
if (state.phase === "IDLE" && state.completed && !state.shouldFlush) {
const completed = state.completed;
if (!isMatchingType(type, completed.critical)) {
return idleWithoutAnimation;
}
const wasOver = whatIsDraggedOver(completed.impact) === id;
const wasCombining = Boolean(completed.impact.at && completed.impact.at.type === "COMBINE");
const isHome = completed.critical.droppable.id === id;
if (wasOver) {
return wasCombining ? idleWithAnimation : idleWithoutAnimation;
}
if (isHome) {
return idleWithAnimation;
}
return idleWithoutAnimation;
}
return idleWithoutAnimation;
};
return selector;
};
const mapDispatchToProps = {
updateViewportMaxScroll
};
const ConnectedDroppable = connect(makeMapStateToProps, mapDispatchToProps, (stateProps, dispatchProps, ownProps) => {
return {
...attachDefaultPropsToOwnProps(ownProps),
...stateProps,
...dispatchProps
};
}, {
context: StoreContext,
areStatePropsEqual: isStrictEqual
})(Droppable$1);
var ConnectedDroppable$1 = ConnectedDroppable;
const TaskbarEntry = lazy(() => import("./index-BA88Gpwx.js").then((n) => n.i));
const StyledDraggableEntryContainer = styled.div`
display: flex;
min-width: 0;
overflow: hidden;
place-content: center;
position: relative;
cursor: default;
`;
const TaskbarEntries = ({ clockWidth }) => {
const { windows } = useContext$4();
const { applications } = useContext$2();
const [sequence, setSequence] = useState([]);
const [windowOrder, setWindowOrder] = useState(
/* @__PURE__ */ new Map()
);
useEffect(() => {
const initialSequence = Object.keys(windows).map((id) => ({
type: "window",
windowID: id
}));
setSequence(initialSequence);
const initialOrder = /* @__PURE__ */ new Map();
Object.keys(windows).forEach((id, index) => {
initialOrder.set(id, index);
});
setWindowOrder(initialOrder);
}, []);
useEffect(() => {
setSequence((prevSequence) => {
const windowIds = Object.keys(windows);
const newSequence = prevSequence.filter(
(item) => windowIds.includes(item.windowID)
);
const newWindows = windowIds.filter(
(id) => !newSequence.some((item) => item.windowID === id)
);
newWindows.forEach((id) => {
newSequence.push({ type: "window", windowID: id });
setWindowOrder((prevOrder) => {
const newOrder = new Map(prevOrder);
newOrder.set(id, newSequence.length - 1);
return newOrder;
});
});
newSequence.sort(
(a, b) => (windowOrder.get(a.windowID) ?? 0) - (windowOrder.get(b.windowID) ?? 0)
);
return newSequence;
});
}, [windows, windowOrder]);
const onDragEnd2 = useCallback$1((result) => {
if (!result.destination) return;
const newItems = Array.from(sequence);
const [movedItem] = newItems.splice(result.source.index, 1);
newItems.splice(result.destination.index, 0, movedItem);
setSequence(newItems);
const newOrder = /* @__PURE__ */ new Map();
newItems.forEach((item, index) => {
newOrder.set(item.windowID, index);
});
setWindowOrder(newOrder);
}, [sequence]);
const pinnedApps = useMemo$1(
() => applications.filter((someApp) => !!someApp.taskbarPin),
[applications]
);
useEffect(() => {
}, [pinnedApps]);
return /* @__PURE__ */ jsx(DragDropContext, { onDragEnd: onDragEnd2, children: /* @__PURE__ */ jsx(ConnectedDroppable$1, { droppableId: "droppable", direction: "horizontal", children: (provided) => /* @__PURE__ */ jsxs(
StyledTaskbarEntries,
{
$clockWidth: clockWidth,
ref: provided.innerRef,
...provided.droppableProps,
children: [
/* @__PURE__ */ jsx(AnimatePresence, { initial: false, presenceAffectsLayout: false, children: sequence.map((item, index) => {
const { windowID } = item;
const window2 = windows[windowID];
if (window2 && !window2.closing && !window2.hideTaskbarEntry) {
const { icon, title } = window2;
return /* @__PURE__ */ jsx(
PublicDraggable,
{
draggableId: windowID,
index,
children: (provided2, snapshot) => {
return /* @__PURE__ */ jsx(
StyledDraggableEntryContainer,
{
ref: provided2.innerRef,
...provided2.draggableProps,
...provided2.dragHandleProps,
style: {
userSelect: "none",
...provided2.draggableProps.style,
...snapshot.isDragging && {
position: "fixed",
// left: provided.draggableProps.style?.left || 0,
top: void 0,
transform: provided2.draggableProps.style.transform
}
},
children: /* @__PURE__ */ jsx(
TaskbarEntry,
{
icon,
id: windowID,
title
},
windowID
)
}
);
}
},
windowID
);
}
return null;
}) }),
provided.placeholder
]
}
) }) });
};
const TaskbarEntries$1 = memo(TaskbarEntries);
const StyledSection = styled.div`
max-width: 100%;
display: flex;
${(props) => props.$grow && "flex-grow: 1;"}
`;
const WinTaskbar = () => {
const [startMenuVisible, setStartMenuVisible] = useState(false);
const [clockWidth, setClockWidth] = useState(CLOCK_CANVAS_BASE_WIDTH);
const toggleStartMenu = useCallback$1(
(showMenu) => setStartMenuVisible((currentMenuState) => showMenu ?? !currentMenuState),
[]
);
return /* @__PURE__ */ jsxs(Fragment, { children: [
/* @__PURE__ */ jsxs(
StyledWinTaskbar,
{
"data-rd-type": "rd_win_taskbar",
...useTaskbarContextMenu(),
...FOCUSABLE_ELEMENT,
children: [
/* @__PURE__ */ jsx(StyledSection, { "data-rd-type": "rd_taskbar_section" }),
/* @__PURE__ */ jsxs(StyledSection, { "data-rd-type": "rd_taskbar_section", children: [
/* @__PURE__ */ jsx(
StartButton,
{
startMenuVisible,
toggleStartMenu
}
),
/* @__PURE__ */ jsx(TaskbarEntries$1, { clockWidth })
] }),
/* @__PURE__ */ jsx(StyledSection, { "data-rd-type": "rd_taskbar_section" })
]
}
),
/* @__PURE__ */ jsx(
AnimatePresence,
{
initial: false,
presenceAffectsLayout: false
}
)
] });
};
const WinTaskbar$1 = memo(WinTaskbar);
const DesktopContainer = styled.div`
width: 100%;
height: 100%;
flex-grow: 1;
`;
const Desktop = () => {
return /* @__PURE__ */ jsx(DesktopContainer, { className: "rd_desktop" });
};
const Desktop$1 = memo(Desktop);
const StyledWindowRenderer = styled.div`
width: 100%;
height: 100%;
position: absolute;
overflow: hidden;
top: 0;
left: 0;
`;
const Window = lazy(() => import("./index-DHqG8dyW.js"));
const WindowWrapperFC = ({
Component,
id
// addContainer = false,
}) => {
const props = useMemo$1(() => ({ rd_window_id: id, id }), [id]);
const SafeComponent = useMemo$1(
() => /* @__PURE__ */ jsx(Component, { ...props }),
[Component, props]
);
return /* @__PURE__ */ jsx(Window, { id, children: SafeComponent });
};
const WindowWrapper = memo(WindowWrapperFC);
const WindowsAreaFC = () => {
const { windows = {} } = useContext$4();
const { linkElement } = useContext$7();
const linkRenderer = useCallback$1(
(renderEle) => {
if (renderEle) {
linkElement("WindowsViewArea", renderEle);
}
},
[linkElement]
);
return /* @__PURE__ */ jsx(StyledWindowRenderer, { ref: linkRenderer, className: "rd_windows_renderer", children: /* @__PURE__ */ jsx(AnimatePresence, { initial: false, presenceAffectsLayout: false, children: Object.entries(windows).map(
([id, { closing, Component }]) => id && Component && !closing && /* @__PURE__ */ jsx(
WindowWrapper,
{
id,
Component
},
id
)
) }) });
};
const WindowsRenderer = memo(WindowsAreaFC);
const StyledWallpaperImage = styled("div")`
width: 100%;
height: 100%;
position: absolute;
top: 0;
left: 0;
z-index: 0;
background-image: url(${(props) => props.$imgSrc});
background-color: var(--wintheme);
background-repeat: no-repeat;
background-size: cover;
background-position: center;
transition: all 0.2s ease;
`;
const StyledWallpaperBackground = styled.div`
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: ${(props) => props.$background || "#0078d4"};
z-index: -1;
`;
const Wallpaper = () => {
const { wallpaper: sessionWallpaper } = useContext();
const { wallpaper: configWallpaper } = useContext$2();
const wallpaper = sessionWallpaper || configWallpaper;
if (typeof wallpaper === "object" && wallpaper !== null && "type" in wallpaper && wallpaper.type === "image") {
return /* @__PURE__ */ jsx(StyledWallpaperImage, { "data-rd-type": "rd_wallpaper_image", $imgSrc: wallpaper.src });
}
if (typeof wallpaper === "string") {
if (wallpaper.match(/\.(jpg|jpeg|png|gif|svg|webp)$/i) || wallpaper.startsWith("http")) {
return /* @__PURE__ */ jsx(StyledWallpaperImage, { "data-rd-type": "rd_wallpaper_image", $imgSrc: wallpaper });
}
return /* @__PURE__ */ jsx(StyledWallpaperBackground, { "data-rd-type": "rd_wallpaper_color", $background: wallpaper });
}
return /* @__PURE__ */ jsx(StyledWallpaperBackground, { "data-rd-type": "rd_wallpaper_default", $background: "linear-gradient(135deg, #667eea 0%, #764ba2 100%)" });
};
const Wallpaper$1 = memo(Wallpaper);
const StyledMainView = styled.div`
position: relative;
width: 100%;
height: 100%;
flex-grow: 1;
`;
const MainView = ({ ...props }) => {
return /* @__PURE__ */ jsxs(StyledMainView, { "data-rd-type": "rd_mainview", ...props, children: [
/* @__PURE__ */ jsx(Wallpaper$1, {}),
/* @__PURE__ */ jsx(Desktop$1, {}),
/* @__PURE__ */ jsx(WindowsRenderer, {})
] });
};
const MainView$1 = memo(MainView);
const LayoutWrap = () => {
var _a;
const { themeLayout, disableTaskbar } = useContext$2();
const layoutConfig = themeLayout === "win11" ? Win11Layout : themeLayout === "macos" ? macOSLayout : DefaultLayout;
return /* @__PURE__ */ jsxs(Fragment, { children: [
/* @__PURE__ */ jsx(MainView$1, {}),
!disableTaskbar && ((_a = layoutConfig.bottom) == null ? void 0 : _a.includes("wintaskbar")) && /* @__PURE__ */ jsx(WinTaskbar$1, {})
] });
};
const LayoutWrap$1 = memo(LayoutWrap);
const PropsLogic = ({ config }) => {
const { openApp } = useContext$3();
const { createWindow } = useContext$4();
useEffect(() => {
var _a;
if (config.applications) {
config.applications.forEach((app) => {
if (app.runOnStart && app.windowContent) {
setTimeout(() => {
openApp(app);
}, 100);
}
});
}
if ((_a = config.initialState) == null ? void 0 : _a.windows) {
config.initialState.windows.forEach((windowData, index) => {
setTimeout(() => {
createWindow({
...windowData,
Component: windowData.Component || (() => /* @__PURE__ */ jsx("div", { children: "Empty Window" }))
});
}, 200 * (index + 1));
});
}
}, [config.applications, config.initialState, openApp, createWindow]);
return null;
};
const PropsLogic$1 = memo(PropsLogic);
const WindowContext = createContext({});
const WindowProvider = ({ children, id, rd_window_id }) => {
return /* @__PURE__ */ jsx(WindowContext.Provider, { value: { id, rd_window_id: rd_window_id || id }, children });
};
const WindowContainer = ({ children, id }) => {
return /* @__PURE__ */ jsx(WindowProvider, { rd_window_id: id, id, children });
};
const WindowContainer$1 = WindowContainer;
let mountedInstances = 0;
const NestedApp = () => {
return "";
};
const ReactDesk = (props) => {
const actualConfig = useMemo$1(
() => props.config ? props.config : props,
[props]
);
useEffect(() => {
mountedInstances++;
return () => {
mountedInstances--;
};
}, []);
return /* @__PURE__ */ jsx(Provider$9, { children: /* @__PURE__ */ jsx(Provider$a, { children: /* @__PURE__ */ jsx(Provider$1, { children: /* @__PURE__ */ jsx(Provider$6, { children: /* @__PURE__ */ jsx(Provider$5, { children: /* @__PURE__ */ jsx(Provider$4, { children: /* @__PURE__ */ jsx(Provider$3, { config: actualConfig, children: /* @__PURE__ */ jsx(Provider$8, { children: /* @__PURE__ */ jsx(StyledApp$1, { children: /* @__PURE__ */ jsx(StyledMainContainer, { "data-rd-type": "rd_main", children: /* @__PURE__ */ jsxs(Provider$7, { children: [
/* @__PURE__ */ jsx(PropsLogic$1, { config: actualConfig }),
/* @__PURE__ */ jsx(ProcessesContainer, {}),
/* @__PURE__ */ jsx(NestedApp, {}),
/* @__PURE__ */ jsx(LayoutWrap$1, {})
] }) }) }) }) }) }) }) }) }) }) });
};
const ReactDesk$1 = ReactDesk;
export {
useContext$4 as $,
isAnimationControls as A,
isKeyframesTarget as B,
variantPriorityOrder as C,
isVariantLabel as D,
isCSSVariableToken as E,
transformPropOrder as F,
isBrowser as G,
isControllingVariants as H,
isVariantNode as I,
isRefObject as J,
featureDefinitions as K,
variantProps as L,
isCSSVariableName as M,
buildHTMLStyles as N,
scrapeMotionValuesFromProps$1 as O,
renderHTML as P,
camelCaseAttributes as Q,
camelToDash as R,
scrapeMotionValuesFromProps as S,
buildSVGAttrs as T,
renderSVG as U,
isSVGTag as V,
isSVGComponent as W,
defaultStyles as X,
m as Y,
TRANSITIONS_IN_SECONDS as Z,
useContext as _,
isString as a,
useContext$2 as a0,
isSafari as a1,
DIV_BUTTON_PROPS as a2,
Icon$1 as a3,
AnimatePresence as a4,
label as a5,
reactIsExports$1 as a6,
getAugmentedNamespace as a7,
getDefaultExportFromCjs as a8,
pxToNum as a9,
useContext$5 as aA,
useContext$3 as aB,
useContext$9 as aC,
WindowContainer$1 as aD,
mountedInstances as aE,
viewWidth as aa,
viewHeight as ab,
WIN_TASKBAR_HEIGHT as ac,
commonjsGlobal as ad,
useContext$8 as ae,
useContext$7 as af,
calcInitialPosition as ag,
getElementSize as ah,
DEFAULT_WINDOW_SIZE as ai,
useContext$1 as aj,
TRANSITIONS_IN_MILLISECONDS as ak,
FOCUSABLE_ELEMENT as al,
haltEvent as am,
PREVENT_SCROLL as an,
Button as ao,
useContext$6 as ap,
LONG_PRESS_DELAY_MS as aq,
DEFAULT_SCROLLBAR_WIDTH as ar,
Provider$2 as as,
useWindowsRef as at,
MENU_SEPERATOR as au,
PEEK_MAX_WIDTH as av,
isCanvasDrawn as aw,
MILLISECONDS_IN_SECOND as ax,
HIGH_PRIORITY_ELEMENT as ay,
ReactDesk$1 as az,
floatRegex as b,
number as c,
sanitize as d,
alpha as e,
frame as f,
clamp as g,
colorRegex as h,
invariant$2 as i,
cssVariableRegex as j,
cancelFrame as k,
frameData as l,
numberValueTypes as m,
noop$3 as n,
isMotionValue as o,
percent as p,
px as q,
resolveVariantFromProps as r,
singleColorRegex as s,
transformProps as t,
degrees as u,
vw as v,
warning$2 as w,
vh as x,
resolveFinalValueInKeyframes as y,
optimizedAppearDataAttribute as z
};
//# sourceMappingURL=index-CGa3ZYCK.js.map