@webcodateam/turnstone
Version:
React customisable autocomplete component with typeahead and grouped results from multiple APIs.
1,543 lines (1,541 loc) • 66.4 kB
JavaScript
var __defProp = Object.defineProperty;
var __defProps = Object.defineProperties;
var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
var __getOwnPropSymbols = Object.getOwnPropertySymbols;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __propIsEnum = Object.prototype.propertyIsEnumerable;
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
var __spreadValues = (a, b) => {
for (var prop in b || (b = {}))
if (__hasOwnProp.call(b, prop))
__defNormalProp(a, prop, b[prop]);
if (__getOwnPropSymbols)
for (var prop of __getOwnPropSymbols(b)) {
if (__propIsEnum.call(b, prop))
__defNormalProp(a, prop, b[prop]);
}
return a;
};
var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
var __objRest = (source, exclude) => {
var target = {};
for (var prop in source)
if (__hasOwnProp.call(source, prop) && exclude.indexOf(prop) < 0)
target[prop] = source[prop];
if (source != null && __getOwnPropSymbols)
for (var prop of __getOwnPropSymbols(source)) {
if (exclude.indexOf(prop) < 0 && __propIsEnum.call(source, prop))
target[prop] = source[prop];
}
return target;
};
import React, { createContext, useReducer, useEffect, useContext, useRef, useMemo, useCallback, useState, createElement, useLayoutEffect, useDebugValue, useImperativeHandle } from "react";
var propTypes = { exports: {} };
var ReactPropTypesSecret$1 = "SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED";
var ReactPropTypesSecret_1 = ReactPropTypesSecret$1;
var ReactPropTypesSecret = ReactPropTypesSecret_1;
function emptyFunction() {
}
function emptyFunctionWithReset() {
}
emptyFunctionWithReset.resetWarningCache = emptyFunction;
var factoryWithThrowingShims = function() {
function shim(props, propName, componentName, location, propFullName, secret) {
if (secret === ReactPropTypesSecret) {
return;
}
var err = new Error("Calling PropTypes validators directly is not supported by the `prop-types` package. Use PropTypes.checkPropTypes() to call them. Read more at http://fb.me/use-check-prop-types");
err.name = "Invariant Violation";
throw err;
}
shim.isRequired = shim;
function getShim() {
return shim;
}
var ReactPropTypes = {
array: shim,
bigint: shim,
bool: shim,
func: shim,
number: shim,
object: shim,
string: shim,
symbol: shim,
any: shim,
arrayOf: getShim,
element: shim,
elementType: shim,
instanceOf: getShim,
node: shim,
objectOf: getShim,
oneOf: getShim,
oneOfType: getShim,
shape: getShim,
exact: getShim,
checkPropTypes: emptyFunctionWithReset,
resetWarningCache: emptyFunction
};
ReactPropTypes.PropTypes = ReactPropTypes;
return ReactPropTypes;
};
{
propTypes.exports = factoryWithThrowingShims();
}
var PropTypes = propTypes.exports;
const SET_QUERY = "SET_QUERY";
const SET_ITEMS = "SET_ITEMS";
const SET_ITEMS_ERROR = "SET_ITEMS_ERROR";
const CLEAR = "CLEAR";
const SET_HIGHLIGHTED = "SET_HIGHLIGHTED";
const CLEAR_HIGHLIGHTED = "CLEAR_HIGHLIGHTED";
const NEXT_HIGHLIGHTED = "NEXT_HIGHLIGHTED";
const PREV_HIGHLIGHTED = "PREV_HIGHLIGHTED";
const SET_SELECTED = "SET_SELECTED";
const undef = void 0;
function isUndefined$1(value) {
return value === undef;
}
const highlightedItem = (index, items) => {
if (!items[index])
return undef;
return { index, text: items[index].text };
};
const reducer = (state, action) => {
const newState = (() => {
let newState2, item;
switch (action.type) {
case SET_QUERY:
newState2 = {
itemsError: false,
query: action.query,
selected: undef
};
if (action.query.length < state.props.minQueryLength)
newState2.canShowListbox = false;
if (action.query.length === 0 && state.props.defaultListbox)
newState2.canShowListbox = true;
return newState2;
case SET_ITEMS:
newState2 = {
items: action.items,
itemsError: false,
highlighted: action.items.length && state.query.length ? highlightedItem(0, action.items) : undef
};
if (state.query.length || action.items.length)
newState2.canShowListbox = true;
return newState2;
case CLEAR:
return {
query: "",
items: [],
itemsError: false,
canShowListbox: false,
highlighted: undef,
selected: undef
};
case SET_ITEMS_ERROR:
return {
items: [],
itemsError: true,
canShowListbox: false
};
case SET_HIGHLIGHTED:
return { highlighted: highlightedItem(action.index, state.items) };
case CLEAR_HIGHLIGHTED:
return { highlighted: undef };
case PREV_HIGHLIGHTED:
return state.highlighted && state.highlighted.index > 0 ? { highlighted: highlightedItem(state.highlighted.index - 1, state.items) } : {};
case NEXT_HIGHLIGHTED:
return state.highlighted && state.highlighted.index < state.items.length - 1 ? { highlighted: highlightedItem(state.highlighted.index + 1, state.items) } : {};
case SET_SELECTED:
item = isUndefined$1(action.index) ? action.item : state.items[action.index];
return { selected: item, query: item ? item.text : undef };
default:
throw new Error("Invalid action type passed to reducer");
}
})();
return __spreadValues(__spreadValues({}, state), newState);
};
const setQuery = (query) => {
return {
type: SET_QUERY,
query
};
};
const setItems = (items) => {
return {
type: SET_ITEMS,
items
};
};
const setItemsError = () => {
return {
type: SET_ITEMS_ERROR
};
};
const clear = () => {
return {
type: CLEAR
};
};
const setHighlighted = (index) => {
return {
type: SET_HIGHLIGHTED,
index
};
};
const highlightPrev = () => {
return {
type: PREV_HIGHLIGHTED
};
};
const highlightNext = () => {
return {
type: NEXT_HIGHLIGHTED
};
};
const setSelected = (i) => {
const type = SET_SELECTED;
return typeof i === "object" ? { type, item: i } : { type, index: i };
};
var jsxRuntime = { exports: {} };
var reactJsxRuntime_production_min = {};
/*
object-assign
(c) Sindre Sorhus
@license MIT
*/
var getOwnPropertySymbols = Object.getOwnPropertySymbols;
var hasOwnProperty = Object.prototype.hasOwnProperty;
var propIsEnumerable = Object.prototype.propertyIsEnumerable;
function toObject(val) {
if (val === null || val === void 0) {
throw new TypeError("Object.assign cannot be called with null or undefined");
}
return Object(val);
}
function shouldUseNative() {
try {
if (!Object.assign) {
return false;
}
var test1 = new String("abc");
test1[5] = "de";
if (Object.getOwnPropertyNames(test1)[0] === "5") {
return false;
}
var test2 = {};
for (var i = 0; i < 10; i++) {
test2["_" + String.fromCharCode(i)] = i;
}
var order2 = Object.getOwnPropertyNames(test2).map(function(n2) {
return test2[n2];
});
if (order2.join("") !== "0123456789") {
return false;
}
var test3 = {};
"abcdefghijklmnopqrst".split("").forEach(function(letter) {
test3[letter] = letter;
});
if (Object.keys(Object.assign({}, test3)).join("") !== "abcdefghijklmnopqrst") {
return false;
}
return true;
} catch (err) {
return false;
}
}
shouldUseNative() ? Object.assign : function(target, source) {
var from;
var to = toObject(target);
var symbols;
for (var s = 1; s < arguments.length; s++) {
from = Object(arguments[s]);
for (var key in from) {
if (hasOwnProperty.call(from, key)) {
to[key] = from[key];
}
}
if (getOwnPropertySymbols) {
symbols = getOwnPropertySymbols(from);
for (var i = 0; i < symbols.length; i++) {
if (propIsEnumerable.call(from, symbols[i])) {
to[symbols[i]] = from[symbols[i]];
}
}
}
}
return to;
};
/** @license React v17.0.2
* react-jsx-runtime.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 f = React, g = 60103;
reactJsxRuntime_production_min.Fragment = 60107;
if (typeof Symbol === "function" && Symbol.for) {
var h = Symbol.for;
g = h("react.element");
reactJsxRuntime_production_min.Fragment = h("react.fragment");
}
var m = f.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner, n = Object.prototype.hasOwnProperty, p = { key: true, ref: true, __self: true, __source: true };
function q(c, a, k) {
var b, d = {}, e = null, l = null;
k !== void 0 && (e = "" + k);
a.key !== void 0 && (e = "" + a.key);
a.ref !== void 0 && (l = a.ref);
for (b in a)
n.call(a, b) && !p.hasOwnProperty(b) && (d[b] = a[b]);
if (c && c.defaultProps)
for (b in a = c.defaultProps, a)
d[b] === void 0 && (d[b] = a[b]);
return { $$typeof: g, type: c, key: e, ref: l, props: d, _owner: m.current };
}
reactJsxRuntime_production_min.jsx = q;
reactJsxRuntime_production_min.jsxs = q;
{
jsxRuntime.exports = reactJsxRuntime_production_min;
}
const jsx = jsxRuntime.exports.jsx;
const jsxs = jsxRuntime.exports.jsxs;
const Fragment = jsxRuntime.exports.Fragment;
const StateContext = createContext();
const StateContextProvider = (props) => {
const {
text = "",
items = []
} = props;
const _a2 = props, {
children
} = _a2, propsMinusChildren = __objRest(_a2, [
"children"
]);
const [state, dispatch] = useReducer(reducer, {
query: text,
items,
itemsError: false,
canShowListbox: false,
highlighted: undef,
selected: undef,
props: propsMinusChildren
});
useEffect(() => dispatch(setQuery(text)), [text]);
return /* @__PURE__ */ jsx(StateContext.Provider, {
value: {
state,
dispatch
},
children
});
};
const styles$1 = {
listbox: {
position: "absolute",
zIndex: 4
}
};
function escapeStringRegexp(string) {
if (typeof string !== "string") {
throw new TypeError("Expected a string");
}
return string.replace(/[|\\{}()[\]^$+*?.]/g, "\\$&").replace(/-/g, "\\x2d");
}
function MatchingText(props) {
const {
text,
match,
global,
styles: styles2
} = props;
const patternPrefix = global ? "" : "^";
const pattern = `${patternPrefix}(${escapeStringRegexp(match)})`;
const regex = new RegExp(pattern, "i");
const parts = match ? text.split(regex).filter((part) => part.length) : [text];
const matchingText = parts.map((part, index) => {
const isMatch = part.toLowerCase() === match.toLowerCase();
return isMatch ? /* @__PURE__ */ jsx("strong", {
className: styles2.match,
children: parts[index]
}, `part${index}`) : /* @__PURE__ */ jsx(React.Fragment, {
children: parts[index]
}, `part${index}`);
});
return /* @__PURE__ */ jsx(Fragment, {
children: matchingText
});
}
function Item(props) {
const {
index,
item,
styles: styles2
} = props;
const {
state,
dispatch
} = useContext(StateContext);
const {
highlighted,
query
} = state;
const ItemContents = state.props.Item;
const globalMatch = item.searchType === "contains";
const isHighlighted = highlighted && index === highlighted.index;
const divClassName = styles2[isHighlighted ? "highlightedItem" : "item"];
const handleMouseEnter = () => {
dispatch(setHighlighted(index));
};
const handleClick = () => {
dispatch(setSelected(index));
};
const setCustomSelected = (value, displayField) => {
dispatch(setSelected({
value,
displayField,
text: value[displayField]
}));
};
const itemContents = ItemContents ? /* @__PURE__ */ jsx(ItemContents, {
appearsInDefaultListbox: item.defaultListbox,
groupId: item.groupId,
groupIndex: item.groupIndex,
groupName: item.groupName,
index,
isHighlighted,
item: item.value,
query,
searchType: item.searchType,
setSelected: setCustomSelected,
totalItems: state.items.length
}) : state.props.matchText && !item.defaultListbox ? /* @__PURE__ */ jsx(MatchingText, {
text: item.text,
match: query,
global: globalMatch,
styles: styles2
}) : /* @__PURE__ */ jsx(Fragment, {
children: item.text
});
return /* @__PURE__ */ jsx("div", {
className: divClassName,
onMouseEnter: handleMouseEnter,
onMouseDown: handleClick,
role: "option",
"aria-selected": isHighlighted,
"aria-label": item.text,
children: itemContents
});
}
function ItemFirst(props) {
const {
groupName,
index,
item,
styles: styles2
} = props;
const {
state
} = useContext(StateContext);
const GroupName = state.props.GroupName;
const groupHeading = !!groupName && (GroupName ? /* @__PURE__ */ jsx(GroupName, {
id: item.groupId,
index: item.groupIndex,
children: groupName
}) : groupName);
return /* @__PURE__ */ jsxs(React.Fragment, {
children: [!!groupHeading && /* @__PURE__ */ jsx("div", {
className: styles2.groupHeading,
children: groupHeading
}), /* @__PURE__ */ jsx(Item, {
index,
item,
styles: styles2
}, `item${index}`)]
});
}
function Listbox(props) {
const {
id,
items,
noItemsMessage,
styles: styles2
} = props;
const {
state
} = useContext(StateContext);
const itemElements = () => {
return /* @__PURE__ */ jsx("div", {
id,
className: styles2.listbox,
style: styles$1.listbox,
role: "listbox",
children: items.map((item, index) => index === 0 || item.groupIndex !== items[index - 1].groupIndex ? /* @__PURE__ */ jsx(ItemFirst, {
groupName: item.groupName,
index,
item,
styles: styles2
}, `item${index}`) : /* @__PURE__ */ jsx(Item, {
index,
item,
styles: styles2
}, `item${index}`))
});
};
const noItemsMsg = () => {
return /* @__PURE__ */ jsx("div", {
id,
className: styles2.listbox,
style: styles$1.listbox,
children: /* @__PURE__ */ jsx("div", {
className: styles2.noItems,
children: noItemsMessage
})
});
};
const listbox = () => {
if (items && items.length) {
return itemElements();
} else if (noItemsMessage && state.query) {
return noItemsMsg();
} else {
return /* @__PURE__ */ jsx(React.Fragment, {});
}
};
return listbox();
}
function Errorbox(props) {
const {
id,
errorMessage,
styles: styles2
} = props;
return /* @__PURE__ */ jsx("div", {
id,
className: styles2.errorbox,
style: styles$1.listbox,
children: /* @__PURE__ */ jsx("div", {
className: styles2.errorMessage,
children: errorMessage
})
});
}
function useDebouncedCallback(func, wait, options) {
var _this = this;
var lastCallTime = useRef(null);
var lastInvokeTime = useRef(0);
var timerId = useRef(null);
var lastArgs = useRef([]);
var lastThis = useRef();
var result = useRef();
var funcRef = useRef(func);
var mounted = useRef(true);
funcRef.current = func;
var useRAF = !wait && wait !== 0 && typeof window !== "undefined";
if (typeof func !== "function") {
throw new TypeError("Expected a function");
}
wait = +wait || 0;
options = options || {};
var leading = !!options.leading;
var trailing = "trailing" in options ? !!options.trailing : true;
var maxing = "maxWait" in options;
var maxWait = maxing ? Math.max(+options.maxWait || 0, wait) : null;
useEffect(function() {
mounted.current = true;
return function() {
mounted.current = false;
};
}, []);
var debounced = useMemo(function() {
var invokeFunc = function(time) {
var args = lastArgs.current;
var thisArg = lastThis.current;
lastArgs.current = lastThis.current = null;
lastInvokeTime.current = time;
return result.current = funcRef.current.apply(thisArg, args);
};
var startTimer = function(pendingFunc, wait2) {
if (useRAF)
cancelAnimationFrame(timerId.current);
timerId.current = useRAF ? requestAnimationFrame(pendingFunc) : setTimeout(pendingFunc, wait2);
};
var shouldInvoke = function(time) {
if (!mounted.current)
return false;
var timeSinceLastCall = time - lastCallTime.current;
var timeSinceLastInvoke = time - lastInvokeTime.current;
return !lastCallTime.current || timeSinceLastCall >= wait || timeSinceLastCall < 0 || maxing && timeSinceLastInvoke >= maxWait;
};
var trailingEdge = function(time) {
timerId.current = null;
if (trailing && lastArgs.current) {
return invokeFunc(time);
}
lastArgs.current = lastThis.current = null;
return result.current;
};
var timerExpired = function() {
var time = Date.now();
if (shouldInvoke(time)) {
return trailingEdge(time);
}
if (!mounted.current) {
return;
}
var timeSinceLastCall = time - lastCallTime.current;
var timeSinceLastInvoke = time - lastInvokeTime.current;
var timeWaiting = wait - timeSinceLastCall;
var remainingWait = maxing ? Math.min(timeWaiting, maxWait - timeSinceLastInvoke) : timeWaiting;
startTimer(timerExpired, remainingWait);
};
var func2 = function() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
var time = Date.now();
var isInvoking = shouldInvoke(time);
lastArgs.current = args;
lastThis.current = _this;
lastCallTime.current = time;
if (isInvoking) {
if (!timerId.current && mounted.current) {
lastInvokeTime.current = lastCallTime.current;
startTimer(timerExpired, wait);
return leading ? invokeFunc(lastCallTime.current) : result.current;
}
if (maxing) {
startTimer(timerExpired, wait);
return invokeFunc(lastCallTime.current);
}
}
if (!timerId.current) {
startTimer(timerExpired, wait);
}
return result.current;
};
func2.cancel = function() {
if (timerId.current) {
useRAF ? cancelAnimationFrame(timerId.current) : clearTimeout(timerId.current);
}
lastInvokeTime.current = 0;
lastArgs.current = lastCallTime.current = lastThis.current = timerId.current = null;
};
func2.isPending = function() {
return !!timerId.current;
};
func2.flush = function() {
return !timerId.current ? result.current : trailingEdge(Date.now());
};
return func2;
}, [leading, maxing, wait, maxWait, trailing, useRAF]);
return debounced;
}
function valueEquality(left, right) {
return left === right;
}
function adjustFunctionValueOfSetState(value) {
return typeof value === "function" ? function() {
return value;
} : value;
}
function useStateIgnoreCallback(initialState) {
var _a2 = useState(adjustFunctionValueOfSetState(initialState)), state = _a2[0], setState = _a2[1];
var setStateIgnoreCallback = useCallback(function(value) {
return setState(adjustFunctionValueOfSetState(value));
}, []);
return [state, setStateIgnoreCallback];
}
function useDebounce(value, delay, options) {
var eq = options && options.equalityFn || valueEquality;
var _a2 = useStateIgnoreCallback(value), state = _a2[0], dispatch = _a2[1];
var debounced = useDebouncedCallback(useCallback(function(value2) {
return dispatch(value2);
}, [dispatch]), delay, options);
var previousValue = useRef(value);
if (!eq(previousValue.current, value)) {
debounced(value);
previousValue.current = value;
}
return [state, debounced];
}
/*! *****************************************************************************
Copyright (c) Microsoft Corporation.
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
***************************************************************************** */
function __awaiter(thisArg, _arguments, P, generator) {
function adopt(value) {
return value instanceof P ? value : new P(function(resolve) {
resolve(value);
});
}
return new (P || (P = Promise))(function(resolve, reject) {
function fulfilled(value) {
try {
step(generator.next(value));
} catch (e) {
reject(e);
}
}
function rejected(value) {
try {
step(generator["throw"](value));
} catch (e) {
reject(e);
}
}
function step(result) {
result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected);
}
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
}
function __generator(thisArg, body) {
var _ = { label: 0, sent: function() {
if (t[0] & 1)
throw t[1];
return t[1];
}, trys: [], ops: [] }, f2, y, t, g2;
return g2 = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g2[Symbol.iterator] = function() {
return this;
}), g2;
function verb(n2) {
return function(v) {
return step([n2, v]);
};
}
function step(op) {
if (f2)
throw new TypeError("Generator is already executing.");
while (_)
try {
if (f2 = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done)
return t;
if (y = 0, t)
op = [op[0] & 2, t.value];
switch (op[0]) {
case 0:
case 1:
t = op;
break;
case 4:
_.label++;
return { value: op[1], done: false };
case 5:
_.label++;
y = op[1];
op = [0];
continue;
case 7:
op = _.ops.pop();
_.trys.pop();
continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
_ = 0;
continue;
}
if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
_.label = op[1];
break;
}
if (op[0] === 6 && _.label < t[1]) {
_.label = t[1];
t = op;
break;
}
if (t && _.label < t[2]) {
_.label = t[2];
_.ops.push(op);
break;
}
if (t[2])
_.ops.pop();
_.trys.pop();
continue;
}
op = body.call(thisArg, _);
} catch (e) {
op = [6, e];
y = 0;
} finally {
f2 = t = 0;
}
if (op[0] & 5)
throw op[1];
return { value: op[0] ? op[1] : void 0, done: true };
}
}
var noop = function() {
};
var UNDEFINED = noop();
var OBJECT = Object;
var isUndefined = function(v) {
return v === UNDEFINED;
};
var isFunction = function(v) {
return typeof v == "function";
};
var mergeObjects = function(a, b) {
return OBJECT.assign({}, a, b);
};
var STR_UNDEFINED = "undefined";
var hasWindow = function() {
return typeof window != STR_UNDEFINED;
};
var hasDocument = function() {
return typeof document != STR_UNDEFINED;
};
var hasRequestAnimationFrame = function() {
return hasWindow() && typeof window["requestAnimationFrame"] != STR_UNDEFINED;
};
var table = /* @__PURE__ */ new WeakMap();
var counter = 0;
var stableHash = function(arg) {
var type = typeof arg;
var constructor = arg && arg.constructor;
var isDate = constructor == Date;
var result;
var index;
if (OBJECT(arg) === arg && !isDate && constructor != RegExp) {
result = table.get(arg);
if (result)
return result;
result = ++counter + "~";
table.set(arg, result);
if (constructor == Array) {
result = "@";
for (index = 0; index < arg.length; index++) {
result += stableHash(arg[index]) + ",";
}
table.set(arg, result);
}
if (constructor == OBJECT) {
result = "#";
var keys = OBJECT.keys(arg).sort();
while (!isUndefined(index = keys.pop())) {
if (!isUndefined(arg[index])) {
result += index + ":" + stableHash(arg[index]) + ",";
}
}
table.set(arg, result);
}
} else {
result = isDate ? arg.toJSON() : type == "symbol" ? arg.toString() : type == "string" ? JSON.stringify(arg) : "" + arg;
}
return result;
};
var online = true;
var isOnline = function() {
return online;
};
var hasWin = hasWindow();
var hasDoc = hasDocument();
var onWindowEvent = hasWin && window.addEventListener ? window.addEventListener.bind(window) : noop;
var onDocumentEvent = hasDoc ? document.addEventListener.bind(document) : noop;
var offWindowEvent = hasWin && window.removeEventListener ? window.removeEventListener.bind(window) : noop;
var offDocumentEvent = hasDoc ? document.removeEventListener.bind(document) : noop;
var isVisible = function() {
var visibilityState = hasDoc && document.visibilityState;
return isUndefined(visibilityState) || visibilityState !== "hidden";
};
var initFocus = function(callback) {
onDocumentEvent("visibilitychange", callback);
onWindowEvent("focus", callback);
return function() {
offDocumentEvent("visibilitychange", callback);
offWindowEvent("focus", callback);
};
};
var initReconnect = function(callback) {
var onOnline = function() {
online = true;
callback();
};
var onOffline = function() {
online = false;
};
onWindowEvent("online", onOnline);
onWindowEvent("offline", onOffline);
return function() {
offWindowEvent("online", onOnline);
offWindowEvent("offline", onOffline);
};
};
var preset = {
isOnline,
isVisible
};
var defaultConfigOptions = {
initFocus,
initReconnect
};
var IS_SERVER = !hasWindow() || "Deno" in window;
var rAF = function(f2) {
return hasRequestAnimationFrame() ? window["requestAnimationFrame"](f2) : setTimeout(f2, 1);
};
var useIsomorphicLayoutEffect = IS_SERVER ? useEffect : useLayoutEffect;
var navigatorConnection = typeof navigator !== "undefined" && navigator.connection;
var slowConnection = !IS_SERVER && navigatorConnection && (["slow-2g", "2g"].includes(navigatorConnection.effectiveType) || navigatorConnection.saveData);
var serialize = function(key) {
if (isFunction(key)) {
try {
key = key();
} catch (err) {
key = "";
}
}
var args = [].concat(key);
key = typeof key == "string" ? key : (Array.isArray(key) ? key.length : key) ? stableHash(key) : "";
var infoKey = key ? "$swr$" + key : "";
return [key, args, infoKey];
};
var SWRGlobalState = /* @__PURE__ */ new WeakMap();
var FOCUS_EVENT = 0;
var RECONNECT_EVENT = 1;
var MUTATE_EVENT = 2;
var broadcastState = function(cache2, key, data, error, isValidating, revalidate, broadcast) {
if (broadcast === void 0) {
broadcast = true;
}
var _a2 = SWRGlobalState.get(cache2), EVENT_REVALIDATORS = _a2[0], STATE_UPDATERS = _a2[1], FETCH = _a2[3];
var revalidators = EVENT_REVALIDATORS[key];
var updaters = STATE_UPDATERS[key];
if (broadcast && updaters) {
for (var i = 0; i < updaters.length; ++i) {
updaters[i](data, error, isValidating);
}
}
if (revalidate) {
delete FETCH[key];
if (revalidators && revalidators[0]) {
return revalidators[0](MUTATE_EVENT).then(function() {
return cache2.get(key);
});
}
}
return cache2.get(key);
};
var __timestamp = 0;
var getTimestamp = function() {
return ++__timestamp;
};
var internalMutate = function() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
return __awaiter(void 0, void 0, void 0, function() {
var cache2, _key, _data, _opts, options, populateCache, revalidate, rollbackOnError, optimisticData, _a2, key, keyInfo, _b, MUTATION, data, error, beforeMutationTs, hasOptimisticData, rollbackData, res;
return __generator(this, function(_c) {
switch (_c.label) {
case 0:
cache2 = args[0], _key = args[1], _data = args[2], _opts = args[3];
options = typeof _opts === "boolean" ? { revalidate: _opts } : _opts || {};
populateCache = isUndefined(options.populateCache) ? true : options.populateCache;
revalidate = options.revalidate !== false;
rollbackOnError = options.rollbackOnError !== false;
optimisticData = options.optimisticData;
_a2 = serialize(_key), key = _a2[0], keyInfo = _a2[2];
if (!key)
return [2];
_b = SWRGlobalState.get(cache2), MUTATION = _b[2];
if (args.length < 3) {
return [2, broadcastState(cache2, key, cache2.get(key), UNDEFINED, UNDEFINED, revalidate, true)];
}
data = _data;
beforeMutationTs = getTimestamp();
MUTATION[key] = [beforeMutationTs, 0];
hasOptimisticData = !isUndefined(optimisticData);
rollbackData = cache2.get(key);
if (hasOptimisticData) {
cache2.set(key, optimisticData);
broadcastState(cache2, key, optimisticData);
}
if (isFunction(data)) {
try {
data = data(cache2.get(key));
} catch (err) {
error = err;
}
}
if (!(data && isFunction(data.then)))
return [3, 2];
return [
4,
data.catch(function(err) {
error = err;
})
];
case 1:
data = _c.sent();
if (beforeMutationTs !== MUTATION[key][0]) {
if (error)
throw error;
return [2, data];
} else if (error && hasOptimisticData && rollbackOnError) {
populateCache = true;
data = rollbackData;
cache2.set(key, rollbackData);
}
_c.label = 2;
case 2:
if (populateCache) {
if (!error) {
if (isFunction(populateCache)) {
data = populateCache(data, rollbackData);
}
cache2.set(key, data);
}
cache2.set(keyInfo, mergeObjects(cache2.get(keyInfo), { error }));
}
MUTATION[key][1] = getTimestamp();
return [
4,
broadcastState(cache2, key, data, error, UNDEFINED, revalidate, !!populateCache)
];
case 3:
res = _c.sent();
if (error)
throw error;
return [2, populateCache ? res : data];
}
});
});
};
var revalidateAllKeys = function(revalidators, type) {
for (var key in revalidators) {
if (revalidators[key][0])
revalidators[key][0](type);
}
};
var initCache = function(provider, options) {
if (!SWRGlobalState.has(provider)) {
var opts = mergeObjects(defaultConfigOptions, options);
var EVENT_REVALIDATORS = {};
var mutate2 = internalMutate.bind(UNDEFINED, provider);
var unmount = noop;
SWRGlobalState.set(provider, [EVENT_REVALIDATORS, {}, {}, {}, mutate2]);
if (!IS_SERVER) {
var releaseFocus_1 = opts.initFocus(setTimeout.bind(UNDEFINED, revalidateAllKeys.bind(UNDEFINED, EVENT_REVALIDATORS, FOCUS_EVENT)));
var releaseReconnect_1 = opts.initReconnect(setTimeout.bind(UNDEFINED, revalidateAllKeys.bind(UNDEFINED, EVENT_REVALIDATORS, RECONNECT_EVENT)));
unmount = function() {
releaseFocus_1 && releaseFocus_1();
releaseReconnect_1 && releaseReconnect_1();
SWRGlobalState.delete(provider);
};
}
return [provider, mutate2, unmount];
}
return [provider, SWRGlobalState.get(provider)[4]];
};
var onErrorRetry = function(_, __, config, revalidate, opts) {
var maxRetryCount = config.errorRetryCount;
var currentRetryCount = opts.retryCount;
var timeout = ~~((Math.random() + 0.5) * (1 << (currentRetryCount < 8 ? currentRetryCount : 8))) * config.errorRetryInterval;
if (!isUndefined(maxRetryCount) && currentRetryCount > maxRetryCount) {
return;
}
setTimeout(revalidate, timeout, opts);
};
var _a = initCache(/* @__PURE__ */ new Map()), cache = _a[0], mutate = _a[1];
var defaultConfig = mergeObjects({
onLoadingSlow: noop,
onSuccess: noop,
onError: noop,
onErrorRetry,
onDiscarded: noop,
revalidateOnFocus: true,
revalidateOnReconnect: true,
revalidateIfStale: true,
shouldRetryOnError: true,
errorRetryInterval: slowConnection ? 1e4 : 5e3,
focusThrottleInterval: 5 * 1e3,
dedupingInterval: 2 * 1e3,
loadingTimeout: slowConnection ? 5e3 : 3e3,
compare: function(currentData, newData) {
return stableHash(currentData) == stableHash(newData);
},
isPaused: function() {
return false;
},
cache,
mutate,
fallback: {}
}, preset);
var mergeConfigs = function(a, b) {
var v = mergeObjects(a, b);
if (b) {
var u1 = a.use, f1 = a.fallback;
var u2 = b.use, f2 = b.fallback;
if (u1 && u2) {
v.use = u1.concat(u2);
}
if (f1 && f2) {
v.fallback = mergeObjects(f1, f2);
}
}
return v;
};
var SWRConfigContext = createContext({});
var SWRConfig$1 = function(props) {
var value = props.value;
var extendedConfig = mergeConfigs(useContext(SWRConfigContext), value);
var provider = value && value.provider;
var cacheContext = useState(function() {
return provider ? initCache(provider(extendedConfig.cache || cache), value) : UNDEFINED;
})[0];
if (cacheContext) {
extendedConfig.cache = cacheContext[0];
extendedConfig.mutate = cacheContext[1];
}
useIsomorphicLayoutEffect(function() {
return cacheContext ? cacheContext[2] : UNDEFINED;
}, []);
return createElement(SWRConfigContext.Provider, mergeObjects(props, {
value: extendedConfig
}));
};
var useStateWithDeps = function(state, unmountedRef) {
var rerender = useState({})[1];
var stateRef = useRef(state);
var stateDependenciesRef = useRef({
data: false,
error: false,
isValidating: false
});
var setState = useCallback(function(payload) {
var shouldRerender = false;
var currentState = stateRef.current;
for (var _ in payload) {
var k = _;
if (currentState[k] !== payload[k]) {
currentState[k] = payload[k];
if (stateDependenciesRef.current[k]) {
shouldRerender = true;
}
}
}
if (shouldRerender && !unmountedRef.current) {
rerender({});
}
}, []);
useIsomorphicLayoutEffect(function() {
stateRef.current = state;
});
return [stateRef, stateDependenciesRef.current, setState];
};
var normalize = function(args) {
return isFunction(args[1]) ? [args[0], args[1], args[2] || {}] : [args[0], null, (args[1] === null ? args[2] : args[1]) || {}];
};
var useSWRConfig = function() {
return mergeObjects(defaultConfig, useContext(SWRConfigContext));
};
var withArgs = function(hook) {
return function useSWRArgs() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
var fallbackConfig = useSWRConfig();
var _a2 = normalize(args), key = _a2[0], fn = _a2[1], _config = _a2[2];
var config = mergeConfigs(fallbackConfig, _config);
var next = hook;
var use = config.use;
if (use) {
for (var i = use.length; i-- > 0; ) {
next = use[i](next);
}
}
return next(key, fn || config.fetcher, config);
};
};
var subscribeCallback = function(key, callbacks, callback) {
var keyedRevalidators = callbacks[key] || (callbacks[key] = []);
keyedRevalidators.push(callback);
return function() {
var index = keyedRevalidators.indexOf(callback);
if (index >= 0) {
keyedRevalidators[index] = keyedRevalidators[keyedRevalidators.length - 1];
keyedRevalidators.pop();
}
};
};
var WITH_DEDUPE = { dedupe: true };
var useSWRHandler = function(_key, fetcher2, config) {
var cache2 = config.cache, compare = config.compare, fallbackData = config.fallbackData, suspense = config.suspense, revalidateOnMount = config.revalidateOnMount, refreshInterval = config.refreshInterval, refreshWhenHidden = config.refreshWhenHidden, refreshWhenOffline = config.refreshWhenOffline;
var _a2 = SWRGlobalState.get(cache2), EVENT_REVALIDATORS = _a2[0], STATE_UPDATERS = _a2[1], MUTATION = _a2[2], FETCH = _a2[3];
var _b = serialize(_key), key = _b[0], fnArgs = _b[1], keyInfo = _b[2];
var initialMountedRef = useRef(false);
var unmountedRef = useRef(false);
var keyRef = useRef(key);
var fetcherRef = useRef(fetcher2);
var configRef = useRef(config);
var getConfig = function() {
return configRef.current;
};
var isActive = function() {
return getConfig().isVisible() && getConfig().isOnline();
};
var patchFetchInfo = function(info2) {
return cache2.set(keyInfo, mergeObjects(cache2.get(keyInfo), info2));
};
var cached = cache2.get(key);
var fallback = isUndefined(fallbackData) ? config.fallback[key] : fallbackData;
var data = isUndefined(cached) ? fallback : cached;
var info = cache2.get(keyInfo) || {};
var error = info.error;
var isInitialMount = !initialMountedRef.current;
var shouldRevalidate = function() {
if (isInitialMount && !isUndefined(revalidateOnMount))
return revalidateOnMount;
if (getConfig().isPaused())
return false;
return suspense ? !isUndefined(data) : isUndefined(data) || config.revalidateIfStale;
};
var resolveValidating = function() {
if (!key || !fetcher2)
return false;
if (info.isValidating)
return true;
return isInitialMount && shouldRevalidate();
};
var isValidating = resolveValidating();
var _c = useStateWithDeps({
data,
error,
isValidating
}, unmountedRef), stateRef = _c[0], stateDependencies = _c[1], setState = _c[2];
var revalidate = useCallback(function(revalidateOpts) {
return __awaiter(void 0, void 0, void 0, function() {
var currentFetcher, newData, startAt, loading, opts, shouldStartNewRequest, isCurrentKeyMounted, cleanupState, newState, finishRequestAndUpdateState, mutationInfo, err_1;
var _a3;
return __generator(this, function(_b2) {
switch (_b2.label) {
case 0:
currentFetcher = fetcherRef.current;
if (!key || !currentFetcher || unmountedRef.current || getConfig().isPaused()) {
return [2, false];
}
loading = true;
opts = revalidateOpts || {};
shouldStartNewRequest = !FETCH[key] || !opts.dedupe;
isCurrentKeyMounted = function() {
return !unmountedRef.current && key === keyRef.current && initialMountedRef.current;
};
cleanupState = function() {
var requestInfo = FETCH[key];
if (requestInfo && requestInfo[1] === startAt) {
delete FETCH[key];
}
};
newState = { isValidating: false };
finishRequestAndUpdateState = function() {
patchFetchInfo({ isValidating: false });
if (isCurrentKeyMounted()) {
setState(newState);
}
};
patchFetchInfo({
isValidating: true
});
setState({ isValidating: true });
_b2.label = 1;
case 1:
_b2.trys.push([1, 3, , 4]);
if (shouldStartNewRequest) {
broadcastState(cache2, key, stateRef.current.data, stateRef.current.error, true);
if (config.loadingTimeout && !cache2.get(key)) {
setTimeout(function() {
if (loading && isCurrentKeyMounted()) {
getConfig().onLoadingSlow(key, config);
}
}, config.loadingTimeout);
}
FETCH[key] = [currentFetcher.apply(void 0, fnArgs), getTimestamp()];
}
_a3 = FETCH[key], newData = _a3[0], startAt = _a3[1];
return [4, newData];
case 2:
newData = _b2.sent();
if (shouldStartNewRequest) {
setTimeout(cleanupState, config.dedupingInterval);
}
if (!FETCH[key] || FETCH[key][1] !== startAt) {
if (shouldStartNewRequest) {
if (isCurrentKeyMounted()) {
getConfig().onDiscarded(key);
}
}
return [2, false];
}
patchFetchInfo({
error: UNDEFINED
});
newState.error = UNDEFINED;
mutationInfo = MUTATION[key];
if (!isUndefined(mutationInfo) && (startAt <= mutationInfo[0] || startAt <= mutationInfo[1] || mutationInfo[1] === 0)) {
finishRequestAndUpdateState();
if (shouldStartNewRequest) {
if (isCurrentKeyMounted()) {
getConfig().onDiscarded(key);
}
}
return [2, false];
}
if (!compare(stateRef.current.data, newData)) {
newState.data = newData;
} else {
newState.data = stateRef.current.data;
}
if (!compare(cache2.get(key), newData)) {
cache2.set(key, newData);
}
if (shouldStartNewRequest) {
if (isCurrentKeyMounted()) {
getConfig().onSuccess(newData, key, config);
}
}
return [3, 4];
case 3:
err_1 = _b2.sent();
cleanupState();
if (!getConfig().isPaused()) {
patchFetchInfo({ error: err_1 });
newState.error = err_1;
if (shouldStartNewRequest && isCurrentKeyMounted()) {
getConfig().onError(err_1, key, config);
if (typeof config.shouldRetryOnError === "boolean" && config.shouldRetryOnError || isFunction(config.shouldRetryOnError) && config.shouldRetryOnError(err_1)) {
if (isActive()) {
getConfig().onErrorRetry(err_1, key, config, revalidate, {
retryCount: (opts.retryCount || 0) + 1,
dedupe: true
});
}
}
}
}
return [3, 4];
case 4:
loading = false;
finishRequestAndUpdateState();
if (isCurrentKeyMounted() && shouldStartNewRequest) {
broadcastState(cache2, key, newState.data, newState.error, false);
}
return [2, true];
}
});
});
}, [key]);
var boundMutate = useCallback(internalMutate.bind(UNDEFINED, cache2, function() {
return keyRef.current;
}), []);
useIsomorphicLayoutEffect(function() {
fetcherRef.current = fetcher2;
configRef.current = config;
});
useIsomorphicLayoutEffect(function() {
if (!key)
return;
var keyChanged = key !== keyRef.current;
var softRevalidate = revalidate.bind(UNDEFINED, WITH_DEDUPE);
var onStateUpdate = function(updatedData, updatedError, updatedIsValidating) {
setState(mergeObjects({
error: updatedError,
isValidating: updatedIsValidating
}, compare(stateRef.current.data, updatedData) ? UNDEFINED : {
data: updatedData
}));
};
var nextFocusRevalidatedAt = 0;
var onRevalidate = function(type) {
if (type == FOCUS_EVENT) {
var now = Date.now();
if (getConfig().revalidateOnFocus && now > nextFocusRevalidatedAt && isActive()) {
nextFocusRevalidatedAt = now + getConfig().focusThrottleInterval;
softRevalidate();
}
} else if (type == RECONNECT_EVENT) {
if (getConfig().revalidateOnReconnect && isActive()) {
softRevalidate();
}
} else if (type == MUTATE_EVENT) {
return revalidate();
}
return;
};
var unsubUpdate = subscribeCallback(key, STATE_UPDATERS, onStateUpdate);
var unsubEvents = subscribeCallback(key, EVENT_REVALIDATORS, onRevalidate);
unmountedRef.current = false;
keyRef.current = key;
initialMountedRef.current = true;
if (keyChanged) {
setState({
data,
error,
isValidating
});
}
if (shouldRevalidate()) {
if (isUndefined(data) || IS_SERVER) {
softRevalidate();
} else {
rAF(softRevalidate);
}
}
return function() {
unmountedRef.current = true;
unsubUpdate();
unsubEvents();
};
}, [key, revalidate]);
useIsomorphicLayoutEffect(function() {
var timer;
function next() {
var interval = isFunction(refreshInterval) ? refreshInterval(data) : refreshInterval;
if (interval && timer !== -1) {
timer = setTimeout(execute, interval);
}
}
function execute() {
if (!stateRef.current.error && (refreshWhenHidden || getConfig().isVisible()) && (refreshWhenOffline || getConfig().isOnline())) {
revalidate(WITH_DEDUPE).then(next);
} else {
next();
}
}
next();
return function() {
if (timer) {
clearTimeout(timer);
timer = -1;
}
};
}, [refreshInterval, refreshWhenHidden, refreshWhenOffline, revalidate]);
useDebugValue(data);
if (suspense && isUndefined(data) && key) {
fetcherRef.current = fetcher2;
configRef.current = config;
unmountedRef.current = false;
throw isUndefined(error) ? revalidate(WITH_DEDUPE) : error;
}
return {
mutate: boundMutate,
get data() {
stateDependencies.data = true;
return data;
},
get error() {
stateDependencies.error = true;
return error;
},
get isValidating() {
stateDependencies.isValidating = true;
return isValidating;
}
};
};
OBJECT.defineProperty(SWRConfig$1, "default", {
value: defaultConfig
});
var useSWR = withArgs(useSWRHandler);
var dist = {};
Object.defineProperty(dist, "__esModule", {
value: true
});
var _default = dist.default = firstOfType;
function firstOfType(collection, type) {
for (const i in collection) {
if (typeof collection[i] === type) {
return collection[i];
}
}
}
function swrLaggyMiddleware(useSWRNext) {
return (key, fetcher2, config) => {
const laggyDataRef = useRef();
const swr = useSWRNext(key, fetcher2, config);
useEffect(() => {
if (swr.data !== void 0) {
laggyDataRef.current = swr.data;
}
}, [swr.data]);
const resetLaggy = useCallback(() => {
laggyDataRef.current = void 0;
}, []);
const dataOrLaggyData = swr.data === void 0 ? laggyDataRef.current : swr.data;
const isLagging = swr.data === void 0 && laggyDataRef.current !== void 0;
return Object.assign({}, swr, {
data: dataOrLaggyData,
isLagging,
resetLaggy
});
};
}
const convertListboxToFunction = (listbox, maxItems) => {
if (typeof listbox === "function")
return listbox;
return () => Promise.resolve(Array.isArray(listbox) ? listbox : [__spreadValues(__spreadValues({}, listbox), { name: "", ratio: maxItems })]);
};
const filterSuppliedData = (group, query) => {
const { data, displayField, searchType } = group;
const caseInsensitiveSearchType = searchType ? searchType.toLowerCase() : searchType;
switch (caseInsensitiveSearchType) {
case "startswith":
return data.filter((item) => itemText(item, displayField).toLowerCase().startsWith(query.toLowerCase()));
case "contains":
return data.filter((item) => itemText(item, displayField).toLowerCase().includes(query.toLowerCase()));
default:
return data;
}
};
const limitResults = (groups, listboxProp, maxItems) => {
const ratios = listboxProp.map((group) => group.ratio || 1);
const ratioTotal = ratios.reduce((total, ratio) => total + ratio, 0);
const ratioMultiplier = maxItems / ratioTotal;
const resultTotal = groups.flat().length;
const groupCounts = [];
let unassignedSlots = resultTotal < maxItems ? resultTotal : maxItems;
while (unassignedSlots > 0) {
groups = groups.map((group, i) => {
if (!groupCounts[i]) {
groupCounts[i] = Math.round(ratios[i] * ratioMultiplier);
if (groupCounts[i] > group.length)
groupCounts[i] = group.length;
unassignedSlots = unassignedSlots - groupCounts[i];
} else if (groupCounts[i] < group.length) {
unassignedSlots -= ++groupCounts[i];
}
return group;
});
}
return groups.map((group, index) => group.slice(0, groupCounts[index]));
};
const itemText = (item, displayField) => {
const itemType = typeof item;
const text = itemType === "string" && isUndefined$1(displayField) ? item : item[displayField];
return isUndefined$1(text) ? _default(item, "string") || "" : text;
};
const swrOptions = (isImmutable) => {
const swrBaseOptions = {
use: [swrLaggyMiddleware]
};
return isImmutable ? __spreadProps(__spreadValues({}, swrBaseOptions), {
revalidateIfStale: false,
revalidateOnFocus: false,
revalidateOnReconnect: false
}) : swrBaseOptions;
};
const