From 363a8d1033bdd2103e1929acaf116073c7c224a7 Mon Sep 17 00:00:00 2001 From: JP Cen Date: Sun, 29 Oct 2023 04:58:22 -0400 Subject: [PATCH] 0.8 Release --- main.js | 74904 +++++++++++++++++++++++++++--------------------- manifest.json | 2 +- styles.css | 3138 +- 3 files changed, 44534 insertions(+), 33510 deletions(-) diff --git a/main.js b/main.js index 50e1730..e352439 100644 --- a/main.js +++ b/main.js @@ -46,671 +46,1255 @@ var __toBinary = /* @__PURE__ */ (() => { }; })(); -// node_modules/lodash/lodash.js -var require_lodash = __commonJS({ - "node_modules/lodash/lodash.js"(exports, module2) { - (function() { - var undefined2; - var VERSION = "4.17.21"; - var LARGE_ARRAY_SIZE = 200; - var CORE_ERROR_TEXT = "Unsupported core-js use. Try https://npms.io/search?q=ponyfill.", FUNC_ERROR_TEXT = "Expected a function", INVALID_TEMPL_VAR_ERROR_TEXT = "Invalid `variable` option passed into `_.template`"; - var HASH_UNDEFINED = "__lodash_hash_undefined__"; - var MAX_MEMOIZE_SIZE = 500; - var PLACEHOLDER = "__lodash_placeholder__"; - var CLONE_DEEP_FLAG = 1, CLONE_FLAT_FLAG = 2, CLONE_SYMBOLS_FLAG = 4; - var COMPARE_PARTIAL_FLAG = 1, COMPARE_UNORDERED_FLAG = 2; - var WRAP_BIND_FLAG = 1, WRAP_BIND_KEY_FLAG = 2, WRAP_CURRY_BOUND_FLAG = 4, WRAP_CURRY_FLAG = 8, WRAP_CURRY_RIGHT_FLAG = 16, WRAP_PARTIAL_FLAG = 32, WRAP_PARTIAL_RIGHT_FLAG = 64, WRAP_ARY_FLAG = 128, WRAP_REARG_FLAG = 256, WRAP_FLIP_FLAG = 512; - var DEFAULT_TRUNC_LENGTH = 30, DEFAULT_TRUNC_OMISSION = "..."; - var HOT_COUNT = 800, HOT_SPAN = 16; - var LAZY_FILTER_FLAG = 1, LAZY_MAP_FLAG = 2, LAZY_WHILE_FLAG = 3; - var INFINITY = 1 / 0, MAX_SAFE_INTEGER = 9007199254740991, MAX_INTEGER = 17976931348623157e292, NAN = 0 / 0; - var MAX_ARRAY_LENGTH = 4294967295, MAX_ARRAY_INDEX = MAX_ARRAY_LENGTH - 1, HALF_MAX_ARRAY_LENGTH = MAX_ARRAY_LENGTH >>> 1; - var wrapFlags = [ - ["ary", WRAP_ARY_FLAG], - ["bind", WRAP_BIND_FLAG], - ["bindKey", WRAP_BIND_KEY_FLAG], - ["curry", WRAP_CURRY_FLAG], - ["curryRight", WRAP_CURRY_RIGHT_FLAG], - ["flip", WRAP_FLIP_FLAG], - ["partial", WRAP_PARTIAL_FLAG], - ["partialRight", WRAP_PARTIAL_RIGHT_FLAG], - ["rearg", WRAP_REARG_FLAG] - ]; - var argsTag = "[object Arguments]", arrayTag = "[object Array]", asyncTag = "[object AsyncFunction]", boolTag = "[object Boolean]", dateTag = "[object Date]", domExcTag = "[object DOMException]", errorTag = "[object Error]", funcTag = "[object Function]", genTag = "[object GeneratorFunction]", mapTag = "[object Map]", numberTag = "[object Number]", nullTag = "[object Null]", objectTag = "[object Object]", promiseTag = "[object Promise]", proxyTag = "[object Proxy]", regexpTag = "[object RegExp]", setTag = "[object Set]", stringTag = "[object String]", symbolTag = "[object Symbol]", undefinedTag = "[object Undefined]", weakMapTag = "[object WeakMap]", weakSetTag = "[object WeakSet]"; - var arrayBufferTag = "[object ArrayBuffer]", dataViewTag = "[object DataView]", float32Tag = "[object Float32Array]", float64Tag = "[object Float64Array]", int8Tag = "[object Int8Array]", int16Tag = "[object Int16Array]", int32Tag = "[object Int32Array]", uint8Tag = "[object Uint8Array]", uint8ClampedTag = "[object Uint8ClampedArray]", uint16Tag = "[object Uint16Array]", uint32Tag = "[object Uint32Array]"; - var reEmptyStringLeading = /\b__p \+= '';/g, reEmptyStringMiddle = /\b(__p \+=) '' \+/g, reEmptyStringTrailing = /(__e\(.*?\)|\b__t\)) \+\n'';/g; - var reEscapedHtml = /&(?:amp|lt|gt|quot|#39);/g, reUnescapedHtml = /[&<>"']/g, reHasEscapedHtml = RegExp(reEscapedHtml.source), reHasUnescapedHtml = RegExp(reUnescapedHtml.source); - var reEscape = /<%-([\s\S]+?)%>/g, reEvaluate = /<%([\s\S]+?)%>/g, reInterpolate = /<%=([\s\S]+?)%>/g; - var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/, reIsPlainProp = /^\w*$/, rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g; - var reRegExpChar = /[\\^$.*+?()[\]{}|]/g, reHasRegExpChar = RegExp(reRegExpChar.source); - var reTrimStart = /^\s+/; - var reWhitespace = /\s/; - var reWrapComment = /\{(?:\n\/\* \[wrapped with .+\] \*\/)?\n?/, reWrapDetails = /\{\n\/\* \[wrapped with (.+)\] \*/, reSplitDetails = /,? & /; - var reAsciiWord = /[^\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f]+/g; - var reForbiddenIdentifierChars = /[()=,{}\[\]\/\s]/; - var reEscapeChar = /\\(\\)?/g; - var reEsTemplate = /\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g; - var reFlags = /\w*$/; - var reIsBadHex = /^[-+]0x[0-9a-f]+$/i; - var reIsBinary = /^0b[01]+$/i; - var reIsHostCtor = /^\[object .+?Constructor\]$/; - var reIsOctal = /^0o[0-7]+$/i; - var reIsUint = /^(?:0|[1-9]\d*)$/; - var reLatin = /[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g; - var reNoMatch = /($^)/; - var reUnescapedString = /['\n\r\u2028\u2029\\]/g; - var rsAstralRange = "\\ud800-\\udfff", rsComboMarksRange = "\\u0300-\\u036f", reComboHalfMarksRange = "\\ufe20-\\ufe2f", rsComboSymbolsRange = "\\u20d0-\\u20ff", rsComboRange = rsComboMarksRange + reComboHalfMarksRange + rsComboSymbolsRange, rsDingbatRange = "\\u2700-\\u27bf", rsLowerRange = "a-z\\xdf-\\xf6\\xf8-\\xff", rsMathOpRange = "\\xac\\xb1\\xd7\\xf7", rsNonCharRange = "\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf", rsPunctuationRange = "\\u2000-\\u206f", rsSpaceRange = " \\t\\x0b\\f\\xa0\\ufeff\\n\\r\\u2028\\u2029\\u1680\\u180e\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200a\\u202f\\u205f\\u3000", rsUpperRange = "A-Z\\xc0-\\xd6\\xd8-\\xde", rsVarRange = "\\ufe0e\\ufe0f", rsBreakRange = rsMathOpRange + rsNonCharRange + rsPunctuationRange + rsSpaceRange; - var rsApos = "['\u2019]", rsAstral = "[" + rsAstralRange + "]", rsBreak = "[" + rsBreakRange + "]", rsCombo = "[" + rsComboRange + "]", rsDigits = "\\d+", rsDingbat = "[" + rsDingbatRange + "]", rsLower = "[" + rsLowerRange + "]", rsMisc = "[^" + rsAstralRange + rsBreakRange + rsDigits + rsDingbatRange + rsLowerRange + rsUpperRange + "]", rsFitz = "\\ud83c[\\udffb-\\udfff]", rsModifier = "(?:" + rsCombo + "|" + rsFitz + ")", rsNonAstral = "[^" + rsAstralRange + "]", rsRegional = "(?:\\ud83c[\\udde6-\\uddff]){2}", rsSurrPair = "[\\ud800-\\udbff][\\udc00-\\udfff]", rsUpper = "[" + rsUpperRange + "]", rsZWJ = "\\u200d"; - var rsMiscLower = "(?:" + rsLower + "|" + rsMisc + ")", rsMiscUpper = "(?:" + rsUpper + "|" + rsMisc + ")", rsOptContrLower = "(?:" + rsApos + "(?:d|ll|m|re|s|t|ve))?", rsOptContrUpper = "(?:" + rsApos + "(?:D|LL|M|RE|S|T|VE))?", reOptMod = rsModifier + "?", rsOptVar = "[" + rsVarRange + "]?", rsOptJoin = "(?:" + rsZWJ + "(?:" + [rsNonAstral, rsRegional, rsSurrPair].join("|") + ")" + rsOptVar + reOptMod + ")*", rsOrdLower = "\\d*(?:1st|2nd|3rd|(?![123])\\dth)(?=\\b|[A-Z_])", rsOrdUpper = "\\d*(?:1ST|2ND|3RD|(?![123])\\dTH)(?=\\b|[a-z_])", rsSeq = rsOptVar + reOptMod + rsOptJoin, rsEmoji = "(?:" + [rsDingbat, rsRegional, rsSurrPair].join("|") + ")" + rsSeq, rsSymbol = "(?:" + [rsNonAstral + rsCombo + "?", rsCombo, rsRegional, rsSurrPair, rsAstral].join("|") + ")"; - var reApos = RegExp(rsApos, "g"); - var reComboMark = RegExp(rsCombo, "g"); - var reUnicode = RegExp(rsFitz + "(?=" + rsFitz + ")|" + rsSymbol + rsSeq, "g"); - var reUnicodeWord = RegExp([ - rsUpper + "?" + rsLower + "+" + rsOptContrLower + "(?=" + [rsBreak, rsUpper, "$"].join("|") + ")", - rsMiscUpper + "+" + rsOptContrUpper + "(?=" + [rsBreak, rsUpper + rsMiscLower, "$"].join("|") + ")", - rsUpper + "?" + rsMiscLower + "+" + rsOptContrLower, - rsUpper + "+" + rsOptContrUpper, - rsOrdUpper, - rsOrdLower, - rsDigits, - rsEmoji - ].join("|"), "g"); - var reHasUnicode = RegExp("[" + rsZWJ + rsAstralRange + rsComboRange + rsVarRange + "]"); - var reHasUnicodeWord = /[a-z][A-Z]|[A-Z]{2}[a-z]|[0-9][a-zA-Z]|[a-zA-Z][0-9]|[^a-zA-Z0-9 ]/; - var contextProps = [ - "Array", - "Buffer", - "DataView", - "Date", - "Error", - "Float32Array", - "Float64Array", - "Function", - "Int8Array", - "Int16Array", - "Int32Array", - "Map", - "Math", - "Object", - "Promise", - "RegExp", - "Set", - "String", - "Symbol", - "TypeError", - "Uint8Array", - "Uint8ClampedArray", - "Uint16Array", - "Uint32Array", - "WeakMap", - "_", - "clearTimeout", - "isFinite", - "parseInt", - "setTimeout" - ]; - var templateCounter = -1; - 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 cloneableTags = {}; - cloneableTags[argsTag] = cloneableTags[arrayTag] = cloneableTags[arrayBufferTag] = cloneableTags[dataViewTag] = cloneableTags[boolTag] = cloneableTags[dateTag] = cloneableTags[float32Tag] = cloneableTags[float64Tag] = cloneableTags[int8Tag] = cloneableTags[int16Tag] = cloneableTags[int32Tag] = cloneableTags[mapTag] = cloneableTags[numberTag] = cloneableTags[objectTag] = cloneableTags[regexpTag] = cloneableTags[setTag] = cloneableTags[stringTag] = cloneableTags[symbolTag] = cloneableTags[uint8Tag] = cloneableTags[uint8ClampedTag] = cloneableTags[uint16Tag] = cloneableTags[uint32Tag] = true; - cloneableTags[errorTag] = cloneableTags[funcTag] = cloneableTags[weakMapTag] = false; - var deburredLetters = { - "\xC0": "A", - "\xC1": "A", - "\xC2": "A", - "\xC3": "A", - "\xC4": "A", - "\xC5": "A", - "\xE0": "a", - "\xE1": "a", - "\xE2": "a", - "\xE3": "a", - "\xE4": "a", - "\xE5": "a", - "\xC7": "C", - "\xE7": "c", - "\xD0": "D", - "\xF0": "d", - "\xC8": "E", - "\xC9": "E", - "\xCA": "E", - "\xCB": "E", - "\xE8": "e", - "\xE9": "e", - "\xEA": "e", - "\xEB": "e", - "\xCC": "I", - "\xCD": "I", - "\xCE": "I", - "\xCF": "I", - "\xEC": "i", - "\xED": "i", - "\xEE": "i", - "\xEF": "i", - "\xD1": "N", - "\xF1": "n", - "\xD2": "O", - "\xD3": "O", - "\xD4": "O", - "\xD5": "O", - "\xD6": "O", - "\xD8": "O", - "\xF2": "o", - "\xF3": "o", - "\xF4": "o", - "\xF5": "o", - "\xF6": "o", - "\xF8": "o", - "\xD9": "U", - "\xDA": "U", - "\xDB": "U", - "\xDC": "U", - "\xF9": "u", - "\xFA": "u", - "\xFB": "u", - "\xFC": "u", - "\xDD": "Y", - "\xFD": "y", - "\xFF": "y", - "\xC6": "Ae", - "\xE6": "ae", - "\xDE": "Th", - "\xFE": "th", - "\xDF": "ss", - "\u0100": "A", - "\u0102": "A", - "\u0104": "A", - "\u0101": "a", - "\u0103": "a", - "\u0105": "a", - "\u0106": "C", - "\u0108": "C", - "\u010A": "C", - "\u010C": "C", - "\u0107": "c", - "\u0109": "c", - "\u010B": "c", - "\u010D": "c", - "\u010E": "D", - "\u0110": "D", - "\u010F": "d", - "\u0111": "d", - "\u0112": "E", - "\u0114": "E", - "\u0116": "E", - "\u0118": "E", - "\u011A": "E", - "\u0113": "e", - "\u0115": "e", - "\u0117": "e", - "\u0119": "e", - "\u011B": "e", - "\u011C": "G", - "\u011E": "G", - "\u0120": "G", - "\u0122": "G", - "\u011D": "g", - "\u011F": "g", - "\u0121": "g", - "\u0123": "g", - "\u0124": "H", - "\u0126": "H", - "\u0125": "h", - "\u0127": "h", - "\u0128": "I", - "\u012A": "I", - "\u012C": "I", - "\u012E": "I", - "\u0130": "I", - "\u0129": "i", - "\u012B": "i", - "\u012D": "i", - "\u012F": "i", - "\u0131": "i", - "\u0134": "J", - "\u0135": "j", - "\u0136": "K", - "\u0137": "k", - "\u0138": "k", - "\u0139": "L", - "\u013B": "L", - "\u013D": "L", - "\u013F": "L", - "\u0141": "L", - "\u013A": "l", - "\u013C": "l", - "\u013E": "l", - "\u0140": "l", - "\u0142": "l", - "\u0143": "N", - "\u0145": "N", - "\u0147": "N", - "\u014A": "N", - "\u0144": "n", - "\u0146": "n", - "\u0148": "n", - "\u014B": "n", - "\u014C": "O", - "\u014E": "O", - "\u0150": "O", - "\u014D": "o", - "\u014F": "o", - "\u0151": "o", - "\u0154": "R", - "\u0156": "R", - "\u0158": "R", - "\u0155": "r", - "\u0157": "r", - "\u0159": "r", - "\u015A": "S", - "\u015C": "S", - "\u015E": "S", - "\u0160": "S", - "\u015B": "s", - "\u015D": "s", - "\u015F": "s", - "\u0161": "s", - "\u0162": "T", - "\u0164": "T", - "\u0166": "T", - "\u0163": "t", - "\u0165": "t", - "\u0167": "t", - "\u0168": "U", - "\u016A": "U", - "\u016C": "U", - "\u016E": "U", - "\u0170": "U", - "\u0172": "U", - "\u0169": "u", - "\u016B": "u", - "\u016D": "u", - "\u016F": "u", - "\u0171": "u", - "\u0173": "u", - "\u0174": "W", - "\u0175": "w", - "\u0176": "Y", - "\u0177": "y", - "\u0178": "Y", - "\u0179": "Z", - "\u017B": "Z", - "\u017D": "Z", - "\u017A": "z", - "\u017C": "z", - "\u017E": "z", - "\u0132": "IJ", - "\u0133": "ij", - "\u0152": "Oe", - "\u0153": "oe", - "\u0149": "'n", - "\u017F": "s" - }; - var htmlEscapes = { - "&": "&", - "<": "<", - ">": ">", - '"': """, - "'": "'" - }; - var htmlUnescapes = { - "&": "&", - "<": "<", - ">": ">", - """: '"', - "'": "'" - }; - var stringEscapes = { - "\\": "\\", - "'": "'", - "\n": "n", - "\r": "r", - "\u2028": "u2028", - "\u2029": "u2029" +// node_modules/fuzzysort/fuzzysort.js +var require_fuzzysort = __commonJS({ + "node_modules/fuzzysort/fuzzysort.js"(exports, module2) { + ((root, UMD) => { + if (typeof define === "function" && define.amd) + define([], UMD); + else if (typeof module2 === "object" && module2.exports) + module2.exports = UMD(); + else + root["fuzzysort"] = UMD(); + })(exports, (_12) => { + "use strict"; + var single = (search, target) => { + if (search == "farzher") + return { target: "farzher was here (^-^*)/", score: 0, _indexes: [0] }; + if (!search || !target) + return NULL; + var preparedSearch = getPreparedSearch(search); + if (!isObj(target)) + target = getPrepared(target); + var searchBitflags = preparedSearch.bitflags; + if ((searchBitflags & target._bitflags) !== searchBitflags) + return NULL; + return algorithm(preparedSearch, target); }; - var freeParseFloat = parseFloat, freeParseInt = parseInt; - var freeGlobal = typeof global == "object" && global && global.Object === Object && global; - var freeSelf = typeof self == "object" && self && self.Object === Object && self; - var root = freeGlobal || freeSelf || Function("return this")(); - var freeExports = typeof exports == "object" && exports && !exports.nodeType && exports; - var freeModule = freeExports && typeof module2 == "object" && module2 && !module2.nodeType && module2; - 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 (e4) { - } - }(); - var nodeIsArrayBuffer = nodeUtil && nodeUtil.isArrayBuffer, nodeIsDate = nodeUtil && nodeUtil.isDate, nodeIsMap = nodeUtil && nodeUtil.isMap, nodeIsRegExp = nodeUtil && nodeUtil.isRegExp, nodeIsSet = nodeUtil && nodeUtil.isSet, nodeIsTypedArray = nodeUtil && nodeUtil.isTypedArray; - function apply(func, thisArg, args) { - switch (args.length) { - case 0: - return func.call(thisArg); - case 1: - return func.call(thisArg, args[0]); - case 2: - return func.call(thisArg, args[0], args[1]); - case 3: - return func.call(thisArg, args[0], args[1], args[2]); - } - return func.apply(thisArg, args); - } - function arrayAggregator(array, setter, iteratee, accumulator) { - var index = -1, length = array == null ? 0 : array.length; - while (++index < length) { - var value = array[index]; - setter(accumulator, value, iteratee(value), array); - } - return accumulator; - } - function arrayEach(array, iteratee) { - var index = -1, length = array == null ? 0 : array.length; - while (++index < length) { - if (iteratee(array[index], index, array) === false) { - break; - } - } - return array; - } - function arrayEachRight(array, iteratee) { - var length = array == null ? 0 : array.length; - while (length--) { - if (iteratee(array[length], length, array) === false) { - break; + var go = (search, targets, options) => { + if (search == "farzher") + return [{ target: "farzher was here (^-^*)/", score: 0, _indexes: [0], obj: targets ? targets[0] : NULL }]; + if (!search) + return options && options.all ? all(search, targets, options) : noResults; + var preparedSearch = getPreparedSearch(search); + var searchBitflags = preparedSearch.bitflags; + var containsSpace = preparedSearch.containsSpace; + var threshold = options && options.threshold || INT_MIN; + var limit = options && options["limit"] || INT_MAX; + var resultsLen = 0; + var limitedCount = 0; + var targetsLen = targets.length; + if (options && options.key) { + var key2 = options.key; + for (var i4 = 0; i4 < targetsLen; ++i4) { + var obj = targets[i4]; + var target = getValue(obj, key2); + if (!target) + continue; + if (!isObj(target)) + target = getPrepared(target); + if ((searchBitflags & target._bitflags) !== searchBitflags) + continue; + var result = algorithm(preparedSearch, target); + if (result === NULL) + continue; + if (result.score < threshold) + continue; + result = { target: result.target, _targetLower: "", _targetLowerCodes: NULL, _nextBeginningIndexes: NULL, _bitflags: 0, score: result.score, _indexes: result._indexes, obj }; + if (resultsLen < limit) { + q5.add(result); + ++resultsLen; + } else { + ++limitedCount; + if (result.score > q5.peek().score) + q5.replaceTop(result); + } } - } - return array; - } - function arrayEvery(array, predicate) { - var index = -1, length = array == null ? 0 : array.length; - while (++index < length) { - if (!predicate(array[index], index, array)) { - return false; + } else if (options && options.keys) { + var scoreFn = options["scoreFn"] || defaultScoreFn; + var keys = options.keys; + var keysLen = keys.length; + for (var i4 = 0; i4 < targetsLen; ++i4) { + var obj = targets[i4]; + var objResults = new Array(keysLen); + for (var keyI = 0; keyI < keysLen; ++keyI) { + var key2 = keys[keyI]; + var target = getValue(obj, key2); + if (!target) { + objResults[keyI] = NULL; + continue; + } + if (!isObj(target)) + target = getPrepared(target); + if ((searchBitflags & target._bitflags) !== searchBitflags) + objResults[keyI] = NULL; + else + objResults[keyI] = algorithm(preparedSearch, target); + } + objResults.obj = obj; + var score = scoreFn(objResults); + if (score === NULL) + continue; + if (score < threshold) + continue; + objResults.score = score; + if (resultsLen < limit) { + q5.add(objResults); + ++resultsLen; + } else { + ++limitedCount; + if (score > q5.peek().score) + q5.replaceTop(objResults); + } } - } - return true; - } - function arrayFilter(array, predicate) { - var index = -1, length = array == null ? 0 : array.length, resIndex = 0, result = []; - while (++index < length) { - var value = array[index]; - if (predicate(value, index, array)) { - result[resIndex++] = value; + } else { + for (var i4 = 0; i4 < targetsLen; ++i4) { + var target = targets[i4]; + if (!target) + continue; + if (!isObj(target)) + target = getPrepared(target); + if ((searchBitflags & target._bitflags) !== searchBitflags) + continue; + var result = algorithm(preparedSearch, target); + if (result === NULL) + continue; + if (result.score < threshold) + continue; + if (resultsLen < limit) { + q5.add(result); + ++resultsLen; + } else { + ++limitedCount; + if (result.score > q5.peek().score) + q5.replaceTop(result); + } } } - return result; - } - function arrayIncludes(array, value) { - var length = array == null ? 0 : array.length; - return !!length && baseIndexOf(array, value, 0) > -1; - } - function arrayIncludesWith(array, value, comparator) { - var index = -1, length = array == null ? 0 : array.length; - while (++index < length) { - if (comparator(value, array[index])) { - return true; + if (resultsLen === 0) + return noResults; + var results = new Array(resultsLen); + for (var i4 = resultsLen - 1; i4 >= 0; --i4) + results[i4] = q5.poll(); + results.total = resultsLen + limitedCount; + return results; + }; + var highlight = (result, hOpen, hClose) => { + if (typeof hOpen === "function") + return highlightCallback(result, hOpen); + if (result === NULL) + return NULL; + if (hOpen === void 0) + hOpen = ""; + if (hClose === void 0) + hClose = ""; + var highlighted = ""; + var matchesIndex = 0; + var opened = false; + var target = result.target; + var targetLen = target.length; + var indexes2 = result._indexes; + indexes2 = indexes2.slice(0, indexes2.len).sort((a5, b4) => a5 - b4); + for (var i4 = 0; i4 < targetLen; ++i4) { + var char = target[i4]; + if (indexes2[matchesIndex] === i4) { + ++matchesIndex; + if (!opened) { + opened = true; + highlighted += hOpen; + } + if (matchesIndex === indexes2.length) { + highlighted += char + hClose + target.substr(i4 + 1); + break; + } + } else { + if (opened) { + opened = false; + highlighted += hClose; + } } + highlighted += char; } - return false; - } - function arrayMap(array, iteratee) { - var index = -1, length = array == null ? 0 : array.length, result = Array(length); - while (++index < length) { - result[index] = iteratee(array[index], index, array); + return highlighted; + }; + var highlightCallback = (result, cb) => { + if (result === NULL) + return NULL; + var target = result.target; + var targetLen = target.length; + var indexes2 = result._indexes; + indexes2 = indexes2.slice(0, indexes2.len).sort((a5, b4) => a5 - b4); + var highlighted = ""; + var matchI = 0; + var indexesI = 0; + var opened = false; + var result = []; + for (var i4 = 0; i4 < targetLen; ++i4) { + var char = target[i4]; + if (indexes2[indexesI] === i4) { + ++indexesI; + if (!opened) { + opened = true; + result.push(highlighted); + highlighted = ""; + } + if (indexesI === indexes2.length) { + highlighted += char; + result.push(cb(highlighted, matchI++)); + highlighted = ""; + result.push(target.substr(i4 + 1)); + break; + } + } else { + if (opened) { + opened = false; + result.push(cb(highlighted, matchI++)); + highlighted = ""; + } + } + highlighted += char; } return result; - } - function arrayPush(array, values) { - var index = -1, length = values.length, offset = array.length; - while (++index < length) { - array[offset + index] = values[index]; - } - return array; - } - function arrayReduce(array, iteratee, accumulator, initAccum) { - var index = -1, length = array == null ? 0 : array.length; - if (initAccum && length) { - accumulator = array[++index]; - } - while (++index < length) { - accumulator = iteratee(accumulator, array[index], index, array); + }; + var indexes = (result) => result._indexes.slice(0, result._indexes.len).sort((a5, b4) => a5 - b4); + var prepare = (target) => { + if (typeof target !== "string") + target = ""; + var info = prepareLowerInfo(target); + return { "target": target, _targetLower: info._lower, _targetLowerCodes: info.lowerCodes, _nextBeginningIndexes: NULL, _bitflags: info.bitflags, "score": NULL, _indexes: [0], "obj": NULL }; + }; + var prepareSearch = (search) => { + if (typeof search !== "string") + search = ""; + search = search.trim(); + var info = prepareLowerInfo(search); + var spaceSearches = []; + if (info.containsSpace) { + var searches = search.split(/\s+/); + searches = [...new Set(searches)]; + for (var i4 = 0; i4 < searches.length; i4++) { + if (searches[i4] === "") + continue; + var _info = prepareLowerInfo(searches[i4]); + spaceSearches.push({ lowerCodes: _info.lowerCodes, _lower: searches[i4].toLowerCase(), containsSpace: false }); + } } - return accumulator; - } - function arrayReduceRight(array, iteratee, accumulator, initAccum) { - var length = array == null ? 0 : array.length; - if (initAccum && length) { - accumulator = array[--length]; + return { lowerCodes: info.lowerCodes, bitflags: info.bitflags, containsSpace: info.containsSpace, _lower: info._lower, spaceSearches }; + }; + var getPrepared = (target) => { + if (target.length > 999) + return prepare(target); + var targetPrepared = preparedCache.get(target); + if (targetPrepared !== void 0) + return targetPrepared; + targetPrepared = prepare(target); + preparedCache.set(target, targetPrepared); + return targetPrepared; + }; + var getPreparedSearch = (search) => { + if (search.length > 999) + return prepareSearch(search); + var searchPrepared = preparedSearchCache.get(search); + if (searchPrepared !== void 0) + return searchPrepared; + searchPrepared = prepareSearch(search); + preparedSearchCache.set(search, searchPrepared); + return searchPrepared; + }; + var all = (search, targets, options) => { + var results = []; + results.total = targets.length; + var limit = options && options.limit || INT_MAX; + if (options && options.key) { + for (var i4 = 0; i4 < targets.length; i4++) { + var obj = targets[i4]; + var target = getValue(obj, options.key); + if (!target) + continue; + if (!isObj(target)) + target = getPrepared(target); + target.score = INT_MIN; + target._indexes.len = 0; + var result = target; + result = { target: result.target, _targetLower: "", _targetLowerCodes: NULL, _nextBeginningIndexes: NULL, _bitflags: 0, score: target.score, _indexes: NULL, obj }; + results.push(result); + if (results.length >= limit) + return results; + } + } else if (options && options.keys) { + for (var i4 = 0; i4 < targets.length; i4++) { + var obj = targets[i4]; + var objResults = new Array(options.keys.length); + for (var keyI = options.keys.length - 1; keyI >= 0; --keyI) { + var target = getValue(obj, options.keys[keyI]); + if (!target) { + objResults[keyI] = NULL; + continue; + } + if (!isObj(target)) + target = getPrepared(target); + target.score = INT_MIN; + target._indexes.len = 0; + objResults[keyI] = target; + } + objResults.obj = obj; + objResults.score = INT_MIN; + results.push(objResults); + if (results.length >= limit) + return results; + } + } else { + for (var i4 = 0; i4 < targets.length; i4++) { + var target = targets[i4]; + if (!target) + continue; + if (!isObj(target)) + target = getPrepared(target); + target.score = INT_MIN; + target._indexes.len = 0; + results.push(target); + if (results.length >= limit) + return results; + } } - while (length--) { - accumulator = iteratee(accumulator, array[length], length, array); + return results; + }; + var algorithm = (preparedSearch, prepared, allowSpaces = false) => { + if (allowSpaces === false && preparedSearch.containsSpace) + return algorithmSpaces(preparedSearch, prepared); + var searchLower = preparedSearch._lower; + var searchLowerCodes = preparedSearch.lowerCodes; + var searchLowerCode = searchLowerCodes[0]; + var targetLowerCodes = prepared._targetLowerCodes; + var searchLen = searchLowerCodes.length; + var targetLen = targetLowerCodes.length; + var searchI = 0; + var targetI = 0; + var matchesSimpleLen = 0; + for (; ; ) { + var isMatch2 = searchLowerCode === targetLowerCodes[targetI]; + if (isMatch2) { + matchesSimple[matchesSimpleLen++] = targetI; + ++searchI; + if (searchI === searchLen) + break; + searchLowerCode = searchLowerCodes[searchI]; + } + ++targetI; + if (targetI >= targetLen) + return NULL; } - return accumulator; - } - function arraySome(array, predicate) { - var index = -1, length = array == null ? 0 : array.length; - while (++index < length) { - if (predicate(array[index], index, array)) { - return true; + var searchI = 0; + var successStrict = false; + var matchesStrictLen = 0; + var nextBeginningIndexes = prepared._nextBeginningIndexes; + if (nextBeginningIndexes === NULL) + nextBeginningIndexes = prepared._nextBeginningIndexes = prepareNextBeginningIndexes(prepared.target); + var firstPossibleI = targetI = matchesSimple[0] === 0 ? 0 : nextBeginningIndexes[matchesSimple[0] - 1]; + var backtrackCount = 0; + if (targetI !== targetLen) + for (; ; ) { + if (targetI >= targetLen) { + if (searchI <= 0) + break; + ++backtrackCount; + if (backtrackCount > 200) + break; + --searchI; + var lastMatch = matchesStrict[--matchesStrictLen]; + targetI = nextBeginningIndexes[lastMatch]; + } else { + var isMatch2 = searchLowerCodes[searchI] === targetLowerCodes[targetI]; + if (isMatch2) { + matchesStrict[matchesStrictLen++] = targetI; + ++searchI; + if (searchI === searchLen) { + successStrict = true; + break; + } + ++targetI; + } else { + targetI = nextBeginningIndexes[targetI]; + } + } } + var substringIndex = prepared._targetLower.indexOf(searchLower, matchesSimple[0]); + var isSubstring = ~substringIndex; + if (isSubstring && !successStrict) { + for (var i4 = 0; i4 < matchesSimpleLen; ++i4) + matchesSimple[i4] = substringIndex + i4; } - return false; - } - var asciiSize = baseProperty("length"); - function asciiToArray(string) { - return string.split(""); - } - function asciiWords(string) { - return string.match(reAsciiWord) || []; - } - function baseFindKey(collection, predicate, eachFunc) { - var result; - eachFunc(collection, function(value, key2, collection2) { - if (predicate(value, key2, collection2)) { - result = key2; - return false; + var isSubstringBeginning = false; + if (isSubstring) { + isSubstringBeginning = prepared._nextBeginningIndexes[substringIndex - 1] === substringIndex; + } + { + if (successStrict) { + var matchesBest = matchesStrict; + var matchesBestLen = matchesStrictLen; + } else { + var matchesBest = matchesSimple; + var matchesBestLen = matchesSimpleLen; } - }); - return result; - } - function baseFindIndex(array, predicate, fromIndex, fromRight) { - var length = array.length, index = fromIndex + (fromRight ? 1 : -1); - while (fromRight ? index-- : ++index < length) { - if (predicate(array[index], index, array)) { - return index; + var score = 0; + var extraMatchGroupCount = 0; + for (var i4 = 1; i4 < searchLen; ++i4) { + if (matchesBest[i4] - matchesBest[i4 - 1] !== 1) { + score -= matchesBest[i4]; + ++extraMatchGroupCount; + } } - } - return -1; - } - function baseIndexOf(array, value, fromIndex) { - return value === value ? strictIndexOf(array, value, fromIndex) : baseFindIndex(array, baseIsNaN, fromIndex); - } - function baseIndexOfWith(array, value, fromIndex, comparator) { - var index = fromIndex - 1, length = array.length; - while (++index < length) { - if (comparator(array[index], value)) { - return index; + var unmatchedDistance = matchesBest[searchLen - 1] - matchesBest[0] - (searchLen - 1); + score -= (12 + unmatchedDistance) * extraMatchGroupCount; + if (matchesBest[0] !== 0) + score -= matchesBest[0] * matchesBest[0] * 0.2; + if (!successStrict) { + score *= 1e3; + } else { + var uniqueBeginningIndexes = 1; + for (var i4 = nextBeginningIndexes[0]; i4 < targetLen; i4 = nextBeginningIndexes[i4]) + ++uniqueBeginningIndexes; + if (uniqueBeginningIndexes > 24) + score *= (uniqueBeginningIndexes - 24) * 10; } + if (isSubstring) + score /= 1 + searchLen * searchLen * 1; + if (isSubstringBeginning) + score /= 1 + searchLen * searchLen * 1; + score -= targetLen - searchLen; + prepared.score = score; + for (var i4 = 0; i4 < matchesBestLen; ++i4) + prepared._indexes[i4] = matchesBest[i4]; + prepared._indexes.len = matchesBestLen; + return prepared; } - return -1; - } - function baseIsNaN(value) { - return value !== value; - } - function baseMean(array, iteratee) { - var length = array == null ? 0 : array.length; - return length ? baseSum(array, iteratee) / length : NAN; - } - function baseProperty(key2) { - return function(object) { - return object == null ? undefined2 : object[key2]; - }; - } - function basePropertyOf(object) { - return function(key2) { - return object == null ? undefined2 : object[key2]; - }; - } - function baseReduce(collection, iteratee, accumulator, initAccum, eachFunc) { - eachFunc(collection, function(value, index, collection2) { - accumulator = initAccum ? (initAccum = false, value) : iteratee(accumulator, value, index, collection2); - }); - return accumulator; - } - function baseSortBy(array, comparer) { - var length = array.length; - array.sort(comparer); - while (length--) { - array[length] = array[length].value; - } - return array; - } - function baseSum(array, iteratee) { - var result, index = -1, length = array.length; - while (++index < length) { - var current = iteratee(array[index]); - if (current !== undefined2) { - result = result === undefined2 ? current : result + current; + }; + var algorithmSpaces = (preparedSearch, target) => { + var seen_indexes = /* @__PURE__ */ new Set(); + var score = 0; + var result = NULL; + var first_seen_index_last_search = 0; + var searches = preparedSearch.spaceSearches; + for (var i4 = 0; i4 < searches.length; ++i4) { + var search = searches[i4]; + result = algorithm(search, target); + if (result === NULL) + return NULL; + score += result.score; + if (result._indexes[0] < first_seen_index_last_search) { + score -= first_seen_index_last_search - result._indexes[0]; } + first_seen_index_last_search = result._indexes[0]; + for (var j4 = 0; j4 < result._indexes.len; ++j4) + seen_indexes.add(result._indexes[j4]); } - return result; - } - function baseTimes(n2, iteratee) { - var index = -1, result = Array(n2); - while (++index < n2) { - result[index] = iteratee(index); + var allowSpacesResult = algorithm(preparedSearch, target, true); + if (allowSpacesResult !== NULL && allowSpacesResult.score > score) { + return allowSpacesResult; } + result.score = score; + var i4 = 0; + for (let index of seen_indexes) + result._indexes[i4++] = index; + result._indexes.len = i4; return result; - } - function baseToPairs(object, props2) { - return arrayMap(props2, function(key2) { - return [key2, object[key2]]; - }); - } - function baseTrim(string) { - return string ? string.slice(0, trimmedEndIndex(string) + 1).replace(reTrimStart, "") : string; - } - function baseUnary(func) { - return function(value) { - return func(value); - }; - } - function baseValues(object, props2) { - return arrayMap(props2, function(key2) { - return object[key2]; - }); - } - function cacheHas(cache, key2) { - return cache.has(key2); - } - function charsStartIndex(strSymbols, chrSymbols) { - var index = -1, length = strSymbols.length; - while (++index < length && baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) { + }; + var prepareLowerInfo = (str) => { + var strLen = str.length; + var lower = str.toLowerCase(); + var lowerCodes = []; + var bitflags = 0; + var containsSpace = false; + for (var i4 = 0; i4 < strLen; ++i4) { + var lowerCode = lowerCodes[i4] = lower.charCodeAt(i4); + if (lowerCode === 32) { + containsSpace = true; + continue; + } + var bit = lowerCode >= 97 && lowerCode <= 122 ? lowerCode - 97 : lowerCode >= 48 && lowerCode <= 57 ? 26 : lowerCode <= 127 ? 30 : 31; + bitflags |= 1 << bit; } - return index; - } - function charsEndIndex(strSymbols, chrSymbols) { - var index = strSymbols.length; - while (index-- && baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) { + return { lowerCodes, bitflags, containsSpace, _lower: lower }; + }; + var prepareBeginningIndexes = (target) => { + var targetLen = target.length; + var beginningIndexes = []; + var beginningIndexesLen = 0; + var wasUpper = false; + var wasAlphanum = false; + for (var i4 = 0; i4 < targetLen; ++i4) { + var targetCode = target.charCodeAt(i4); + var isUpper = targetCode >= 65 && targetCode <= 90; + var isAlphanum = isUpper || targetCode >= 97 && targetCode <= 122 || targetCode >= 48 && targetCode <= 57; + var isBeginning = isUpper && !wasUpper || !wasAlphanum || !isAlphanum; + wasUpper = isUpper; + wasAlphanum = isAlphanum; + if (isBeginning) + beginningIndexes[beginningIndexesLen++] = i4; } - return index; - } - function countHolders(array, placeholder) { - var length = array.length, result = 0; - while (length--) { - if (array[length] === placeholder) { - ++result; + return beginningIndexes; + }; + var prepareNextBeginningIndexes = (target) => { + var targetLen = target.length; + var beginningIndexes = prepareBeginningIndexes(target); + var nextBeginningIndexes = []; + var lastIsBeginning = beginningIndexes[0]; + var lastIsBeginningI = 0; + for (var i4 = 0; i4 < targetLen; ++i4) { + if (lastIsBeginning > i4) { + nextBeginningIndexes[i4] = lastIsBeginning; + } else { + lastIsBeginning = beginningIndexes[++lastIsBeginningI]; + nextBeginningIndexes[i4] = lastIsBeginning === void 0 ? targetLen : lastIsBeginning; } } - return result; - } - var deburrLetter = basePropertyOf(deburredLetters); - var escapeHtmlChar = basePropertyOf(htmlEscapes); - function escapeStringChar(chr) { - return "\\" + stringEscapes[chr]; - } - function getValue(object, key2) { - return object == null ? undefined2 : object[key2]; - } - function hasUnicode(string) { - return reHasUnicode.test(string); - } - function hasUnicodeWord(string) { - return reHasUnicodeWord.test(string); - } - function iteratorToArray(iterator) { - var data, result = []; - while (!(data = iterator.next()).done) { - result.push(data.value); + return nextBeginningIndexes; + }; + var cleanup = () => { + preparedCache.clear(); + preparedSearchCache.clear(); + matchesSimple = []; + matchesStrict = []; + }; + var preparedCache = /* @__PURE__ */ new Map(); + var preparedSearchCache = /* @__PURE__ */ new Map(); + var matchesSimple = []; + var matchesStrict = []; + var defaultScoreFn = (a5) => { + var max3 = INT_MIN; + var len = a5.length; + for (var i4 = 0; i4 < len; ++i4) { + var result = a5[i4]; + if (result === NULL) + continue; + var score = result.score; + if (score > max3) + max3 = score; } - return result; - } - function mapToArray(map) { - var index = -1, result = Array(map.size); - map.forEach(function(value, key2) { - result[++index] = [key2, value]; - }); - return result; - } - function overArg(func, transform) { - return function(arg) { - return func(transform(arg)); + if (max3 === INT_MIN) + return NULL; + return max3; + }; + var getValue = (obj, prop) => { + var tmp = obj[prop]; + if (tmp !== void 0) + return tmp; + var segs = prop; + if (!Array.isArray(prop)) + segs = prop.split("."); + var len = segs.length; + var i4 = -1; + while (obj && ++i4 < len) + obj = obj[segs[i4]]; + return obj; + }; + var isObj = (x5) => { + return typeof x5 === "object"; + }; + var INT_MAX = Infinity; + var INT_MIN = -INT_MAX; + var noResults = []; + noResults.total = 0; + var NULL = null; + var fastpriorityqueue = (r3) => { + var e4 = [], o3 = 0, a5 = {}, v3 = (r4) => { + for (var a6 = 0, v4 = e4[a6], c4 = 1; c4 < o3; ) { + var s5 = c4 + 1; + a6 = c4, s5 < o3 && e4[s5].score < e4[c4].score && (a6 = s5), e4[a6 - 1 >> 1] = e4[a6], c4 = 1 + (a6 << 1); + } + for (var f4 = a6 - 1 >> 1; a6 > 0 && v4.score < e4[f4].score; f4 = (a6 = f4) - 1 >> 1) + e4[a6] = e4[f4]; + e4[a6] = v4; }; + return a5.add = (r4) => { + var a6 = o3; + e4[o3++] = r4; + for (var v4 = a6 - 1 >> 1; a6 > 0 && r4.score < e4[v4].score; v4 = (a6 = v4) - 1 >> 1) + e4[a6] = e4[v4]; + e4[a6] = r4; + }, a5.poll = (r4) => { + if (0 !== o3) { + var a6 = e4[0]; + return e4[0] = e4[--o3], v3(), a6; + } + }, a5.peek = (r4) => { + if (0 !== o3) + return e4[0]; + }, a5.replaceTop = (r4) => { + e4[0] = r4, v3(); + }, a5; + }; + var q5 = fastpriorityqueue(); + return { "single": single, "go": go, "highlight": highlight, "prepare": prepare, "indexes": indexes, "cleanup": cleanup }; + }); + } +}); + +// node_modules/lodash/lodash.js +var require_lodash = __commonJS({ + "node_modules/lodash/lodash.js"(exports, module2) { + (function() { + var undefined2; + var VERSION = "4.17.21"; + var LARGE_ARRAY_SIZE = 200; + var CORE_ERROR_TEXT = "Unsupported core-js use. Try https://npms.io/search?q=ponyfill.", FUNC_ERROR_TEXT = "Expected a function", INVALID_TEMPL_VAR_ERROR_TEXT = "Invalid `variable` option passed into `_.template`"; + var HASH_UNDEFINED = "__lodash_hash_undefined__"; + var MAX_MEMOIZE_SIZE = 500; + var PLACEHOLDER = "__lodash_placeholder__"; + var CLONE_DEEP_FLAG = 1, CLONE_FLAT_FLAG = 2, CLONE_SYMBOLS_FLAG = 4; + var COMPARE_PARTIAL_FLAG = 1, COMPARE_UNORDERED_FLAG = 2; + var WRAP_BIND_FLAG = 1, WRAP_BIND_KEY_FLAG = 2, WRAP_CURRY_BOUND_FLAG = 4, WRAP_CURRY_FLAG = 8, WRAP_CURRY_RIGHT_FLAG = 16, WRAP_PARTIAL_FLAG = 32, WRAP_PARTIAL_RIGHT_FLAG = 64, WRAP_ARY_FLAG = 128, WRAP_REARG_FLAG = 256, WRAP_FLIP_FLAG = 512; + var DEFAULT_TRUNC_LENGTH = 30, DEFAULT_TRUNC_OMISSION = "..."; + var HOT_COUNT = 800, HOT_SPAN = 16; + var LAZY_FILTER_FLAG = 1, LAZY_MAP_FLAG = 2, LAZY_WHILE_FLAG = 3; + var INFINITY = 1 / 0, MAX_SAFE_INTEGER = 9007199254740991, MAX_INTEGER = 17976931348623157e292, NAN = 0 / 0; + var MAX_ARRAY_LENGTH = 4294967295, MAX_ARRAY_INDEX = MAX_ARRAY_LENGTH - 1, HALF_MAX_ARRAY_LENGTH = MAX_ARRAY_LENGTH >>> 1; + var wrapFlags = [ + ["ary", WRAP_ARY_FLAG], + ["bind", WRAP_BIND_FLAG], + ["bindKey", WRAP_BIND_KEY_FLAG], + ["curry", WRAP_CURRY_FLAG], + ["curryRight", WRAP_CURRY_RIGHT_FLAG], + ["flip", WRAP_FLIP_FLAG], + ["partial", WRAP_PARTIAL_FLAG], + ["partialRight", WRAP_PARTIAL_RIGHT_FLAG], + ["rearg", WRAP_REARG_FLAG] + ]; + var argsTag = "[object Arguments]", arrayTag = "[object Array]", asyncTag = "[object AsyncFunction]", boolTag = "[object Boolean]", dateTag = "[object Date]", domExcTag = "[object DOMException]", errorTag = "[object Error]", funcTag = "[object Function]", genTag = "[object GeneratorFunction]", mapTag = "[object Map]", numberTag = "[object Number]", nullTag = "[object Null]", objectTag = "[object Object]", promiseTag = "[object Promise]", proxyTag = "[object Proxy]", regexpTag = "[object RegExp]", setTag = "[object Set]", stringTag = "[object String]", symbolTag = "[object Symbol]", undefinedTag = "[object Undefined]", weakMapTag = "[object WeakMap]", weakSetTag = "[object WeakSet]"; + var arrayBufferTag = "[object ArrayBuffer]", dataViewTag = "[object DataView]", float32Tag = "[object Float32Array]", float64Tag = "[object Float64Array]", int8Tag = "[object Int8Array]", int16Tag = "[object Int16Array]", int32Tag = "[object Int32Array]", uint8Tag = "[object Uint8Array]", uint8ClampedTag = "[object Uint8ClampedArray]", uint16Tag = "[object Uint16Array]", uint32Tag = "[object Uint32Array]"; + var reEmptyStringLeading = /\b__p \+= '';/g, reEmptyStringMiddle = /\b(__p \+=) '' \+/g, reEmptyStringTrailing = /(__e\(.*?\)|\b__t\)) \+\n'';/g; + var reEscapedHtml = /&(?:amp|lt|gt|quot|#39);/g, reUnescapedHtml = /[&<>"']/g, reHasEscapedHtml = RegExp(reEscapedHtml.source), reHasUnescapedHtml = RegExp(reUnescapedHtml.source); + var reEscape = /<%-([\s\S]+?)%>/g, reEvaluate = /<%([\s\S]+?)%>/g, reInterpolate = /<%=([\s\S]+?)%>/g; + var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/, reIsPlainProp = /^\w*$/, rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g; + var reRegExpChar = /[\\^$.*+?()[\]{}|]/g, reHasRegExpChar = RegExp(reRegExpChar.source); + var reTrimStart = /^\s+/; + var reWhitespace = /\s/; + var reWrapComment = /\{(?:\n\/\* \[wrapped with .+\] \*\/)?\n?/, reWrapDetails = /\{\n\/\* \[wrapped with (.+)\] \*/, reSplitDetails = /,? & /; + var reAsciiWord = /[^\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f]+/g; + var reForbiddenIdentifierChars = /[()=,{}\[\]\/\s]/; + var reEscapeChar = /\\(\\)?/g; + var reEsTemplate = /\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g; + var reFlags = /\w*$/; + var reIsBadHex = /^[-+]0x[0-9a-f]+$/i; + var reIsBinary = /^0b[01]+$/i; + var reIsHostCtor = /^\[object .+?Constructor\]$/; + var reIsOctal = /^0o[0-7]+$/i; + var reIsUint = /^(?:0|[1-9]\d*)$/; + var reLatin = /[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g; + var reNoMatch = /($^)/; + var reUnescapedString = /['\n\r\u2028\u2029\\]/g; + var rsAstralRange = "\\ud800-\\udfff", rsComboMarksRange = "\\u0300-\\u036f", reComboHalfMarksRange = "\\ufe20-\\ufe2f", rsComboSymbolsRange = "\\u20d0-\\u20ff", rsComboRange = rsComboMarksRange + reComboHalfMarksRange + rsComboSymbolsRange, rsDingbatRange = "\\u2700-\\u27bf", rsLowerRange = "a-z\\xdf-\\xf6\\xf8-\\xff", rsMathOpRange = "\\xac\\xb1\\xd7\\xf7", rsNonCharRange = "\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf", rsPunctuationRange = "\\u2000-\\u206f", rsSpaceRange = " \\t\\x0b\\f\\xa0\\ufeff\\n\\r\\u2028\\u2029\\u1680\\u180e\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200a\\u202f\\u205f\\u3000", rsUpperRange = "A-Z\\xc0-\\xd6\\xd8-\\xde", rsVarRange = "\\ufe0e\\ufe0f", rsBreakRange = rsMathOpRange + rsNonCharRange + rsPunctuationRange + rsSpaceRange; + var rsApos = "['\u2019]", rsAstral = "[" + rsAstralRange + "]", rsBreak = "[" + rsBreakRange + "]", rsCombo = "[" + rsComboRange + "]", rsDigits = "\\d+", rsDingbat = "[" + rsDingbatRange + "]", rsLower = "[" + rsLowerRange + "]", rsMisc = "[^" + rsAstralRange + rsBreakRange + rsDigits + rsDingbatRange + rsLowerRange + rsUpperRange + "]", rsFitz = "\\ud83c[\\udffb-\\udfff]", rsModifier = "(?:" + rsCombo + "|" + rsFitz + ")", rsNonAstral = "[^" + rsAstralRange + "]", rsRegional = "(?:\\ud83c[\\udde6-\\uddff]){2}", rsSurrPair = "[\\ud800-\\udbff][\\udc00-\\udfff]", rsUpper = "[" + rsUpperRange + "]", rsZWJ = "\\u200d"; + var rsMiscLower = "(?:" + rsLower + "|" + rsMisc + ")", rsMiscUpper = "(?:" + rsUpper + "|" + rsMisc + ")", rsOptContrLower = "(?:" + rsApos + "(?:d|ll|m|re|s|t|ve))?", rsOptContrUpper = "(?:" + rsApos + "(?:D|LL|M|RE|S|T|VE))?", reOptMod = rsModifier + "?", rsOptVar = "[" + rsVarRange + "]?", rsOptJoin = "(?:" + rsZWJ + "(?:" + [rsNonAstral, rsRegional, rsSurrPair].join("|") + ")" + rsOptVar + reOptMod + ")*", rsOrdLower = "\\d*(?:1st|2nd|3rd|(?![123])\\dth)(?=\\b|[A-Z_])", rsOrdUpper = "\\d*(?:1ST|2ND|3RD|(?![123])\\dTH)(?=\\b|[a-z_])", rsSeq = rsOptVar + reOptMod + rsOptJoin, rsEmoji = "(?:" + [rsDingbat, rsRegional, rsSurrPair].join("|") + ")" + rsSeq, rsSymbol = "(?:" + [rsNonAstral + rsCombo + "?", rsCombo, rsRegional, rsSurrPair, rsAstral].join("|") + ")"; + var reApos = RegExp(rsApos, "g"); + var reComboMark = RegExp(rsCombo, "g"); + var reUnicode = RegExp(rsFitz + "(?=" + rsFitz + ")|" + rsSymbol + rsSeq, "g"); + var reUnicodeWord = RegExp([ + rsUpper + "?" + rsLower + "+" + rsOptContrLower + "(?=" + [rsBreak, rsUpper, "$"].join("|") + ")", + rsMiscUpper + "+" + rsOptContrUpper + "(?=" + [rsBreak, rsUpper + rsMiscLower, "$"].join("|") + ")", + rsUpper + "?" + rsMiscLower + "+" + rsOptContrLower, + rsUpper + "+" + rsOptContrUpper, + rsOrdUpper, + rsOrdLower, + rsDigits, + rsEmoji + ].join("|"), "g"); + var reHasUnicode = RegExp("[" + rsZWJ + rsAstralRange + rsComboRange + rsVarRange + "]"); + var reHasUnicodeWord = /[a-z][A-Z]|[A-Z]{2}[a-z]|[0-9][a-zA-Z]|[a-zA-Z][0-9]|[^a-zA-Z0-9 ]/; + var contextProps = [ + "Array", + "Buffer", + "DataView", + "Date", + "Error", + "Float32Array", + "Float64Array", + "Function", + "Int8Array", + "Int16Array", + "Int32Array", + "Map", + "Math", + "Object", + "Promise", + "RegExp", + "Set", + "String", + "Symbol", + "TypeError", + "Uint8Array", + "Uint8ClampedArray", + "Uint16Array", + "Uint32Array", + "WeakMap", + "_", + "clearTimeout", + "isFinite", + "parseInt", + "setTimeout" + ]; + var templateCounter = -1; + 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 cloneableTags = {}; + cloneableTags[argsTag] = cloneableTags[arrayTag] = cloneableTags[arrayBufferTag] = cloneableTags[dataViewTag] = cloneableTags[boolTag] = cloneableTags[dateTag] = cloneableTags[float32Tag] = cloneableTags[float64Tag] = cloneableTags[int8Tag] = cloneableTags[int16Tag] = cloneableTags[int32Tag] = cloneableTags[mapTag] = cloneableTags[numberTag] = cloneableTags[objectTag] = cloneableTags[regexpTag] = cloneableTags[setTag] = cloneableTags[stringTag] = cloneableTags[symbolTag] = cloneableTags[uint8Tag] = cloneableTags[uint8ClampedTag] = cloneableTags[uint16Tag] = cloneableTags[uint32Tag] = true; + cloneableTags[errorTag] = cloneableTags[funcTag] = cloneableTags[weakMapTag] = false; + var deburredLetters = { + "\xC0": "A", + "\xC1": "A", + "\xC2": "A", + "\xC3": "A", + "\xC4": "A", + "\xC5": "A", + "\xE0": "a", + "\xE1": "a", + "\xE2": "a", + "\xE3": "a", + "\xE4": "a", + "\xE5": "a", + "\xC7": "C", + "\xE7": "c", + "\xD0": "D", + "\xF0": "d", + "\xC8": "E", + "\xC9": "E", + "\xCA": "E", + "\xCB": "E", + "\xE8": "e", + "\xE9": "e", + "\xEA": "e", + "\xEB": "e", + "\xCC": "I", + "\xCD": "I", + "\xCE": "I", + "\xCF": "I", + "\xEC": "i", + "\xED": "i", + "\xEE": "i", + "\xEF": "i", + "\xD1": "N", + "\xF1": "n", + "\xD2": "O", + "\xD3": "O", + "\xD4": "O", + "\xD5": "O", + "\xD6": "O", + "\xD8": "O", + "\xF2": "o", + "\xF3": "o", + "\xF4": "o", + "\xF5": "o", + "\xF6": "o", + "\xF8": "o", + "\xD9": "U", + "\xDA": "U", + "\xDB": "U", + "\xDC": "U", + "\xF9": "u", + "\xFA": "u", + "\xFB": "u", + "\xFC": "u", + "\xDD": "Y", + "\xFD": "y", + "\xFF": "y", + "\xC6": "Ae", + "\xE6": "ae", + "\xDE": "Th", + "\xFE": "th", + "\xDF": "ss", + "\u0100": "A", + "\u0102": "A", + "\u0104": "A", + "\u0101": "a", + "\u0103": "a", + "\u0105": "a", + "\u0106": "C", + "\u0108": "C", + "\u010A": "C", + "\u010C": "C", + "\u0107": "c", + "\u0109": "c", + "\u010B": "c", + "\u010D": "c", + "\u010E": "D", + "\u0110": "D", + "\u010F": "d", + "\u0111": "d", + "\u0112": "E", + "\u0114": "E", + "\u0116": "E", + "\u0118": "E", + "\u011A": "E", + "\u0113": "e", + "\u0115": "e", + "\u0117": "e", + "\u0119": "e", + "\u011B": "e", + "\u011C": "G", + "\u011E": "G", + "\u0120": "G", + "\u0122": "G", + "\u011D": "g", + "\u011F": "g", + "\u0121": "g", + "\u0123": "g", + "\u0124": "H", + "\u0126": "H", + "\u0125": "h", + "\u0127": "h", + "\u0128": "I", + "\u012A": "I", + "\u012C": "I", + "\u012E": "I", + "\u0130": "I", + "\u0129": "i", + "\u012B": "i", + "\u012D": "i", + "\u012F": "i", + "\u0131": "i", + "\u0134": "J", + "\u0135": "j", + "\u0136": "K", + "\u0137": "k", + "\u0138": "k", + "\u0139": "L", + "\u013B": "L", + "\u013D": "L", + "\u013F": "L", + "\u0141": "L", + "\u013A": "l", + "\u013C": "l", + "\u013E": "l", + "\u0140": "l", + "\u0142": "l", + "\u0143": "N", + "\u0145": "N", + "\u0147": "N", + "\u014A": "N", + "\u0144": "n", + "\u0146": "n", + "\u0148": "n", + "\u014B": "n", + "\u014C": "O", + "\u014E": "O", + "\u0150": "O", + "\u014D": "o", + "\u014F": "o", + "\u0151": "o", + "\u0154": "R", + "\u0156": "R", + "\u0158": "R", + "\u0155": "r", + "\u0157": "r", + "\u0159": "r", + "\u015A": "S", + "\u015C": "S", + "\u015E": "S", + "\u0160": "S", + "\u015B": "s", + "\u015D": "s", + "\u015F": "s", + "\u0161": "s", + "\u0162": "T", + "\u0164": "T", + "\u0166": "T", + "\u0163": "t", + "\u0165": "t", + "\u0167": "t", + "\u0168": "U", + "\u016A": "U", + "\u016C": "U", + "\u016E": "U", + "\u0170": "U", + "\u0172": "U", + "\u0169": "u", + "\u016B": "u", + "\u016D": "u", + "\u016F": "u", + "\u0171": "u", + "\u0173": "u", + "\u0174": "W", + "\u0175": "w", + "\u0176": "Y", + "\u0177": "y", + "\u0178": "Y", + "\u0179": "Z", + "\u017B": "Z", + "\u017D": "Z", + "\u017A": "z", + "\u017C": "z", + "\u017E": "z", + "\u0132": "IJ", + "\u0133": "ij", + "\u0152": "Oe", + "\u0153": "oe", + "\u0149": "'n", + "\u017F": "s" + }; + var htmlEscapes = { + "&": "&", + "<": "<", + ">": ">", + '"': """, + "'": "'" + }; + var htmlUnescapes = { + "&": "&", + "<": "<", + ">": ">", + """: '"', + "'": "'" + }; + var stringEscapes = { + "\\": "\\", + "'": "'", + "\n": "n", + "\r": "r", + "\u2028": "u2028", + "\u2029": "u2029" + }; + var freeParseFloat = parseFloat, freeParseInt = parseInt; + var freeGlobal = typeof global == "object" && global && global.Object === Object && global; + var freeSelf = typeof self == "object" && self && self.Object === Object && self; + var root = freeGlobal || freeSelf || Function("return this")(); + var freeExports = typeof exports == "object" && exports && !exports.nodeType && exports; + var freeModule = freeExports && typeof module2 == "object" && module2 && !module2.nodeType && module2; + var moduleExports = freeModule && freeModule.exports === freeExports; + var freeProcess = moduleExports && freeGlobal.process; + var nodeUtil = function() { + try { + var types2 = freeModule && freeModule.require && freeModule.require("util").types; + if (types2) { + return types2; + } + return freeProcess && freeProcess.binding && freeProcess.binding("util"); + } catch (e4) { + } + }(); + var nodeIsArrayBuffer = nodeUtil && nodeUtil.isArrayBuffer, nodeIsDate = nodeUtil && nodeUtil.isDate, nodeIsMap = nodeUtil && nodeUtil.isMap, nodeIsRegExp = nodeUtil && nodeUtil.isRegExp, nodeIsSet = nodeUtil && nodeUtil.isSet, nodeIsTypedArray = nodeUtil && nodeUtil.isTypedArray; + function apply(func, thisArg, args) { + switch (args.length) { + case 0: + return func.call(thisArg); + case 1: + return func.call(thisArg, args[0]); + case 2: + return func.call(thisArg, args[0], args[1]); + case 3: + return func.call(thisArg, args[0], args[1], args[2]); + } + return func.apply(thisArg, args); } - function replaceHolders(array, placeholder) { - var index = -1, length = array.length, resIndex = 0, result = []; + function arrayAggregator(array, setter, iteratee, accumulator) { + var index = -1, length = array == null ? 0 : array.length; while (++index < length) { var value = array[index]; - if (value === placeholder || value === PLACEHOLDER) { - array[index] = PLACEHOLDER; - result[resIndex++] = index; - } + setter(accumulator, value, iteratee(value), array); } - return result; - } - function setToArray(set) { - var index = -1, result = Array(set.size); - set.forEach(function(value) { - result[++index] = value; - }); - return result; - } - function setToPairs(set) { - var index = -1, result = Array(set.size); - set.forEach(function(value) { - result[++index] = [value, value]; - }); - return result; + return accumulator; } - function strictIndexOf(array, value, fromIndex) { - var index = fromIndex - 1, length = array.length; + function arrayEach(array, iteratee) { + var index = -1, length = array == null ? 0 : array.length; while (++index < length) { - if (array[index] === value) { - return index; + if (iteratee(array[index], index, array) === false) { + break; } } - return -1; + return array; } - function strictLastIndexOf(array, value, fromIndex) { - var index = fromIndex + 1; - while (index--) { - if (array[index] === value) { - return index; + function arrayEachRight(array, iteratee) { + var length = array == null ? 0 : array.length; + while (length--) { + if (iteratee(array[length], length, array) === false) { + break; } } - return index; - } - function stringSize(string) { - return hasUnicode(string) ? unicodeSize(string) : asciiSize(string); + return array; } - function stringToArray(string) { + function arrayEvery(array, predicate) { + var index = -1, length = array == null ? 0 : array.length; + while (++index < length) { + if (!predicate(array[index], index, array)) { + return false; + } + } + return true; + } + function arrayFilter(array, predicate) { + var index = -1, length = array == null ? 0 : array.length, resIndex = 0, result = []; + while (++index < length) { + var value = array[index]; + if (predicate(value, index, array)) { + result[resIndex++] = value; + } + } + return result; + } + function arrayIncludes(array, value) { + var length = array == null ? 0 : array.length; + return !!length && baseIndexOf(array, value, 0) > -1; + } + function arrayIncludesWith(array, value, comparator) { + var index = -1, length = array == null ? 0 : array.length; + while (++index < length) { + if (comparator(value, array[index])) { + return true; + } + } + return false; + } + function arrayMap(array, iteratee) { + var index = -1, length = array == null ? 0 : array.length, result = Array(length); + while (++index < length) { + result[index] = iteratee(array[index], index, array); + } + return result; + } + function arrayPush(array, values) { + var index = -1, length = values.length, offset2 = array.length; + while (++index < length) { + array[offset2 + index] = values[index]; + } + return array; + } + function arrayReduce(array, iteratee, accumulator, initAccum) { + var index = -1, length = array == null ? 0 : array.length; + if (initAccum && length) { + accumulator = array[++index]; + } + while (++index < length) { + accumulator = iteratee(accumulator, array[index], index, array); + } + return accumulator; + } + function arrayReduceRight(array, iteratee, accumulator, initAccum) { + var length = array == null ? 0 : array.length; + if (initAccum && length) { + accumulator = array[--length]; + } + while (length--) { + accumulator = iteratee(accumulator, array[length], length, array); + } + return accumulator; + } + function arraySome(array, predicate) { + var index = -1, length = array == null ? 0 : array.length; + while (++index < length) { + if (predicate(array[index], index, array)) { + return true; + } + } + return false; + } + var asciiSize = baseProperty("length"); + function asciiToArray(string) { + return string.split(""); + } + function asciiWords(string) { + return string.match(reAsciiWord) || []; + } + function baseFindKey(collection, predicate, eachFunc) { + var result; + eachFunc(collection, function(value, key2, collection2) { + if (predicate(value, key2, collection2)) { + result = key2; + return false; + } + }); + return result; + } + function baseFindIndex(array, predicate, fromIndex, fromRight) { + var length = array.length, index = fromIndex + (fromRight ? 1 : -1); + while (fromRight ? index-- : ++index < length) { + if (predicate(array[index], index, array)) { + return index; + } + } + return -1; + } + function baseIndexOf(array, value, fromIndex) { + return value === value ? strictIndexOf(array, value, fromIndex) : baseFindIndex(array, baseIsNaN, fromIndex); + } + function baseIndexOfWith(array, value, fromIndex, comparator) { + var index = fromIndex - 1, length = array.length; + while (++index < length) { + if (comparator(array[index], value)) { + return index; + } + } + return -1; + } + function baseIsNaN(value) { + return value !== value; + } + function baseMean(array, iteratee) { + var length = array == null ? 0 : array.length; + return length ? baseSum(array, iteratee) / length : NAN; + } + function baseProperty(key2) { + return function(object) { + return object == null ? undefined2 : object[key2]; + }; + } + function basePropertyOf(object) { + return function(key2) { + return object == null ? undefined2 : object[key2]; + }; + } + function baseReduce(collection, iteratee, accumulator, initAccum, eachFunc) { + eachFunc(collection, function(value, index, collection2) { + accumulator = initAccum ? (initAccum = false, value) : iteratee(accumulator, value, index, collection2); + }); + return accumulator; + } + function baseSortBy(array, comparer) { + var length = array.length; + array.sort(comparer); + while (length--) { + array[length] = array[length].value; + } + return array; + } + function baseSum(array, iteratee) { + var result, index = -1, length = array.length; + while (++index < length) { + var current2 = iteratee(array[index]); + if (current2 !== undefined2) { + result = result === undefined2 ? current2 : result + current2; + } + } + return result; + } + function baseTimes(n2, iteratee) { + var index = -1, result = Array(n2); + while (++index < n2) { + result[index] = iteratee(index); + } + return result; + } + function baseToPairs(object, props2) { + return arrayMap(props2, function(key2) { + return [key2, object[key2]]; + }); + } + function baseTrim(string) { + return string ? string.slice(0, trimmedEndIndex(string) + 1).replace(reTrimStart, "") : string; + } + function baseUnary(func) { + return function(value) { + return func(value); + }; + } + function baseValues(object, props2) { + return arrayMap(props2, function(key2) { + return object[key2]; + }); + } + function cacheHas(cache, key2) { + return cache.has(key2); + } + function charsStartIndex(strSymbols, chrSymbols) { + var index = -1, length = strSymbols.length; + while (++index < length && baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) { + } + return index; + } + function charsEndIndex(strSymbols, chrSymbols) { + var index = strSymbols.length; + while (index-- && baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) { + } + return index; + } + function countHolders(array, placeholder) { + var length = array.length, result = 0; + while (length--) { + if (array[length] === placeholder) { + ++result; + } + } + return result; + } + var deburrLetter = basePropertyOf(deburredLetters); + var escapeHtmlChar = basePropertyOf(htmlEscapes); + function escapeStringChar(chr) { + return "\\" + stringEscapes[chr]; + } + function getValue(object, key2) { + return object == null ? undefined2 : object[key2]; + } + function hasUnicode(string) { + return reHasUnicode.test(string); + } + function hasUnicodeWord(string) { + return reHasUnicodeWord.test(string); + } + function iteratorToArray(iterator) { + var data2, result = []; + while (!(data2 = iterator.next()).done) { + result.push(data2.value); + } + return result; + } + function mapToArray(map) { + var index = -1, result = Array(map.size); + map.forEach(function(value, key2) { + result[++index] = [key2, value]; + }); + return result; + } + function overArg(func, transform) { + return function(arg) { + return func(transform(arg)); + }; + } + function replaceHolders(array, placeholder) { + var index = -1, length = array.length, resIndex = 0, result = []; + while (++index < length) { + var value = array[index]; + if (value === placeholder || value === PLACEHOLDER) { + array[index] = PLACEHOLDER; + result[resIndex++] = index; + } + } + return result; + } + function setToArray(set) { + var index = -1, result = Array(set.size); + set.forEach(function(value) { + result[++index] = value; + }); + return result; + } + function setToPairs(set) { + var index = -1, result = Array(set.size); + set.forEach(function(value) { + result[++index] = [value, value]; + }); + return result; + } + function strictIndexOf(array, value, fromIndex) { + var index = fromIndex - 1, length = array.length; + while (++index < length) { + if (array[index] === value) { + return index; + } + } + return -1; + } + function strictLastIndexOf(array, value, fromIndex) { + var index = fromIndex + 1; + while (index--) { + if (array[index] === value) { + return index; + } + } + return index; + } + function stringSize(string) { + return hasUnicode(string) ? unicodeSize(string) : asciiSize(string); + } + function stringToArray(string) { return hasUnicode(string) ? unicodeToArray(string) : asciiToArray(string); } function trimmedEndIndex(string) { @@ -734,12 +1318,12 @@ var require_lodash = __commonJS({ return string.match(reUnicodeWord) || []; } var runInContext = function runInContext2(context) { - context = context == null ? root : _9.defaults(root.Object(), context, _9.pick(root, contextProps)); + context = context == null ? root : _12.defaults(root.Object(), context, _12.pick(root, contextProps)); var Array2 = context.Array, Date2 = context.Date, Error2 = context.Error, Function2 = context.Function, Math2 = context.Math, Object2 = context.Object, RegExp2 = context.RegExp, String2 = context.String, TypeError2 = context.TypeError; var arrayProto = Array2.prototype, funcProto = Function2.prototype, objectProto = Object2.prototype; var coreJsData = context["__core-js_shared__"]; var funcToString = funcProto.toString; - var hasOwnProperty = objectProto.hasOwnProperty; + var hasOwnProperty2 = objectProto.hasOwnProperty; var idCounter = 0; var maskSrcKey = function() { var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || ""); @@ -749,7 +1333,7 @@ var require_lodash = __commonJS({ var objectCtorString = funcToString.call(Object2); var oldDash = root._; var reIsNative = RegExp2( - "^" + funcToString.call(hasOwnProperty).replace(reRegExpChar, "\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, "$1.*?") + "$" + "^" + funcToString.call(hasOwnProperty2).replace(reRegExpChar, "\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, "$1.*?") + "$" ); var Buffer2 = moduleExports ? context.Buffer : undefined2, Symbol2 = context.Symbol, Uint8Array2 = context.Uint8Array, allocUnsafe = Buffer2 ? Buffer2.allocUnsafe : undefined2, getPrototype = overArg(Object2.getPrototypeOf, Object2), objectCreate = Object2.create, propertyIsEnumerable = objectProto.propertyIsEnumerable, splice = arrayProto.splice, spreadableSymbol = Symbol2 ? Symbol2.isConcatSpreadable : undefined2, symIterator = Symbol2 ? Symbol2.iterator : undefined2, symToStringTag = Symbol2 ? Symbol2.toStringTag : undefined2; var defineProperty = function() { @@ -768,11 +1352,11 @@ var require_lodash = __commonJS({ var dataViewCtorString = toSource(DataView), mapCtorString = toSource(Map2), promiseCtorString = toSource(Promise2), setCtorString = toSource(Set2), weakMapCtorString = toSource(WeakMap2); var symbolProto = Symbol2 ? Symbol2.prototype : undefined2, symbolValueOf = symbolProto ? symbolProto.valueOf : undefined2, symbolToString = symbolProto ? symbolProto.toString : undefined2; function lodash(value) { - if (isObjectLike(value) && !isArray(value) && !(value instanceof LazyWrapper)) { + if (isObjectLike(value) && !isArray2(value) && !(value instanceof LazyWrapper)) { if (value instanceof LodashWrapper) { return value; } - if (hasOwnProperty.call(value, "__wrapped__")) { + if (hasOwnProperty2.call(value, "__wrapped__")) { return wrapperClone(value); } } @@ -782,7 +1366,7 @@ var require_lodash = __commonJS({ function object() { } return function(proto) { - if (!isObject(proto)) { + if (!isObject2(proto)) { return {}; } if (objectCreate) { @@ -847,7 +1431,7 @@ var require_lodash = __commonJS({ return result2; } function lazyValue() { - var array = this.__wrapped__.value(), dir = this.__dir__, isArr = isArray(array), isRight = dir < 0, arrLength = isArr ? array.length : 0, view = getView(0, arrLength, this.__views__), start = view.start, end = view.end, length = end - start, index = isRight ? end : start - 1, iteratees = this.__iteratees__, iterLength = iteratees.length, resIndex = 0, takeCount = nativeMin(length, this.__takeCount__); + var array = this.__wrapped__.value(), dir = this.__dir__, isArr = isArray2(array), isRight = dir < 0, arrLength = isArr ? array.length : 0, view = getView(0, arrLength, this.__views__), start = view.start, end = view.end, length = end - start, index = isRight ? end : start - 1, iteratees = this.__iteratees__, iterLength = iteratees.length, resIndex = 0, takeCount = nativeMin(length, this.__takeCount__); if (!isArr || !isRight && arrLength == length && takeCount == length) { return baseWrapperValue(array, this.__actions__); } @@ -857,7 +1441,7 @@ var require_lodash = __commonJS({ index += dir; var iterIndex = -1, value = array[index]; while (++iterIndex < iterLength) { - var data = iteratees[iterIndex], iteratee2 = data.iteratee, type = data.type, computed = iteratee2(value); + var data2 = iteratees[iterIndex], iteratee2 = data2.iteratee, type = data2.type, computed = iteratee2(value); if (type == LAZY_MAP_FLAG) { value = computed; } else if (!computed) { @@ -892,21 +1476,21 @@ var require_lodash = __commonJS({ return result2; } function hashGet(key2) { - var data = this.__data__; + var data2 = this.__data__; if (nativeCreate) { - var result2 = data[key2]; + var result2 = data2[key2]; return result2 === HASH_UNDEFINED ? undefined2 : result2; } - return hasOwnProperty.call(data, key2) ? data[key2] : undefined2; + return hasOwnProperty2.call(data2, key2) ? data2[key2] : undefined2; } function hashHas(key2) { - var data = this.__data__; - return nativeCreate ? data[key2] !== undefined2 : hasOwnProperty.call(data, key2); + var data2 = this.__data__; + return nativeCreate ? data2[key2] !== undefined2 : hasOwnProperty2.call(data2, key2); } function hashSet(key2, value) { - var data = this.__data__; + var data2 = this.__data__; this.size += this.has(key2) ? 0 : 1; - data[key2] = nativeCreate && value === undefined2 ? HASH_UNDEFINED : value; + data2[key2] = nativeCreate && value === undefined2 ? HASH_UNDEFINED : value; return this; } Hash.prototype.clear = hashClear; @@ -927,33 +1511,33 @@ var require_lodash = __commonJS({ this.size = 0; } function listCacheDelete(key2) { - var data = this.__data__, index = assocIndexOf(data, key2); + var data2 = this.__data__, index = assocIndexOf(data2, key2); if (index < 0) { return false; } - var lastIndex = data.length - 1; + var lastIndex = data2.length - 1; if (index == lastIndex) { - data.pop(); + data2.pop(); } else { - splice.call(data, index, 1); + splice.call(data2, index, 1); } --this.size; return true; } function listCacheGet(key2) { - var data = this.__data__, index = assocIndexOf(data, key2); - return index < 0 ? undefined2 : data[index][1]; + var data2 = this.__data__, index = assocIndexOf(data2, key2); + return index < 0 ? undefined2 : data2[index][1]; } function listCacheHas(key2) { return assocIndexOf(this.__data__, key2) > -1; } function listCacheSet(key2, value) { - var data = this.__data__, index = assocIndexOf(data, key2); + var data2 = this.__data__, index = assocIndexOf(data2, key2); if (index < 0) { ++this.size; - data.push([key2, value]); + data2.push([key2, value]); } else { - data[index][1] = value; + data2[index][1] = value; } return this; } @@ -962,7 +1546,7 @@ var require_lodash = __commonJS({ ListCache.prototype.get = listCacheGet; ListCache.prototype.has = listCacheHas; ListCache.prototype.set = listCacheSet; - function MapCache2(entries) { + function MapCache(entries) { var index = -1, length = entries == null ? 0 : entries.length; this.clear(); while (++index < length) { @@ -990,19 +1574,19 @@ var require_lodash = __commonJS({ return getMapData(this, key2).has(key2); } function mapCacheSet(key2, value) { - var data = getMapData(this, key2), size2 = data.size; - data.set(key2, value); - this.size += data.size == size2 ? 0 : 1; + var data2 = getMapData(this, key2), size2 = data2.size; + data2.set(key2, value); + this.size += data2.size == size2 ? 0 : 1; return this; } - MapCache2.prototype.clear = mapCacheClear; - MapCache2.prototype["delete"] = mapCacheDelete; - MapCache2.prototype.get = mapCacheGet; - MapCache2.prototype.has = mapCacheHas; - MapCache2.prototype.set = mapCacheSet; + MapCache.prototype.clear = mapCacheClear; + MapCache.prototype["delete"] = mapCacheDelete; + MapCache.prototype.get = mapCacheGet; + MapCache.prototype.has = mapCacheHas; + MapCache.prototype.set = mapCacheSet; function SetCache(values2) { var index = -1, length = values2 == null ? 0 : values2.length; - this.__data__ = new MapCache2(); + this.__data__ = new MapCache(); while (++index < length) { this.add(values2[index]); } @@ -1017,16 +1601,16 @@ var require_lodash = __commonJS({ SetCache.prototype.add = SetCache.prototype.push = setCacheAdd; SetCache.prototype.has = setCacheHas; function Stack(entries) { - var data = this.__data__ = new ListCache(entries); - this.size = data.size; + var data2 = this.__data__ = new ListCache(entries); + this.size = data2.size; } function stackClear() { this.__data__ = new ListCache(); this.size = 0; } function stackDelete(key2) { - var data = this.__data__, result2 = data["delete"](key2); - this.size = data.size; + var data2 = this.__data__, result2 = data2["delete"](key2); + this.size = data2.size; return result2; } function stackGet(key2) { @@ -1036,18 +1620,18 @@ var require_lodash = __commonJS({ return this.__data__.has(key2); } function stackSet(key2, value) { - var data = this.__data__; - if (data instanceof ListCache) { - var pairs = data.__data__; + var data2 = this.__data__; + if (data2 instanceof ListCache) { + var pairs = data2.__data__; if (!Map2 || pairs.length < LARGE_ARRAY_SIZE - 1) { pairs.push([key2, value]); - this.size = ++data.size; + this.size = ++data2.size; return this; } - data = this.__data__ = new MapCache2(pairs); + data2 = this.__data__ = new MapCache(pairs); } - data.set(key2, value); - this.size = data.size; + data2.set(key2, value); + this.size = data2.size; return this; } Stack.prototype.clear = stackClear; @@ -1056,9 +1640,9 @@ var require_lodash = __commonJS({ 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, result2 = skipIndexes ? baseTimes(value.length, String2) : [], length = result2.length; + var isArr = isArray2(value), isArg = !isArr && isArguments(value), isBuff = !isArr && !isArg && isBuffer(value), isType = !isArr && !isArg && !isBuff && isTypedArray(value), skipIndexes = isArr || isArg || isBuff || isType, result2 = skipIndexes ? baseTimes(value.length, String2) : [], length = result2.length; for (var key2 in value) { - if ((inherited || hasOwnProperty.call(value, key2)) && !(skipIndexes && (key2 == "length" || isBuff && (key2 == "offset" || key2 == "parent") || isType && (key2 == "buffer" || key2 == "byteLength" || key2 == "byteOffset") || isIndex(key2, length)))) { + if ((inherited || hasOwnProperty2.call(value, key2)) && !(skipIndexes && (key2 == "length" || isBuff && (key2 == "offset" || key2 == "parent") || isType && (key2 == "buffer" || key2 == "byteLength" || key2 == "byteOffset") || isIndex(key2, length)))) { result2.push(key2); } } @@ -1081,7 +1665,7 @@ var require_lodash = __commonJS({ } function assignValue(object, key2, value) { var objValue = object[key2]; - if (!(hasOwnProperty.call(object, key2) && eq(objValue, value)) || value === undefined2 && !(key2 in object)) { + if (!(hasOwnProperty2.call(object, key2) && eq(objValue, value)) || value === undefined2 && !(key2 in object)) { baseAssignValue(object, key2, value); } } @@ -1144,10 +1728,10 @@ var require_lodash = __commonJS({ if (result2 !== undefined2) { return result2; } - if (!isObject(value)) { + if (!isObject2(value)) { return value; } - var isArr = isArray(value); + var isArr = isArray2(value); if (isArr) { result2 = initCloneArray(value); if (!isDeep) { @@ -1271,9 +1855,9 @@ var require_lodash = __commonJS({ function baseExtremum(array, iteratee2, comparator) { var index = -1, length = array.length; while (++index < length) { - var value = array[index], current = iteratee2(value); - if (current != null && (computed === undefined2 ? current === current && !isSymbol(current) : comparator(current, computed))) { - var computed = current, result2 = value; + var value = array[index], current2 = iteratee2(value); + if (current2 != null && (computed === undefined2 ? current2 === current2 && !isSymbol(current2) : comparator(current2, computed))) { + var computed = current2, result2 = value; } } return result2; @@ -1344,7 +1928,7 @@ var require_lodash = __commonJS({ } function baseGetAllKeys(object, keysFunc, symbolsFunc) { var result2 = keysFunc(object); - return isArray(object) ? result2 : arrayPush(result2, symbolsFunc(object)); + return isArray2(object) ? result2 : arrayPush(result2, symbolsFunc(object)); } function baseGetTag(value) { if (value == null) { @@ -1356,7 +1940,7 @@ var require_lodash = __commonJS({ return value > other; } function baseHas(object, key2) { - return object != null && hasOwnProperty.call(object, key2); + return object != null && hasOwnProperty2.call(object, key2); } function baseHasIn(object, key2) { return object != null && key2 in Object2(object); @@ -1427,7 +2011,7 @@ var require_lodash = __commonJS({ return baseIsEqualDeep(value, other, bitmask, customizer, baseIsEqual, stack); } function baseIsEqualDeep(object, other, bitmask, customizer, equalFunc, stack) { - var objIsArr = isArray(object), othIsArr = isArray(other), objTag = objIsArr ? arrayTag : getTag(object), othTag = othIsArr ? arrayTag : getTag(other); + var objIsArr = isArray2(object), othIsArr = isArray2(other), objTag = objIsArr ? arrayTag : getTag(object), othTag = othIsArr ? arrayTag : getTag(other); objTag = objTag == argsTag ? objectTag : objTag; othTag = othTag == argsTag ? objectTag : othTag; var objIsObj = objTag == objectTag, othIsObj = othTag == objectTag, isSameTag = objTag == othTag; @@ -1443,7 +2027,7 @@ var require_lodash = __commonJS({ return objIsArr || isTypedArray(object) ? equalArrays(object, other, bitmask, customizer, equalFunc, stack) : equalByTag(object, other, objTag, bitmask, customizer, equalFunc, stack); } if (!(bitmask & COMPARE_PARTIAL_FLAG)) { - var objIsWrapped = objIsObj && hasOwnProperty.call(object, "__wrapped__"), othIsWrapped = othIsObj && hasOwnProperty.call(other, "__wrapped__"); + var objIsWrapped = objIsObj && hasOwnProperty2.call(object, "__wrapped__"), othIsWrapped = othIsObj && hasOwnProperty2.call(other, "__wrapped__"); if (objIsWrapped || othIsWrapped) { var objUnwrapped = objIsWrapped ? object.value() : object, othUnwrapped = othIsWrapped ? other.value() : other; stack || (stack = new Stack()); @@ -1466,15 +2050,15 @@ var require_lodash = __commonJS({ } object = Object2(object); while (index--) { - var data = matchData[index]; - if (noCustomizer && data[2] ? data[1] !== object[data[0]] : !(data[0] in object)) { + var data2 = matchData[index]; + if (noCustomizer && data2[2] ? data2[1] !== object[data2[0]] : !(data2[0] in object)) { return false; } } while (++index < length) { - data = matchData[index]; - var key2 = data[0], objValue = object[key2], srcValue = data[1]; - if (noCustomizer && data[2]) { + data2 = matchData[index]; + var key2 = data2[0], objValue = object[key2], srcValue = data2[1]; + if (noCustomizer && data2[2]) { if (objValue === undefined2 && !(key2 in object)) { return false; } @@ -1491,7 +2075,7 @@ var require_lodash = __commonJS({ return true; } function baseIsNative(value) { - if (!isObject(value) || isMasked(value)) { + if (!isObject2(value) || isMasked(value)) { return false; } var pattern = isFunction2(value) ? reIsNative : reIsHostCtor; @@ -1514,7 +2098,7 @@ var require_lodash = __commonJS({ return identity; } if (typeof value == "object") { - return isArray(value) ? baseMatchesProperty(value[0], value[1]) : baseMatches(value); + return isArray2(value) ? baseMatchesProperty(value[0], value[1]) : baseMatches(value); } return property(value); } @@ -1524,19 +2108,19 @@ var require_lodash = __commonJS({ } var result2 = []; for (var key2 in Object2(object)) { - if (hasOwnProperty.call(object, key2) && key2 != "constructor") { + if (hasOwnProperty2.call(object, key2) && key2 != "constructor") { result2.push(key2); } } return result2; } function baseKeysIn(object) { - if (!isObject(object)) { + if (!isObject2(object)) { return nativeKeysIn(object); } var isProto = isPrototype(object), result2 = []; for (var key2 in object) { - if (!(key2 == "constructor" && (isProto || !hasOwnProperty.call(object, key2)))) { + if (!(key2 == "constructor" && (isProto || !hasOwnProperty2.call(object, key2)))) { result2.push(key2); } } @@ -1576,7 +2160,7 @@ var require_lodash = __commonJS({ } baseFor(source, function(srcValue, key2) { stack || (stack = new Stack()); - if (isObject(srcValue)) { + if (isObject2(srcValue)) { baseMergeDeep(object, source, key2, srcIndex, baseMerge, customizer, stack); } else { var newValue = customizer ? customizer(safeGet(object, key2), srcValue, key2 + "", object, source, stack) : undefined2; @@ -1596,10 +2180,10 @@ var require_lodash = __commonJS({ var newValue = customizer ? customizer(objValue, srcValue, key2 + "", object, source, stack) : undefined2; var isCommon = newValue === undefined2; if (isCommon) { - var isArr = isArray(srcValue), isBuff = !isArr && isBuffer(srcValue), isTyped = !isArr && !isBuff && isTypedArray(srcValue); + var isArr = isArray2(srcValue), isBuff = !isArr && isBuffer(srcValue), isTyped = !isArr && !isBuff && isTypedArray(srcValue); newValue = srcValue; if (isArr || isBuff || isTyped) { - if (isArray(objValue)) { + if (isArray2(objValue)) { newValue = objValue; } else if (isArrayLikeObject(objValue)) { newValue = copyArray(objValue); @@ -1616,7 +2200,7 @@ var require_lodash = __commonJS({ newValue = objValue; if (isArguments(objValue)) { newValue = toPlainObject(objValue); - } else if (!isObject(objValue) || isFunction2(objValue)) { + } else if (!isObject2(objValue) || isFunction2(objValue)) { newValue = initCloneObject(srcValue); } } else { @@ -1641,7 +2225,7 @@ var require_lodash = __commonJS({ function baseOrderBy(collection, iteratees, orders) { if (iteratees.length) { iteratees = arrayMap(iteratees, function(iteratee2) { - if (isArray(iteratee2)) { + if (isArray2(iteratee2)) { return function(value) { return baseGet(value, iteratee2.length === 1 ? iteratee2[0] : iteratee2); }; @@ -1755,7 +2339,7 @@ var require_lodash = __commonJS({ return shuffleSelf(array, baseClamp(n2, 0, array.length)); } function baseSet(object, path, value, customizer) { - if (!isObject(object)) { + if (!isObject2(object)) { return object; } path = castPath(path, object); @@ -1769,7 +2353,7 @@ var require_lodash = __commonJS({ var objValue = nested[key2]; newValue = customizer ? customizer(objValue, key2, nested) : undefined2; if (newValue === undefined2) { - newValue = isObject(objValue) ? objValue : isIndex(path[index + 1]) ? [] : {}; + newValue = isObject2(objValue) ? objValue : isIndex(path[index + 1]) ? [] : {}; } } assignValue(nested, key2, newValue); @@ -1777,8 +2361,8 @@ var require_lodash = __commonJS({ } return object; } - var baseSetData = !metaMap ? identity : function(func, data) { - metaMap.set(func, data); + var baseSetData = !metaMap ? identity : function(func, data2) { + metaMap.set(func, data2); return func; }; var baseSetToString = !defineProperty ? identity : function(func, string) { @@ -1886,7 +2470,7 @@ var require_lodash = __commonJS({ if (typeof value == "string") { return value; } - if (isArray(value)) { + if (isArray2(value)) { return arrayMap(value, baseToString) + ""; } if (isSymbol(value)) { @@ -1989,10 +2573,10 @@ var require_lodash = __commonJS({ return typeof value == "function" ? value : identity; } function castPath(value, object) { - if (isArray(value)) { + if (isArray2(value)) { return value; } - return isKey(value, object) ? [value] : stringToPath(toString2(value)); + return isKey(value, object) ? [value] : stringToPath(toString3(value)); } var castRest = baseRest; function castSlice(array, start, end) { @@ -2079,13 +2663,13 @@ var require_lodash = __commonJS({ while (++argsIndex < rangeLength) { result2[argsIndex] = args[argsIndex]; } - var offset = argsIndex; + var offset2 = argsIndex; while (++rightIndex < rightLength) { - result2[offset + rightIndex] = partials[rightIndex]; + result2[offset2 + rightIndex] = partials[rightIndex]; } while (++holdersIndex < holdersLength) { if (isUncurried || argsIndex < argsLength) { - result2[offset + holders[holdersIndex]] = args[argsIndex++]; + result2[offset2 + holders[holdersIndex]] = args[argsIndex++]; } } return result2; @@ -2124,7 +2708,7 @@ var require_lodash = __commonJS({ } function createAggregator(setter, initializer) { return function(collection, iteratee2) { - var func = isArray(collection) ? arrayAggregator : baseAggregator, accumulator = initializer ? initializer() : {}; + var func = isArray2(collection) ? arrayAggregator : baseAggregator, accumulator = initializer ? initializer() : {}; return func(collection, setter, getIteratee(iteratee2, 2), accumulator); }; } @@ -2185,7 +2769,7 @@ var require_lodash = __commonJS({ } function createCaseFirst(methodName) { return function(string) { - string = toString2(string); + string = toString3(string); var strSymbols = hasUnicode(string) ? stringToArray(string) : undefined2; var chr = strSymbols ? strSymbols[0] : string.charAt(0); var trailing = strSymbols ? castSlice(strSymbols, 1).join("") : string.slice(1); @@ -2219,7 +2803,7 @@ var require_lodash = __commonJS({ return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5], args[6]); } var thisBinding = baseCreate(Ctor.prototype), result2 = Ctor.apply(thisBinding, args); - return isObject(result2) ? result2 : thisBinding; + return isObject2(result2) ? result2 : thisBinding; }; } function createCurry(func, bitmask, arity) { @@ -2282,16 +2866,16 @@ var require_lodash = __commonJS({ index = wrapper ? index : length; while (++index < length) { func = funcs[index]; - var funcName = getFuncName(func), data = funcName == "wrapper" ? getData(func) : undefined2; - if (data && isLaziable(data[0]) && data[1] == (WRAP_ARY_FLAG | WRAP_CURRY_FLAG | WRAP_PARTIAL_FLAG | WRAP_REARG_FLAG) && !data[4].length && data[9] == 1) { - wrapper = wrapper[getFuncName(data[0])].apply(wrapper, data[3]); + var funcName = getFuncName(func), data2 = funcName == "wrapper" ? getData(func) : undefined2; + if (data2 && isLaziable(data2[0]) && data2[1] == (WRAP_ARY_FLAG | WRAP_CURRY_FLAG | WRAP_PARTIAL_FLAG | WRAP_REARG_FLAG) && !data2[4].length && data2[9] == 1) { + wrapper = wrapper[getFuncName(data2[0])].apply(wrapper, data2[3]); } else { wrapper = func.length == 1 && isLaziable(func) ? wrapper[funcName]() : wrapper.thru(func); } } return function() { var args = arguments, value = args[0]; - if (wrapper && args.length == 1 && isArray(value)) { + if (wrapper && args.length == 1 && isArray2(value)) { return wrapper.plant(value).value(); } var index2 = 0, result2 = length ? funcs[index2].apply(this, args) : value; @@ -2472,14 +3056,14 @@ var require_lodash = __commonJS({ number = toNumber(number); precision = precision == null ? 0 : nativeMin(toInteger2(precision), 292); if (precision && nativeIsFinite(number)) { - var pair = (toString2(number) + "e").split("e"), value = func(pair[0] + "e" + (+pair[1] + precision)); - pair = (toString2(value) + "e").split("e"); + var pair = (toString3(number) + "e").split("e"), value = func(pair[0] + "e" + (+pair[1] + precision)); + pair = (toString3(value) + "e").split("e"); return +(pair[0] + "e" + (+pair[1] - precision)); } return func(number); }; } - var createSet = !(Set2 && 1 / setToArray(new Set2([, -0]))[1] == INFINITY) ? noop2 : function(values2) { + var createSet = !(Set2 && 1 / setToArray(new Set2([, -0]))[1] == INFINITY) ? noop3 : function(values2) { return new Set2(values2); }; function createToPairs(keysFunc) { @@ -2511,7 +3095,7 @@ var require_lodash = __commonJS({ var partialsRight = partials, holdersRight = holders; partials = holders = undefined2; } - var data = isBindKey ? undefined2 : getData(func); + var data2 = isBindKey ? undefined2 : getData(func); var newData = [ func, bitmask, @@ -2524,8 +3108,8 @@ var require_lodash = __commonJS({ ary2, arity ]; - if (data) { - mergeData(newData, data); + if (data2) { + mergeData(newData, data2); } func = newData[0]; bitmask = newData[1]; @@ -2545,17 +3129,17 @@ var require_lodash = __commonJS({ } else { result2 = createHybrid.apply(undefined2, newData); } - var setter = data ? baseSetData : setData; + var setter = data2 ? baseSetData : setData; return setWrapToString(setter(result2, newData), func, bitmask); } function customDefaultsAssignIn(objValue, srcValue, key2, object) { - if (objValue === undefined2 || eq(objValue, objectProto[key2]) && !hasOwnProperty.call(object, key2)) { + if (objValue === undefined2 || eq(objValue, objectProto[key2]) && !hasOwnProperty2.call(object, key2)) { return srcValue; } return objValue; } function customDefaultsMerge(objValue, srcValue, key2, object, source, stack) { - if (isObject(objValue) && isObject(srcValue)) { + if (isObject2(objValue) && isObject2(srcValue)) { stack.set(srcValue, objValue); baseMerge(objValue, srcValue, undefined2, customDefaultsMerge, stack); stack["delete"](srcValue); @@ -2662,7 +3246,7 @@ var require_lodash = __commonJS({ var index = objLength; while (index--) { var key2 = objProps[index]; - if (!(isPartial ? key2 in other : hasOwnProperty.call(other, key2))) { + if (!(isPartial ? key2 in other : hasOwnProperty2.call(other, key2))) { return false; } } @@ -2698,7 +3282,7 @@ var require_lodash = __commonJS({ return result2; } function flatRest(func) { - return setToString(overRest(func, undefined2, flatten), func + ""); + return setToString(overRest(func, undefined2, flatten2), func + ""); } function getAllKeys(object) { return baseGetAllKeys(object, keys, getSymbols); @@ -2706,21 +3290,21 @@ var require_lodash = __commonJS({ function getAllKeysIn(object) { return baseGetAllKeys(object, keysIn, getSymbolsIn); } - var getData = !metaMap ? noop2 : function(func) { + var getData = !metaMap ? noop3 : function(func) { return metaMap.get(func); }; function getFuncName(func) { - var result2 = func.name + "", array = realNames[result2], length = hasOwnProperty.call(realNames, result2) ? array.length : 0; + var result2 = func.name + "", array = realNames[result2], length = hasOwnProperty2.call(realNames, result2) ? array.length : 0; while (length--) { - var data = array[length], otherFunc = data.func; + var data2 = array[length], otherFunc = data2.func; if (otherFunc == null || otherFunc == func) { - return data.name; + return data2.name; } } return result2; } function getHolder(func) { - var object = hasOwnProperty.call(lodash, "placeholder") ? lodash : func; + var object = hasOwnProperty2.call(lodash, "placeholder") ? lodash : func; return object.placeholder; } function getIteratee() { @@ -2729,8 +3313,8 @@ var require_lodash = __commonJS({ return arguments.length ? result2(arguments[0], arguments[1]) : result2; } function getMapData(map2, key2) { - var data = map2.__data__; - return isKeyable(key2) ? data[typeof key2 == "string" ? "string" : "hash"] : data.map; + var data2 = map2.__data__; + return isKeyable(key2) ? data2[typeof key2 == "string" ? "string" : "hash"] : data2.map; } function getMatchData(object) { var result2 = keys(object), length = result2.length; @@ -2745,7 +3329,7 @@ var require_lodash = __commonJS({ return baseIsNative(value) ? value : undefined2; } function getRawTag(value) { - var isOwn = hasOwnProperty.call(value, symToStringTag), tag = value[symToStringTag]; + var isOwn = hasOwnProperty2.call(value, symToStringTag), tag = value[symToStringTag]; try { value[symToStringTag] = undefined2; var unmasked = true; @@ -2802,8 +3386,8 @@ var require_lodash = __commonJS({ function getView(start, end, transforms) { var index = -1, length = transforms.length; while (++index < length) { - var data = transforms[index], size2 = data.size; - switch (data.type) { + var data2 = transforms[index], size2 = data2.size; + switch (data2.type) { case "drop": start += size2; break; @@ -2838,11 +3422,11 @@ var require_lodash = __commonJS({ return result2; } length = object == null ? 0 : object.length; - return !!length && isLength(length) && isIndex(key2, length) && (isArray(object) || isArguments(object)); + return !!length && isLength(length) && isIndex(key2, length) && (isArray2(object) || isArguments(object)); } function initCloneArray(array) { var length = array.length, result2 = new array.constructor(length); - if (length && typeof array[0] == "string" && hasOwnProperty.call(array, "index")) { + if (length && typeof array[0] == "string" && hasOwnProperty2.call(array, "index")) { result2.index = array.index; result2.input = array.input; } @@ -2895,7 +3479,7 @@ var require_lodash = __commonJS({ return source.replace(reWrapComment, "{\n/* [wrapped with " + details + "] */\n"); } function isFlattenable(value) { - return isArray(value) || isArguments(value) || !!(spreadableSymbol && value && value[spreadableSymbol]); + return isArray2(value) || isArguments(value) || !!(spreadableSymbol && value && value[spreadableSymbol]); } function isIndex(value, length) { var type = typeof value; @@ -2903,7 +3487,7 @@ var require_lodash = __commonJS({ return !!length && (type == "number" || type != "symbol" && reIsUint.test(value)) && (value > -1 && value % 1 == 0 && value < length); } function isIterateeCall(value, index, object) { - if (!isObject(object)) { + if (!isObject2(object)) { return false; } var type = typeof index; @@ -2913,7 +3497,7 @@ var require_lodash = __commonJS({ return false; } function isKey(value, object) { - if (isArray(value)) { + if (isArray2(value)) { return false; } var type = typeof value; @@ -2934,8 +3518,8 @@ var require_lodash = __commonJS({ if (func === other) { return true; } - var data = getData(other); - return !!data && func === data[0]; + var data2 = getData(other); + return !!data2 && func === data2[0]; } function isMasked(func) { return !!maskSrcKey && maskSrcKey in func; @@ -2946,7 +3530,7 @@ var require_lodash = __commonJS({ return value === proto; } function isStrictComparable(value) { - return value === value && !isObject(value); + return value === value && !isObject2(value); } function matchesStrictComparable(key2, srcValue) { return function(object) { @@ -2966,41 +3550,41 @@ var require_lodash = __commonJS({ var cache = result2.cache; return result2; } - function mergeData(data, source) { - var bitmask = data[1], srcBitmask = source[1], newBitmask = bitmask | srcBitmask, isCommon = newBitmask < (WRAP_BIND_FLAG | WRAP_BIND_KEY_FLAG | WRAP_ARY_FLAG); - var isCombo = srcBitmask == WRAP_ARY_FLAG && bitmask == WRAP_CURRY_FLAG || srcBitmask == WRAP_ARY_FLAG && bitmask == WRAP_REARG_FLAG && data[7].length <= source[8] || srcBitmask == (WRAP_ARY_FLAG | WRAP_REARG_FLAG) && source[7].length <= source[8] && bitmask == WRAP_CURRY_FLAG; + function mergeData(data2, source) { + var bitmask = data2[1], srcBitmask = source[1], newBitmask = bitmask | srcBitmask, isCommon = newBitmask < (WRAP_BIND_FLAG | WRAP_BIND_KEY_FLAG | WRAP_ARY_FLAG); + var isCombo = srcBitmask == WRAP_ARY_FLAG && bitmask == WRAP_CURRY_FLAG || srcBitmask == WRAP_ARY_FLAG && bitmask == WRAP_REARG_FLAG && data2[7].length <= source[8] || srcBitmask == (WRAP_ARY_FLAG | WRAP_REARG_FLAG) && source[7].length <= source[8] && bitmask == WRAP_CURRY_FLAG; if (!(isCommon || isCombo)) { - return data; + return data2; } if (srcBitmask & WRAP_BIND_FLAG) { - data[2] = source[2]; + data2[2] = source[2]; newBitmask |= bitmask & WRAP_BIND_FLAG ? 0 : WRAP_CURRY_BOUND_FLAG; } var value = source[3]; if (value) { - var partials = data[3]; - data[3] = partials ? composeArgs(partials, value, source[4]) : value; - data[4] = partials ? replaceHolders(data[3], PLACEHOLDER) : source[4]; + var partials = data2[3]; + data2[3] = partials ? composeArgs(partials, value, source[4]) : value; + data2[4] = partials ? replaceHolders(data2[3], PLACEHOLDER) : source[4]; } value = source[5]; if (value) { - partials = data[5]; - data[5] = partials ? composeArgsRight(partials, value, source[6]) : value; - data[6] = partials ? replaceHolders(data[5], PLACEHOLDER) : source[6]; + partials = data2[5]; + data2[5] = partials ? composeArgsRight(partials, value, source[6]) : value; + data2[6] = partials ? replaceHolders(data2[5], PLACEHOLDER) : source[6]; } value = source[7]; if (value) { - data[7] = value; + data2[7] = value; } if (srcBitmask & WRAP_ARY_FLAG) { - data[8] = data[8] == null ? source[8] : nativeMin(data[8], source[8]); + data2[8] = data2[8] == null ? source[8] : nativeMin(data2[8], source[8]); } - if (data[9] == null) { - data[9] = source[9]; + if (data2[9] == null) { + data2[9] = source[9]; } - data[0] = source[0]; - data[1] = newBitmask; - return data; + data2[0] = source[0]; + data2[1] = newBitmask; + return data2; } function nativeKeysIn(object) { var result2 = []; @@ -3169,7 +3753,7 @@ var require_lodash = __commonJS({ while (index--) { args[index - 1] = arguments[index]; } - return arrayPush(isArray(array) ? copyArray(array) : [array], baseFlatten(args, 1)); + return arrayPush(isArray2(array) ? copyArray(array) : [array], baseFlatten(args, 1)); } var difference = baseRest(function(array, values2) { return isArrayLikeObject(array) ? baseDifference(array, baseFlatten(values2, 1, isArrayLikeObject, true)) : []; @@ -3245,7 +3829,7 @@ var require_lodash = __commonJS({ } return baseFindIndex(array, getIteratee(predicate, 3), index, true); } - function flatten(array) { + function flatten2(array) { var length = array == null ? 0 : array.length; return length ? baseFlatten(array, 1) : []; } @@ -3460,7 +4044,7 @@ var require_lodash = __commonJS({ comparator = typeof comparator == "function" ? comparator : undefined2; return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true), undefined2, comparator); }); - function uniq4(array) { + function uniq3(array) { return array && array.length ? baseUniq(array) : []; } function uniqBy(array, iteratee2) { @@ -3613,21 +4197,21 @@ var require_lodash = __commonJS({ return baseWrapperValue(this.__wrapped__, this.__actions__); } var countBy = createAggregator(function(result2, value, key2) { - if (hasOwnProperty.call(result2, key2)) { + if (hasOwnProperty2.call(result2, key2)) { ++result2[key2]; } else { baseAssignValue(result2, key2, 1); } }); function every(collection, predicate, guard) { - var func = isArray(collection) ? arrayEvery : baseEvery; + var func = isArray2(collection) ? arrayEvery : baseEvery; if (guard && isIterateeCall(collection, predicate, guard)) { predicate = undefined2; } return func(collection, getIteratee(predicate, 3)); } function filter(collection, predicate) { - var func = isArray(collection) ? arrayFilter : baseFilter; + var func = isArray2(collection) ? arrayFilter : baseFilter; return func(collection, getIteratee(predicate, 3)); } var find = createFind(findIndex2); @@ -3643,15 +4227,15 @@ var require_lodash = __commonJS({ return baseFlatten(map(collection, iteratee2), depth); } function forEach(collection, iteratee2) { - var func = isArray(collection) ? arrayEach : baseEach; + var func = isArray2(collection) ? arrayEach : baseEach; return func(collection, getIteratee(iteratee2, 3)); } function forEachRight(collection, iteratee2) { - var func = isArray(collection) ? arrayEachRight : baseEachRight; + var func = isArray2(collection) ? arrayEachRight : baseEachRight; return func(collection, getIteratee(iteratee2, 3)); } var groupBy2 = createAggregator(function(result2, value, key2) { - if (hasOwnProperty.call(result2, key2)) { + if (hasOwnProperty2.call(result2, key2)) { result2[key2].push(value); } else { baseAssignValue(result2, key2, [value]); @@ -3677,18 +4261,18 @@ var require_lodash = __commonJS({ baseAssignValue(result2, key2, value); }); function map(collection, iteratee2) { - var func = isArray(collection) ? arrayMap : baseMap; + var func = isArray2(collection) ? arrayMap : baseMap; return func(collection, getIteratee(iteratee2, 3)); } function orderBy(collection, iteratees, orders, guard) { if (collection == null) { return []; } - if (!isArray(iteratees)) { + if (!isArray2(iteratees)) { iteratees = iteratees == null ? [] : [iteratees]; } orders = guard ? undefined2 : orders; - if (!isArray(orders)) { + if (!isArray2(orders)) { orders = orders == null ? [] : [orders]; } return baseOrderBy(collection, iteratees, orders); @@ -3699,19 +4283,19 @@ var require_lodash = __commonJS({ return [[], []]; }); function reduce(collection, iteratee2, accumulator) { - var func = isArray(collection) ? arrayReduce : baseReduce, initAccum = arguments.length < 3; + var func = isArray2(collection) ? arrayReduce : baseReduce, initAccum = arguments.length < 3; return func(collection, getIteratee(iteratee2, 4), accumulator, initAccum, baseEach); } function reduceRight(collection, iteratee2, accumulator) { - var func = isArray(collection) ? arrayReduceRight : baseReduce, initAccum = arguments.length < 3; + var func = isArray2(collection) ? arrayReduceRight : baseReduce, initAccum = arguments.length < 3; return func(collection, getIteratee(iteratee2, 4), accumulator, initAccum, baseEachRight); } function reject(collection, predicate) { - var func = isArray(collection) ? arrayFilter : baseFilter; + var func = isArray2(collection) ? arrayFilter : baseFilter; return func(collection, negate(getIteratee(predicate, 3))); } function sample(collection) { - var func = isArray(collection) ? arraySample : baseSample; + var func = isArray2(collection) ? arraySample : baseSample; return func(collection); } function sampleSize(collection, n2, guard) { @@ -3720,11 +4304,11 @@ var require_lodash = __commonJS({ } else { n2 = toInteger2(n2); } - var func = isArray(collection) ? arraySampleSize : baseSampleSize; + var func = isArray2(collection) ? arraySampleSize : baseSampleSize; return func(collection, n2); } function shuffle(collection) { - var func = isArray(collection) ? arrayShuffle : baseShuffle; + var func = isArray2(collection) ? arrayShuffle : baseShuffle; return func(collection); } function size(collection) { @@ -3741,7 +4325,7 @@ var require_lodash = __commonJS({ return baseKeys(collection).length; } function some(collection, predicate, guard) { - var func = isArray(collection) ? arraySome : baseSome; + var func = isArray2(collection) ? arraySome : baseSome; if (guard && isIterateeCall(collection, predicate, guard)) { predicate = undefined2; } @@ -3828,7 +4412,7 @@ var require_lodash = __commonJS({ throw new TypeError2(FUNC_ERROR_TEXT); } wait = toNumber(wait) || 0; - if (isObject(options)) { + if (isObject2(options)) { leading = !!options.leading; maxing = "maxWait" in options; maxWait = maxing ? nativeMax(toNumber(options.maxWait) || 0, wait) : maxWait; @@ -3925,10 +4509,10 @@ var require_lodash = __commonJS({ memoized.cache = cache.set(key2, result2) || cache; return result2; }; - memoized.cache = new (memoize.Cache || MapCache2)(); + memoized.cache = new (memoize.Cache || MapCache)(); return memoized; } - memoize.Cache = MapCache2; + memoize.Cache = MapCache; function negate(predicate) { if (typeof predicate != "function") { throw new TypeError2(FUNC_ERROR_TEXT); @@ -3952,7 +4536,7 @@ var require_lodash = __commonJS({ return before(2, func); } var overArgs = castRest(function(func, transforms) { - transforms = transforms.length == 1 && isArray(transforms[0]) ? arrayMap(transforms[0], baseUnary(getIteratee())) : arrayMap(baseFlatten(transforms, 1), baseUnary(getIteratee())); + transforms = transforms.length == 1 && isArray2(transforms[0]) ? arrayMap(transforms[0], baseUnary(getIteratee())) : arrayMap(baseFlatten(transforms, 1), baseUnary(getIteratee())); var funcsLength = transforms.length; return baseRest(function(args) { var index = -1, length = nativeMin(args.length, funcsLength); @@ -3998,7 +4582,7 @@ var require_lodash = __commonJS({ if (typeof func != "function") { throw new TypeError2(FUNC_ERROR_TEXT); } - if (isObject(options)) { + if (isObject2(options)) { leading = "leading" in options ? !!options.leading : leading; trailing = "trailing" in options ? !!options.trailing : trailing; } @@ -4019,7 +4603,7 @@ var require_lodash = __commonJS({ return []; } var value = arguments[0]; - return isArray(value) ? value : [value]; + return isArray2(value) ? value : [value]; } function clone(value) { return baseClone(value, CLONE_SYMBOLS_FLAG); @@ -4048,9 +4632,9 @@ var require_lodash = __commonJS({ var isArguments = baseIsArguments(function() { return arguments; }()) ? baseIsArguments : function(value) { - return isObjectLike(value) && hasOwnProperty.call(value, "callee") && !propertyIsEnumerable.call(value, "callee"); + return isObjectLike(value) && hasOwnProperty2.call(value, "callee") && !propertyIsEnumerable.call(value, "callee"); }; - var isArray = Array2.isArray; + var isArray2 = Array2.isArray; var isArrayBuffer = nodeIsArrayBuffer ? baseUnary(nodeIsArrayBuffer) : baseIsArrayBuffer; function isArrayLike(value) { return value != null && isLength(value.length) && !isFunction2(value); @@ -4070,7 +4654,7 @@ var require_lodash = __commonJS({ if (value == null) { return true; } - if (isArrayLike(value) && (isArray(value) || typeof value == "string" || typeof value.splice == "function" || isBuffer(value) || isTypedArray(value) || isArguments(value))) { + if (isArrayLike(value) && (isArray2(value) || typeof value == "string" || typeof value.splice == "function" || isBuffer(value) || isTypedArray(value) || isArguments(value))) { return !value.length; } var tag = getTag(value); @@ -4081,7 +4665,7 @@ var require_lodash = __commonJS({ return !baseKeys(value).length; } for (var key2 in value) { - if (hasOwnProperty.call(value, key2)) { + if (hasOwnProperty2.call(value, key2)) { return false; } } @@ -4095,18 +4679,18 @@ var require_lodash = __commonJS({ var result2 = customizer ? customizer(value, other) : undefined2; return result2 === undefined2 ? baseIsEqual(value, other, undefined2, customizer) : !!result2; } - function isError2(value) { + function isError(value) { if (!isObjectLike(value)) { return false; } var tag = baseGetTag(value); return tag == errorTag || tag == domExcTag || typeof value.message == "string" && typeof value.name == "string" && !isPlainObject(value); } - function isFinite(value) { + function isFinite2(value) { return typeof value == "number" && nativeIsFinite(value); } function isFunction2(value) { - if (!isObject(value)) { + if (!isObject2(value)) { return false; } var tag = baseGetTag(value); @@ -4118,7 +4702,7 @@ var require_lodash = __commonJS({ function isLength(value) { return typeof value == "number" && value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER; } - function isObject(value) { + function isObject2(value) { var type = typeof value; return value != null && (type == "object" || type == "function"); } @@ -4159,7 +4743,7 @@ var require_lodash = __commonJS({ if (proto === null) { return true; } - var Ctor = hasOwnProperty.call(proto, "constructor") && proto.constructor; + var Ctor = hasOwnProperty2.call(proto, "constructor") && proto.constructor; return typeof Ctor == "function" && Ctor instanceof Ctor && funcToString.call(Ctor) == objectCtorString; } var isRegExp = nodeIsRegExp ? baseUnary(nodeIsRegExp) : baseIsRegExp; @@ -4168,7 +4752,7 @@ var require_lodash = __commonJS({ } var isSet = nodeIsSet ? baseUnary(nodeIsSet) : baseIsSet; function isString(value) { - return typeof value == "string" || !isArray(value) && isObjectLike(value) && baseGetTag(value) == stringTag; + return typeof value == "string" || !isArray2(value) && isObjectLike(value) && baseGetTag(value) == stringTag; } function isSymbol(value) { return typeof value == "symbol" || isObjectLike(value) && baseGetTag(value) == symbolTag; @@ -4225,9 +4809,9 @@ var require_lodash = __commonJS({ if (isSymbol(value)) { return NAN; } - if (isObject(value)) { + if (isObject2(value)) { var other = typeof value.valueOf == "function" ? value.valueOf() : value; - value = isObject(other) ? other + "" : other; + value = isObject2(other) ? other + "" : other; } if (typeof value != "string") { return value === 0 ? value : +value; @@ -4242,7 +4826,7 @@ var require_lodash = __commonJS({ function toSafeInteger(value) { return value ? baseClamp(toInteger2(value), -MAX_SAFE_INTEGER, MAX_SAFE_INTEGER) : value === 0 ? value : 0; } - function toString2(value) { + function toString3(value) { return value == null ? "" : baseToString(value); } var assign2 = createAssigner(function(object, source) { @@ -4251,7 +4835,7 @@ var require_lodash = __commonJS({ return; } for (var key2 in source) { - if (hasOwnProperty.call(source, key2)) { + if (hasOwnProperty2.call(source, key2)) { assignValue(object, key2, source[key2]); } } @@ -4265,7 +4849,7 @@ var require_lodash = __commonJS({ var assignWith = createAssigner(function(object, source, srcIndex, customizer) { copyObject(source, keys(source), object, customizer); }); - var at = flatRest(baseAt); + var at2 = flatRest(baseAt); function create(prototype, properties2) { var result2 = baseCreate(prototype); return properties2 == null ? result2 : baseAssign(result2, properties2); @@ -4286,7 +4870,7 @@ var require_lodash = __commonJS({ while (++propsIndex < propsLength) { var key2 = props2[propsIndex]; var value = object[key2]; - if (value === undefined2 || eq(value, objectProto[key2]) && !hasOwnProperty.call(object, key2)) { + if (value === undefined2 || eq(value, objectProto[key2]) && !hasOwnProperty2.call(object, key2)) { object[key2] = source[key2]; } } @@ -4341,7 +4925,7 @@ var require_lodash = __commonJS({ if (value != null && typeof value.toString != "function") { value = nativeObjectToString.call(value); } - if (hasOwnProperty.call(result2, value)) { + if (hasOwnProperty2.call(result2, value)) { result2[value].push(key2); } else { result2[value] = [key2]; @@ -4442,13 +5026,13 @@ var require_lodash = __commonJS({ var toPairs = createToPairs(keys); var toPairsIn = createToPairs(keysIn); function transform(object, iteratee2, accumulator) { - var isArr = isArray(object), isArrLike = isArr || isBuffer(object) || isTypedArray(object); + var isArr = isArray2(object), isArrLike = isArr || isBuffer(object) || isTypedArray(object); iteratee2 = getIteratee(iteratee2, 4); if (accumulator == null) { var Ctor = object && object.constructor; if (isArrLike) { accumulator = isArr ? new Ctor() : []; - } else if (isObject(object)) { + } else if (isObject2(object)) { accumulator = isFunction2(Ctor) ? baseCreate(getPrototype(object)) : {}; } else { accumulator = {}; @@ -4475,7 +5059,7 @@ var require_lodash = __commonJS({ function valuesIn(object) { return object == null ? [] : baseValues(object, keysIn(object)); } - function clamp(number, lower, upper) { + function clamp2(number, lower, upper) { if (upper === undefined2) { upper = lower; lower = undefined2; @@ -4542,14 +5126,14 @@ var require_lodash = __commonJS({ return result2 + (index ? capitalize(word) : word); }); function capitalize(string) { - return upperFirst(toString2(string).toLowerCase()); + return upperFirst(toString3(string).toLowerCase()); } function deburr(string) { - string = toString2(string); + string = toString3(string); return string && string.replace(reLatin, deburrLetter).replace(reComboMark, ""); } function endsWith(string, target, position) { - string = toString2(string); + string = toString3(string); target = baseToString(target); var length = string.length; position = position === undefined2 ? length : baseClamp(toInteger2(position), 0, length); @@ -4558,11 +5142,11 @@ var require_lodash = __commonJS({ return position >= 0 && string.slice(position, end) == target; } function escape(string) { - string = toString2(string); + string = toString3(string); return string && reHasUnescapedHtml.test(string) ? string.replace(reUnescapedHtml, escapeHtmlChar) : string; } function escapeRegExp(string) { - string = toString2(string); + string = toString3(string); return string && reHasRegExpChar.test(string) ? string.replace(reRegExpChar, "\\$&") : string; } var kebabCase = createCompounder(function(result2, word, index) { @@ -4573,7 +5157,7 @@ var require_lodash = __commonJS({ }); var lowerFirst = createCaseFirst("toLowerCase"); function pad(string, length, chars) { - string = toString2(string); + string = toString3(string); length = toInteger2(length); var strLength = length ? stringSize(string) : 0; if (!length || strLength >= length) { @@ -4583,13 +5167,13 @@ var require_lodash = __commonJS({ return createPadding(nativeFloor(mid), chars) + string + createPadding(nativeCeil(mid), chars); } function padEnd(string, length, chars) { - string = toString2(string); + string = toString3(string); length = toInteger2(length); var strLength = length ? stringSize(string) : 0; return length && strLength < length ? string + createPadding(length - strLength, chars) : string; } function padStart(string, length, chars) { - string = toString2(string); + string = toString3(string); length = toInteger2(length); var strLength = length ? stringSize(string) : 0; return length && strLength < length ? createPadding(length - strLength, chars) + string : string; @@ -4600,7 +5184,7 @@ var require_lodash = __commonJS({ } else if (radix) { radix = +radix; } - return nativeParseInt(toString2(string).replace(reTrimStart, ""), radix || 0); + return nativeParseInt(toString3(string).replace(reTrimStart, ""), radix || 0); } function repeat(string, n2, guard) { if (guard ? isIterateeCall(string, n2, guard) : n2 === undefined2) { @@ -4608,10 +5192,10 @@ var require_lodash = __commonJS({ } else { n2 = toInteger2(n2); } - return baseRepeat(toString2(string), n2); + return baseRepeat(toString3(string), n2); } function replace() { - var args = arguments, string = toString2(args[0]); + var args = arguments, string = toString3(args[0]); return args.length < 3 ? string : string.replace(args[1], args[2]); } var snakeCase = createCompounder(function(result2, word, index) { @@ -4625,7 +5209,7 @@ var require_lodash = __commonJS({ if (!limit) { return []; } - string = toString2(string); + string = toString3(string); if (string && (typeof separator == "string" || separator != null && !isRegExp(separator))) { separator = baseToString(separator); if (!separator && hasUnicode(string)) { @@ -4638,7 +5222,7 @@ var require_lodash = __commonJS({ return result2 + (index ? " " : "") + upperFirst(word); }); function startsWith(string, target, position) { - string = toString2(string); + string = toString3(string); position = position == null ? 0 : baseClamp(toInteger2(position), 0, string.length); target = baseToString(target); return string.slice(position, position + target.length) == target; @@ -4648,7 +5232,7 @@ var require_lodash = __commonJS({ if (guard && isIterateeCall(string, options, guard)) { options = undefined2; } - string = toString2(string); + string = toString3(string); options = assignInWith({}, options, settings, customDefaultsAssignIn); var imports = assignInWith({}, options.imports, settings.imports, customDefaultsAssignIn), importsKeys = keys(imports), importsValues = baseValues(imports, importsKeys); var isEscaping, isEvaluating, index = 0, interpolate = options.interpolate || reNoMatch, source = "__p += '"; @@ -4656,10 +5240,10 @@ var require_lodash = __commonJS({ (options.escape || reNoMatch).source + "|" + interpolate.source + "|" + (interpolate === reInterpolate ? reEsTemplate : reNoMatch).source + "|" + (options.evaluate || reNoMatch).source + "|$", "g" ); - var sourceURL = "//# sourceURL=" + (hasOwnProperty.call(options, "sourceURL") ? (options.sourceURL + "").replace(/\s/g, " ") : "lodash.templateSources[" + ++templateCounter + "]") + "\n"; - string.replace(reDelimiters, function(match2, escapeValue, interpolateValue, esTemplateValue, evaluateValue, offset) { + var sourceURL = "//# sourceURL=" + (hasOwnProperty2.call(options, "sourceURL") ? (options.sourceURL + "").replace(/\s/g, " ") : "lodash.templateSources[" + ++templateCounter + "]") + "\n"; + string.replace(reDelimiters, function(match2, escapeValue, interpolateValue, esTemplateValue, evaluateValue, offset2) { interpolateValue || (interpolateValue = esTemplateValue); - source += string.slice(index, offset).replace(reUnescapedString, escapeStringChar); + source += string.slice(index, offset2).replace(reUnescapedString, escapeStringChar); if (escapeValue) { isEscaping = true; source += "' +\n__e(" + escapeValue + ") +\n'"; @@ -4671,11 +5255,11 @@ var require_lodash = __commonJS({ if (interpolateValue) { source += "' +\n((__t = (" + interpolateValue + ")) == null ? '' : __t) +\n'"; } - index = offset + match2.length; + index = offset2 + match2.length; return match2; }); source += "';\n"; - var variable = hasOwnProperty.call(options, "variable") && options.variable; + var variable = hasOwnProperty2.call(options, "variable") && options.variable; if (!variable) { source = "with (obj) {\n" + source + "\n}\n"; } else if (reForbiddenIdentifierChars.test(variable)) { @@ -4687,19 +5271,19 @@ var require_lodash = __commonJS({ return Function2(importsKeys, sourceURL + "return " + source).apply(undefined2, importsValues); }); result2.source = source; - if (isError2(result2)) { + if (isError(result2)) { throw result2; } return result2; } function toLower(value) { - return toString2(value).toLowerCase(); + return toString3(value).toLowerCase(); } function toUpper(value) { - return toString2(value).toUpperCase(); + return toString3(value).toUpperCase(); } function trim(string, chars, guard) { - string = toString2(string); + string = toString3(string); if (string && (guard || chars === undefined2)) { return baseTrim(string); } @@ -4710,7 +5294,7 @@ var require_lodash = __commonJS({ return castSlice(strSymbols, start, end).join(""); } function trimEnd(string, chars, guard) { - string = toString2(string); + string = toString3(string); if (string && (guard || chars === undefined2)) { return string.slice(0, trimmedEndIndex(string) + 1); } @@ -4721,7 +5305,7 @@ var require_lodash = __commonJS({ return castSlice(strSymbols, 0, end).join(""); } function trimStart(string, chars, guard) { - string = toString2(string); + string = toString3(string); if (string && (guard || chars === undefined2)) { return string.replace(reTrimStart, ""); } @@ -4733,12 +5317,12 @@ var require_lodash = __commonJS({ } function truncate(string, options) { var length = DEFAULT_TRUNC_LENGTH, omission = DEFAULT_TRUNC_OMISSION; - if (isObject(options)) { + if (isObject2(options)) { var separator = "separator" in options ? options.separator : separator; length = "length" in options ? toInteger2(options.length) : length; omission = "omission" in options ? baseToString(options.omission) : omission; } - string = toString2(string); + string = toString3(string); var strLength = string.length; if (hasUnicode(string)) { var strSymbols = stringToArray(string); @@ -4762,7 +5346,7 @@ var require_lodash = __commonJS({ if (string.slice(end).search(separator)) { var match2, substring = result2; if (!separator.global) { - separator = RegExp2(separator.source, toString2(reFlags.exec(separator)) + "g"); + separator = RegExp2(separator.source, toString3(reFlags.exec(separator)) + "g"); } separator.lastIndex = 0; while (match2 = separator.exec(substring)) { @@ -4779,7 +5363,7 @@ var require_lodash = __commonJS({ return result2 + omission; } function unescape(string) { - string = toString2(string); + string = toString3(string); return string && reHasEscapedHtml.test(string) ? string.replace(reEscapedHtml, unescapeHtmlChar) : string; } var upperCase = createCompounder(function(result2, word, index) { @@ -4787,7 +5371,7 @@ var require_lodash = __commonJS({ }); var upperFirst = createCaseFirst("toUpperCase"); function words(string, pattern, guard) { - string = toString2(string); + string = toString3(string); pattern = guard ? undefined2 : pattern; if (pattern === undefined2) { return hasUnicodeWord(string) ? unicodeWords(string) : asciiWords(string); @@ -4798,7 +5382,7 @@ var require_lodash = __commonJS({ try { return apply(func, undefined2, args); } catch (e4) { - return isError2(e4) ? e4 : new Error2(e4); + return isError(e4) ? e4 : new Error2(e4); } }); var bindAll = flatRest(function(object, methodNames) { @@ -4863,13 +5447,13 @@ var require_lodash = __commonJS({ }); function mixin(object, source, options) { var props2 = keys(source), methodNames = baseFunctions(source, props2); - if (options == null && !(isObject(source) && (methodNames.length || !props2.length))) { + if (options == null && !(isObject2(source) && (methodNames.length || !props2.length))) { options = source; source = object; object = this; methodNames = baseFunctions(source, keys(source)); } - var chain2 = !(isObject(options) && "chain" in options) || !!options.chain, isFunc = isFunction2(object); + var chain2 = !(isObject2(options) && "chain" in options) || !!options.chain, isFunc = isFunction2(object); arrayEach(methodNames, function(methodName) { var func = source[methodName]; object[methodName] = func; @@ -4894,7 +5478,7 @@ var require_lodash = __commonJS({ } return this; } - function noop2() { + function noop3() { } function nthArg(n2) { n2 = toInteger2(n2); @@ -4945,14 +5529,14 @@ var require_lodash = __commonJS({ return result2; } function toPath(value) { - if (isArray(value)) { + if (isArray2(value)) { return arrayMap(value, toKey); } - return isSymbol(value) ? [value] : copyArray(stringToPath(toString2(value))); + return isSymbol(value) ? [value] : copyArray(stringToPath(toString3(value))); } - function uniqueId(prefix) { + function uniqueId3(prefix) { var id2 = ++idCounter; - return toString2(prefix) + id2; + return toString3(prefix) + id2; } var add2 = createMathOperation(function(augend, addend) { return augend + addend; @@ -4999,7 +5583,7 @@ var require_lodash = __commonJS({ lodash.assignIn = assignIn; lodash.assignInWith = assignInWith; lodash.assignWith = assignWith; - lodash.at = at; + lodash.at = at2; lodash.before = before; lodash.bind = bind; lodash.bindAll = bindAll; @@ -5033,7 +5617,7 @@ var require_lodash = __commonJS({ lodash.flatMap = flatMap; lodash.flatMapDeep = flatMapDeep; lodash.flatMapDepth = flatMapDepth; - lodash.flatten = flatten; + lodash.flatten = flatten2; lodash.flattenDeep = flattenDeep; lodash.flattenDepth = flattenDepth; lodash.flip = flip; @@ -5122,7 +5706,7 @@ var require_lodash = __commonJS({ lodash.union = union; lodash.unionBy = unionBy; lodash.unionWith = unionWith; - lodash.uniq = uniq4; + lodash.uniq = uniq3; lodash.uniqBy = uniqBy; lodash.uniqWith = uniqWith; lodash.unset = unset; @@ -5152,7 +5736,7 @@ var require_lodash = __commonJS({ lodash.camelCase = camelCase; lodash.capitalize = capitalize; lodash.ceil = ceil; - lodash.clamp = clamp; + lodash.clamp = clamp2; lodash.clone = clone; lodash.cloneDeep = cloneDeep; lodash.cloneDeepWith = cloneDeepWith; @@ -5191,7 +5775,7 @@ var require_lodash = __commonJS({ lodash.inRange = inRange; lodash.invoke = invoke; lodash.isArguments = isArguments; - lodash.isArray = isArray; + lodash.isArray = isArray2; lodash.isArrayBuffer = isArrayBuffer; lodash.isArrayLike = isArrayLike; lodash.isArrayLikeObject = isArrayLikeObject; @@ -5202,8 +5786,8 @@ var require_lodash = __commonJS({ lodash.isEmpty = isEmpty; lodash.isEqual = isEqual2; lodash.isEqualWith = isEqualWith; - lodash.isError = isError2; - lodash.isFinite = isFinite; + lodash.isError = isError; + lodash.isFinite = isFinite2; lodash.isFunction = isFunction2; lodash.isInteger = isInteger; lodash.isLength = isLength; @@ -5215,7 +5799,7 @@ var require_lodash = __commonJS({ lodash.isNil = isNil; lodash.isNull = isNull; lodash.isNumber = isNumber; - lodash.isObject = isObject; + lodash.isObject = isObject2; lodash.isObjectLike = isObjectLike; lodash.isPlainObject = isPlainObject; lodash.isRegExp = isRegExp; @@ -5249,7 +5833,7 @@ var require_lodash = __commonJS({ lodash.multiply = multiply; lodash.nth = nth; lodash.noConflict = noConflict; - lodash.noop = noop2; + lodash.noop = noop3; lodash.now = now; lodash.pad = pad; lodash.padEnd = padEnd; @@ -5286,14 +5870,14 @@ var require_lodash = __commonJS({ lodash.toLower = toLower; lodash.toNumber = toNumber; lodash.toSafeInteger = toSafeInteger; - lodash.toString = toString2; + lodash.toString = toString3; lodash.toUpper = toUpper; lodash.trim = trim; lodash.trimEnd = trimEnd; lodash.trimStart = trimStart; lodash.truncate = truncate; lodash.unescape = unescape; - lodash.uniqueId = uniqueId; + lodash.uniqueId = uniqueId3; lodash.upperCase = upperCase; lodash.upperFirst = upperFirst; lodash.each = forEach; @@ -5302,7 +5886,7 @@ var require_lodash = __commonJS({ mixin(lodash, function() { var source = {}; baseForOwn(lodash, function(func, methodName) { - if (!hasOwnProperty.call(lodash.prototype, methodName)) { + if (!hasOwnProperty2.call(lodash.prototype, methodName)) { source[methodName] = func; } }); @@ -5403,7 +5987,7 @@ var require_lodash = __commonJS({ return; } lodash.prototype[methodName] = function() { - var value = this.__wrapped__, args = isTaker ? [1] : arguments, isLazy = value instanceof LazyWrapper, iteratee2 = args[0], useLazy = isLazy || isArray(value); + var value = this.__wrapped__, args = isTaker ? [1] : arguments, isLazy = value instanceof LazyWrapper, iteratee2 = args[0], useLazy = isLazy || isArray2(value); var interceptor = function(value2) { var result3 = lodashFunc.apply(lodash, arrayPush([value2], args)); return isTaker && chainAll ? result3[0] : result3; @@ -5431,10 +6015,10 @@ var require_lodash = __commonJS({ var args = arguments; if (retUnwrapped && !this.__chain__) { var value = this.value(); - return func.apply(isArray(value) ? value : [], args); + return func.apply(isArray2(value) ? value : [], args); } return this[chainName](function(value2) { - return func.apply(isArray(value2) ? value2 : [], args); + return func.apply(isArray2(value2) ? value2 : [], args); }); }; }); @@ -5442,7 +6026,7 @@ var require_lodash = __commonJS({ var lodashFunc = lodash[methodName]; if (lodashFunc) { var key2 = lodashFunc.name + ""; - if (!hasOwnProperty.call(realNames, key2)) { + if (!hasOwnProperty2.call(realNames, key2)) { realNames[key2] = []; } realNames[key2].push({ "name": methodName, "func": lodashFunc }); @@ -5468,602 +6052,576 @@ var require_lodash = __commonJS({ } return lodash; }; - var _9 = runInContext(); + var _12 = runInContext(); if (typeof define == "function" && typeof define.amd == "object" && define.amd) { - root._ = _9; + root._ = _12; define(function() { - return _9; + return _12; }); } else if (freeModule) { - (freeModule.exports = _9)._ = _9; - freeExports._ = _9; + (freeModule.exports = _12)._ = _12; + freeExports._ = _12; } else { - root._ = _9; + root._ = _12; } }).call(exports); } }); -// node_modules/fuzzysort/fuzzysort.js -var require_fuzzysort = __commonJS({ - "node_modules/fuzzysort/fuzzysort.js"(exports, module2) { - ((root, UMD) => { - if (typeof define === "function" && define.amd) - define([], UMD); - else if (typeof module2 === "object" && module2.exports) - module2.exports = UMD(); - else - root["fuzzysort"] = UMD(); - })(exports, (_9) => { +// node_modules/classnames/index.js +var require_classnames = __commonJS({ + "node_modules/classnames/index.js"(exports, module2) { + (function() { "use strict"; - var single = (search, target) => { - if (search == "farzher") - return { target: "farzher was here (^-^*)/", score: 0, _indexes: [0] }; - if (!search || !target) - return NULL; - var preparedSearch = getPreparedSearch(search); - if (!isObj(target)) - target = getPrepared(target); - var searchBitflags = preparedSearch.bitflags; - if ((searchBitflags & target._bitflags) !== searchBitflags) - return NULL; - return algorithm(preparedSearch, target); - }; - var go = (search, targets, options) => { - if (search == "farzher") - return [{ target: "farzher was here (^-^*)/", score: 0, _indexes: [0], obj: targets ? targets[0] : NULL }]; - if (!search) - return options && options.all ? all(search, targets, options) : noResults; - var preparedSearch = getPreparedSearch(search); - var searchBitflags = preparedSearch.bitflags; - var containsSpace = preparedSearch.containsSpace; - var threshold = options && options.threshold || INT_MIN; - var limit = options && options["limit"] || INT_MAX; - var resultsLen = 0; - var limitedCount = 0; - var targetsLen = targets.length; - if (options && options.key) { - var key2 = options.key; - for (var i4 = 0; i4 < targetsLen; ++i4) { - var obj = targets[i4]; - var target = getValue(obj, key2); - if (!target) - continue; - if (!isObj(target)) - target = getPrepared(target); - if ((searchBitflags & target._bitflags) !== searchBitflags) - continue; - var result = algorithm(preparedSearch, target); - if (result === NULL) - continue; - if (result.score < threshold) - continue; - result = { target: result.target, _targetLower: "", _targetLowerCodes: NULL, _nextBeginningIndexes: NULL, _bitflags: 0, score: result.score, _indexes: result._indexes, obj }; - if (resultsLen < limit) { - q5.add(result); - ++resultsLen; - } else { - ++limitedCount; - if (result.score > q5.peek().score) - q5.replaceTop(result); - } - } - } else if (options && options.keys) { - var scoreFn = options["scoreFn"] || defaultScoreFn; - var keys = options.keys; - var keysLen = keys.length; - for (var i4 = 0; i4 < targetsLen; ++i4) { - var obj = targets[i4]; - var objResults = new Array(keysLen); - for (var keyI = 0; keyI < keysLen; ++keyI) { - var key2 = keys[keyI]; - var target = getValue(obj, key2); - if (!target) { - objResults[keyI] = NULL; - continue; + var hasOwn2 = {}.hasOwnProperty; + var nativeCodeString = "[native code]"; + function classNames9() { + var classes = []; + for (var i4 = 0; i4 < arguments.length; i4++) { + var arg = arguments[i4]; + if (!arg) + continue; + var argType = typeof arg; + if (argType === "string" || argType === "number") { + classes.push(arg); + } else if (Array.isArray(arg)) { + if (arg.length) { + var inner = classNames9.apply(null, arg); + if (inner) { + classes.push(inner); } - if (!isObj(target)) - target = getPrepared(target); - if ((searchBitflags & target._bitflags) !== searchBitflags) - objResults[keyI] = NULL; - else - objResults[keyI] = algorithm(preparedSearch, target); } - objResults.obj = obj; - var score = scoreFn(objResults); - if (score === NULL) - continue; - if (score < threshold) + } else if (argType === "object") { + if (arg.toString !== Object.prototype.toString && !arg.toString.toString().includes("[native code]")) { + classes.push(arg.toString()); continue; - objResults.score = score; - if (resultsLen < limit) { - q5.add(objResults); - ++resultsLen; - } else { - ++limitedCount; - if (score > q5.peek().score) - q5.replaceTop(objResults); } - } - } else { - for (var i4 = 0; i4 < targetsLen; ++i4) { - var target = targets[i4]; - if (!target) - continue; - if (!isObj(target)) - target = getPrepared(target); - if ((searchBitflags & target._bitflags) !== searchBitflags) - continue; - var result = algorithm(preparedSearch, target); - if (result === NULL) - continue; - if (result.score < threshold) - continue; - if (resultsLen < limit) { - q5.add(result); - ++resultsLen; - } else { - ++limitedCount; - if (result.score > q5.peek().score) - q5.replaceTop(result); + for (var key2 in arg) { + if (hasOwn2.call(arg, key2) && arg[key2]) { + classes.push(key2); + } } } } - if (resultsLen === 0) - return noResults; - var results = new Array(resultsLen); - for (var i4 = resultsLen - 1; i4 >= 0; --i4) - results[i4] = q5.poll(); - results.total = resultsLen + limitedCount; - return results; - }; - var highlight = (result, hOpen, hClose) => { - if (typeof hOpen === "function") - return highlightCallback(result, hOpen); - if (result === NULL) - return NULL; - if (hOpen === void 0) - hOpen = ""; - if (hClose === void 0) - hClose = ""; - var highlighted = ""; - var matchesIndex = 0; - var opened = false; - var target = result.target; - var targetLen = target.length; - var indexes2 = result._indexes; - indexes2 = indexes2.slice(0, indexes2.len).sort((a5, b4) => a5 - b4); - for (var i4 = 0; i4 < targetLen; ++i4) { - var char = target[i4]; - if (indexes2[matchesIndex] === i4) { - ++matchesIndex; - if (!opened) { - opened = true; - highlighted += hOpen; - } - if (matchesIndex === indexes2.length) { - highlighted += char + hClose + target.substr(i4 + 1); - break; - } + return classes.join(" "); + } + if (typeof module2 !== "undefined" && module2.exports) { + classNames9.default = classNames9; + module2.exports = classNames9; + } else if (typeof define === "function" && typeof define.amd === "object" && define.amd) { + define("classnames", [], function() { + return classNames9; + }); + } else { + window.classNames = classNames9; + } + })(); + } +}); + +// node_modules/tslib/tslib.js +var require_tslib = __commonJS({ + "node_modules/tslib/tslib.js"(exports, module2) { + var __extends4; + var __assign5; + var __rest3; + var __decorate2; + var __param2; + var __esDecorate2; + var __runInitializers2; + var __propKey2; + var __setFunctionName2; + var __metadata2; + var __awaiter2; + var __generator2; + var __exportStar2; + var __values2; + var __read2; + var __spread2; + var __spreadArrays2; + var __spreadArray3; + var __await2; + var __asyncGenerator2; + var __asyncDelegator2; + var __asyncValues2; + var __makeTemplateObject2; + var __importStar2; + var __importDefault2; + var __classPrivateFieldGet2; + var __classPrivateFieldSet2; + var __classPrivateFieldIn2; + var __createBinding2; + (function(factory) { + var root = typeof global === "object" ? global : typeof self === "object" ? self : typeof this === "object" ? this : {}; + if (typeof define === "function" && define.amd) { + define("tslib", ["exports"], function(exports2) { + factory(createExporter(root, createExporter(exports2))); + }); + } else if (typeof module2 === "object" && typeof module2.exports === "object") { + factory(createExporter(root, createExporter(module2.exports))); + } else { + factory(createExporter(root)); + } + function createExporter(exports2, previous) { + if (exports2 !== root) { + if (typeof Object.create === "function") { + Object.defineProperty(exports2, "__esModule", { value: true }); } else { - if (opened) { - opened = false; - highlighted += hClose; - } + exports2.__esModule = true; } - highlighted += char; } - return highlighted; + return function(id2, v3) { + return exports2[id2] = previous ? previous(id2, v3) : v3; + }; + } + })(function(exporter) { + var extendStatics = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(d5, b4) { + d5.__proto__ = b4; + } || function(d5, b4) { + for (var p3 in b4) + if (Object.prototype.hasOwnProperty.call(b4, p3)) + d5[p3] = b4[p3]; }; - var highlightCallback = (result, cb) => { - if (result === NULL) - return NULL; - var target = result.target; - var targetLen = target.length; - var indexes2 = result._indexes; - indexes2 = indexes2.slice(0, indexes2.len).sort((a5, b4) => a5 - b4); - var highlighted = ""; - var matchI = 0; - var indexesI = 0; - var opened = false; - var result = []; - for (var i4 = 0; i4 < targetLen; ++i4) { - var char = target[i4]; - if (indexes2[indexesI] === i4) { - ++indexesI; - if (!opened) { - opened = true; - result.push(highlighted); - highlighted = ""; - } - if (indexesI === indexes2.length) { - highlighted += char; - result.push(cb(highlighted, matchI++)); - highlighted = ""; - result.push(target.substr(i4 + 1)); - break; - } - } else { - if (opened) { - opened = false; - result.push(cb(highlighted, matchI++)); - highlighted = ""; - } - } - highlighted += char; + __extends4 = function(d5, b4) { + if (typeof b4 !== "function" && b4 !== null) + throw new TypeError("Class extends value " + String(b4) + " is not a constructor or null"); + extendStatics(d5, b4); + function __() { + this.constructor = d5; } - return result; + d5.prototype = b4 === null ? Object.create(b4) : (__.prototype = b4.prototype, new __()); }; - var indexes = (result) => result._indexes.slice(0, result._indexes.len).sort((a5, b4) => a5 - b4); - var prepare = (target) => { - if (typeof target !== "string") - target = ""; - var info = prepareLowerInfo(target); - return { "target": target, _targetLower: info._lower, _targetLowerCodes: info.lowerCodes, _nextBeginningIndexes: NULL, _bitflags: info.bitflags, "score": NULL, _indexes: [0], "obj": NULL }; + __assign5 = Object.assign || function(t4) { + for (var s5, i4 = 1, n2 = arguments.length; i4 < n2; i4++) { + s5 = arguments[i4]; + for (var p3 in s5) + if (Object.prototype.hasOwnProperty.call(s5, p3)) + t4[p3] = s5[p3]; + } + return t4; }; - var prepareSearch = (search) => { - if (typeof search !== "string") - search = ""; - search = search.trim(); - var info = prepareLowerInfo(search); - var spaceSearches = []; - if (info.containsSpace) { - var searches = search.split(/\s+/); - searches = [...new Set(searches)]; - for (var i4 = 0; i4 < searches.length; i4++) { - if (searches[i4] === "") + __rest3 = function(s5, e4) { + var t4 = {}; + for (var p3 in s5) + if (Object.prototype.hasOwnProperty.call(s5, p3) && e4.indexOf(p3) < 0) + t4[p3] = s5[p3]; + if (s5 != null && typeof Object.getOwnPropertySymbols === "function") + for (var i4 = 0, p3 = Object.getOwnPropertySymbols(s5); i4 < p3.length; i4++) { + if (e4.indexOf(p3[i4]) < 0 && Object.prototype.propertyIsEnumerable.call(s5, p3[i4])) + t4[p3[i4]] = s5[p3[i4]]; + } + return t4; + }; + __decorate2 = function(decorators, target, key2, desc) { + var c4 = arguments.length, r3 = c4 < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key2) : desc, d5; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") + r3 = Reflect.decorate(decorators, target, key2, desc); + else + for (var i4 = decorators.length - 1; i4 >= 0; i4--) + if (d5 = decorators[i4]) + r3 = (c4 < 3 ? d5(r3) : c4 > 3 ? d5(target, key2, r3) : d5(target, key2)) || r3; + return c4 > 3 && r3 && Object.defineProperty(target, key2, r3), r3; + }; + __param2 = function(paramIndex, decorator) { + return function(target, key2) { + decorator(target, key2, paramIndex); + }; + }; + __esDecorate2 = function(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) { + function accept(f4) { + if (f4 !== void 0 && typeof f4 !== "function") + throw new TypeError("Function expected"); + return f4; + } + var kind = contextIn.kind, key2 = kind === "getter" ? "get" : kind === "setter" ? "set" : "value"; + var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null; + var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {}); + var _12, done = false; + for (var i4 = decorators.length - 1; i4 >= 0; i4--) { + var context = {}; + for (var p3 in contextIn) + context[p3] = p3 === "access" ? {} : contextIn[p3]; + for (var p3 in contextIn.access) + context.access[p3] = contextIn.access[p3]; + context.addInitializer = function(f4) { + if (done) + throw new TypeError("Cannot add initializers after decoration has completed"); + extraInitializers.push(accept(f4 || null)); + }; + var result = (0, decorators[i4])(kind === "accessor" ? { get: descriptor.get, set: descriptor.set } : descriptor[key2], context); + if (kind === "accessor") { + if (result === void 0) continue; - var _info = prepareLowerInfo(searches[i4]); - spaceSearches.push({ lowerCodes: _info.lowerCodes, _lower: searches[i4].toLowerCase(), containsSpace: false }); + if (result === null || typeof result !== "object") + throw new TypeError("Object expected"); + if (_12 = accept(result.get)) + descriptor.get = _12; + if (_12 = accept(result.set)) + descriptor.set = _12; + if (_12 = accept(result.init)) + initializers.push(_12); + } else if (_12 = accept(result)) { + if (kind === "field") + initializers.push(_12); + else + descriptor[key2] = _12; } } - return { lowerCodes: info.lowerCodes, bitflags: info.bitflags, containsSpace: info.containsSpace, _lower: info._lower, spaceSearches }; + if (target) + Object.defineProperty(target, contextIn.name, descriptor); + done = true; }; - var getPrepared = (target) => { - if (target.length > 999) - return prepare(target); - var targetPrepared = preparedCache.get(target); - if (targetPrepared !== void 0) - return targetPrepared; - targetPrepared = prepare(target); - preparedCache.set(target, targetPrepared); - return targetPrepared; + __runInitializers2 = function(thisArg, initializers, value) { + var useValue = arguments.length > 2; + for (var i4 = 0; i4 < initializers.length; i4++) { + value = useValue ? initializers[i4].call(thisArg, value) : initializers[i4].call(thisArg); + } + return useValue ? value : void 0; }; - var getPreparedSearch = (search) => { - if (search.length > 999) - return prepareSearch(search); - var searchPrepared = preparedSearchCache.get(search); - if (searchPrepared !== void 0) - return searchPrepared; - searchPrepared = prepareSearch(search); - preparedSearchCache.set(search, searchPrepared); - return searchPrepared; + __propKey2 = function(x5) { + return typeof x5 === "symbol" ? x5 : "".concat(x5); }; - var all = (search, targets, options) => { - var results = []; - results.total = targets.length; - var limit = options && options.limit || INT_MAX; - if (options && options.key) { - for (var i4 = 0; i4 < targets.length; i4++) { - var obj = targets[i4]; - var target = getValue(obj, options.key); - if (!target) - continue; - if (!isObj(target)) - target = getPrepared(target); - target.score = INT_MIN; - target._indexes.len = 0; - var result = target; - result = { target: result.target, _targetLower: "", _targetLowerCodes: NULL, _nextBeginningIndexes: NULL, _bitflags: 0, score: target.score, _indexes: NULL, obj }; - results.push(result); - if (results.length >= limit) - return results; + __setFunctionName2 = function(f4, name, prefix) { + if (typeof name === "symbol") + name = name.description ? "[".concat(name.description, "]") : ""; + return Object.defineProperty(f4, "name", { configurable: true, value: prefix ? "".concat(prefix, " ", name) : name }); + }; + __metadata2 = function(metadataKey, metadataValue) { + if (typeof Reflect === "object" && typeof Reflect.metadata === "function") + return Reflect.metadata(metadataKey, metadataValue); + }; + __awaiter2 = function(thisArg, _arguments, P4, generator) { + function adopt(value) { + return value instanceof P4 ? value : new P4(function(resolve) { + resolve(value); + }); + } + return new (P4 || (P4 = Promise))(function(resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e4) { + reject(e4); + } } - } else if (options && options.keys) { - for (var i4 = 0; i4 < targets.length; i4++) { - var obj = targets[i4]; - var objResults = new Array(options.keys.length); - for (var keyI = options.keys.length - 1; keyI >= 0; --keyI) { - var target = getValue(obj, options.keys[keyI]); - if (!target) { - objResults[keyI] = NULL; - continue; - } - if (!isObj(target)) - target = getPrepared(target); - target.score = INT_MIN; - target._indexes.len = 0; - objResults[keyI] = target; + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e4) { + reject(e4); } - objResults.obj = obj; - objResults.score = INT_MIN; - results.push(objResults); - if (results.length >= limit) - return results; } - } else { - for (var i4 = 0; i4 < targets.length; i4++) { - var target = targets[i4]; - if (!target) - continue; - if (!isObj(target)) - target = getPrepared(target); - target.score = INT_MIN; - target._indexes.len = 0; - results.push(target); - if (results.length >= limit) - return results; + function step(result) { + result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - } - return results; + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); }; - var algorithm = (preparedSearch, prepared, allowSpaces = false) => { - if (allowSpaces === false && preparedSearch.containsSpace) - return algorithmSpaces(preparedSearch, prepared); - var searchLower = preparedSearch._lower; - var searchLowerCodes = preparedSearch.lowerCodes; - var searchLowerCode = searchLowerCodes[0]; - var targetLowerCodes = prepared._targetLowerCodes; - var searchLen = searchLowerCodes.length; - var targetLen = targetLowerCodes.length; - var searchI = 0; - var targetI = 0; - var matchesSimpleLen = 0; - for (; ; ) { - var isMatch2 = searchLowerCode === targetLowerCodes[targetI]; - if (isMatch2) { - matchesSimple[matchesSimpleLen++] = targetI; - ++searchI; - if (searchI === searchLen) - break; - searchLowerCode = searchLowerCodes[searchI]; - } - ++targetI; - if (targetI >= targetLen) - return NULL; + __generator2 = function(thisArg, body) { + var _12 = { label: 0, sent: function() { + if (t4[0] & 1) + throw t4[1]; + return t4[1]; + }, trys: [], ops: [] }, f4, y5, t4, g4; + return g4 = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g4[Symbol.iterator] = function() { + return this; + }), g4; + function verb(n2) { + return function(v3) { + return step([n2, v3]); + }; } - var searchI = 0; - var successStrict = false; - var matchesStrictLen = 0; - var nextBeginningIndexes = prepared._nextBeginningIndexes; - if (nextBeginningIndexes === NULL) - nextBeginningIndexes = prepared._nextBeginningIndexes = prepareNextBeginningIndexes(prepared.target); - var firstPossibleI = targetI = matchesSimple[0] === 0 ? 0 : nextBeginningIndexes[matchesSimple[0] - 1]; - var backtrackCount = 0; - if (targetI !== targetLen) - for (; ; ) { - if (targetI >= targetLen) { - if (searchI <= 0) - break; - ++backtrackCount; - if (backtrackCount > 200) - break; - --searchI; - var lastMatch = matchesStrict[--matchesStrictLen]; - targetI = nextBeginningIndexes[lastMatch]; - } else { - var isMatch2 = searchLowerCodes[searchI] === targetLowerCodes[targetI]; - if (isMatch2) { - matchesStrict[matchesStrictLen++] = targetI; - ++searchI; - if (searchI === searchLen) { - successStrict = true; + function step(op) { + if (f4) + throw new TypeError("Generator is already executing."); + while (g4 && (g4 = 0, op[0] && (_12 = 0)), _12) + try { + if (f4 = 1, y5 && (t4 = op[0] & 2 ? y5["return"] : op[0] ? y5["throw"] || ((t4 = y5["return"]) && t4.call(y5), 0) : y5.next) && !(t4 = t4.call(y5, op[1])).done) + return t4; + if (y5 = 0, t4) + op = [op[0] & 2, t4.value]; + switch (op[0]) { + case 0: + case 1: + t4 = op; break; - } - ++targetI; - } else { - targetI = nextBeginningIndexes[targetI]; + case 4: + _12.label++; + return { value: op[1], done: false }; + case 5: + _12.label++; + y5 = op[1]; + op = [0]; + continue; + case 7: + op = _12.ops.pop(); + _12.trys.pop(); + continue; + default: + if (!(t4 = _12.trys, t4 = t4.length > 0 && t4[t4.length - 1]) && (op[0] === 6 || op[0] === 2)) { + _12 = 0; + continue; + } + if (op[0] === 3 && (!t4 || op[1] > t4[0] && op[1] < t4[3])) { + _12.label = op[1]; + break; + } + if (op[0] === 6 && _12.label < t4[1]) { + _12.label = t4[1]; + t4 = op; + break; + } + if (t4 && _12.label < t4[2]) { + _12.label = t4[2]; + _12.ops.push(op); + break; + } + if (t4[2]) + _12.ops.pop(); + _12.trys.pop(); + continue; } + op = body.call(thisArg, _12); + } catch (e4) { + op = [6, e4]; + y5 = 0; + } finally { + f4 = t4 = 0; } - } - var substringIndex = prepared._targetLower.indexOf(searchLower, matchesSimple[0]); - var isSubstring = ~substringIndex; - if (isSubstring && !successStrict) { - for (var i4 = 0; i4 < matchesSimpleLen; ++i4) - matchesSimple[i4] = substringIndex + i4; + if (op[0] & 5) + throw op[1]; + return { value: op[0] ? op[1] : void 0, done: true }; } - var isSubstringBeginning = false; - if (isSubstring) { - isSubstringBeginning = prepared._nextBeginningIndexes[substringIndex - 1] === substringIndex; + }; + __exportStar2 = function(m5, o3) { + for (var p3 in m5) + if (p3 !== "default" && !Object.prototype.hasOwnProperty.call(o3, p3)) + __createBinding2(o3, m5, p3); + }; + __createBinding2 = Object.create ? function(o3, m5, k5, k22) { + if (k22 === void 0) + k22 = k5; + var desc = Object.getOwnPropertyDescriptor(m5, k5); + if (!desc || ("get" in desc ? !m5.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m5[k5]; + } }; } - { - if (successStrict) { - var matchesBest = matchesStrict; - var matchesBestLen = matchesStrictLen; - } else { - var matchesBest = matchesSimple; - var matchesBestLen = matchesSimpleLen; - } - var score = 0; - var extraMatchGroupCount = 0; - for (var i4 = 1; i4 < searchLen; ++i4) { - if (matchesBest[i4] - matchesBest[i4 - 1] !== 1) { - score -= matchesBest[i4]; - ++extraMatchGroupCount; + Object.defineProperty(o3, k22, desc); + } : function(o3, m5, k5, k22) { + if (k22 === void 0) + k22 = k5; + o3[k22] = m5[k5]; + }; + __values2 = function(o3) { + var s5 = typeof Symbol === "function" && Symbol.iterator, m5 = s5 && o3[s5], i4 = 0; + if (m5) + return m5.call(o3); + if (o3 && typeof o3.length === "number") + return { + next: function() { + if (o3 && i4 >= o3.length) + o3 = void 0; + return { value: o3 && o3[i4++], done: !o3 }; } + }; + throw new TypeError(s5 ? "Object is not iterable." : "Symbol.iterator is not defined."); + }; + __read2 = function(o3, n2) { + var m5 = typeof Symbol === "function" && o3[Symbol.iterator]; + if (!m5) + return o3; + var i4 = m5.call(o3), r3, ar = [], e4; + try { + while ((n2 === void 0 || n2-- > 0) && !(r3 = i4.next()).done) + ar.push(r3.value); + } catch (error) { + e4 = { error }; + } finally { + try { + if (r3 && !r3.done && (m5 = i4["return"])) + m5.call(i4); + } finally { + if (e4) + throw e4.error; } - var unmatchedDistance = matchesBest[searchLen - 1] - matchesBest[0] - (searchLen - 1); - score -= (12 + unmatchedDistance) * extraMatchGroupCount; - if (matchesBest[0] !== 0) - score -= matchesBest[0] * matchesBest[0] * 0.2; - if (!successStrict) { - score *= 1e3; - } else { - var uniqueBeginningIndexes = 1; - for (var i4 = nextBeginningIndexes[0]; i4 < targetLen; i4 = nextBeginningIndexes[i4]) - ++uniqueBeginningIndexes; - if (uniqueBeginningIndexes > 24) - score *= (uniqueBeginningIndexes - 24) * 10; - } - if (isSubstring) - score /= 1 + searchLen * searchLen * 1; - if (isSubstringBeginning) - score /= 1 + searchLen * searchLen * 1; - score -= targetLen - searchLen; - prepared.score = score; - for (var i4 = 0; i4 < matchesBestLen; ++i4) - prepared._indexes[i4] = matchesBest[i4]; - prepared._indexes.len = matchesBestLen; - return prepared; } + return ar; }; - var algorithmSpaces = (preparedSearch, target) => { - var seen_indexes = /* @__PURE__ */ new Set(); - var score = 0; - var result = NULL; - var first_seen_index_last_search = 0; - var searches = preparedSearch.spaceSearches; - for (var i4 = 0; i4 < searches.length; ++i4) { - var search = searches[i4]; - result = algorithm(search, target); - if (result === NULL) - return NULL; - score += result.score; - if (result._indexes[0] < first_seen_index_last_search) { - score -= first_seen_index_last_search - result._indexes[0]; + __spread2 = function() { + for (var ar = [], i4 = 0; i4 < arguments.length; i4++) + ar = ar.concat(__read2(arguments[i4])); + return ar; + }; + __spreadArrays2 = function() { + for (var s5 = 0, i4 = 0, il = arguments.length; i4 < il; i4++) + s5 += arguments[i4].length; + for (var r3 = Array(s5), k5 = 0, i4 = 0; i4 < il; i4++) + for (var a5 = arguments[i4], j4 = 0, jl = a5.length; j4 < jl; j4++, k5++) + r3[k5] = a5[j4]; + return r3; + }; + __spreadArray3 = function(to, from, pack) { + if (pack || arguments.length === 2) + for (var i4 = 0, l3 = from.length, ar; i4 < l3; i4++) { + if (ar || !(i4 in from)) { + if (!ar) + ar = Array.prototype.slice.call(from, 0, i4); + ar[i4] = from[i4]; + } } - first_seen_index_last_search = result._indexes[0]; - for (var j4 = 0; j4 < result._indexes.len; ++j4) - seen_indexes.add(result._indexes[j4]); + return to.concat(ar || Array.prototype.slice.call(from)); + }; + __await2 = function(v3) { + return this instanceof __await2 ? (this.v = v3, this) : new __await2(v3); + }; + __asyncGenerator2 = function(thisArg, _arguments, generator) { + if (!Symbol.asyncIterator) + throw new TypeError("Symbol.asyncIterator is not defined."); + var g4 = generator.apply(thisArg, _arguments || []), i4, q5 = []; + return i4 = {}, verb("next"), verb("throw"), verb("return"), i4[Symbol.asyncIterator] = function() { + return this; + }, i4; + function verb(n2) { + if (g4[n2]) + i4[n2] = function(v3) { + return new Promise(function(a5, b4) { + q5.push([n2, v3, a5, b4]) > 1 || resume(n2, v3); + }); + }; } - var allowSpacesResult = algorithm(preparedSearch, target, true); - if (allowSpacesResult !== NULL && allowSpacesResult.score > score) { - return allowSpacesResult; + function resume(n2, v3) { + try { + step(g4[n2](v3)); + } catch (e4) { + settle(q5[0][3], e4); + } + } + function step(r3) { + r3.value instanceof __await2 ? Promise.resolve(r3.value.v).then(fulfill, reject) : settle(q5[0][2], r3); + } + function fulfill(value) { + resume("next", value); + } + function reject(value) { + resume("throw", value); + } + function settle(f4, v3) { + if (f4(v3), q5.shift(), q5.length) + resume(q5[0][0], q5[0][1]); } - result.score = score; - var i4 = 0; - for (let index of seen_indexes) - result._indexes[i4++] = index; - result._indexes.len = i4; - return result; }; - var prepareLowerInfo = (str) => { - var strLen = str.length; - var lower = str.toLowerCase(); - var lowerCodes = []; - var bitflags = 0; - var containsSpace = false; - for (var i4 = 0; i4 < strLen; ++i4) { - var lowerCode = lowerCodes[i4] = lower.charCodeAt(i4); - if (lowerCode === 32) { - containsSpace = true; - continue; - } - var bit = lowerCode >= 97 && lowerCode <= 122 ? lowerCode - 97 : lowerCode >= 48 && lowerCode <= 57 ? 26 : lowerCode <= 127 ? 30 : 31; - bitflags |= 1 << bit; + __asyncDelegator2 = function(o3) { + var i4, p3; + return i4 = {}, verb("next"), verb("throw", function(e4) { + throw e4; + }), verb("return"), i4[Symbol.iterator] = function() { + return this; + }, i4; + function verb(n2, f4) { + i4[n2] = o3[n2] ? function(v3) { + return (p3 = !p3) ? { value: __await2(o3[n2](v3)), done: false } : f4 ? f4(v3) : v3; + } : f4; } - return { lowerCodes, bitflags, containsSpace, _lower: lower }; }; - var prepareBeginningIndexes = (target) => { - var targetLen = target.length; - var beginningIndexes = []; - var beginningIndexesLen = 0; - var wasUpper = false; - var wasAlphanum = false; - for (var i4 = 0; i4 < targetLen; ++i4) { - var targetCode = target.charCodeAt(i4); - var isUpper = targetCode >= 65 && targetCode <= 90; - var isAlphanum = isUpper || targetCode >= 97 && targetCode <= 122 || targetCode >= 48 && targetCode <= 57; - var isBeginning = isUpper && !wasUpper || !wasAlphanum || !isAlphanum; - wasUpper = isUpper; - wasAlphanum = isAlphanum; - if (isBeginning) - beginningIndexes[beginningIndexesLen++] = i4; + __asyncValues2 = function(o3) { + if (!Symbol.asyncIterator) + throw new TypeError("Symbol.asyncIterator is not defined."); + var m5 = o3[Symbol.asyncIterator], i4; + return m5 ? m5.call(o3) : (o3 = typeof __values2 === "function" ? __values2(o3) : o3[Symbol.iterator](), i4 = {}, verb("next"), verb("throw"), verb("return"), i4[Symbol.asyncIterator] = function() { + return this; + }, i4); + function verb(n2) { + i4[n2] = o3[n2] && function(v3) { + return new Promise(function(resolve, reject) { + v3 = o3[n2](v3), settle(resolve, reject, v3.done, v3.value); + }); + }; + } + function settle(resolve, reject, d5, v3) { + Promise.resolve(v3).then(function(v4) { + resolve({ value: v4, done: d5 }); + }, reject); } - return beginningIndexes; }; - var prepareNextBeginningIndexes = (target) => { - var targetLen = target.length; - var beginningIndexes = prepareBeginningIndexes(target); - var nextBeginningIndexes = []; - var lastIsBeginning = beginningIndexes[0]; - var lastIsBeginningI = 0; - for (var i4 = 0; i4 < targetLen; ++i4) { - if (lastIsBeginning > i4) { - nextBeginningIndexes[i4] = lastIsBeginning; - } else { - lastIsBeginning = beginningIndexes[++lastIsBeginningI]; - nextBeginningIndexes[i4] = lastIsBeginning === void 0 ? targetLen : lastIsBeginning; - } + __makeTemplateObject2 = function(cooked, raw) { + if (Object.defineProperty) { + Object.defineProperty(cooked, "raw", { value: raw }); + } else { + cooked.raw = raw; } - return nextBeginningIndexes; + return cooked; }; - var cleanup = () => { - preparedCache.clear(); - preparedSearchCache.clear(); - matchesSimple = []; - matchesStrict = []; + var __setModuleDefault = Object.create ? function(o3, v3) { + Object.defineProperty(o3, "default", { enumerable: true, value: v3 }); + } : function(o3, v3) { + o3["default"] = v3; }; - var preparedCache = /* @__PURE__ */ new Map(); - var preparedSearchCache = /* @__PURE__ */ new Map(); - var matchesSimple = []; - var matchesStrict = []; - var defaultScoreFn = (a5) => { - var max3 = INT_MIN; - var len = a5.length; - for (var i4 = 0; i4 < len; ++i4) { - var result = a5[i4]; - if (result === NULL) - continue; - var score = result.score; - if (score > max3) - max3 = score; + __importStar2 = function(mod) { + if (mod && mod.__esModule) + return mod; + var result = {}; + if (mod != null) { + for (var k5 in mod) + if (k5 !== "default" && Object.prototype.hasOwnProperty.call(mod, k5)) + __createBinding2(result, mod, k5); } - if (max3 === INT_MIN) - return NULL; - return max3; + __setModuleDefault(result, mod); + return result; }; - var getValue = (obj, prop) => { - var tmp = obj[prop]; - if (tmp !== void 0) - return tmp; - var segs = prop; - if (!Array.isArray(prop)) - segs = prop.split("."); - var len = segs.length; - var i4 = -1; - while (obj && ++i4 < len) - obj = obj[segs[i4]]; - return obj; + __importDefault2 = function(mod) { + return mod && mod.__esModule ? mod : { "default": mod }; }; - var isObj = (x5) => { - return typeof x5 === "object"; + __classPrivateFieldGet2 = function(receiver, state, kind, f4) { + if (kind === "a" && !f4) + throw new TypeError("Private accessor was defined without a getter"); + if (typeof state === "function" ? receiver !== state || !f4 : !state.has(receiver)) + throw new TypeError("Cannot read private member from an object whose class did not declare it"); + return kind === "m" ? f4 : kind === "a" ? f4.call(receiver) : f4 ? f4.value : state.get(receiver); }; - var INT_MAX = Infinity; - var INT_MIN = -INT_MAX; - var noResults = []; - noResults.total = 0; - var NULL = null; - var fastpriorityqueue = (r3) => { - var e4 = [], o3 = 0, a5 = {}, v3 = (r4) => { - for (var a6 = 0, v4 = e4[a6], c4 = 1; c4 < o3; ) { - var s5 = c4 + 1; - a6 = c4, s5 < o3 && e4[s5].score < e4[c4].score && (a6 = s5), e4[a6 - 1 >> 1] = e4[a6], c4 = 1 + (a6 << 1); - } - for (var f4 = a6 - 1 >> 1; a6 > 0 && v4.score < e4[f4].score; f4 = (a6 = f4) - 1 >> 1) - e4[a6] = e4[f4]; - e4[a6] = v4; - }; - return a5.add = (r4) => { - var a6 = o3; - e4[o3++] = r4; - for (var v4 = a6 - 1 >> 1; a6 > 0 && r4.score < e4[v4].score; v4 = (a6 = v4) - 1 >> 1) - e4[a6] = e4[v4]; - e4[a6] = r4; - }, a5.poll = (r4) => { - if (0 !== o3) { - var a6 = e4[0]; - return e4[0] = e4[--o3], v3(), a6; - } - }, a5.peek = (r4) => { - if (0 !== o3) - return e4[0]; - }, a5.replaceTop = (r4) => { - e4[0] = r4, v3(); - }, a5; + __classPrivateFieldSet2 = function(receiver, state, value, kind, f4) { + if (kind === "m") + throw new TypeError("Private method is not writable"); + if (kind === "a" && !f4) + throw new TypeError("Private accessor was defined without a setter"); + if (typeof state === "function" ? receiver !== state || !f4 : !state.has(receiver)) + throw new TypeError("Cannot write private member to an object whose class did not declare it"); + return kind === "a" ? f4.call(receiver, value) : f4 ? f4.value = value : state.set(receiver, value), value; }; - var q5 = fastpriorityqueue(); - return { "single": single, "go": go, "highlight": highlight, "prepare": prepare, "indexes": indexes, "cleanup": cleanup }; + __classPrivateFieldIn2 = function(state, receiver) { + if (receiver === null || typeof receiver !== "object" && typeof receiver !== "function") + throw new TypeError("Cannot use 'in' operator on non-object"); + return typeof state === "function" ? receiver === state : state.has(receiver); + }; + exporter("__extends", __extends4); + exporter("__assign", __assign5); + exporter("__rest", __rest3); + exporter("__decorate", __decorate2); + exporter("__param", __param2); + exporter("__esDecorate", __esDecorate2); + exporter("__runInitializers", __runInitializers2); + exporter("__propKey", __propKey2); + exporter("__setFunctionName", __setFunctionName2); + exporter("__metadata", __metadata2); + exporter("__awaiter", __awaiter2); + exporter("__generator", __generator2); + exporter("__exportStar", __exportStar2); + exporter("__createBinding", __createBinding2); + exporter("__values", __values2); + exporter("__read", __read2); + exporter("__spread", __spread2); + exporter("__spreadArrays", __spreadArrays2); + exporter("__spreadArray", __spreadArray3); + exporter("__await", __await2); + exporter("__asyncGenerator", __asyncGenerator2); + exporter("__asyncDelegator", __asyncDelegator2); + exporter("__asyncValues", __asyncValues2); + exporter("__makeTemplateObject", __makeTemplateObject2); + exporter("__importStar", __importStar2); + exporter("__importDefault", __importDefault2); + exporter("__classPrivateFieldGet", __classPrivateFieldGet2); + exporter("__classPrivateFieldSet", __classPrivateFieldSet2); + exporter("__classPrivateFieldIn", __classPrivateFieldIn2); }); } }); @@ -6101,9 +6659,9 @@ var require_he = __commonJS({ var invalidReferenceCodePoints = [1, 2, 3, 4, 5, 6, 7, 8, 11, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 64976, 64977, 64978, 64979, 64980, 64981, 64982, 64983, 64984, 64985, 64986, 64987, 64988, 64989, 64990, 64991, 64992, 64993, 64994, 64995, 64996, 64997, 64998, 64999, 65e3, 65001, 65002, 65003, 65004, 65005, 65006, 65007, 65534, 65535, 131070, 131071, 196606, 196607, 262142, 262143, 327678, 327679, 393214, 393215, 458750, 458751, 524286, 524287, 589822, 589823, 655358, 655359, 720894, 720895, 786430, 786431, 851966, 851967, 917502, 917503, 983038, 983039, 1048574, 1048575, 1114110, 1114111]; var stringFromCharCode = String.fromCharCode; var object = {}; - var hasOwnProperty = object.hasOwnProperty; + var hasOwnProperty2 = object.hasOwnProperty; var has = function(object2, propertyName) { - return hasOwnProperty.call(object2, propertyName); + return hasOwnProperty2.call(object2, propertyName); }; var contains = function(array, value) { var index = -1; @@ -6310,561 +6868,804 @@ var require_he = __commonJS({ } }); -// node_modules/classnames/index.js -var require_classnames = __commonJS({ - "node_modules/classnames/index.js"(exports, module2) { - (function() { - "use strict"; - var hasOwn = {}.hasOwnProperty; - var nativeCodeString = "[native code]"; - function classNames9() { - var classes = []; - for (var i4 = 0; i4 < arguments.length; i4++) { - var arg = arguments[i4]; - if (!arg) - continue; - var argType = typeof arg; - if (argType === "string" || argType === "number") { - classes.push(arg); - } else if (Array.isArray(arg)) { - if (arg.length) { - var inner = classNames9.apply(null, arg); - if (inner) { - classes.push(inner); - } +// node_modules/react-is/cjs/react-is.development.js +var require_react_is_development = __commonJS({ + "node_modules/react-is/cjs/react-is.development.js"(exports) { + "use strict"; + if (true) { + (function() { + "use strict"; + 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" || 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; } - } else if (argType === "object") { - if (arg.toString !== Object.prototype.toString && !arg.toString.toString().includes("[native code]")) { - classes.push(arg.toString()); - continue; + } + 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 Element = REACT_ELEMENT_TYPE; + var ForwardRef = REACT_FORWARD_REF_TYPE; + var Fragment = 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."); } - for (var key2 in arg) { - if (hasOwn.call(arg, key2) && arg[key2]) { - classes.push(key2); + } + 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 isElement(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; + } + exports.AsyncMode = AsyncMode; + exports.ConcurrentMode = ConcurrentMode; + exports.ContextConsumer = ContextConsumer; + exports.ContextProvider = ContextProvider; + exports.Element = Element; + exports.ForwardRef = ForwardRef; + exports.Fragment = Fragment; + exports.Lazy = Lazy; + exports.Memo = Memo; + exports.Portal = Portal; + exports.Profiler = Profiler; + exports.StrictMode = StrictMode; + exports.Suspense = Suspense; + exports.isAsyncMode = isAsyncMode; + exports.isConcurrentMode = isConcurrentMode; + exports.isContextConsumer = isContextConsumer; + exports.isContextProvider = isContextProvider; + exports.isElement = isElement; + exports.isForwardRef = isForwardRef; + exports.isFragment = isFragment; + exports.isLazy = isLazy; + exports.isMemo = isMemo; + exports.isPortal = isPortal; + exports.isProfiler = isProfiler; + exports.isStrictMode = isStrictMode; + exports.isSuspense = isSuspense; + exports.isValidElementType = isValidElementType; + exports.typeOf = typeOf; + })(); + } + } +}); + +// node_modules/react-is/index.js +var require_react_is = __commonJS({ + "node_modules/react-is/index.js"(exports, module2) { + "use strict"; + if (false) { + module2.exports = null; + } else { + module2.exports = require_react_is_development(); + } + } +}); + +// node_modules/object-assign/index.js +var require_object_assign = __commonJS({ + "node_modules/object-assign/index.js"(exports, module2) { + "use strict"; + var getOwnPropertySymbols = Object.getOwnPropertySymbols; + var hasOwnProperty2 = 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 i4 = 0; i4 < 10; i4++) { + test2["_" + String.fromCharCode(i4)] = i4; + } + 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; + } + } + module2.exports = shouldUseNative() ? Object.assign : function(target, source) { + var from; + var to = toObject(target); + var symbols; + for (var s5 = 1; s5 < arguments.length; s5++) { + from = Object(arguments[s5]); + for (var key2 in from) { + if (hasOwnProperty2.call(from, key2)) { + to[key2] = from[key2]; + } + } + if (getOwnPropertySymbols) { + symbols = getOwnPropertySymbols(from); + for (var i4 = 0; i4 < symbols.length; i4++) { + if (propIsEnumerable.call(from, symbols[i4])) { + to[symbols[i4]] = from[symbols[i4]]; + } + } + } + } + return to; + }; + } +}); + +// node_modules/prop-types/lib/ReactPropTypesSecret.js +var require_ReactPropTypesSecret = __commonJS({ + "node_modules/prop-types/lib/ReactPropTypesSecret.js"(exports, module2) { + "use strict"; + var ReactPropTypesSecret = "SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED"; + module2.exports = ReactPropTypesSecret; + } +}); + +// node_modules/prop-types/lib/has.js +var require_has = __commonJS({ + "node_modules/prop-types/lib/has.js"(exports, module2) { + module2.exports = Function.call.bind(Object.prototype.hasOwnProperty); + } +}); + +// node_modules/prop-types/checkPropTypes.js +var require_checkPropTypes = __commonJS({ + "node_modules/prop-types/checkPropTypes.js"(exports, module2) { + "use strict"; + var printWarning = function() { + }; + if (true) { + ReactPropTypesSecret = require_ReactPropTypesSecret(); + loggedTypeFailures = {}; + has = require_has(); + printWarning = function(text2) { + var message = "Warning: " + text2; + if (typeof console !== "undefined") { + console.error(message); + } + try { + throw new Error(message); + } catch (x5) { + } + }; + } + var ReactPropTypesSecret; + var loggedTypeFailures; + var has; + function checkPropTypes(typeSpecs, values, location, componentName, getStack) { + if (true) { + for (var typeSpecName in typeSpecs) { + if (has(typeSpecs, typeSpecName)) { + var error; + try { + if (typeof typeSpecs[typeSpecName] !== "function") { + var err = Error( + (componentName || "React class") + ": " + location + " type `" + typeSpecName + "` is invalid; it must be a function, usually from the `prop-types` package, but received `" + typeof typeSpecs[typeSpecName] + "`.This often happens because of typos such as `PropTypes.function` instead of `PropTypes.func`." + ); + err.name = "Invariant Violation"; + throw err; } + error = typeSpecs[typeSpecName](values, typeSpecName, componentName, location, null, ReactPropTypesSecret); + } catch (ex) { + error = ex; + } + if (error && !(error instanceof Error)) { + printWarning( + (componentName || "React class") + ": type specification of " + location + " `" + typeSpecName + "` is invalid; the type checker function must return `null` or an `Error` but returned a " + typeof error + ". You may have forgotten to pass an argument to the type checker creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and shape all require an argument)." + ); + } + if (error instanceof Error && !(error.message in loggedTypeFailures)) { + loggedTypeFailures[error.message] = true; + var stack = getStack ? getStack() : ""; + printWarning( + "Failed " + location + " type: " + error.message + (stack != null ? stack : "") + ); } } } - return classes.join(" "); } - if (typeof module2 !== "undefined" && module2.exports) { - classNames9.default = classNames9; - module2.exports = classNames9; - } else if (typeof define === "function" && typeof define.amd === "object" && define.amd) { - define("classnames", [], function() { - return classNames9; - }); - } else { - window.classNames = classNames9; + } + checkPropTypes.resetWarningCache = function() { + if (true) { + loggedTypeFailures = {}; } - })(); + }; + module2.exports = checkPropTypes; } }); -// node_modules/tslib/tslib.js -var require_tslib = __commonJS({ - "node_modules/tslib/tslib.js"(exports, module2) { - var __extends2; - var __assign3; - var __rest3; - var __decorate2; - var __param2; - var __esDecorate2; - var __runInitializers2; - var __propKey2; - var __setFunctionName2; - var __metadata2; - var __awaiter2; - var __generator2; - var __exportStar2; - var __values2; - var __read2; - var __spread2; - var __spreadArrays2; - var __spreadArray3; - var __await2; - var __asyncGenerator2; - var __asyncDelegator2; - var __asyncValues2; - var __makeTemplateObject2; - var __importStar2; - var __importDefault2; - var __classPrivateFieldGet2; - var __classPrivateFieldSet2; - var __classPrivateFieldIn2; - var __createBinding2; - (function(factory) { - var root = typeof global === "object" ? global : typeof self === "object" ? self : typeof this === "object" ? this : {}; - if (typeof define === "function" && define.amd) { - define("tslib", ["exports"], function(exports2) { - factory(createExporter(root, createExporter(exports2))); - }); - } else if (typeof module2 === "object" && typeof module2.exports === "object") { - factory(createExporter(root, createExporter(module2.exports))); - } else { - factory(createExporter(root)); +// node_modules/prop-types/factoryWithTypeCheckers.js +var require_factoryWithTypeCheckers = __commonJS({ + "node_modules/prop-types/factoryWithTypeCheckers.js"(exports, module2) { + "use strict"; + var ReactIs = require_react_is(); + var assign2 = require_object_assign(); + var ReactPropTypesSecret = require_ReactPropTypesSecret(); + var has = require_has(); + var checkPropTypes = require_checkPropTypes(); + var printWarning = function() { + }; + if (true) { + printWarning = function(text2) { + var message = "Warning: " + text2; + if (typeof console !== "undefined") { + console.error(message); + } + try { + throw new Error(message); + } catch (x5) { + } + }; + } + function emptyFunctionThatReturnsNull() { + return null; + } + module2.exports = function(isValidElement, throwOnDirectAccess) { + var ITERATOR_SYMBOL = typeof Symbol === "function" && Symbol.iterator; + var FAUX_ITERATOR_SYMBOL = "@@iterator"; + function getIteratorFn(maybeIterable) { + var iteratorFn = maybeIterable && (ITERATOR_SYMBOL && maybeIterable[ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL]); + if (typeof iteratorFn === "function") { + return iteratorFn; + } + } + var ANONYMOUS = "<>"; + var ReactPropTypes = { + array: createPrimitiveTypeChecker("array"), + bigint: createPrimitiveTypeChecker("bigint"), + bool: createPrimitiveTypeChecker("boolean"), + func: createPrimitiveTypeChecker("function"), + number: createPrimitiveTypeChecker("number"), + object: createPrimitiveTypeChecker("object"), + string: createPrimitiveTypeChecker("string"), + symbol: createPrimitiveTypeChecker("symbol"), + any: createAnyTypeChecker(), + arrayOf: createArrayOfTypeChecker, + element: createElementTypeChecker(), + elementType: createElementTypeTypeChecker(), + instanceOf: createInstanceTypeChecker, + node: createNodeChecker(), + objectOf: createObjectOfTypeChecker, + oneOf: createEnumTypeChecker, + oneOfType: createUnionTypeChecker, + shape: createShapeTypeChecker, + exact: createStrictShapeTypeChecker + }; + function is(x5, y5) { + if (x5 === y5) { + return x5 !== 0 || 1 / x5 === 1 / y5; + } else { + return x5 !== x5 && y5 !== y5; + } } - function createExporter(exports2, previous) { - if (exports2 !== root) { - if (typeof Object.create === "function") { - Object.defineProperty(exports2, "__esModule", { value: true }); + function PropTypeError(message, data2) { + this.message = message; + this.data = data2 && typeof data2 === "object" ? data2 : {}; + this.stack = ""; + } + PropTypeError.prototype = Error.prototype; + function createChainableTypeChecker(validate) { + if (true) { + var manualPropTypeCallCache = {}; + var manualPropTypeWarningCount = 0; + } + function checkType(isRequired, props2, propName, componentName, location, propFullName, secret) { + componentName = componentName || ANONYMOUS; + propFullName = propFullName || propName; + if (secret !== ReactPropTypesSecret) { + if (throwOnDirectAccess) { + 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; + } else if (typeof console !== "undefined") { + var cacheKey = componentName + ":" + propName; + if (!manualPropTypeCallCache[cacheKey] && manualPropTypeWarningCount < 3) { + printWarning( + "You are manually calling a React.PropTypes validation function for the `" + propFullName + "` prop on `" + componentName + "`. This is deprecated and will throw in the standalone `prop-types` package. You may be seeing this warning due to a third-party PropTypes library. See https://fb.me/react-warning-dont-call-proptypes for details." + ); + manualPropTypeCallCache[cacheKey] = true; + manualPropTypeWarningCount++; + } + } + } + if (props2[propName] == null) { + if (isRequired) { + if (props2[propName] === null) { + return new PropTypeError("The " + location + " `" + propFullName + "` is marked as required " + ("in `" + componentName + "`, but its value is `null`.")); + } + return new PropTypeError("The " + location + " `" + propFullName + "` is marked as required in " + ("`" + componentName + "`, but its value is `undefined`.")); + } + return null; } else { - exports2.__esModule = true; + return validate(props2, propName, componentName, location, propFullName); + } + } + var chainedCheckType = checkType.bind(null, false); + chainedCheckType.isRequired = checkType.bind(null, true); + return chainedCheckType; + } + function createPrimitiveTypeChecker(expectedType) { + function validate(props2, propName, componentName, location, propFullName, secret) { + var propValue = props2[propName]; + var propType = getPropType(propValue); + if (propType !== expectedType) { + var preciseType = getPreciseType(propValue); + return new PropTypeError( + "Invalid " + location + " `" + propFullName + "` of type " + ("`" + preciseType + "` supplied to `" + componentName + "`, expected ") + ("`" + expectedType + "`."), + { expectedType } + ); } + return null; } - return function(id2, v3) { - return exports2[id2] = previous ? previous(id2, v3) : v3; - }; + return createChainableTypeChecker(validate); } - })(function(exporter) { - var extendStatics = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(d5, b4) { - d5.__proto__ = b4; - } || function(d5, b4) { - for (var p3 in b4) - if (Object.prototype.hasOwnProperty.call(b4, p3)) - d5[p3] = b4[p3]; - }; - __extends2 = function(d5, b4) { - if (typeof b4 !== "function" && b4 !== null) - throw new TypeError("Class extends value " + String(b4) + " is not a constructor or null"); - extendStatics(d5, b4); - function __() { - this.constructor = d5; - } - d5.prototype = b4 === null ? Object.create(b4) : (__.prototype = b4.prototype, new __()); - }; - __assign3 = Object.assign || function(t4) { - for (var s5, i4 = 1, n2 = arguments.length; i4 < n2; i4++) { - s5 = arguments[i4]; - for (var p3 in s5) - if (Object.prototype.hasOwnProperty.call(s5, p3)) - t4[p3] = s5[p3]; + function createAnyTypeChecker() { + return createChainableTypeChecker(emptyFunctionThatReturnsNull); + } + function createArrayOfTypeChecker(typeChecker) { + function validate(props2, propName, componentName, location, propFullName) { + if (typeof typeChecker !== "function") { + return new PropTypeError("Property `" + propFullName + "` of component `" + componentName + "` has invalid PropType notation inside arrayOf."); + } + var propValue = props2[propName]; + if (!Array.isArray(propValue)) { + var propType = getPropType(propValue); + return new PropTypeError("Invalid " + location + " `" + propFullName + "` of type " + ("`" + propType + "` supplied to `" + componentName + "`, expected an array.")); + } + for (var i4 = 0; i4 < propValue.length; i4++) { + var error = typeChecker(propValue, i4, componentName, location, propFullName + "[" + i4 + "]", ReactPropTypesSecret); + if (error instanceof Error) { + return error; + } + } + return null; } - return t4; - }; - __rest3 = function(s5, e4) { - var t4 = {}; - for (var p3 in s5) - if (Object.prototype.hasOwnProperty.call(s5, p3) && e4.indexOf(p3) < 0) - t4[p3] = s5[p3]; - if (s5 != null && typeof Object.getOwnPropertySymbols === "function") - for (var i4 = 0, p3 = Object.getOwnPropertySymbols(s5); i4 < p3.length; i4++) { - if (e4.indexOf(p3[i4]) < 0 && Object.prototype.propertyIsEnumerable.call(s5, p3[i4])) - t4[p3[i4]] = s5[p3[i4]]; + return createChainableTypeChecker(validate); + } + function createElementTypeChecker() { + function validate(props2, propName, componentName, location, propFullName) { + var propValue = props2[propName]; + if (!isValidElement(propValue)) { + var propType = getPropType(propValue); + return new PropTypeError("Invalid " + location + " `" + propFullName + "` of type " + ("`" + propType + "` supplied to `" + componentName + "`, expected a single ReactElement.")); } - return t4; - }; - __decorate2 = function(decorators, target, key2, desc) { - var c4 = arguments.length, r3 = c4 < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key2) : desc, d5; - if (typeof Reflect === "object" && typeof Reflect.decorate === "function") - r3 = Reflect.decorate(decorators, target, key2, desc); - else - for (var i4 = decorators.length - 1; i4 >= 0; i4--) - if (d5 = decorators[i4]) - r3 = (c4 < 3 ? d5(r3) : c4 > 3 ? d5(target, key2, r3) : d5(target, key2)) || r3; - return c4 > 3 && r3 && Object.defineProperty(target, key2, r3), r3; - }; - __param2 = function(paramIndex, decorator) { - return function(target, key2) { - decorator(target, key2, paramIndex); - }; - }; - __esDecorate2 = function(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) { - function accept(f4) { - if (f4 !== void 0 && typeof f4 !== "function") - throw new TypeError("Function expected"); - return f4; + return null; } - var kind = contextIn.kind, key2 = kind === "getter" ? "get" : kind === "setter" ? "set" : "value"; - var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null; - var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {}); - var _9, done = false; - for (var i4 = decorators.length - 1; i4 >= 0; i4--) { - var context = {}; - for (var p3 in contextIn) - context[p3] = p3 === "access" ? {} : contextIn[p3]; - for (var p3 in contextIn.access) - context.access[p3] = contextIn.access[p3]; - context.addInitializer = function(f4) { - if (done) - throw new TypeError("Cannot add initializers after decoration has completed"); - extraInitializers.push(accept(f4 || null)); - }; - var result = (0, decorators[i4])(kind === "accessor" ? { get: descriptor.get, set: descriptor.set } : descriptor[key2], context); - if (kind === "accessor") { - if (result === void 0) - continue; - if (result === null || typeof result !== "object") - throw new TypeError("Object expected"); - if (_9 = accept(result.get)) - descriptor.get = _9; - if (_9 = accept(result.set)) - descriptor.set = _9; - if (_9 = accept(result.init)) - initializers.push(_9); - } else if (_9 = accept(result)) { - if (kind === "field") - initializers.push(_9); - else - descriptor[key2] = _9; + return createChainableTypeChecker(validate); + } + function createElementTypeTypeChecker() { + function validate(props2, propName, componentName, location, propFullName) { + var propValue = props2[propName]; + if (!ReactIs.isValidElementType(propValue)) { + var propType = getPropType(propValue); + return new PropTypeError("Invalid " + location + " `" + propFullName + "` of type " + ("`" + propType + "` supplied to `" + componentName + "`, expected a single ReactElement type.")); } + return null; } - if (target) - Object.defineProperty(target, contextIn.name, descriptor); - done = true; - }; - __runInitializers2 = function(thisArg, initializers, value) { - var useValue = arguments.length > 2; - for (var i4 = 0; i4 < initializers.length; i4++) { - value = useValue ? initializers[i4].call(thisArg, value) : initializers[i4].call(thisArg); + return createChainableTypeChecker(validate); + } + function createInstanceTypeChecker(expectedClass) { + function validate(props2, propName, componentName, location, propFullName) { + if (!(props2[propName] instanceof expectedClass)) { + var expectedClassName = expectedClass.name || ANONYMOUS; + var actualClassName = getClassName(props2[propName]); + return new PropTypeError("Invalid " + location + " `" + propFullName + "` of type " + ("`" + actualClassName + "` supplied to `" + componentName + "`, expected ") + ("instance of `" + expectedClassName + "`.")); + } + return null; } - return useValue ? value : void 0; - }; - __propKey2 = function(x5) { - return typeof x5 === "symbol" ? x5 : "".concat(x5); - }; - __setFunctionName2 = function(f4, name, prefix) { - if (typeof name === "symbol") - name = name.description ? "[".concat(name.description, "]") : ""; - return Object.defineProperty(f4, "name", { configurable: true, value: prefix ? "".concat(prefix, " ", name) : name }); - }; - __metadata2 = function(metadataKey, metadataValue) { - if (typeof Reflect === "object" && typeof Reflect.metadata === "function") - return Reflect.metadata(metadataKey, metadataValue); - }; - __awaiter2 = function(thisArg, _arguments, P4, generator) { - function adopt(value) { - return value instanceof P4 ? value : new P4(function(resolve) { - resolve(value); - }); + return createChainableTypeChecker(validate); + } + function createEnumTypeChecker(expectedValues) { + if (!Array.isArray(expectedValues)) { + if (true) { + if (arguments.length > 1) { + printWarning( + "Invalid arguments supplied to oneOf, expected an array, got " + arguments.length + " arguments. A common mistake is to write oneOf(x, y, z) instead of oneOf([x, y, z])." + ); + } else { + printWarning("Invalid argument supplied to oneOf, expected an array."); + } + } + return emptyFunctionThatReturnsNull; } - return new (P4 || (P4 = Promise))(function(resolve, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e4) { - reject(e4); + function validate(props2, propName, componentName, location, propFullName) { + var propValue = props2[propName]; + for (var i4 = 0; i4 < expectedValues.length; i4++) { + if (is(propValue, expectedValues[i4])) { + return null; } } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e4) { - reject(e4); + var valuesString = JSON.stringify(expectedValues, function replacer(key2, value) { + var type = getPreciseType(value); + if (type === "symbol") { + return String(value); } + return value; + }); + return new PropTypeError("Invalid " + location + " `" + propFullName + "` of value `" + String(propValue) + "` " + ("supplied to `" + componentName + "`, expected one of " + valuesString + ".")); + } + return createChainableTypeChecker(validate); + } + function createObjectOfTypeChecker(typeChecker) { + function validate(props2, propName, componentName, location, propFullName) { + if (typeof typeChecker !== "function") { + return new PropTypeError("Property `" + propFullName + "` of component `" + componentName + "` has invalid PropType notation inside objectOf."); } - function step(result) { - result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); + var propValue = props2[propName]; + var propType = getPropType(propValue); + if (propType !== "object") { + return new PropTypeError("Invalid " + location + " `" + propFullName + "` of type " + ("`" + propType + "` supplied to `" + componentName + "`, expected an object.")); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; - __generator2 = function(thisArg, body) { - var _9 = { label: 0, sent: function() { - if (t4[0] & 1) - throw t4[1]; - return t4[1]; - }, trys: [], ops: [] }, f4, y5, t4, g4; - return g4 = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g4[Symbol.iterator] = function() { - return this; - }), g4; - function verb(n2) { - return function(v3) { - return step([n2, v3]); - }; - } - function step(op) { - if (f4) - throw new TypeError("Generator is already executing."); - while (g4 && (g4 = 0, op[0] && (_9 = 0)), _9) - try { - if (f4 = 1, y5 && (t4 = op[0] & 2 ? y5["return"] : op[0] ? y5["throw"] || ((t4 = y5["return"]) && t4.call(y5), 0) : y5.next) && !(t4 = t4.call(y5, op[1])).done) - return t4; - if (y5 = 0, t4) - op = [op[0] & 2, t4.value]; - switch (op[0]) { - case 0: - case 1: - t4 = op; - break; - case 4: - _9.label++; - return { value: op[1], done: false }; - case 5: - _9.label++; - y5 = op[1]; - op = [0]; - continue; - case 7: - op = _9.ops.pop(); - _9.trys.pop(); - continue; - default: - if (!(t4 = _9.trys, t4 = t4.length > 0 && t4[t4.length - 1]) && (op[0] === 6 || op[0] === 2)) { - _9 = 0; - continue; - } - if (op[0] === 3 && (!t4 || op[1] > t4[0] && op[1] < t4[3])) { - _9.label = op[1]; - break; - } - if (op[0] === 6 && _9.label < t4[1]) { - _9.label = t4[1]; - t4 = op; - break; - } - if (t4 && _9.label < t4[2]) { - _9.label = t4[2]; - _9.ops.push(op); - break; - } - if (t4[2]) - _9.ops.pop(); - _9.trys.pop(); - continue; + for (var key2 in propValue) { + if (has(propValue, key2)) { + var error = typeChecker(propValue, key2, componentName, location, propFullName + "." + key2, ReactPropTypesSecret); + if (error instanceof Error) { + return error; } - op = body.call(thisArg, _9); - } catch (e4) { - op = [6, e4]; - y5 = 0; - } finally { - f4 = t4 = 0; } - if (op[0] & 5) - throw op[1]; - return { value: op[0] ? op[1] : void 0, done: true }; + } + return null; } - }; - __exportStar2 = function(m5, o3) { - for (var p3 in m5) - if (p3 !== "default" && !Object.prototype.hasOwnProperty.call(o3, p3)) - __createBinding2(o3, m5, p3); - }; - __createBinding2 = Object.create ? function(o3, m5, k5, k22) { - if (k22 === void 0) - k22 = k5; - var desc = Object.getOwnPropertyDescriptor(m5, k5); - if (!desc || ("get" in desc ? !m5.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { - return m5[k5]; - } }; + return createChainableTypeChecker(validate); + } + function createUnionTypeChecker(arrayOfTypeCheckers) { + if (!Array.isArray(arrayOfTypeCheckers)) { + true ? printWarning("Invalid argument supplied to oneOfType, expected an instance of array.") : void 0; + return emptyFunctionThatReturnsNull; } - Object.defineProperty(o3, k22, desc); - } : function(o3, m5, k5, k22) { - if (k22 === void 0) - k22 = k5; - o3[k22] = m5[k5]; - }; - __values2 = function(o3) { - var s5 = typeof Symbol === "function" && Symbol.iterator, m5 = s5 && o3[s5], i4 = 0; - if (m5) - return m5.call(o3); - if (o3 && typeof o3.length === "number") - return { - next: function() { - if (o3 && i4 >= o3.length) - o3 = void 0; - return { value: o3 && o3[i4++], done: !o3 }; + for (var i4 = 0; i4 < arrayOfTypeCheckers.length; i4++) { + var checker = arrayOfTypeCheckers[i4]; + if (typeof checker !== "function") { + printWarning( + "Invalid argument supplied to oneOfType. Expected an array of check functions, but received " + getPostfixForTypeWarning(checker) + " at index " + i4 + "." + ); + return emptyFunctionThatReturnsNull; + } + } + function validate(props2, propName, componentName, location, propFullName) { + var expectedTypes = []; + for (var i5 = 0; i5 < arrayOfTypeCheckers.length; i5++) { + var checker2 = arrayOfTypeCheckers[i5]; + var checkerResult = checker2(props2, propName, componentName, location, propFullName, ReactPropTypesSecret); + if (checkerResult == null) { + return null; + } + if (checkerResult.data && has(checkerResult.data, "expectedType")) { + expectedTypes.push(checkerResult.data.expectedType); } - }; - throw new TypeError(s5 ? "Object is not iterable." : "Symbol.iterator is not defined."); - }; - __read2 = function(o3, n2) { - var m5 = typeof Symbol === "function" && o3[Symbol.iterator]; - if (!m5) - return o3; - var i4 = m5.call(o3), r3, ar = [], e4; - try { - while ((n2 === void 0 || n2-- > 0) && !(r3 = i4.next()).done) - ar.push(r3.value); - } catch (error) { - e4 = { error }; - } finally { - try { - if (r3 && !r3.done && (m5 = i4["return"])) - m5.call(i4); - } finally { - if (e4) - throw e4.error; } + var expectedTypesMessage = expectedTypes.length > 0 ? ", expected one of type [" + expectedTypes.join(", ") + "]" : ""; + return new PropTypeError("Invalid " + location + " `" + propFullName + "` supplied to " + ("`" + componentName + "`" + expectedTypesMessage + ".")); } - return ar; - }; - __spread2 = function() { - for (var ar = [], i4 = 0; i4 < arguments.length; i4++) - ar = ar.concat(__read2(arguments[i4])); - return ar; - }; - __spreadArrays2 = function() { - for (var s5 = 0, i4 = 0, il = arguments.length; i4 < il; i4++) - s5 += arguments[i4].length; - for (var r3 = Array(s5), k5 = 0, i4 = 0; i4 < il; i4++) - for (var a5 = arguments[i4], j4 = 0, jl = a5.length; j4 < jl; j4++, k5++) - r3[k5] = a5[j4]; - return r3; - }; - __spreadArray3 = function(to, from, pack) { - if (pack || arguments.length === 2) - for (var i4 = 0, l3 = from.length, ar; i4 < l3; i4++) { - if (ar || !(i4 in from)) { - if (!ar) - ar = Array.prototype.slice.call(from, 0, i4); - ar[i4] = from[i4]; + return createChainableTypeChecker(validate); + } + function createNodeChecker() { + function validate(props2, propName, componentName, location, propFullName) { + if (!isNode2(props2[propName])) { + return new PropTypeError("Invalid " + location + " `" + propFullName + "` supplied to " + ("`" + componentName + "`, expected a ReactNode.")); + } + return null; + } + return createChainableTypeChecker(validate); + } + function invalidValidatorError(componentName, location, propFullName, key2, type) { + return new PropTypeError( + (componentName || "React class") + ": " + location + " type `" + propFullName + "." + key2 + "` is invalid; it must be a function, usually from the `prop-types` package, but received `" + type + "`." + ); + } + function createShapeTypeChecker(shapeTypes) { + function validate(props2, propName, componentName, location, propFullName) { + var propValue = props2[propName]; + var propType = getPropType(propValue); + if (propType !== "object") { + return new PropTypeError("Invalid " + location + " `" + propFullName + "` of type `" + propType + "` " + ("supplied to `" + componentName + "`, expected `object`.")); + } + for (var key2 in shapeTypes) { + var checker = shapeTypes[key2]; + if (typeof checker !== "function") { + return invalidValidatorError(componentName, location, propFullName, key2, getPreciseType(checker)); + } + var error = checker(propValue, key2, componentName, location, propFullName + "." + key2, ReactPropTypesSecret); + if (error) { + return error; } } - return to.concat(ar || Array.prototype.slice.call(from)); - }; - __await2 = function(v3) { - return this instanceof __await2 ? (this.v = v3, this) : new __await2(v3); - }; - __asyncGenerator2 = function(thisArg, _arguments, generator) { - if (!Symbol.asyncIterator) - throw new TypeError("Symbol.asyncIterator is not defined."); - var g4 = generator.apply(thisArg, _arguments || []), i4, q5 = []; - return i4 = {}, verb("next"), verb("throw"), verb("return"), i4[Symbol.asyncIterator] = function() { - return this; - }, i4; - function verb(n2) { - if (g4[n2]) - i4[n2] = function(v3) { - return new Promise(function(a5, b4) { - q5.push([n2, v3, a5, b4]) > 1 || resume(n2, v3); - }); - }; + return null; } - function resume(n2, v3) { - try { - step(g4[n2](v3)); - } catch (e4) { - settle(q5[0][3], e4); + return createChainableTypeChecker(validate); + } + function createStrictShapeTypeChecker(shapeTypes) { + function validate(props2, propName, componentName, location, propFullName) { + var propValue = props2[propName]; + var propType = getPropType(propValue); + if (propType !== "object") { + return new PropTypeError("Invalid " + location + " `" + propFullName + "` of type `" + propType + "` " + ("supplied to `" + componentName + "`, expected `object`.")); + } + var allKeys = assign2({}, props2[propName], shapeTypes); + for (var key2 in allKeys) { + var checker = shapeTypes[key2]; + if (has(shapeTypes, key2) && typeof checker !== "function") { + return invalidValidatorError(componentName, location, propFullName, key2, getPreciseType(checker)); + } + if (!checker) { + return new PropTypeError( + "Invalid " + location + " `" + propFullName + "` key `" + key2 + "` supplied to `" + componentName + "`.\nBad object: " + JSON.stringify(props2[propName], null, " ") + "\nValid keys: " + JSON.stringify(Object.keys(shapeTypes), null, " ") + ); + } + var error = checker(propValue, key2, componentName, location, propFullName + "." + key2, ReactPropTypesSecret); + if (error) { + return error; + } } + return null; } - function step(r3) { - r3.value instanceof __await2 ? Promise.resolve(r3.value.v).then(fulfill, reject) : settle(q5[0][2], r3); + return createChainableTypeChecker(validate); + } + function isNode2(propValue) { + switch (typeof propValue) { + case "number": + case "string": + case "undefined": + return true; + case "boolean": + return !propValue; + case "object": + if (Array.isArray(propValue)) { + return propValue.every(isNode2); + } + if (propValue === null || isValidElement(propValue)) { + return true; + } + var iteratorFn = getIteratorFn(propValue); + if (iteratorFn) { + var iterator = iteratorFn.call(propValue); + var step; + if (iteratorFn !== propValue.entries) { + while (!(step = iterator.next()).done) { + if (!isNode2(step.value)) { + return false; + } + } + } else { + while (!(step = iterator.next()).done) { + var entry = step.value; + if (entry) { + if (!isNode2(entry[1])) { + return false; + } + } + } + } + } else { + return false; + } + return true; + default: + return false; } - function fulfill(value) { - resume("next", value); + } + function isSymbol(propType, propValue) { + if (propType === "symbol") { + return true; } - function reject(value) { - resume("throw", value); + if (!propValue) { + return false; } - function settle(f4, v3) { - if (f4(v3), q5.shift(), q5.length) - resume(q5[0][0], q5[0][1]); + if (propValue["@@toStringTag"] === "Symbol") { + return true; } - }; - __asyncDelegator2 = function(o3) { - var i4, p3; - return i4 = {}, verb("next"), verb("throw", function(e4) { - throw e4; - }), verb("return"), i4[Symbol.iterator] = function() { - return this; - }, i4; - function verb(n2, f4) { - i4[n2] = o3[n2] ? function(v3) { - return (p3 = !p3) ? { value: __await2(o3[n2](v3)), done: false } : f4 ? f4(v3) : v3; - } : f4; + if (typeof Symbol === "function" && propValue instanceof Symbol) { + return true; } - }; - __asyncValues2 = function(o3) { - if (!Symbol.asyncIterator) - throw new TypeError("Symbol.asyncIterator is not defined."); - var m5 = o3[Symbol.asyncIterator], i4; - return m5 ? m5.call(o3) : (o3 = typeof __values2 === "function" ? __values2(o3) : o3[Symbol.iterator](), i4 = {}, verb("next"), verb("throw"), verb("return"), i4[Symbol.asyncIterator] = function() { - return this; - }, i4); - function verb(n2) { - i4[n2] = o3[n2] && function(v3) { - return new Promise(function(resolve, reject) { - v3 = o3[n2](v3), settle(resolve, reject, v3.done, v3.value); - }); - }; + return false; + } + function getPropType(propValue) { + var propType = typeof propValue; + if (Array.isArray(propValue)) { + return "array"; } - function settle(resolve, reject, d5, v3) { - Promise.resolve(v3).then(function(v4) { - resolve({ value: v4, done: d5 }); - }, reject); + if (propValue instanceof RegExp) { + return "object"; } - }; - __makeTemplateObject2 = function(cooked, raw) { - if (Object.defineProperty) { - Object.defineProperty(cooked, "raw", { value: raw }); - } else { - cooked.raw = raw; + if (isSymbol(propType, propValue)) { + return "symbol"; } - return cooked; - }; - var __setModuleDefault = Object.create ? function(o3, v3) { - Object.defineProperty(o3, "default", { enumerable: true, value: v3 }); - } : function(o3, v3) { - o3["default"] = v3; - }; - __importStar2 = function(mod) { - if (mod && mod.__esModule) - return mod; - var result = {}; - if (mod != null) { - for (var k5 in mod) - if (k5 !== "default" && Object.prototype.hasOwnProperty.call(mod, k5)) - __createBinding2(result, mod, k5); + return propType; + } + function getPreciseType(propValue) { + if (typeof propValue === "undefined" || propValue === null) { + return "" + propValue; } - __setModuleDefault(result, mod); - return result; - }; - __importDefault2 = function(mod) { - return mod && mod.__esModule ? mod : { "default": mod }; - }; - __classPrivateFieldGet2 = function(receiver, state, kind, f4) { - if (kind === "a" && !f4) - throw new TypeError("Private accessor was defined without a getter"); - if (typeof state === "function" ? receiver !== state || !f4 : !state.has(receiver)) - throw new TypeError("Cannot read private member from an object whose class did not declare it"); - return kind === "m" ? f4 : kind === "a" ? f4.call(receiver) : f4 ? f4.value : state.get(receiver); - }; - __classPrivateFieldSet2 = function(receiver, state, value, kind, f4) { - if (kind === "m") - throw new TypeError("Private method is not writable"); - if (kind === "a" && !f4) - throw new TypeError("Private accessor was defined without a setter"); - if (typeof state === "function" ? receiver !== state || !f4 : !state.has(receiver)) - throw new TypeError("Cannot write private member to an object whose class did not declare it"); - return kind === "a" ? f4.call(receiver, value) : f4 ? f4.value = value : state.set(receiver, value), value; - }; - __classPrivateFieldIn2 = function(state, receiver) { - if (receiver === null || typeof receiver !== "object" && typeof receiver !== "function") - throw new TypeError("Cannot use 'in' operator on non-object"); - return typeof state === "function" ? receiver === state : state.has(receiver); - }; - exporter("__extends", __extends2); - exporter("__assign", __assign3); - exporter("__rest", __rest3); - exporter("__decorate", __decorate2); - exporter("__param", __param2); - exporter("__esDecorate", __esDecorate2); - exporter("__runInitializers", __runInitializers2); - exporter("__propKey", __propKey2); - exporter("__setFunctionName", __setFunctionName2); - exporter("__metadata", __metadata2); - exporter("__awaiter", __awaiter2); - exporter("__generator", __generator2); - exporter("__exportStar", __exportStar2); - exporter("__createBinding", __createBinding2); - exporter("__values", __values2); - exporter("__read", __read2); - exporter("__spread", __spread2); - exporter("__spreadArrays", __spreadArrays2); - exporter("__spreadArray", __spreadArray3); - exporter("__await", __await2); - exporter("__asyncGenerator", __asyncGenerator2); - exporter("__asyncDelegator", __asyncDelegator2); - exporter("__asyncValues", __asyncValues2); - exporter("__makeTemplateObject", __makeTemplateObject2); - exporter("__importStar", __importStar2); - exporter("__importDefault", __importDefault2); - exporter("__classPrivateFieldGet", __classPrivateFieldGet2); - exporter("__classPrivateFieldSet", __classPrivateFieldSet2); - exporter("__classPrivateFieldIn", __classPrivateFieldIn2); - }); + var propType = getPropType(propValue); + if (propType === "object") { + if (propValue instanceof Date) { + return "date"; + } else if (propValue instanceof RegExp) { + return "regexp"; + } + } + return propType; + } + function getPostfixForTypeWarning(value) { + var type = getPreciseType(value); + switch (type) { + case "array": + case "object": + return "an " + type; + case "boolean": + case "date": + case "regexp": + return "a " + type; + default: + return type; + } + } + function getClassName(propValue) { + if (!propValue.constructor || !propValue.constructor.name) { + return ANONYMOUS; + } + return propValue.constructor.name; + } + ReactPropTypes.checkPropTypes = checkPropTypes; + ReactPropTypes.resetWarningCache = checkPropTypes.resetWarningCache; + ReactPropTypes.PropTypes = ReactPropTypes; + return ReactPropTypes; + }; + } +}); + +// node_modules/prop-types/index.js +var require_prop_types = __commonJS({ + "node_modules/prop-types/index.js"(exports, module2) { + if (true) { + ReactIs = require_react_is(); + throwOnDirectAccess = true; + module2.exports = require_factoryWithTypeCheckers()(ReactIs.isElement, throwOnDirectAccess); + } else { + module2.exports = null(); + } + var ReactIs; + var throwOnDirectAccess; + } +}); + +// node_modules/attr-accept/dist/es/index.js +var require_es = __commonJS({ + "node_modules/attr-accept/dist/es/index.js"(exports) { + "use strict"; + exports.__esModule = true; + exports.default = function(file, acceptedFiles) { + if (file && acceptedFiles) { + var acceptedFilesArray = Array.isArray(acceptedFiles) ? acceptedFiles : acceptedFiles.split(","); + var fileName = file.name || ""; + var mimeType = (file.type || "").toLowerCase(); + var baseMimeType = mimeType.replace(/\/.*$/, ""); + return acceptedFilesArray.some(function(type) { + var validType = type.trim().toLowerCase(); + if (validType.charAt(0) === ".") { + return fileName.toLowerCase().endsWith(validType); + } else if (validType.endsWith("/*")) { + return baseMimeType === validType.replace(/\/.*$/, ""); + } + return mimeType === validType; + }); + } + return true; + }; } }); @@ -7328,7 +8129,7 @@ var require_localforage = __commonJS({ var DETECT_BLOB_SUPPORT_STORE = "local-forage-detect-blob-support"; var supportsBlobs = void 0; var dbContexts = {}; - var toString2 = Object.prototype.toString; + var toString3 = Object.prototype.toString; var READ_ONLY = "readonly"; var READ_WRITE = "readwrite"; function _binStringToArrayBuffer(bin) { @@ -7705,7 +8506,7 @@ var require_localforage = __commonJS({ var dbInfo; self2.ready().then(function() { dbInfo = self2._dbInfo; - if (toString2.call(value) === "[object Blob]") { + if (toString3.call(value) === "[object Blob]") { return _checkBlobSupport(dbInfo.db).then(function(blobSupport) { if (blobSupport) { return value; @@ -8759,7 +9560,7 @@ var require_localforage = __commonJS({ } return false; }; - var isArray = Array.isArray || function(arg) { + var isArray2 = Array.isArray || function(arg) { return Object.prototype.toString.call(arg) === "[object Array]"; }; var DefinedDrivers = {}; @@ -8788,13 +9589,13 @@ var require_localforage = __commonJS({ }); }; } - function extend() { + function extend2() { for (var i4 = 1; i4 < arguments.length; i4++) { var arg = arguments[i4]; if (arg) { for (var _key in arg) { if (arg.hasOwnProperty(_key)) { - if (isArray(arg[_key])) { + if (isArray2(arg[_key])) { arguments[0][_key] = arg[_key].slice(); } else { arguments[0][_key] = arg[_key]; @@ -8818,8 +9619,8 @@ var require_localforage = __commonJS({ } } } - this._defaultConfig = extend({}, DefaultConfig); - this._config = extend({}, this._defaultConfig, options); + this._defaultConfig = extend2({}, DefaultConfig); + this._config = extend2({}, this._defaultConfig, options); this._driverSet = null; this._initDriver = null; this._ready = false; @@ -8937,7 +9738,7 @@ var require_localforage = __commonJS({ }; LocalForage2.prototype.setDriver = function setDriver(drivers, callback, errorCallback) { var self2 = this; - if (!isArray(drivers)) { + if (!isArray2(drivers)) { drivers = [drivers]; } var supportedDrivers = this._getSupportedDrivers(drivers); @@ -8995,7 +9796,7 @@ var require_localforage = __commonJS({ return !!DriverSupport[driverName]; }; LocalForage2.prototype._extend = function _extend(libraryMethodsAndProperties) { - extend(this, libraryMethodsAndProperties); + extend2(this, libraryMethodsAndProperties); }; LocalForage2.prototype._getSupportedDrivers = function _getSupportedDrivers(drivers) { var supportedDrivers = []; @@ -11432,41 +12233,42 @@ var TooltipViewManager = class { } update(update) { if (update.focusChanged && !update.view.hasFocus) { - let input2 = update.state.facet(this.facet); - for (let t4 of this.tooltipViews) + const input2 = update.state.facet(this.facet); + for (const t4 of this.tooltipViews) t4.dom.remove(); this.input = input2; this.tooltips = []; this.tooltipViews = []; return true; } - let input = update.state.facet(this.facet); - let tooltips2 = input.filter((x5) => x5); + const input = update.state.facet(this.facet); + const tooltips2 = input.filter((x5) => x5); if (input === this.input) { - for (let t4 of this.tooltipViews) + for (const t4 of this.tooltipViews) if (t4.update) t4.update(update); return false; } - let tooltipViews = []; + const tooltipViews = []; for (let i4 = 0; i4 < tooltips2.length; i4++) { - let tip = tooltips2[i4], known = -1; + const tip = tooltips2[i4]; + let known = -1; if (!tip) continue; for (let i5 = 0; i5 < this.tooltips.length; i5++) { - let other = this.tooltips[i5]; + const other = this.tooltips[i5]; if (other && other.create == tip.create) known = i5; } if (known < 0) { tooltipViews[i4] = this.createTooltipView(tip); } else { - let tooltipView = tooltipViews[i4] = this.tooltipViews[known]; + const tooltipView = tooltipViews[i4] = this.tooltipViews[known]; if (tooltipView.update) tooltipView.update(update); } } - for (let t4 of this.tooltipViews) + for (const t4 of this.tooltipViews) if (tooltipViews.indexOf(t4) < 0) t4.dom.remove(); this.input = input; @@ -11499,7 +12301,7 @@ var tooltipPlugin = import_view.ViewPlugin.fromClass( this.lastTransaction = 0; this.measureTimeout = -1; var _a2; - let config = view.state.facet(tooltipConfig); + const config = view.state.facet(tooltipConfig); this.position = config.position; this.parent = config.parent; this.classes = view.themeClasses; @@ -11541,7 +12343,7 @@ var tooltipPlugin = import_view.ViewPlugin.fromClass( observeIntersection() { if (this.intersectionObserver) { this.intersectionObserver.disconnect(); - for (let tooltip of this.manager.tooltipViews) + for (const tooltip of this.manager.tooltipViews) this.intersectionObserver.observe(tooltip.dom); } } @@ -11555,14 +12357,14 @@ var tooltipPlugin = import_view.ViewPlugin.fromClass( update(update) { if (update.transactions.length) this.lastTransaction = Date.now(); - let updated = this.manager.update(update); + const updated = this.manager.update(update); if (updated) this.observeIntersection(); let shouldMeasure = updated || update.geometryChanged; - let newConfig = update.state.facet(tooltipConfig); + const newConfig = update.state.facet(tooltipConfig); if (newConfig.position != this.position) { this.position = newConfig.position; - for (let t4 of this.manager.tooltipViews) + for (const t4 of this.manager.tooltipViews) t4.dom.style.position = this.position; shouldMeasure = true; } @@ -11571,7 +12373,7 @@ var tooltipPlugin = import_view.ViewPlugin.fromClass( this.container.remove(); this.parent = newConfig.parent; this.createContainer(); - for (let t4 of this.manager.tooltipViews) + for (const t4 of this.manager.tooltipViews) this.container.appendChild(t4.dom); shouldMeasure = true; } else if (this.parent && this.view.themeClasses != this.classes) { @@ -11581,10 +12383,10 @@ var tooltipPlugin = import_view.ViewPlugin.fromClass( this.maybeMeasure(); } createTooltip(tooltip) { - let tooltipView = tooltip.create(this.view); + const tooltipView = tooltip.create(this.view); tooltipView.dom.classList.add("cm-tooltip"); if (tooltip.arrow && !tooltipView.dom.querySelector(".cm-tooltip > .cm-tooltip-arrow")) { - let arrow = document.createElement("div"); + const arrow = document.createElement("div"); arrow.className = "cm-tooltip-arrow"; tooltipView.dom.appendChild(arrow); } @@ -11601,18 +12403,18 @@ var tooltipPlugin = import_view.ViewPlugin.fromClass( "resize", this.measureSoon ); - for (let { dom } of this.manager.tooltipViews) + for (const { dom } of this.manager.tooltipViews) dom.remove(); (_b2 = this.intersectionObserver) == null ? void 0 : _b2.disconnect(); clearTimeout(this.measureTimeout); } readMeasure() { - let editor = this.view.dom.getBoundingClientRect(); + const editor = this.view.dom.getBoundingClientRect(); return { editor, parent: this.parent ? this.container.getBoundingClientRect() : editor, pos: this.manager.tooltips.map((t4, i4) => { - let tv = this.manager.tooltipViews[i4]; + const tv = this.manager.tooltipViews[i4]; return tv.getCoords ? tv.getCoords(t4.pos) : this.view.coordsAtPos(t4.pos); }), size: this.manager.tooltipViews.map( @@ -11625,33 +12427,33 @@ var tooltipPlugin = import_view.ViewPlugin.fromClass( }; } writeMeasure(measured) { - let { editor, space } = measured; - let others = []; + const { editor, space } = measured; + const others = []; for (let i4 = 0; i4 < this.manager.tooltips.length; i4++) { - let tooltip = this.manager.tooltips[i4], tView = this.manager.tooltipViews[i4], { dom } = tView; - let pos = measured.pos[i4], size = measured.size[i4]; + const tooltip = this.manager.tooltips[i4], tView = this.manager.tooltipViews[i4], { dom } = tView; + const pos = measured.pos[i4], size = measured.size[i4]; if (!pos || pos.bottom <= Math.max(editor.top, space.top) || pos.top >= Math.min(editor.bottom, space.bottom) || pos.right < Math.max(editor.left, space.left) - 0.1 || pos.left > Math.min(editor.right, space.right) + 0.1) { dom.style.top = Outside; continue; } - let arrow = tooltip.arrow ? tView.dom.querySelector(".cm-tooltip-arrow") : null; - let arrowHeight = arrow ? 7 /* Size */ : 0; - let width = size.right - size.left, height = size.bottom - size.top; - let offset = tView.offset || noOffset, ltr = this.view.textDirection == import_view.Direction.LTR; - let left = size.width > space.right - space.left ? ltr ? space.left : space.right - size.width : ltr ? Math.min( - pos.left - (arrow ? 14 /* Offset */ : 0) + offset.x, + const arrow = tooltip.arrow ? tView.dom.querySelector(".cm-tooltip-arrow") : null; + const arrowHeight = arrow ? 7 /* Size */ : 0; + const width = size.right - size.left, height = size.bottom - size.top; + const offset2 = tView.offset || noOffset, ltr = this.view.textDirection == import_view.Direction.LTR; + const left = size.width > space.right - space.left ? ltr ? space.left : space.right - size.width : ltr ? Math.min( + pos.left - (arrow ? 14 /* Offset */ : 0) + offset2.x, space.right - width ) : Math.max( space.left, - pos.left - width + (arrow ? 14 /* Offset */ : 0) - offset.x + pos.left - width + (arrow ? 14 /* Offset */ : 0) - offset2.x ); let above = !!tooltip.above; - if (!tooltip.strictSide && (above ? pos.top - (size.bottom - size.top) - offset.y < space.top : pos.bottom + (size.bottom - size.top) + offset.y > space.bottom) && above == space.bottom - pos.bottom > pos.top - space.top) + if (!tooltip.strictSide && (above ? pos.top - (size.bottom - size.top) - offset2.y < space.top : pos.bottom + (size.bottom - size.top) + offset2.y > space.bottom) && above == space.bottom - pos.bottom > pos.top - space.top) above = !above; - let top = above ? pos.top - height - arrowHeight - offset.y : pos.bottom + arrowHeight + offset.y; - let right = left + width; + let top = above ? pos.top - height - arrowHeight - offset2.y : pos.bottom + arrowHeight + offset2.y; + const right = left + width; if (tView.overlap !== true) { - for (let r3 of others) + for (const r3 of others) if (r3.left < right && r3.right > left && r3.top < top + height && r3.bottom > top) top = above ? r3.top - height - 2 - arrowHeight : r3.bottom + arrowHeight + 2; } @@ -11661,11 +12463,11 @@ var tooltipPlugin = import_view.ViewPlugin.fromClass( if (typeof dims === "undefined") { const dims2 = { top: 0, left: 0 }; } - const frames = win.parent.document.getElementsByTagName("iframe"); + const frames2 = win.parent.document.getElementsByTagName("iframe"); let frame; let found = false; - for (let i5 = 0, len = frames.length; i5 < len; i5++) { - frame = frames[i5]; + for (let i5 = 0, len = frames2.length; i5 < len; i5++) { + frame = frames2[i5]; if (frame.contentWindow == win) { found = true; break; @@ -11692,7 +12494,7 @@ var tooltipPlugin = import_view.ViewPlugin.fromClass( dom.style.left = viewCoords.left + left + "px"; } if (arrow) - arrow.style.left = `${pos.left + (ltr ? offset.x : -offset.x) - (left + 14 /* Offset */ - 7 /* Size */)}px`; + arrow.style.left = `${pos.left + (ltr ? offset2.x : -offset2.x) - (left + 14 /* Offset */ - 7 /* Size */)}px`; if (tView.overlap !== true) others.push({ left, top, right, bottom: top + height }); dom.classList.toggle("cm-tooltip-above", above); @@ -11708,7 +12510,7 @@ var tooltipPlugin = import_view.ViewPlugin.fromClass( if (this.inView != this.view.inView) { this.inView = this.view.inView; if (!this.inView) - for (let tv of this.manager.tooltipViews) + for (const tv of this.manager.tooltipViews) tv.dom.style.top = Outside; } } @@ -11804,7 +12606,7 @@ var HoverTooltipHost = class { return new HoverTooltipHost(view); } createHostedView(tooltip) { - let hostedView = tooltip.create(this.view); + const hostedView = tooltip.create(this.view); hostedView.dom.classList.add("cm-tooltip-section"); this.dom.appendChild(hostedView.dom); if (this.mounted && hostedView.mount) @@ -11812,14 +12614,14 @@ var HoverTooltipHost = class { return hostedView; } mount(view) { - for (let hostedView of this.manager.tooltipViews) { + for (const hostedView of this.manager.tooltipViews) { if (hostedView.mount) hostedView.mount(view); } this.mounted = true; } positioned() { - for (let hostedView of this.manager.tooltipViews) { + for (const hostedView of this.manager.tooltipViews) { if (hostedView.positioned) hostedView.positioned(); } @@ -11831,7 +12633,7 @@ var HoverTooltipHost = class { var showHoverTooltipHost = showTooltip.compute( [showHoverTooltip], (state) => { - let tooltips2 = state.facet(showHoverTooltip).filter((t4) => t4); + const tooltips2 = state.facet(showHoverTooltip).filter((t4) => t4); if (tooltips2.length === 0) return null; return { @@ -11880,7 +12682,7 @@ var HoverPlugin = class { this.hoverTimeout = -1; if (this.active) return; - let hovered = Date.now() - this.lastMove.time; + const hovered = Date.now() - this.lastMove.time; if (hovered < this.hoverTime) this.hoverTimeout = setTimeout(this.checkHover, this.hoverTime - hovered); else @@ -11888,22 +12690,22 @@ var HoverPlugin = class { } startHover() { clearTimeout(this.restartTimeout); - let { lastMove } = this; - let pos = this.view.contentDOM.contains(lastMove.target) ? this.view.posAtCoords(lastMove) : null; + const { lastMove } = this; + const pos = this.view.contentDOM.contains(lastMove.target) ? this.view.posAtCoords(lastMove) : null; if (pos == null) return; - let posCoords = this.view.coordsAtPos(pos); + const posCoords = this.view.coordsAtPos(pos); if (posCoords == null || lastMove.y < posCoords.top || lastMove.y > posCoords.bottom || lastMove.x < posCoords.left - this.view.defaultCharacterWidth || lastMove.x > posCoords.right + this.view.defaultCharacterWidth) return; - let bidi = this.view.bidiSpans(this.view.state.doc.lineAt(pos)).find((s5) => s5.from <= pos && s5.to >= pos); - let rtl = bidi && bidi.dir == import_view.Direction.RTL ? -1 : 1; - let open = this.source( + const bidi = this.view.bidiSpans(this.view.state.doc.lineAt(pos)).find((s5) => s5.from <= pos && s5.to >= pos); + const rtl = bidi && bidi.dir == import_view.Direction.RTL ? -1 : 1; + const open = this.source( this.view, pos, lastMove.x < posCoords.left ? -rtl : rtl ); if (open == null ? void 0 : open.then) { - let pending = this.pending = { pos }; + const pending = this.pending = { pos }; open.then( (result) => { if (this.pending == pending) { @@ -11928,9 +12730,9 @@ var HoverPlugin = class { }; if (this.hoverTimeout < 0) this.hoverTimeout = setTimeout(this.checkHover, this.hoverTime); - let tooltip = this.active; + const tooltip = this.active; if (tooltip && !isInTooltip(this.lastMove.target) || this.pending) { - let { pos } = tooltip || this.pending, end = (_a2 = tooltip == null ? void 0 : tooltip.end) != null ? _a2 : pos; + const { pos } = tooltip || this.pending, end = (_a2 = tooltip == null ? void 0 : tooltip.end) != null ? _a2 : pos; if (pos == end ? this.view.posAtCoords(this.lastMove) != pos : !isOverRange( this.view, pos, @@ -11963,15 +12765,15 @@ function isInTooltip(elt) { return false; } function isOverRange(view, from, to, x5, y5, margin) { - let range = document.createRange(); - let fromDOM = view.domAtPos(from), toDOM = view.domAtPos(to); + const range = document.createRange(); + const fromDOM = view.domAtPos(from), toDOM = view.domAtPos(to); range.setEnd(toDOM.node, toDOM.offset); range.setStart(fromDOM.node, fromDOM.offset); - let rects = range.getClientRects(); + const rects = range.getClientRects(); range.detach(); for (let i4 = 0; i4 < rects.length; i4++) { - let rect = rects[i4]; - let dist = Math.max( + const rect = rects[i4]; + const dist = Math.max( rect.top - y5, y5 - rect.bottom, rect.left - x5, @@ -11983,15 +12785,15 @@ function isOverRange(view, from, to, x5, y5, margin) { return false; } function hoverTooltip(source, options = {}) { - let setHover = import_state.StateEffect.define(); - let hoverState = import_state.StateField.define({ + const setHover = import_state.StateEffect.define(); + const hoverState = import_state.StateField.define({ create() { return null; }, update(value, tr) { if (value && options.hideOnChange && (tr.docChanged || tr.selection)) return null; - for (let effect of tr.effects) { + for (const effect of tr.effects) { if (effect.is(setHover)) { return effect.value; } @@ -11999,10 +12801,10 @@ function hoverTooltip(source, options = {}) { return null; } if (value && tr.docChanged) { - let newPos = tr.changes.mapPos(value.pos, -1, import_state.MapMode.TrackDel); + const newPos = tr.changes.mapPos(value.pos, -1, import_state.MapMode.TrackDel); if (newPos == null) return null; - let copy = Object.assign(/* @__PURE__ */ Object.create(null), value); + const copy = Object.assign(/* @__PURE__ */ Object.create(null), value); copy.pos = newPos; if (value.end != null) copy.end = tr.changes.mapPos(value.end); @@ -12255,11 +13057,11 @@ function M(n2, u4) { }); } function N(l3, u4, i4, t4, r3, o3, f4, e4) { - var s5, a5, h5, y5 = i4.props, p3 = u4.props, d5 = u4.type, _9 = 0; + var s5, a5, h5, y5 = i4.props, p3 = u4.props, d5 = u4.type, _12 = 0; if ("svg" === d5 && (r3 = true), null != o3) { - for (; _9 < o3.length; _9++) - if ((s5 = o3[_9]) && "setAttribute" in s5 == !!d5 && (d5 ? s5.localName === d5 : 3 === s5.nodeType)) { - l3 = s5, o3[_9] = null; + for (; _12 < o3.length; _12++) + if ((s5 = o3[_12]) && "setAttribute" in s5 == !!d5 && (d5 ? s5.localName === d5 : 3 === s5.nodeType)) { + l3 = s5, o3[_12] = null; break; } } @@ -12273,16 +13075,16 @@ function N(l3, u4, i4, t4, r3, o3, f4, e4) { else { if (o3 = o3 && n.call(l3.childNodes), a5 = (y5 = i4.props || c).dangerouslySetInnerHTML, h5 = p3.dangerouslySetInnerHTML, !e4) { if (null != o3) - for (y5 = {}, _9 = 0; _9 < l3.attributes.length; _9++) - y5[l3.attributes[_9].name] = l3.attributes[_9].value; + for (y5 = {}, _12 = 0; _12 < l3.attributes.length; _12++) + y5[l3.attributes[_12].name] = l3.attributes[_12].value; (h5 || a5) && (h5 && (a5 && h5.__html == a5.__html || h5.__html === l3.innerHTML) || (l3.innerHTML = h5 && h5.__html || "")); } if (H(l3, p3, y5, r3, e4), h5) u4.__k = []; - else if (_9 = u4.props.children, x(l3, Array.isArray(_9) ? _9 : [_9], u4, i4, t4, r3 && "foreignObject" !== d5, o3, f4, o3 ? o3[0] : i4.__k && b(i4, 0), e4), null != o3) - for (_9 = o3.length; _9--; ) - null != o3[_9] && v(o3[_9]); - e4 || ("value" in p3 && void 0 !== (_9 = p3.value) && (_9 !== l3.value || "progress" === d5 && !_9 || "option" === d5 && _9 !== y5.value) && T(l3, "value", _9, y5.value, false), "checked" in p3 && void 0 !== (_9 = p3.checked) && _9 !== l3.checked && T(l3, "checked", _9, y5.checked, false)); + else if (_12 = u4.props.children, x(l3, Array.isArray(_12) ? _12 : [_12], u4, i4, t4, r3 && "foreignObject" !== d5, o3, f4, o3 ? o3[0] : i4.__k && b(i4, 0), e4), null != o3) + for (_12 = o3.length; _12--; ) + null != o3[_12] && v(o3[_12]); + e4 || ("value" in p3 && void 0 !== (_12 = p3.value) && (_12 !== l3.value || "progress" === d5 && !_12 || "option" === d5 && _12 !== y5.value) && T(l3, "value", _12, y5.value, false), "checked" in p3 && void 0 !== (_12 = p3.checked) && _12 !== l3.checked && T(l3, "checked", _12, y5.checked, false)); } return l3; } @@ -12868,28 +13670,28 @@ function createRoot(container) { // src/utils/codemirror.ts var import_language = require("@codemirror/language"); -var getActiveCM = () => { +var getActiveCM = (plugin) => { let rcm; - app.workspace.iterateLeaves((leaf) => { + plugin.app.workspace.iterateLeaves((leaf) => { var _a2; const cm = (_a2 = leaf.view.editor) == null ? void 0 : _a2.cm; if (cm == null ? void 0 : cm.hasFocus) { rcm = cm; return true; } - }, app.workspace["rootSplit"]); + }, plugin.app.workspace["rootSplit"]); return rcm; }; -var getActiveMarkdownView = () => { +var getActiveMarkdownView = (plugin) => { let rv; - app.workspace.iterateLeaves((leaf) => { + plugin.app.workspace.iterateLeaves((leaf) => { var _a2; const cm = (_a2 = leaf.view.editor) == null ? void 0 : _a2.cm; if (cm == null ? void 0 : cm.hasFocus) { rv = leaf.view; return true; } - }, app.workspace["rootSplit"]); + }, plugin.app.workspace["rootSplit"]); return rv; }; function iterateTreeAtPos(pos, state, iterateFns) { @@ -12946,11 +13748,11 @@ var calloutField = import_state2.StateField.define({ if (tr.state.field(flowTypeStateField, false) != "doc") { return value; } - let builder = new import_state2.RangeSetBuilder(); - let nodes2 = []; + const builder = new import_state2.RangeSetBuilder(); + const nodes = []; (0, import_language2.syntaxTree)(tr.state).iterate({ enter: ({ name, from, to }) => { - nodes2.push({ name, from, to }); + nodes.push({ name, from, to }); } }); const nextQuote = (ns, to) => { @@ -12969,10 +13771,10 @@ var calloutField = import_state2.StateField.define({ previous.next(); } let index = 0; - nodes2.map(({ name, from, to }) => { + nodes.map(({ name, from, to }) => { if (name.contains("HyperMD-callout")) { const existingCallout = previousSpecs[index]; - const endQuote = nextQuote(nodes2, to); + const endQuote = nextQuote(nodes, to); const lineStart = tr.state.doc.lineAt(from).number; const lineEnd = tr.state.doc.lineAt(endQuote).number; if (existingCallout) { @@ -13044,6 +13846,60 @@ var calloutBlock = (range, text2, id2) => import_view2.Decoration.widget({ block: true }); +// src/types/types.ts +var eventTypes = { + activePathChange: "mkmd-active-path", + frameSelected: "mkmd-active-frame", + frameLayerSelected: "mkmd-frame-layer", + refreshView: "mkmd-refresh-view", + revealFile: "mkmd-reveal-file", + collapseFolders: "mkmd-collapse-folders", + toggleBacklinks: "mkmd-toggle-backlinks", + metadataChange: "mkmd-tags-change", + vaultChange: "mkmd-vault-change", + mdbChange: "mkmd-mdb-change", + spacesChange: "mkmd-spaces-change", + frameChange: "mkmd-frame-change", + updateSections: "mkmd-update-sections", + settingsChanged: "mkmd-settings-changed", + spawnPortal: "mkmd-portal-spawn", + loadPortal: "mkmd-portal-load", + openFilePortal: "mkmd-portal-file", + focusPortal: "mkmd-portal-focus" +}; + +// src/dispatch/flowDispatch.ts +var createFlowEditorInElement = (id2, leaf, source, el, type, path, from, to) => { + const evt = new CustomEvent(eventTypes.spawnPortal, { + detail: { id: id2, leaf, source, el, path, from, to, type } + }); + activeWindow.dispatchEvent(evt); +}; +var loadFlowEditorByDOM = (el, view, id2) => { + const evt = new CustomEvent(eventTypes.loadPortal, { + detail: { id: id2, el, view } + }); + activeWindow.dispatchEvent(evt); +}; +var focusFlowEditor = (id2, top) => { + const evt = new CustomEvent(eventTypes.focusPortal, { + detail: { id: id2, parent: false, top } + }); + activeWindow.dispatchEvent(evt); +}; +var focusFlowEditorParent = (id2, top) => { + const evt = new CustomEvent(eventTypes.focusPortal, { + detail: { id: id2, parent: true, top } + }); + activeWindow.dispatchEvent(evt); +}; +var openFileFlowEditor = (file, source) => { + const evt = new CustomEvent(eventTypes.openFilePortal, { + detail: { file, source } + }); + activeWindow.dispatchEvent(evt); +}; + // src/i18n.ts var T4 = class { constructor() { @@ -13093,23 +13949,22 @@ var T4 = class { toggleItalics: "Toggle Italics", openSpaces: "Open Spaces", reloadSpaces: "Reload Spaces", - loadBackupSpace: "Restore Spaces from Backup", - backupSpace: "Backup Space", blink: "Blink", - openFileContext: "Open Context Explorer", - convertFolderNote: "Convert to Folder Note", + openFileContext: "Open Explorer", + convertFolderNote: "Convert to Space", revealFile: "Reveal File in Spaces", + releaseNotes: "Release Notes", toggleBacklinks: "Toggle Backlinks", collapseAllFolders: "Collapse All Folders", addFileSpace: "Add File to Space", removeFileSpace: "Remove File from Space" }, menu: { - fileMetadata: "File Metadata", + fileMetadata: "None", fileMetadataDescription: "This note only", openFilePane: "Open in a new pane", rename: "Rename", - changeToFolderNote: "Convert to Folder Note", + changeToFolderNote: "New Space from Note", moveFile: "Move file to...", duplicate: "Make a copy", edit: "Edit", @@ -13140,8 +13995,9 @@ var T4 = class { importDataview: "Import All Dataview Properties", saveAllProperties: "Save All Properties to Files", mergeProperties: "Merge Properties", - openTag: "Open Tag", - removeTag: "Remove Tag", + openSpace: "Open Space", + removeFromSpace: "Remove from Space", + editCode: "Edit Code", deleteProperty: "Delete Property", hideProperty: "Hide Property", unhideProperty: "Unhide Property", @@ -13151,6 +14007,7 @@ var T4 = class { deleteRow: "Delete Item", collapseAll: "Collapse All", customSort: "Custom Sort", + groupSpaces: "Group Spaces", fileNameSortAlphaAsc: "File Name (A to Z)", fileNameSortAlphaDesc: "File Name (Z to A)", createdTimeSortAsc: "Created Time (new to old)", @@ -13160,16 +14017,15 @@ var T4 = class { spaces: "Spaces", tags: "Tags", manageHiddenFiles: "Manage Hidden Files", - unpinSpace: "Unpin", - pinSpace: "Pinned", - homeSpace: "Home", + unpinSpace: "Remove from Waypoints", + pinSpace: "Add to Waypoints", deleteSpace: "Delete Space", changeColor: "Change Color", changePropertyType: "Change Type", deleteFiles: "Delete Files", createFolderSpace: "Create Space from Folder", folder: "Folder", - syncToContext: "Sync to Context" + syncToContext: "Add to Space" }, buttons: { moreOptions: "More Options", @@ -13180,11 +14036,9 @@ var T4 = class { removeBanner: "Remove Cover", rename: "Change Name", saveSpace: "Save Space", - createFolder: "New Folder", + createFolder: "New Space", createNote: "New Note", createCanvas: "New Canvas", - createSection: "New Space", - createSectionSmart: "New Smart Space", cancel: "Cancel", search: "Search", delete: "Delete", @@ -13192,7 +14046,7 @@ var T4 = class { openFlow: "Open Flow", hideFlow: "Hide Flow", openLink: "Open Link", - addTag: "Add Tag", + addToSpace: "Add to Space", tag: "Tag", syncFields: "Sync Properties", convertTable: "Convert to Markdown", @@ -13261,12 +14115,24 @@ var T4 = class { tag: { label: "Tag" }, + object: { + label: "Object" + }, context: { - label: "Context" + label: "Relation" }, image: { label: "Image" }, + color: { + label: "Color" + }, + space: { + label: "Space" + }, + icon: { + label: "Icon" + }, fileProperty: { label: "Look Up", createdTime: "Created", @@ -13301,13 +14167,15 @@ var T4 = class { optionItemSelectPlaceholder: "Select Option", viewItemSelectPlaceholder: "Select View", tagItemSelectPlaceholder: "Find Tag", + spaceSelectPlaceholder: "Select Space", propertyItemSelectPlaceholder: "Select Property", sortItemSelectPlaceholder: "Select Sort", filterItemSelectPlaceholder: "Select Filter", syncFrontmatterProperty: "Sync Frontmatter Property", newProperty: "New Property", propertyType: "Type", - propertyContext: "Context", + propertyValueSpace: "Space", + propertyValueProperty: "Property", dateFormat: "Date Format", propertyFileProp: "Property", multiple: "Multiple", @@ -13355,7 +14223,6 @@ var T4 = class { sectionDataview: "Dataview", sectionAppearance: "Appearance", sectionContext: "Context", - sectionSync: "Sync and Backup", inlineStickerMenu: { name: "Inline Stickers", desc: "Add inline stickers by typing :" @@ -13413,8 +14280,8 @@ var T4 = class { desc: "Hide the frontmatter when inline context is enabled" }, openFileContext: { - name: "Auto Open Context Explorer", - desc: "Automatically open context explorer panel in the right panel" + name: "Auto Open Explorer", + desc: "Automatically open explorer panel in the right panel" }, folderNote: { name: "Enable Folder Note", @@ -13436,10 +14303,6 @@ var T4 = class { name: "Line Numbers", desc: "Display line numbers" }, - compactMode: { - name: "Compact Mode", - desc: "Display the Spaces menu in a more compact format" - }, contexts: { name: "Contexts", desc: `Contexts allows you to have full control over the metadata of your files` @@ -13497,22 +14360,10 @@ var T4 = class { name: "Text and Highlight Colors \u{1F9EA}", desc: `Select text color and highlight color, (this may change in the future because of the limitations with HTML and Obsidian)` }, - spaceAutoBackup: { - name: "Auto Backup", - desc: "Automatically backup spaces, you can restore backups using the Load Backup command" - }, - spaceAutoBackupInterval: { - name: "Auto Backup Interval", - desc: "Automatically backup spaces file every x minutes" - }, spaceRowHeight: { name: "Row Height", desc: "The height for each row in spaces (in pixels), default is 28" }, - syncTimeout: { - name: "Sync Timeout", - desc: "Number of seconds to wait for Spaces file to sync. Space changes will not save during this timeout" - }, makeChar: { name: "Flow Menu Trigger", desc: "Character to open the Flow Menu" @@ -13567,2031 +14418,6722 @@ var T4 = class { }; var i18n_default = new T4().texts; -// src/utils/icons.ts -var defaultIconForExtension = (type, solid) => { - if (!type) - return solid ? uiIconSet["mk-ui-folder-solid"] : uiIconSet["mk-ui-folder"]; - switch (type) { - case "png": - case "jpg": - case "jpeg": - case "svg": - return uiIconSet["mk-make-image"]; - break; - case "mov": - case "webm": - return uiIconSet["mk-ui-video"]; - break; - case "canvas": - return uiIconSet["mk-ui-canvas"]; - default: - return solid ? uiIconSet["mk-ui-file-solid"] : uiIconSet["mk-ui-file"]; +// src/utils/array.ts +var insert = (arr, index, newItem) => !index || index <= 0 ? [ + newItem, + ...arr +] : [ + ...arr.slice(0, index), + newItem, + ...arr.slice(index) +]; +var insertMulti = (arr, index, newItem) => !index || index <= 0 ? [ + ...newItem, + ...arr +] : [ + ...arr.slice(0, index), + ...newItem, + ...arr.slice(index) +]; +var uniq = (a5) => [...new Set(a5)]; +var uniqCaseInsensitive = (a5) => [ + ...new Map(a5.map((s5) => [s5.toLowerCase(), s5])).values() +]; +var uniqueNameFromString = (name, cols) => { + let newName = name; + if (cols.includes(newName)) { + let append = 1; + while (cols.includes(newName)) { + newName = name + append.toString(); + append += 1; + } } + return newName; +}; +var onlyUniqueProp = (prop) => (value, index, self2) => { + return self2.findIndex((v3) => value[prop] == v3[prop]) === index; +}; +var orderArrayByArray = (array, order, key2) => { + return array.sort(function(a5, b4) { + const A4 = order.indexOf(a5[key2]), B5 = order.indexOf(b4[key2]); + if (A4 > B5) { + if (A4 != -1 && B5 == -1) { + return -1; + } + return 1; + } else { + if (B5 != -1 && A4 == -1) { + return 1; + } + return -1; + } + }); }; -var uiIconSet = { - "mk-ui-close": ` - - `, - "mk-ui-flow-hover": ` - - `, - "mk-ui-folder": ` - - `, - "mk-ui-open-link": ` - - `, - "mk-ui-file": ` - -`, - "mk-ui-expand": ` - -`, - "mk-ui-new-folder": ``, - "mk-ui-new-note": ``, - "mk-ui-collapse": ` - -`, - "mk-ui-options": ` - -`, - "mk-ui-plus": ` - -`, - "mk-ui-collapse-sm": ` - -`, - "mk-ui-search": ` - - -`, - "mk-ui-view-options": ` - - -`, - "mk-ui-clear": ` - - -`, - "mk-ui-new-file": ` - - -`, - "mk-ui-blink": ` - - - - -`, - "mk-ui-spaces": ` - -`, - "mk-ui-home": ` - -`, - "mk-ui-tags": ` - -`, - "mk-ui-handle": ` - - - - - - - -`, - "mk-ui-new-space": ` - - -`, - "mk-ui-file-solid": ` - - - -`, - "mk-ui-folder-solid": ` - - -`, - "mk-ui-sync": ` - - -`, - "mk-ui-stack": ` - - -`, - "mk-ui-cut": ` - - -`, - "mk-ui-backlink": ` - - -`, - "mk-ui-canvas": ` - - - - - -`, - "mk-ui-video": ` - - -`, - "mk-ui-edit": ` - - -`, - "mk-ui-list": ` - - - -`, - "mk-ui-build": ` - - -`, - "mk-ui-check": ` - - -`, - "mk-ui-layout": ` - - -`, - "mk-ui-colors": ` - - -`, - "mk-make-todo": ` - - - -`, - "mk-make-list": ` - - - - - - - -`, - "mk-make-ordered": ` - - - - - - - -`, - "mk-make-h1": ` - - - -`, - "mk-make-h2": ` - - - -`, - "mk-make-h3": ` - - - -`, - "mk-make-quote": ` - - - - - -`, - "mk-make-hr": ` - - -`, - "mk-make-link": ` - - -`, - "mk-make-image": ` - - - - - -`, - "mk-make-codeblock": ` - - - - -`, - "mk-make-callout": ` - - - -`, - "mk-make-note": ` - - - - - -`, - "mk-make-flow": ` - - -`, - "mk-make-tag": ` - - -`, - "mk-make-table": ` - - - - -`, - "mk-make-date": ` - - -`, - "mk-make-indent": ` - - - - - -`, - "mk-make-unindent": ` - - - - - -`, - "mk-mark-strong": ` - - -`, - "mk-mark-em": ` - -`, - "mk-mark-strikethrough": ` - - - -`, - "mk-mark-code": ` - - - - -`, - "mk-mark-link": ` - -`, - "mk-mark-blocklink": ` - - - - -`, - "mk-mark-highlight": ` - - - - - -`, - "mk-make-attach": ` - - - - -`, - "mk-make-keyboard": ` - - - -`, - "mk-make-slash": ` - - - -`, - "mk-make-style": ` - -`, - "mk-mark-color": ` - - -` +// src/utils/strings.ts +function ensureArray(value) { + if (Array.isArray(value)) { + return value; + } + return []; +} +function ensureStringValueFromSet(value, values, defaultValue2) { + const _v = ensureString(value); + return values.some((f4) => f4 == _v) ? _v : defaultValue2; +} +function ensureString(value) { + if (!value) + return ""; + if (typeof value !== "string") { + return value.toString(); + } + return value; +} +function ensureBoolean(value) { + if (!value) + return false; + return true; +} +function parseStickerString(input) { + if (!input) { + return ["", ""]; + } + const match2 = input.match(/^(.*?)\s*\/\/\s*(.*)$/); + if (match2) { + return [match2[1], match2[2]]; + } else { + return ["", input]; + } +} +var emojiFromString = (emoji) => { + let html; + try { + html = unifiedToNative(emoji); + } catch (e4) { + html = emoji; + } + return html; }; -var mkLogo = ` - - -`; -var lucideIcons = [ - "accessibility", - "activity", - "air-vent", - "airplay", - "alarm-check", - "alarm-clock-off", - "alarm-clock", - "alarm-minus", - "alarm-plus", - "album", - "alert-circle", - "alert-octagon", - "alert-triangle", - "align-center-horizontal", - "align-center-vertical", - "align-center", - "align-end-horizontal", - "align-end-vertical", - "align-horizontal-distribute-center", - "align-horizontal-distribute-end", - "align-horizontal-distribute-start", - "align-horizontal-justify-center", - "align-horizontal-justify-end", - "align-horizontal-justify-start", - "align-horizontal-space-around", - "align-horizontal-space-between", - "align-justify", - "align-left", - "align-right", - "align-start-horizontal", - "align-start-vertical", - "align-vertical-distribute-center", - "align-vertical-distribute-end", - "align-vertical-distribute-start", - "align-vertical-justify-center", - "align-vertical-justify-end", - "align-vertical-justify-start", - "align-vertical-space-around", - "align-vertical-space-between", - "anchor", - "angry", - "annoyed", - "aperture", - "apple", - "archive-restore", - "archive", - "armchair", - "arrow-big-down", - "arrow-big-left", - "arrow-big-right", - "arrow-big-up", - "arrow-down-circle", - "arrow-down-left-from-circle", - "arrow-down-left", - "arrow-down-right-from-circle", - "arrow-down-right", - "arrow-down", - "arrow-left-circle", - "arrow-left-right", - "arrow-left", - "arrow-right-circle", - "arrow-right", - "arrow-up-circle", - "arrow-up-down", - "arrow-up-left-from-circle", - "arrow-up-left", - "arrow-up-right-from-circle", - "arrow-up-right", - "arrow-up", - "asterisk", - "at-sign", - "atom", - "award", - "axe", - "axis-3d", - "baby", - "backpack", - "baggage-claim", - "ban", - "banana", - "banknote", - "bar-chart-2", - "bar-chart-3", - "bar-chart-4", - "bar-chart-horizontal", - "bar-chart", - "baseline", - "bath", - "battery-charging", - "battery-full", - "battery-low", - "battery-medium", - "battery-warning", - "battery", - "beaker", - "bean-off", - "bean", - "bed-double", - "bed-single", - "bed", - "beef", - "beer", - "bell-minus", - "bell-off", - "bell-plus", - "bell-ring", - "bell", - "bike", - "binary", - "bird", - "bitcoin", - "blinds", - "bluetooth-connected", - "bluetooth-off", - "bluetooth-searching", - "bluetooth", - "bold", - "bomb", - "bone", - "book-copy", - "book-down", - "book-key", - "book-lock", - "book-marked", - "book-minus", - "book-open-check", - "book-open", - "book-plus", - "book-template", - "book-up", - "book-x", - "book", - "bookmark-minus", - "bookmark-plus", - "bookmark", - "bot", - "box-select", - "box", - "boxes", - "brain-circuit", - "brain-cog", - "brain", - "briefcase", - "brush", - "bug", - "building-2", - "building", - "bus", - "cake", - "calculator", - "calendar-check-2", - "calendar-check", - "calendar-clock", - "calendar-days", - "calendar-heart", - "calendar-minus", - "calendar-off", - "calendar-plus", - "calendar-range", - "calendar-search", - "calendar-x2", - "calendar-x", - "calendar", - "camera-off", - "camera", - "candy-off", - "candy", - "car", - "carrot", - "case-lower", - "case-sensitive", - "case-upper", - "cast", - "castle", - "cat", - "check-check", - "check-circle-2", - "check-circle", - "check-square", - "check", - "chef-hat", - "cherry", - "chevron-down-square", - "chevron-down", - "chevron-first", - "chevron-last", - "chevron-left-square", - "chevron-left", - "chevron-right-square", - "chevron-right", - "chevron-up-square", - "chevron-up", - "chevrons-down-up", - "chevrons-down", - "chevrons-left-right", - "chevrons-left", - "chevrons-right-left", - "chevrons-right", - "chevrons-up-down", - "chevrons-up", - "chrome", - "church", - "cigarette-off", - "cigarette", - "circle-dot", - "circle-ellipsis", - "circle-equal", - "circle-off", - "circle-slash-2", - "circle-slash", - "circle", - "circuit-board", - "citrus", - "clapperboard", - "clipboard-check", - "clipboard-copy", - "clipboard-edit", - "clipboard-list", - "clipboard-paste", - "clipboard-signature", - "clipboard-type", - "clipboard-x", - "clipboard", - "clock-1", - "clock-10", - "clock-11", - "clock-12", - "clock-2", - "clock-3", - "clock-4", - "clock-5", - "clock-6", - "clock-7", - "clock-8", - "clock-9", - "clock", - "cloud-cog", - "cloud-drizzle", - "cloud-fog", - "cloud-hail", - "cloud-lightning", - "cloud-moon-rain", - "cloud-moon", - "cloud-off", - "cloud-rain-wind", - "cloud-rain", - "cloud-snow", - "cloud-sun-rain", - "cloud-sun", - "cloud", - "cloudy", - "clover", - "code-2", - "code", - "codepen", - "codesandbox", - "coffee", - "cog", - "coins", - "columns", - "command", - "compass", - "component", - "concierge-bell", - "construction", - "contact", - "contrast", - "cookie", - "copy-check", - "copy-minus", - "copy-plus", - "copy-slash", - "copy-x", - "copy", - "copyleft", - "copyright", - "corner-down-left", - "corner-down-right", - "corner-left-down", - "corner-left-up", - "corner-right-down", - "corner-right-up", - "corner-up-left", - "corner-up-right", - "cpu", - "creative-commons", - "credit-card", - "croissant", - "crop", - "cross", - "crosshair", - "crown", - "cup-soda", - "curly-braces", - "currency", - "database-backup", - "database", - "delete", - "diamond", - "dice-1", - "dice-2", - "dice-3", - "dice-4", - "dice-5", - "dice-6", - "dices", - "diff", - "disc-2", - "disc", - "divide-circle", - "divide-square", - "divide", - "dna-off", - "dna", - "dog", - "dollar-sign", - "door-closed", - "door-open", - "download-cloud", - "download", - "dribbble", - "droplet", - "droplets", - "drumstick", - "dumbbell", - "ear-off", - "ear", - "edit-2", - "edit-3", - "edit", - "egg-fried", - "egg-off", - "egg", - "equal-not", - "equal", - "eraser", - "euro", - "expand", - "external-link", - "eye-off", - "eye", - "facebook", - "factory", - "fan", - "fast-forward", - "feather", - "figma", - "file-archive", - "file-audio-2", - "file-audio", - "file-axis-3d", - "file-badge-2", - "file-badge", - "file-bar-chart-2", - "file-bar-chart", - "file-box", - "file-check-2", - "file-check", - "file-clock", - "file-code", - "file-cog-2", - "file-cog", - "file-diff", - "file-digit", - "file-down", - "file-edit", - "file-heart", - "file-image", - "file-input", - "file-json-2", - "file-json", - "file-key-2", - "file-key", - "file-line-chart", - "file-lock-2", - "file-lock", - "file-minus-2", - "file-minus", - "file-output", - "file-pie-chart", - "file-plus-2", - "file-plus", - "file-question", - "file-scan", - "file-search-2", - "file-search", - "file-signature", - "file-spreadsheet", - "file-symlink", - "file-terminal", - "file-text", - "file-type-2", - "file-type", - "file-up", - "file-video-2", - "file-video", - "file-volume-2", - "file-volume", - "file-warning", - "file-x2", - "file-x", - "file", - "files", - "film", - "filter-x", - "filter", - "fingerprint", - "fish-off", - "fish", - "flag-off", - "flag-triangle-left", - "flag-triangle-right", - "flag", - "flame", - "flashlight-off", - "flashlight", - "flask-conical-off", - "flask-conical", - "flask-round", - "flip-horizontal-2", - "flip-horizontal", - "flip-vertical-2", - "flip-vertical", - "flower-2", - "flower", - "focus", - "folder-archive", - "folder-check", - "folder-clock", - "folder-closed", - "folder-cog-2", - "folder-cog", - "folder-down", - "folder-edit", - "folder-git-2", - "folder-git", - "folder-heart", - "folder-input", - "folder-key", - "folder-lock", - "folder-minus", - "folder-open", - "folder-output", - "folder-plus", - "folder-search-2", - "folder-search", - "folder-symlink", - "folder-tree", - "folder-up", - "folder-x", - "folder", - "folders", - "footprints", - "forklift", - "form-input", - "forward", - "frame", - "framer", - "frown", - "fuel", - "function-square", - "gamepad-2", - "gamepad", - "gauge", - "gavel", - "gem", - "ghost", - "gift", - "git-branch-plus", - "git-branch", - "git-commit", - "git-compare", - "git-fork", - "git-merge", - "git-pull-request-closed", - "git-pull-request-draft", - "git-pull-request", - "github", - "gitlab", - "glass-water", - "glasses", - "globe-2", - "globe", - "grab", - "graduation-cap", - "grape", - "grid", - "grip-horizontal", - "grip-vertical", - "grip", - "hammer", - "hand-metal", - "hand", - "hard-drive", - "hard-hat", - "hash", - "haze", - "heading-1", - "heading-2", - "heading-3", - "heading-4", - "heading-5", - "heading-6", - "heading", - "headphones", - "heart-crack", - "heart-handshake", - "heart-off", - "heart-pulse", - "heart", - "help-circle", - "helping-hand", - "hexagon", - "highlighter", - "history", - "home", - "hop-off", - "hop", - "hotel", - "hourglass", - "ice-cream-2", - "ice-cream", - "image-minus", - "image-off", - "image-plus", - "image", - "import", - "inbox", - "indent", - "indian-rupee", - "infinity", - "info", - "inspect", - "instagram", - "italic", - "japanese-yen", - "joystick", - "key", - "keyboard", - "lamp-ceiling", - "lamp-desk", - "lamp-floor", - "lamp-wall-down", - "lamp-wall-up", - "lamp", - "landmark", - "languages", - "laptop-2", - "laptop", - "lasso-select", - "lasso", - "laugh", - "layers", - "layout-dashboard", - "layout-grid", - "layout-list", - "layout-template", - "layout", - "leaf", - "library", - "life-buoy", - "lightbulb-off", - "lightbulb", - "line-chart", - "link-2off", - "link-2", - "link", - "linkedin", - "list-checks", - "list-end", - "list-minus", - "list-music", - "list-ordered", - "list-plus", - "list-start", - "list-tree", - "list-video", - "list-x", - "list", - "loader-2", - "loader", - "locate-fixed", - "locate-off", - "locate", - "lock", - "log-in", - "log-out", - "luggage", - "magnet", - "mail-check", - "mail-minus", - "mail-open", - "mail-plus", - "mail-question", - "mail-search", - "mail-warning", - "mail-x", - "mail", - "mailbox", - "mails", - "map-pin-off", - "map-pin", - "map", - "martini", - "maximize-2", - "maximize", - "medal", - "megaphone-off", - "megaphone", - "meh", - "menu", - "message-circle", - "message-square-dashed", - "message-square-plus", - "message-square", - "messages-square", - "mic-2", - "mic-off", - "mic", - "microscope", - "microwave", - "milestone", - "milk-off", - "milk", - "minimize-2", - "minimize", - "minus-circle", - "minus-square", - "minus", - "monitor-off", - "monitor-smartphone", - "monitor-speaker", - "monitor", - "moon", - "more-horizontal", - "more-vertical", - "mountain-snow", - "mountain", - "mouse-pointer-2", - "mouse-pointer-click", - "mouse-pointer", - "mouse", - "move-3d", - "move-diagonal-2", - "move-diagonal", - "move-horizontal", - "move-vertical", - "move", - "music-2", - "music-3", - "music-4", - "music", - "navigation-2off", - "navigation-2", - "navigation-off", - "navigation", - "network", - "newspaper", - "nfc", - "nut-off", - "nut", - "octagon", - "option", - "orbit", - "outdent", - "package-2", - "package-check", - "package-minus", - "package-open", - "package-plus", - "package-search", - "package-x", - "package", - "paint-bucket", - "paintbrush-2", - "paintbrush", - "palette", - "palmtree", - "paperclip", - "parking-circle-off", - "parking-circle", - "parking-square-off", - "parking-square", - "party-popper", - "pause-circle", - "pause-octagon", - "pause", - "pen-tool", - "pencil", - "percent", - "person-standing", - "phone-call", - "phone-forwarded", - "phone-incoming", - "phone-missed", - "phone-off", - "phone-outgoing", - "phone", - "picture-in-picture-2", - "picture-in-picture", - "pie-chart", - "piggy-bank", - "pilcrow", - "pill", - "pin-off", - "pin", - "pipette", - "pizza", - "plane-landing", - "plane-takeoff", - "plane", - "play-circle", - "play", - "plug-2", - "plug-zap", - "plug", - "plus-circle", - "plus-square", - "plus", - "pocket", - "podcast", - "pointer", - "pound-sterling", - "power-off", - "power", - "printer", - "puzzle", - "qr-code", - "quote", - "radio-receiver", - "radio-tower", - "radio", - "rat", - "receipt", - "rectangle-horizontal", - "rectangle-vertical", - "recycle", - "redo-2", - "redo", - "refresh-ccw", - "refresh-cw", - "refrigerator", - "regex", - "remove-formatting", - "repeat-1", - "repeat", - "replace-all", - "replace", - "reply-all", - "reply", - "rewind", - "rocket", - "rocking-chair", - "rotate-3d", - "rotate-ccw", - "rotate-cw", - "router", - "rss", - "ruler", - "russian-ruble", - "sailboat", - "salad", - "sandwich", - "save", - "scale-3d", - "scale", - "scaling", - "scan-face", - "scan-line", - "scan", - "school-2", - "school", - "scissors", - "screen-share-off", - "screen-share", - "scroll", - "search", - "send", - "separator-horizontal", - "separator-vertical", - "server-cog", - "server-crash", - "server-off", - "server", - "settings-2", - "settings", - "share-2", - "share", - "sheet", - "shield-alert", - "shield-check", - "shield-close", - "shield-off", - "shield-question", - "shield", - "ship", - "shirt", - "shopping-bag", - "shopping-cart", - "shovel", - "shower-head", - "shrink", - "shrub", - "shuffle", - "sidebar-close", - "sidebar-open", - "sidebar", - "sigma", - "signal-high", - "signal-low", - "signal-medium", - "signal-zero", - "signal", - "siren", - "skip-back", - "skip-forward", - "skull", - "slack", - "slice", - "sliders-horizontal", - "sliders", - "smartphone-charging", - "smartphone-nfc", - "smartphone", - "smile-plus", - "smile", - "snowflake", - "sofa", - "sort-asc", - "sort-desc", - "soup", - "space", - "speaker", - "spline", - "split-square-horizontal", - "split-square-vertical", - "sprout", - "square", - "stamp", - "star-half", - "star-off", - "star", - "step-back", - "step-forward", - "stethoscope", - "sticker", - "sticky-note", - "stop-circle", - "store", - "stretch-horizontal", - "stretch-vertical", - "strikethrough", - "subscript", - "subtitles", - "sun-dim", - "sun-medium", - "sun-moon", - "sun-snow", - "sun", - "sunrise", - "sunset", - "superscript", - "swiss-franc", - "switch-camera", - "sword", - "swords", - "syringe", - "table-2", - "table", - "tablet", - "tablets", - "tag", - "tags", - "target", - "tent", - "terminal-square", - "terminal", - "test-tube-2", - "test-tube", - "test-tubes", - "text-cursor-input", - "text-cursor", - "text-selection", - "text", - "thermometer-snowflake", - "thermometer-sun", - "thermometer", - "thumbs-down", - "thumbs-up", - "ticket", - "timer-off", - "timer-reset", - "timer", - "toggle-left", - "toggle-right", - "tornado", - "tower-control", - "toy-brick", - "train", - "trash-2", - "trash", - "tree-deciduous", - "tree-pine", - "trees", - "trello", - "trending-down", - "trending-up", - "triangle", - "trophy", - "truck", - "tv-2", - "tv", - "twitch", - "twitter", - "type", - "umbrella", - "underline", - "undo-2", - "undo", - "unlink-2", - "unlink", - "unlock", - "upload-cloud", - "upload", - "usb", - "user-check", - "user-cog", - "user-minus", - "user-plus", - "user-x", - "user", - "users", - "utensils-crossed", - "utensils", - "utility-pole", - "vegan", - "venetian-mask", - "verified", - "vibrate-off", - "vibrate", - "video-off", - "video", - "view", - "voicemail", - "volume-1", - "volume-2", - "volume-x", - "volume", - "vote", - "wallet", - "wand-2", - "wand", - "warehouse", - "watch", - "waves", - "webcam", - "webhook", - "wheat-off", - "wheat", - "whole-word", - "wifi-off", - "wifi", - "wind", - "wine-off", - "wine", - "wrap-text", - "wrench", - "x-circle", - "x-octagon", - "x-square", - "x", - "youtube", - "zap-off", - "zap", - "zoom-in", - "zoom-out" -]; +var unifiedToNative = (unified) => { + const unicodes = unified.split("-"); + const codePoints = unicodes.map((u4) => `0x${u4}`); + return String.fromCodePoint(...codePoints); +}; +var indexOfCharElseEOS = (char, str) => { + if (str.indexOf(char) > 0) + return str.indexOf(char); + return str.length; +}; +var spaceNameFromSpacePath = (contextPath, plugin) => { + var _a2, _b2; + return (_b2 = (_a2 = plugin.index.spacesIndex.get(contextPath)) == null ? void 0 : _a2.name) != null ? _b2 : contextPath; +}; +var spacePathFromName = (spaceName) => "spaces://" + encodeSpaceName(spaceName); +var encodeSpaceName = (spaceName) => spaceName.replace(/\//g, "+"); +var tagSpacePathFromTag = (tag) => "spaces://" + tag; +var wrapQuotes = (s5) => `"${s5}"`; +var removeQuotes = (s5) => { + if (!s5) + return s5; + const singleQuoteWithSemicolon = s5.startsWith("'") && (s5.endsWith("';") || s5.endsWith("'")); + const doubleQuoteWithSemicolon = s5.startsWith('"') && (s5.endsWith('";') || s5.endsWith('"')); + if (singleQuoteWithSemicolon || doubleQuoteWithSemicolon) { + s5 = s5.substring(1, s5.length - 1); + if (s5.endsWith('"') || s5.endsWith("'")) { + s5 = s5.substring(0, s5.length - 1); + } + return s5; + } else { + return s5; + } +}; +var filePathToString = (filename) => { + if (filename.lastIndexOf("/") != -1) { + if (filename.lastIndexOf(".") != -1) + return removeLeadingSlash( + filename.substring( + filename.lastIndexOf("/") + 1, + filename.lastIndexOf(".") + ) + ); + return filename.substring(filename.lastIndexOf("/") + 1); + } + if (filename.lastIndexOf(".") != -1) { + return filename.substring(0, filename.lastIndexOf(".")); + } + return filename; +}; +var stringFromTag = (string) => { + if (string.charAt(0) == "#") { + if (string.charAt(1) == "#") { + return string.substring(2, string.length); + } + return string.substring(1, string.length); + } + return string; +}; +var fileNameToString = (filename) => filename.substring(0, filename.lastIndexOf(".")) || filename; +var removeLeadingSlash = (path) => path.charAt(0) == "/" ? path.substring(1) : path; +var filePathToFolderPath = (filename) => removeLeadingSlash(filename.substring(0, filename.lastIndexOf("/"))) || filename; +var folderPathToString = (filename) => removeLeadingSlash(filename.substring(filename.lastIndexOf("/"))) || filename; +var pathDisplayName = (path, plugin) => { + if (!path) + return ""; + if (path.type == "vault") + return plugin.app.vault.getName(); + if ((path == null ? void 0 : path.type) == "folder") { + return folderPathToString(path.path); + } + if ((path == null ? void 0 : path.type) == "tag") + return stringFromTag(path.space); + if ((path == null ? void 0 : path.type) == "space") + return spaceNameFromSpacePath(path.space, plugin); + if (path.isRemote) { + return folderPathToString(path.path); + } + return path.path; +}; +var folderNotePathFromAFile = (settings, aFile) => !aFile ? null : settings.folderNoteInsideFolder ? `${aFile.path}/${aFile.name}.md` : aFile.parent == "/" ? `${aFile.name}.md` : `${aFile.parent}/${aFile.name}.md`; +var folderPathFromFolderNoteFile = (settings, aFile) => !aFile ? null : settings.folderNoteInsideFolder ? aFile.parent : `${aFile.parent}/${aFile.name}`; +var spacePathFromSpaceDefFile = (aFile) => !aFile ? null : "spaces://" + aFile.name; -// src/components/FlowEditor/FlowEditorHover.tsx -var FlowEditorHover = (props2) => { +// src/utils/parser.tsx +var parseSortStrat = (str) => { + const [a5, b4] = str.split("_"); + return { field: a5, asc: b4 == "asc", group: true }; +}; +var parseMultiString = (str) => { + var _a2; + return (_a2 = str == null ? void 0 : str.match(/(\\.|[^,])+/g)) != null ? _a2 : []; +}; +var parseLinkString = (string) => { + if (!string) + return ""; + const match2 = /\[\[(.*?)\]\]/g.exec(string); + const stringValue = (match2 == null ? void 0 : match2.length) > 1 ? match2[1].substring(0, indexOfCharElseEOS("|", match2[1])) : string; + if (stringValue) + return stringValue; + return string; +}; +var parseLinkDisplayString = (string) => { + return filePathToString(parseLinkString(string)); +}; + +// src/utils/serializer.ts +var serializeMultiString = (value) => value.join(","); +var serializeMultiDisplayString = (value) => value.join(", "); +var serializeSQLValues = (value) => value.join(", "); +var serializeSQLStatements = (value) => value.join("; "); +var serializeSQLFieldNames = (value) => value.join(","); + +// src/components/RemoteMarkdownView/FileView.tsx +var import_obsidian2 = require("obsidian"); + +// src/components/RemoteMarkdownView/FileLinkViewComponent.tsx +var import_obsidian = require("obsidian"); +var FileLinkViewComponent = (props2) => { + const ref2 = _2(null); + const [markdown, setMarkdown] = h2(""); + p2(() => { + if (ref2.current) + import_obsidian.MarkdownRenderer.render( + props2.plugin.app, + markdown, + ref2.current, + props2.path, + props2.component + ); + }, [markdown]); + p2(() => { + fetch(props2.path).then((res) => res.text()).then((f4) => setMarkdown(f4)); + }, [props2.path]); return /* @__PURE__ */ Cn.createElement("div", { - className: "mk-flowblock-menu" - }, props2.type == "file" ? /* @__PURE__ */ Cn.createElement(Cn.Fragment, null, props2.toggle && /* @__PURE__ */ Cn.createElement("div", { - "aria-label": i18n_default.buttons.toggleFlow, - onClick: props2.toggleFlow, - className: `mk-hover-button ${props2.toggleState ? "mk-toggle-on" : ""}`, - dangerouslySetInnerHTML: { - __html: uiIconSet["mk-ui-flow-hover"] + className: "markdown-preview-view markdown-rendered node-insert-event is-readable-line-width allow-fold-headings show-indentation-guide allow-fold-lists show-frontmatter" + }, /* @__PURE__ */ Cn.createElement("div", { + className: "markdown-preview-sizer markdown-preview-section", + ref: ref2 + })); +}; + +// src/components/RemoteMarkdownView/FileView.tsx +var FILE_VIEW_TYPE = "make-file-view"; +var FileLinkView = class extends import_obsidian2.ItemView { + constructor(leaf, plugin, viewType) { + super(leaf); + this.navigation = true; + this.plugin = plugin; + this.viewType = viewType; + } + getViewType() { + return FILE_VIEW_TYPE; + } + getDisplayText() { + return this.path; + } + async onClose() { + this.destroy(); + } + destroy() { + if (this.root) + this.root.unmount(); + } + async onOpen() { + this.destroy(); + } + async setState(state, result) { + this.path = state.path; + this.constructView(this.path); + const displayName = this.path; + await super.setState(state, result); + this.leaf.tabHeaderInnerTitleEl.innerText = displayName; + this.leaf.view.titleEl = displayName; + const headerEl = this.leaf.view.headerEl; + if (headerEl) { + headerEl.querySelector(".view-header-title").innerText = displayName; + } + result.history = true; + return; + } + getState() { + const state = super.getState(); + state.path = this.path; + return state; + } + constructView(path) { + this.destroy(); + this.root = createRoot(this.contentEl); + this.root.render( + /* @__PURE__ */ Cn.createElement("div", { + className: "markdown-reading-view" + }, /* @__PURE__ */ Cn.createElement(FileLinkViewComponent, { + path, + plugin: this.plugin, + component: this + })) + ); + } +}; + +// src/types/mframe.ts +var defaultFrameEditorProps = { editMode: 0 }; + +// src/utils/objects.ts +var replaceKeys = (object1, object2) => { + const newObject = {}; + for (const key2 in object1) { + const newKey = Object.prototype.hasOwnProperty.call(object2, key2) ? object2[key2] : key2; + newObject[newKey] = object1[key2]; + } + return newObject; +}; +function applyFunctionToObject(object, func) { + const newObject = {}; + for (const key2 in object) { + if (Object.prototype.hasOwnProperty.call(object, key2)) { + newObject[key2] = func(object[key2]); + } + } + return newObject; +} +var replaceKeysByValue = (object1, object2) => { + const reversedObject2 = {}; + for (const key2 in object2) { + reversedObject2[object2[key2]] = key2; + } + return replaceKeys(object1, reversedObject2); +}; + +// src/utils/uri.ts +var import_obsidian3 = require("obsidian"); + +// src/utils/regex.ts +var relativeURLRegex = /^[a-zA-Z0-9][^\\\\:|<\>"*?]*$/g; +var urlRegex = /https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*)/gi; + +// src/utils/uri.ts +var openPath = (plugin, _path, location) => { + if (!_path) + return; + const { type, path } = _path; + if (type == "file" || type == "folder") { + const afile = getAbstractFileAtPath(plugin, path); + if (afile) { + openAFile(afile, plugin, location); + } else { + if (type == "file") + createNewMarkdownFile( + plugin, + defaultNoteFolder(plugin, null), + path + ); + } + return; + } + if (type == "tag") { + openTagContext(path, plugin, location); + return; + } + if (type == "url") { + openURL(path, plugin, location); + return; + } +}; +var uriForFolder = (path) => { + if (path == "/") + return { + type: "vault", + basePath: path, + fullPath: path, + space: null, + path, + alias: null, + ref: null, + refStr: null, + refType: null, + query: null + }; + return { + type: "folder", + basePath: path, + fullPath: path, + space: null, + path, + alias: null, + ref: null, + refStr: null, + refType: null, + query: null + }; +}; +function uriByString(plugin, uri, source) { + if (!uri) + return null; + const fullPath = uri; + let refTypeChar = ""; + const parseQuery = (queryString) => { + const query2 = {}; + queryString.split("&").forEach((param) => { + const [key2, value] = param.split("="); + query2[decodeURIComponent(key2)] = decodeURIComponent(value); + }); + return query2; + }; + const mapRefType = (refTypeChar2) => { + if (refTypeChar2 === "^") + return "context"; + if (refTypeChar2 === "*") + return "frame"; + return null; + }; + let space = null; + let path = null; + let alias = null; + let reference = null; + let refType = null; + let query = null; + if (uri.startsWith("spaces://")) { + const spaceStr = uri.slice("spaces://".length); + if (spaceStr.charAt(0) == "#") { + const endIndex = spaceStr.lastIndexOf("/#"); + if (endIndex != -1) { + space = spaceStr.slice(0, endIndex); + uri = spaceStr.slice(endIndex); + } else { + space = spaceStr; + uri = "/"; + } + } else { + const spaceParts = spaceStr.split("/"); + space = spaceParts[0]; + uri = "/" + (spaceParts.slice(1).join("/") || ""); + } + } + const lastSlashIndex = uri.lastIndexOf("/"); + const lastHashIndex = uri.lastIndexOf("#"); + const lastPipeIndex = uri.lastIndexOf("|"); + const queryIndex = uri.lastIndexOf("?"); + if (queryIndex !== -1) { + query = parseQuery(uri.slice(queryIndex + 1)); + uri = uri.slice(0, queryIndex); + } + if (lastHashIndex !== -1 && lastHashIndex > lastSlashIndex) { + const refPart = uri.slice(lastHashIndex + 1); + refType = mapRefType(refPart[0]); + if (refType || lastHashIndex != lastSlashIndex + 1) { + refTypeChar = refPart[0]; + reference = refType ? refPart.slice(1) : refPart; + uri = uri.slice(0, lastHashIndex); + } + } + if (lastPipeIndex !== -1 && lastPipeIndex > lastSlashIndex) { + alias = uri.slice(lastPipeIndex + 1); + uri = uri.slice(0, lastPipeIndex); + } + path = uri; + return { + basePath: `${space ? `spaces://${space}` : path}`, + type: uriTypeByString(plugin, space, path, source), + space, + fullPath, + path: removeTrailingSlashFromFolder(uri), + alias, + ref: reference, + refType, + refStr: refTypeChar ? refTypeChar + reference : null, + query + }; +} +var uriTypeByString = (plugin, space, file, source) => { + if ((space == null ? void 0 : space.charAt(0)) == "#") { + return "tag"; + } + if ((space == null ? void 0 : space.length) > 0) { + return "space"; + } + if (file.charAt(file.length - 1) == "/") { + if (file == "/") + return "vault"; + return "folder"; + } + let portalFile; + if (source) { + portalFile = plugin.app.metadataCache.getFirstLinkpathDest(file, source); + } else { + portalFile = plugin.app.vault.getAbstractFileByPath(file); + } + if (portalFile instanceof import_obsidian3.TFolder) { + return "folder"; + } + if (portalFile instanceof import_obsidian3.TFile || file.match(relativeURLRegex)) { + return "file"; + } + if (file.match(urlRegex)) + return "url"; + return "unknown"; +}; + +// node_modules/acorn/dist/acorn.mjs +var astralIdentifierCodes = [509, 0, 227, 0, 150, 4, 294, 9, 1368, 2, 2, 1, 6, 3, 41, 2, 5, 0, 166, 1, 574, 3, 9, 9, 370, 1, 81, 2, 71, 10, 50, 3, 123, 2, 54, 14, 32, 10, 3, 1, 11, 3, 46, 10, 8, 0, 46, 9, 7, 2, 37, 13, 2, 9, 6, 1, 45, 0, 13, 2, 49, 13, 9, 3, 2, 11, 83, 11, 7, 0, 3, 0, 158, 11, 6, 9, 7, 3, 56, 1, 2, 6, 3, 1, 3, 2, 10, 0, 11, 1, 3, 6, 4, 4, 193, 17, 10, 9, 5, 0, 82, 19, 13, 9, 214, 6, 3, 8, 28, 1, 83, 16, 16, 9, 82, 12, 9, 9, 84, 14, 5, 9, 243, 14, 166, 9, 71, 5, 2, 1, 3, 3, 2, 0, 2, 1, 13, 9, 120, 6, 3, 6, 4, 0, 29, 9, 41, 6, 2, 3, 9, 0, 10, 10, 47, 15, 406, 7, 2, 7, 17, 9, 57, 21, 2, 13, 123, 5, 4, 0, 2, 1, 2, 6, 2, 0, 9, 9, 49, 4, 2, 1, 2, 4, 9, 9, 330, 3, 10, 1, 2, 0, 49, 6, 4, 4, 14, 9, 5351, 0, 7, 14, 13835, 9, 87, 9, 39, 4, 60, 6, 26, 9, 1014, 0, 2, 54, 8, 3, 82, 0, 12, 1, 19628, 1, 4706, 45, 3, 22, 543, 4, 4, 5, 9, 7, 3, 6, 31, 3, 149, 2, 1418, 49, 513, 54, 5, 49, 9, 0, 15, 0, 23, 4, 2, 14, 1361, 6, 2, 16, 3, 6, 2, 1, 2, 4, 101, 0, 161, 6, 10, 9, 357, 0, 62, 13, 499, 13, 983, 6, 110, 6, 6, 9, 4759, 9, 787719, 239]; +var astralIdentifierStartCodes = [0, 11, 2, 25, 2, 18, 2, 1, 2, 14, 3, 13, 35, 122, 70, 52, 268, 28, 4, 48, 48, 31, 14, 29, 6, 37, 11, 29, 3, 35, 5, 7, 2, 4, 43, 157, 19, 35, 5, 35, 5, 39, 9, 51, 13, 10, 2, 14, 2, 6, 2, 1, 2, 10, 2, 14, 2, 6, 2, 1, 68, 310, 10, 21, 11, 7, 25, 5, 2, 41, 2, 8, 70, 5, 3, 0, 2, 43, 2, 1, 4, 0, 3, 22, 11, 22, 10, 30, 66, 18, 2, 1, 11, 21, 11, 25, 71, 55, 7, 1, 65, 0, 16, 3, 2, 2, 2, 28, 43, 28, 4, 28, 36, 7, 2, 27, 28, 53, 11, 21, 11, 18, 14, 17, 111, 72, 56, 50, 14, 50, 14, 35, 349, 41, 7, 1, 79, 28, 11, 0, 9, 21, 43, 17, 47, 20, 28, 22, 13, 52, 58, 1, 3, 0, 14, 44, 33, 24, 27, 35, 30, 0, 3, 0, 9, 34, 4, 0, 13, 47, 15, 3, 22, 0, 2, 0, 36, 17, 2, 24, 20, 1, 64, 6, 2, 0, 2, 3, 2, 14, 2, 9, 8, 46, 39, 7, 3, 1, 3, 21, 2, 6, 2, 1, 2, 4, 4, 0, 19, 0, 13, 4, 159, 52, 19, 3, 21, 2, 31, 47, 21, 1, 2, 0, 185, 46, 42, 3, 37, 47, 21, 0, 60, 42, 14, 0, 72, 26, 38, 6, 186, 43, 117, 63, 32, 7, 3, 0, 3, 7, 2, 1, 2, 23, 16, 0, 2, 0, 95, 7, 3, 38, 17, 0, 2, 0, 29, 0, 11, 39, 8, 0, 22, 0, 12, 45, 20, 0, 19, 72, 264, 8, 2, 36, 18, 0, 50, 29, 113, 6, 2, 1, 2, 37, 22, 0, 26, 5, 2, 1, 2, 31, 15, 0, 328, 18, 16, 0, 2, 12, 2, 33, 125, 0, 80, 921, 103, 110, 18, 195, 2637, 96, 16, 1071, 18, 5, 4026, 582, 8634, 568, 8, 30, 18, 78, 18, 29, 19, 47, 17, 3, 32, 20, 6, 18, 689, 63, 129, 74, 6, 0, 67, 12, 65, 1, 2, 0, 29, 6135, 9, 1237, 43, 8, 8936, 3, 2, 6, 2, 1, 2, 290, 16, 0, 30, 2, 3, 0, 15, 3, 9, 395, 2309, 106, 6, 12, 4, 8, 8, 9, 5991, 84, 2, 70, 2, 1, 3, 0, 3, 1, 3, 3, 2, 11, 2, 0, 2, 6, 2, 64, 2, 3, 3, 7, 2, 6, 2, 27, 2, 3, 2, 4, 2, 0, 4, 6, 2, 339, 3, 24, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 7, 1845, 30, 7, 5, 262, 61, 147, 44, 11, 6, 17, 0, 322, 29, 19, 43, 485, 27, 757, 6, 2, 3, 2, 1, 2, 14, 2, 196, 60, 67, 8, 0, 1205, 3, 2, 26, 2, 1, 2, 0, 3, 0, 2, 9, 2, 3, 2, 0, 2, 0, 7, 0, 5, 0, 2, 0, 2, 0, 2, 2, 2, 1, 2, 0, 3, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 1, 2, 0, 3, 3, 2, 6, 2, 3, 2, 3, 2, 0, 2, 9, 2, 16, 6, 2, 2, 4, 2, 16, 4421, 42719, 33, 4153, 7, 221, 3, 5761, 15, 7472, 3104, 541, 1507, 4938, 6, 4191]; +var nonASCIIidentifierChars = "\u200C\u200D\xB7\u0300-\u036F\u0387\u0483-\u0487\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u0610-\u061A\u064B-\u0669\u0670\u06D6-\u06DC\u06DF-\u06E4\u06E7\u06E8\u06EA-\u06ED\u06F0-\u06F9\u0711\u0730-\u074A\u07A6-\u07B0\u07C0-\u07C9\u07EB-\u07F3\u07FD\u0816-\u0819\u081B-\u0823\u0825-\u0827\u0829-\u082D\u0859-\u085B\u0898-\u089F\u08CA-\u08E1\u08E3-\u0903\u093A-\u093C\u093E-\u094F\u0951-\u0957\u0962\u0963\u0966-\u096F\u0981-\u0983\u09BC\u09BE-\u09C4\u09C7\u09C8\u09CB-\u09CD\u09D7\u09E2\u09E3\u09E6-\u09EF\u09FE\u0A01-\u0A03\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A66-\u0A71\u0A75\u0A81-\u0A83\u0ABC\u0ABE-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AE2\u0AE3\u0AE6-\u0AEF\u0AFA-\u0AFF\u0B01-\u0B03\u0B3C\u0B3E-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B55-\u0B57\u0B62\u0B63\u0B66-\u0B6F\u0B82\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD7\u0BE6-\u0BEF\u0C00-\u0C04\u0C3C\u0C3E-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C62\u0C63\u0C66-\u0C6F\u0C81-\u0C83\u0CBC\u0CBE-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CE2\u0CE3\u0CE6-\u0CEF\u0CF3\u0D00-\u0D03\u0D3B\u0D3C\u0D3E-\u0D44\u0D46-\u0D48\u0D4A-\u0D4D\u0D57\u0D62\u0D63\u0D66-\u0D6F\u0D81-\u0D83\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2\u0DF3\u0E31\u0E34-\u0E3A\u0E47-\u0E4E\u0E50-\u0E59\u0EB1\u0EB4-\u0EBC\u0EC8-\u0ECE\u0ED0-\u0ED9\u0F18\u0F19\u0F20-\u0F29\u0F35\u0F37\u0F39\u0F3E\u0F3F\u0F71-\u0F84\u0F86\u0F87\u0F8D-\u0F97\u0F99-\u0FBC\u0FC6\u102B-\u103E\u1040-\u1049\u1056-\u1059\u105E-\u1060\u1062-\u1064\u1067-\u106D\u1071-\u1074\u1082-\u108D\u108F-\u109D\u135D-\u135F\u1369-\u1371\u1712-\u1715\u1732-\u1734\u1752\u1753\u1772\u1773\u17B4-\u17D3\u17DD\u17E0-\u17E9\u180B-\u180D\u180F-\u1819\u18A9\u1920-\u192B\u1930-\u193B\u1946-\u194F\u19D0-\u19DA\u1A17-\u1A1B\u1A55-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AB0-\u1ABD\u1ABF-\u1ACE\u1B00-\u1B04\u1B34-\u1B44\u1B50-\u1B59\u1B6B-\u1B73\u1B80-\u1B82\u1BA1-\u1BAD\u1BB0-\u1BB9\u1BE6-\u1BF3\u1C24-\u1C37\u1C40-\u1C49\u1C50-\u1C59\u1CD0-\u1CD2\u1CD4-\u1CE8\u1CED\u1CF4\u1CF7-\u1CF9\u1DC0-\u1DFF\u203F\u2040\u2054\u20D0-\u20DC\u20E1\u20E5-\u20F0\u2CEF-\u2CF1\u2D7F\u2DE0-\u2DFF\u302A-\u302F\u3099\u309A\uA620-\uA629\uA66F\uA674-\uA67D\uA69E\uA69F\uA6F0\uA6F1\uA802\uA806\uA80B\uA823-\uA827\uA82C\uA880\uA881\uA8B4-\uA8C5\uA8D0-\uA8D9\uA8E0-\uA8F1\uA8FF-\uA909\uA926-\uA92D\uA947-\uA953\uA980-\uA983\uA9B3-\uA9C0\uA9D0-\uA9D9\uA9E5\uA9F0-\uA9F9\uAA29-\uAA36\uAA43\uAA4C\uAA4D\uAA50-\uAA59\uAA7B-\uAA7D\uAAB0\uAAB2-\uAAB4\uAAB7\uAAB8\uAABE\uAABF\uAAC1\uAAEB-\uAAEF\uAAF5\uAAF6\uABE3-\uABEA\uABEC\uABED\uABF0-\uABF9\uFB1E\uFE00-\uFE0F\uFE20-\uFE2F\uFE33\uFE34\uFE4D-\uFE4F\uFF10-\uFF19\uFF3F"; +var nonASCIIidentifierStartChars = "\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0560-\u0588\u05D0-\u05EA\u05EF-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u0860-\u086A\u0870-\u0887\u0889-\u088E\u08A0-\u08C9\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u09FC\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0AF9\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58-\u0C5A\u0C5D\u0C60\u0C61\u0C80\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D04-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D54-\u0D56\u0D5F-\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E86-\u0E8A\u0E8C-\u0EA3\u0EA5\u0EA7-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u1711\u171F-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1878\u1880-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4C\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1C80-\u1C88\u1C90-\u1CBA\u1CBD-\u1CBF\u1CE9-\u1CEC\u1CEE-\u1CF3\u1CF5\u1CF6\u1CFA\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2118-\u211D\u2124\u2126\u2128\u212A-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309B-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312F\u3131-\u318E\u31A0-\u31BF\u31F0-\u31FF\u3400-\u4DBF\u4E00-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA7CA\uA7D0\uA7D1\uA7D3\uA7D5-\uA7D9\uA7F2-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA8FD\uA8FE\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uA9E0-\uA9E4\uA9E6-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB69\uAB70-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC"; +var reservedWords = { + 3: "abstract boolean byte char class double enum export extends final float goto implements import int interface long native package private protected public short static super synchronized throws transient volatile", + 5: "class enum extends super const export import", + 6: "enum", + strict: "implements interface let package private protected public static yield", + strictBind: "eval arguments" +}; +var ecma5AndLessKeywords = "break case catch continue debugger default do else finally for function if return switch throw try var while with null true false instanceof typeof void delete new in this"; +var keywords$1 = { + 5: ecma5AndLessKeywords, + "5module": ecma5AndLessKeywords + " export import", + 6: ecma5AndLessKeywords + " const class extends export import super" +}; +var keywordRelationalOperator = /^in(stanceof)?$/; +var nonASCIIidentifierStart = new RegExp("[" + nonASCIIidentifierStartChars + "]"); +var nonASCIIidentifier = new RegExp("[" + nonASCIIidentifierStartChars + nonASCIIidentifierChars + "]"); +function isInAstralSet(code, set) { + var pos = 65536; + for (var i4 = 0; i4 < set.length; i4 += 2) { + pos += set[i4]; + if (pos > code) { + return false; + } + pos += set[i4 + 1]; + if (pos >= code) { + return true; + } + } + return false; +} +function isIdentifierStart(code, astral) { + if (code < 65) { + return code === 36; + } + if (code < 91) { + return true; + } + if (code < 97) { + return code === 95; + } + if (code < 123) { + return true; + } + if (code <= 65535) { + return code >= 170 && nonASCIIidentifierStart.test(String.fromCharCode(code)); + } + if (astral === false) { + return false; + } + return isInAstralSet(code, astralIdentifierStartCodes); +} +function isIdentifierChar(code, astral) { + if (code < 48) { + return code === 36; + } + if (code < 58) { + return true; + } + if (code < 65) { + return false; + } + if (code < 91) { + return true; + } + if (code < 97) { + return code === 95; + } + if (code < 123) { + return true; + } + if (code <= 65535) { + return code >= 170 && nonASCIIidentifier.test(String.fromCharCode(code)); + } + if (astral === false) { + return false; + } + return isInAstralSet(code, astralIdentifierStartCodes) || isInAstralSet(code, astralIdentifierCodes); +} +var TokenType = function TokenType2(label, conf) { + if (conf === void 0) + conf = {}; + this.label = label; + this.keyword = conf.keyword; + this.beforeExpr = !!conf.beforeExpr; + this.startsExpr = !!conf.startsExpr; + this.isLoop = !!conf.isLoop; + this.isAssign = !!conf.isAssign; + this.prefix = !!conf.prefix; + this.postfix = !!conf.postfix; + this.binop = conf.binop || null; + this.updateContext = null; +}; +function binop(name, prec) { + return new TokenType(name, { beforeExpr: true, binop: prec }); +} +var beforeExpr = { beforeExpr: true }; +var startsExpr = { startsExpr: true }; +var keywords = {}; +function kw(name, options) { + if (options === void 0) + options = {}; + options.keyword = name; + return keywords[name] = new TokenType(name, options); +} +var types$1 = { + num: new TokenType("num", startsExpr), + regexp: new TokenType("regexp", startsExpr), + string: new TokenType("string", startsExpr), + name: new TokenType("name", startsExpr), + privateId: new TokenType("privateId", startsExpr), + eof: new TokenType("eof"), + bracketL: new TokenType("[", { beforeExpr: true, startsExpr: true }), + bracketR: new TokenType("]"), + braceL: new TokenType("{", { beforeExpr: true, startsExpr: true }), + braceR: new TokenType("}"), + parenL: new TokenType("(", { beforeExpr: true, startsExpr: true }), + parenR: new TokenType(")"), + comma: new TokenType(",", beforeExpr), + semi: new TokenType(";", beforeExpr), + colon: new TokenType(":", beforeExpr), + dot: new TokenType("."), + question: new TokenType("?", beforeExpr), + questionDot: new TokenType("?."), + arrow: new TokenType("=>", beforeExpr), + template: new TokenType("template"), + invalidTemplate: new TokenType("invalidTemplate"), + ellipsis: new TokenType("...", beforeExpr), + backQuote: new TokenType("`", startsExpr), + dollarBraceL: new TokenType("${", { beforeExpr: true, startsExpr: true }), + eq: new TokenType("=", { beforeExpr: true, isAssign: true }), + assign: new TokenType("_=", { beforeExpr: true, isAssign: true }), + incDec: new TokenType("++/--", { prefix: true, postfix: true, startsExpr: true }), + prefix: new TokenType("!/~", { beforeExpr: true, prefix: true, startsExpr: true }), + logicalOR: binop("||", 1), + logicalAND: binop("&&", 2), + bitwiseOR: binop("|", 3), + bitwiseXOR: binop("^", 4), + bitwiseAND: binop("&", 5), + equality: binop("==/!=/===/!==", 6), + relational: binop("/<=/>=", 7), + bitShift: binop("<>/>>>", 8), + plusMin: new TokenType("+/-", { beforeExpr: true, binop: 9, prefix: true, startsExpr: true }), + modulo: binop("%", 10), + star: binop("*", 10), + slash: binop("/", 10), + starstar: new TokenType("**", { beforeExpr: true }), + coalesce: binop("??", 1), + _break: kw("break"), + _case: kw("case", beforeExpr), + _catch: kw("catch"), + _continue: kw("continue"), + _debugger: kw("debugger"), + _default: kw("default", beforeExpr), + _do: kw("do", { isLoop: true, beforeExpr: true }), + _else: kw("else", beforeExpr), + _finally: kw("finally"), + _for: kw("for", { isLoop: true }), + _function: kw("function", startsExpr), + _if: kw("if"), + _return: kw("return", beforeExpr), + _switch: kw("switch"), + _throw: kw("throw", beforeExpr), + _try: kw("try"), + _var: kw("var"), + _const: kw("const"), + _while: kw("while", { isLoop: true }), + _with: kw("with"), + _new: kw("new", { beforeExpr: true, startsExpr: true }), + _this: kw("this", startsExpr), + _super: kw("super", startsExpr), + _class: kw("class", startsExpr), + _extends: kw("extends", beforeExpr), + _export: kw("export"), + _import: kw("import", startsExpr), + _null: kw("null", startsExpr), + _true: kw("true", startsExpr), + _false: kw("false", startsExpr), + _in: kw("in", { beforeExpr: true, binop: 7 }), + _instanceof: kw("instanceof", { beforeExpr: true, binop: 7 }), + _typeof: kw("typeof", { beforeExpr: true, prefix: true, startsExpr: true }), + _void: kw("void", { beforeExpr: true, prefix: true, startsExpr: true }), + _delete: kw("delete", { beforeExpr: true, prefix: true, startsExpr: true }) +}; +var lineBreak = /\r\n?|\n|\u2028|\u2029/; +var lineBreakG = new RegExp(lineBreak.source, "g"); +function isNewLine(code) { + return code === 10 || code === 13 || code === 8232 || code === 8233; +} +function nextLineBreak(code, from, end) { + if (end === void 0) + end = code.length; + for (var i4 = from; i4 < end; i4++) { + var next = code.charCodeAt(i4); + if (isNewLine(next)) { + return i4 < end - 1 && next === 13 && code.charCodeAt(i4 + 1) === 10 ? i4 + 2 : i4 + 1; + } + } + return -1; +} +var nonASCIIwhitespace = /[\u1680\u2000-\u200a\u202f\u205f\u3000\ufeff]/; +var skipWhiteSpace = /(?:\s|\/\/.*|\/\*[^]*?\*\/)*/g; +var ref = Object.prototype; +var hasOwnProperty = ref.hasOwnProperty; +var toString = ref.toString; +var hasOwn = Object.hasOwn || function(obj, propName) { + return hasOwnProperty.call(obj, propName); +}; +var isArray = Array.isArray || function(obj) { + return toString.call(obj) === "[object Array]"; +}; +function wordsRegexp(words) { + return new RegExp("^(?:" + words.replace(/ /g, "|") + ")$"); +} +function codePointToString(code) { + if (code <= 65535) { + return String.fromCharCode(code); + } + code -= 65536; + return String.fromCharCode((code >> 10) + 55296, (code & 1023) + 56320); +} +var loneSurrogate = /(?:[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])/; +var Position = function Position2(line, col) { + this.line = line; + this.column = col; +}; +Position.prototype.offset = function offset(n2) { + return new Position(this.line, this.column + n2); +}; +var SourceLocation = function SourceLocation2(p3, start, end) { + this.start = start; + this.end = end; + if (p3.sourceFile !== null) { + this.source = p3.sourceFile; + } +}; +function getLineInfo(input, offset2) { + for (var line = 1, cur = 0; ; ) { + var nextBreak = nextLineBreak(input, cur, offset2); + if (nextBreak < 0) { + return new Position(line, offset2 - cur); + } + ++line; + cur = nextBreak; + } +} +var defaultOptions = { + ecmaVersion: null, + sourceType: "script", + onInsertedSemicolon: null, + onTrailingComma: null, + allowReserved: null, + allowReturnOutsideFunction: false, + allowImportExportEverywhere: false, + allowAwaitOutsideFunction: null, + allowSuperOutsideMethod: null, + allowHashBang: false, + locations: false, + onToken: null, + onComment: null, + ranges: false, + program: null, + sourceFile: null, + directSourceFile: null, + preserveParens: false +}; +var warnedAboutEcmaVersion = false; +function getOptions(opts) { + var options = {}; + for (var opt in defaultOptions) { + options[opt] = opts && hasOwn(opts, opt) ? opts[opt] : defaultOptions[opt]; + } + if (options.ecmaVersion === "latest") { + options.ecmaVersion = 1e8; + } else if (options.ecmaVersion == null) { + if (!warnedAboutEcmaVersion && typeof console === "object" && console.warn) { + warnedAboutEcmaVersion = true; + console.warn("Since Acorn 8.0.0, options.ecmaVersion is required.\nDefaulting to 2020, but this will stop working in the future."); + } + options.ecmaVersion = 11; + } else if (options.ecmaVersion >= 2015) { + options.ecmaVersion -= 2009; + } + if (options.allowReserved == null) { + options.allowReserved = options.ecmaVersion < 5; + } + if (!opts || opts.allowHashBang == null) { + options.allowHashBang = options.ecmaVersion >= 14; + } + if (isArray(options.onToken)) { + var tokens = options.onToken; + options.onToken = function(token) { + return tokens.push(token); + }; + } + if (isArray(options.onComment)) { + options.onComment = pushComment(options, options.onComment); + } + return options; +} +function pushComment(options, array) { + return function(block, text2, start, end, startLoc, endLoc) { + var comment = { + type: block ? "Block" : "Line", + value: text2, + start, + end + }; + if (options.locations) { + comment.loc = new SourceLocation(this, startLoc, endLoc); + } + if (options.ranges) { + comment.range = [start, end]; + } + array.push(comment); + }; +} +var SCOPE_TOP = 1; +var SCOPE_FUNCTION = 2; +var SCOPE_ASYNC = 4; +var SCOPE_GENERATOR = 8; +var SCOPE_ARROW = 16; +var SCOPE_SIMPLE_CATCH = 32; +var SCOPE_SUPER = 64; +var SCOPE_DIRECT_SUPER = 128; +var SCOPE_CLASS_STATIC_BLOCK = 256; +var SCOPE_VAR = SCOPE_TOP | SCOPE_FUNCTION | SCOPE_CLASS_STATIC_BLOCK; +function functionFlags(async, generator) { + return SCOPE_FUNCTION | (async ? SCOPE_ASYNC : 0) | (generator ? SCOPE_GENERATOR : 0); +} +var BIND_NONE = 0; +var BIND_VAR = 1; +var BIND_LEXICAL = 2; +var BIND_FUNCTION = 3; +var BIND_SIMPLE_CATCH = 4; +var BIND_OUTSIDE = 5; +var Parser = function Parser2(options, input, startPos) { + this.options = options = getOptions(options); + this.sourceFile = options.sourceFile; + this.keywords = wordsRegexp(keywords$1[options.ecmaVersion >= 6 ? 6 : options.sourceType === "module" ? "5module" : 5]); + var reserved = ""; + if (options.allowReserved !== true) { + reserved = reservedWords[options.ecmaVersion >= 6 ? 6 : options.ecmaVersion === 5 ? 5 : 3]; + if (options.sourceType === "module") { + reserved += " await"; + } + } + this.reservedWords = wordsRegexp(reserved); + var reservedStrict = (reserved ? reserved + " " : "") + reservedWords.strict; + this.reservedWordsStrict = wordsRegexp(reservedStrict); + this.reservedWordsStrictBind = wordsRegexp(reservedStrict + " " + reservedWords.strictBind); + this.input = String(input); + this.containsEsc = false; + if (startPos) { + this.pos = startPos; + this.lineStart = this.input.lastIndexOf("\n", startPos - 1) + 1; + this.curLine = this.input.slice(0, this.lineStart).split(lineBreak).length; + } else { + this.pos = this.lineStart = 0; + this.curLine = 1; + } + this.type = types$1.eof; + this.value = null; + this.start = this.end = this.pos; + this.startLoc = this.endLoc = this.curPosition(); + this.lastTokEndLoc = this.lastTokStartLoc = null; + this.lastTokStart = this.lastTokEnd = this.pos; + this.context = this.initialContext(); + this.exprAllowed = true; + this.inModule = options.sourceType === "module"; + this.strict = this.inModule || this.strictDirective(this.pos); + this.potentialArrowAt = -1; + this.potentialArrowInForAwait = false; + this.yieldPos = this.awaitPos = this.awaitIdentPos = 0; + this.labels = []; + this.undefinedExports = /* @__PURE__ */ Object.create(null); + if (this.pos === 0 && options.allowHashBang && this.input.slice(0, 2) === "#!") { + this.skipLineComment(2); + } + this.scopeStack = []; + this.enterScope(SCOPE_TOP); + this.regexpState = null; + this.privateNameStack = []; +}; +var prototypeAccessors = { inFunction: { configurable: true }, inGenerator: { configurable: true }, inAsync: { configurable: true }, canAwait: { configurable: true }, allowSuper: { configurable: true }, allowDirectSuper: { configurable: true }, treatFunctionsAsVar: { configurable: true }, allowNewDotTarget: { configurable: true }, inClassStaticBlock: { configurable: true } }; +Parser.prototype.parse = function parse() { + var node = this.options.program || this.startNode(); + this.nextToken(); + return this.parseTopLevel(node); +}; +prototypeAccessors.inFunction.get = function() { + return (this.currentVarScope().flags & SCOPE_FUNCTION) > 0; +}; +prototypeAccessors.inGenerator.get = function() { + return (this.currentVarScope().flags & SCOPE_GENERATOR) > 0 && !this.currentVarScope().inClassFieldInit; +}; +prototypeAccessors.inAsync.get = function() { + return (this.currentVarScope().flags & SCOPE_ASYNC) > 0 && !this.currentVarScope().inClassFieldInit; +}; +prototypeAccessors.canAwait.get = function() { + for (var i4 = this.scopeStack.length - 1; i4 >= 0; i4--) { + var scope = this.scopeStack[i4]; + if (scope.inClassFieldInit || scope.flags & SCOPE_CLASS_STATIC_BLOCK) { + return false; + } + if (scope.flags & SCOPE_FUNCTION) { + return (scope.flags & SCOPE_ASYNC) > 0; + } + } + return this.inModule && this.options.ecmaVersion >= 13 || this.options.allowAwaitOutsideFunction; +}; +prototypeAccessors.allowSuper.get = function() { + var ref2 = this.currentThisScope(); + var flags = ref2.flags; + var inClassFieldInit = ref2.inClassFieldInit; + return (flags & SCOPE_SUPER) > 0 || inClassFieldInit || this.options.allowSuperOutsideMethod; +}; +prototypeAccessors.allowDirectSuper.get = function() { + return (this.currentThisScope().flags & SCOPE_DIRECT_SUPER) > 0; +}; +prototypeAccessors.treatFunctionsAsVar.get = function() { + return this.treatFunctionsAsVarInScope(this.currentScope()); +}; +prototypeAccessors.allowNewDotTarget.get = function() { + var ref2 = this.currentThisScope(); + var flags = ref2.flags; + var inClassFieldInit = ref2.inClassFieldInit; + return (flags & (SCOPE_FUNCTION | SCOPE_CLASS_STATIC_BLOCK)) > 0 || inClassFieldInit; +}; +prototypeAccessors.inClassStaticBlock.get = function() { + return (this.currentVarScope().flags & SCOPE_CLASS_STATIC_BLOCK) > 0; +}; +Parser.extend = function extend() { + var plugins = [], len = arguments.length; + while (len--) + plugins[len] = arguments[len]; + var cls = this; + for (var i4 = 0; i4 < plugins.length; i4++) { + cls = plugins[i4](cls); + } + return cls; +}; +Parser.parse = function parse2(input, options) { + return new this(options, input).parse(); +}; +Parser.parseExpressionAt = function parseExpressionAt(input, pos, options) { + var parser = new this(options, input, pos); + parser.nextToken(); + return parser.parseExpression(); +}; +Parser.tokenizer = function tokenizer(input, options) { + return new this(options, input); +}; +Object.defineProperties(Parser.prototype, prototypeAccessors); +var pp$9 = Parser.prototype; +var literal = /^(?:'((?:\\.|[^'\\])*?)'|"((?:\\.|[^"\\])*?)")/; +pp$9.strictDirective = function(start) { + if (this.options.ecmaVersion < 5) { + return false; + } + for (; ; ) { + skipWhiteSpace.lastIndex = start; + start += skipWhiteSpace.exec(this.input)[0].length; + var match2 = literal.exec(this.input.slice(start)); + if (!match2) { + return false; + } + if ((match2[1] || match2[2]) === "use strict") { + skipWhiteSpace.lastIndex = start + match2[0].length; + var spaceAfter = skipWhiteSpace.exec(this.input), end = spaceAfter.index + spaceAfter[0].length; + var next = this.input.charAt(end); + return next === ";" || next === "}" || lineBreak.test(spaceAfter[0]) && !(/[(`.[+\-/*%<>=,?^&]/.test(next) || next === "!" && this.input.charAt(end + 1) === "="); + } + start += match2[0].length; + skipWhiteSpace.lastIndex = start; + start += skipWhiteSpace.exec(this.input)[0].length; + if (this.input[start] === ";") { + start++; + } + } +}; +pp$9.eat = function(type) { + if (this.type === type) { + this.next(); + return true; + } else { + return false; + } +}; +pp$9.isContextual = function(name) { + return this.type === types$1.name && this.value === name && !this.containsEsc; +}; +pp$9.eatContextual = function(name) { + if (!this.isContextual(name)) { + return false; + } + this.next(); + return true; +}; +pp$9.expectContextual = function(name) { + if (!this.eatContextual(name)) { + this.unexpected(); + } +}; +pp$9.canInsertSemicolon = function() { + return this.type === types$1.eof || this.type === types$1.braceR || lineBreak.test(this.input.slice(this.lastTokEnd, this.start)); +}; +pp$9.insertSemicolon = function() { + if (this.canInsertSemicolon()) { + if (this.options.onInsertedSemicolon) { + this.options.onInsertedSemicolon(this.lastTokEnd, this.lastTokEndLoc); + } + return true; + } +}; +pp$9.semicolon = function() { + if (!this.eat(types$1.semi) && !this.insertSemicolon()) { + this.unexpected(); + } +}; +pp$9.afterTrailingComma = function(tokType, notNext) { + if (this.type === tokType) { + if (this.options.onTrailingComma) { + this.options.onTrailingComma(this.lastTokStart, this.lastTokStartLoc); + } + if (!notNext) { + this.next(); + } + return true; + } +}; +pp$9.expect = function(type) { + this.eat(type) || this.unexpected(); +}; +pp$9.unexpected = function(pos) { + this.raise(pos != null ? pos : this.start, "Unexpected token"); +}; +var DestructuringErrors = function DestructuringErrors2() { + this.shorthandAssign = this.trailingComma = this.parenthesizedAssign = this.parenthesizedBind = this.doubleProto = -1; +}; +pp$9.checkPatternErrors = function(refDestructuringErrors, isAssign) { + if (!refDestructuringErrors) { + return; + } + if (refDestructuringErrors.trailingComma > -1) { + this.raiseRecoverable(refDestructuringErrors.trailingComma, "Comma is not permitted after the rest element"); + } + var parens = isAssign ? refDestructuringErrors.parenthesizedAssign : refDestructuringErrors.parenthesizedBind; + if (parens > -1) { + this.raiseRecoverable(parens, isAssign ? "Assigning to rvalue" : "Parenthesized pattern"); + } +}; +pp$9.checkExpressionErrors = function(refDestructuringErrors, andThrow) { + if (!refDestructuringErrors) { + return false; + } + var shorthandAssign = refDestructuringErrors.shorthandAssign; + var doubleProto = refDestructuringErrors.doubleProto; + if (!andThrow) { + return shorthandAssign >= 0 || doubleProto >= 0; + } + if (shorthandAssign >= 0) { + this.raise(shorthandAssign, "Shorthand property assignments are valid only in destructuring patterns"); + } + if (doubleProto >= 0) { + this.raiseRecoverable(doubleProto, "Redefinition of __proto__ property"); + } +}; +pp$9.checkYieldAwaitInDefaultParams = function() { + if (this.yieldPos && (!this.awaitPos || this.yieldPos < this.awaitPos)) { + this.raise(this.yieldPos, "Yield expression cannot be a default value"); + } + if (this.awaitPos) { + this.raise(this.awaitPos, "Await expression cannot be a default value"); + } +}; +pp$9.isSimpleAssignTarget = function(expr) { + if (expr.type === "ParenthesizedExpression") { + return this.isSimpleAssignTarget(expr.expression); + } + return expr.type === "Identifier" || expr.type === "MemberExpression"; +}; +var pp$8 = Parser.prototype; +pp$8.parseTopLevel = function(node) { + var exports = /* @__PURE__ */ Object.create(null); + if (!node.body) { + node.body = []; + } + while (this.type !== types$1.eof) { + var stmt = this.parseStatement(null, true, exports); + node.body.push(stmt); + } + if (this.inModule) { + for (var i4 = 0, list = Object.keys(this.undefinedExports); i4 < list.length; i4 += 1) { + var name = list[i4]; + this.raiseRecoverable(this.undefinedExports[name].start, "Export '" + name + "' is not defined"); + } + } + this.adaptDirectivePrologue(node.body); + this.next(); + node.sourceType = this.options.sourceType; + return this.finishNode(node, "Program"); +}; +var loopLabel = { kind: "loop" }; +var switchLabel = { kind: "switch" }; +pp$8.isLet = function(context) { + if (this.options.ecmaVersion < 6 || !this.isContextual("let")) { + return false; + } + skipWhiteSpace.lastIndex = this.pos; + var skip = skipWhiteSpace.exec(this.input); + var next = this.pos + skip[0].length, nextCh = this.input.charCodeAt(next); + if (nextCh === 91 || nextCh === 92) { + return true; + } + if (context) { + return false; + } + if (nextCh === 123 || nextCh > 55295 && nextCh < 56320) { + return true; + } + if (isIdentifierStart(nextCh, true)) { + var pos = next + 1; + while (isIdentifierChar(nextCh = this.input.charCodeAt(pos), true)) { + ++pos; + } + if (nextCh === 92 || nextCh > 55295 && nextCh < 56320) { + return true; + } + var ident = this.input.slice(next, pos); + if (!keywordRelationalOperator.test(ident)) { + return true; + } + } + return false; +}; +pp$8.isAsyncFunction = function() { + if (this.options.ecmaVersion < 8 || !this.isContextual("async")) { + return false; + } + skipWhiteSpace.lastIndex = this.pos; + var skip = skipWhiteSpace.exec(this.input); + var next = this.pos + skip[0].length, after; + return !lineBreak.test(this.input.slice(this.pos, next)) && this.input.slice(next, next + 8) === "function" && (next + 8 === this.input.length || !(isIdentifierChar(after = this.input.charCodeAt(next + 8)) || after > 55295 && after < 56320)); +}; +pp$8.parseStatement = function(context, topLevel, exports) { + var starttype = this.type, node = this.startNode(), kind; + if (this.isLet(context)) { + starttype = types$1._var; + kind = "let"; + } + switch (starttype) { + case types$1._break: + case types$1._continue: + return this.parseBreakContinueStatement(node, starttype.keyword); + case types$1._debugger: + return this.parseDebuggerStatement(node); + case types$1._do: + return this.parseDoStatement(node); + case types$1._for: + return this.parseForStatement(node); + case types$1._function: + if (context && (this.strict || context !== "if" && context !== "label") && this.options.ecmaVersion >= 6) { + this.unexpected(); + } + return this.parseFunctionStatement(node, false, !context); + case types$1._class: + if (context) { + this.unexpected(); + } + return this.parseClass(node, true); + case types$1._if: + return this.parseIfStatement(node); + case types$1._return: + return this.parseReturnStatement(node); + case types$1._switch: + return this.parseSwitchStatement(node); + case types$1._throw: + return this.parseThrowStatement(node); + case types$1._try: + return this.parseTryStatement(node); + case types$1._const: + case types$1._var: + kind = kind || this.value; + if (context && kind !== "var") { + this.unexpected(); + } + return this.parseVarStatement(node, kind); + case types$1._while: + return this.parseWhileStatement(node); + case types$1._with: + return this.parseWithStatement(node); + case types$1.braceL: + return this.parseBlock(true, node); + case types$1.semi: + return this.parseEmptyStatement(node); + case types$1._export: + case types$1._import: + if (this.options.ecmaVersion > 10 && starttype === types$1._import) { + skipWhiteSpace.lastIndex = this.pos; + var skip = skipWhiteSpace.exec(this.input); + var next = this.pos + skip[0].length, nextCh = this.input.charCodeAt(next); + if (nextCh === 40 || nextCh === 46) { + return this.parseExpressionStatement(node, this.parseExpression()); + } + } + if (!this.options.allowImportExportEverywhere) { + if (!topLevel) { + this.raise(this.start, "'import' and 'export' may only appear at the top level"); + } + if (!this.inModule) { + this.raise(this.start, "'import' and 'export' may appear only with 'sourceType: module'"); + } + } + return starttype === types$1._import ? this.parseImport(node) : this.parseExport(node, exports); + default: + if (this.isAsyncFunction()) { + if (context) { + this.unexpected(); + } + this.next(); + return this.parseFunctionStatement(node, true, !context); + } + var maybeName = this.value, expr = this.parseExpression(); + if (starttype === types$1.name && expr.type === "Identifier" && this.eat(types$1.colon)) { + return this.parseLabeledStatement(node, maybeName, expr, context); + } else { + return this.parseExpressionStatement(node, expr); + } + } +}; +pp$8.parseBreakContinueStatement = function(node, keyword) { + var isBreak = keyword === "break"; + this.next(); + if (this.eat(types$1.semi) || this.insertSemicolon()) { + node.label = null; + } else if (this.type !== types$1.name) { + this.unexpected(); + } else { + node.label = this.parseIdent(); + this.semicolon(); + } + var i4 = 0; + for (; i4 < this.labels.length; ++i4) { + var lab = this.labels[i4]; + if (node.label == null || lab.name === node.label.name) { + if (lab.kind != null && (isBreak || lab.kind === "loop")) { + break; + } + if (node.label && isBreak) { + break; + } + } + } + if (i4 === this.labels.length) { + this.raise(node.start, "Unsyntactic " + keyword); + } + return this.finishNode(node, isBreak ? "BreakStatement" : "ContinueStatement"); +}; +pp$8.parseDebuggerStatement = function(node) { + this.next(); + this.semicolon(); + return this.finishNode(node, "DebuggerStatement"); +}; +pp$8.parseDoStatement = function(node) { + this.next(); + this.labels.push(loopLabel); + node.body = this.parseStatement("do"); + this.labels.pop(); + this.expect(types$1._while); + node.test = this.parseParenExpression(); + if (this.options.ecmaVersion >= 6) { + this.eat(types$1.semi); + } else { + this.semicolon(); + } + return this.finishNode(node, "DoWhileStatement"); +}; +pp$8.parseForStatement = function(node) { + this.next(); + var awaitAt = this.options.ecmaVersion >= 9 && this.canAwait && this.eatContextual("await") ? this.lastTokStart : -1; + this.labels.push(loopLabel); + this.enterScope(0); + this.expect(types$1.parenL); + if (this.type === types$1.semi) { + if (awaitAt > -1) { + this.unexpected(awaitAt); + } + return this.parseFor(node, null); + } + var isLet = this.isLet(); + if (this.type === types$1._var || this.type === types$1._const || isLet) { + var init$1 = this.startNode(), kind = isLet ? "let" : this.value; + this.next(); + this.parseVar(init$1, true, kind); + this.finishNode(init$1, "VariableDeclaration"); + if ((this.type === types$1._in || this.options.ecmaVersion >= 6 && this.isContextual("of")) && init$1.declarations.length === 1) { + if (this.options.ecmaVersion >= 9) { + if (this.type === types$1._in) { + if (awaitAt > -1) { + this.unexpected(awaitAt); + } + } else { + node.await = awaitAt > -1; + } + } + return this.parseForIn(node, init$1); + } + if (awaitAt > -1) { + this.unexpected(awaitAt); + } + return this.parseFor(node, init$1); + } + var startsWithLet = this.isContextual("let"), isForOf = false; + var refDestructuringErrors = new DestructuringErrors(); + var init = this.parseExpression(awaitAt > -1 ? "await" : true, refDestructuringErrors); + if (this.type === types$1._in || (isForOf = this.options.ecmaVersion >= 6 && this.isContextual("of"))) { + if (this.options.ecmaVersion >= 9) { + if (this.type === types$1._in) { + if (awaitAt > -1) { + this.unexpected(awaitAt); + } + } else { + node.await = awaitAt > -1; + } + } + if (startsWithLet && isForOf) { + this.raise(init.start, "The left-hand side of a for-of loop may not start with 'let'."); + } + this.toAssignable(init, false, refDestructuringErrors); + this.checkLValPattern(init); + return this.parseForIn(node, init); + } else { + this.checkExpressionErrors(refDestructuringErrors, true); + } + if (awaitAt > -1) { + this.unexpected(awaitAt); + } + return this.parseFor(node, init); +}; +pp$8.parseFunctionStatement = function(node, isAsync, declarationPosition) { + this.next(); + return this.parseFunction(node, FUNC_STATEMENT | (declarationPosition ? 0 : FUNC_HANGING_STATEMENT), false, isAsync); +}; +pp$8.parseIfStatement = function(node) { + this.next(); + node.test = this.parseParenExpression(); + node.consequent = this.parseStatement("if"); + node.alternate = this.eat(types$1._else) ? this.parseStatement("if") : null; + return this.finishNode(node, "IfStatement"); +}; +pp$8.parseReturnStatement = function(node) { + if (!this.inFunction && !this.options.allowReturnOutsideFunction) { + this.raise(this.start, "'return' outside of function"); + } + this.next(); + if (this.eat(types$1.semi) || this.insertSemicolon()) { + node.argument = null; + } else { + node.argument = this.parseExpression(); + this.semicolon(); + } + return this.finishNode(node, "ReturnStatement"); +}; +pp$8.parseSwitchStatement = function(node) { + this.next(); + node.discriminant = this.parseParenExpression(); + node.cases = []; + this.expect(types$1.braceL); + this.labels.push(switchLabel); + this.enterScope(0); + var cur; + for (var sawDefault = false; this.type !== types$1.braceR; ) { + if (this.type === types$1._case || this.type === types$1._default) { + var isCase = this.type === types$1._case; + if (cur) { + this.finishNode(cur, "SwitchCase"); + } + node.cases.push(cur = this.startNode()); + cur.consequent = []; + this.next(); + if (isCase) { + cur.test = this.parseExpression(); + } else { + if (sawDefault) { + this.raiseRecoverable(this.lastTokStart, "Multiple default clauses"); + } + sawDefault = true; + cur.test = null; + } + this.expect(types$1.colon); + } else { + if (!cur) { + this.unexpected(); + } + cur.consequent.push(this.parseStatement(null)); + } + } + this.exitScope(); + if (cur) { + this.finishNode(cur, "SwitchCase"); + } + this.next(); + this.labels.pop(); + return this.finishNode(node, "SwitchStatement"); +}; +pp$8.parseThrowStatement = function(node) { + this.next(); + if (lineBreak.test(this.input.slice(this.lastTokEnd, this.start))) { + this.raise(this.lastTokEnd, "Illegal newline after throw"); + } + node.argument = this.parseExpression(); + this.semicolon(); + return this.finishNode(node, "ThrowStatement"); +}; +var empty$1 = []; +pp$8.parseTryStatement = function(node) { + this.next(); + node.block = this.parseBlock(); + node.handler = null; + if (this.type === types$1._catch) { + var clause = this.startNode(); + this.next(); + if (this.eat(types$1.parenL)) { + clause.param = this.parseBindingAtom(); + var simple = clause.param.type === "Identifier"; + this.enterScope(simple ? SCOPE_SIMPLE_CATCH : 0); + this.checkLValPattern(clause.param, simple ? BIND_SIMPLE_CATCH : BIND_LEXICAL); + this.expect(types$1.parenR); + } else { + if (this.options.ecmaVersion < 10) { + this.unexpected(); + } + clause.param = null; + this.enterScope(0); + } + clause.body = this.parseBlock(false); + this.exitScope(); + node.handler = this.finishNode(clause, "CatchClause"); + } + node.finalizer = this.eat(types$1._finally) ? this.parseBlock() : null; + if (!node.handler && !node.finalizer) { + this.raise(node.start, "Missing catch or finally clause"); + } + return this.finishNode(node, "TryStatement"); +}; +pp$8.parseVarStatement = function(node, kind) { + this.next(); + this.parseVar(node, false, kind); + this.semicolon(); + return this.finishNode(node, "VariableDeclaration"); +}; +pp$8.parseWhileStatement = function(node) { + this.next(); + node.test = this.parseParenExpression(); + this.labels.push(loopLabel); + node.body = this.parseStatement("while"); + this.labels.pop(); + return this.finishNode(node, "WhileStatement"); +}; +pp$8.parseWithStatement = function(node) { + if (this.strict) { + this.raise(this.start, "'with' in strict mode"); + } + this.next(); + node.object = this.parseParenExpression(); + node.body = this.parseStatement("with"); + return this.finishNode(node, "WithStatement"); +}; +pp$8.parseEmptyStatement = function(node) { + this.next(); + return this.finishNode(node, "EmptyStatement"); +}; +pp$8.parseLabeledStatement = function(node, maybeName, expr, context) { + for (var i$1 = 0, list = this.labels; i$1 < list.length; i$1 += 1) { + var label = list[i$1]; + if (label.name === maybeName) { + this.raise(expr.start, "Label '" + maybeName + "' is already declared"); + } + } + var kind = this.type.isLoop ? "loop" : this.type === types$1._switch ? "switch" : null; + for (var i4 = this.labels.length - 1; i4 >= 0; i4--) { + var label$1 = this.labels[i4]; + if (label$1.statementStart === node.start) { + label$1.statementStart = this.start; + label$1.kind = kind; + } else { + break; + } + } + this.labels.push({ name: maybeName, kind, statementStart: this.start }); + node.body = this.parseStatement(context ? context.indexOf("label") === -1 ? context + "label" : context : "label"); + this.labels.pop(); + node.label = expr; + return this.finishNode(node, "LabeledStatement"); +}; +pp$8.parseExpressionStatement = function(node, expr) { + node.expression = expr; + this.semicolon(); + return this.finishNode(node, "ExpressionStatement"); +}; +pp$8.parseBlock = function(createNewLexicalScope, node, exitStrict) { + if (createNewLexicalScope === void 0) + createNewLexicalScope = true; + if (node === void 0) + node = this.startNode(); + node.body = []; + this.expect(types$1.braceL); + if (createNewLexicalScope) { + this.enterScope(0); + } + while (this.type !== types$1.braceR) { + var stmt = this.parseStatement(null); + node.body.push(stmt); + } + if (exitStrict) { + this.strict = false; + } + this.next(); + if (createNewLexicalScope) { + this.exitScope(); + } + return this.finishNode(node, "BlockStatement"); +}; +pp$8.parseFor = function(node, init) { + node.init = init; + this.expect(types$1.semi); + node.test = this.type === types$1.semi ? null : this.parseExpression(); + this.expect(types$1.semi); + node.update = this.type === types$1.parenR ? null : this.parseExpression(); + this.expect(types$1.parenR); + node.body = this.parseStatement("for"); + this.exitScope(); + this.labels.pop(); + return this.finishNode(node, "ForStatement"); +}; +pp$8.parseForIn = function(node, init) { + var isForIn = this.type === types$1._in; + this.next(); + if (init.type === "VariableDeclaration" && init.declarations[0].init != null && (!isForIn || this.options.ecmaVersion < 8 || this.strict || init.kind !== "var" || init.declarations[0].id.type !== "Identifier")) { + this.raise( + init.start, + (isForIn ? "for-in" : "for-of") + " loop variable declaration may not have an initializer" + ); + } + node.left = init; + node.right = isForIn ? this.parseExpression() : this.parseMaybeAssign(); + this.expect(types$1.parenR); + node.body = this.parseStatement("for"); + this.exitScope(); + this.labels.pop(); + return this.finishNode(node, isForIn ? "ForInStatement" : "ForOfStatement"); +}; +pp$8.parseVar = function(node, isFor, kind) { + node.declarations = []; + node.kind = kind; + for (; ; ) { + var decl = this.startNode(); + this.parseVarId(decl, kind); + if (this.eat(types$1.eq)) { + decl.init = this.parseMaybeAssign(isFor); + } else if (kind === "const" && !(this.type === types$1._in || this.options.ecmaVersion >= 6 && this.isContextual("of"))) { + this.unexpected(); + } else if (decl.id.type !== "Identifier" && !(isFor && (this.type === types$1._in || this.isContextual("of")))) { + this.raise(this.lastTokEnd, "Complex binding patterns require an initialization value"); + } else { + decl.init = null; + } + node.declarations.push(this.finishNode(decl, "VariableDeclarator")); + if (!this.eat(types$1.comma)) { + break; + } + } + return node; +}; +pp$8.parseVarId = function(decl, kind) { + decl.id = this.parseBindingAtom(); + this.checkLValPattern(decl.id, kind === "var" ? BIND_VAR : BIND_LEXICAL, false); +}; +var FUNC_STATEMENT = 1; +var FUNC_HANGING_STATEMENT = 2; +var FUNC_NULLABLE_ID = 4; +pp$8.parseFunction = function(node, statement, allowExpressionBody, isAsync, forInit) { + this.initFunction(node); + if (this.options.ecmaVersion >= 9 || this.options.ecmaVersion >= 6 && !isAsync) { + if (this.type === types$1.star && statement & FUNC_HANGING_STATEMENT) { + this.unexpected(); + } + node.generator = this.eat(types$1.star); + } + if (this.options.ecmaVersion >= 8) { + node.async = !!isAsync; + } + if (statement & FUNC_STATEMENT) { + node.id = statement & FUNC_NULLABLE_ID && this.type !== types$1.name ? null : this.parseIdent(); + if (node.id && !(statement & FUNC_HANGING_STATEMENT)) { + this.checkLValSimple(node.id, this.strict || node.generator || node.async ? this.treatFunctionsAsVar ? BIND_VAR : BIND_LEXICAL : BIND_FUNCTION); + } + } + var oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos; + this.yieldPos = 0; + this.awaitPos = 0; + this.awaitIdentPos = 0; + this.enterScope(functionFlags(node.async, node.generator)); + if (!(statement & FUNC_STATEMENT)) { + node.id = this.type === types$1.name ? this.parseIdent() : null; + } + this.parseFunctionParams(node); + this.parseFunctionBody(node, allowExpressionBody, false, forInit); + this.yieldPos = oldYieldPos; + this.awaitPos = oldAwaitPos; + this.awaitIdentPos = oldAwaitIdentPos; + return this.finishNode(node, statement & FUNC_STATEMENT ? "FunctionDeclaration" : "FunctionExpression"); +}; +pp$8.parseFunctionParams = function(node) { + this.expect(types$1.parenL); + node.params = this.parseBindingList(types$1.parenR, false, this.options.ecmaVersion >= 8); + this.checkYieldAwaitInDefaultParams(); +}; +pp$8.parseClass = function(node, isStatement) { + this.next(); + var oldStrict = this.strict; + this.strict = true; + this.parseClassId(node, isStatement); + this.parseClassSuper(node); + var privateNameMap = this.enterClassBody(); + var classBody = this.startNode(); + var hadConstructor = false; + classBody.body = []; + this.expect(types$1.braceL); + while (this.type !== types$1.braceR) { + var element = this.parseClassElement(node.superClass !== null); + if (element) { + classBody.body.push(element); + if (element.type === "MethodDefinition" && element.kind === "constructor") { + if (hadConstructor) { + this.raise(element.start, "Duplicate constructor in the same class"); + } + hadConstructor = true; + } else if (element.key && element.key.type === "PrivateIdentifier" && isPrivateNameConflicted(privateNameMap, element)) { + this.raiseRecoverable(element.key.start, "Identifier '#" + element.key.name + "' has already been declared"); + } + } + } + this.strict = oldStrict; + this.next(); + node.body = this.finishNode(classBody, "ClassBody"); + this.exitClassBody(); + return this.finishNode(node, isStatement ? "ClassDeclaration" : "ClassExpression"); +}; +pp$8.parseClassElement = function(constructorAllowsSuper) { + if (this.eat(types$1.semi)) { + return null; + } + var ecmaVersion = this.options.ecmaVersion; + var node = this.startNode(); + var keyName = ""; + var isGenerator = false; + var isAsync = false; + var kind = "method"; + var isStatic = false; + if (this.eatContextual("static")) { + if (ecmaVersion >= 13 && this.eat(types$1.braceL)) { + this.parseClassStaticBlock(node); + return node; + } + if (this.isClassElementNameStart() || this.type === types$1.star) { + isStatic = true; + } else { + keyName = "static"; + } + } + node.static = isStatic; + if (!keyName && ecmaVersion >= 8 && this.eatContextual("async")) { + if ((this.isClassElementNameStart() || this.type === types$1.star) && !this.canInsertSemicolon()) { + isAsync = true; + } else { + keyName = "async"; + } + } + if (!keyName && (ecmaVersion >= 9 || !isAsync) && this.eat(types$1.star)) { + isGenerator = true; + } + if (!keyName && !isAsync && !isGenerator) { + var lastValue = this.value; + if (this.eatContextual("get") || this.eatContextual("set")) { + if (this.isClassElementNameStart()) { + kind = lastValue; + } else { + keyName = lastValue; + } + } + } + if (keyName) { + node.computed = false; + node.key = this.startNodeAt(this.lastTokStart, this.lastTokStartLoc); + node.key.name = keyName; + this.finishNode(node.key, "Identifier"); + } else { + this.parseClassElementName(node); + } + if (ecmaVersion < 13 || this.type === types$1.parenL || kind !== "method" || isGenerator || isAsync) { + var isConstructor = !node.static && checkKeyName(node, "constructor"); + var allowsDirectSuper = isConstructor && constructorAllowsSuper; + if (isConstructor && kind !== "method") { + this.raise(node.key.start, "Constructor can't have get/set modifier"); + } + node.kind = isConstructor ? "constructor" : kind; + this.parseClassMethod(node, isGenerator, isAsync, allowsDirectSuper); + } else { + this.parseClassField(node); + } + return node; +}; +pp$8.isClassElementNameStart = function() { + return this.type === types$1.name || this.type === types$1.privateId || this.type === types$1.num || this.type === types$1.string || this.type === types$1.bracketL || this.type.keyword; +}; +pp$8.parseClassElementName = function(element) { + if (this.type === types$1.privateId) { + if (this.value === "constructor") { + this.raise(this.start, "Classes can't have an element named '#constructor'"); + } + element.computed = false; + element.key = this.parsePrivateIdent(); + } else { + this.parsePropertyName(element); + } +}; +pp$8.parseClassMethod = function(method, isGenerator, isAsync, allowsDirectSuper) { + var key2 = method.key; + if (method.kind === "constructor") { + if (isGenerator) { + this.raise(key2.start, "Constructor can't be a generator"); + } + if (isAsync) { + this.raise(key2.start, "Constructor can't be an async method"); + } + } else if (method.static && checkKeyName(method, "prototype")) { + this.raise(key2.start, "Classes may not have a static property named prototype"); + } + var value = method.value = this.parseMethod(isGenerator, isAsync, allowsDirectSuper); + if (method.kind === "get" && value.params.length !== 0) { + this.raiseRecoverable(value.start, "getter should have no params"); + } + if (method.kind === "set" && value.params.length !== 1) { + this.raiseRecoverable(value.start, "setter should have exactly one param"); + } + if (method.kind === "set" && value.params[0].type === "RestElement") { + this.raiseRecoverable(value.params[0].start, "Setter cannot use rest params"); + } + return this.finishNode(method, "MethodDefinition"); +}; +pp$8.parseClassField = function(field) { + if (checkKeyName(field, "constructor")) { + this.raise(field.key.start, "Classes can't have a field named 'constructor'"); + } else if (field.static && checkKeyName(field, "prototype")) { + this.raise(field.key.start, "Classes can't have a static field named 'prototype'"); + } + if (this.eat(types$1.eq)) { + var scope = this.currentThisScope(); + var inClassFieldInit = scope.inClassFieldInit; + scope.inClassFieldInit = true; + field.value = this.parseMaybeAssign(); + scope.inClassFieldInit = inClassFieldInit; + } else { + field.value = null; + } + this.semicolon(); + return this.finishNode(field, "PropertyDefinition"); +}; +pp$8.parseClassStaticBlock = function(node) { + node.body = []; + var oldLabels = this.labels; + this.labels = []; + this.enterScope(SCOPE_CLASS_STATIC_BLOCK | SCOPE_SUPER); + while (this.type !== types$1.braceR) { + var stmt = this.parseStatement(null); + node.body.push(stmt); + } + this.next(); + this.exitScope(); + this.labels = oldLabels; + return this.finishNode(node, "StaticBlock"); +}; +pp$8.parseClassId = function(node, isStatement) { + if (this.type === types$1.name) { + node.id = this.parseIdent(); + if (isStatement) { + this.checkLValSimple(node.id, BIND_LEXICAL, false); + } + } else { + if (isStatement === true) { + this.unexpected(); + } + node.id = null; + } +}; +pp$8.parseClassSuper = function(node) { + node.superClass = this.eat(types$1._extends) ? this.parseExprSubscripts(null, false) : null; +}; +pp$8.enterClassBody = function() { + var element = { declared: /* @__PURE__ */ Object.create(null), used: [] }; + this.privateNameStack.push(element); + return element.declared; +}; +pp$8.exitClassBody = function() { + var ref2 = this.privateNameStack.pop(); + var declared = ref2.declared; + var used = ref2.used; + var len = this.privateNameStack.length; + var parent = len === 0 ? null : this.privateNameStack[len - 1]; + for (var i4 = 0; i4 < used.length; ++i4) { + var id2 = used[i4]; + if (!hasOwn(declared, id2.name)) { + if (parent) { + parent.used.push(id2); + } else { + this.raiseRecoverable(id2.start, "Private field '#" + id2.name + "' must be declared in an enclosing class"); + } + } + } +}; +function isPrivateNameConflicted(privateNameMap, element) { + var name = element.key.name; + var curr = privateNameMap[name]; + var next = "true"; + if (element.type === "MethodDefinition" && (element.kind === "get" || element.kind === "set")) { + next = (element.static ? "s" : "i") + element.kind; + } + if (curr === "iget" && next === "iset" || curr === "iset" && next === "iget" || curr === "sget" && next === "sset" || curr === "sset" && next === "sget") { + privateNameMap[name] = "true"; + return false; + } else if (!curr) { + privateNameMap[name] = next; + return false; + } else { + return true; + } +} +function checkKeyName(node, name) { + var computed = node.computed; + var key2 = node.key; + return !computed && (key2.type === "Identifier" && key2.name === name || key2.type === "Literal" && key2.value === name); +} +pp$8.parseExport = function(node, exports) { + this.next(); + if (this.eat(types$1.star)) { + if (this.options.ecmaVersion >= 11) { + if (this.eatContextual("as")) { + node.exported = this.parseModuleExportName(); + this.checkExport(exports, node.exported, this.lastTokStart); + } else { + node.exported = null; + } + } + this.expectContextual("from"); + if (this.type !== types$1.string) { + this.unexpected(); + } + node.source = this.parseExprAtom(); + this.semicolon(); + return this.finishNode(node, "ExportAllDeclaration"); + } + if (this.eat(types$1._default)) { + this.checkExport(exports, "default", this.lastTokStart); + var isAsync; + if (this.type === types$1._function || (isAsync = this.isAsyncFunction())) { + var fNode = this.startNode(); + this.next(); + if (isAsync) { + this.next(); + } + node.declaration = this.parseFunction(fNode, FUNC_STATEMENT | FUNC_NULLABLE_ID, false, isAsync); + } else if (this.type === types$1._class) { + var cNode = this.startNode(); + node.declaration = this.parseClass(cNode, "nullableID"); + } else { + node.declaration = this.parseMaybeAssign(); + this.semicolon(); + } + return this.finishNode(node, "ExportDefaultDeclaration"); + } + if (this.shouldParseExportStatement()) { + node.declaration = this.parseStatement(null); + if (node.declaration.type === "VariableDeclaration") { + this.checkVariableExport(exports, node.declaration.declarations); + } else { + this.checkExport(exports, node.declaration.id, node.declaration.id.start); + } + node.specifiers = []; + node.source = null; + } else { + node.declaration = null; + node.specifiers = this.parseExportSpecifiers(exports); + if (this.eatContextual("from")) { + if (this.type !== types$1.string) { + this.unexpected(); + } + node.source = this.parseExprAtom(); + } else { + for (var i4 = 0, list = node.specifiers; i4 < list.length; i4 += 1) { + var spec = list[i4]; + this.checkUnreserved(spec.local); + this.checkLocalExport(spec.local); + if (spec.local.type === "Literal") { + this.raise(spec.local.start, "A string literal cannot be used as an exported binding without `from`."); + } + } + node.source = null; + } + this.semicolon(); + } + return this.finishNode(node, "ExportNamedDeclaration"); +}; +pp$8.checkExport = function(exports, name, pos) { + if (!exports) { + return; + } + if (typeof name !== "string") { + name = name.type === "Identifier" ? name.name : name.value; + } + if (hasOwn(exports, name)) { + this.raiseRecoverable(pos, "Duplicate export '" + name + "'"); + } + exports[name] = true; +}; +pp$8.checkPatternExport = function(exports, pat) { + var type = pat.type; + if (type === "Identifier") { + this.checkExport(exports, pat, pat.start); + } else if (type === "ObjectPattern") { + for (var i4 = 0, list = pat.properties; i4 < list.length; i4 += 1) { + var prop = list[i4]; + this.checkPatternExport(exports, prop); + } + } else if (type === "ArrayPattern") { + for (var i$1 = 0, list$1 = pat.elements; i$1 < list$1.length; i$1 += 1) { + var elt = list$1[i$1]; + if (elt) { + this.checkPatternExport(exports, elt); + } + } + } else if (type === "Property") { + this.checkPatternExport(exports, pat.value); + } else if (type === "AssignmentPattern") { + this.checkPatternExport(exports, pat.left); + } else if (type === "RestElement") { + this.checkPatternExport(exports, pat.argument); + } else if (type === "ParenthesizedExpression") { + this.checkPatternExport(exports, pat.expression); + } +}; +pp$8.checkVariableExport = function(exports, decls) { + if (!exports) { + return; + } + for (var i4 = 0, list = decls; i4 < list.length; i4 += 1) { + var decl = list[i4]; + this.checkPatternExport(exports, decl.id); + } +}; +pp$8.shouldParseExportStatement = function() { + return this.type.keyword === "var" || this.type.keyword === "const" || this.type.keyword === "class" || this.type.keyword === "function" || this.isLet() || this.isAsyncFunction(); +}; +pp$8.parseExportSpecifiers = function(exports) { + var nodes = [], first = true; + this.expect(types$1.braceL); + while (!this.eat(types$1.braceR)) { + if (!first) { + this.expect(types$1.comma); + if (this.afterTrailingComma(types$1.braceR)) { + break; + } + } else { + first = false; + } + var node = this.startNode(); + node.local = this.parseModuleExportName(); + node.exported = this.eatContextual("as") ? this.parseModuleExportName() : node.local; + this.checkExport( + exports, + node.exported, + node.exported.start + ); + nodes.push(this.finishNode(node, "ExportSpecifier")); + } + return nodes; +}; +pp$8.parseImport = function(node) { + this.next(); + if (this.type === types$1.string) { + node.specifiers = empty$1; + node.source = this.parseExprAtom(); + } else { + node.specifiers = this.parseImportSpecifiers(); + this.expectContextual("from"); + node.source = this.type === types$1.string ? this.parseExprAtom() : this.unexpected(); + } + this.semicolon(); + return this.finishNode(node, "ImportDeclaration"); +}; +pp$8.parseImportSpecifiers = function() { + var nodes = [], first = true; + if (this.type === types$1.name) { + var node = this.startNode(); + node.local = this.parseIdent(); + this.checkLValSimple(node.local, BIND_LEXICAL); + nodes.push(this.finishNode(node, "ImportDefaultSpecifier")); + if (!this.eat(types$1.comma)) { + return nodes; + } + } + if (this.type === types$1.star) { + var node$1 = this.startNode(); + this.next(); + this.expectContextual("as"); + node$1.local = this.parseIdent(); + this.checkLValSimple(node$1.local, BIND_LEXICAL); + nodes.push(this.finishNode(node$1, "ImportNamespaceSpecifier")); + return nodes; + } + this.expect(types$1.braceL); + while (!this.eat(types$1.braceR)) { + if (!first) { + this.expect(types$1.comma); + if (this.afterTrailingComma(types$1.braceR)) { + break; + } + } else { + first = false; + } + var node$2 = this.startNode(); + node$2.imported = this.parseModuleExportName(); + if (this.eatContextual("as")) { + node$2.local = this.parseIdent(); + } else { + this.checkUnreserved(node$2.imported); + node$2.local = node$2.imported; + } + this.checkLValSimple(node$2.local, BIND_LEXICAL); + nodes.push(this.finishNode(node$2, "ImportSpecifier")); + } + return nodes; +}; +pp$8.parseModuleExportName = function() { + if (this.options.ecmaVersion >= 13 && this.type === types$1.string) { + var stringLiteral = this.parseLiteral(this.value); + if (loneSurrogate.test(stringLiteral.value)) { + this.raise(stringLiteral.start, "An export name cannot include a lone surrogate."); + } + return stringLiteral; + } + return this.parseIdent(true); +}; +pp$8.adaptDirectivePrologue = function(statements) { + for (var i4 = 0; i4 < statements.length && this.isDirectiveCandidate(statements[i4]); ++i4) { + statements[i4].directive = statements[i4].expression.raw.slice(1, -1); + } +}; +pp$8.isDirectiveCandidate = function(statement) { + return this.options.ecmaVersion >= 5 && statement.type === "ExpressionStatement" && statement.expression.type === "Literal" && typeof statement.expression.value === "string" && (this.input[statement.start] === '"' || this.input[statement.start] === "'"); +}; +var pp$7 = Parser.prototype; +pp$7.toAssignable = function(node, isBinding, refDestructuringErrors) { + if (this.options.ecmaVersion >= 6 && node) { + switch (node.type) { + case "Identifier": + if (this.inAsync && node.name === "await") { + this.raise(node.start, "Cannot use 'await' as identifier inside an async function"); + } + break; + case "ObjectPattern": + case "ArrayPattern": + case "AssignmentPattern": + case "RestElement": + break; + case "ObjectExpression": + node.type = "ObjectPattern"; + if (refDestructuringErrors) { + this.checkPatternErrors(refDestructuringErrors, true); + } + for (var i4 = 0, list = node.properties; i4 < list.length; i4 += 1) { + var prop = list[i4]; + this.toAssignable(prop, isBinding); + if (prop.type === "RestElement" && (prop.argument.type === "ArrayPattern" || prop.argument.type === "ObjectPattern")) { + this.raise(prop.argument.start, "Unexpected token"); + } + } + break; + case "Property": + if (node.kind !== "init") { + this.raise(node.key.start, "Object pattern can't contain getter or setter"); + } + this.toAssignable(node.value, isBinding); + break; + case "ArrayExpression": + node.type = "ArrayPattern"; + if (refDestructuringErrors) { + this.checkPatternErrors(refDestructuringErrors, true); + } + this.toAssignableList(node.elements, isBinding); + break; + case "SpreadElement": + node.type = "RestElement"; + this.toAssignable(node.argument, isBinding); + if (node.argument.type === "AssignmentPattern") { + this.raise(node.argument.start, "Rest elements cannot have a default value"); + } + break; + case "AssignmentExpression": + if (node.operator !== "=") { + this.raise(node.left.end, "Only '=' operator can be used for specifying default value."); + } + node.type = "AssignmentPattern"; + delete node.operator; + this.toAssignable(node.left, isBinding); + break; + case "ParenthesizedExpression": + this.toAssignable(node.expression, isBinding, refDestructuringErrors); + break; + case "ChainExpression": + this.raiseRecoverable(node.start, "Optional chaining cannot appear in left-hand side"); + break; + case "MemberExpression": + if (!isBinding) { + break; + } + default: + this.raise(node.start, "Assigning to rvalue"); + } + } else if (refDestructuringErrors) { + this.checkPatternErrors(refDestructuringErrors, true); + } + return node; +}; +pp$7.toAssignableList = function(exprList, isBinding) { + var end = exprList.length; + for (var i4 = 0; i4 < end; i4++) { + var elt = exprList[i4]; + if (elt) { + this.toAssignable(elt, isBinding); + } + } + if (end) { + var last = exprList[end - 1]; + if (this.options.ecmaVersion === 6 && isBinding && last && last.type === "RestElement" && last.argument.type !== "Identifier") { + this.unexpected(last.argument.start); + } + } + return exprList; +}; +pp$7.parseSpread = function(refDestructuringErrors) { + var node = this.startNode(); + this.next(); + node.argument = this.parseMaybeAssign(false, refDestructuringErrors); + return this.finishNode(node, "SpreadElement"); +}; +pp$7.parseRestBinding = function() { + var node = this.startNode(); + this.next(); + if (this.options.ecmaVersion === 6 && this.type !== types$1.name) { + this.unexpected(); + } + node.argument = this.parseBindingAtom(); + return this.finishNode(node, "RestElement"); +}; +pp$7.parseBindingAtom = function() { + if (this.options.ecmaVersion >= 6) { + switch (this.type) { + case types$1.bracketL: + var node = this.startNode(); + this.next(); + node.elements = this.parseBindingList(types$1.bracketR, true, true); + return this.finishNode(node, "ArrayPattern"); + case types$1.braceL: + return this.parseObj(true); + } + } + return this.parseIdent(); +}; +pp$7.parseBindingList = function(close, allowEmpty, allowTrailingComma) { + var elts = [], first = true; + while (!this.eat(close)) { + if (first) { + first = false; + } else { + this.expect(types$1.comma); + } + if (allowEmpty && this.type === types$1.comma) { + elts.push(null); + } else if (allowTrailingComma && this.afterTrailingComma(close)) { + break; + } else if (this.type === types$1.ellipsis) { + var rest = this.parseRestBinding(); + this.parseBindingListItem(rest); + elts.push(rest); + if (this.type === types$1.comma) { + this.raise(this.start, "Comma is not permitted after the rest element"); + } + this.expect(close); + break; + } else { + var elem = this.parseMaybeDefault(this.start, this.startLoc); + this.parseBindingListItem(elem); + elts.push(elem); + } + } + return elts; +}; +pp$7.parseBindingListItem = function(param) { + return param; +}; +pp$7.parseMaybeDefault = function(startPos, startLoc, left) { + left = left || this.parseBindingAtom(); + if (this.options.ecmaVersion < 6 || !this.eat(types$1.eq)) { + return left; + } + var node = this.startNodeAt(startPos, startLoc); + node.left = left; + node.right = this.parseMaybeAssign(); + return this.finishNode(node, "AssignmentPattern"); +}; +pp$7.checkLValSimple = function(expr, bindingType, checkClashes) { + if (bindingType === void 0) + bindingType = BIND_NONE; + var isBind = bindingType !== BIND_NONE; + switch (expr.type) { + case "Identifier": + if (this.strict && this.reservedWordsStrictBind.test(expr.name)) { + this.raiseRecoverable(expr.start, (isBind ? "Binding " : "Assigning to ") + expr.name + " in strict mode"); + } + if (isBind) { + if (bindingType === BIND_LEXICAL && expr.name === "let") { + this.raiseRecoverable(expr.start, "let is disallowed as a lexically bound name"); + } + if (checkClashes) { + if (hasOwn(checkClashes, expr.name)) { + this.raiseRecoverable(expr.start, "Argument name clash"); + } + checkClashes[expr.name] = true; + } + if (bindingType !== BIND_OUTSIDE) { + this.declareName(expr.name, bindingType, expr.start); + } + } + break; + case "ChainExpression": + this.raiseRecoverable(expr.start, "Optional chaining cannot appear in left-hand side"); + break; + case "MemberExpression": + if (isBind) { + this.raiseRecoverable(expr.start, "Binding member expression"); + } + break; + case "ParenthesizedExpression": + if (isBind) { + this.raiseRecoverable(expr.start, "Binding parenthesized expression"); + } + return this.checkLValSimple(expr.expression, bindingType, checkClashes); + default: + this.raise(expr.start, (isBind ? "Binding" : "Assigning to") + " rvalue"); + } +}; +pp$7.checkLValPattern = function(expr, bindingType, checkClashes) { + if (bindingType === void 0) + bindingType = BIND_NONE; + switch (expr.type) { + case "ObjectPattern": + for (var i4 = 0, list = expr.properties; i4 < list.length; i4 += 1) { + var prop = list[i4]; + this.checkLValInnerPattern(prop, bindingType, checkClashes); + } + break; + case "ArrayPattern": + for (var i$1 = 0, list$1 = expr.elements; i$1 < list$1.length; i$1 += 1) { + var elem = list$1[i$1]; + if (elem) { + this.checkLValInnerPattern(elem, bindingType, checkClashes); + } + } + break; + default: + this.checkLValSimple(expr, bindingType, checkClashes); + } +}; +pp$7.checkLValInnerPattern = function(expr, bindingType, checkClashes) { + if (bindingType === void 0) + bindingType = BIND_NONE; + switch (expr.type) { + case "Property": + this.checkLValInnerPattern(expr.value, bindingType, checkClashes); + break; + case "AssignmentPattern": + this.checkLValPattern(expr.left, bindingType, checkClashes); + break; + case "RestElement": + this.checkLValPattern(expr.argument, bindingType, checkClashes); + break; + default: + this.checkLValPattern(expr, bindingType, checkClashes); + } +}; +var TokContext = function TokContext2(token, isExpr, preserveSpace, override, generator) { + this.token = token; + this.isExpr = !!isExpr; + this.preserveSpace = !!preserveSpace; + this.override = override; + this.generator = !!generator; +}; +var types = { + b_stat: new TokContext("{", false), + b_expr: new TokContext("{", true), + b_tmpl: new TokContext("${", false), + p_stat: new TokContext("(", false), + p_expr: new TokContext("(", true), + q_tmpl: new TokContext("`", true, true, function(p3) { + return p3.tryReadTemplateToken(); + }), + f_stat: new TokContext("function", false), + f_expr: new TokContext("function", true), + f_expr_gen: new TokContext("function", true, false, null, true), + f_gen: new TokContext("function", false, false, null, true) +}; +var pp$6 = Parser.prototype; +pp$6.initialContext = function() { + return [types.b_stat]; +}; +pp$6.curContext = function() { + return this.context[this.context.length - 1]; +}; +pp$6.braceIsBlock = function(prevType) { + var parent = this.curContext(); + if (parent === types.f_expr || parent === types.f_stat) { + return true; + } + if (prevType === types$1.colon && (parent === types.b_stat || parent === types.b_expr)) { + return !parent.isExpr; + } + if (prevType === types$1._return || prevType === types$1.name && this.exprAllowed) { + return lineBreak.test(this.input.slice(this.lastTokEnd, this.start)); + } + if (prevType === types$1._else || prevType === types$1.semi || prevType === types$1.eof || prevType === types$1.parenR || prevType === types$1.arrow) { + return true; + } + if (prevType === types$1.braceL) { + return parent === types.b_stat; + } + if (prevType === types$1._var || prevType === types$1._const || prevType === types$1.name) { + return false; + } + return !this.exprAllowed; +}; +pp$6.inGeneratorContext = function() { + for (var i4 = this.context.length - 1; i4 >= 1; i4--) { + var context = this.context[i4]; + if (context.token === "function") { + return context.generator; + } + } + return false; +}; +pp$6.updateContext = function(prevType) { + var update, type = this.type; + if (type.keyword && prevType === types$1.dot) { + this.exprAllowed = false; + } else if (update = type.updateContext) { + update.call(this, prevType); + } else { + this.exprAllowed = type.beforeExpr; + } +}; +pp$6.overrideContext = function(tokenCtx) { + if (this.curContext() !== tokenCtx) { + this.context[this.context.length - 1] = tokenCtx; + } +}; +types$1.parenR.updateContext = types$1.braceR.updateContext = function() { + if (this.context.length === 1) { + this.exprAllowed = true; + return; + } + var out = this.context.pop(); + if (out === types.b_stat && this.curContext().token === "function") { + out = this.context.pop(); + } + this.exprAllowed = !out.isExpr; +}; +types$1.braceL.updateContext = function(prevType) { + this.context.push(this.braceIsBlock(prevType) ? types.b_stat : types.b_expr); + this.exprAllowed = true; +}; +types$1.dollarBraceL.updateContext = function() { + this.context.push(types.b_tmpl); + this.exprAllowed = true; +}; +types$1.parenL.updateContext = function(prevType) { + var statementParens = prevType === types$1._if || prevType === types$1._for || prevType === types$1._with || prevType === types$1._while; + this.context.push(statementParens ? types.p_stat : types.p_expr); + this.exprAllowed = true; +}; +types$1.incDec.updateContext = function() { +}; +types$1._function.updateContext = types$1._class.updateContext = function(prevType) { + if (prevType.beforeExpr && prevType !== types$1._else && !(prevType === types$1.semi && this.curContext() !== types.p_stat) && !(prevType === types$1._return && lineBreak.test(this.input.slice(this.lastTokEnd, this.start))) && !((prevType === types$1.colon || prevType === types$1.braceL) && this.curContext() === types.b_stat)) { + this.context.push(types.f_expr); + } else { + this.context.push(types.f_stat); + } + this.exprAllowed = false; +}; +types$1.backQuote.updateContext = function() { + if (this.curContext() === types.q_tmpl) { + this.context.pop(); + } else { + this.context.push(types.q_tmpl); + } + this.exprAllowed = false; +}; +types$1.star.updateContext = function(prevType) { + if (prevType === types$1._function) { + var index = this.context.length - 1; + if (this.context[index] === types.f_expr) { + this.context[index] = types.f_expr_gen; + } else { + this.context[index] = types.f_gen; + } + } + this.exprAllowed = true; +}; +types$1.name.updateContext = function(prevType) { + var allowed = false; + if (this.options.ecmaVersion >= 6 && prevType !== types$1.dot) { + if (this.value === "of" && !this.exprAllowed || this.value === "yield" && this.inGeneratorContext()) { + allowed = true; + } + } + this.exprAllowed = allowed; +}; +var pp$5 = Parser.prototype; +pp$5.checkPropClash = function(prop, propHash, refDestructuringErrors) { + if (this.options.ecmaVersion >= 9 && prop.type === "SpreadElement") { + return; + } + if (this.options.ecmaVersion >= 6 && (prop.computed || prop.method || prop.shorthand)) { + return; + } + var key2 = prop.key; + var name; + switch (key2.type) { + case "Identifier": + name = key2.name; + break; + case "Literal": + name = String(key2.value); + break; + default: + return; + } + var kind = prop.kind; + if (this.options.ecmaVersion >= 6) { + if (name === "__proto__" && kind === "init") { + if (propHash.proto) { + if (refDestructuringErrors) { + if (refDestructuringErrors.doubleProto < 0) { + refDestructuringErrors.doubleProto = key2.start; + } + } else { + this.raiseRecoverable(key2.start, "Redefinition of __proto__ property"); + } + } + propHash.proto = true; + } + return; + } + name = "$" + name; + var other = propHash[name]; + if (other) { + var redefinition; + if (kind === "init") { + redefinition = this.strict && other.init || other.get || other.set; + } else { + redefinition = other.init || other[kind]; + } + if (redefinition) { + this.raiseRecoverable(key2.start, "Redefinition of property"); + } + } else { + other = propHash[name] = { + init: false, + get: false, + set: false + }; + } + other[kind] = true; +}; +pp$5.parseExpression = function(forInit, refDestructuringErrors) { + var startPos = this.start, startLoc = this.startLoc; + var expr = this.parseMaybeAssign(forInit, refDestructuringErrors); + if (this.type === types$1.comma) { + var node = this.startNodeAt(startPos, startLoc); + node.expressions = [expr]; + while (this.eat(types$1.comma)) { + node.expressions.push(this.parseMaybeAssign(forInit, refDestructuringErrors)); + } + return this.finishNode(node, "SequenceExpression"); + } + return expr; +}; +pp$5.parseMaybeAssign = function(forInit, refDestructuringErrors, afterLeftParse) { + if (this.isContextual("yield")) { + if (this.inGenerator) { + return this.parseYield(forInit); + } else { + this.exprAllowed = false; + } + } + var ownDestructuringErrors = false, oldParenAssign = -1, oldTrailingComma = -1, oldDoubleProto = -1; + if (refDestructuringErrors) { + oldParenAssign = refDestructuringErrors.parenthesizedAssign; + oldTrailingComma = refDestructuringErrors.trailingComma; + oldDoubleProto = refDestructuringErrors.doubleProto; + refDestructuringErrors.parenthesizedAssign = refDestructuringErrors.trailingComma = -1; + } else { + refDestructuringErrors = new DestructuringErrors(); + ownDestructuringErrors = true; + } + var startPos = this.start, startLoc = this.startLoc; + if (this.type === types$1.parenL || this.type === types$1.name) { + this.potentialArrowAt = this.start; + this.potentialArrowInForAwait = forInit === "await"; + } + var left = this.parseMaybeConditional(forInit, refDestructuringErrors); + if (afterLeftParse) { + left = afterLeftParse.call(this, left, startPos, startLoc); + } + if (this.type.isAssign) { + var node = this.startNodeAt(startPos, startLoc); + node.operator = this.value; + if (this.type === types$1.eq) { + left = this.toAssignable(left, false, refDestructuringErrors); + } + if (!ownDestructuringErrors) { + refDestructuringErrors.parenthesizedAssign = refDestructuringErrors.trailingComma = refDestructuringErrors.doubleProto = -1; + } + if (refDestructuringErrors.shorthandAssign >= left.start) { + refDestructuringErrors.shorthandAssign = -1; + } + if (this.type === types$1.eq) { + this.checkLValPattern(left); + } else { + this.checkLValSimple(left); + } + node.left = left; + this.next(); + node.right = this.parseMaybeAssign(forInit); + if (oldDoubleProto > -1) { + refDestructuringErrors.doubleProto = oldDoubleProto; + } + return this.finishNode(node, "AssignmentExpression"); + } else { + if (ownDestructuringErrors) { + this.checkExpressionErrors(refDestructuringErrors, true); + } + } + if (oldParenAssign > -1) { + refDestructuringErrors.parenthesizedAssign = oldParenAssign; + } + if (oldTrailingComma > -1) { + refDestructuringErrors.trailingComma = oldTrailingComma; + } + return left; +}; +pp$5.parseMaybeConditional = function(forInit, refDestructuringErrors) { + var startPos = this.start, startLoc = this.startLoc; + var expr = this.parseExprOps(forInit, refDestructuringErrors); + if (this.checkExpressionErrors(refDestructuringErrors)) { + return expr; + } + if (this.eat(types$1.question)) { + var node = this.startNodeAt(startPos, startLoc); + node.test = expr; + node.consequent = this.parseMaybeAssign(); + this.expect(types$1.colon); + node.alternate = this.parseMaybeAssign(forInit); + return this.finishNode(node, "ConditionalExpression"); + } + return expr; +}; +pp$5.parseExprOps = function(forInit, refDestructuringErrors) { + var startPos = this.start, startLoc = this.startLoc; + var expr = this.parseMaybeUnary(refDestructuringErrors, false, false, forInit); + if (this.checkExpressionErrors(refDestructuringErrors)) { + return expr; + } + return expr.start === startPos && expr.type === "ArrowFunctionExpression" ? expr : this.parseExprOp(expr, startPos, startLoc, -1, forInit); +}; +pp$5.parseExprOp = function(left, leftStartPos, leftStartLoc, minPrec, forInit) { + var prec = this.type.binop; + if (prec != null && (!forInit || this.type !== types$1._in)) { + if (prec > minPrec) { + var logical = this.type === types$1.logicalOR || this.type === types$1.logicalAND; + var coalesce = this.type === types$1.coalesce; + if (coalesce) { + prec = types$1.logicalAND.binop; + } + var op = this.value; + this.next(); + var startPos = this.start, startLoc = this.startLoc; + var right = this.parseExprOp(this.parseMaybeUnary(null, false, false, forInit), startPos, startLoc, prec, forInit); + var node = this.buildBinary(leftStartPos, leftStartLoc, left, right, op, logical || coalesce); + if (logical && this.type === types$1.coalesce || coalesce && (this.type === types$1.logicalOR || this.type === types$1.logicalAND)) { + this.raiseRecoverable(this.start, "Logical expressions and coalesce expressions cannot be mixed. Wrap either by parentheses"); + } + return this.parseExprOp(node, leftStartPos, leftStartLoc, minPrec, forInit); + } + } + return left; +}; +pp$5.buildBinary = function(startPos, startLoc, left, right, op, logical) { + if (right.type === "PrivateIdentifier") { + this.raise(right.start, "Private identifier can only be left side of binary expression"); + } + var node = this.startNodeAt(startPos, startLoc); + node.left = left; + node.operator = op; + node.right = right; + return this.finishNode(node, logical ? "LogicalExpression" : "BinaryExpression"); +}; +pp$5.parseMaybeUnary = function(refDestructuringErrors, sawUnary, incDec, forInit) { + var startPos = this.start, startLoc = this.startLoc, expr; + if (this.isContextual("await") && this.canAwait) { + expr = this.parseAwait(forInit); + sawUnary = true; + } else if (this.type.prefix) { + var node = this.startNode(), update = this.type === types$1.incDec; + node.operator = this.value; + node.prefix = true; + this.next(); + node.argument = this.parseMaybeUnary(null, true, update, forInit); + this.checkExpressionErrors(refDestructuringErrors, true); + if (update) { + this.checkLValSimple(node.argument); + } else if (this.strict && node.operator === "delete" && node.argument.type === "Identifier") { + this.raiseRecoverable(node.start, "Deleting local variable in strict mode"); + } else if (node.operator === "delete" && isPrivateFieldAccess(node.argument)) { + this.raiseRecoverable(node.start, "Private fields can not be deleted"); + } else { + sawUnary = true; + } + expr = this.finishNode(node, update ? "UpdateExpression" : "UnaryExpression"); + } else if (!sawUnary && this.type === types$1.privateId) { + if (forInit || this.privateNameStack.length === 0) { + this.unexpected(); + } + expr = this.parsePrivateIdent(); + if (this.type !== types$1._in) { + this.unexpected(); + } + } else { + expr = this.parseExprSubscripts(refDestructuringErrors, forInit); + if (this.checkExpressionErrors(refDestructuringErrors)) { + return expr; + } + while (this.type.postfix && !this.canInsertSemicolon()) { + var node$1 = this.startNodeAt(startPos, startLoc); + node$1.operator = this.value; + node$1.prefix = false; + node$1.argument = expr; + this.checkLValSimple(expr); + this.next(); + expr = this.finishNode(node$1, "UpdateExpression"); + } + } + if (!incDec && this.eat(types$1.starstar)) { + if (sawUnary) { + this.unexpected(this.lastTokStart); + } else { + return this.buildBinary(startPos, startLoc, expr, this.parseMaybeUnary(null, false, false, forInit), "**", false); + } + } else { + return expr; + } +}; +function isPrivateFieldAccess(node) { + return node.type === "MemberExpression" && node.property.type === "PrivateIdentifier" || node.type === "ChainExpression" && isPrivateFieldAccess(node.expression); +} +pp$5.parseExprSubscripts = function(refDestructuringErrors, forInit) { + var startPos = this.start, startLoc = this.startLoc; + var expr = this.parseExprAtom(refDestructuringErrors, forInit); + if (expr.type === "ArrowFunctionExpression" && this.input.slice(this.lastTokStart, this.lastTokEnd) !== ")") { + return expr; + } + var result = this.parseSubscripts(expr, startPos, startLoc, false, forInit); + if (refDestructuringErrors && result.type === "MemberExpression") { + if (refDestructuringErrors.parenthesizedAssign >= result.start) { + refDestructuringErrors.parenthesizedAssign = -1; + } + if (refDestructuringErrors.parenthesizedBind >= result.start) { + refDestructuringErrors.parenthesizedBind = -1; + } + if (refDestructuringErrors.trailingComma >= result.start) { + refDestructuringErrors.trailingComma = -1; + } + } + return result; +}; +pp$5.parseSubscripts = function(base2, startPos, startLoc, noCalls, forInit) { + var maybeAsyncArrow = this.options.ecmaVersion >= 8 && base2.type === "Identifier" && base2.name === "async" && this.lastTokEnd === base2.end && !this.canInsertSemicolon() && base2.end - base2.start === 5 && this.potentialArrowAt === base2.start; + var optionalChained = false; + while (true) { + var element = this.parseSubscript(base2, startPos, startLoc, noCalls, maybeAsyncArrow, optionalChained, forInit); + if (element.optional) { + optionalChained = true; + } + if (element === base2 || element.type === "ArrowFunctionExpression") { + if (optionalChained) { + var chainNode = this.startNodeAt(startPos, startLoc); + chainNode.expression = element; + element = this.finishNode(chainNode, "ChainExpression"); + } + return element; + } + base2 = element; + } +}; +pp$5.parseSubscript = function(base2, startPos, startLoc, noCalls, maybeAsyncArrow, optionalChained, forInit) { + var optionalSupported = this.options.ecmaVersion >= 11; + var optional = optionalSupported && this.eat(types$1.questionDot); + if (noCalls && optional) { + this.raise(this.lastTokStart, "Optional chaining cannot appear in the callee of new expressions"); + } + var computed = this.eat(types$1.bracketL); + if (computed || optional && this.type !== types$1.parenL && this.type !== types$1.backQuote || this.eat(types$1.dot)) { + var node = this.startNodeAt(startPos, startLoc); + node.object = base2; + if (computed) { + node.property = this.parseExpression(); + this.expect(types$1.bracketR); + } else if (this.type === types$1.privateId && base2.type !== "Super") { + node.property = this.parsePrivateIdent(); + } else { + node.property = this.parseIdent(this.options.allowReserved !== "never"); + } + node.computed = !!computed; + if (optionalSupported) { + node.optional = optional; + } + base2 = this.finishNode(node, "MemberExpression"); + } else if (!noCalls && this.eat(types$1.parenL)) { + var refDestructuringErrors = new DestructuringErrors(), oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos; + this.yieldPos = 0; + this.awaitPos = 0; + this.awaitIdentPos = 0; + var exprList = this.parseExprList(types$1.parenR, this.options.ecmaVersion >= 8, false, refDestructuringErrors); + if (maybeAsyncArrow && !optional && !this.canInsertSemicolon() && this.eat(types$1.arrow)) { + this.checkPatternErrors(refDestructuringErrors, false); + this.checkYieldAwaitInDefaultParams(); + if (this.awaitIdentPos > 0) { + this.raise(this.awaitIdentPos, "Cannot use 'await' as identifier inside an async function"); + } + this.yieldPos = oldYieldPos; + this.awaitPos = oldAwaitPos; + this.awaitIdentPos = oldAwaitIdentPos; + return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), exprList, true, forInit); + } + this.checkExpressionErrors(refDestructuringErrors, true); + this.yieldPos = oldYieldPos || this.yieldPos; + this.awaitPos = oldAwaitPos || this.awaitPos; + this.awaitIdentPos = oldAwaitIdentPos || this.awaitIdentPos; + var node$1 = this.startNodeAt(startPos, startLoc); + node$1.callee = base2; + node$1.arguments = exprList; + if (optionalSupported) { + node$1.optional = optional; + } + base2 = this.finishNode(node$1, "CallExpression"); + } else if (this.type === types$1.backQuote) { + if (optional || optionalChained) { + this.raise(this.start, "Optional chaining cannot appear in the tag of tagged template expressions"); + } + var node$2 = this.startNodeAt(startPos, startLoc); + node$2.tag = base2; + node$2.quasi = this.parseTemplate({ isTagged: true }); + base2 = this.finishNode(node$2, "TaggedTemplateExpression"); + } + return base2; +}; +pp$5.parseExprAtom = function(refDestructuringErrors, forInit) { + if (this.type === types$1.slash) { + this.readRegexp(); + } + var node, canBeArrow = this.potentialArrowAt === this.start; + switch (this.type) { + case types$1._super: + if (!this.allowSuper) { + this.raise(this.start, "'super' keyword outside a method"); + } + node = this.startNode(); + this.next(); + if (this.type === types$1.parenL && !this.allowDirectSuper) { + this.raise(node.start, "super() call outside constructor of a subclass"); + } + if (this.type !== types$1.dot && this.type !== types$1.bracketL && this.type !== types$1.parenL) { + this.unexpected(); + } + return this.finishNode(node, "Super"); + case types$1._this: + node = this.startNode(); + this.next(); + return this.finishNode(node, "ThisExpression"); + case types$1.name: + var startPos = this.start, startLoc = this.startLoc, containsEsc = this.containsEsc; + var id2 = this.parseIdent(false); + if (this.options.ecmaVersion >= 8 && !containsEsc && id2.name === "async" && !this.canInsertSemicolon() && this.eat(types$1._function)) { + this.overrideContext(types.f_expr); + return this.parseFunction(this.startNodeAt(startPos, startLoc), 0, false, true, forInit); + } + if (canBeArrow && !this.canInsertSemicolon()) { + if (this.eat(types$1.arrow)) { + return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), [id2], false, forInit); + } + if (this.options.ecmaVersion >= 8 && id2.name === "async" && this.type === types$1.name && !containsEsc && (!this.potentialArrowInForAwait || this.value !== "of" || this.containsEsc)) { + id2 = this.parseIdent(false); + if (this.canInsertSemicolon() || !this.eat(types$1.arrow)) { + this.unexpected(); + } + return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), [id2], true, forInit); + } + } + return id2; + case types$1.regexp: + var value = this.value; + node = this.parseLiteral(value.value); + node.regex = { pattern: value.pattern, flags: value.flags }; + return node; + case types$1.num: + case types$1.string: + return this.parseLiteral(this.value); + case types$1._null: + case types$1._true: + case types$1._false: + node = this.startNode(); + node.value = this.type === types$1._null ? null : this.type === types$1._true; + node.raw = this.type.keyword; + this.next(); + return this.finishNode(node, "Literal"); + case types$1.parenL: + var start = this.start, expr = this.parseParenAndDistinguishExpression(canBeArrow, forInit); + if (refDestructuringErrors) { + if (refDestructuringErrors.parenthesizedAssign < 0 && !this.isSimpleAssignTarget(expr)) { + refDestructuringErrors.parenthesizedAssign = start; + } + if (refDestructuringErrors.parenthesizedBind < 0) { + refDestructuringErrors.parenthesizedBind = start; + } + } + return expr; + case types$1.bracketL: + node = this.startNode(); + this.next(); + node.elements = this.parseExprList(types$1.bracketR, true, true, refDestructuringErrors); + return this.finishNode(node, "ArrayExpression"); + case types$1.braceL: + this.overrideContext(types.b_expr); + return this.parseObj(false, refDestructuringErrors); + case types$1._function: + node = this.startNode(); + this.next(); + return this.parseFunction(node, 0); + case types$1._class: + return this.parseClass(this.startNode(), false); + case types$1._new: + return this.parseNew(); + case types$1.backQuote: + return this.parseTemplate(); + case types$1._import: + if (this.options.ecmaVersion >= 11) { + return this.parseExprImport(); + } else { + return this.unexpected(); + } + default: + this.unexpected(); + } +}; +pp$5.parseExprImport = function() { + var node = this.startNode(); + if (this.containsEsc) { + this.raiseRecoverable(this.start, "Escape sequence in keyword import"); + } + var meta = this.parseIdent(true); + switch (this.type) { + case types$1.parenL: + return this.parseDynamicImport(node); + case types$1.dot: + node.meta = meta; + return this.parseImportMeta(node); + default: + this.unexpected(); + } +}; +pp$5.parseDynamicImport = function(node) { + this.next(); + node.source = this.parseMaybeAssign(); + if (!this.eat(types$1.parenR)) { + var errorPos = this.start; + if (this.eat(types$1.comma) && this.eat(types$1.parenR)) { + this.raiseRecoverable(errorPos, "Trailing comma is not allowed in import()"); + } else { + this.unexpected(errorPos); + } + } + return this.finishNode(node, "ImportExpression"); +}; +pp$5.parseImportMeta = function(node) { + this.next(); + var containsEsc = this.containsEsc; + node.property = this.parseIdent(true); + if (node.property.name !== "meta") { + this.raiseRecoverable(node.property.start, "The only valid meta property for import is 'import.meta'"); + } + if (containsEsc) { + this.raiseRecoverable(node.start, "'import.meta' must not contain escaped characters"); + } + if (this.options.sourceType !== "module" && !this.options.allowImportExportEverywhere) { + this.raiseRecoverable(node.start, "Cannot use 'import.meta' outside a module"); + } + return this.finishNode(node, "MetaProperty"); +}; +pp$5.parseLiteral = function(value) { + var node = this.startNode(); + node.value = value; + node.raw = this.input.slice(this.start, this.end); + if (node.raw.charCodeAt(node.raw.length - 1) === 110) { + node.bigint = node.raw.slice(0, -1).replace(/_/g, ""); + } + this.next(); + return this.finishNode(node, "Literal"); +}; +pp$5.parseParenExpression = function() { + this.expect(types$1.parenL); + var val = this.parseExpression(); + this.expect(types$1.parenR); + return val; +}; +pp$5.parseParenAndDistinguishExpression = function(canBeArrow, forInit) { + var startPos = this.start, startLoc = this.startLoc, val, allowTrailingComma = this.options.ecmaVersion >= 8; + if (this.options.ecmaVersion >= 6) { + this.next(); + var innerStartPos = this.start, innerStartLoc = this.startLoc; + var exprList = [], first = true, lastIsComma = false; + var refDestructuringErrors = new DestructuringErrors(), oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, spreadStart; + this.yieldPos = 0; + this.awaitPos = 0; + while (this.type !== types$1.parenR) { + first ? first = false : this.expect(types$1.comma); + if (allowTrailingComma && this.afterTrailingComma(types$1.parenR, true)) { + lastIsComma = true; + break; + } else if (this.type === types$1.ellipsis) { + spreadStart = this.start; + exprList.push(this.parseParenItem(this.parseRestBinding())); + if (this.type === types$1.comma) { + this.raise(this.start, "Comma is not permitted after the rest element"); + } + break; + } else { + exprList.push(this.parseMaybeAssign(false, refDestructuringErrors, this.parseParenItem)); + } + } + var innerEndPos = this.lastTokEnd, innerEndLoc = this.lastTokEndLoc; + this.expect(types$1.parenR); + if (canBeArrow && !this.canInsertSemicolon() && this.eat(types$1.arrow)) { + this.checkPatternErrors(refDestructuringErrors, false); + this.checkYieldAwaitInDefaultParams(); + this.yieldPos = oldYieldPos; + this.awaitPos = oldAwaitPos; + return this.parseParenArrowList(startPos, startLoc, exprList, forInit); + } + if (!exprList.length || lastIsComma) { + this.unexpected(this.lastTokStart); + } + if (spreadStart) { + this.unexpected(spreadStart); + } + this.checkExpressionErrors(refDestructuringErrors, true); + this.yieldPos = oldYieldPos || this.yieldPos; + this.awaitPos = oldAwaitPos || this.awaitPos; + if (exprList.length > 1) { + val = this.startNodeAt(innerStartPos, innerStartLoc); + val.expressions = exprList; + this.finishNodeAt(val, "SequenceExpression", innerEndPos, innerEndLoc); + } else { + val = exprList[0]; + } + } else { + val = this.parseParenExpression(); + } + if (this.options.preserveParens) { + var par = this.startNodeAt(startPos, startLoc); + par.expression = val; + return this.finishNode(par, "ParenthesizedExpression"); + } else { + return val; + } +}; +pp$5.parseParenItem = function(item) { + return item; +}; +pp$5.parseParenArrowList = function(startPos, startLoc, exprList, forInit) { + return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), exprList, false, forInit); +}; +var empty = []; +pp$5.parseNew = function() { + if (this.containsEsc) { + this.raiseRecoverable(this.start, "Escape sequence in keyword new"); + } + var node = this.startNode(); + var meta = this.parseIdent(true); + if (this.options.ecmaVersion >= 6 && this.eat(types$1.dot)) { + node.meta = meta; + var containsEsc = this.containsEsc; + node.property = this.parseIdent(true); + if (node.property.name !== "target") { + this.raiseRecoverable(node.property.start, "The only valid meta property for new is 'new.target'"); + } + if (containsEsc) { + this.raiseRecoverable(node.start, "'new.target' must not contain escaped characters"); + } + if (!this.allowNewDotTarget) { + this.raiseRecoverable(node.start, "'new.target' can only be used in functions and class static block"); + } + return this.finishNode(node, "MetaProperty"); + } + var startPos = this.start, startLoc = this.startLoc, isImport = this.type === types$1._import; + node.callee = this.parseSubscripts(this.parseExprAtom(), startPos, startLoc, true, false); + if (isImport && node.callee.type === "ImportExpression") { + this.raise(startPos, "Cannot use new with import()"); + } + if (this.eat(types$1.parenL)) { + node.arguments = this.parseExprList(types$1.parenR, this.options.ecmaVersion >= 8, false); + } else { + node.arguments = empty; + } + return this.finishNode(node, "NewExpression"); +}; +pp$5.parseTemplateElement = function(ref2) { + var isTagged = ref2.isTagged; + var elem = this.startNode(); + if (this.type === types$1.invalidTemplate) { + if (!isTagged) { + this.raiseRecoverable(this.start, "Bad escape sequence in untagged template literal"); + } + elem.value = { + raw: this.value, + cooked: null + }; + } else { + elem.value = { + raw: this.input.slice(this.start, this.end).replace(/\r\n?/g, "\n"), + cooked: this.value + }; + } + this.next(); + elem.tail = this.type === types$1.backQuote; + return this.finishNode(elem, "TemplateElement"); +}; +pp$5.parseTemplate = function(ref2) { + if (ref2 === void 0) + ref2 = {}; + var isTagged = ref2.isTagged; + if (isTagged === void 0) + isTagged = false; + var node = this.startNode(); + this.next(); + node.expressions = []; + var curElt = this.parseTemplateElement({ isTagged }); + node.quasis = [curElt]; + while (!curElt.tail) { + if (this.type === types$1.eof) { + this.raise(this.pos, "Unterminated template literal"); + } + this.expect(types$1.dollarBraceL); + node.expressions.push(this.parseExpression()); + this.expect(types$1.braceR); + node.quasis.push(curElt = this.parseTemplateElement({ isTagged })); + } + this.next(); + return this.finishNode(node, "TemplateLiteral"); +}; +pp$5.isAsyncProp = function(prop) { + return !prop.computed && prop.key.type === "Identifier" && prop.key.name === "async" && (this.type === types$1.name || this.type === types$1.num || this.type === types$1.string || this.type === types$1.bracketL || this.type.keyword || this.options.ecmaVersion >= 9 && this.type === types$1.star) && !lineBreak.test(this.input.slice(this.lastTokEnd, this.start)); +}; +pp$5.parseObj = function(isPattern, refDestructuringErrors) { + var node = this.startNode(), first = true, propHash = {}; + node.properties = []; + this.next(); + while (!this.eat(types$1.braceR)) { + if (!first) { + this.expect(types$1.comma); + if (this.options.ecmaVersion >= 5 && this.afterTrailingComma(types$1.braceR)) { + break; + } + } else { + first = false; + } + var prop = this.parseProperty(isPattern, refDestructuringErrors); + if (!isPattern) { + this.checkPropClash(prop, propHash, refDestructuringErrors); + } + node.properties.push(prop); + } + return this.finishNode(node, isPattern ? "ObjectPattern" : "ObjectExpression"); +}; +pp$5.parseProperty = function(isPattern, refDestructuringErrors) { + var prop = this.startNode(), isGenerator, isAsync, startPos, startLoc; + if (this.options.ecmaVersion >= 9 && this.eat(types$1.ellipsis)) { + if (isPattern) { + prop.argument = this.parseIdent(false); + if (this.type === types$1.comma) { + this.raise(this.start, "Comma is not permitted after the rest element"); + } + return this.finishNode(prop, "RestElement"); + } + prop.argument = this.parseMaybeAssign(false, refDestructuringErrors); + if (this.type === types$1.comma && refDestructuringErrors && refDestructuringErrors.trailingComma < 0) { + refDestructuringErrors.trailingComma = this.start; + } + return this.finishNode(prop, "SpreadElement"); + } + if (this.options.ecmaVersion >= 6) { + prop.method = false; + prop.shorthand = false; + if (isPattern || refDestructuringErrors) { + startPos = this.start; + startLoc = this.startLoc; + } + if (!isPattern) { + isGenerator = this.eat(types$1.star); + } + } + var containsEsc = this.containsEsc; + this.parsePropertyName(prop); + if (!isPattern && !containsEsc && this.options.ecmaVersion >= 8 && !isGenerator && this.isAsyncProp(prop)) { + isAsync = true; + isGenerator = this.options.ecmaVersion >= 9 && this.eat(types$1.star); + this.parsePropertyName(prop); + } else { + isAsync = false; + } + this.parsePropertyValue(prop, isPattern, isGenerator, isAsync, startPos, startLoc, refDestructuringErrors, containsEsc); + return this.finishNode(prop, "Property"); +}; +pp$5.parsePropertyValue = function(prop, isPattern, isGenerator, isAsync, startPos, startLoc, refDestructuringErrors, containsEsc) { + if ((isGenerator || isAsync) && this.type === types$1.colon) { + this.unexpected(); + } + if (this.eat(types$1.colon)) { + prop.value = isPattern ? this.parseMaybeDefault(this.start, this.startLoc) : this.parseMaybeAssign(false, refDestructuringErrors); + prop.kind = "init"; + } else if (this.options.ecmaVersion >= 6 && this.type === types$1.parenL) { + if (isPattern) { + this.unexpected(); + } + prop.kind = "init"; + prop.method = true; + prop.value = this.parseMethod(isGenerator, isAsync); + } else if (!isPattern && !containsEsc && this.options.ecmaVersion >= 5 && !prop.computed && prop.key.type === "Identifier" && (prop.key.name === "get" || prop.key.name === "set") && (this.type !== types$1.comma && this.type !== types$1.braceR && this.type !== types$1.eq)) { + if (isGenerator || isAsync) { + this.unexpected(); + } + prop.kind = prop.key.name; + this.parsePropertyName(prop); + prop.value = this.parseMethod(false); + var paramCount = prop.kind === "get" ? 0 : 1; + if (prop.value.params.length !== paramCount) { + var start = prop.value.start; + if (prop.kind === "get") { + this.raiseRecoverable(start, "getter should have no params"); + } else { + this.raiseRecoverable(start, "setter should have exactly one param"); + } + } else { + if (prop.kind === "set" && prop.value.params[0].type === "RestElement") { + this.raiseRecoverable(prop.value.params[0].start, "Setter cannot use rest params"); + } + } + } else if (this.options.ecmaVersion >= 6 && !prop.computed && prop.key.type === "Identifier") { + if (isGenerator || isAsync) { + this.unexpected(); + } + this.checkUnreserved(prop.key); + if (prop.key.name === "await" && !this.awaitIdentPos) { + this.awaitIdentPos = startPos; + } + prop.kind = "init"; + if (isPattern) { + prop.value = this.parseMaybeDefault(startPos, startLoc, this.copyNode(prop.key)); + } else if (this.type === types$1.eq && refDestructuringErrors) { + if (refDestructuringErrors.shorthandAssign < 0) { + refDestructuringErrors.shorthandAssign = this.start; + } + prop.value = this.parseMaybeDefault(startPos, startLoc, this.copyNode(prop.key)); + } else { + prop.value = this.copyNode(prop.key); + } + prop.shorthand = true; + } else { + this.unexpected(); + } +}; +pp$5.parsePropertyName = function(prop) { + if (this.options.ecmaVersion >= 6) { + if (this.eat(types$1.bracketL)) { + prop.computed = true; + prop.key = this.parseMaybeAssign(); + this.expect(types$1.bracketR); + return prop.key; + } else { + prop.computed = false; + } + } + return prop.key = this.type === types$1.num || this.type === types$1.string ? this.parseExprAtom() : this.parseIdent(this.options.allowReserved !== "never"); +}; +pp$5.initFunction = function(node) { + node.id = null; + if (this.options.ecmaVersion >= 6) { + node.generator = node.expression = false; + } + if (this.options.ecmaVersion >= 8) { + node.async = false; + } +}; +pp$5.parseMethod = function(isGenerator, isAsync, allowDirectSuper) { + var node = this.startNode(), oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos; + this.initFunction(node); + if (this.options.ecmaVersion >= 6) { + node.generator = isGenerator; + } + if (this.options.ecmaVersion >= 8) { + node.async = !!isAsync; + } + this.yieldPos = 0; + this.awaitPos = 0; + this.awaitIdentPos = 0; + this.enterScope(functionFlags(isAsync, node.generator) | SCOPE_SUPER | (allowDirectSuper ? SCOPE_DIRECT_SUPER : 0)); + this.expect(types$1.parenL); + node.params = this.parseBindingList(types$1.parenR, false, this.options.ecmaVersion >= 8); + this.checkYieldAwaitInDefaultParams(); + this.parseFunctionBody(node, false, true, false); + this.yieldPos = oldYieldPos; + this.awaitPos = oldAwaitPos; + this.awaitIdentPos = oldAwaitIdentPos; + return this.finishNode(node, "FunctionExpression"); +}; +pp$5.parseArrowExpression = function(node, params, isAsync, forInit) { + var oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos; + this.enterScope(functionFlags(isAsync, false) | SCOPE_ARROW); + this.initFunction(node); + if (this.options.ecmaVersion >= 8) { + node.async = !!isAsync; + } + this.yieldPos = 0; + this.awaitPos = 0; + this.awaitIdentPos = 0; + node.params = this.toAssignableList(params, true); + this.parseFunctionBody(node, true, false, forInit); + this.yieldPos = oldYieldPos; + this.awaitPos = oldAwaitPos; + this.awaitIdentPos = oldAwaitIdentPos; + return this.finishNode(node, "ArrowFunctionExpression"); +}; +pp$5.parseFunctionBody = function(node, isArrowFunction, isMethod, forInit) { + var isExpression = isArrowFunction && this.type !== types$1.braceL; + var oldStrict = this.strict, useStrict = false; + if (isExpression) { + node.body = this.parseMaybeAssign(forInit); + node.expression = true; + this.checkParams(node, false); + } else { + var nonSimple = this.options.ecmaVersion >= 7 && !this.isSimpleParamList(node.params); + if (!oldStrict || nonSimple) { + useStrict = this.strictDirective(this.end); + if (useStrict && nonSimple) { + this.raiseRecoverable(node.start, "Illegal 'use strict' directive in function with non-simple parameter list"); + } + } + var oldLabels = this.labels; + this.labels = []; + if (useStrict) { + this.strict = true; + } + this.checkParams(node, !oldStrict && !useStrict && !isArrowFunction && !isMethod && this.isSimpleParamList(node.params)); + if (this.strict && node.id) { + this.checkLValSimple(node.id, BIND_OUTSIDE); + } + node.body = this.parseBlock(false, void 0, useStrict && !oldStrict); + node.expression = false; + this.adaptDirectivePrologue(node.body.body); + this.labels = oldLabels; + } + this.exitScope(); +}; +pp$5.isSimpleParamList = function(params) { + for (var i4 = 0, list = params; i4 < list.length; i4 += 1) { + var param = list[i4]; + if (param.type !== "Identifier") { + return false; + } + } + return true; +}; +pp$5.checkParams = function(node, allowDuplicates) { + var nameHash = /* @__PURE__ */ Object.create(null); + for (var i4 = 0, list = node.params; i4 < list.length; i4 += 1) { + var param = list[i4]; + this.checkLValInnerPattern(param, BIND_VAR, allowDuplicates ? null : nameHash); + } +}; +pp$5.parseExprList = function(close, allowTrailingComma, allowEmpty, refDestructuringErrors) { + var elts = [], first = true; + while (!this.eat(close)) { + if (!first) { + this.expect(types$1.comma); + if (allowTrailingComma && this.afterTrailingComma(close)) { + break; + } + } else { + first = false; + } + var elt = void 0; + if (allowEmpty && this.type === types$1.comma) { + elt = null; + } else if (this.type === types$1.ellipsis) { + elt = this.parseSpread(refDestructuringErrors); + if (refDestructuringErrors && this.type === types$1.comma && refDestructuringErrors.trailingComma < 0) { + refDestructuringErrors.trailingComma = this.start; + } + } else { + elt = this.parseMaybeAssign(false, refDestructuringErrors); + } + elts.push(elt); + } + return elts; +}; +pp$5.checkUnreserved = function(ref2) { + var start = ref2.start; + var end = ref2.end; + var name = ref2.name; + if (this.inGenerator && name === "yield") { + this.raiseRecoverable(start, "Cannot use 'yield' as identifier inside a generator"); + } + if (this.inAsync && name === "await") { + this.raiseRecoverable(start, "Cannot use 'await' as identifier inside an async function"); + } + if (this.currentThisScope().inClassFieldInit && name === "arguments") { + this.raiseRecoverable(start, "Cannot use 'arguments' in class field initializer"); + } + if (this.inClassStaticBlock && (name === "arguments" || name === "await")) { + this.raise(start, "Cannot use " + name + " in class static initialization block"); + } + if (this.keywords.test(name)) { + this.raise(start, "Unexpected keyword '" + name + "'"); + } + if (this.options.ecmaVersion < 6 && this.input.slice(start, end).indexOf("\\") !== -1) { + return; + } + var re = this.strict ? this.reservedWordsStrict : this.reservedWords; + if (re.test(name)) { + if (!this.inAsync && name === "await") { + this.raiseRecoverable(start, "Cannot use keyword 'await' outside an async function"); + } + this.raiseRecoverable(start, "The keyword '" + name + "' is reserved"); + } +}; +pp$5.parseIdent = function(liberal) { + var node = this.startNode(); + if (this.type === types$1.name) { + node.name = this.value; + } else if (this.type.keyword) { + node.name = this.type.keyword; + if ((node.name === "class" || node.name === "function") && (this.lastTokEnd !== this.lastTokStart + 1 || this.input.charCodeAt(this.lastTokStart) !== 46)) { + this.context.pop(); + } + } else { + this.unexpected(); + } + this.next(!!liberal); + this.finishNode(node, "Identifier"); + if (!liberal) { + this.checkUnreserved(node); + if (node.name === "await" && !this.awaitIdentPos) { + this.awaitIdentPos = node.start; + } + } + return node; +}; +pp$5.parsePrivateIdent = function() { + var node = this.startNode(); + if (this.type === types$1.privateId) { + node.name = this.value; + } else { + this.unexpected(); + } + this.next(); + this.finishNode(node, "PrivateIdentifier"); + if (this.privateNameStack.length === 0) { + this.raise(node.start, "Private field '#" + node.name + "' must be declared in an enclosing class"); + } else { + this.privateNameStack[this.privateNameStack.length - 1].used.push(node); + } + return node; +}; +pp$5.parseYield = function(forInit) { + if (!this.yieldPos) { + this.yieldPos = this.start; + } + var node = this.startNode(); + this.next(); + if (this.type === types$1.semi || this.canInsertSemicolon() || this.type !== types$1.star && !this.type.startsExpr) { + node.delegate = false; + node.argument = null; + } else { + node.delegate = this.eat(types$1.star); + node.argument = this.parseMaybeAssign(forInit); + } + return this.finishNode(node, "YieldExpression"); +}; +pp$5.parseAwait = function(forInit) { + if (!this.awaitPos) { + this.awaitPos = this.start; + } + var node = this.startNode(); + this.next(); + node.argument = this.parseMaybeUnary(null, true, false, forInit); + return this.finishNode(node, "AwaitExpression"); +}; +var pp$4 = Parser.prototype; +pp$4.raise = function(pos, message) { + var loc = getLineInfo(this.input, pos); + message += " (" + loc.line + ":" + loc.column + ")"; + var err = new SyntaxError(message); + err.pos = pos; + err.loc = loc; + err.raisedAt = this.pos; + throw err; +}; +pp$4.raiseRecoverable = pp$4.raise; +pp$4.curPosition = function() { + if (this.options.locations) { + return new Position(this.curLine, this.pos - this.lineStart); + } +}; +var pp$3 = Parser.prototype; +var Scope = function Scope2(flags) { + this.flags = flags; + this.var = []; + this.lexical = []; + this.functions = []; + this.inClassFieldInit = false; +}; +pp$3.enterScope = function(flags) { + this.scopeStack.push(new Scope(flags)); +}; +pp$3.exitScope = function() { + this.scopeStack.pop(); +}; +pp$3.treatFunctionsAsVarInScope = function(scope) { + return scope.flags & SCOPE_FUNCTION || !this.inModule && scope.flags & SCOPE_TOP; +}; +pp$3.declareName = function(name, bindingType, pos) { + var redeclared = false; + if (bindingType === BIND_LEXICAL) { + var scope = this.currentScope(); + redeclared = scope.lexical.indexOf(name) > -1 || scope.functions.indexOf(name) > -1 || scope.var.indexOf(name) > -1; + scope.lexical.push(name); + if (this.inModule && scope.flags & SCOPE_TOP) { + delete this.undefinedExports[name]; + } + } else if (bindingType === BIND_SIMPLE_CATCH) { + var scope$1 = this.currentScope(); + scope$1.lexical.push(name); + } else if (bindingType === BIND_FUNCTION) { + var scope$2 = this.currentScope(); + if (this.treatFunctionsAsVar) { + redeclared = scope$2.lexical.indexOf(name) > -1; + } else { + redeclared = scope$2.lexical.indexOf(name) > -1 || scope$2.var.indexOf(name) > -1; + } + scope$2.functions.push(name); + } else { + for (var i4 = this.scopeStack.length - 1; i4 >= 0; --i4) { + var scope$3 = this.scopeStack[i4]; + if (scope$3.lexical.indexOf(name) > -1 && !(scope$3.flags & SCOPE_SIMPLE_CATCH && scope$3.lexical[0] === name) || !this.treatFunctionsAsVarInScope(scope$3) && scope$3.functions.indexOf(name) > -1) { + redeclared = true; + break; + } + scope$3.var.push(name); + if (this.inModule && scope$3.flags & SCOPE_TOP) { + delete this.undefinedExports[name]; + } + if (scope$3.flags & SCOPE_VAR) { + break; + } + } + } + if (redeclared) { + this.raiseRecoverable(pos, "Identifier '" + name + "' has already been declared"); + } +}; +pp$3.checkLocalExport = function(id2) { + if (this.scopeStack[0].lexical.indexOf(id2.name) === -1 && this.scopeStack[0].var.indexOf(id2.name) === -1) { + this.undefinedExports[id2.name] = id2; + } +}; +pp$3.currentScope = function() { + return this.scopeStack[this.scopeStack.length - 1]; +}; +pp$3.currentVarScope = function() { + for (var i4 = this.scopeStack.length - 1; ; i4--) { + var scope = this.scopeStack[i4]; + if (scope.flags & SCOPE_VAR) { + return scope; + } + } +}; +pp$3.currentThisScope = function() { + for (var i4 = this.scopeStack.length - 1; ; i4--) { + var scope = this.scopeStack[i4]; + if (scope.flags & SCOPE_VAR && !(scope.flags & SCOPE_ARROW)) { + return scope; + } + } +}; +var Node = function Node2(parser, pos, loc) { + this.type = ""; + this.start = pos; + this.end = 0; + if (parser.options.locations) { + this.loc = new SourceLocation(parser, loc); + } + if (parser.options.directSourceFile) { + this.sourceFile = parser.options.directSourceFile; + } + if (parser.options.ranges) { + this.range = [pos, 0]; + } +}; +var pp$2 = Parser.prototype; +pp$2.startNode = function() { + return new Node(this, this.start, this.startLoc); +}; +pp$2.startNodeAt = function(pos, loc) { + return new Node(this, pos, loc); +}; +function finishNodeAt(node, type, pos, loc) { + node.type = type; + node.end = pos; + if (this.options.locations) { + node.loc.end = loc; + } + if (this.options.ranges) { + node.range[1] = pos; + } + return node; +} +pp$2.finishNode = function(node, type) { + return finishNodeAt.call(this, node, type, this.lastTokEnd, this.lastTokEndLoc); +}; +pp$2.finishNodeAt = function(node, type, pos, loc) { + return finishNodeAt.call(this, node, type, pos, loc); +}; +pp$2.copyNode = function(node) { + var newNode = new Node(this, node.start, this.startLoc); + for (var prop in node) { + newNode[prop] = node[prop]; + } + return newNode; +}; +var ecma9BinaryProperties = "ASCII ASCII_Hex_Digit AHex Alphabetic Alpha Any Assigned Bidi_Control Bidi_C Bidi_Mirrored Bidi_M Case_Ignorable CI Cased Changes_When_Casefolded CWCF Changes_When_Casemapped CWCM Changes_When_Lowercased CWL Changes_When_NFKC_Casefolded CWKCF Changes_When_Titlecased CWT Changes_When_Uppercased CWU Dash Default_Ignorable_Code_Point DI Deprecated Dep Diacritic Dia Emoji Emoji_Component Emoji_Modifier Emoji_Modifier_Base Emoji_Presentation Extender Ext Grapheme_Base Gr_Base Grapheme_Extend Gr_Ext Hex_Digit Hex IDS_Binary_Operator IDSB IDS_Trinary_Operator IDST ID_Continue IDC ID_Start IDS Ideographic Ideo Join_Control Join_C Logical_Order_Exception LOE Lowercase Lower Math Noncharacter_Code_Point NChar Pattern_Syntax Pat_Syn Pattern_White_Space Pat_WS Quotation_Mark QMark Radical Regional_Indicator RI Sentence_Terminal STerm Soft_Dotted SD Terminal_Punctuation Term Unified_Ideograph UIdeo Uppercase Upper Variation_Selector VS White_Space space XID_Continue XIDC XID_Start XIDS"; +var ecma10BinaryProperties = ecma9BinaryProperties + " Extended_Pictographic"; +var ecma11BinaryProperties = ecma10BinaryProperties; +var ecma12BinaryProperties = ecma11BinaryProperties + " EBase EComp EMod EPres ExtPict"; +var ecma13BinaryProperties = ecma12BinaryProperties; +var ecma14BinaryProperties = ecma13BinaryProperties; +var unicodeBinaryProperties = { + 9: ecma9BinaryProperties, + 10: ecma10BinaryProperties, + 11: ecma11BinaryProperties, + 12: ecma12BinaryProperties, + 13: ecma13BinaryProperties, + 14: ecma14BinaryProperties +}; +var unicodeGeneralCategoryValues = "Cased_Letter LC Close_Punctuation Pe Connector_Punctuation Pc Control Cc cntrl Currency_Symbol Sc Dash_Punctuation Pd Decimal_Number Nd digit Enclosing_Mark Me Final_Punctuation Pf Format Cf Initial_Punctuation Pi Letter L Letter_Number Nl Line_Separator Zl Lowercase_Letter Ll Mark M Combining_Mark Math_Symbol Sm Modifier_Letter Lm Modifier_Symbol Sk Nonspacing_Mark Mn Number N Open_Punctuation Ps Other C Other_Letter Lo Other_Number No Other_Punctuation Po Other_Symbol So Paragraph_Separator Zp Private_Use Co Punctuation P punct Separator Z Space_Separator Zs Spacing_Mark Mc Surrogate Cs Symbol S Titlecase_Letter Lt Unassigned Cn Uppercase_Letter Lu"; +var ecma9ScriptValues = "Adlam Adlm Ahom Anatolian_Hieroglyphs Hluw Arabic Arab Armenian Armn Avestan Avst Balinese Bali Bamum Bamu Bassa_Vah Bass Batak Batk Bengali Beng Bhaiksuki Bhks Bopomofo Bopo Brahmi Brah Braille Brai Buginese Bugi Buhid Buhd Canadian_Aboriginal Cans Carian Cari Caucasian_Albanian Aghb Chakma Cakm Cham Cham Cherokee Cher Common Zyyy Coptic Copt Qaac Cuneiform Xsux Cypriot Cprt Cyrillic Cyrl Deseret Dsrt Devanagari Deva Duployan Dupl Egyptian_Hieroglyphs Egyp Elbasan Elba Ethiopic Ethi Georgian Geor Glagolitic Glag Gothic Goth Grantha Gran Greek Grek Gujarati Gujr Gurmukhi Guru Han Hani Hangul Hang Hanunoo Hano Hatran Hatr Hebrew Hebr Hiragana Hira Imperial_Aramaic Armi Inherited Zinh Qaai Inscriptional_Pahlavi Phli Inscriptional_Parthian Prti Javanese Java Kaithi Kthi Kannada Knda Katakana Kana Kayah_Li Kali Kharoshthi Khar Khmer Khmr Khojki Khoj Khudawadi Sind Lao Laoo Latin Latn Lepcha Lepc Limbu Limb Linear_A Lina Linear_B Linb Lisu Lisu Lycian Lyci Lydian Lydi Mahajani Mahj Malayalam Mlym Mandaic Mand Manichaean Mani Marchen Marc Masaram_Gondi Gonm Meetei_Mayek Mtei Mende_Kikakui Mend Meroitic_Cursive Merc Meroitic_Hieroglyphs Mero Miao Plrd Modi Mongolian Mong Mro Mroo Multani Mult Myanmar Mymr Nabataean Nbat New_Tai_Lue Talu Newa Newa Nko Nkoo Nushu Nshu Ogham Ogam Ol_Chiki Olck Old_Hungarian Hung Old_Italic Ital Old_North_Arabian Narb Old_Permic Perm Old_Persian Xpeo Old_South_Arabian Sarb Old_Turkic Orkh Oriya Orya Osage Osge Osmanya Osma Pahawh_Hmong Hmng Palmyrene Palm Pau_Cin_Hau Pauc Phags_Pa Phag Phoenician Phnx Psalter_Pahlavi Phlp Rejang Rjng Runic Runr Samaritan Samr Saurashtra Saur Sharada Shrd Shavian Shaw Siddham Sidd SignWriting Sgnw Sinhala Sinh Sora_Sompeng Sora Soyombo Soyo Sundanese Sund Syloti_Nagri Sylo Syriac Syrc Tagalog Tglg Tagbanwa Tagb Tai_Le Tale Tai_Tham Lana Tai_Viet Tavt Takri Takr Tamil Taml Tangut Tang Telugu Telu Thaana Thaa Thai Thai Tibetan Tibt Tifinagh Tfng Tirhuta Tirh Ugaritic Ugar Vai Vaii Warang_Citi Wara Yi Yiii Zanabazar_Square Zanb"; +var ecma10ScriptValues = ecma9ScriptValues + " Dogra Dogr Gunjala_Gondi Gong Hanifi_Rohingya Rohg Makasar Maka Medefaidrin Medf Old_Sogdian Sogo Sogdian Sogd"; +var ecma11ScriptValues = ecma10ScriptValues + " Elymaic Elym Nandinagari Nand Nyiakeng_Puachue_Hmong Hmnp Wancho Wcho"; +var ecma12ScriptValues = ecma11ScriptValues + " Chorasmian Chrs Diak Dives_Akuru Khitan_Small_Script Kits Yezi Yezidi"; +var ecma13ScriptValues = ecma12ScriptValues + " Cypro_Minoan Cpmn Old_Uyghur Ougr Tangsa Tnsa Toto Vithkuqi Vith"; +var ecma14ScriptValues = ecma13ScriptValues + " Kawi Nag_Mundari Nagm"; +var unicodeScriptValues = { + 9: ecma9ScriptValues, + 10: ecma10ScriptValues, + 11: ecma11ScriptValues, + 12: ecma12ScriptValues, + 13: ecma13ScriptValues, + 14: ecma14ScriptValues +}; +var data = {}; +function buildUnicodeData(ecmaVersion) { + var d5 = data[ecmaVersion] = { + binary: wordsRegexp(unicodeBinaryProperties[ecmaVersion] + " " + unicodeGeneralCategoryValues), + nonBinary: { + General_Category: wordsRegexp(unicodeGeneralCategoryValues), + Script: wordsRegexp(unicodeScriptValues[ecmaVersion]) + } + }; + d5.nonBinary.Script_Extensions = d5.nonBinary.Script; + d5.nonBinary.gc = d5.nonBinary.General_Category; + d5.nonBinary.sc = d5.nonBinary.Script; + d5.nonBinary.scx = d5.nonBinary.Script_Extensions; +} +for (i4 = 0, list = [9, 10, 11, 12, 13, 14]; i4 < list.length; i4 += 1) { + ecmaVersion = list[i4]; + buildUnicodeData(ecmaVersion); +} +var ecmaVersion; +var i4; +var list; +var pp$1 = Parser.prototype; +var RegExpValidationState = function RegExpValidationState2(parser) { + this.parser = parser; + this.validFlags = "gim" + (parser.options.ecmaVersion >= 6 ? "uy" : "") + (parser.options.ecmaVersion >= 9 ? "s" : "") + (parser.options.ecmaVersion >= 13 ? "d" : ""); + this.unicodeProperties = data[parser.options.ecmaVersion >= 14 ? 14 : parser.options.ecmaVersion]; + this.source = ""; + this.flags = ""; + this.start = 0; + this.switchU = false; + this.switchN = false; + this.pos = 0; + this.lastIntValue = 0; + this.lastStringValue = ""; + this.lastAssertionIsQuantifiable = false; + this.numCapturingParens = 0; + this.maxBackReference = 0; + this.groupNames = []; + this.backReferenceNames = []; +}; +RegExpValidationState.prototype.reset = function reset(start, pattern, flags) { + var unicode = flags.indexOf("u") !== -1; + this.start = start | 0; + this.source = pattern + ""; + this.flags = flags; + this.switchU = unicode && this.parser.options.ecmaVersion >= 6; + this.switchN = unicode && this.parser.options.ecmaVersion >= 9; +}; +RegExpValidationState.prototype.raise = function raise(message) { + this.parser.raiseRecoverable(this.start, "Invalid regular expression: /" + this.source + "/: " + message); +}; +RegExpValidationState.prototype.at = function at(i4, forceU) { + if (forceU === void 0) + forceU = false; + var s5 = this.source; + var l3 = s5.length; + if (i4 >= l3) { + return -1; + } + var c4 = s5.charCodeAt(i4); + if (!(forceU || this.switchU) || c4 <= 55295 || c4 >= 57344 || i4 + 1 >= l3) { + return c4; + } + var next = s5.charCodeAt(i4 + 1); + return next >= 56320 && next <= 57343 ? (c4 << 10) + next - 56613888 : c4; +}; +RegExpValidationState.prototype.nextIndex = function nextIndex(i4, forceU) { + if (forceU === void 0) + forceU = false; + var s5 = this.source; + var l3 = s5.length; + if (i4 >= l3) { + return l3; + } + var c4 = s5.charCodeAt(i4), next; + if (!(forceU || this.switchU) || c4 <= 55295 || c4 >= 57344 || i4 + 1 >= l3 || (next = s5.charCodeAt(i4 + 1)) < 56320 || next > 57343) { + return i4 + 1; + } + return i4 + 2; +}; +RegExpValidationState.prototype.current = function current(forceU) { + if (forceU === void 0) + forceU = false; + return this.at(this.pos, forceU); +}; +RegExpValidationState.prototype.lookahead = function lookahead(forceU) { + if (forceU === void 0) + forceU = false; + return this.at(this.nextIndex(this.pos, forceU), forceU); +}; +RegExpValidationState.prototype.advance = function advance(forceU) { + if (forceU === void 0) + forceU = false; + this.pos = this.nextIndex(this.pos, forceU); +}; +RegExpValidationState.prototype.eat = function eat(ch, forceU) { + if (forceU === void 0) + forceU = false; + if (this.current(forceU) === ch) { + this.advance(forceU); + return true; + } + return false; +}; +pp$1.validateRegExpFlags = function(state) { + var validFlags = state.validFlags; + var flags = state.flags; + for (var i4 = 0; i4 < flags.length; i4++) { + var flag = flags.charAt(i4); + if (validFlags.indexOf(flag) === -1) { + this.raise(state.start, "Invalid regular expression flag"); + } + if (flags.indexOf(flag, i4 + 1) > -1) { + this.raise(state.start, "Duplicate regular expression flag"); + } + } +}; +pp$1.validateRegExpPattern = function(state) { + this.regexp_pattern(state); + if (!state.switchN && this.options.ecmaVersion >= 9 && state.groupNames.length > 0) { + state.switchN = true; + this.regexp_pattern(state); + } +}; +pp$1.regexp_pattern = function(state) { + state.pos = 0; + state.lastIntValue = 0; + state.lastStringValue = ""; + state.lastAssertionIsQuantifiable = false; + state.numCapturingParens = 0; + state.maxBackReference = 0; + state.groupNames.length = 0; + state.backReferenceNames.length = 0; + this.regexp_disjunction(state); + if (state.pos !== state.source.length) { + if (state.eat(41)) { + state.raise("Unmatched ')'"); + } + if (state.eat(93) || state.eat(125)) { + state.raise("Lone quantifier brackets"); + } + } + if (state.maxBackReference > state.numCapturingParens) { + state.raise("Invalid escape"); + } + for (var i4 = 0, list = state.backReferenceNames; i4 < list.length; i4 += 1) { + var name = list[i4]; + if (state.groupNames.indexOf(name) === -1) { + state.raise("Invalid named capture referenced"); + } + } +}; +pp$1.regexp_disjunction = function(state) { + this.regexp_alternative(state); + while (state.eat(124)) { + this.regexp_alternative(state); + } + if (this.regexp_eatQuantifier(state, true)) { + state.raise("Nothing to repeat"); + } + if (state.eat(123)) { + state.raise("Lone quantifier brackets"); + } +}; +pp$1.regexp_alternative = function(state) { + while (state.pos < state.source.length && this.regexp_eatTerm(state)) { + } +}; +pp$1.regexp_eatTerm = function(state) { + if (this.regexp_eatAssertion(state)) { + if (state.lastAssertionIsQuantifiable && this.regexp_eatQuantifier(state)) { + if (state.switchU) { + state.raise("Invalid quantifier"); + } + } + return true; + } + if (state.switchU ? this.regexp_eatAtom(state) : this.regexp_eatExtendedAtom(state)) { + this.regexp_eatQuantifier(state); + return true; + } + return false; +}; +pp$1.regexp_eatAssertion = function(state) { + var start = state.pos; + state.lastAssertionIsQuantifiable = false; + if (state.eat(94) || state.eat(36)) { + return true; + } + if (state.eat(92)) { + if (state.eat(66) || state.eat(98)) { + return true; + } + state.pos = start; + } + if (state.eat(40) && state.eat(63)) { + var lookbehind = false; + if (this.options.ecmaVersion >= 9) { + lookbehind = state.eat(60); + } + if (state.eat(61) || state.eat(33)) { + this.regexp_disjunction(state); + if (!state.eat(41)) { + state.raise("Unterminated group"); + } + state.lastAssertionIsQuantifiable = !lookbehind; + return true; + } + } + state.pos = start; + return false; +}; +pp$1.regexp_eatQuantifier = function(state, noError) { + if (noError === void 0) + noError = false; + if (this.regexp_eatQuantifierPrefix(state, noError)) { + state.eat(63); + return true; + } + return false; +}; +pp$1.regexp_eatQuantifierPrefix = function(state, noError) { + return state.eat(42) || state.eat(43) || state.eat(63) || this.regexp_eatBracedQuantifier(state, noError); +}; +pp$1.regexp_eatBracedQuantifier = function(state, noError) { + var start = state.pos; + if (state.eat(123)) { + var min3 = 0, max3 = -1; + if (this.regexp_eatDecimalDigits(state)) { + min3 = state.lastIntValue; + if (state.eat(44) && this.regexp_eatDecimalDigits(state)) { + max3 = state.lastIntValue; + } + if (state.eat(125)) { + if (max3 !== -1 && max3 < min3 && !noError) { + state.raise("numbers out of order in {} quantifier"); + } + return true; + } + } + if (state.switchU && !noError) { + state.raise("Incomplete quantifier"); + } + state.pos = start; + } + return false; +}; +pp$1.regexp_eatAtom = function(state) { + return this.regexp_eatPatternCharacters(state) || state.eat(46) || this.regexp_eatReverseSolidusAtomEscape(state) || this.regexp_eatCharacterClass(state) || this.regexp_eatUncapturingGroup(state) || this.regexp_eatCapturingGroup(state); +}; +pp$1.regexp_eatReverseSolidusAtomEscape = function(state) { + var start = state.pos; + if (state.eat(92)) { + if (this.regexp_eatAtomEscape(state)) { + return true; + } + state.pos = start; + } + return false; +}; +pp$1.regexp_eatUncapturingGroup = function(state) { + var start = state.pos; + if (state.eat(40)) { + if (state.eat(63) && state.eat(58)) { + this.regexp_disjunction(state); + if (state.eat(41)) { + return true; + } + state.raise("Unterminated group"); + } + state.pos = start; + } + return false; +}; +pp$1.regexp_eatCapturingGroup = function(state) { + if (state.eat(40)) { + if (this.options.ecmaVersion >= 9) { + this.regexp_groupSpecifier(state); + } else if (state.current() === 63) { + state.raise("Invalid group"); + } + this.regexp_disjunction(state); + if (state.eat(41)) { + state.numCapturingParens += 1; + return true; + } + state.raise("Unterminated group"); + } + return false; +}; +pp$1.regexp_eatExtendedAtom = function(state) { + return state.eat(46) || this.regexp_eatReverseSolidusAtomEscape(state) || this.regexp_eatCharacterClass(state) || this.regexp_eatUncapturingGroup(state) || this.regexp_eatCapturingGroup(state) || this.regexp_eatInvalidBracedQuantifier(state) || this.regexp_eatExtendedPatternCharacter(state); +}; +pp$1.regexp_eatInvalidBracedQuantifier = function(state) { + if (this.regexp_eatBracedQuantifier(state, true)) { + state.raise("Nothing to repeat"); + } + return false; +}; +pp$1.regexp_eatSyntaxCharacter = function(state) { + var ch = state.current(); + if (isSyntaxCharacter(ch)) { + state.lastIntValue = ch; + state.advance(); + return true; + } + return false; +}; +function isSyntaxCharacter(ch) { + return ch === 36 || ch >= 40 && ch <= 43 || ch === 46 || ch === 63 || ch >= 91 && ch <= 94 || ch >= 123 && ch <= 125; +} +pp$1.regexp_eatPatternCharacters = function(state) { + var start = state.pos; + var ch = 0; + while ((ch = state.current()) !== -1 && !isSyntaxCharacter(ch)) { + state.advance(); + } + return state.pos !== start; +}; +pp$1.regexp_eatExtendedPatternCharacter = function(state) { + var ch = state.current(); + if (ch !== -1 && ch !== 36 && !(ch >= 40 && ch <= 43) && ch !== 46 && ch !== 63 && ch !== 91 && ch !== 94 && ch !== 124) { + state.advance(); + return true; + } + return false; +}; +pp$1.regexp_groupSpecifier = function(state) { + if (state.eat(63)) { + if (this.regexp_eatGroupName(state)) { + if (state.groupNames.indexOf(state.lastStringValue) !== -1) { + state.raise("Duplicate capture group name"); + } + state.groupNames.push(state.lastStringValue); + return; + } + state.raise("Invalid group"); + } +}; +pp$1.regexp_eatGroupName = function(state) { + state.lastStringValue = ""; + if (state.eat(60)) { + if (this.regexp_eatRegExpIdentifierName(state) && state.eat(62)) { + return true; + } + state.raise("Invalid capture group name"); + } + return false; +}; +pp$1.regexp_eatRegExpIdentifierName = function(state) { + state.lastStringValue = ""; + if (this.regexp_eatRegExpIdentifierStart(state)) { + state.lastStringValue += codePointToString(state.lastIntValue); + while (this.regexp_eatRegExpIdentifierPart(state)) { + state.lastStringValue += codePointToString(state.lastIntValue); + } + return true; + } + return false; +}; +pp$1.regexp_eatRegExpIdentifierStart = function(state) { + var start = state.pos; + var forceU = this.options.ecmaVersion >= 11; + var ch = state.current(forceU); + state.advance(forceU); + if (ch === 92 && this.regexp_eatRegExpUnicodeEscapeSequence(state, forceU)) { + ch = state.lastIntValue; + } + if (isRegExpIdentifierStart(ch)) { + state.lastIntValue = ch; + return true; + } + state.pos = start; + return false; +}; +function isRegExpIdentifierStart(ch) { + return isIdentifierStart(ch, true) || ch === 36 || ch === 95; +} +pp$1.regexp_eatRegExpIdentifierPart = function(state) { + var start = state.pos; + var forceU = this.options.ecmaVersion >= 11; + var ch = state.current(forceU); + state.advance(forceU); + if (ch === 92 && this.regexp_eatRegExpUnicodeEscapeSequence(state, forceU)) { + ch = state.lastIntValue; + } + if (isRegExpIdentifierPart(ch)) { + state.lastIntValue = ch; + return true; + } + state.pos = start; + return false; +}; +function isRegExpIdentifierPart(ch) { + return isIdentifierChar(ch, true) || ch === 36 || ch === 95 || ch === 8204 || ch === 8205; +} +pp$1.regexp_eatAtomEscape = function(state) { + if (this.regexp_eatBackReference(state) || this.regexp_eatCharacterClassEscape(state) || this.regexp_eatCharacterEscape(state) || state.switchN && this.regexp_eatKGroupName(state)) { + return true; + } + if (state.switchU) { + if (state.current() === 99) { + state.raise("Invalid unicode escape"); } - }), /* @__PURE__ */ Cn.createElement("div", { - "aria-label": i18n_default.buttons.openLink, - onClick: props2.openLink, - className: "mk-hover-button", - dangerouslySetInnerHTML: { __html: uiIconSet["mk-ui-open-link"] } - })) : /* @__PURE__ */ Cn.createElement(Cn.Fragment, null, /* @__PURE__ */ Cn.createElement("div", { - "aria-label": i18n_default.buttons.convertTable, - onClick: props2.convertTable, - className: "mk-icon-xsmall mk-hover-button", - dangerouslySetInnerHTML: { __html: uiIconSet["mk-ui-sync"] } - }), /* @__PURE__ */ Cn.createElement("div", { - "aria-label": i18n_default.buttons.cutTable, - onClick: props2.cutTable, - className: "mk-icon-xsmall mk-hover-button", - dangerouslySetInnerHTML: { __html: uiIconSet["mk-ui-cut"] } - }), /* @__PURE__ */ Cn.createElement("div", { - "aria-label": i18n_default.buttons.deleteTable, - onClick: props2.deleteTable, - className: "mk-icon-xsmall mk-hover-button", - dangerouslySetInnerHTML: { __html: uiIconSet["mk-ui-close"] } - })), " "); + state.raise("Invalid escape"); + } + return false; }; - -// src/types/types.ts -var eventTypes = { - activePathChange: "mkmd-active-path", - refreshView: "mkmd-refresh-view", - revealFile: "mkmd-reveal-file", - collapseFolders: "mkmd-collapse-folders", - toggleBacklinks: "mkmd-toggle-backlinks", - metadataChange: "mkmd-tags-change", - vaultChange: "mkmd-vault-change", - mdbChange: "mkmd-mdb-change", - spacesChange: "mkmd-spaces-change", - updateSections: "mkmd-update-sections", - settingsChanged: "mkmd-settings-changed", - spawnPortal: "mkmd-portal-spawn", - loadPortal: "mkmd-portal-load", - openFilePortal: "mkmd-portal-file", - focusPortal: "mkmd-portal-focus" +pp$1.regexp_eatBackReference = function(state) { + var start = state.pos; + if (this.regexp_eatDecimalEscape(state)) { + var n2 = state.lastIntValue; + if (state.switchU) { + if (n2 > state.maxBackReference) { + state.maxBackReference = n2; + } + return true; + } + if (n2 <= state.numCapturingParens) { + return true; + } + state.pos = start; + } + return false; }; - -// src/dispatch/flowDispatch.ts -var createFlowEditorInElement = (id2, el, type, file, ref, from, to) => { - const evt = new CustomEvent(eventTypes.spawnPortal, { - detail: { id: id2, el, file, from, to, ref, type } - }); - activeWindow.dispatchEvent(evt); +pp$1.regexp_eatKGroupName = function(state) { + if (state.eat(107)) { + if (this.regexp_eatGroupName(state)) { + state.backReferenceNames.push(state.lastStringValue); + return true; + } + state.raise("Invalid named reference"); + } + return false; }; -var loadFlowEditorByDOM = (el, view, id2) => { - const evt = new CustomEvent(eventTypes.loadPortal, { - detail: { id: id2, el, view } - }); - activeWindow.dispatchEvent(evt); +pp$1.regexp_eatCharacterEscape = function(state) { + return this.regexp_eatControlEscape(state) || this.regexp_eatCControlLetter(state) || this.regexp_eatZero(state) || this.regexp_eatHexEscapeSequence(state) || this.regexp_eatRegExpUnicodeEscapeSequence(state, false) || !state.switchU && this.regexp_eatLegacyOctalEscapeSequence(state) || this.regexp_eatIdentityEscape(state); }; -var focusFlowEditor = (id2, top) => { - const evt = new CustomEvent(eventTypes.focusPortal, { - detail: { id: id2, parent: false, top } - }); - activeWindow.dispatchEvent(evt); +pp$1.regexp_eatCControlLetter = function(state) { + var start = state.pos; + if (state.eat(99)) { + if (this.regexp_eatControlLetter(state)) { + return true; + } + state.pos = start; + } + return false; }; -var focusFlowEditorParent = (id2, top) => { - const evt = new CustomEvent(eventTypes.focusPortal, { - detail: { id: id2, parent: true, top } - }); - activeWindow.dispatchEvent(evt); +pp$1.regexp_eatZero = function(state) { + if (state.current() === 48 && !isDecimalDigit(state.lookahead())) { + state.lastIntValue = 0; + state.advance(); + return true; + } + return false; }; -var openFileFlowEditor = (file, source) => { - const evt = new CustomEvent(eventTypes.openFilePortal, { - detail: { file, source } - }); - activeWindow.dispatchEvent(evt); +pp$1.regexp_eatControlEscape = function(state) { + var ch = state.current(); + if (ch === 116) { + state.lastIntValue = 9; + state.advance(); + return true; + } + if (ch === 110) { + state.lastIntValue = 10; + state.advance(); + return true; + } + if (ch === 118) { + state.lastIntValue = 11; + state.advance(); + return true; + } + if (ch === 102) { + state.lastIntValue = 12; + state.advance(); + return true; + } + if (ch === 114) { + state.lastIntValue = 13; + state.advance(); + return true; + } + return false; }; - -// src/cm-extensions/flowEditor/flowEditor.tsx -var import_obsidian44 = require("obsidian"); - -// src/components/ui/modals/vaultChangeModals.ts -var import_obsidian42 = require("obsidian"); - -// src/components/ContextView/ContextView.tsx -var import_obsidian38 = require("obsidian"); - -// src/utils/strings.ts -function parseStickerString(input) { - if (!input) { - return ["", ""]; +pp$1.regexp_eatControlLetter = function(state) { + var ch = state.current(); + if (isControlLetter(ch)) { + state.lastIntValue = ch % 32; + state.advance(); + return true; } - let match2 = input.match(/^(.*?)\s*\/\/\s*(.*)$/); - if (match2) { - return [match2[1], match2[2]]; - } else { - return ["", input]; + return false; +}; +function isControlLetter(ch) { + return ch >= 65 && ch <= 90 || ch >= 97 && ch <= 122; +} +pp$1.regexp_eatRegExpUnicodeEscapeSequence = function(state, forceU) { + if (forceU === void 0) + forceU = false; + var start = state.pos; + var switchU = forceU || state.switchU; + if (state.eat(117)) { + if (this.regexp_eatFixedHexDigits(state, 4)) { + var lead = state.lastIntValue; + if (switchU && lead >= 55296 && lead <= 56319) { + var leadSurrogateEnd = state.pos; + if (state.eat(92) && state.eat(117) && this.regexp_eatFixedHexDigits(state, 4)) { + var trail = state.lastIntValue; + if (trail >= 56320 && trail <= 57343) { + state.lastIntValue = (lead - 55296) * 1024 + (trail - 56320) + 65536; + return true; + } + } + state.pos = leadSurrogateEnd; + state.lastIntValue = lead; + } + return true; + } + if (switchU && state.eat(123) && this.regexp_eatHexDigits(state) && state.eat(125) && isValidUnicode(state.lastIntValue)) { + return true; + } + if (switchU) { + state.raise("Invalid unicode escape"); + } + state.pos = start; + } + return false; +}; +function isValidUnicode(ch) { + return ch >= 0 && ch <= 1114111; +} +pp$1.regexp_eatIdentityEscape = function(state) { + if (state.switchU) { + if (this.regexp_eatSyntaxCharacter(state)) { + return true; + } + if (state.eat(47)) { + state.lastIntValue = 47; + return true; + } + return false; + } + var ch = state.current(); + if (ch !== 99 && (!state.switchN || ch !== 107)) { + state.lastIntValue = ch; + state.advance(); + return true; + } + return false; +}; +pp$1.regexp_eatDecimalEscape = function(state) { + state.lastIntValue = 0; + var ch = state.current(); + if (ch >= 49 && ch <= 57) { + do { + state.lastIntValue = 10 * state.lastIntValue + (ch - 48); + state.advance(); + } while ((ch = state.current()) >= 48 && ch <= 57); + return true; + } + return false; +}; +pp$1.regexp_eatCharacterClassEscape = function(state) { + var ch = state.current(); + if (isCharacterClassEscape(ch)) { + state.lastIntValue = -1; + state.advance(); + return true; + } + if (state.switchU && this.options.ecmaVersion >= 9 && (ch === 80 || ch === 112)) { + state.lastIntValue = -1; + state.advance(); + if (state.eat(123) && this.regexp_eatUnicodePropertyValueExpression(state) && state.eat(125)) { + return true; + } + state.raise("Invalid property name"); } + return false; +}; +function isCharacterClassEscape(ch) { + return ch === 100 || ch === 68 || ch === 115 || ch === 83 || ch === 119 || ch === 87; } -var emojiFromString = (emoji) => { - let html; - try { - html = unifiedToNative(emoji); - } catch (e4) { - html = emoji; +pp$1.regexp_eatUnicodePropertyValueExpression = function(state) { + var start = state.pos; + if (this.regexp_eatUnicodePropertyName(state) && state.eat(61)) { + var name = state.lastStringValue; + if (this.regexp_eatUnicodePropertyValue(state)) { + var value = state.lastStringValue; + this.regexp_validateUnicodePropertyNameAndValue(state, name, value); + return true; + } } - return html; + state.pos = start; + if (this.regexp_eatLoneUnicodePropertyNameOrValue(state)) { + var nameOrValue = state.lastStringValue; + this.regexp_validateUnicodePropertyNameOrValue(state, nameOrValue); + return true; + } + return false; }; -var unifiedToNative = (unified) => { - let unicodes = unified.split("-"); - let codePoints = unicodes.map((u4) => `0x${u4}`); - return String.fromCodePoint(...codePoints); +pp$1.regexp_validateUnicodePropertyNameAndValue = function(state, name, value) { + if (!hasOwn(state.unicodeProperties.nonBinary, name)) { + state.raise("Invalid property name"); + } + if (!state.unicodeProperties.nonBinary[name].test(value)) { + state.raise("Invalid property value"); + } }; -var indexOfCharElseEOS = (char, str) => { - if (str.indexOf(char) > 0) - return str.indexOf(char); - return str.length; +pp$1.regexp_validateUnicodePropertyNameOrValue = function(state, nameOrValue) { + if (!state.unicodeProperties.binary.test(nameOrValue)) { + state.raise("Invalid property name"); + } }; -var spaceNameFromContextPath = (contextPath) => contextPath.substring(0, contextPath.length - 2); -var spaceContextPathFromName = (spaceName) => spaceName.replace(/\//g, "+") + "//"; -var filePathToString = (filename) => { - if (filename.lastIndexOf("/") != -1) { - if (filename.lastIndexOf(".") != -1) - return removeLeadingSlash( - filename.substring( - filename.lastIndexOf("/") + 1, - filename.lastIndexOf(".") - ) - ); - return filename.substring(filename.lastIndexOf("/") + 1); +pp$1.regexp_eatUnicodePropertyName = function(state) { + var ch = 0; + state.lastStringValue = ""; + while (isUnicodePropertyNameCharacter(ch = state.current())) { + state.lastStringValue += codePointToString(ch); + state.advance(); } - if (filename.lastIndexOf(".") != -1) { - return filename.substring(0, filename.lastIndexOf(".")); + return state.lastStringValue !== ""; +}; +function isUnicodePropertyNameCharacter(ch) { + return isControlLetter(ch) || ch === 95; +} +pp$1.regexp_eatUnicodePropertyValue = function(state) { + var ch = 0; + state.lastStringValue = ""; + while (isUnicodePropertyValueCharacter(ch = state.current())) { + state.lastStringValue += codePointToString(ch); + state.advance(); } - return filename; + return state.lastStringValue !== ""; }; -var stringFromTag = (string) => { - if (string.charAt(0) == "#") { - return string.substring(1, string.length); +function isUnicodePropertyValueCharacter(ch) { + return isUnicodePropertyNameCharacter(ch) || isDecimalDigit(ch); +} +pp$1.regexp_eatLoneUnicodePropertyNameOrValue = function(state) { + return this.regexp_eatUnicodePropertyValue(state); +}; +pp$1.regexp_eatCharacterClass = function(state) { + if (state.eat(91)) { + state.eat(94); + this.regexp_classRanges(state); + if (state.eat(93)) { + return true; + } + state.raise("Unterminated character class"); } - return string; + return false; }; -var fileNameToString = (filename) => filename.substring(0, filename.lastIndexOf(".")) || filename; -var removeLeadingSlash = (path) => path.charAt(0) == "/" ? path.substring(1) : path; -var folderPathToString = (filename) => removeLeadingSlash(filename.substring(filename.lastIndexOf("/"))) || filename; -var contextDisplayName = (context) => { - if (!context) - return ""; - if ((context == null ? void 0 : context.type) == "folder") - return folderPathToString(context.contextPath); - if ((context == null ? void 0 : context.type) == "tag") - return stringFromTag(context.contextPath); - if ((context == null ? void 0 : context.type) == "space") - return spaceNameFromContextPath(context.contextPath); - if (context.isRemote) { - return folderPathToString(context.contextPath); +pp$1.regexp_classRanges = function(state) { + while (this.regexp_eatClassAtom(state)) { + var left = state.lastIntValue; + if (state.eat(45) && this.regexp_eatClassAtom(state)) { + var right = state.lastIntValue; + if (state.switchU && (left === -1 || right === -1)) { + state.raise("Invalid character class"); + } + if (left !== -1 && right !== -1 && left > right) { + state.raise("Range out of order in character class"); + } + } } - return context.contextPath; }; -var folderNotePathFromAFile = (settings, aFile) => !aFile ? null : settings.folderNoteInsideFolder ? `${aFile.path}/${aFile.name}.md` : aFile.parent == "/" ? `${aFile.name}.md` : `${aFile.parent}/${aFile.name}.md`; -var folderPathFromFolderNoteFile = (settings, aFile) => !aFile ? null : settings.folderNoteInsideFolder ? aFile.parent : aFile.parent == "/" ? aFile.name : `${aFile.parent}/${aFile.name}`; - -// src/components/ui/menus/selectMenu/concerns/matchers.js -function escapeForRegExp(string) { - return string.replace(/[-\\^$*+?.()|[\]{}]/g, "\\$&"); +pp$1.regexp_eatClassAtom = function(state) { + var start = state.pos; + if (state.eat(92)) { + if (this.regexp_eatClassEscape(state)) { + return true; + } + if (state.switchU) { + var ch$1 = state.current(); + if (ch$1 === 99 || isOctalDigit(ch$1)) { + state.raise("Invalid class escape"); + } + state.raise("Invalid escape"); + } + state.pos = start; + } + var ch = state.current(); + if (ch !== 93) { + state.lastIntValue = ch; + state.advance(); + return true; + } + return false; +}; +pp$1.regexp_eatClassEscape = function(state) { + var start = state.pos; + if (state.eat(98)) { + state.lastIntValue = 8; + return true; + } + if (state.switchU && state.eat(45)) { + state.lastIntValue = 45; + return true; + } + if (!state.switchU && state.eat(99)) { + if (this.regexp_eatClassControlLetter(state)) { + return true; + } + state.pos = start; + } + return this.regexp_eatCharacterClassEscape(state) || this.regexp_eatCharacterEscape(state); +}; +pp$1.regexp_eatClassControlLetter = function(state) { + var ch = state.current(); + if (isDecimalDigit(ch) || ch === 95) { + state.lastIntValue = ch % 32; + state.advance(); + return true; + } + return false; +}; +pp$1.regexp_eatHexEscapeSequence = function(state) { + var start = state.pos; + if (state.eat(120)) { + if (this.regexp_eatFixedHexDigits(state, 2)) { + return true; + } + if (state.switchU) { + state.raise("Invalid escape"); + } + state.pos = start; + } + return false; +}; +pp$1.regexp_eatDecimalDigits = function(state) { + var start = state.pos; + var ch = 0; + state.lastIntValue = 0; + while (isDecimalDigit(ch = state.current())) { + state.lastIntValue = 10 * state.lastIntValue + (ch - 48); + state.advance(); + } + return state.pos !== start; +}; +function isDecimalDigit(ch) { + return ch >= 48 && ch <= 57; } -function matchAny(string) { - return new RegExp(escapeForRegExp(string), "gi"); +pp$1.regexp_eatHexDigits = function(state) { + var start = state.pos; + var ch = 0; + state.lastIntValue = 0; + while (isHexDigit(ch = state.current())) { + state.lastIntValue = 16 * state.lastIntValue + hexToInt(ch); + state.advance(); + } + return state.pos !== start; +}; +function isHexDigit(ch) { + return ch >= 48 && ch <= 57 || ch >= 65 && ch <= 70 || ch >= 97 && ch <= 102; } -function matchExact(string) { - return new RegExp(`^${escapeForRegExp(string)}$`, "i"); +function hexToInt(ch) { + if (ch >= 65 && ch <= 70) { + return 10 + (ch - 65); + } + if (ch >= 97 && ch <= 102) { + return 10 + (ch - 97); + } + return ch - 48; } - -// src/components/ContextView/MDBContext.tsx -var import_lodash2 = __toESM(require_lodash()); -var import_obsidian7 = require("obsidian"); - -// src/types/context.ts -var FilePropertyName = "File"; - -// src/utils/contexts/parsers.ts -var parsePropString = (str) => { - var _a2; - const [p1, p22] = (_a2 = str == null ? void 0 : str.match(/(\\.|[^.])+/g)) != null ? _a2 : []; - if (p22) +pp$1.regexp_eatLegacyOctalEscapeSequence = function(state) { + if (this.regexp_eatOctalDigit(state)) { + var n1 = state.lastIntValue; + if (this.regexp_eatOctalDigit(state)) { + var n2 = state.lastIntValue; + if (n1 <= 3 && this.regexp_eatOctalDigit(state)) { + state.lastIntValue = n1 * 64 + n2 * 8 + state.lastIntValue; + } else { + state.lastIntValue = n1 * 8 + n2; + } + } else { + state.lastIntValue = n1; + } + return true; + } + return false; +}; +pp$1.regexp_eatOctalDigit = function(state) { + var ch = state.current(); + if (isOctalDigit(ch)) { + state.lastIntValue = ch - 48; + state.advance(); + return true; + } + state.lastIntValue = 0; + return false; +}; +function isOctalDigit(ch) { + return ch >= 48 && ch <= 55; +} +pp$1.regexp_eatFixedHexDigits = function(state, length) { + var start = state.pos; + state.lastIntValue = 0; + for (var i4 = 0; i4 < length; ++i4) { + var ch = state.current(); + if (!isHexDigit(ch)) { + state.pos = start; + return false; + } + state.lastIntValue = 16 * state.lastIntValue + hexToInt(ch); + state.advance(); + } + return true; +}; +var Token = function Token2(p3) { + this.type = p3.type; + this.value = p3.value; + this.start = p3.start; + this.end = p3.end; + if (p3.options.locations) { + this.loc = new SourceLocation(p3, p3.startLoc, p3.endLoc); + } + if (p3.options.ranges) { + this.range = [p3.start, p3.end]; + } +}; +var pp = Parser.prototype; +pp.next = function(ignoreEscapeSequenceInKeyword) { + if (!ignoreEscapeSequenceInKeyword && this.type.keyword && this.containsEsc) { + this.raiseRecoverable(this.start, "Escape sequence in keyword " + this.type.keyword); + } + if (this.options.onToken) { + this.options.onToken(new Token(this)); + } + this.lastTokEnd = this.end; + this.lastTokStart = this.start; + this.lastTokEndLoc = this.endLoc; + this.lastTokStartLoc = this.startLoc; + this.nextToken(); +}; +pp.getToken = function() { + this.next(); + return new Token(this); +}; +if (typeof Symbol !== "undefined") { + pp[Symbol.iterator] = function() { + var this$1$1 = this; return { - field: p1, - property: p22 + next: function() { + var token = this$1$1.getToken(); + return { + done: token.type === types$1.eof, + value: token + }; + } }; - return { field: "File", property: p1 }; + }; +} +pp.nextToken = function() { + var curContext = this.curContext(); + if (!curContext || !curContext.preserveSpace) { + this.skipSpace(); + } + this.start = this.pos; + if (this.options.locations) { + this.startLoc = this.curPosition(); + } + if (this.pos >= this.input.length) { + return this.finishToken(types$1.eof); + } + if (curContext.override) { + return curContext.override(this); + } else { + this.readToken(this.fullCharCodeAtPos()); + } }; - -// src/schemas/mdb.ts -var fieldTypeForType = (type) => fieldTypes.find((t4) => type == t4.type) || fieldTypes.find((t4) => type == t4.multiType); -var fieldTypes = [ - { - type: "unknown", - label: "", - restricted: true - }, - { - type: "preview", - label: i18n_default.properties.preview.label, - restricted: true - }, - { - type: "text", - label: i18n_default.properties.text.label, - metadata: true, - icon: "mk-make-h3" - }, - { - type: "number", - label: i18n_default.properties.number.label, - metadata: true, - icon: "mk-make-tag" - }, - { - type: "boolean", - label: i18n_default.properties.boolean.label, - metadata: true, - icon: "mk-make-todo" - }, - { - type: "date", - label: i18n_default.properties.date.label, - metadata: true, - icon: "mk-make-date" - }, - { - type: "option", - label: i18n_default.properties.option.label, - multi: true, - multiType: "option-multi", - icon: "mk-make-list" - }, - { - type: "file", - label: i18n_default.properties.file.label, - restricted: true, - icon: "mk-make-h3" - }, - { - type: "fileprop", - label: i18n_default.properties.fileProperty.label - }, - { - type: "link", - label: i18n_default.properties.link.label, - multi: true, - multiType: "link-multi", - metadata: true, - icon: "mk-make-note" - }, - { - type: "context", - label: i18n_default.properties.context.label, - multi: true, - multiType: "context-multi", - icon: "mk-make-note" - }, - { - type: "object", - label: i18n_default.properties.context.label, - restricted: true, - metadata: true - }, - { - type: "image", - label: i18n_default.properties.image.label, - multi: true, - multiType: "image-multi", - metadata: true, - icon: "mk-make-image" +pp.readToken = function(code) { + if (isIdentifierStart(code, this.options.ecmaVersion >= 6) || code === 92) { + return this.readWord(); } -]; -var defaultValueForPropertyType = (name, value, type) => { - if (type == "preview") { - return "https://images.unsplash.com/photo-1675789652575-0a5d2425b6c2?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=2070&q=80"; + return this.getTokenFromCode(code); +}; +pp.fullCharCodeAtPos = function() { + var code = this.input.charCodeAt(this.pos); + if (code <= 55295 || code >= 56320) { + return code; + } + var next = this.input.charCodeAt(this.pos + 1); + return next <= 56319 || next >= 57344 ? code : (code << 10) + next - 56613888; +}; +pp.skipBlockComment = function() { + var startLoc = this.options.onComment && this.curPosition(); + var start = this.pos, end = this.input.indexOf("*/", this.pos += 2); + if (end === -1) { + this.raise(this.pos - 2, "Unterminated comment"); + } + this.pos = end + 2; + if (this.options.locations) { + for (var nextBreak = void 0, pos = start; (nextBreak = nextLineBreak(this.input, pos, this.pos)) > -1; ) { + ++this.curLine; + pos = this.lineStart = nextBreak; + } + } + if (this.options.onComment) { + this.options.onComment( + true, + this.input.slice(start + 2, end), + start, + this.pos, + startLoc, + this.curPosition() + ); + } +}; +pp.skipLineComment = function(startSkip) { + var start = this.pos; + var startLoc = this.options.onComment && this.curPosition(); + var ch = this.input.charCodeAt(this.pos += startSkip); + while (this.pos < this.input.length && !isNewLine(ch)) { + ch = this.input.charCodeAt(++this.pos); + } + if (this.options.onComment) { + this.options.onComment( + false, + this.input.slice(start + startSkip, this.pos), + start, + this.pos, + startLoc, + this.curPosition() + ); + } +}; +pp.skipSpace = function() { + loop: + while (this.pos < this.input.length) { + var ch = this.input.charCodeAt(this.pos); + switch (ch) { + case 32: + case 160: + ++this.pos; + break; + case 13: + if (this.input.charCodeAt(this.pos + 1) === 10) { + ++this.pos; + } + case 10: + case 8232: + case 8233: + ++this.pos; + if (this.options.locations) { + ++this.curLine; + this.lineStart = this.pos; + } + break; + case 47: + switch (this.input.charCodeAt(this.pos + 1)) { + case 42: + this.skipBlockComment(); + break; + case 47: + this.skipLineComment(2); + break; + default: + break loop; + } + break; + default: + if (ch > 8 && ch < 14 || ch >= 5760 && nonASCIIwhitespace.test(String.fromCharCode(ch))) { + ++this.pos; + } else { + break loop; + } + } + } +}; +pp.finishToken = function(type, val) { + this.end = this.pos; + if (this.options.locations) { + this.endLoc = this.curPosition(); + } + var prevType = this.type; + this.type = type; + this.value = val; + this.updateContext(prevType); +}; +pp.readToken_dot = function() { + var next = this.input.charCodeAt(this.pos + 1); + if (next >= 48 && next <= 57) { + return this.readNumber(true); + } + var next2 = this.input.charCodeAt(this.pos + 2); + if (this.options.ecmaVersion >= 6 && next === 46 && next2 === 46) { + this.pos += 3; + return this.finishToken(types$1.ellipsis); + } else { + ++this.pos; + return this.finishToken(types$1.dot); + } +}; +pp.readToken_slash = function() { + var next = this.input.charCodeAt(this.pos + 1); + if (this.exprAllowed) { + ++this.pos; + return this.readRegexp(); + } + if (next === 61) { + return this.finishOp(types$1.assign, 2); + } + return this.finishOp(types$1.slash, 1); +}; +pp.readToken_mult_modulo_exp = function(code) { + var next = this.input.charCodeAt(this.pos + 1); + var size = 1; + var tokentype = code === 42 ? types$1.star : types$1.modulo; + if (this.options.ecmaVersion >= 7 && code === 42 && next === 42) { + ++size; + tokentype = types$1.starstar; + next = this.input.charCodeAt(this.pos + 2); + } + if (next === 61) { + return this.finishOp(types$1.assign, size + 1); + } + return this.finishOp(tokentype, size); +}; +pp.readToken_pipe_amp = function(code) { + var next = this.input.charCodeAt(this.pos + 1); + if (next === code) { + if (this.options.ecmaVersion >= 12) { + var next2 = this.input.charCodeAt(this.pos + 2); + if (next2 === 61) { + return this.finishOp(types$1.assign, 3); + } + } + return this.finishOp(code === 124 ? types$1.logicalOR : types$1.logicalAND, 2); + } + if (next === 61) { + return this.finishOp(types$1.assign, 2); + } + return this.finishOp(code === 124 ? types$1.bitwiseOR : types$1.bitwiseAND, 1); +}; +pp.readToken_caret = function() { + var next = this.input.charCodeAt(this.pos + 1); + if (next === 61) { + return this.finishOp(types$1.assign, 2); + } + return this.finishOp(types$1.bitwiseXOR, 1); +}; +pp.readToken_plus_min = function(code) { + var next = this.input.charCodeAt(this.pos + 1); + if (next === code) { + if (next === 45 && !this.inModule && this.input.charCodeAt(this.pos + 2) === 62 && (this.lastTokEnd === 0 || lineBreak.test(this.input.slice(this.lastTokEnd, this.pos)))) { + this.skipLineComment(3); + this.skipSpace(); + return this.nextToken(); + } + return this.finishOp(types$1.incDec, 2); + } + if (next === 61) { + return this.finishOp(types$1.assign, 2); + } + return this.finishOp(types$1.plusMin, 1); +}; +pp.readToken_lt_gt = function(code) { + var next = this.input.charCodeAt(this.pos + 1); + var size = 1; + if (next === code) { + size = code === 62 && this.input.charCodeAt(this.pos + 2) === 62 ? 3 : 2; + if (this.input.charCodeAt(this.pos + size) === 61) { + return this.finishOp(types$1.assign, size + 1); + } + return this.finishOp(types$1.bitShift, size); + } + if (next === 33 && code === 60 && !this.inModule && this.input.charCodeAt(this.pos + 2) === 45 && this.input.charCodeAt(this.pos + 3) === 45) { + this.skipLineComment(4); + this.skipSpace(); + return this.nextToken(); + } + if (next === 61) { + size = 2; + } + return this.finishOp(types$1.relational, size); +}; +pp.readToken_eq_excl = function(code) { + var next = this.input.charCodeAt(this.pos + 1); + if (next === 61) { + return this.finishOp(types$1.equality, this.input.charCodeAt(this.pos + 2) === 61 ? 3 : 2); + } + if (code === 61 && next === 62 && this.options.ecmaVersion >= 6) { + this.pos += 2; + return this.finishToken(types$1.arrow); + } + return this.finishOp(code === 61 ? types$1.eq : types$1.prefix, 1); +}; +pp.readToken_question = function() { + var ecmaVersion = this.options.ecmaVersion; + if (ecmaVersion >= 11) { + var next = this.input.charCodeAt(this.pos + 1); + if (next === 46) { + var next2 = this.input.charCodeAt(this.pos + 2); + if (next2 < 48 || next2 > 57) { + return this.finishOp(types$1.questionDot, 2); + } + } + if (next === 63) { + if (ecmaVersion >= 12) { + var next2$1 = this.input.charCodeAt(this.pos + 2); + if (next2$1 === 61) { + return this.finishOp(types$1.assign, 3); + } + } + return this.finishOp(types$1.coalesce, 2); + } + } + return this.finishOp(types$1.question, 1); +}; +pp.readToken_numberSign = function() { + var ecmaVersion = this.options.ecmaVersion; + var code = 35; + if (ecmaVersion >= 13) { + ++this.pos; + code = this.fullCharCodeAtPos(); + if (isIdentifierStart(code, true) || code === 92) { + return this.finishToken(types$1.privateId, this.readWord1()); + } + } + this.raise(this.pos, "Unexpected character '" + codePointToString(code) + "'"); +}; +pp.getTokenFromCode = function(code) { + switch (code) { + case 46: + return this.readToken_dot(); + case 40: + ++this.pos; + return this.finishToken(types$1.parenL); + case 41: + ++this.pos; + return this.finishToken(types$1.parenR); + case 59: + ++this.pos; + return this.finishToken(types$1.semi); + case 44: + ++this.pos; + return this.finishToken(types$1.comma); + case 91: + ++this.pos; + return this.finishToken(types$1.bracketL); + case 93: + ++this.pos; + return this.finishToken(types$1.bracketR); + case 123: + ++this.pos; + return this.finishToken(types$1.braceL); + case 125: + ++this.pos; + return this.finishToken(types$1.braceR); + case 58: + ++this.pos; + return this.finishToken(types$1.colon); + case 96: + if (this.options.ecmaVersion < 6) { + break; + } + ++this.pos; + return this.finishToken(types$1.backQuote); + case 48: + var next = this.input.charCodeAt(this.pos + 1); + if (next === 120 || next === 88) { + return this.readRadixNumber(16); + } + if (this.options.ecmaVersion >= 6) { + if (next === 111 || next === 79) { + return this.readRadixNumber(8); + } + if (next === 98 || next === 66) { + return this.readRadixNumber(2); + } + } + case 49: + case 50: + case 51: + case 52: + case 53: + case 54: + case 55: + case 56: + case 57: + return this.readNumber(false); + case 34: + case 39: + return this.readString(code); + case 47: + return this.readToken_slash(); + case 37: + case 42: + return this.readToken_mult_modulo_exp(code); + case 124: + case 38: + return this.readToken_pipe_amp(code); + case 94: + return this.readToken_caret(); + case 43: + case 45: + return this.readToken_plus_min(code); + case 60: + case 62: + return this.readToken_lt_gt(code); + case 61: + case 33: + return this.readToken_eq_excl(code); + case 63: + return this.readToken_question(); + case 126: + return this.finishOp(types$1.prefix, 1); + case 35: + return this.readToken_numberSign(); + } + this.raise(this.pos, "Unexpected character '" + codePointToString(code) + "'"); +}; +pp.finishOp = function(type, size) { + var str = this.input.slice(this.pos, this.pos + size); + this.pos += size; + return this.finishToken(type, str); +}; +pp.readRegexp = function() { + var escaped, inClass, start = this.pos; + for (; ; ) { + if (this.pos >= this.input.length) { + this.raise(start, "Unterminated regular expression"); + } + var ch = this.input.charAt(this.pos); + if (lineBreak.test(ch)) { + this.raise(start, "Unterminated regular expression"); + } + if (!escaped) { + if (ch === "[") { + inClass = true; + } else if (ch === "]" && inClass) { + inClass = false; + } else if (ch === "/" && !inClass) { + break; + } + escaped = ch === "\\"; + } else { + escaped = false; + } + ++this.pos; + } + var pattern = this.input.slice(start, this.pos); + ++this.pos; + var flagsStart = this.pos; + var flags = this.readWord1(); + if (this.containsEsc) { + this.unexpected(flagsStart); + } + var state = this.regexpState || (this.regexpState = new RegExpValidationState(this)); + state.reset(start, pattern, flags); + this.validateRegExpFlags(state); + this.validateRegExpPattern(state); + var value = null; + try { + value = new RegExp(pattern, flags); + } catch (e4) { + } + return this.finishToken(types$1.regexp, { pattern, flags, value }); +}; +pp.readInt = function(radix, len, maybeLegacyOctalNumericLiteral) { + var allowSeparators = this.options.ecmaVersion >= 12 && len === void 0; + var isLegacyOctalNumericLiteral = maybeLegacyOctalNumericLiteral && this.input.charCodeAt(this.pos) === 48; + var start = this.pos, total = 0, lastCode = 0; + for (var i4 = 0, e4 = len == null ? Infinity : len; i4 < e4; ++i4, ++this.pos) { + var code = this.input.charCodeAt(this.pos), val = void 0; + if (allowSeparators && code === 95) { + if (isLegacyOctalNumericLiteral) { + this.raiseRecoverable(this.pos, "Numeric separator is not allowed in legacy octal numeric literals"); + } + if (lastCode === 95) { + this.raiseRecoverable(this.pos, "Numeric separator must be exactly one underscore"); + } + if (i4 === 0) { + this.raiseRecoverable(this.pos, "Numeric separator is not allowed at the first of digits"); + } + lastCode = code; + continue; + } + if (code >= 97) { + val = code - 97 + 10; + } else if (code >= 65) { + val = code - 65 + 10; + } else if (code >= 48 && code <= 57) { + val = code - 48; + } else { + val = Infinity; + } + if (val >= radix) { + break; + } + lastCode = code; + total = total * radix + val; + } + if (allowSeparators && lastCode === 95) { + this.raiseRecoverable(this.pos - 1, "Numeric separator is not allowed at the last of digits"); + } + if (this.pos === start || len != null && this.pos - start !== len) { + return null; + } + return total; +}; +function stringToNumber(str, isLegacyOctalNumericLiteral) { + if (isLegacyOctalNumericLiteral) { + return parseInt(str, 8); + } + return parseFloat(str.replace(/_/g, "")); +} +function stringToBigInt(str) { + if (typeof BigInt !== "function") { + return null; + } + return BigInt(str.replace(/_/g, "")); +} +pp.readRadixNumber = function(radix) { + var start = this.pos; + this.pos += 2; + var val = this.readInt(radix); + if (val == null) { + this.raise(this.start + 2, "Expected number in radix " + radix); + } + if (this.options.ecmaVersion >= 11 && this.input.charCodeAt(this.pos) === 110) { + val = stringToBigInt(this.input.slice(start, this.pos)); + ++this.pos; + } else if (isIdentifierStart(this.fullCharCodeAtPos())) { + this.raise(this.pos, "Identifier directly after number"); + } + return this.finishToken(types$1.num, val); +}; +pp.readNumber = function(startsWithDot) { + var start = this.pos; + if (!startsWithDot && this.readInt(10, void 0, true) === null) { + this.raise(start, "Invalid number"); + } + var octal = this.pos - start >= 2 && this.input.charCodeAt(start) === 48; + if (octal && this.strict) { + this.raise(start, "Invalid number"); + } + var next = this.input.charCodeAt(this.pos); + if (!octal && !startsWithDot && this.options.ecmaVersion >= 11 && next === 110) { + var val$1 = stringToBigInt(this.input.slice(start, this.pos)); + ++this.pos; + if (isIdentifierStart(this.fullCharCodeAtPos())) { + this.raise(this.pos, "Identifier directly after number"); + } + return this.finishToken(types$1.num, val$1); + } + if (octal && /[89]/.test(this.input.slice(start, this.pos))) { + octal = false; + } + if (next === 46 && !octal) { + ++this.pos; + this.readInt(10); + next = this.input.charCodeAt(this.pos); + } + if ((next === 69 || next === 101) && !octal) { + next = this.input.charCodeAt(++this.pos); + if (next === 43 || next === 45) { + ++this.pos; + } + if (this.readInt(10) === null) { + this.raise(start, "Invalid number"); + } + } + if (isIdentifierStart(this.fullCharCodeAtPos())) { + this.raise(this.pos, "Identifier directly after number"); + } + var val = stringToNumber(this.input.slice(start, this.pos), octal); + return this.finishToken(types$1.num, val); +}; +pp.readCodePoint = function() { + var ch = this.input.charCodeAt(this.pos), code; + if (ch === 123) { + if (this.options.ecmaVersion < 6) { + this.unexpected(); + } + var codePos = ++this.pos; + code = this.readHexChar(this.input.indexOf("}", this.pos) - this.pos); + ++this.pos; + if (code > 1114111) { + this.invalidStringToken(codePos, "Code point out of bounds"); + } + } else { + code = this.readHexChar(4); + } + return code; +}; +pp.readString = function(quote) { + var out = "", chunkStart = ++this.pos; + for (; ; ) { + if (this.pos >= this.input.length) { + this.raise(this.start, "Unterminated string constant"); + } + var ch = this.input.charCodeAt(this.pos); + if (ch === quote) { + break; + } + if (ch === 92) { + out += this.input.slice(chunkStart, this.pos); + out += this.readEscapedChar(false); + chunkStart = this.pos; + } else if (ch === 8232 || ch === 8233) { + if (this.options.ecmaVersion < 10) { + this.raise(this.start, "Unterminated string constant"); + } + ++this.pos; + if (this.options.locations) { + this.curLine++; + this.lineStart = this.pos; + } + } else { + if (isNewLine(ch)) { + this.raise(this.start, "Unterminated string constant"); + } + ++this.pos; + } + } + out += this.input.slice(chunkStart, this.pos++); + return this.finishToken(types$1.string, out); +}; +var INVALID_TEMPLATE_ESCAPE_ERROR = {}; +pp.tryReadTemplateToken = function() { + this.inTemplateElement = true; + try { + this.readTmplToken(); + } catch (err) { + if (err === INVALID_TEMPLATE_ESCAPE_ERROR) { + this.readInvalidTemplateToken(); + } else { + throw err; + } + } + this.inTemplateElement = false; +}; +pp.invalidStringToken = function(position, message) { + if (this.inTemplateElement && this.options.ecmaVersion >= 9) { + throw INVALID_TEMPLATE_ESCAPE_ERROR; + } else { + this.raise(position, message); + } +}; +pp.readTmplToken = function() { + var out = "", chunkStart = this.pos; + for (; ; ) { + if (this.pos >= this.input.length) { + this.raise(this.start, "Unterminated template"); + } + var ch = this.input.charCodeAt(this.pos); + if (ch === 96 || ch === 36 && this.input.charCodeAt(this.pos + 1) === 123) { + if (this.pos === this.start && (this.type === types$1.template || this.type === types$1.invalidTemplate)) { + if (ch === 36) { + this.pos += 2; + return this.finishToken(types$1.dollarBraceL); + } else { + ++this.pos; + return this.finishToken(types$1.backQuote); + } + } + out += this.input.slice(chunkStart, this.pos); + return this.finishToken(types$1.template, out); + } + if (ch === 92) { + out += this.input.slice(chunkStart, this.pos); + out += this.readEscapedChar(true); + chunkStart = this.pos; + } else if (isNewLine(ch)) { + out += this.input.slice(chunkStart, this.pos); + ++this.pos; + switch (ch) { + case 13: + if (this.input.charCodeAt(this.pos) === 10) { + ++this.pos; + } + case 10: + out += "\n"; + break; + default: + out += String.fromCharCode(ch); + break; + } + if (this.options.locations) { + ++this.curLine; + this.lineStart = this.pos; + } + chunkStart = this.pos; + } else { + ++this.pos; + } + } +}; +pp.readInvalidTemplateToken = function() { + for (; this.pos < this.input.length; this.pos++) { + switch (this.input[this.pos]) { + case "\\": + ++this.pos; + break; + case "$": + if (this.input[this.pos + 1] !== "{") { + break; + } + case "`": + return this.finishToken(types$1.invalidTemplate, this.input.slice(this.start, this.pos)); + } + } + this.raise(this.start, "Unterminated template"); +}; +pp.readEscapedChar = function(inTemplate) { + var ch = this.input.charCodeAt(++this.pos); + ++this.pos; + switch (ch) { + case 110: + return "\n"; + case 114: + return "\r"; + case 120: + return String.fromCharCode(this.readHexChar(2)); + case 117: + return codePointToString(this.readCodePoint()); + case 116: + return " "; + case 98: + return "\b"; + case 118: + return "\v"; + case 102: + return "\f"; + case 13: + if (this.input.charCodeAt(this.pos) === 10) { + ++this.pos; + } + case 10: + if (this.options.locations) { + this.lineStart = this.pos; + ++this.curLine; + } + return ""; + case 56: + case 57: + if (this.strict) { + this.invalidStringToken( + this.pos - 1, + "Invalid escape sequence" + ); + } + if (inTemplate) { + var codePos = this.pos - 1; + this.invalidStringToken( + codePos, + "Invalid escape sequence in template string" + ); + } + default: + if (ch >= 48 && ch <= 55) { + var octalStr = this.input.substr(this.pos - 1, 3).match(/^[0-7]+/)[0]; + var octal = parseInt(octalStr, 8); + if (octal > 255) { + octalStr = octalStr.slice(0, -1); + octal = parseInt(octalStr, 8); + } + this.pos += octalStr.length - 1; + ch = this.input.charCodeAt(this.pos); + if ((octalStr !== "0" || ch === 56 || ch === 57) && (this.strict || inTemplate)) { + this.invalidStringToken( + this.pos - 1 - octalStr.length, + inTemplate ? "Octal literal in template string" : "Octal literal in strict mode" + ); + } + return String.fromCharCode(octal); + } + if (isNewLine(ch)) { + return ""; + } + return String.fromCharCode(ch); + } +}; +pp.readHexChar = function(len) { + var codePos = this.pos; + var n2 = this.readInt(16, len); + if (n2 === null) { + this.invalidStringToken(codePos, "Bad character escape sequence"); + } + return n2; +}; +pp.readWord1 = function() { + this.containsEsc = false; + var word = "", first = true, chunkStart = this.pos; + var astral = this.options.ecmaVersion >= 6; + while (this.pos < this.input.length) { + var ch = this.fullCharCodeAtPos(); + if (isIdentifierChar(ch, astral)) { + this.pos += ch <= 65535 ? 1 : 2; + } else if (ch === 92) { + this.containsEsc = true; + word += this.input.slice(chunkStart, this.pos); + var escStart = this.pos; + if (this.input.charCodeAt(++this.pos) !== 117) { + this.invalidStringToken(this.pos, "Expecting Unicode escape sequence \\uXXXX"); + } + ++this.pos; + var esc = this.readCodePoint(); + if (!(first ? isIdentifierStart : isIdentifierChar)(esc, astral)) { + this.invalidStringToken(escStart, "Invalid Unicode escape"); + } + word += codePointToString(esc); + chunkStart = this.pos; + } else { + break; + } + first = false; + } + return word + this.input.slice(chunkStart, this.pos); +}; +pp.readWord = function() { + var word = this.readWord1(); + var type = types$1.name; + if (this.keywords.test(word)) { + type = keywords[word]; + } + return this.finishToken(type, word); +}; +var version = "8.8.2"; +Parser.acorn = { + Parser, + version, + defaultOptions, + Position, + SourceLocation, + getLineInfo, + Node, + TokenType, + tokTypes: types$1, + keywordTypes: keywords, + TokContext, + tokContexts: types, + isIdentifierChar, + isIdentifierStart, + Token, + isNewLine, + lineBreak, + lineBreakG, + nonASCIIwhitespace +}; +function parse3(input, options) { + return Parser.parse(input, options); +} + +// node_modules/acorn-walk/dist/walk.mjs +function ancestor(node, visitors, baseVisitor, state, override) { + var ancestors = []; + if (!baseVisitor) { + baseVisitor = base; } - if (type == "fileprop") { - const { field, property } = parsePropString(value); - if (property == "ctime" || property == "mtime") - return (Date.now() - 60).toString(); - return value; + (function c4(node2, st, override2) { + var type = override2 || node2.type, found = visitors[type]; + var isNew = node2 !== ancestors[ancestors.length - 1]; + if (isNew) { + ancestors.push(node2); + } + baseVisitor[type](node2, st, c4); + if (found) { + found(node2, st || ancestors, ancestors); + } + if (isNew) { + ancestors.pop(); + } + })(node, state, override); +} +function skipThrough(node, st, c4) { + c4(node, st); +} +function ignore(_node, _st, _c2) { +} +var base = {}; +base.Program = base.BlockStatement = base.StaticBlock = function(node, st, c4) { + for (var i4 = 0, list = node.body; i4 < list.length; i4 += 1) { + var stmt = list[i4]; + c4(stmt, st, "Statement"); } - if (type == "file") { - return "Note Name"; +}; +base.Statement = skipThrough; +base.EmptyStatement = ignore; +base.ExpressionStatement = base.ParenthesizedExpression = base.ChainExpression = function(node, st, c4) { + return c4(node.expression, st, "Expression"); +}; +base.IfStatement = function(node, st, c4) { + c4(node.test, st, "Expression"); + c4(node.consequent, st, "Statement"); + if (node.alternate) { + c4(node.alternate, st, "Statement"); } - if (type == "date") { - return "2020-04-21"; +}; +base.LabeledStatement = function(node, st, c4) { + return c4(node.body, st, "Statement"); +}; +base.BreakStatement = base.ContinueStatement = ignore; +base.WithStatement = function(node, st, c4) { + c4(node.object, st, "Expression"); + c4(node.body, st, "Statement"); +}; +base.SwitchStatement = function(node, st, c4) { + c4(node.discriminant, st, "Expression"); + for (var i$1 = 0, list$1 = node.cases; i$1 < list$1.length; i$1 += 1) { + var cs = list$1[i$1]; + if (cs.test) { + c4(cs.test, st, "Expression"); + } + for (var i4 = 0, list = cs.consequent; i4 < list.length; i4 += 1) { + var cons = list[i4]; + c4(cons, st, "Statement"); + } } - if (type == "number") { - return "123"; +}; +base.SwitchCase = function(node, st, c4) { + if (node.test) { + c4(node.test, st, "Expression"); } - if (type == "boolean") { - return "true"; + for (var i4 = 0, list = node.consequent; i4 < list.length; i4 += 1) { + var cons = list[i4]; + c4(cons, st, "Statement"); } - if (type == "link") { - return "[[Select Note]]"; +}; +base.ReturnStatement = base.YieldExpression = base.AwaitExpression = function(node, st, c4) { + if (node.argument) { + c4(node.argument, st, "Expression"); } - if (type == "option") { - return "one, two"; +}; +base.ThrowStatement = base.SpreadElement = function(node, st, c4) { + return c4(node.argument, st, "Expression"); +}; +base.TryStatement = function(node, st, c4) { + c4(node.block, st, "Statement"); + if (node.handler) { + c4(node.handler, st); } - if (type == "text") { - return name; + if (node.finalizer) { + c4(node.finalizer, st, "Statement"); } - if (type == "image") { - return "https://images.unsplash.com/photo-1675789652575-0a5d2425b6c2?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=2070&q=80"; +}; +base.CatchClause = function(node, st, c4) { + if (node.param) { + c4(node.param, st, "Pattern"); } - return ""; + c4(node.body, st, "Statement"); }; -var defaultFileDBSchema = { - id: "files", - name: "Files", - type: "db", - primary: "true" +base.WhileStatement = base.DoWhileStatement = function(node, st, c4) { + c4(node.test, st, "Expression"); + c4(node.body, st, "Statement"); }; -var defaultFileListSchema = { - id: "filesView", - name: "Files", - type: "list", - def: "files" +base.ForStatement = function(node, st, c4) { + if (node.init) { + c4(node.init, st, "ForInit"); + } + if (node.test) { + c4(node.test, st, "Expression"); + } + if (node.update) { + c4(node.update, st, "Expression"); + } + c4(node.body, st, "Statement"); }; -var defaultFileTableSchema = { - id: "filesView", - name: "Files", - type: "table", - def: "files" +base.ForInStatement = base.ForOfStatement = function(node, st, c4) { + c4(node.left, st, "ForInit"); + c4(node.right, st, "Expression"); + c4(node.body, st, "Statement"); }; -var defaultFolderSchema = { - uniques: [], - cols: ["id", "name", "type", "def", "predicate", "primary"], - rows: [defaultFileDBSchema, defaultFileListSchema] +base.ForInit = function(node, st, c4) { + if (node.type === "VariableDeclaration") { + c4(node, st); + } else { + c4(node, st, "Expression"); + } }; -var defaultTagSchema = { - uniques: [], - cols: ["id", "name", "type", "def", "predicate", "primary"], - rows: [defaultFileDBSchema, defaultFileTableSchema] +base.DebuggerStatement = ignore; +base.FunctionDeclaration = function(node, st, c4) { + return c4(node, st, "Function"); }; -var fieldSchema = { - uniques: ["name,schemaId"], - cols: [ - "name", - "schemaId", - "type", - "value", - "attrs", - "hidden", - "unique", - "primary" - ] +base.VariableDeclaration = function(node, st, c4) { + for (var i4 = 0, list = node.declarations; i4 < list.length; i4 += 1) { + var decl = list[i4]; + c4(decl, st); + } }; -var defaultFolderFields = { - ...fieldSchema, - rows: [ - { - name: i18n_default.properties.preview.label, - schemaId: "files", - type: "preview", - hidden: "", - unique: "", - attrs: "", - value: "", - primary: "" - }, - { - name: FilePropertyName, - schemaId: "files", - type: "file", - primary: "true", - hidden: "", - unique: "", - attrs: "", - value: "" - }, - { - name: i18n_default.properties.fileProperty.createdTime, - schemaId: "files", - type: "fileprop", - value: "File.ctime", - hidden: "", - unique: "", - attrs: "", - primary: "" - } - ] +base.VariableDeclarator = function(node, st, c4) { + c4(node.id, st, "Pattern"); + if (node.init) { + c4(node.init, st, "Expression"); + } }; -var defaultFieldsForContext = (context) => { - if (context.type == "tag") { - return defaultTagFields; - } else if (context.type == "folder") { - return defaultFolderFields; +base.Function = function(node, st, c4) { + if (node.id) { + c4(node.id, st, "Pattern"); } - return defaultFolderFields; + for (var i4 = 0, list = node.params; i4 < list.length; i4 += 1) { + var param = list[i4]; + c4(param, st, "Pattern"); + } + c4(node.body, st, node.expression ? "Expression" : "Statement"); }; -var defaultTableFields = [ - { - name: i18n_default.properties.defaultField, - schemaId: "", - type: "text" +base.Pattern = function(node, st, c4) { + if (node.type === "Identifier") { + c4(node, st, "VariablePattern"); + } else if (node.type === "MemberExpression") { + c4(node, st, "MemberPattern"); + } else { + c4(node, st); } -]; -var defaultTagFields = { - ...fieldSchema, - rows: [ - { - name: FilePropertyName, - schemaId: "files", - type: "file", - primary: "true", - hidden: "", - unique: "", - attrs: "", - value: "" - } - ] }; -var defaultMDBTableForContext = (context) => { - if (context.type == "tag") { - return defaultTagMDBTable; - } else if (context.type == "folder") { - return defaultFolderMDBTable; +base.VariablePattern = ignore; +base.MemberPattern = skipThrough; +base.RestElement = function(node, st, c4) { + return c4(node.argument, st, "Pattern"); +}; +base.ArrayPattern = function(node, st, c4) { + for (var i4 = 0, list = node.elements; i4 < list.length; i4 += 1) { + var elt = list[i4]; + if (elt) { + c4(elt, st, "Pattern"); + } } - return defaultFolderMDBTable; }; -var defaultFolderMDBTable = { - schema: defaultFileDBSchema, - cols: defaultFolderFields.rows, - rows: [] +base.ObjectPattern = function(node, st, c4) { + for (var i4 = 0, list = node.properties; i4 < list.length; i4 += 1) { + var prop = list[i4]; + if (prop.type === "Property") { + if (prop.computed) { + c4(prop.key, st, "Expression"); + } + c4(prop.value, st, "Pattern"); + } else if (prop.type === "RestElement") { + c4(prop.argument, st, "Pattern"); + } + } }; -var defaultQueryMDBTable = { - schema: defaultFileDBSchema, - cols: defaultFolderFields.rows, - rows: [] +base.Expression = skipThrough; +base.ThisExpression = base.Super = base.MetaProperty = ignore; +base.ArrayExpression = function(node, st, c4) { + for (var i4 = 0, list = node.elements; i4 < list.length; i4 += 1) { + var elt = list[i4]; + if (elt) { + c4(elt, st, "Expression"); + } + } }; -var defaultTagMDBTable = { - schema: defaultFileDBSchema, - cols: defaultTagFields.rows, - rows: [] +base.ObjectExpression = function(node, st, c4) { + for (var i4 = 0, list = node.properties; i4 < list.length; i4 += 1) { + var prop = list[i4]; + c4(prop, st); + } }; -var fieldsToTable = (fields, schemas) => { - return fields.filter((s5) => schemas.find((g4) => g4.id == s5.schemaId && g4.type == "db")).reduce((p3, c4) => { - return { - ...p3, - ...p3[c4.schemaId] ? { - [c4.schemaId]: { - uniques: c4.unique == "true" ? [...p3[c4.schemaId].uniques, c4.name] : p3[c4.schemaId].uniques, - cols: [...p3[c4.schemaId].cols, c4.name], - rows: [] - } - } : { - [c4.schemaId]: { - uniques: c4.unique == "true" ? [c4.name] : [], - cols: [c4.name], - rows: [] - } - } - }; - }, {}); +base.FunctionExpression = base.ArrowFunctionExpression = base.FunctionDeclaration; +base.SequenceExpression = function(node, st, c4) { + for (var i4 = 0, list = node.expressions; i4 < list.length; i4 += 1) { + var expr = list[i4]; + c4(expr, st, "Expression"); + } }; -var defaultTablesForContext = (context) => { - if (context.type == "tag") { - return defaultTagTables; - } else if (context.type == "folder") { - return defaultFolderTables; +base.TemplateLiteral = function(node, st, c4) { + for (var i4 = 0, list = node.quasis; i4 < list.length; i4 += 1) { + var quasi = list[i4]; + c4(quasi, st); + } + for (var i$1 = 0, list$1 = node.expressions; i$1 < list$1.length; i$1 += 1) { + var expr = list$1[i$1]; + c4(expr, st, "Expression"); } - return defaultFolderTables; }; -var defaultFolderTables = { - m_schema: defaultFolderSchema, - m_fields: defaultFolderFields, - ...fieldsToTable( - defaultFolderFields.rows, - defaultFolderSchema.rows - ) +base.TemplateElement = ignore; +base.UnaryExpression = base.UpdateExpression = function(node, st, c4) { + c4(node.argument, st, "Expression"); }; -var defaultTagTables = { - m_schema: defaultTagSchema, - m_fields: defaultTagFields, - ...fieldsToTable( - defaultTagFields.rows, - defaultTagSchema.rows - ) +base.BinaryExpression = base.LogicalExpression = function(node, st, c4) { + c4(node.left, st, "Expression"); + c4(node.right, st, "Expression"); }; - -// src/utils/array.ts -var insert = (arr, index, newItem) => index <= 0 ? [ - newItem, - ...arr -] : [ - ...arr.slice(0, index), - newItem, - ...arr.slice(index) -]; -var uniq = (a5) => [...new Set(a5)]; -var uniqCaseInsensitive = (a5) => [ - ...new Map(a5.map((s5) => [s5.toLowerCase(), s5])).values() -]; -var uniqueNameFromString = (name, cols) => { - let newName = name; - if (cols.includes(newName)) { - let append = 1; - while (cols.includes(newName)) { - newName = name + append.toString(); - append += 1; +base.AssignmentExpression = base.AssignmentPattern = function(node, st, c4) { + c4(node.left, st, "Pattern"); + c4(node.right, st, "Expression"); +}; +base.ConditionalExpression = function(node, st, c4) { + c4(node.test, st, "Expression"); + c4(node.consequent, st, "Expression"); + c4(node.alternate, st, "Expression"); +}; +base.NewExpression = base.CallExpression = function(node, st, c4) { + c4(node.callee, st, "Expression"); + if (node.arguments) { + for (var i4 = 0, list = node.arguments; i4 < list.length; i4 += 1) { + var arg = list[i4]; + c4(arg, st, "Expression"); } } - return newName; }; -var onlyUniqueProp = (prop) => (value, index, self2) => { - return self2.findIndex((v3) => value[prop] == v3[prop]) === index; +base.MemberExpression = function(node, st, c4) { + c4(node.object, st, "Expression"); + if (node.computed) { + c4(node.property, st, "Expression"); + } }; -var onlyUniquePropCaseInsensitive = (prop) => (value, index, self2) => { - return self2.findIndex( - (v3) => value[prop].toLowerCase() == v3[prop].toLowerCase() - ) === index; +base.ExportNamedDeclaration = base.ExportDefaultDeclaration = function(node, st, c4) { + if (node.declaration) { + c4(node.declaration, st, node.type === "ExportNamedDeclaration" || node.declaration.id ? "Statement" : "Expression"); + } + if (node.source) { + c4(node.source, st, "Expression"); + } }; - -// src/utils/sanitize.ts -var sanitizeTableName = (name) => { - return name == null ? void 0 : name.replace(/[^a-z0-9+]+/gi, ""); +base.ExportAllDeclaration = function(node, st, c4) { + if (node.exported) { + c4(node.exported, st); + } + c4(node.source, st, "Expression"); }; -var sanitizeColumnName = (name) => { - if ((name == null ? void 0 : name.charAt(0)) == "_") { - return sanitizeColumnName(name.substring(1)); +base.ImportDeclaration = function(node, st, c4) { + for (var i4 = 0, list = node.specifiers; i4 < list.length; i4 += 1) { + var spec = list[i4]; + c4(spec, st); } - return name == null ? void 0 : name.replace(/"/g, ``); + c4(node.source, st, "Expression"); }; -var sanitizeSQLStatement = (name) => { - return name == null ? void 0 : name.replace(/'/g, `''`); +base.ImportExpression = function(node, st, c4) { + c4(node.source, st, "Expression"); }; - -// src/utils/serializer.ts -var serializeSpace = (space) => ({ ...space, def: JSON.stringify(space.def) }); -var serializeMultiString = (value) => value.join(","); -var serializeMultiDisplayString = (value) => value.join(", "); -var serializeSQLValues = (value) => value.join(", "); -var serializeSQLStatements = (value) => value.join("; "); -var serializeSQLFieldNames = (value) => value.join(","); - -// src/utils/tree.ts -var import_obsidian = require("obsidian"); -var nodeIsAncestorOfTarget = (node, target) => { - var _a2; - if (!node.item || !node.item.isFolder) - return false; - return (_a2 = target.item) == null ? void 0 : _a2.path.contains(node.item.path + "/"); +base.ImportSpecifier = base.ImportDefaultSpecifier = base.ImportNamespaceSpecifier = base.Identifier = base.PrivateIdentifier = base.Literal = ignore; +base.TaggedTemplateExpression = function(node, st, c4) { + c4(node.tag, st, "Expression"); + c4(node.quasi, st, "Expression"); }; -var excludeVaultItemPredicate = (settings) => (f4, index, folder) => !(f4.folder != "true" && settings.hiddenExtensions.find( - (e4) => f4.path.endsWith(e4) -)) && !settings.hiddenFiles.find((e4) => e4 == f4.path) && (!settings.enableFolderNote || !settings.folderNoteInsideFolder && !folder.some((g4) => g4.path + ".md" == f4.path) || settings.folderNoteInsideFolder && !(f4.parent + "/" + folderPathToString(f4.parent) + ".md" == f4.path)); -var excludeFilePredicate = (plugin) => (f4, index, folder) => !(f4 instanceof import_obsidian.TFile && plugin.settings.hiddenExtensions.find((e4) => f4.path.endsWith(e4))) && !plugin.settings.hiddenFiles.find((e4) => e4 == f4.path) && (!plugin.settings.enableFolderNote || !plugin.settings.folderNoteInsideFolder && !folder.some((g4) => g4.path + ".md" == f4.path) || plugin.settings.folderNoteInsideFolder && !(f4.parent.path + "/" + f4.parent.name + ".md" == f4.path)); -var folderChildren = (plugin, f4, exclusionList) => { - var _a2, _b2; - return (_b2 = (_a2 = f4 == null ? void 0 : f4.children) == null ? void 0 : _a2.filter(excludeFilePredicate(plugin))) != null ? _b2 : []; +base.ClassDeclaration = base.ClassExpression = function(node, st, c4) { + return c4(node, st, "Class"); }; -var compareByField = (field, dir) => (_a2, _b2) => { - const a5 = dir ? _a2 : _b2; - const b4 = dir ? _b2 : _a2; - if (a5[field] < b4[field]) { - return -1; +base.Class = function(node, st, c4) { + if (node.id) { + c4(node.id, st, "Pattern"); } - if (a5[field] > b4[field]) { - return 1; + if (node.superClass) { + c4(node.superClass, st, "Expression"); } - return 0; + c4(node.body, st); }; -var compareByFieldCaseInsensitive = (field, dir) => (_a2, _b2) => { - const a5 = dir ? _a2 : _b2; - const b4 = dir ? _b2 : _a2; - if (a5[field].toLowerCase() < b4[field].toLowerCase()) { - return -1; - } - if (a5[field].toLowerCase() > b4[field].toLowerCase()) { - return 1; +base.ClassBody = function(node, st, c4) { + for (var i4 = 0, list = node.body; i4 < list.length; i4 += 1) { + var elt = list[i4]; + c4(elt, st); } - return 0; }; -var internalPluginLoaded = (pluginName, app2) => { - var _a2; - return (_a2 = app2.internalPlugins.plugins[pluginName]) == null ? void 0 : _a2._loaded; +base.MethodDefinition = base.PropertyDefinition = base.Property = function(node, st, c4) { + if (node.computed) { + c4(node.key, st, "Expression"); + } + if (node.value) { + c4(node.value, st, "Expression"); + } }; -function selectElementContents(el) { - if (!el) - return; - var range = document.createRange(); - range.selectNodeContents(el); - var sel = window.getSelection(); - sel.removeAllRanges(); - sel.addRange(range); -} -// src/utils/db/db.ts -var import_obsidian2 = require("obsidian"); -var getDBFile = async (path, isRemote) => { - if (isRemote) { - return fetch(path).then((res) => res.arrayBuffer()); +// node_modules/astring/dist/astring.mjs +var { stringify } = JSON; +if (!String.prototype.repeat) { + throw new Error( + "String.prototype.repeat is undefined, see https://github.com/davidbonnet/astring#installation" + ); +} +if (!String.prototype.endsWith) { + throw new Error( + "String.prototype.endsWith is undefined, see https://github.com/davidbonnet/astring#installation" + ); +} +var OPERATOR_PRECEDENCE = { + "||": 3, + "&&": 4, + "|": 5, + "??": 5, + "^": 6, + "&": 7, + "==": 8, + "!=": 8, + "===": 8, + "!==": 8, + "<": 9, + ">": 9, + "<=": 9, + ">=": 9, + in: 9, + instanceof: 9, + "<<": 10, + ">>": 10, + ">>>": 10, + "+": 11, + "-": 11, + "*": 12, + "%": 12, + "/": 12, + "**": 13 +}; +var NEEDS_PARENTHESES = 17; +var EXPRESSIONS_PRECEDENCE = { + ArrayExpression: 20, + TaggedTemplateExpression: 20, + ThisExpression: 20, + Identifier: 20, + PrivateIdentifier: 20, + Literal: 18, + TemplateLiteral: 20, + Super: 20, + SequenceExpression: 20, + MemberExpression: 19, + ChainExpression: 19, + CallExpression: 19, + NewExpression: 19, + ArrowFunctionExpression: NEEDS_PARENTHESES, + ClassExpression: NEEDS_PARENTHESES, + FunctionExpression: NEEDS_PARENTHESES, + ObjectExpression: NEEDS_PARENTHESES, + UpdateExpression: 16, + UnaryExpression: 15, + AwaitExpression: 15, + BinaryExpression: 14, + LogicalExpression: 13, + ConditionalExpression: 4, + AssignmentExpression: 3, + YieldExpression: 2, + RestElement: 1 +}; +function formatSequence(state, nodes) { + const { generator } = state; + state.write("("); + if (nodes != null && nodes.length > 0) { + generator[nodes[0].type](nodes[0], state); + const { length } = nodes; + for (let i4 = 1; i4 < length; i4++) { + const param = nodes[i4]; + state.write(", "); + generator[param.type](param, state); + } + } + state.write(")"); +} +function expressionNeedsParenthesis(state, node, parentNode, isRightHand) { + const nodePrecedence = state.expressionsPrecedence[node.type]; + if (nodePrecedence === NEEDS_PARENTHESES) { + return true; } - if (!await app.vault.adapter.exists((0, import_obsidian2.normalizePath)(path))) { - return null; + const parentNodePrecedence = state.expressionsPrecedence[parentNode.type]; + if (nodePrecedence !== parentNodePrecedence) { + return !isRightHand && nodePrecedence === 15 && parentNodePrecedence === 14 && parentNode.operator === "**" || nodePrecedence < parentNodePrecedence; } - const file = await app.vault.adapter.readBinary( - (0, import_obsidian2.normalizePath)(path) - ); - return file; -}; -var getDB = async (sqlJS, path, isRemote) => { - const buf = await getDBFile(path, isRemote); - if (buf) { - return new sqlJS.Database(new Uint8Array(buf)); + if (nodePrecedence !== 13 && nodePrecedence !== 14) { + return false; } - return new sqlJS.Database(); -}; -var saveDBFile = async (path, binary) => { - const file = app.vault.adapter.writeBinary( - (0, import_obsidian2.normalizePath)(path), - binary - ); - return file; -}; -var dbResultsToDBTables = (res) => { - return res.reduce( - (p3, c4, i4) => [ - ...p3, - { - cols: c4.columns, - rows: c4 ? c4.values.map( - (r3) => c4.columns.reduce( - (prev, curr, index) => ({ ...prev, [curr]: r3[index] }), - {} - ) - ) : [] + if (node.operator === "**" && parentNode.operator === "**") { + return !isRightHand; + } + if (isRightHand) { + return OPERATOR_PRECEDENCE[node.operator] <= OPERATOR_PRECEDENCE[parentNode.operator]; + } + return OPERATOR_PRECEDENCE[node.operator] < OPERATOR_PRECEDENCE[parentNode.operator]; +} +function formatExpression(state, node, parentNode, isRightHand) { + const { generator } = state; + if (expressionNeedsParenthesis(state, node, parentNode, isRightHand)) { + state.write("("); + generator[node.type](node, state); + state.write(")"); + } else { + generator[node.type](node, state); + } +} +function reindent(state, text2, indent, lineEnd) { + const lines = text2.split("\n"); + const end = lines.length - 1; + state.write(lines[0].trim()); + if (end > 0) { + state.write(lineEnd); + for (let i4 = 1; i4 < end; i4++) { + state.write(indent + lines[i4].trim() + lineEnd); + } + state.write(indent + lines[end].trim()); + } +} +function formatComments(state, comments, indent, lineEnd) { + const { length } = comments; + for (let i4 = 0; i4 < length; i4++) { + const comment = comments[i4]; + state.write(indent); + if (comment.type[0] === "L") { + state.write("// " + comment.value.trim() + "\n", comment); + } else { + state.write("/*"); + reindent(state, comment.value, indent, lineEnd); + state.write("*/" + lineEnd); + } + } +} +function hasCallExpression(node) { + let currentNode = node; + while (currentNode != null) { + const { type } = currentNode; + if (type[0] === "C" && type[1] === "a") { + return true; + } else if (type[0] === "M" && type[1] === "e" && type[2] === "m") { + currentNode = currentNode.object; + } else { + return false; + } + } +} +function formatVariableDeclaration(state, node) { + const { generator } = state; + const { declarations } = node; + state.write(node.kind + " "); + const { length } = declarations; + if (length > 0) { + generator.VariableDeclarator(declarations[0], state); + for (let i4 = 1; i4 < length; i4++) { + state.write(", "); + generator.VariableDeclarator(declarations[i4], state); + } + } +} +var ForInStatement; +var FunctionDeclaration; +var RestElement; +var BinaryExpression; +var ArrayExpression; +var BlockStatement; +var GENERATOR = { + Program(node, state) { + const indent = state.indent.repeat(state.indentLevel); + const { lineEnd, writeComments } = state; + if (writeComments && node.comments != null) { + formatComments(state, node.comments, indent, lineEnd); + } + const statements = node.body; + const { length } = statements; + for (let i4 = 0; i4 < length; i4++) { + const statement = statements[i4]; + if (writeComments && statement.comments != null) { + formatComments(state, statement.comments, indent, lineEnd); } - ], - [] - ); -}; -var selectDB = (db, table, condition, fields) => { - const fieldsStr = fields != null ? fields : "*"; - const sqlstr = condition ? `SELECT ${fieldsStr} FROM "${table}" WHERE ${condition};` : `SELECT ${fieldsStr} FROM ${table};`; - let tables; - try { - tables = dbResultsToDBTables(db.exec(sqlstr)); - } catch (e4) { - return null; + state.write(indent); + this[statement.type](statement, state); + state.write(lineEnd); + } + if (writeComments && node.trailingComments != null) { + formatComments(state, node.trailingComments, indent, lineEnd); + } + }, + BlockStatement: BlockStatement = function(node, state) { + const indent = state.indent.repeat(state.indentLevel++); + const { lineEnd, writeComments } = state; + const statementIndent = indent + state.indent; + state.write("{"); + const statements = node.body; + if (statements != null && statements.length > 0) { + state.write(lineEnd); + if (writeComments && node.comments != null) { + formatComments(state, node.comments, statementIndent, lineEnd); + } + const { length } = statements; + for (let i4 = 0; i4 < length; i4++) { + const statement = statements[i4]; + if (writeComments && statement.comments != null) { + formatComments(state, statement.comments, statementIndent, lineEnd); + } + state.write(statementIndent); + this[statement.type](statement, state); + state.write(lineEnd); + } + state.write(indent); + } else { + if (writeComments && node.comments != null) { + state.write(lineEnd); + formatComments(state, node.comments, statementIndent, lineEnd); + state.write(indent); + } + } + if (writeComments && node.trailingComments != null) { + formatComments(state, node.trailingComments, statementIndent, lineEnd); + } + state.write("}"); + state.indentLevel--; + }, + ClassBody: BlockStatement, + StaticBlock(node, state) { + state.write("static "); + this.BlockStatement(node, state); + }, + EmptyStatement(node, state) { + state.write(";"); + }, + ExpressionStatement(node, state) { + const precedence = state.expressionsPrecedence[node.expression.type]; + if (precedence === NEEDS_PARENTHESES || precedence === 3 && node.expression.left.type[0] === "O") { + state.write("("); + this[node.expression.type](node.expression, state); + state.write(")"); + } else { + this[node.expression.type](node.expression, state); + } + state.write(";"); + }, + IfStatement(node, state) { + state.write("if ("); + this[node.test.type](node.test, state); + state.write(") "); + this[node.consequent.type](node.consequent, state); + if (node.alternate != null) { + state.write(" else "); + this[node.alternate.type](node.alternate, state); + } + }, + LabeledStatement(node, state) { + this[node.label.type](node.label, state); + state.write(": "); + this[node.body.type](node.body, state); + }, + BreakStatement(node, state) { + state.write("break"); + if (node.label != null) { + state.write(" "); + this[node.label.type](node.label, state); + } + state.write(";"); + }, + ContinueStatement(node, state) { + state.write("continue"); + if (node.label != null) { + state.write(" "); + this[node.label.type](node.label, state); + } + state.write(";"); + }, + WithStatement(node, state) { + state.write("with ("); + this[node.object.type](node.object, state); + state.write(") "); + this[node.body.type](node.body, state); + }, + SwitchStatement(node, state) { + const indent = state.indent.repeat(state.indentLevel++); + const { lineEnd, writeComments } = state; + state.indentLevel++; + const caseIndent = indent + state.indent; + const statementIndent = caseIndent + state.indent; + state.write("switch ("); + this[node.discriminant.type](node.discriminant, state); + state.write(") {" + lineEnd); + const { cases: occurences } = node; + const { length: occurencesCount } = occurences; + for (let i4 = 0; i4 < occurencesCount; i4++) { + const occurence = occurences[i4]; + if (writeComments && occurence.comments != null) { + formatComments(state, occurence.comments, caseIndent, lineEnd); + } + if (occurence.test) { + state.write(caseIndent + "case "); + this[occurence.test.type](occurence.test, state); + state.write(":" + lineEnd); + } else { + state.write(caseIndent + "default:" + lineEnd); + } + const { consequent } = occurence; + const { length: consequentCount } = consequent; + for (let i5 = 0; i5 < consequentCount; i5++) { + const statement = consequent[i5]; + if (writeComments && statement.comments != null) { + formatComments(state, statement.comments, statementIndent, lineEnd); + } + state.write(statementIndent); + this[statement.type](statement, state); + state.write(lineEnd); + } + } + state.indentLevel -= 2; + state.write(indent + "}"); + }, + ReturnStatement(node, state) { + state.write("return"); + if (node.argument) { + state.write(" "); + this[node.argument.type](node.argument, state); + } + state.write(";"); + }, + ThrowStatement(node, state) { + state.write("throw "); + this[node.argument.type](node.argument, state); + state.write(";"); + }, + TryStatement(node, state) { + state.write("try "); + this[node.block.type](node.block, state); + if (node.handler) { + const { handler } = node; + if (handler.param == null) { + state.write(" catch "); + } else { + state.write(" catch ("); + this[handler.param.type](handler.param, state); + state.write(") "); + } + this[handler.body.type](handler.body, state); + } + if (node.finalizer) { + state.write(" finally "); + this[node.finalizer.type](node.finalizer, state); + } + }, + WhileStatement(node, state) { + state.write("while ("); + this[node.test.type](node.test, state); + state.write(") "); + this[node.body.type](node.body, state); + }, + DoWhileStatement(node, state) { + state.write("do "); + this[node.body.type](node.body, state); + state.write(" while ("); + this[node.test.type](node.test, state); + state.write(");"); + }, + ForStatement(node, state) { + state.write("for ("); + if (node.init != null) { + const { init } = node; + if (init.type[0] === "V") { + formatVariableDeclaration(state, init); + } else { + this[init.type](init, state); + } + } + state.write("; "); + if (node.test) { + this[node.test.type](node.test, state); + } + state.write("; "); + if (node.update) { + this[node.update.type](node.update, state); + } + state.write(") "); + this[node.body.type](node.body, state); + }, + ForInStatement: ForInStatement = function(node, state) { + state.write(`for ${node.await ? "await " : ""}(`); + const { left } = node; + if (left.type[0] === "V") { + formatVariableDeclaration(state, left); + } else { + this[left.type](left, state); + } + state.write(node.type[3] === "I" ? " in " : " of "); + this[node.right.type](node.right, state); + state.write(") "); + this[node.body.type](node.body, state); + }, + ForOfStatement: ForInStatement, + DebuggerStatement(node, state) { + state.write("debugger;", node); + }, + FunctionDeclaration: FunctionDeclaration = function(node, state) { + state.write( + (node.async ? "async " : "") + (node.generator ? "function* " : "function ") + (node.id ? node.id.name : ""), + node + ); + formatSequence(state, node.params); + state.write(" "); + this[node.body.type](node.body, state); + }, + FunctionExpression: FunctionDeclaration, + VariableDeclaration(node, state) { + formatVariableDeclaration(state, node); + state.write(";"); + }, + VariableDeclarator(node, state) { + this[node.id.type](node.id, state); + if (node.init != null) { + state.write(" = "); + this[node.init.type](node.init, state); + } + }, + ClassDeclaration(node, state) { + state.write("class " + (node.id ? `${node.id.name} ` : ""), node); + if (node.superClass) { + state.write("extends "); + const { superClass } = node; + const { type } = superClass; + const precedence = state.expressionsPrecedence[type]; + if ((type[0] !== "C" || type[1] !== "l" || type[5] !== "E") && (precedence === NEEDS_PARENTHESES || precedence < state.expressionsPrecedence.ClassExpression)) { + state.write("("); + this[node.superClass.type](superClass, state); + state.write(")"); + } else { + this[superClass.type](superClass, state); + } + state.write(" "); + } + this.ClassBody(node.body, state); + }, + ImportDeclaration(node, state) { + state.write("import "); + const { specifiers } = node; + const { length } = specifiers; + let i4 = 0; + if (length > 0) { + for (; i4 < length; ) { + if (i4 > 0) { + state.write(", "); + } + const specifier = specifiers[i4]; + const type = specifier.type[6]; + if (type === "D") { + state.write(specifier.local.name, specifier); + i4++; + } else if (type === "N") { + state.write("* as " + specifier.local.name, specifier); + i4++; + } else { + break; + } + } + if (i4 < length) { + state.write("{"); + for (; ; ) { + const specifier = specifiers[i4]; + const { name } = specifier.imported; + state.write(name, specifier); + if (name !== specifier.local.name) { + state.write(" as " + specifier.local.name); + } + if (++i4 < length) { + state.write(", "); + } else { + break; + } + } + state.write("}"); + } + state.write(" from "); + } + this.Literal(node.source, state); + state.write(";"); + }, + ImportExpression(node, state) { + state.write("import("); + this[node.source.type](node.source, state); + state.write(")"); + }, + ExportDefaultDeclaration(node, state) { + state.write("export default "); + this[node.declaration.type](node.declaration, state); + if (state.expressionsPrecedence[node.declaration.type] != null && node.declaration.type[0] !== "F") { + state.write(";"); + } + }, + ExportNamedDeclaration(node, state) { + state.write("export "); + if (node.declaration) { + this[node.declaration.type](node.declaration, state); + } else { + state.write("{"); + const { specifiers } = node, { length } = specifiers; + if (length > 0) { + for (let i4 = 0; ; ) { + const specifier = specifiers[i4]; + const { name } = specifier.local; + state.write(name, specifier); + if (name !== specifier.exported.name) { + state.write(" as " + specifier.exported.name); + } + if (++i4 < length) { + state.write(", "); + } else { + break; + } + } + } + state.write("}"); + if (node.source) { + state.write(" from "); + this.Literal(node.source, state); + } + state.write(";"); + } + }, + ExportAllDeclaration(node, state) { + if (node.exported != null) { + state.write("export * as " + node.exported.name + " from "); + } else { + state.write("export * from "); + } + this.Literal(node.source, state); + state.write(";"); + }, + MethodDefinition(node, state) { + if (node.static) { + state.write("static "); + } + const kind = node.kind[0]; + if (kind === "g" || kind === "s") { + state.write(node.kind + " "); + } + if (node.value.async) { + state.write("async "); + } + if (node.value.generator) { + state.write("*"); + } + if (node.computed) { + state.write("["); + this[node.key.type](node.key, state); + state.write("]"); + } else { + this[node.key.type](node.key, state); + } + formatSequence(state, node.value.params); + state.write(" "); + this[node.value.body.type](node.value.body, state); + }, + ClassExpression(node, state) { + this.ClassDeclaration(node, state); + }, + ArrowFunctionExpression(node, state) { + state.write(node.async ? "async " : "", node); + const { params } = node; + if (params != null) { + if (params.length === 1 && params[0].type[0] === "I") { + state.write(params[0].name, params[0]); + } else { + formatSequence(state, node.params); + } + } + state.write(" => "); + if (node.body.type[0] === "O") { + state.write("("); + this.ObjectExpression(node.body, state); + state.write(")"); + } else { + this[node.body.type](node.body, state); + } + }, + ThisExpression(node, state) { + state.write("this", node); + }, + Super(node, state) { + state.write("super", node); + }, + RestElement: RestElement = function(node, state) { + state.write("..."); + this[node.argument.type](node.argument, state); + }, + SpreadElement: RestElement, + YieldExpression(node, state) { + state.write(node.delegate ? "yield*" : "yield"); + if (node.argument) { + state.write(" "); + this[node.argument.type](node.argument, state); + } + }, + AwaitExpression(node, state) { + state.write("await ", node); + formatExpression(state, node.argument, node); + }, + TemplateLiteral(node, state) { + const { quasis, expressions } = node; + state.write("`"); + const { length } = expressions; + for (let i4 = 0; i4 < length; i4++) { + const expression = expressions[i4]; + const quasi2 = quasis[i4]; + state.write(quasi2.value.raw, quasi2); + state.write("${"); + this[expression.type](expression, state); + state.write("}"); + } + const quasi = quasis[quasis.length - 1]; + state.write(quasi.value.raw, quasi); + state.write("`"); + }, + TemplateElement(node, state) { + state.write(node.value.raw, node); + }, + TaggedTemplateExpression(node, state) { + formatExpression(state, node.tag, node); + this[node.quasi.type](node.quasi, state); + }, + ArrayExpression: ArrayExpression = function(node, state) { + state.write("["); + if (node.elements.length > 0) { + const { elements } = node, { length } = elements; + for (let i4 = 0; ; ) { + const element = elements[i4]; + if (element != null) { + this[element.type](element, state); + } + if (++i4 < length) { + state.write(", "); + } else { + if (element == null) { + state.write(", "); + } + break; + } + } + } + state.write("]"); + }, + ArrayPattern: ArrayExpression, + ObjectExpression(node, state) { + const indent = state.indent.repeat(state.indentLevel++); + const { lineEnd, writeComments } = state; + const propertyIndent = indent + state.indent; + state.write("{"); + if (node.properties.length > 0) { + state.write(lineEnd); + if (writeComments && node.comments != null) { + formatComments(state, node.comments, propertyIndent, lineEnd); + } + const comma = "," + lineEnd; + const { properties: properties2 } = node, { length } = properties2; + for (let i4 = 0; ; ) { + const property = properties2[i4]; + if (writeComments && property.comments != null) { + formatComments(state, property.comments, propertyIndent, lineEnd); + } + state.write(propertyIndent); + this[property.type](property, state); + if (++i4 < length) { + state.write(comma); + } else { + break; + } + } + state.write(lineEnd); + if (writeComments && node.trailingComments != null) { + formatComments(state, node.trailingComments, propertyIndent, lineEnd); + } + state.write(indent + "}"); + } else if (writeComments) { + if (node.comments != null) { + state.write(lineEnd); + formatComments(state, node.comments, propertyIndent, lineEnd); + if (node.trailingComments != null) { + formatComments(state, node.trailingComments, propertyIndent, lineEnd); + } + state.write(indent + "}"); + } else if (node.trailingComments != null) { + state.write(lineEnd); + formatComments(state, node.trailingComments, propertyIndent, lineEnd); + state.write(indent + "}"); + } else { + state.write("}"); + } + } else { + state.write("}"); + } + state.indentLevel--; + }, + Property(node, state) { + if (node.method || node.kind[0] !== "i") { + this.MethodDefinition(node, state); + } else { + if (!node.shorthand) { + if (node.computed) { + state.write("["); + this[node.key.type](node.key, state); + state.write("]"); + } else { + this[node.key.type](node.key, state); + } + state.write(": "); + } + this[node.value.type](node.value, state); + } + }, + PropertyDefinition(node, state) { + if (node.static) { + state.write("static "); + } + if (node.computed) { + state.write("["); + } + this[node.key.type](node.key, state); + if (node.computed) { + state.write("]"); + } + if (node.value == null) { + if (node.key.type[0] !== "F") { + state.write(";"); + } + return; + } + state.write(" = "); + this[node.value.type](node.value, state); + state.write(";"); + }, + ObjectPattern(node, state) { + state.write("{"); + if (node.properties.length > 0) { + const { properties: properties2 } = node, { length } = properties2; + for (let i4 = 0; ; ) { + this[properties2[i4].type](properties2[i4], state); + if (++i4 < length) { + state.write(", "); + } else { + break; + } + } + } + state.write("}"); + }, + SequenceExpression(node, state) { + formatSequence(state, node.expressions); + }, + UnaryExpression(node, state) { + if (node.prefix) { + const { + operator, + argument, + argument: { type } + } = node; + state.write(operator); + const needsParentheses = expressionNeedsParenthesis(state, argument, node); + if (!needsParentheses && (operator.length > 1 || type[0] === "U" && (type[1] === "n" || type[1] === "p") && argument.prefix && argument.operator[0] === operator && (operator === "+" || operator === "-"))) { + state.write(" "); + } + if (needsParentheses) { + state.write(operator.length > 1 ? " (" : "("); + this[type](argument, state); + state.write(")"); + } else { + this[type](argument, state); + } + } else { + this[node.argument.type](node.argument, state); + state.write(node.operator); + } + }, + UpdateExpression(node, state) { + if (node.prefix) { + state.write(node.operator); + this[node.argument.type](node.argument, state); + } else { + this[node.argument.type](node.argument, state); + state.write(node.operator); + } + }, + AssignmentExpression(node, state) { + this[node.left.type](node.left, state); + state.write(" " + node.operator + " "); + this[node.right.type](node.right, state); + }, + AssignmentPattern(node, state) { + this[node.left.type](node.left, state); + state.write(" = "); + this[node.right.type](node.right, state); + }, + BinaryExpression: BinaryExpression = function(node, state) { + const isIn = node.operator === "in"; + if (isIn) { + state.write("("); + } + formatExpression(state, node.left, node, false); + state.write(" " + node.operator + " "); + formatExpression(state, node.right, node, true); + if (isIn) { + state.write(")"); + } + }, + LogicalExpression: BinaryExpression, + ConditionalExpression(node, state) { + const { test } = node; + const precedence = state.expressionsPrecedence[test.type]; + if (precedence === NEEDS_PARENTHESES || precedence <= state.expressionsPrecedence.ConditionalExpression) { + state.write("("); + this[test.type](test, state); + state.write(")"); + } else { + this[test.type](test, state); + } + state.write(" ? "); + this[node.consequent.type](node.consequent, state); + state.write(" : "); + this[node.alternate.type](node.alternate, state); + }, + NewExpression(node, state) { + state.write("new "); + const precedence = state.expressionsPrecedence[node.callee.type]; + if (precedence === NEEDS_PARENTHESES || precedence < state.expressionsPrecedence.CallExpression || hasCallExpression(node.callee)) { + state.write("("); + this[node.callee.type](node.callee, state); + state.write(")"); + } else { + this[node.callee.type](node.callee, state); + } + formatSequence(state, node["arguments"]); + }, + CallExpression(node, state) { + const precedence = state.expressionsPrecedence[node.callee.type]; + if (precedence === NEEDS_PARENTHESES || precedence < state.expressionsPrecedence.CallExpression) { + state.write("("); + this[node.callee.type](node.callee, state); + state.write(")"); + } else { + this[node.callee.type](node.callee, state); + } + if (node.optional) { + state.write("?."); + } + formatSequence(state, node["arguments"]); + }, + ChainExpression(node, state) { + this[node.expression.type](node.expression, state); + }, + MemberExpression(node, state) { + const precedence = state.expressionsPrecedence[node.object.type]; + if (precedence === NEEDS_PARENTHESES || precedence < state.expressionsPrecedence.MemberExpression) { + state.write("("); + this[node.object.type](node.object, state); + state.write(")"); + } else { + this[node.object.type](node.object, state); + } + if (node.computed) { + if (node.optional) { + state.write("?."); + } + state.write("["); + this[node.property.type](node.property, state); + state.write("]"); + } else { + if (node.optional) { + state.write("?."); + } else { + state.write("."); + } + this[node.property.type](node.property, state); + } + }, + MetaProperty(node, state) { + state.write(node.meta.name + "." + node.property.name, node); + }, + Identifier(node, state) { + state.write(node.name, node); + }, + PrivateIdentifier(node, state) { + state.write(`#${node.name}`, node); + }, + Literal(node, state) { + if (node.raw != null) { + state.write(node.raw, node); + } else if (node.regex != null) { + this.RegExpLiteral(node, state); + } else if (node.bigint != null) { + state.write(node.bigint + "n", node); + } else { + state.write(stringify(node.value), node); + } + }, + RegExpLiteral(node, state) { + const { regex } = node; + state.write(`/${regex.pattern}/${regex.flags}`, node); } - if (tables.length == 1) - return tables[0]; - return null; }; -var deleteFromDB = (db, table, condition) => { - const sqlstr = `DELETE FROM "${table}" WHERE ${condition};`; - try { - db.exec(sqlstr); - } catch (e4) { - console.log(e4); +var EMPTY_OBJECT = {}; +var State = class { + constructor(options) { + const setup = options == null ? EMPTY_OBJECT : options; + this.output = ""; + if (setup.output != null) { + this.output = setup.output; + this.write = this.writeToStream; + } else { + this.output = ""; + } + this.generator = setup.generator != null ? setup.generator : GENERATOR; + this.expressionsPrecedence = setup.expressionsPrecedence != null ? setup.expressionsPrecedence : EXPRESSIONS_PRECEDENCE; + this.indent = setup.indent != null ? setup.indent : " "; + this.lineEnd = setup.lineEnd != null ? setup.lineEnd : "\n"; + this.indentLevel = setup.startingIndentLevel != null ? setup.startingIndentLevel : 0; + this.writeComments = setup.comments ? setup.comments : false; + if (setup.sourceMap != null) { + this.write = setup.output == null ? this.writeAndMap : this.writeToStreamAndMap; + this.sourceMap = setup.sourceMap; + this.line = 1; + this.column = 0; + this.lineEndSize = this.lineEnd.split("\n").length - 1; + this.mapping = { + original: null, + generated: this, + name: void 0, + source: setup.sourceMap.file || setup.sourceMap._file + }; + } } -}; -var dropTable = (db, table) => { - const sqlstr = `DROP TABLE IF EXISTS "${table}";`; - try { - db.exec(sqlstr); - } catch (e4) { - console.log(e4); + write(code) { + this.output += code; + } + writeToStream(code) { + this.output.write(code); + } + writeAndMap(code, node) { + this.output += code; + this.map(code, node); + } + writeToStreamAndMap(code, node) { + this.output.write(code); + this.map(code, node); + } + map(code, node) { + if (node != null) { + const { type } = node; + if (type[0] === "L" && type[2] === "n") { + this.column = 0; + this.line++; + return; + } + if (node.loc != null) { + const { mapping } = this; + mapping.original = node.loc.start; + mapping.name = node.name; + this.sourceMap.addMapping(mapping); + } + if (type[0] === "T" && type[8] === "E" || type[0] === "L" && type[1] === "i" && typeof node.value === "string") { + const { length: length2 } = code; + let { column, line } = this; + for (let i4 = 0; i4 < length2; i4++) { + if (code[i4] === "\n") { + column = 0; + line++; + } else { + column++; + } + } + this.column = column; + this.line = line; + return; + } + } + const { length } = code; + const { lineEnd } = this; + if (length > 0) { + if (this.lineEndSize > 0 && (lineEnd.length === 1 ? code[length - 1] === lineEnd : code.endsWith(lineEnd))) { + this.line += this.lineEndSize; + this.column = 0; + } else { + this.column += length; + } + } + } + toString() { + return this.output; } }; -var replaceDB = (db, tables) => { - const sqlstr = serializeSQLStatements(Object.keys(tables).map((t4) => { - const tableFields = tables[t4].cols; - const fieldQuery = serializeSQLFieldNames(uniq(tableFields).map((f4) => `'${sanitizeSQLStatement(f4)}' char`)); - const rowsQuery = tables[t4].rows.reduce((prev, curr) => { - return `${prev} REPLACE INTO "${t4}" VALUES (${serializeSQLValues(tableFields.map((c4) => { - var _a2; - return `'${(_a2 = sanitizeSQLStatement(curr == null ? void 0 : curr[c4])) != null ? _a2 : ""}'`; - }))});`; - }, ""); - const idxQuery = tables[t4].uniques.filter((f4) => f4).reduce((p3, c4) => { - return `${p3} CREATE UNIQUE INDEX IF NOT EXISTS idx_${t4}_${c4.replace( - /,/g, - "_" - )} ON ${t4}(${c4});`; - }, ""); - const insertQuery = `CREATE TABLE IF NOT EXISTS "${t4}" (${fieldQuery}); ${idxQuery} BEGIN TRANSACTION; ${rowsQuery} COMMIT;`; - return `DROP INDEX IF EXISTS idx_${t4}__id; DROP TABLE IF EXISTS "${t4}"; ${fieldQuery.length > 0 ? insertQuery : ""}`; - })); +function generate(node, options) { + const state = new State(options); + state.generator[node.type](node, state); + return state.output; +} + +// src/utils/frames/linker.ts +var preprocessCode = (code, oldName, newName) => { + let string; + let codeBlock = ensureString(code); + const isMultiLine = codeBlock.includes("\n"); + if (isMultiLine) { + const lines = codeBlock.split("\n").filter((line) => line.trim() !== ""); + lines[lines.length - 1] = `${lines[lines.length - 1].replace("return ", "")}`; + codeBlock = lines.join("\n"); + } try { - db.exec(sqlstr); + const ast = parse3(codeBlock, { ecmaVersion: 2020, locations: true }); + ancestor(ast, { + Identifier(node, ancestors) { + const parent = ancestors[ancestors.length - 2]; + if (parent.type !== "MemberExpression" || parent.object === node) { + if (node.name == oldName) { + node.name = newName; + } + } + } + }); + string = generate(ast).trimEnd(); } catch (e4) { console.log(e4); + string = `"error"`; } -}; -var saveDBToPath = async (plugin, path, tables) => { - const sqlJS = await plugin.sqlJS(); - let db = await getDB(sqlJS, path); - if (!db) { - db.close(); - return false; + if (isMultiLine) { + const lines = string.split("\n").filter((line) => line.trim() !== ""); + lines[lines.length - 1] = `return ${lines[lines.length - 1]}`; + string = lines.join("\n"); } - replaceDB(db, tables); - await saveDBFile(path, db.export().buffer); - db.close(); - return true; + return string; +}; +var linkNodes = (parent, schemaId, props2, flattenedTree, uniqueID) => { + const relinkProps = (oldParent, newParent2, props3, node) => { + var _a2, _b2, _c2; + return { + ...node, + parentId: node.parentId == oldParent ? newParent2 : node.parentId, + props: Object.keys((_a2 = node == null ? void 0 : node.props) != null ? _a2 : {}).reduce( + (p3, c4) => { + return { + ...p3, + [c4]: preprocessCode(node.props[c4], oldParent, newParent2) + }; + }, + node.props + ), + actions: Object.keys((_b2 = node == null ? void 0 : node.actions) != null ? _b2 : {}).reduce( + (p3, c4) => { + return { + ...p3, + [c4]: preprocessCode(node.actions[c4], oldParent, newParent2) + }; + }, + node.actions + ), + styles: Object.keys((_c2 = node == null ? void 0 : node.styles) != null ? _c2 : {}).reduce( + (p3, c4) => { + return { + ...p3, + [c4]: preprocessCode(node.styles[c4], oldParent, newParent2) + }; + }, + node.styles + ) + }; + }; + const assignIDs = (parent2, nodes) => { + const [newNodes, newID] = nodes.reduce((p3, c4, i4) => { + const [oldNodes, id2] = p3; + const newNodeID = c4.parentId ? c4.id + id2 : parent2.id; + const newNode = { + ...c4.parentId == "" ? parent2 : oldNodes[i4], + type: oldNodes[i4].type, + id: newNodeID + }; + const returnNodes = oldNodes.map((f4) => f4.id != c4.id ? relinkProps(c4.id, newNodeID, props2, f4) : relinkProps(c4.id, newNodeID, props2, newNode)); + return [returnNodes, id2 + 1]; + }, [nodes, uniqueID]); + return [newNodes, newID]; + }; + const newParent = schemaId != parent.id ? relinkProps(schemaId, parent.id, props2, parent) : parent; + return assignIDs(newParent, flattenedTree); +}; +var linkTreeNodes = (parent, uniqueID) => { + const relinkProps = (oldParent, newParent, treenode) => { + var _a2, _b2, _c2; + let children; + const node = treenode.node; + if (treenode.children) { + children = treenode.children.map((child) => relinkProps(oldParent, newParent, child)); + } + return { + ...treenode, + children, + node: { + ...treenode.node, + parentId: node.parentId == oldParent ? newParent : node.parentId, + props: Object.keys((_a2 = node == null ? void 0 : node.props) != null ? _a2 : {}).reduce( + (p3, c4) => { + return { + ...p3, + [c4]: preprocessCode(node.props[c4], oldParent, newParent) + }; + }, + node.props + ), + actions: Object.keys((_b2 = node == null ? void 0 : node.actions) != null ? _b2 : {}).reduce( + (p3, c4) => { + return { + ...p3, + [c4]: preprocessCode(node.actions[c4], oldParent, newParent) + }; + }, + node.actions + ), + styles: Object.keys((_c2 = node == null ? void 0 : node.styles) != null ? _c2 : {}).reduce( + (p3, c4) => { + return { + ...p3, + [c4]: preprocessCode(node.styles[c4], oldParent, newParent) + }; + }, + node.styles + ) + } + }; + }; + const assignIDs = (parent2, node, uniqueID2) => { + const assignIDToTree = (parent3, node2, id2) => { + const newNodeID = node2.node.parentId ? node2.id + id2 : parent3.id; + let newNode = { ...node2, node: { ...node2.node, id: newNodeID }, id: newNodeID }; + newNode = relinkProps(node2.id, newNodeID, newNode); + if (newNode.children) { + const [newChildren, newID] = newNode.children.reduce( + (acc, child, i4) => { + const [newChild, nextID] = assignIDToTree(newNode, child, id2 + i4 + 1); + acc[0].push(newChild); + return [acc[0], nextID]; + }, + [[], id2] + ); + newNode.children = newChildren; + id2 = newID; + } + return [newNode, id2 + 1]; + }; + return assignIDToTree(parent2, node, uniqueID2); + }; + return assignIDs(parent, parent, uniqueID); }; - -// src/utils/metadata/tags.ts -var import_obsidian3 = require("obsidian"); // src/utils/json.ts var safelyParseJSON = (json) => { @@ -15603,4503 +21145,6242 @@ var safelyParseJSON = (json) => { return parsed; }; -// src/utils/parser.tsx -var parseSortStrat = (str) => { - const [a5, b4] = str.split("_"); - return [a5, b4 == "asc"]; -}; -var parseMultiString = (str) => { - var _a2; - return (_a2 = str == null ? void 0 : str.match(/(\\.|[^,])+/g)) != null ? _a2 : []; -}; -var parseLinkString = (string) => { - if (!string) - return ""; - const match2 = /\[\[(.*?)\]\]/g.exec(string); - const stringValue = (match2 == null ? void 0 : match2.length) > 1 ? match2[1].substring(0, indexOfCharElseEOS("|", match2[1])) : string; - if (stringValue) - return stringValue; - return string; +// src/utils/frames/nodes.ts +var mdbSchemaToFrameSchema = (schema) => { + if (!schema) + return null; + return { + ...schema, + def: safelyParseJSON(schema.def) + }; }; -var parseLinkDisplayString = (string) => { - return filePathToString(parseLinkString(string)); +var frameSchemaToMDBSchema = (frameSchema) => { + return { + ...frameSchema, + def: JSON.stringify(frameSchema.def) + }; }; -var parseContextDefString = (str) => { - var _a2; - if (!str || str.length == 0) - return []; - if (str.charAt(0) == "#") { - return str.split("&").map((f4) => ({ - type: "tag", - value: f4 - })); - } - return (_a2 = safelyParseJSON(str)) != null ? _a2 : []; +var frameToNode = (frame) => { + return { + ...frame, + rank: parseInt(frame.rank), + contexts: safelyParseJSON(frame.contexts), + styles: safelyParseJSON(frame.styles), + actions: safelyParseJSON(frame.actions), + props: safelyParseJSON(frame.props), + types: nodeToTypes(frame.type) + }; }; -var parseSpace = (spaceRow) => { +var nodeToFrame = (node) => { + var _a2, _b2; + const { contexts, styles: styles2, props: props2, actions, ...otherProps } = node; return { - ...spaceRow, - def: parseSpaceDefString(spaceRow.def) + ...otherProps, + rank: (_b2 = (_a2 = node.rank) == null ? void 0 : _a2.toString()) != null ? _b2 : "0", + contexts: JSON.stringify(contexts), + styles: JSON.stringify(styles2), + actions: JSON.stringify(actions), + props: JSON.stringify(props2) }; }; -var parseSpaceDefString = (str) => { - var _a2; - if (!str || str.length == 0) - return { type: "focus", folder: "", filters: [] }; - if (str.charAt(0) != "{") { + +// src/utils/frames/ast.ts +var calculateEditorProps = (props2, treeNode) => { + if (props2.editMode == 0 || !props2.rootId) + return props2; + if (treeNode.node.id == props2.rootId) + return props2; + if (treeNode.isRef) + return { ...props2, dropMode: 0, dragMode: 0, resizeMode: 0, selectMode: 0 }; + if (props2.editMode == 2) { return { - folder: str, - type: "focus", - filters: [ - { - type: "any", - trueFalse: true, - filters: [ - { - type: "filemeta", - fType: "string", - field: "folder", - fn: "equals", - value: str - } - ] - } - ] + ...props2, + resizeMode: 1 /* ResizeSelected */, + dragMode: 2 /* DragSelected */ }; } - return (_a2 = safelyParseJSON(str)) != null ? _a2 : []; -}; - -// src/utils/metadata/tags.ts -var tagKeys = ["tag", "tags", "Tag", "Tags"]; -var tagToTagPath = (tag) => { - if (!tag) - return null; - let string = tag; - if (string.charAt(0) != "#") - string = "#" + string; - return string.replace(/\//g, "+"); -}; -var tagPathToTag = (string) => { - return filePathToString(string).replace(/\+/g, "/"); -}; -var loadTags = (plugin) => { - var _a2; - const folder = plugin.settings.tagContextFolder == "" ? app.vault.getRoot() : getAbstractFileAtPath( - app, - getFolderPathFromString(plugin.settings.tagContextFolder) - ); - return uniq([ - ...Object.keys(app.metadataCache.getTags()), - ...(_a2 = folder == null ? void 0 : folder.children.filter( - (f4) => f4 instanceof import_obsidian3.TFile && f4.extension == "mdb" && f4.name.charAt(0) == "#" - ).map((f4) => tagPathToTag(f4.name))) != null ? _a2 : [] - ]); -}; -var tagExists = (currentCache, findTag) => { - let currentTags = []; - if ((0, import_obsidian3.getAllTags)(currentCache)) { - currentTags = (0, import_obsidian3.getAllTags)(currentCache); - } - return currentTags.find((tag) => tag.toLowerCase() == findTag.toLowerCase()) ? true : false; -}; -var getAllFilesForTag = (tag) => { - let tagsCache = []; - (() => { - app.vault.getMarkdownFiles().forEach((tfile) => { - let currentCache; - if (app.metadataCache.getFileCache(tfile) !== null) { - currentCache = app.metadataCache.getFileCache(tfile); - } - let relativePath = tfile.path; - const hasTag = tagExists(currentCache, tag); - if (hasTag) { - tagsCache.push(relativePath); - } - }); - })(); - return tagsCache; -}; -var addTagToNote = (tag, tFile) => { - const newTag = validateName(tag); - editTagInFrontmatter("", newTag, tFile); -}; -var positionsForTag = (tag, file) => { - const currentCache = app.metadataCache.getFileCache(file); - if (currentCache.tags) { - const positions = currentCache.tags.filter((f4) => f4.tag == tag).map((f4) => f4.position).sort((a5, b4) => { - if (a5.start.offset < b4.start.offset) { - return -1; - } - if (a5.start.offset > b4.start.offset) { - return 1; - } - return 0; - }); - return positions; - } - return []; -}; -var removeTagFromFile = (tag, file) => { - const pos = positionsForTag(tag, file); - removeTagInFrontmatter(tag, file); - editTagInFileBody(tag, "", pos, file); -}; -var validateName = (tag) => { - return tag.trim(); + const firstLevelNode = treeNode.node.parentId == props2.rootId; + const columnChild = treeNode.editorProps.parentType == "column"; + const isColumn = treeNode.node.type == "column"; + const resizeMode = treeNode.node.type == "image" || isColumn ? 2 /* ResizeAlways */ : 0 /* ResizeNever */; + const dragMode = firstLevelNode && treeNode.node.type != "container" || columnChild && !isColumn || isColumn && treeNode.children.length == 0 ? 1 /* DragHandle */ : 0 /* DragNever */; + const dropMode = isColumn ? 3 /* DropModeColumnOnly */ : columnChild ? 2 /* DropModeRowOnly */ : firstLevelNode ? 1 /* DropModeRowColumn */ : 0; + return { + ...props2, + dragMode, + resizeMode, + dropMode + }; }; -var deleteTag = async (plugin, tag, subTags) => { - const files = getAllFilesForTag(tag).map((f4) => getAbstractFileAtPath(app, f4)).filter((f4) => f4 instanceof import_obsidian3.TFile); - files.forEach((file) => removeTagFromFile(tag, file)); - deleteTagContext(plugin, tag); - if (subTags) { - const tags = getAllSubtags(plugin, tag); - tags.forEach((tag2) => deleteTag(plugin, tag2, subTags)); +function replaceSubtree(tree, subtree) { + if (tree.id === subtree.id) { + return subtree; } -}; -var tagsFromDefString = (defStr) => parseContextDefString(defStr).filter((f4) => f4.type == "tag" && f4.value.length > 0).map((f4) => f4.value); -var updateTagsForDefString = (defStr, tags) => JSON.stringify([...parseContextDefString(defStr).filter((f4) => f4.type != "tag"), ...tags.map((f4) => ({ type: "tag", value: f4 }))]); -var addTag = async (plugin, tag) => { - const context = tagContextFromTag(plugin, tag); - await createDefaultDB(plugin, context); -}; -var renameTag = async (plugin, tag, toTag) => { - const tags = getAllSubtags(plugin, tag); - const newTag = validateName(toTag); - const files = getAllFilesForTag(tag); - for (const file of files) { - const tFile = getAbstractFileAtPath(app, file); - if (tFile instanceof import_obsidian3.TFile) { - const positions = positionsForTag(tag, tFile); - if (positions.length > 0) { - await editTagInFileBody(tag, newTag, positions, tFile); - } else { - await editTagInFrontmatter(tag, newTag, tFile); + if (tree.children) { + for (let i4 = 0; i4 < tree.children.length; i4++) { + const replacedChild = replaceSubtree(tree.children[i4], subtree); + if (replacedChild !== tree.children[i4]) { + tree.children[i4] = replacedChild; } } } - await renameTagContextFile(plugin, tag, toTag); - for (const subtag of tags) { - await renameTag(plugin, subtag, subtag.replace(tag, newTag)); + return tree; +} +var getFrameNodesByPath = (plugin, ref2) => { + const path = uriByString(plugin, ref2); + if (!path) + return; + if (path.space == "$kit") { + return kit.find((f4) => f4.schema.id == path.ref); } + const context = plugin.index.framesIndex.get(path.basePath); + return context == null ? void 0 : context.frames[path.ref]; }; -var getAllSubtags = (plugin, tag) => { - const tags = loadTags(plugin); - return tags.filter((f4) => f4.startsWith(tag) && f4 != tag); -}; -var removeTagInFrontmatter = async (oldTag, file) => { - var _a2; - let fm; - if (app.metadataCache.getFileCache(file) !== null) { - fm = (_a2 = app.metadataCache.getFileCache(file)) == null ? void 0 : _a2.frontmatter; - } - if (fm && app.fileManager.processFrontMatter) { - const processKey = (value) => { - if (Array.isArray(value)) { - return value.filter((f4) => stringFromTag(oldTag) != f4); - } else if (typeof value === "string") { - return serializeMultiDisplayString( - value.replace(/\s/g, "").split(",").filter((f4) => stringFromTag(oldTag) != f4) - ); - } - return value; - }; - const editKeys = tagKeys.filter((f4) => { - let tags = []; - if (Array.isArray(fm[f4])) { - tags = fm[f4]; - } else if (typeof fm[f4] === "string") { - tags = fm[f4].replace(/\s/g, "").split(","); - } - if (tags.find((g4) => g4 == stringFromTag(oldTag))) - return true; - return false; - }); - editKeys.forEach((tag) => { - app.fileManager.processFrontMatter(file, (frontmatter) => { - frontmatter[tag] = processKey(fm[tag]); - }); +function flattenToFrameNodes(root) { + const flattenedTree = []; + function traverseAndFlatten(node, parent) { + var _a2; + flattenedTree.push({ ...node.node, parentId: parent, schemaId: root.node.schemaId }); + ((_a2 = node.children) != null ? _a2 : []).forEach((child) => { + traverseAndFlatten(child, node.node.id); }); } -}; -var editTagInFrontmatter = async (oldTag, newTag, file) => { - var _a2; - let fm; - if (app.metadataCache.getFileCache(file) !== null) { - fm = (_a2 = app.metadataCache.getFileCache(file)) == null ? void 0 : _a2.frontmatter; + traverseAndFlatten(root, ""); + return flattenedTree; +} +function insertFrameChildren(root, newChildren) { + function traverseAndInsert(node) { + return { + ...node, + children: node.node.type === "content" && newChildren.length > 0 ? newChildren.map((f4) => ({ ...f4, node: { ...f4.node, parentId: node.id } })) : node.children.map((child) => { + return traverseAndInsert(child); + }) + }; } - const addTag2 = (value) => { - if (Array.isArray(value)) { - return uniq([...value, stringFromTag(newTag)]).filter((f4) => (f4 == null ? void 0 : f4.length) > 0); - } else if (typeof value === "string") { - return serializeMultiDisplayString(uniq([ - ...value.replace(/\s/g, "").split(","), - stringFromTag(newTag) - ]).filter((f4) => (f4 == null ? void 0 : f4.length) > 0)); - } - return stringFromTag(newTag); - }; - if (app.fileManager.processFrontMatter) { - if (fm) { - const processKey = (value) => { - if (Array.isArray(value)) { - return uniq( - value.map( - (f4) => stringFromTag(oldTag) == f4 ? stringFromTag(newTag) : f4 - ) - ); - } else if (typeof value === "string") { - return serializeMultiDisplayString(uniq( - value.replace(/\s/g, "").split(",").map( - (f4) => stringFromTag(oldTag) == f4 ? stringFromTag(newTag) : f4 - ) - )); - } - return value; - }; - const editKeys = tagKeys.filter((f4) => { - let tags = []; - if (Array.isArray(fm[f4])) { - tags = fm[f4]; - } else if (typeof fm[f4] === "string") { - tags = fm[f4].replace(/\s/g, "").split(","); - } - if (tags.find((g4) => g4 == stringFromTag(oldTag))) - return true; - return false; - }); - if (editKeys.length > 0) { - editKeys.forEach((key2) => { - app.fileManager.processFrontMatter(file, (frontmatter) => { - frontmatter[key2] = processKey(fm[key2]); - }); - }); - } else { - app.fileManager.processFrontMatter(file, (frontmatter) => { - frontmatter["tags"] = addTag2(fm["tags"]); - }); - } - } else { - app.fileManager.processFrontMatter(file, (frontmatter) => { - frontmatter["tags"] = stringFromTag(newTag); - }); + const newRoot = traverseAndInsert(root); + return newRoot; +} +var expandNode = (treeNode, id2, plugin) => { + if (treeNode.node.type == "frame") { + const mdbFrame = getFrameNodesByPath(plugin, treeNode.node.ref); + if (treeNode.node.schemaId == (mdbFrame == null ? void 0 : mdbFrame.schema.id)) + return [treeNode, id2]; + if (!mdbFrame || mdbFrame.rows.length == 0) { + return [treeNode, id2]; + } + const linkedNode = linkProps(mdbFrame.cols, treeNode); + const [linkedNodes, newUniqueID] = linkNodes( + linkedNode.node, + mdbFrame.schema.id, + linkedNode.node.props, + mdbFrame.rows.map((f4) => frameToNode(f4)), + id2 + ); + const [newTreeNode, newID] = buildFrameTree( + linkedNode.node, + linkedNodes, + plugin, + newUniqueID, + true, + treeNode.editorProps + ); + if (!newTreeNode) { + return [linkedNode, newID]; } + return [insertFrameChildren({ ...newTreeNode, isRef: false, node: { ...newTreeNode.node, schemaId: linkedNode.node.schemaId, ref: linkedNode.node.ref, types: linkedNode.node.types, propsAttrs: linkedNode.node.propsAttrs, propsValue: linkedNode.node.propsValue, parentId: linkedNode.node.parentId, type: "frame", id: newTreeNode.id } }, treeNode.children), newID]; } + return [treeNode, id2]; }; -var editTagInFileBody = async (oldTag, newTag, positions, file) => { - const offsetOffset = newTag.length - oldTag.length; - if (positions.length == 0) - return false; - const original = await app.vault.read(file); - let text2 = original; - let offset = 0; - for (const { start, end } of positions) { - let startOff = start.offset + offset; - let endOff = end.offset + offset; - if (text2.slice(startOff, endOff) !== oldTag) { - return false; - } - text2 = text2.slice(0, startOff) + newTag + text2.slice(startOff + oldTag.length); - offset += offsetOffset; - } - if (text2 !== original) { - await app.vault.modify(file, text2); - return true; - } +var expandFrame = (node, plugin, uniqueID = 0, editorProps) => { + const [children, lastID] = node.children.reduce((f4, c4) => { + const [nodes, id2] = f4; + const _editorProps = calculateEditorProps({ ...editorProps, parentType: node.node.type }, c4); + const [newNode2, fid] = expandFrame(c4, plugin, id2 + 1, _editorProps); + return [[...nodes, newNode2], fid + 1]; + }, [[], uniqueID]); + const [newNode, newID] = expandNode({ ...node, children, editorProps }, lastID, plugin); + return [{ + ...newNode, + editorProps: calculateEditorProps(newNode.editorProps, newNode) + }, newID]; +}; +var linkProps = (fields, root) => { + const props2 = fields.reduce((p3, c4) => ({ ...p3, [c4.name]: "" }), {}); + const types2 = fields.reduce((p3, c4) => ({ ...p3, [c4.name]: c4.type }), {}); + const propsValue = fields.reduce((p3, c4) => ({ ...p3, [c4.name]: c4.value }), {}); + const propsAttrs = fields.reduce((p3, c4) => ({ ...p3, [c4.name]: c4.attrs }), {}); + return { ...root, node: { + ...root.node, + props: { ...props2, ...root.node.props }, + types: { ...types2, ...root.node.types }, + propsValue: { ...propsValue, ...root.node.propsValue }, + propsAttrs: { ...propsAttrs, ...root.node.propsAttrs } + } }; }; -var allTagsForFile = (file) => { - var _a2, _b2, _c2, _d2, _e2, _f, _g, _h, _i, _j; - let rt = []; - if (file instanceof import_obsidian3.TFile) { - const fCache = app.metadataCache.getCache(file.path); - if (fCache && fCache.tags) - rt.push(...(_b2 = (_a2 = fCache.tags) == null ? void 0 : _a2.map((f4) => f4.tag)) != null ? _b2 : []); - if (fCache && ((_c2 = fCache.frontmatter) == null ? void 0 : _c2.tags)) - rt.push( - ...(typeof ((_d2 = fCache.frontmatter) == null ? void 0 : _d2.tags) === "string" ? parseMultiString(fCache.frontmatter.tags.replace(/ /g, "")) : Array.isArray((_e2 = fCache.frontmatter) == null ? void 0 : _e2.tags) ? (_f = fCache.frontmatter) == null ? void 0 : _f.tags : []).filter((f4) => typeof f4 === "string").map((f4) => "#" + f4) - ); - if (fCache && ((_g = fCache.frontmatter) == null ? void 0 : _g.tag)) - rt.push( - ...(typeof ((_h = fCache.frontmatter) == null ? void 0 : _h.tag) === "string" ? parseMultiString(fCache.frontmatter.tag.replace(/ /g, "")) : Array.isArray((_i = fCache.frontmatter) == null ? void 0 : _i.tag) ? (_j = fCache.frontmatter) == null ? void 0 : _j.tag : []).filter((f4) => typeof f4 === "string").map((f4) => "#" + f4) - ); +var applyPropsToRoot = (root, props2) => ({ + ...root, + node: { + ...root.node, + props: { + ...root.node.props, + ...applyFunctionToObject(props2, (e4) => wrapQuotes(e4)) + } } - return uniq(rt); -}; - -// src/utils/contexts/mdb.ts -var dbTableToMDBTable = (table, schema, fields) => { - var _a2; +}); +var schemaToRoot = (schema) => { return { - schema, - cols: fields, - rows: (_a2 = table == null ? void 0 : table.rows) != null ? _a2 : [] + schemaId: schema.id, + id: schema.id, + type: "group", + rank: 0, + name: schema.id }; }; -var updateFieldsToSchema = (fields, context) => { - const defaultFields = defaultFieldsForContext(context); - return [ - ...fields, - ...defaultFields.rows.filter( - (f4) => !fields.some((g4) => g4.name == f4.name && g4.schemaId == f4.schemaId) - ) - ]; -}; -var getMDBTable = async (plugin, context, table) => { - if (!context) - return null; - const sqlJS = await plugin.sqlJS(); - const buf = await getDBFile(context.dbPath, context.isRemote); - if (!buf) { - return null; - } - const db = new sqlJS.Database(new Uint8Array(buf)); - await sanitizeTableSchema(plugin, db, context); - let fieldsTables; - let schema; - try { - fieldsTables = dbResultsToDBTables( - db.exec(`SELECT * FROM m_fields WHERE schemaId = '${table}'`) - ); - schema = dbResultsToDBTables( - db.exec(`SELECT * FROM m_schema WHERE id = '${table}'`) - )[0].rows[0]; - } catch (e4) { - db.close(); - return null; - } - if (fieldsTables.length == 0) { - db.close(); - return { - schema, - cols: [], - rows: [] - }; - } - const fields = fieldsTables[0].rows.filter( - (f4) => f4.name.length > 0 - ); - const dbTable = dbResultsToDBTables( - db.exec( - `SELECT ${serializeSQLFieldNames( - fields.reduce((p3, c4) => [...p3, `"${c4.name}"`], []) - )} FROM "${table}"` - ) - ); - db.close(); - return dbTableToMDBTable( - dbTable[0], - schema, - schema.primary ? updateFieldsToSchema(fields, context) : fields - ); -}; -var deleteMDBTable = async (plugin, context, table) => { - if (context.readOnly) - return false; - const sqlJS = await plugin.sqlJS(); - const buf = await getDBFile(context.dbPath, context.isRemote); - if (!buf) { - return false; - } - const db = new sqlJS.Database(new Uint8Array(buf)); - deleteFromDB(db, "m_schema", `id = '${sanitizeSQLStatement(table)}'`); - deleteFromDB(db, "m_schema", `def = '${sanitizeSQLStatement(table)}'`); - deleteFromDB(db, "m_fields", `schemaId = '${sanitizeSQLStatement(table)}'`); - dropTable(db, table); - await saveDBFile(context.dbPath, db.export().buffer); - db.close(); - return true; -}; -var getMDBTableSchemas = async (plugin, context) => { - const sqlJS = await plugin.sqlJS(); - const buf = await getDBFile(context.dbPath, context.isRemote); - if (!buf) { - return null; - } - const db = new sqlJS.Database(new Uint8Array(buf)); - await sanitizeTableSchema(plugin, db, context); - const tables = db.exec(`SELECT * FROM m_schema`); - db.close(); - return tables[0].values.map((f4) => { - const [id2, name, type, def, predicate, primary] = f4; - return { id: id2, name, type, def, predicate, primary }; - }); -}; -var saveMDBToPath = async (plugin, context, mdb) => { - var _a2, _b2; - if (context.readOnly) - return; - const sqlJS = await plugin.sqlJS(); - const buf = await getDBFile(context.dbPath, context.isRemote); - if (!buf) { - return null; - } - const db = new sqlJS.Database(new Uint8Array(buf)); - const fieldsTables = dbResultsToDBTables( - db.exec(`SELECT * FROM m_fields WHERE schemaId != '${mdb.schema.id}'`) - ); - const tables = { - m_fields: { - uniques: fieldSchema.uniques, - cols: fieldSchema.cols, - rows: [...(_b2 = (_a2 = fieldsTables[0]) == null ? void 0 : _a2.rows) != null ? _b2 : [], ...mdb.cols] - }, - [mdb.schema.id]: { - uniques: [], - cols: mdb.cols.map((c4) => c4.name), - rows: mdb.rows - } +var schemaToFrame = (schema) => { + return { + schemaId: schema.id, + id: schema.id, + type: "frame", + rank: 0, + name: schema.id }; - db.close(); - return saveDBToPath(plugin, context.dbPath, tables); }; -var optionValuesForColumn = (column, table) => { +var buildRootFromMDBFrame = (plugin, frame, editorProps = defaultFrameEditorProps) => { + return buildRoot(mdbSchemaToFrameSchema(frame.schema), frame.cols, frame.rows.map((f4) => frameToNode(f4)), plugin, editorProps); +}; +var buildRoot = (schema, fields, nodes, plugin, editorProps = defaultFrameEditorProps) => { var _a2; - return uniq( - (_a2 = table == null ? void 0 : table.rows.reduce((p3, c4) => { - return [...p3, ...parseMultiString(c4[column])]; - }, [])) != null ? _a2 : [] - ); + const rootNode = (_a2 = nodes.find((f4) => f4.id == schema.id)) != null ? _a2 : schemaToRoot(schema); + const root = buildFrameTree(rootNode, nodes, plugin, nodes.length, false, { ...editorProps, rootId: schema.id })[0]; + return root && linkProps(fields, root); }; -var defaultTableDataForContext = (plugin, contextInfo) => { +var propertiesForNode = (node) => Object.keys(node.types).map((f4) => { var _a2, _b2; - let files; - if (contextInfo.type == "folder") { - files = folderChildren( - plugin, - getAbstractFileAtPath( - plugin.app, - contextInfo.contextPath - ) - ); - return { - ...defaultMDBTableForContext(contextInfo), - rows: files.map((f4) => ({ File: f4.path })) - }; - } else if (contextInfo.type == "tag") { - files = getAllFilesForTag(contextInfo.contextPath).map((f4) => getAbstractFileAtPath(app, f4)).filter((f4) => f4); - return { - ...defaultMDBTableForContext(contextInfo), - rows: files.map((f4) => ({ File: f4.path })) - }; - } else if (contextInfo.type == "space") { - files = [ - ...(_b2 = (_a2 = plugin.index.spacesMap) == null ? void 0 : _a2.getInverse( - contextInfo.contextPath.substring( - 0, - contextInfo.contextPath.length - 2 - ) - )) != null ? _b2 : [] - ].map((f4) => getAbstractFileAtPath(app, f4)).filter((f4) => f4); - return { - ...defaultMDBTableForContext(contextInfo), - rows: files.map((f4) => ({ File: f4.path })) - }; - } - return null; -}; -var createDefaultDB = async (plugin, context) => { - var _a2; - const table = defaultTableDataForContext(plugin, context); - if (table) { - const defaultFields = defaultFieldsForContext(context); - const defaultTable = defaultTablesForContext(context); - const dbField = { - ...defaultTable, - m_fields: { - uniques: defaultFields.uniques, - cols: defaultFields.cols, - rows: [...(_a2 = defaultFields.rows) != null ? _a2 : [], ...table.cols] - }, - [table.schema.id]: { - uniques: table.cols.filter((c4) => c4.unique == "true").map((c4) => c4.name), - cols: table.cols.map((c4) => c4.name), - rows: table.rows + return { + type: node.types[f4], + name: f4, + schemaId: f4, + value: (_a2 = node.propsValue) == null ? void 0 : _a2[f4], + attrs: (_b2 = node.propsAttrs) == null ? void 0 : _b2[f4] + }; +}); +var buildFrameTree = (root, nodes, plugin, uniqueID = 0, isRef, editorProps = defaultFrameEditorProps) => { + const rootNode = { node: root, id: root.id, children: [], isRef, editorProps }; + const idToNodeMap = { [root.id]: rootNode }; + nodes.forEach((node) => { + idToNodeMap[node.id] = { id: node.id, node, children: [], isRef, editorProps }; + }); + nodes.forEach((node) => { + if (node.parentId) { + const parentNode = idToNodeMap[node.parentId]; + if (parentNode) { + parentNode.children.push({ ...idToNodeMap[node.id], editorProps: { ...editorProps, parentType: parentNode.node.type } }); + parentNode.children.sort((a5, b4) => a5.node.rank - b4.node.rank); } - }; - const result = await saveDBToPath(plugin, context.dbPath, dbField); - if (result) { - await plugin.index.reloadContext(context); - table.rows.map((f4) => getAbstractFileAtPath(app, f4.File)).forEach((f4) => f4 && plugin.index.reloadFile(f4, true)); - return true; + } else { + if (node.id == root.id) + rootNode.node = idToNodeMap[node.id].node; + } + }); + const [treeNode, newID] = expandFrame(idToNodeMap[root.id], plugin, uniqueID, editorProps); + return [treeNode, newID]; +}; +var findParent = (tree, targetId, parentId = null) => { + for (const child of tree.children) { + if (child.id === targetId) { + return tree; } - return false; } - return false; + for (const child of tree.children) { + const foundParent = findParent(child, targetId, tree.id); + if (foundParent) { + return foundParent; + } + } + return null; }; -var sanitizeTableSchema = async (plugin, db, context) => { - const sqlJS = await plugin.sqlJS(); - let tableRes; - try { - tableRes = db.exec( - `SELECT name FROM sqlite_master WHERE type='table';` - ); - } catch (e4) { - console.log(e4); + +// src/schemas/frames.ts +var defaultFrameSchema = { + uniques: ["id,schemaId"], + cols: [ + "id", + "schemaId", + "type", + "parentId", + "name", + "rank", + "icon", + "props", + "actions", + "ref", + "styles", + "contexts" + ] +}; +var nodeToTypes = (type) => { + return type == "flow" ? { value: "link" } : type == "container" || type == "group" || type == "content" || type == "frame" ? {} : { + value: type + }; +}; +var groupNode = { + def: { + icon: "lucide//box-select" + }, + node: { + id: "group", + schemaId: "group", + name: "Group", + rank: 0, + parentId: "", + styles: { + flexDirection: `"column"`, + display: `"flex"` + }, + type: "group" } - if (tableRes && (!tableRes[0] || !tableRes[0].values.some((f4) => f4[0] == "m_schema") || !tableRes[0].values.some((f4) => f4[0] == "m_fields") || !tableRes[0].values.some((f4) => f4[0] == "files"))) { - await createDefaultDB(plugin, context); +}; +var columnsNode = { + def: { + icon: "lucide//columns" + }, + node: { + id: "container", + schemaId: "container", + name: "Columns", + rank: 0, + parentId: "", + styles: { + layout: `"row"`, + width: `'100%'`, + gap: `'24px'` + }, + type: "container" } }; -var createNewRow = (mdb, row, index) => { - if (index) { - return { - ...mdb, - rows: insert(mdb.rows, index, row) - }; +var columnNode = { + def: { + icon: "lucide//columns" + }, + node: { + icon: "lucide//columns", + id: "column", + schemaId: "column", + name: "Column", + rank: 0, + parentId: "", + styles: { + layout: `"column"`, + alignItems: `'flex-start'`, + flex: `1`, + gap: `'16px'`, + width: "0" + }, + type: "column" } - return { - ...mdb, - rows: [...mdb.rows, row] - }; }; -var deleteTagContext = async (plugin, tag) => { - const context = tagContextFromTag(plugin, tag); - if (getAbstractFileAtPath(app, context.dbPath)) { - await deleteFile(plugin, getAbstractFileAtPath(app, context.dbPath)); +var groupableTypes = ["content", "group", "container", "column", "list"]; +var flowNode = { + def: { + icon: "lucide//file-text" + }, + node: { + icon: "lucide//file-text", + schemaId: "flow", + parentId: "", + name: "Existing Note", + rank: 0, + id: "flow", + type: "flow", + props: { + value: "" + }, + styles: { + width: `'100%'` + }, + types: { + value: "link" + } } - app.workspace.iterateLeaves((leaf) => { - if (leaf.view.getViewType() == CONTEXT_VIEW_TYPE && leaf.view.getState().contextPath == tag) { - leaf.setViewState({ type: "empty" }); +}; +var iconNode = { + def: { + icon: "lucide//gem" + }, + node: { + icon: "lucide//gem", + schemaId: "icon", + parentId: "", + name: "Icon", + rank: 0, + id: "icon", + styles: {}, + type: "icon", + props: { + value: "" + }, + types: { + value: "icon" } - }, app.workspace["rootSplit"]); - plugin.index.deleteTag(tag); + } }; -var deleteSpaceContext = async (plugin, space) => { - const context = spaceContextFromSpace(plugin, spaceContextPathFromName(space)); - if (getAbstractFileAtPath(app, context.dbPath)) { - await deleteFile(plugin, getAbstractFileAtPath(app, context.dbPath)); +var spaceNode = { + def: { + icon: "lucide//layout-grid" + }, + node: { + icon: "lucide//layout-grid", + schemaId: "space", + parentId: "", + name: "Space", + rank: 0, + id: "space", + styles: { width: `'100%'` }, + type: "space", + props: { + value: "" + }, + types: { + value: "view" + } } - app.workspace.iterateLeaves((leaf) => { - if (leaf.view.getViewType() == CONTEXT_VIEW_TYPE && leaf.view.getState().contextPath == context.contextPath) { - leaf.setViewState({ type: "empty" }); +}; +var imageNode = { + def: { + icon: "lucide//image" + }, + node: { + icon: "lucide//image", + schemaId: "image", + parentId: "", + name: "Image", + rank: 0, + id: "image", + type: "image", + props: { + value: "" + }, + types: { + value: "image" } - }, app.workspace["rootSplit"]); + } }; -var connectContext = async (plugin, tag, source) => { +var textNode = { + def: { + icon: "lucide//type", + description: "Insert a text labels to decorate your Space" + }, + node: { + icon: "lucide//type", + schemaId: "text", + parentId: "", + name: "Label", + rank: 0, + id: "text", + type: "text", + props: { + value: "" + }, + types: { + value: "text" + } + } }; -var renameSpaceContextFile = async (plugin, space, newSpace) => { - const context = spaceContextFromSpace(plugin, spaceContextPathFromName(space)); - if (getAbstractFileAtPath(app, context.dbPath)) { - const newSpaceDBPath = newSpace + ".mdb"; - if (!getAbstractFileAtPath( - app, - getAbstractFileAtPath(app, context.dbPath).parent.path + "/" + newSpaceDBPath - )) { - await renameFile( - plugin, - getAbstractFileAtPath(app, context.dbPath), - newSpaceDBPath - ); - } else { - await deleteFile(plugin, getAbstractFileAtPath(app, context.dbPath)); +var dividerNode = { + def: { + icon: "lucide//type" + }, + node: { + icon: "lucide//type", + schemaId: "hr", + parentId: "", + name: "Divider", + rank: 0, + id: "hr", + type: "hr", + styles: { + as: `'hr'` } } - app.workspace.iterateLeaves((leaf) => { - if (leaf.view.getViewType() == CONTEXT_VIEW_TYPE && leaf.view.getState().contextPath == context.contextPath) { - leaf.setViewState({ - type: CONTEXT_VIEW_TYPE, - state: { contextPath: spaceContextPathFromName(newSpace) } - }); +}; +var buttonNode = { + id: "button", + def: { + icon: "lucide//mouse-pointer-click" + }, + node: { + icon: "lucide//mouse-pointer-click", + schemaId: "button", + parentId: "", + name: "Button", + rank: 0, + id: "button", + type: "group", + props: { + icon: "", + label: "", + action: "", + actionValue: "" + }, + types: { + icon: "icon", + label: "text", + action: "option", + actionValue: "super" + }, + propsAttrs: { + action: JSON.stringify({ + name: "When Clicked", + icon: "lucide//mouse-pointer-click" + }), + actionValue: JSON.stringify({ + name: "Perform Action" + }) + }, + propsValue: { + action: JSON.stringify({ + options: [{ name: "Run Command", value: "$commands" }, { name: "Open Link", value: "$links" }] + }), + actionValue: JSON.stringify({ + dynamic: true, + field: "action" + }) + }, + actions: { + onClick: `(a,b,c,api) => api.buttonCommand(button.props.action, button.props.actionValue)` + }, + styles: { + class: `'mk-button'`, + gap: `'4px'` } - }, app.workspace["rootSplit"]); + }, + children: [ + { ...iconNode, node: { ...iconNode.node, props: { + value: `button.props.icon` + } } }, + { ...textNode, node: { ...textNode.node, props: { value: `button.props.label` } } } + ] }; -var renameTagContextFile = async (plugin, tag, newTag) => { - const context = tagContextFromTag(plugin, tag); - if (getAbstractFileAtPath(app, context.dbPath)) { - const newTagDBPath = tagToTagPath(newTag) + ".mdb"; - if (!getAbstractFileAtPath( - app, - getAbstractFileAtPath(app, context.dbPath).parent.path + "/" + tagToTagPath(newTag) + ".mdb" - )) { - await renameFile( - plugin, - getAbstractFileAtPath(app, context.dbPath), - tagToTagPath(newTag) + ".mdb" - ); - } else { - await deleteFile(plugin, getAbstractFileAtPath(app, context.dbPath)); +var progressNode = { + id: "progress", + def: { + icon: "lucide//pie-chart" + }, + node: { + icon: "lucide//pie-chart", + schemaId: "progress", + parentId: "", + name: "Progress", + rank: 0, + id: "progress", + type: "group", + props: { + value: "50", + total: "100" + }, + types: { + total: "number", + value: "number" + }, + styles: { + background: `'var(--background-modifier-form-field)'`, + height: `'10px'`, + width: `'100px'`, + borderRadius: `'5px'` } - } - plugin.index.renameTag(tag, newTag); - app.workspace.iterateLeaves((leaf) => { - if (leaf.view.getViewType() == CONTEXT_VIEW_TYPE && leaf.view.getState().contextPath == tag) { - leaf.setViewState({ - type: CONTEXT_VIEW_TYPE, - state: { contextPath: newTag } - }); + }, + children: [ + { ...groupNode, node: { ...groupNode.node, styles: { + width: `progress.props.value/progress.props.total*100+'%'`, + height: `'100%'`, + borderRadius: `'5px'`, + background: `'var(--color-orange)'`, + display: `'block'` + } } } + ] +}; +var cardNode = { + id: "card", + def: { + icon: "lucide//mouse-pointer-click" + }, + node: { + icon: "lucide//mouse-pointer-click", + schemaId: "card", + parentId: "", + name: "Card", + rank: 0, + id: "card", + type: "group", + props: { + icon: "", + label: "" + }, + types: { + icon: "icon", + label: "text" + }, + actions: {}, + styles: { + borderRadius: `'10px'`, + background: `'var(--background-primary-alt)'`, + width: `'160px'`, + height: `'80px'`, + padding: `'16px'`, + border: `'thin solid var(--divider-color)'` } - }, app.workspace["rootSplit"]); + }, + children: [ + { ...iconNode, node: { ...iconNode.node, props: { + value: `card.props.icon` + } } }, + { ...textNode, node: { ...textNode.node, props: { value: `card.props.label` } } } + ] }; - -// src/utils/contexts/predicate/filterFns/filterFnTypes.ts -var filterFnTypes = { - isNotEmpty: { - type: ["text", "file", "link", "link-multi", "fileprop", "image"], - fn: (v3, f4) => !empty(v3, ""), - valueType: "none" +var linkNode = { + id: "link", + def: { + icon: "lucide//link" }, - isEmpty: { - type: ["text", "file", "link", "link-multi", "fileprop", "image"], - fn: (v3, f4) => empty(v3, ""), - valueType: "none" + node: { + icon: "lucide//link", + schemaId: "link", + parentId: "", + name: "Link", + rank: 0, + id: "link", + type: "group", + props: { + label: `"Link"`, + link: "" + }, + styles: { + class: `'mk-a'` + }, + actions: { + onClick: "(e,v,k,api) => { api.openLink(link.props.link, false) }" + }, + types: { + label: "text", + link: "link" + } }, - include: { - fn: (v3, f4) => stringCompare(v3, f4), - type: ["text", "file", "link", "link-multi", "fileprop", "image"], - valueType: "text" + children: [ + { ...textNode, node: { ...textNode.node, props: { value: `link.props.label` } } } + ] +}; +var rootToFrame = (root) => { + var _a2; + return { + schema: { id: root.id, name: root.node.name, type: "frame" }, + cols: Object.keys((_a2 = root.node.types) != null ? _a2 : {}).map((f4) => { + var _a3, _b2; + return { + name: f4, + schemaId: root.id, + type: root.node.types[f4], + value: (_a3 = root.node.propsValue) == null ? void 0 : _a3[f4], + attrs: (_b2 = root.node.propsAttrs) == null ? void 0 : _b2[f4] + }; + }), + rows: flattenToFrameNodes(root).map((f4) => nodeToFrame(f4)) + }; +}; +var kit = [rootToFrame(buttonNode), rootToFrame(dividerNode), rootToFrame(progressNode), rootToFrame(cardNode), rootToFrame(linkNode)]; + +// src/types/context.ts +var FilePropertyName = "File"; + +// src/utils/contexts/parsers.ts +var parsePropString = (str) => { + var _a2; + const [p1, p22] = (_a2 = str == null ? void 0 : str.match(/(\\.|[^.])+/g)) != null ? _a2 : []; + if (p22) + return { + field: p1, + property: p22 + }; + return { field: "File", property: p1 }; +}; + +// src/schemas/mdb.ts +var parseFieldValue = (value, type) => { + let valueProp = safelyParseJSON(value); + if (!type) + return {}; + if (!valueProp) { + if (type == "context") { + if ((value == null ? void 0 : value.length) > 0) { + valueProp = { + space: value + }; + } else { + valueProp = {}; + } + } else if (type.startsWith("date")) { + if ((value == null ? void 0 : value.length) > 0) { + valueProp = { + format: value + }; + } else { + valueProp = {}; + } + } else if (type.startsWith("fileprop")) { + if ((value == null ? void 0 : value.length) > 0) { + const [field, val] = value.split("."); + valueProp = { + field, + value: val + }; + } else { + valueProp = {}; + } + } else if (type.startsWith("option")) { + if ((value == null ? void 0 : value.length) > 0) { + const options = parseMultiString(value).map((f4) => ({ name: f4, value: f4 })); + valueProp = { + options + }; + } else { + valueProp = {}; + } + } + } + return valueProp != null ? valueProp : {}; +}; +var stickerForField = (f4) => { + var _a2, _b2, _c2, _d2, _e2; + return ((_a2 = f4.attrs) == null ? void 0 : _a2.length) > 0 ? (_d2 = (_b2 = safelyParseJSON(f4.attrs)) == null ? void 0 : _b2.icon) != null ? _d2 : (_c2 = fieldTypeForType(f4.type)) == null ? void 0 : _c2.icon : (_e2 = fieldTypeForType(f4.type)) == null ? void 0 : _e2.icon; +}; +var fieldTypeForType = (type) => fieldTypes.find((t4) => type == t4.type) || fieldTypes.find((t4) => type == t4.multiType); +var fieldTypes = [ + { + type: "unknown", + label: "", + restricted: true, + icon: "lucide//file-question" }, - notInclude: { - type: ["text", "file", "link", "link-multi", "fileprop", "image"], - fn: (v3, f4) => !stringCompare(v3, f4), - valueType: "text" + { + type: "text", + label: i18n_default.properties.text.label, + metadata: true, + icon: "lucide//text" }, - is: { - type: ["text", "file", "link", "context", "fileprop"], - fn: stringEqual, - valueType: "text" + { + type: "number", + label: i18n_default.properties.number.label, + metadata: true, + icon: "lucide//binary" }, - isNot: { - type: ["text", "file", "link", "context", "fileprop"], - fn: (v3, f4) => !stringEqual(v3, f4), - valueType: "text" + { + type: "boolean", + label: i18n_default.properties.boolean.label, + metadata: true, + icon: "lucide//check-square" }, - equal: { - type: ["number"], - fn: stringEqual, - valueType: "number" + { + type: "date", + label: i18n_default.properties.date.label, + metadata: true, + icon: "lucide//calendar" }, - isGreatThan: { - type: ["number"], - fn: greaterThan, - valueType: "number" + { + type: "option", + label: i18n_default.properties.option.label, + multi: true, + multiType: "option-multi", + icon: "lucide//list" }, - isLessThan: { - type: ["number"], - fn: lessThan, - valueType: "number" + { + type: "file", + label: i18n_default.properties.file.label, + restricted: true, + icon: "ui//mk-make-h3" }, - isLessThanOrEqual: { - type: ["number"], - fn: (v3, f4) => !greaterThan(v3, f4), - valueType: "number" + { + type: "fileprop", + label: i18n_default.properties.fileProperty.label, + icon: "lucide//list" }, - isGreatThanOrEqual: { - type: ["number"], - fn: (v3, f4) => !lessThan(v3, f4), - valueType: "number" + { + type: "link", + label: i18n_default.properties.link.label, + multi: true, + multiType: "link-multi", + metadata: true, + icon: "lucide//file-text" }, - dateBefore: { - type: ["date", "fileprop"], - fn: lessThan, - valueType: "date" + { + type: "context", + label: i18n_default.properties.context.label, + icon: "ui//mk-make-note", + multi: true, + multiType: "context-multi" }, - dateAfter: { - type: ["date", "fileprop"], - fn: greaterThan, - valueType: "date" + { + type: "object", + label: i18n_default.properties.object.label, + multi: true, + multiType: "object-multi", + metadata: true, + icon: "lucide//list-tree" }, - isAnyInList: { - type: ["option", "context", "option-multi", "context-multi", "tags-multi", "tags"], - fn: listIncludes, - valueType: "list" + { + type: "icon", + label: i18n_default.properties.icon.label, + multi: true, + multiType: "icon-multi", + icon: "lucide//gem", + restricted: true }, - isNoneInList: { - type: ["option", "context", "option-multi", "context-multi", "tags-multi", "tags"], - fn: (v3, f4) => !listIncludes(v3, f4), - valueType: "list" + { + type: "image", + label: i18n_default.properties.image.label, + multi: true, + multiType: "image-multi", + metadata: true, + icon: "ui//mk-make-image" }, - isTrue: { - type: ["boolean"], - fn: (v3, f4) => v3 == "true", - valueType: "none" + { + type: "color", + label: i18n_default.properties.color.label, + icon: "ui//mk-make-image", + restricted: true }, - isFalse: { - type: ["boolean"], - fn: (v3, f4) => v3 != "true", - valueType: "none" + { + type: "space", + label: i18n_default.properties.space.label, + icon: "lucide//layout-grid", + restricted: true + }, + { + type: "super", + label: "Super Property", + icon: "lucide//zap", + restricted: true } +]; +var defaultFileDBSchema = { + id: "files", + name: "Files", + type: "db", + primary: "true" }; - -// src/utils/contexts/predicate/filter.ts -var stringEqual = (value, filterValue) => { - return value == filterValue; +var defaultFileListSchema = { + id: "filesView", + name: "Files", + type: "view", + def: { db: "files" } }; -var empty = (value, filterValue) => { - return (value != null ? value : "").length == 0; +var mainFrameID = "main"; +var defaultMainFrameSchema = (id2) => ({ id: id2, name: id2, type: "frame", def: "", predicate: "", primary: "true" }); +var defaultFramesSchema = { + uniques: [], + cols: ["id", "name", "type", "def", "predicate", "primary"], + rows: [defaultMainFrameSchema(mainFrameID), frameSchemaToMDBSchema(defaultFileListSchema)] }; -var stringCompare = (value, filterValue) => { - return (value != null ? value : "").toLowerCase().includes((filterValue != null ? filterValue : "").toLowerCase()); +var defaultFolderSchema = { + uniques: [], + cols: ["id", "name", "type", "def", "predicate", "primary"], + rows: [defaultFileDBSchema] }; -var greaterThan = (value, filterValue) => { - return parseFloat(value) > parseFloat(filterValue); +var fieldSchema = { + uniques: ["name,schemaId"], + cols: [ + "name", + "schemaId", + "type", + "value", + "attrs", + "hidden", + "unique", + "primary" + ] }; -var lessThan = (value, filterValue) => { - return parseInt(value) > parseInt(filterValue); +var defaultFolderFields = { + ...fieldSchema, + rows: [ + { + name: FilePropertyName, + schemaId: "files", + type: "file", + primary: "true", + hidden: "", + unique: "", + attrs: "", + value: "" + }, + { + name: i18n_default.properties.fileProperty.createdTime, + schemaId: "files", + type: "fileprop", + value: "File.ctime", + hidden: "", + unique: "", + attrs: "", + primary: "true" + } + ] }; -var listIncludes = (value, filterValue) => { - const valueList = value ? parseMultiString(value) : []; - const strings = filterValue ? parseMultiString(filterValue) : []; - return strings.some((f4) => valueList.some((g4) => g4 == f4)); +var defaultFieldsForContext = (space) => { + if (space.uri.type == "tag") { + return defaultTagFields; + } else if (space.uri.type == "folder") { + return defaultFolderFields; + } + return defaultFolderFields; }; -var filterReturnForCol = (col, filter, row) => { - if (!col) - return true; - const filterType = filterFnTypes[filter == null ? void 0 : filter.fn]; - let result = true; - if (filterType && filterType.fn) { - result = filterType.fn(row[filter.field], filter.value); +var defaultTableFields = [ + { + name: i18n_default.properties.defaultField, + schemaId: "", + type: "text" } - return result; +]; +var defaultTagFields = { + ...fieldSchema, + rows: [ + { + name: FilePropertyName, + schemaId: "files", + type: "file", + primary: "true", + hidden: "", + unique: "", + attrs: "", + value: "" + } + ] }; - -// src/utils/contexts/predicate/sort.ts -var simpleSort = (a5, b4) => { - if (a5 < b4) - return -1; - if (a5 > b4) - return 1; - return 0; +var defaultMDBTableForContext = (space) => { + return defaultFolderMDBTable; }; -var stringSort = (value, filterValue) => simpleSort(value, filterValue); -var numSort = (value, filterValue) => simpleSort(parseFloat(value), parseFloat(filterValue)); -var boolSort = (value, filterValue) => simpleSort(value == "true" ? 1 : 0, filterValue == "true" ? 1 : 0); -var countSort = (value, filterValue) => simpleSort(parseMultiString(value).length, parseMultiString(filterValue).length); -var normalizedSortForType = (type, desc) => { - return Object.keys(sortFnTypes).find( - (f4) => sortFnTypes[f4].type.some((g4) => g4 == type) && sortFnTypes[f4].desc == desc - ); +var defaultFolderMDBTable = { + schema: defaultFileDBSchema, + cols: defaultFolderFields.rows, + rows: [] }; -var sortFnTypes = { - alphabetical: { - type: ["text", "file", "link", "context", "fileprop"], - fn: stringSort, - label: i18n_default.sortTypes.alphaAsc, - desc: false - }, - reverseAlphabetical: { - type: ["text", "file", "link", "context", "fileprop"], - fn: (v3, f4) => stringSort(v3, f4) * -1, - label: i18n_default.sortTypes.alphaDesc, - desc: true - }, - earliest: { - type: ["date", "fileprop"], - fn: stringSort, - label: i18n_default.sortTypes.earliest, - desc: false - }, - latest: { - type: ["date", "fileprop"], - fn: (v3, f4) => stringSort(v3, f4) * -1, - label: i18n_default.sortTypes.latest, - desc: true - }, - boolean: { - type: ["boolean"], - fn: boolSort, - label: i18n_default.sortTypes.checkAsc, - desc: false - }, - booleanReverse: { - type: ["boolean"], - fn: (v3, f4) => boolSort(v3, f4) * -1, - label: i18n_default.sortTypes.checkDesc, - desc: true - }, - number: { - type: ["number", "fileprop"], - fn: numSort, - label: "1 \u2192 9", - desc: false +var defaultQueryMDBTable = { + schema: defaultFileDBSchema, + cols: defaultFolderFields.rows, + rows: [] +}; +var defaultTagMDBTable = { + schema: defaultFileDBSchema, + cols: defaultTagFields.rows, + rows: [] +}; +var fieldsToTable = (fields, schemas) => { + return fields.filter((s5) => schemas.find((g4) => g4.id == s5.schemaId && g4.type == "db")).reduce((p3, c4) => { + return { + ...p3, + ...p3[c4.schemaId] ? { + [c4.schemaId]: { + uniques: c4.unique == "true" ? [...p3[c4.schemaId].uniques, c4.name] : p3[c4.schemaId].uniques, + cols: [...p3[c4.schemaId].cols, c4.name], + rows: [] + } + } : { + [c4.schemaId]: { + uniques: c4.unique == "true" ? [c4.name] : [], + cols: [c4.name], + rows: [] + } + } + }; + }, {}); +}; +var defaultTablesForContext = (space) => { + if (space.uri.type == "tag") { + return defaultTagTables; + } else if (space.uri.type == "folder") { + return defaultFolderTables; + } + return defaultFolderTables; +}; +var defaultFolderTables = { + m_schema: defaultFolderSchema, + m_fields: defaultFolderFields, + ...fieldsToTable( + defaultFolderFields.rows, + defaultFolderSchema.rows + ) +}; +var defaultTagTables = { + m_schema: defaultFolderSchema, + m_fields: defaultTagFields, + ...fieldsToTable( + defaultTagFields.rows, + defaultFolderSchema.rows + ) +}; + +// src/components/SpaceView/Frames/DefaultFrames/DefaultFrames.ts +var defaultMainFrame = [ + { + ...groupNode.node, + id: "main", + type: "group", + rank: 0, + schemaId: "main", + props: { + note: "", + space: "" + }, + types: { + note: "link", + space: "space" + }, + propsValue: { + note: JSON.stringify({ + alias: "Space Note" + }), + space: JSON.stringify({ + alias: "Space Files" + }) + }, + styles: { + layout: `"column"`, + class: `'mk-f-main'` + } }, - reverseNumber: { - type: ["number", "fileprop"], - fn: (v3, f4) => numSort(v3, f4) * -1, - label: "9 \u2192 1", - desc: true + { + ...flowNode.node, + rank: 0, + props: { + value: `main.props.note` + }, + styles: { width: `'100%'` }, + parentId: "main", + schemaId: "main" }, - count: { - type: ["option-multi", "context-multi", "link-multi"], - fn: countSort, - label: i18n_default.sortTypes.itemsDesc, - desc: true + { + ...spaceNode.node, + id: "context", + rank: 1, + props: { + value: `main.props.space` + }, + styles: { width: `'100%'` }, + parentId: "main", + schemaId: "main" + } +]; +var DefaultMDBTables = { + main: { + schema: defaultMainFrameSchema(mainFrameID), + cols: [{ name: "space", type: "space", schemaId: "main", value: JSON.stringify({ + alias: "Space Files" + }) }, { name: "note", type: "link", schemaId: "main", value: JSON.stringify({ + alias: "Space Note" + }) }], + rows: defaultMainFrame.map((f4) => nodeToFrame(f4)) }, - reverseCount: { - type: ["option-multi", "context-multi", "link-multi"], - fn: (v3, f4) => countSort(v3, f4) * -1, - label: i18n_default.sortTypes.itemsAsc, - desc: false + filesView: { + schema: frameSchemaToMDBSchema(defaultFileListSchema), + cols: defaultFolderFields.rows, + rows: [] } }; -var sortReturnForCol = (col, sort, row, row2) => { - if (!col) - return 0; - const sortType = sortFnTypes[sort.fn]; - if (sortType) { - return sortType.fn(row[sort.field], row2[sort.field]); + +// src/context/FramesMDBContext.tsx +var import_obsidian5 = require("obsidian"); + +// src/utils/sanitize.ts +var sanitizeTableName = (name) => { + return name == null ? void 0 : name.replace(/[^a-z0-9+]+/gi, ""); +}; +var sanitizeColumnName = (name) => { + if ((name == null ? void 0 : name.charAt(0)) == "_") { + return sanitizeColumnName(name.substring(1)); } - return 0; + return name == null ? void 0 : name.replace(/"/g, ``); +}; +var folderReservedRe = /^[+\$#^]+/; +var illegalRe = /[\/\?<>\\:\*\|":]/g; +var controlRe = /[\x00-\x1f\x80-\x9f]/g; +var reservedRe = /^\.+$/; +var windowsReservedRe = /^(con|prn|aux|nul|com[0-9]|lpt[0-9])(\..*)?$/i; +var sanitizeFolderName = (name) => { + const replacement = ""; + return name.replace(folderReservedRe, replacement).replace(illegalRe, replacement).replace(controlRe, replacement).replace(reservedRe, replacement).replace(windowsReservedRe, replacement); +}; +var sanitizeFileName = (name) => { + const replacement = ""; + return name.replace(illegalRe, replacement).replace(controlRe, replacement).replace(reservedRe, replacement).replace(windowsReservedRe, replacement); +}; +var sanitizeSQLStatement = (name) => { + return name == null ? void 0 : name.replace(/'/g, `''`); }; -// node_modules/date-fns/esm/_lib/toInteger/index.js -function toInteger(dirtyNumber) { - if (dirtyNumber === null || dirtyNumber === true || dirtyNumber === false) { - return NaN; +// src/utils/db/db.ts +var import_obsidian4 = require("obsidian"); +var getDBFile = async (plugin, path, isRemote) => { + if (isRemote) { + return fetch(path).then((res) => res.arrayBuffer()); } - var number = Number(dirtyNumber); - if (isNaN(number)) { - return number; + if (!await plugin.app.vault.adapter.exists((0, import_obsidian4.normalizePath)(path))) { + return null; } - return number < 0 ? Math.ceil(number) : Math.floor(number); -} - -// node_modules/date-fns/esm/_lib/requiredArgs/index.js -function requiredArgs(required, args) { - if (args.length < required) { - throw new TypeError(required + " argument" + (required > 1 ? "s" : "") + " required, but only " + args.length + " present"); + const file = await plugin.app.vault.adapter.readBinary( + (0, import_obsidian4.normalizePath)(path) + ); + return file; +}; +var getDB = async (plugin, sqlJS, path, isRemote) => { + const buf = await getDBFile(plugin, path, isRemote); + if (buf) { + return new sqlJS.Database(new Uint8Array(buf)); } -} - -// node_modules/date-fns/esm/toDate/index.js -function _typeof(obj) { - "@babel/helpers - typeof"; - if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { - _typeof = function _typeof5(obj2) { - return typeof obj2; - }; - } else { - _typeof = function _typeof5(obj2) { - return obj2 && typeof Symbol === "function" && obj2.constructor === Symbol && obj2 !== Symbol.prototype ? "symbol" : typeof obj2; + return new sqlJS.Database(); +}; +var saveDBFile = async (plugin, path, binary) => { + if (!await plugin.app.vault.adapter.exists( + removeTrailingSlashFromFolder(getParentPathFromString(path)) + )) { + await plugin.app.vault.createFolder(getParentPathFromString(path)); + } + const file = plugin.app.vault.adapter.writeBinary( + (0, import_obsidian4.normalizePath)(path), + binary + ); + return file; +}; +var mdbFrameToDBTables = (tables, uniques) => { + return Object.keys(tables).reduce((p3, c4) => { + return { + ...p3, + [c4]: { + uniques: defaultFrameSchema.uniques, + cols: defaultFrameSchema.cols, + rows: tables[c4].rows + } }; + }, {}); +}; +var schemasAndFields = (tables) => { + return { + m_fields: { + uniques: fieldSchema.uniques, + cols: fieldSchema.cols, + rows: Object.values(tables).flatMap((f4) => f4.cols) + }, + m_schema: defaultFramesSchema + }; +}; +var dbResultsToDBTables = (res) => { + return res.reduce( + (p3, c4, i4) => [ + ...p3, + { + cols: c4.columns, + rows: c4 ? c4.values.map( + (r3) => c4.columns.reduce( + (prev, curr, index) => ({ ...prev, [curr]: r3[index] }), + {} + ) + ) : [] + } + ], + [] + ); +}; +var selectDB = (db, table, condition, fields) => { + const fieldsStr = fields != null ? fields : "*"; + const sqlstr = condition ? `SELECT ${fieldsStr} FROM "${table}" WHERE ${condition};` : `SELECT ${fieldsStr} FROM ${table};`; + let tables; + try { + tables = dbResultsToDBTables(db.exec(sqlstr)); + } catch (e4) { + return null; } - return _typeof(obj); -} -function toDate(argument) { - requiredArgs(1, arguments); - var argStr = Object.prototype.toString.call(argument); - if (argument instanceof Date || _typeof(argument) === "object" && argStr === "[object Date]") { - return new Date(argument.getTime()); - } else if (typeof argument === "number" || argStr === "[object Number]") { - return new Date(argument); - } else { - if ((typeof argument === "string" || argStr === "[object String]") && typeof console !== "undefined") { - console.warn("Starting with v2.0.0-beta.1 date-fns doesn't accept strings as date arguments. Please use `parseISO` to parse strings. See: https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#string-arguments"); - console.warn(new Error().stack); - } - return new Date(NaN); + if (tables.length == 1) + return tables[0]; + return null; +}; +var deleteFromDB = (db, table, condition) => { + const sqlstr = `DELETE FROM "${table}" WHERE ${condition};`; + try { + db.exec(sqlstr); + } catch (e4) { + console.log(e4); } -} - -// node_modules/date-fns/esm/addDays/index.js -function addDays(dirtyDate, dirtyAmount) { - requiredArgs(2, arguments); - var date = toDate(dirtyDate); - var amount = toInteger(dirtyAmount); - if (isNaN(amount)) { - return new Date(NaN); +}; +var dropTable = (db, table) => { + const sqlstr = `DROP TABLE IF EXISTS "${table}";`; + try { + db.exec(sqlstr); + } catch (e4) { + console.log(e4); } - if (!amount) { - return date; +}; +var replaceDB = (db, tables) => { + const sqlstr = serializeSQLStatements(Object.keys(tables).map((t4) => { + const tableFields = tables[t4].cols; + const fieldQuery = serializeSQLFieldNames(uniq(tableFields).filter((f4) => f4).map((f4) => `'${sanitizeSQLStatement(f4)}' char`)); + const rowsQuery = tables[t4].rows.reduce((prev, curr) => { + return `${prev} REPLACE INTO "${t4}" VALUES (${serializeSQLValues(tableFields.map((c4) => { + var _a2; + return `'${sanitizeSQLStatement((_a2 = curr == null ? void 0 : curr[c4]) != null ? _a2 : "")}'`; + }))});`; + }, ""); + const idxQuery = tables[t4].uniques.filter((f4) => f4).reduce((p3, c4) => { + return `${p3} CREATE UNIQUE INDEX IF NOT EXISTS "idx_${t4}_${c4.replace( + /,/g, + "_" + )}" ON "${t4}"(${c4});`; + }, ""); + const insertQuery = `CREATE TABLE IF NOT EXISTS "${t4}" (${fieldQuery}); ${idxQuery} BEGIN TRANSACTION; ${rowsQuery} COMMIT;`; + return `DROP INDEX IF EXISTS "idx_${t4}__id"; DROP TABLE IF EXISTS "${t4}"; ${fieldQuery.length > 0 ? insertQuery : ""}`; + })); + try { + db.exec(sqlstr); + } catch (e4) { + console.log(sqlstr); + console.log(e4); } - date.setDate(date.getDate() + amount); - return date; -} +}; +var saveSpaceDBToPath = async (plugin, space, type, tables) => { + let returnValue = false; + if (type == "context") { + returnValue = await saveDBToPath(plugin, space.dbPath, tables); + plugin.index.reloadContext(space); + } else if (type == "frames") { + returnValue = await saveDBToPath(plugin, space.framePath, tables); + plugin.index.reloadFrames(space); + } + return returnValue; +}; +var saveDBToPath = async (plugin, path, tables) => { + const sqlJS = await plugin.sqlJS(); + const db = await getDB(plugin, sqlJS, path); + if (!db) { + db.close(); + return false; + } + replaceDB(db, tables); + await saveDBFile(plugin, path, db.export().buffer); + db.close(); + return true; +}; -// node_modules/date-fns/esm/addMonths/index.js -function addMonths(dirtyDate, dirtyAmount) { - requiredArgs(2, arguments); - var date = toDate(dirtyDate); - var amount = toInteger(dirtyAmount); - if (isNaN(amount)) { - return new Date(NaN); +// src/utils/contexts/mdb.ts +var dbTableToMDBTable = (table, schema, fields) => { + var _a2; + return { + schema, + cols: fields, + rows: (_a2 = table == null ? void 0 : table.rows) != null ? _a2 : [] + }; +}; +var updateFieldsToSchema = (fields, space) => { + const defaultFields = defaultFieldsForContext(space); + return [ + ...fields, + ...defaultFields.rows.filter( + (f4) => !fields.some((g4) => g4.name == f4.name && g4.schemaId == f4.schemaId) + ) + ]; +}; +var getContextMDB = async (plugin, space) => { + if (!space) + return null; + const sqlJS = await plugin.sqlJS(); + const buf = await getDBFile(plugin, space.dbPath, space.isRemote); + if (!buf) { + return null; } - if (!amount) { - return date; + const db = new sqlJS.Database(new Uint8Array(buf)); + await sanitizeTableSchema(plugin, db, space, "context"); + let fields; + let schemas; + try { + fields = dbResultsToDBTables( + db.exec(`SELECT * FROM m_fields`) + )[0].rows; + schemas = dbResultsToDBTables( + db.exec(`SELECT * FROM m_schema`) + )[0].rows; + } catch (e4) { + db.close(); + return null; } - var dayOfMonth = date.getDate(); - var endOfDesiredMonth = new Date(date.getTime()); - endOfDesiredMonth.setMonth(date.getMonth() + amount + 1, 0); - var daysInMonth = endOfDesiredMonth.getDate(); - if (dayOfMonth >= daysInMonth) { - return endOfDesiredMonth; - } else { - date.setFullYear(endOfDesiredMonth.getFullYear(), endOfDesiredMonth.getMonth(), dayOfMonth); - return date; + let dbTable; + try { + dbTable = schemas.filter((f4) => f4.type == "db").map((f4) => ({ [f4.id]: dbResultsToDBTables( + db.exec( + `SELECT * FROM "${f4.id}"` + ) + )[0] })).reduce((p3, c4) => ({ ...p3, ...c4 }), {}); + } catch (e4) { + db.close(); + return null; } -} - -// node_modules/date-fns/esm/addMilliseconds/index.js -function addMilliseconds(dirtyDate, dirtyAmount) { - requiredArgs(2, arguments); - var timestamp = toDate(dirtyDate).getTime(); - var amount = toInteger(dirtyAmount); - return new Date(timestamp + amount); -} - -// node_modules/date-fns/esm/_lib/defaultOptions/index.js -var defaultOptions = {}; -function getDefaultOptions() { - return defaultOptions; -} - -// node_modules/date-fns/esm/startOfWeek/index.js -function startOfWeek(dirtyDate, options) { - var _ref, _ref2, _ref3, _options$weekStartsOn, _options$locale, _options$locale$optio, _defaultOptions$local, _defaultOptions$local2; - requiredArgs(1, arguments); - var defaultOptions3 = getDefaultOptions(); - var weekStartsOn = toInteger((_ref = (_ref2 = (_ref3 = (_options$weekStartsOn = options === null || options === void 0 ? void 0 : options.weekStartsOn) !== null && _options$weekStartsOn !== void 0 ? _options$weekStartsOn : options === null || options === void 0 ? void 0 : (_options$locale = options.locale) === null || _options$locale === void 0 ? void 0 : (_options$locale$optio = _options$locale.options) === null || _options$locale$optio === void 0 ? void 0 : _options$locale$optio.weekStartsOn) !== null && _ref3 !== void 0 ? _ref3 : defaultOptions3.weekStartsOn) !== null && _ref2 !== void 0 ? _ref2 : (_defaultOptions$local = defaultOptions3.locale) === null || _defaultOptions$local === void 0 ? void 0 : (_defaultOptions$local2 = _defaultOptions$local.options) === null || _defaultOptions$local2 === void 0 ? void 0 : _defaultOptions$local2.weekStartsOn) !== null && _ref !== void 0 ? _ref : 0); - if (!(weekStartsOn >= 0 && weekStartsOn <= 6)) { - throw new RangeError("weekStartsOn must be between 0 and 6 inclusively"); + db.close(); + return { + schemas, + fields, + tables: dbTable + }; +}; +var getFramesMDB = async (plugin, space) => { + var _a2, _b2, _c2, _d2; + if (!space) + return null; + const sqlJS = await plugin.sqlJS(); + const buf = await getDBFile(plugin, space.framePath, space.isRemote); + if (!buf) { + return null; } - var date = toDate(dirtyDate); - var day = date.getDay(); - var diff = (day < weekStartsOn ? 7 : 0) + day - weekStartsOn; - date.setDate(date.getDate() - diff); - date.setHours(0, 0, 0, 0); - return date; -} - -// node_modules/date-fns/esm/startOfISOWeek/index.js -function startOfISOWeek(dirtyDate) { - requiredArgs(1, arguments); - return startOfWeek(dirtyDate, { - weekStartsOn: 1 - }); -} - -// node_modules/date-fns/esm/getISOWeekYear/index.js -function getISOWeekYear(dirtyDate) { - requiredArgs(1, arguments); - var date = toDate(dirtyDate); - var year = date.getFullYear(); - var fourthOfJanuaryOfNextYear = new Date(0); - fourthOfJanuaryOfNextYear.setFullYear(year + 1, 0, 4); - fourthOfJanuaryOfNextYear.setHours(0, 0, 0, 0); - var startOfNextYear = startOfISOWeek(fourthOfJanuaryOfNextYear); - var fourthOfJanuaryOfThisYear = new Date(0); - fourthOfJanuaryOfThisYear.setFullYear(year, 0, 4); - fourthOfJanuaryOfThisYear.setHours(0, 0, 0, 0); - var startOfThisYear = startOfISOWeek(fourthOfJanuaryOfThisYear); - if (date.getTime() >= startOfNextYear.getTime()) { - return year + 1; - } else if (date.getTime() >= startOfThisYear.getTime()) { - return year; - } else { - return year - 1; + const db = new sqlJS.Database(new Uint8Array(buf)); + let fields; + let schemas; + try { + fields = (_b2 = (_a2 = dbResultsToDBTables( + db.exec(`SELECT * FROM m_fields`) + )[0]) == null ? void 0 : _a2.rows) != null ? _b2 : []; + schemas = (_d2 = (_c2 = dbResultsToDBTables( + db.exec(`SELECT * FROM m_schema`) + )[0]) == null ? void 0 : _c2.rows) != null ? _d2 : []; + } catch (e4) { + console.log(e4); + db.close(); + return null; } -} - -// node_modules/date-fns/esm/startOfISOWeekYear/index.js -function startOfISOWeekYear(dirtyDate) { - requiredArgs(1, arguments); - var year = getISOWeekYear(dirtyDate); - var fourthOfJanuary = new Date(0); - fourthOfJanuary.setFullYear(year, 0, 4); - fourthOfJanuary.setHours(0, 0, 0, 0); - var date = startOfISOWeek(fourthOfJanuary); - return date; -} - -// node_modules/date-fns/esm/_lib/getTimezoneOffsetInMilliseconds/index.js -function getTimezoneOffsetInMilliseconds(date) { - var utcDate = new Date(Date.UTC(date.getFullYear(), date.getMonth(), date.getDate(), date.getHours(), date.getMinutes(), date.getSeconds(), date.getMilliseconds())); - utcDate.setUTCFullYear(date.getFullYear()); - return date.getTime() - utcDate.getTime(); -} - -// node_modules/date-fns/esm/startOfDay/index.js -function startOfDay(dirtyDate) { - requiredArgs(1, arguments); - var date = toDate(dirtyDate); - date.setHours(0, 0, 0, 0); - return date; -} - -// node_modules/date-fns/esm/differenceInCalendarDays/index.js -var MILLISECONDS_IN_DAY = 864e5; -function differenceInCalendarDays(dirtyDateLeft, dirtyDateRight) { - requiredArgs(2, arguments); - var startOfDayLeft = startOfDay(dirtyDateLeft); - var startOfDayRight = startOfDay(dirtyDateRight); - var timestampLeft = startOfDayLeft.getTime() - getTimezoneOffsetInMilliseconds(startOfDayLeft); - var timestampRight = startOfDayRight.getTime() - getTimezoneOffsetInMilliseconds(startOfDayRight); - return Math.round((timestampLeft - timestampRight) / MILLISECONDS_IN_DAY); -} - -// node_modules/date-fns/esm/addWeeks/index.js -function addWeeks(dirtyDate, dirtyAmount) { - requiredArgs(2, arguments); - var amount = toInteger(dirtyAmount); - var days = amount * 7; - return addDays(dirtyDate, days); -} - -// node_modules/date-fns/esm/addYears/index.js -function addYears(dirtyDate, dirtyAmount) { - requiredArgs(2, arguments); - var amount = toInteger(dirtyAmount); - return addMonths(dirtyDate, amount * 12); -} - -// node_modules/date-fns/esm/max/index.js -function _typeof2(obj) { - "@babel/helpers - typeof"; - if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { - _typeof2 = function _typeof5(obj2) { - return typeof obj2; - }; - } else { - _typeof2 = function _typeof5(obj2) { - return obj2 && typeof Symbol === "function" && obj2.constructor === Symbol && obj2 !== Symbol.prototype ? "symbol" : typeof obj2; + const dbTable = schemas.filter((f4) => f4.type == "frame" || f4.type == "listitem").map((f4) => { + try { + const table = dbResultsToDBTables( + db.exec( + `SELECT * FROM "${f4.id}"` + ) + )[0]; + return { [f4.id]: table }; + } catch (e4) { + return {}; + } + }).reduce((p3, c4) => ({ ...p3, ...c4 }), {}); + db.close(); + return { + schemas, + fields, + tables: dbTable + }; +}; +var dbPathForSpaceInfo = (spaceInfo, type) => type == "context" ? spaceInfo.dbPath : type == "frames" ? spaceInfo.framePath : null; +var getMDBTable = async (plugin, space, table, dbType) => { + if (!space) + return null; + const sqlJS = await plugin.sqlJS(); + const buf = await getDBFile(plugin, space.dbPath, space.isRemote); + if (!buf) { + return null; + } + const db = new sqlJS.Database(new Uint8Array(buf)); + await sanitizeTableSchema(plugin, db, space, dbType); + let fieldsTables; + let schema; + try { + fieldsTables = dbResultsToDBTables( + db.exec(`SELECT * FROM m_fields WHERE schemaId = '${table}'`) + ); + schema = dbResultsToDBTables( + db.exec(`SELECT * FROM m_schema WHERE id = '${table}'`) + )[0].rows[0]; + } catch (e4) { + db.close(); + return null; + } + if (fieldsTables.length == 0) { + db.close(); + return { + schema, + cols: [], + rows: [] }; } - return _typeof2(obj); -} -function max(dirtyDatesArray) { - requiredArgs(1, arguments); - var datesArray; - if (dirtyDatesArray && typeof dirtyDatesArray.forEach === "function") { - datesArray = dirtyDatesArray; - } else if (_typeof2(dirtyDatesArray) === "object" && dirtyDatesArray !== null) { - datesArray = Array.prototype.slice.call(dirtyDatesArray); - } else { - return new Date(NaN); + const fields = fieldsTables[0].rows.filter( + (f4) => f4.name.length > 0 + ); + const dbTable = dbResultsToDBTables( + db.exec( + `SELECT ${serializeSQLFieldNames( + fields.reduce((p3, c4) => [...p3, `"${c4.name}"`], []) + )} FROM "${table}"` + ) + ); + db.close(); + return dbTableToMDBTable( + dbTable[0], + schema, + schema.primary ? updateFieldsToSchema(fields, space) : fields + ); +}; +var deleteMDBTable = async (plugin, space, table, dbPath) => { + if (space.readOnly) + return false; + const sqlJS = await plugin.sqlJS(); + const buf = await getDBFile(plugin, dbPath, space.isRemote); + if (!buf) { + return false; } - var result; - datesArray.forEach(function(dirtyDate) { - var currentDate = toDate(dirtyDate); - if (result === void 0 || result < currentDate || isNaN(Number(currentDate))) { - result = currentDate; + const db = new sqlJS.Database(new Uint8Array(buf)); + deleteFromDB(db, "m_schema", `id = '${sanitizeSQLStatement(table)}'`); + deleteFromDB(db, "m_schema", `def = '${sanitizeSQLStatement(table)}'`); + deleteFromDB(db, "m_fields", `schemaId = '${sanitizeSQLStatement(table)}'`); + dropTable(db, table); + await saveDBFile(plugin, dbPath, db.export().buffer); + db.close(); + return true; +}; +var getMDBTableSchemas = async (plugin, space, dbType) => { + var _a2, _b2; + const sqlJS = await plugin.sqlJS(); + const buf = await getDBFile(plugin, dbPathForSpaceInfo(space, dbType), space.isRemote); + if (!buf) { + return null; + } + const db = new sqlJS.Database(new Uint8Array(buf)); + await sanitizeTableSchema(plugin, db, space, dbType); + const tables = db.exec(`SELECT * FROM m_schema`); + db.close(); + return ((_b2 = (_a2 = tables[0]) == null ? void 0 : _a2.values) != null ? _b2 : []).map((f4) => { + const [id2, name, type, def, predicate, primary] = f4; + return { id: id2, name, type, def, predicate, primary }; + }); +}; +var saveMDBToPath = async (plugin, context, mdb) => { + var _a2, _b2; + if (context.readOnly) + return; + const sqlJS = await plugin.sqlJS(); + const buf = await getDBFile(plugin, context.dbPath, context.isRemote); + if (!buf) { + return null; + } + const db = new sqlJS.Database(new Uint8Array(buf)); + const fieldsTables = dbResultsToDBTables( + db.exec(`SELECT * FROM m_fields WHERE schemaId != '${mdb.schema.id}'`) + ); + const schemaTables = dbResultsToDBTables( + db.exec(`SELECT * FROM m_schema`) + ); + const newSchemas = schemaTables.length > 0 ? { ...schemaTables[0], uniques: [], rows: [...schemaTables[0].rows.filter((f4) => f4.id != mdb.schema.id), mdb.schema] } : { ...defaultFolderSchema, rows: [...defaultFolderSchema.rows, mdb.schema] }; + const tables = { + m_schema: newSchemas, + m_fields: { + uniques: fieldSchema.uniques, + cols: fieldSchema.cols, + rows: [...(_b2 = (_a2 = fieldsTables[0]) == null ? void 0 : _a2.rows) != null ? _b2 : [], ...mdb.cols] + }, + [mdb.schema.id]: { + uniques: [], + cols: mdb.cols.map((c4) => c4.name), + rows: mdb.rows + } + }; + db.close(); + return saveSpaceDBToPath(plugin, context, "context", tables); +}; +var optionValuesForColumn = (column, table) => { + var _a2; + return uniq( + (_a2 = table == null ? void 0 : table.rows.reduce((p3, c4) => { + return [...p3, ...parseMultiString(c4[column])]; + }, [])) != null ? _a2 : [] + ); +}; +var defaultTableDataForContext = (plugin, space) => { + const files = [...plugin.index.getSpaceItems(space.path, true)]; + return { + ...defaultMDBTableForContext(space), + rows: files.map((f4) => ({ File: f4.path })) + }; +}; +var createFramesMDB = async (plugin, space) => { + const dbField = { + m_schema: defaultFramesSchema, + m_fields: { + uniques: fieldSchema.uniques, + cols: fieldSchema.cols, + rows: [] } - }); - return result || new Date(NaN); -} - -// node_modules/date-fns/esm/min/index.js -function _typeof3(obj) { - "@babel/helpers - typeof"; - if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { - _typeof3 = function _typeof5(obj2) { - return typeof obj2; - }; - } else { - _typeof3 = function _typeof5(obj2) { - return obj2 && typeof Symbol === "function" && obj2.constructor === Symbol && obj2 !== Symbol.prototype ? "symbol" : typeof obj2; - }; + }; + const result = await saveSpaceDBToPath(plugin, space, "frames", dbField); + if (result) { + await plugin.index.reloadFrames(space); + return true; } - return _typeof3(obj); -} -function min(dirtyDatesArray) { - requiredArgs(1, arguments); - var datesArray; - if (dirtyDatesArray && typeof dirtyDatesArray.forEach === "function") { - datesArray = dirtyDatesArray; - } else if (_typeof3(dirtyDatesArray) === "object" && dirtyDatesArray !== null) { - datesArray = Array.prototype.slice.call(dirtyDatesArray); - } else { - return new Date(NaN); + return false; +}; +var createContextMDB = async (plugin, space) => { + var _a2; + const table = defaultTableDataForContext(plugin, space); + if (table) { + const defaultFields = defaultFieldsForContext(space); + const defaultTable = defaultTablesForContext(space); + const dbField = { + ...defaultTable, + m_fields: { + uniques: defaultFields.uniques, + cols: defaultFields.cols, + rows: [...(_a2 = defaultFields.rows) != null ? _a2 : [], ...table.cols] + }, + [table.schema.id]: { + uniques: table.cols.filter((c4) => c4.unique == "true").map((c4) => c4.name), + cols: table.cols.map((c4) => c4.name), + rows: table.rows + } + }; + const result = await saveSpaceDBToPath(plugin, space, "context", dbField); + if (result) { + await plugin.index.reloadContext(space); + table.rows.map((f4) => getAbstractFileAtPath(plugin, f4.File)).forEach((f4) => f4 && plugin.index.reloadFile(f4, true)); + return true; + } + return false; } - var result; - datesArray.forEach(function(dirtyDate) { - var currentDate = toDate(dirtyDate); - if (result === void 0 || result > currentDate || isNaN(currentDate.getDate())) { - result = currentDate; + return false; +}; +var sanitizeTableSchema = async (plugin, db, space, dbType) => { + const tableRes = db.exec( + `SELECT name FROM sqlite_master WHERE type='table';` + ); + if (dbType == "context") { + if (!tableRes[0] || !tableRes[0].values.some((f4) => f4[0] == "m_schema") || !tableRes[0].values.some((f4) => f4[0] == "m_fields") || !tableRes[0].values.some((f4) => f4[0] == "files")) { + await createContextMDB(plugin, space); } - }); - return result || new Date(NaN); -} - -// node_modules/date-fns/esm/compareAsc/index.js -function compareAsc(dirtyDateLeft, dirtyDateRight) { - requiredArgs(2, arguments); - var dateLeft = toDate(dirtyDateLeft); - var dateRight = toDate(dirtyDateRight); - var diff = dateLeft.getTime() - dateRight.getTime(); - if (diff < 0) { - return -1; - } else if (diff > 0) { - return 1; } else { - return diff; + if (!tableRes[0] || !tableRes[0].values.some((f4) => f4[0] == "m_schema") || !tableRes[0].values.some((f4) => f4[0] == "m_fields")) { + await createFramesMDB(plugin, space); + } } -} - -// node_modules/date-fns/esm/isSameDay/index.js -function isSameDay(dirtyDateLeft, dirtyDateRight) { - requiredArgs(2, arguments); - var dateLeftStartOfDay = startOfDay(dirtyDateLeft); - var dateRightStartOfDay = startOfDay(dirtyDateRight); - return dateLeftStartOfDay.getTime() === dateRightStartOfDay.getTime(); -} - -// node_modules/date-fns/esm/isDate/index.js -function _typeof4(obj) { - "@babel/helpers - typeof"; - if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { - _typeof4 = function _typeof5(obj2) { - return typeof obj2; - }; - } else { - _typeof4 = function _typeof5(obj2) { - return obj2 && typeof Symbol === "function" && obj2.constructor === Symbol && obj2 !== Symbol.prototype ? "symbol" : typeof obj2; +}; +var createNewRow = (mdb, row, index) => { + if (index) { + return { + ...mdb, + rows: insert(mdb.rows, index, row) }; } - return _typeof4(obj); -} -function isDate(value) { - requiredArgs(1, arguments); - return value instanceof Date || _typeof4(value) === "object" && Object.prototype.toString.call(value) === "[object Date]"; -} - -// node_modules/date-fns/esm/isValid/index.js -function isValid(dirtyDate) { - requiredArgs(1, arguments); - if (!isDate(dirtyDate) && typeof dirtyDate !== "number") { - return false; - } - var date = toDate(dirtyDate); - return !isNaN(Number(date)); -} - -// node_modules/date-fns/esm/differenceInCalendarMonths/index.js -function differenceInCalendarMonths(dirtyDateLeft, dirtyDateRight) { - requiredArgs(2, arguments); - var dateLeft = toDate(dirtyDateLeft); - var dateRight = toDate(dirtyDateRight); - var yearDiff = dateLeft.getFullYear() - dateRight.getFullYear(); - var monthDiff = dateLeft.getMonth() - dateRight.getMonth(); - return yearDiff * 12 + monthDiff; -} - -// node_modules/date-fns/esm/differenceInCalendarWeeks/index.js -var MILLISECONDS_IN_WEEK = 6048e5; -function differenceInCalendarWeeks(dirtyDateLeft, dirtyDateRight, options) { - requiredArgs(2, arguments); - var startOfWeekLeft = startOfWeek(dirtyDateLeft, options); - var startOfWeekRight = startOfWeek(dirtyDateRight, options); - var timestampLeft = startOfWeekLeft.getTime() - getTimezoneOffsetInMilliseconds(startOfWeekLeft); - var timestampRight = startOfWeekRight.getTime() - getTimezoneOffsetInMilliseconds(startOfWeekRight); - return Math.round((timestampLeft - timestampRight) / MILLISECONDS_IN_WEEK); -} - -// node_modules/date-fns/esm/differenceInMilliseconds/index.js -function differenceInMilliseconds(dateLeft, dateRight) { - requiredArgs(2, arguments); - return toDate(dateLeft).getTime() - toDate(dateRight).getTime(); -} - -// node_modules/date-fns/esm/_lib/roundingMethods/index.js -var roundingMap = { - ceil: Math.ceil, - round: Math.round, - floor: Math.floor, - trunc: function trunc(value) { - return value < 0 ? Math.ceil(value) : Math.floor(value); + return { + ...mdb, + rows: [...mdb.rows, row] + }; +}; +var deleteSpaceFolder = async (plugin, space) => { + const spacePath = folderForSpace(space, plugin); + if (getAbstractFileAtPath(plugin, spacePath)) { + await deleteFile(plugin, getAbstractFileAtPath(plugin, spacePath)); } }; -var defaultRoundingMethod = "trunc"; -function getRoundingMethod(method) { - return method ? roundingMap[method] : roundingMap[defaultRoundingMethod]; -} - -// node_modules/date-fns/esm/endOfDay/index.js -function endOfDay(dirtyDate) { - requiredArgs(1, arguments); - var date = toDate(dirtyDate); - date.setHours(23, 59, 59, 999); - return date; -} - -// node_modules/date-fns/esm/endOfMonth/index.js -function endOfMonth(dirtyDate) { - requiredArgs(1, arguments); - var date = toDate(dirtyDate); - var month = date.getMonth(); - date.setFullYear(date.getFullYear(), month + 1, 0); - date.setHours(23, 59, 59, 999); - return date; -} - -// node_modules/date-fns/esm/isLastDayOfMonth/index.js -function isLastDayOfMonth(dirtyDate) { - requiredArgs(1, arguments); - var date = toDate(dirtyDate); - return endOfDay(date).getTime() === endOfMonth(date).getTime(); -} - -// node_modules/date-fns/esm/differenceInMonths/index.js -function differenceInMonths(dirtyDateLeft, dirtyDateRight) { - requiredArgs(2, arguments); - var dateLeft = toDate(dirtyDateLeft); - var dateRight = toDate(dirtyDateRight); - var sign = compareAsc(dateLeft, dateRight); - var difference = Math.abs(differenceInCalendarMonths(dateLeft, dateRight)); - var result; - if (difference < 1) { - result = 0; - } else { - if (dateLeft.getMonth() === 1 && dateLeft.getDate() > 27) { - dateLeft.setDate(30); +var spaceFolderDelete = (space) => { + app.workspace.iterateLeaves((leaf) => { + if (leaf.view.getViewType() == SPACE_VIEW_TYPE && leaf.view.getState().path == space) { + leaf.setViewState({ type: "empty" }); } - dateLeft.setMonth(dateLeft.getMonth() - sign * difference); - var isLastMonthNotFull = compareAsc(dateLeft, dateRight) === -sign; - if (isLastDayOfMonth(toDate(dirtyDateLeft)) && difference === 1 && compareAsc(dirtyDateLeft, dateRight) === 1) { - isLastMonthNotFull = false; + }, app.workspace["rootSplit"]); +}; +var renameSpaceFolder = async (plugin, space, newSpace) => { + const spacePath = folderForSpace(space, plugin); + if (getAbstractFileAtPath(plugin, spacePath)) { + if (!getAbstractFileAtPath( + plugin, + folderForSpace(newSpace, plugin) + )) { + await renameFile( + plugin, + getAbstractFileAtPath(plugin, spacePath), + newSpace + ); + } else { + await deleteFile(plugin, getAbstractFileAtPath(plugin, spacePath)); } - result = sign * (difference - Number(isLastMonthNotFull)); } - return result === 0 ? 0 : result; -} - -// node_modules/date-fns/esm/differenceInSeconds/index.js -function differenceInSeconds(dateLeft, dateRight, options) { - requiredArgs(2, arguments); - var diff = differenceInMilliseconds(dateLeft, dateRight) / 1e3; - return getRoundingMethod(options === null || options === void 0 ? void 0 : options.roundingMethod)(diff); -} - -// node_modules/date-fns/esm/startOfMonth/index.js -function startOfMonth(dirtyDate) { - requiredArgs(1, arguments); - var date = toDate(dirtyDate); - date.setDate(1); - date.setHours(0, 0, 0, 0); - return date; -} - -// node_modules/date-fns/esm/startOfYear/index.js -function startOfYear(dirtyDate) { - requiredArgs(1, arguments); - var cleanDate = toDate(dirtyDate); - var date = new Date(0); - date.setFullYear(cleanDate.getFullYear(), 0, 1); - date.setHours(0, 0, 0, 0); - return date; -} +}; -// node_modules/date-fns/esm/endOfWeek/index.js -function endOfWeek(dirtyDate, options) { - var _ref, _ref2, _ref3, _options$weekStartsOn, _options$locale, _options$locale$optio, _defaultOptions$local, _defaultOptions$local2; - requiredArgs(1, arguments); - var defaultOptions3 = getDefaultOptions(); - var weekStartsOn = toInteger((_ref = (_ref2 = (_ref3 = (_options$weekStartsOn = options === null || options === void 0 ? void 0 : options.weekStartsOn) !== null && _options$weekStartsOn !== void 0 ? _options$weekStartsOn : options === null || options === void 0 ? void 0 : (_options$locale = options.locale) === null || _options$locale === void 0 ? void 0 : (_options$locale$optio = _options$locale.options) === null || _options$locale$optio === void 0 ? void 0 : _options$locale$optio.weekStartsOn) !== null && _ref3 !== void 0 ? _ref3 : defaultOptions3.weekStartsOn) !== null && _ref2 !== void 0 ? _ref2 : (_defaultOptions$local = defaultOptions3.locale) === null || _defaultOptions$local === void 0 ? void 0 : (_defaultOptions$local2 = _defaultOptions$local.options) === null || _defaultOptions$local2 === void 0 ? void 0 : _defaultOptions$local2.weekStartsOn) !== null && _ref !== void 0 ? _ref : 0); - if (!(weekStartsOn >= 0 && weekStartsOn <= 6)) { - throw new RangeError("weekStartsOn must be between 0 and 6 inclusively"); +// src/utils/frames/mdb.ts +var getMFrameTables = async (plugin, space) => { + if (!frames) + return null; + const sqlJS = await plugin.sqlJS(); + const buf = await getDBFile(plugin, space.framePath, space.isRemote); + if (!buf) { + return null; } - var date = toDate(dirtyDate); - var day = date.getDay(); - var diff = (day < weekStartsOn ? -7 : 0) + 6 - (day - weekStartsOn); - date.setDate(date.getDate() + diff); - date.setHours(23, 59, 59, 999); - return date; -} - -// node_modules/date-fns/esm/endOfISOWeek/index.js -function endOfISOWeek(dirtyDate) { - requiredArgs(1, arguments); - return endOfWeek(dirtyDate, { - weekStartsOn: 1 + const db = new sqlJS.Database(new Uint8Array(buf)); + const schemas = dbResultsToDBTables( + db.exec(`SELECT * FROM m_schema`) + )[0].rows; + const mdbTables = {}; + schemas.forEach((schema) => { + var _a2, _b2; + let fieldsTables; + try { + fieldsTables = dbResultsToDBTables( + db.exec(`SELECT * FROM m_fields WHERE schemaId = '${schema.id}'`) + ); + } catch (e4) { + return; + } + const fields = ((_b2 = (_a2 = fieldsTables == null ? void 0 : fieldsTables[0]) == null ? void 0 : _a2.rows) != null ? _b2 : []).filter( + (f4) => f4.name.length > 0 + ); + let dbTable; + try { + dbTable = dbResultsToDBTables(db.exec(`SELECT * FROM "${schema.id}"`)); + mdbTables[schema.id] = dbTableToMDBTable( + dbTable[0], + schema, + fields + ); + } catch (e4) { + mdbTables[schema.id] = { + schema, + cols: fields, + rows: [] + }; + return; + } }); -} - -// node_modules/date-fns/esm/subMilliseconds/index.js -function subMilliseconds(dirtyDate, dirtyAmount) { - requiredArgs(2, arguments); - var amount = toInteger(dirtyAmount); - return addMilliseconds(dirtyDate, -amount); -} + db.close(); + return mdbTables; +}; +var saveMFramesToPath = async (plugin, space, mdb) => { + var _a2, _b2, _c2; + if (space.readOnly) + return; + const sqlJS = await plugin.sqlJS(); + const buf = await getDBFile(plugin, space.framePath, space.isRemote); + if (!buf) { + return null; + } + const db = new sqlJS.Database(new Uint8Array(buf)); + const fieldsTables = dbResultsToDBTables( + db.exec(`SELECT * FROM m_fields WHERE schemaId != '${mdb.schema.id}'`) + ); + const schemaTables = dbResultsToDBTables( + db.exec(`SELECT * FROM m_schema`) + ); + const newSchemas = ((_a2 = schemaTables[0]) == null ? void 0 : _a2.rows) ? { ...schemaTables[0], uniques: [], rows: [...schemaTables[0].rows.filter((f4) => f4.id != mdb.schema.id), mdb.schema] } : { ...defaultFramesSchema, rows: [...defaultFramesSchema.rows, mdb.schema] }; + const tables = { + m_schema: newSchemas, + m_fields: { + uniques: fieldSchema.uniques, + cols: fieldSchema.cols, + rows: [...(_c2 = (_b2 = fieldsTables[0]) == null ? void 0 : _b2.rows) != null ? _c2 : [], ...mdb.cols] + }, + [mdb.schema.id]: { + uniques: defaultFrameSchema.uniques, + cols: defaultFrameSchema.cols, + rows: mdb.rows + } + }; + db.close(); + return saveSpaceDBToPath(plugin, space, "frames", tables); +}; -// node_modules/date-fns/esm/_lib/getUTCDayOfYear/index.js -var MILLISECONDS_IN_DAY2 = 864e5; -function getUTCDayOfYear(dirtyDate) { - requiredArgs(1, arguments); - var date = toDate(dirtyDate); - var timestamp = date.getTime(); - date.setUTCMonth(0, 1); - date.setUTCHours(0, 0, 0, 0); - var startOfYearTimestamp = date.getTime(); - var difference = timestamp - startOfYearTimestamp; - return Math.floor(difference / MILLISECONDS_IN_DAY2) + 1; -} +// src/context/SpaceContext.tsx +var SpaceContext = F({ + spaceInfo: null, + readMode: false, + spaceCache: null +}); +var SpaceContextProvider = (props2) => { + var _a2; + const readMode = (_a2 = props2.space) == null ? void 0 : _a2.readOnly; + const spaceInfo = F2(() => { + return props2.space; + }, [props2.space]); + const [spaceCache, setSpaceCache] = h2(null); + const reloadSpace = () => { + const spaceCache2 = props2.plugin.index.spacesIndex.get(spaceInfo.path); + if (spaceCache2) { + setSpaceCache(spaceCache2); + } + }; + p2(() => { + reloadSpace(); + }, [spaceInfo]); + const refreshSpace = T2( + async (evt) => { + if (evt.detail.type == "space") { + if (evt.detail.name == spaceInfo.path) { + reloadSpace(); + } + } + }, + [props2.plugin, spaceInfo] + ); + p2(() => { + window.addEventListener(eventTypes.spacesChange, refreshSpace); + return () => { + window.removeEventListener(eventTypes.spacesChange, refreshSpace); + }; + }, [refreshSpace]); + return /* @__PURE__ */ Cn.createElement(SpaceContext.Provider, { + value: { + spaceCache, + readMode, + spaceInfo + } + }, props2.children); +}; -// node_modules/date-fns/esm/_lib/startOfUTCISOWeek/index.js -function startOfUTCISOWeek(dirtyDate) { - requiredArgs(1, arguments); - var weekStartsOn = 1; - var date = toDate(dirtyDate); - var day = date.getUTCDay(); - var diff = (day < weekStartsOn ? 7 : 0) + day - weekStartsOn; - date.setUTCDate(date.getUTCDate() - diff); - date.setUTCHours(0, 0, 0, 0); - return date; -} +// src/context/FramesMDBContext.tsx +var FramesMDBContext = F({ + frameSchemas: [], + frames: [], + tableData: null, + saveFrame: () => null, + frameSchema: null, + setFrameSchema: () => null, + saveSchema: () => null, + deleteSchema: () => null, + dbFileExists: false, + getMDBData: () => null +}); +var FramesMDBProvider = (props2) => { + const [dbFileExists, setDBFileExists] = h2(false); + const [schemaTable, setSchemaTable] = h2(null); + const schemas = F2( + () => { + var _a2, _b2; + return (_b2 = ((_a2 = schemaTable == null ? void 0 : schemaTable.rows) != null ? _a2 : []).map( + (f4) => mdbSchemaToFrameSchema(f4) + )) != null ? _b2 : []; + }, + [schemaTable] + ); + const frames2 = schemas.filter((f4) => f4.type == "frame"); + const [frameData, setFrameData] = h2(null); + const [frameSchema, setFrameSchema] = h2(null); + const tableData = F2(() => { + return frameData == null ? void 0 : frameData[frameSchema == null ? void 0 : frameSchema.id]; + }, [frameData, frameSchema]); + const defaultSchema = defaultFramesSchema; + const { spaceInfo, readMode } = q2(SpaceContext); + const deleteSchema = async (table) => { + if (table.primary) + return; + const deleteResult = await deleteMDBTable( + props2.plugin, + spaceInfo, + table.id, + spaceInfo.framePath + ); + if (deleteResult) { + const newSchemaTable = { + ...schemaTable, + rows: schemaTable.rows.filter( + (f4) => f4.id != table.id && f4.def != table.id + ) + }; + setSchemaTable(newSchemaTable); + } + }; + const saveSchema = async (table) => { + const newSchema = schemaTable.rows.find((f4) => f4.id == table.id) ? true : false; + const newSchemaTable = newSchema ? { + ...schemaTable, + rows: schemaTable.rows.map( + (f4) => f4.id == table.id ? frameSchemaToMDBSchema(table) : f4 + ) + } : { + ...schemaTable, + rows: [...schemaTable.rows, frameSchemaToMDBSchema(table)] + }; + if (!spaceInfo.readOnly) { + if (!dbFileExists) { + const dbTables = { + ...mdbFrameToDBTables(DefaultMDBTables, { + m_fields: fieldSchema.uniques, + main: defaultFrameSchema.uniques + }), + ...schemasAndFields(DefaultMDBTables), + m_schema: newSchemaTable + }; + await saveSpaceDBToPath( + props2.plugin, + spaceInfo, + "frames", + dbTables + ).then((f4) => { + setDBFileExists(true); + f4 ? getMDBData() : new import_obsidian5.Notice("DB ERROR"); + }); + setDBFileExists(true); + } else { + await saveSpaceDBToPath(props2.plugin, spaceInfo, "frames", { + m_schema: newSchemaTable + }); + } + } + if (table.id == (frameSchema == null ? void 0 : frameSchema.id)) { + setFrameSchema(table); + setFrameData((f4) => ({ + ...f4, + [table.id]: { + ...f4[table.id], + schema: frameSchemaToMDBSchema(table) + } + })); + } + setSchemaTable(newSchemaTable); + }; + p2(() => { + if (schemaTable) + getMDBData().then((f4) => { + if (f4 && Object.keys(f4).length > 0) { + setFrameData(f4); + } + }); + }, [schemaTable]); + p2(() => { + var _a2, _b2; + if (schemaTable) { + if (props2.schema) { + if ((frameSchema == null ? void 0 : frameSchema.id) != props2.schema) { + const preselectSchema = schemaTable.rows.find( + (g4) => g4.id == props2.schema + ); + if (preselectSchema) { + if (preselectSchema.type == "frame" || preselectSchema.type == "listitem") { + setFrameSchema(mdbSchemaToFrameSchema(preselectSchema)); + return; + } else { + const preselectDBSchema = schemaTable.rows.find( + (g4) => g4.id == preselectSchema.def + ); + if (preselectDBSchema) { + setFrameSchema(mdbSchemaToFrameSchema(preselectDBSchema)); + return; + } + } + } else { + const newSchema = { + id: uniqueNameFromString( + sanitizeTableName(props2.schema), + schemaTable.rows.map((g4) => g4.id) + ), + name: props2.schema, + type: "frame" + }; + setFrameSchema(newSchema); + } + } + } else { + if (!frameSchema) { + setFrameSchema( + mdbSchemaToFrameSchema( + (_a2 = schemaTable.rows) == null ? void 0 : _a2.find((g4) => g4.type == "frame") + ) + ); + } else { + setFrameSchema( + mdbSchemaToFrameSchema( + (_b2 = schemaTable.rows) == null ? void 0 : _b2.find((g4) => g4.id == frameSchema.id) + ) + ); + } + } + } + }, [schemaTable]); + const loadTables = T2(async () => { + if (!spaceInfo) + return; + const mdbExists = await props2.plugin.app.vault.adapter.exists( + spaceInfo.framePath + ); + if (mdbExists || spaceInfo.isRemote) { + setDBFileExists(true); + getMDBTableSchemas(props2.plugin, spaceInfo, "frames").then((f4) => { + if (f4) + setSchemaTable((prev) => ({ + ...defaultSchema, + rows: f4 + })); + }); + } else { + if (props2.schema) { + setSchemaTable((prev) => defaultSchema); + } else { + setSchemaTable((prev) => defaultSchema); + } + } + }, [defaultSchema, props2.plugin, props2.schema, spaceInfo]); + const refreshSpace = T2( + async (evt) => { + if (evt.detail.type == "frames" && evt.detail.name == spaceInfo.path) { + loadTables(); + return; + } + }, + [spaceInfo, loadTables] + ); + p2(() => { + window.addEventListener(eventTypes.spacesChange, refreshSpace); + return () => { + window.removeEventListener(eventTypes.spacesChange, refreshSpace); + }; + }, [refreshSpace]); + const getMDBData = async () => { + if (dbFileExists) { + return await getMFrameTables(props2.plugin, spaceInfo); + } else { + return DefaultMDBTables; + } + }; + p2(() => { + loadTables(); + }, [spaceInfo]); + const saveFrame = async (newTable) => { + if (spaceInfo.readOnly) + return; + if (!dbFileExists) { + const dbTables = { + ...mdbFrameToDBTables(DefaultMDBTables, { + m_fields: fieldSchema.uniques, + main: defaultFrameSchema.uniques + }), + ...schemasAndFields(DefaultMDBTables), + [newTable.schema.id]: { + uniques: defaultFrameSchema.uniques, + cols: defaultFrameSchema.cols, + rows: newTable.rows + } + }; + await saveSpaceDBToPath(props2.plugin, spaceInfo, "frames", dbTables).then( + (f4) => { + setDBFileExists(true); + f4 ? getMDBData() : new import_obsidian5.Notice("DB ERROR"); + } + ); + } else { + await saveMFramesToPath( + props2.plugin, + spaceInfo, + newTable + ).then((f4) => { + f4 ? setFrameData((p3) => ({ + ...p3, + [newTable.schema.id]: newTable + })) : new import_obsidian5.Notice("DB ERROR"); + }); + } + }; + return /* @__PURE__ */ Cn.createElement(FramesMDBContext.Provider, { + value: { + frames: frames2, + tableData, + saveFrame, + frameSchemas: schemas, + saveSchema, + deleteSchema, + dbFileExists, + frameSchema, + setFrameSchema, + getMDBData + } + }, props2.children); +}; -// node_modules/date-fns/esm/_lib/getUTCISOWeekYear/index.js -function getUTCISOWeekYear(dirtyDate) { - requiredArgs(1, arguments); - var date = toDate(dirtyDate); - var year = date.getUTCFullYear(); - var fourthOfJanuaryOfNextYear = new Date(0); - fourthOfJanuaryOfNextYear.setUTCFullYear(year + 1, 0, 4); - fourthOfJanuaryOfNextYear.setUTCHours(0, 0, 0, 0); - var startOfNextYear = startOfUTCISOWeek(fourthOfJanuaryOfNextYear); - var fourthOfJanuaryOfThisYear = new Date(0); - fourthOfJanuaryOfThisYear.setUTCFullYear(year, 0, 4); - fourthOfJanuaryOfThisYear.setUTCHours(0, 0, 0, 0); - var startOfThisYear = startOfUTCISOWeek(fourthOfJanuaryOfThisYear); - if (date.getTime() >= startOfNextYear.getTime()) { - return year + 1; - } else if (date.getTime() >= startOfThisYear.getTime()) { - return year; - } else { - return year - 1; +// src/components/SpaceView/Contexts/SpaceView.tsx +var import_obsidian47 = require("obsidian"); + +// node_modules/@dnd-kit/utilities/dist/utilities.esm.js +function useCombinedRefs() { + for (var _len = arguments.length, refs = new Array(_len), _key = 0; _key < _len; _key++) { + refs[_key] = arguments[_key]; } + return F2( + () => (node) => { + refs.forEach((ref2) => ref2(node)); + }, + refs + ); } - -// node_modules/date-fns/esm/_lib/startOfUTCISOWeekYear/index.js -function startOfUTCISOWeekYear(dirtyDate) { - requiredArgs(1, arguments); - var year = getUTCISOWeekYear(dirtyDate); - var fourthOfJanuary = new Date(0); - fourthOfJanuary.setUTCFullYear(year, 0, 4); - fourthOfJanuary.setUTCHours(0, 0, 0, 0); - var date = startOfUTCISOWeek(fourthOfJanuary); - return date; +var canUseDOM = typeof window !== "undefined" && typeof window.document !== "undefined" && typeof window.document.createElement !== "undefined"; +function isWindow(element) { + const elementString = Object.prototype.toString.call(element); + return elementString === "[object Window]" || elementString === "[object global]"; } - -// node_modules/date-fns/esm/_lib/getUTCISOWeek/index.js -var MILLISECONDS_IN_WEEK2 = 6048e5; -function getUTCISOWeek(dirtyDate) { - requiredArgs(1, arguments); - var date = toDate(dirtyDate); - var diff = startOfUTCISOWeek(date).getTime() - startOfUTCISOWeekYear(date).getTime(); - return Math.round(diff / MILLISECONDS_IN_WEEK2) + 1; +function isNode(node) { + return "nodeType" in node; } - -// node_modules/date-fns/esm/_lib/startOfUTCWeek/index.js -function startOfUTCWeek(dirtyDate, options) { - var _ref, _ref2, _ref3, _options$weekStartsOn, _options$locale, _options$locale$optio, _defaultOptions$local, _defaultOptions$local2; - requiredArgs(1, arguments); - var defaultOptions3 = getDefaultOptions(); - var weekStartsOn = toInteger((_ref = (_ref2 = (_ref3 = (_options$weekStartsOn = options === null || options === void 0 ? void 0 : options.weekStartsOn) !== null && _options$weekStartsOn !== void 0 ? _options$weekStartsOn : options === null || options === void 0 ? void 0 : (_options$locale = options.locale) === null || _options$locale === void 0 ? void 0 : (_options$locale$optio = _options$locale.options) === null || _options$locale$optio === void 0 ? void 0 : _options$locale$optio.weekStartsOn) !== null && _ref3 !== void 0 ? _ref3 : defaultOptions3.weekStartsOn) !== null && _ref2 !== void 0 ? _ref2 : (_defaultOptions$local = defaultOptions3.locale) === null || _defaultOptions$local === void 0 ? void 0 : (_defaultOptions$local2 = _defaultOptions$local.options) === null || _defaultOptions$local2 === void 0 ? void 0 : _defaultOptions$local2.weekStartsOn) !== null && _ref !== void 0 ? _ref : 0); - if (!(weekStartsOn >= 0 && weekStartsOn <= 6)) { - throw new RangeError("weekStartsOn must be between 0 and 6 inclusively"); +function getWindow(target) { + var _target$ownerDocument, _target$ownerDocument2; + if (!target) { + return window; } - var date = toDate(dirtyDate); - var day = date.getUTCDay(); - var diff = (day < weekStartsOn ? 7 : 0) + day - weekStartsOn; - date.setUTCDate(date.getUTCDate() - diff); - date.setUTCHours(0, 0, 0, 0); - return date; -} - -// node_modules/date-fns/esm/_lib/getUTCWeekYear/index.js -function getUTCWeekYear(dirtyDate, options) { - var _ref, _ref2, _ref3, _options$firstWeekCon, _options$locale, _options$locale$optio, _defaultOptions$local, _defaultOptions$local2; - requiredArgs(1, arguments); - var date = toDate(dirtyDate); - var year = date.getUTCFullYear(); - var defaultOptions3 = getDefaultOptions(); - var firstWeekContainsDate = toInteger((_ref = (_ref2 = (_ref3 = (_options$firstWeekCon = options === null || options === void 0 ? void 0 : options.firstWeekContainsDate) !== null && _options$firstWeekCon !== void 0 ? _options$firstWeekCon : options === null || options === void 0 ? void 0 : (_options$locale = options.locale) === null || _options$locale === void 0 ? void 0 : (_options$locale$optio = _options$locale.options) === null || _options$locale$optio === void 0 ? void 0 : _options$locale$optio.firstWeekContainsDate) !== null && _ref3 !== void 0 ? _ref3 : defaultOptions3.firstWeekContainsDate) !== null && _ref2 !== void 0 ? _ref2 : (_defaultOptions$local = defaultOptions3.locale) === null || _defaultOptions$local === void 0 ? void 0 : (_defaultOptions$local2 = _defaultOptions$local.options) === null || _defaultOptions$local2 === void 0 ? void 0 : _defaultOptions$local2.firstWeekContainsDate) !== null && _ref !== void 0 ? _ref : 1); - if (!(firstWeekContainsDate >= 1 && firstWeekContainsDate <= 7)) { - throw new RangeError("firstWeekContainsDate must be between 1 and 7 inclusively"); + if (isWindow(target)) { + return target; } - var firstWeekOfNextYear = new Date(0); - firstWeekOfNextYear.setUTCFullYear(year + 1, 0, firstWeekContainsDate); - firstWeekOfNextYear.setUTCHours(0, 0, 0, 0); - var startOfNextYear = startOfUTCWeek(firstWeekOfNextYear, options); - var firstWeekOfThisYear = new Date(0); - firstWeekOfThisYear.setUTCFullYear(year, 0, firstWeekContainsDate); - firstWeekOfThisYear.setUTCHours(0, 0, 0, 0); - var startOfThisYear = startOfUTCWeek(firstWeekOfThisYear, options); - if (date.getTime() >= startOfNextYear.getTime()) { - return year + 1; - } else if (date.getTime() >= startOfThisYear.getTime()) { - return year; - } else { - return year - 1; + if (!isNode(target)) { + return window; } + return (_target$ownerDocument = (_target$ownerDocument2 = target.ownerDocument) == null ? void 0 : _target$ownerDocument2.defaultView) != null ? _target$ownerDocument : window; } - -// node_modules/date-fns/esm/_lib/startOfUTCWeekYear/index.js -function startOfUTCWeekYear(dirtyDate, options) { - var _ref, _ref2, _ref3, _options$firstWeekCon, _options$locale, _options$locale$optio, _defaultOptions$local, _defaultOptions$local2; - requiredArgs(1, arguments); - var defaultOptions3 = getDefaultOptions(); - var firstWeekContainsDate = toInteger((_ref = (_ref2 = (_ref3 = (_options$firstWeekCon = options === null || options === void 0 ? void 0 : options.firstWeekContainsDate) !== null && _options$firstWeekCon !== void 0 ? _options$firstWeekCon : options === null || options === void 0 ? void 0 : (_options$locale = options.locale) === null || _options$locale === void 0 ? void 0 : (_options$locale$optio = _options$locale.options) === null || _options$locale$optio === void 0 ? void 0 : _options$locale$optio.firstWeekContainsDate) !== null && _ref3 !== void 0 ? _ref3 : defaultOptions3.firstWeekContainsDate) !== null && _ref2 !== void 0 ? _ref2 : (_defaultOptions$local = defaultOptions3.locale) === null || _defaultOptions$local === void 0 ? void 0 : (_defaultOptions$local2 = _defaultOptions$local.options) === null || _defaultOptions$local2 === void 0 ? void 0 : _defaultOptions$local2.firstWeekContainsDate) !== null && _ref !== void 0 ? _ref : 1); - var year = getUTCWeekYear(dirtyDate, options); - var firstWeek = new Date(0); - firstWeek.setUTCFullYear(year, 0, firstWeekContainsDate); - firstWeek.setUTCHours(0, 0, 0, 0); - var date = startOfUTCWeek(firstWeek, options); - return date; -} - -// node_modules/date-fns/esm/_lib/getUTCWeek/index.js -var MILLISECONDS_IN_WEEK3 = 6048e5; -function getUTCWeek(dirtyDate, options) { - requiredArgs(1, arguments); - var date = toDate(dirtyDate); - var diff = startOfUTCWeek(date, options).getTime() - startOfUTCWeekYear(date, options).getTime(); - return Math.round(diff / MILLISECONDS_IN_WEEK3) + 1; +function isDocument(node) { + const { + Document + } = getWindow(node); + return node instanceof Document; } - -// node_modules/date-fns/esm/_lib/addLeadingZeros/index.js -function addLeadingZeros(number, targetLength) { - var sign = number < 0 ? "-" : ""; - var output = Math.abs(number).toString(); - while (output.length < targetLength) { - output = "0" + output; +function isHTMLElement(node) { + if (isWindow(node)) { + return false; } - return sign + output; + return node instanceof getWindow(node).HTMLElement; } - -// node_modules/date-fns/esm/_lib/format/lightFormatters/index.js -var formatters = { - y: function y3(date, token) { - var signedYear = date.getUTCFullYear(); - var year = signedYear > 0 ? signedYear : 1 - signedYear; - return addLeadingZeros(token === "yy" ? year % 100 : year, token.length); - }, - M: function M3(date, token) { - var month = date.getUTCMonth(); - return token === "M" ? String(month + 1) : addLeadingZeros(month + 1, 2); - }, - d: function d3(date, token) { - return addLeadingZeros(date.getUTCDate(), token.length); - }, - a: function a3(date, token) { - var dayPeriodEnumValue = date.getUTCHours() / 12 >= 1 ? "pm" : "am"; - switch (token) { - case "a": - case "aa": - return dayPeriodEnumValue.toUpperCase(); - case "aaa": - return dayPeriodEnumValue; - case "aaaaa": - return dayPeriodEnumValue[0]; - case "aaaa": - default: - return dayPeriodEnumValue === "am" ? "a.m." : "p.m."; - } - }, - h: function h3(date, token) { - return addLeadingZeros(date.getUTCHours() % 12 || 12, token.length); - }, - H: function H3(date, token) { - return addLeadingZeros(date.getUTCHours(), token.length); - }, - m: function m3(date, token) { - return addLeadingZeros(date.getUTCMinutes(), token.length); - }, - s: function s3(date, token) { - return addLeadingZeros(date.getUTCSeconds(), token.length); - }, - S: function S2(date, token) { - var numberOfDigits = token.length; - var milliseconds = date.getUTCMilliseconds(); - var fractionalSeconds = Math.floor(milliseconds * Math.pow(10, numberOfDigits - 3)); - return addLeadingZeros(fractionalSeconds, token.length); +function isSVGElement(node) { + return node instanceof getWindow(node).SVGElement; +} +function getOwnerDocument(target) { + if (!target) { + return document; } -}; -var lightFormatters_default = formatters; - -// node_modules/date-fns/esm/_lib/format/formatters/index.js -var dayPeriodEnum = { - am: "am", - pm: "pm", - midnight: "midnight", - noon: "noon", - morning: "morning", - afternoon: "afternoon", - evening: "evening", - night: "night" -}; -var formatters2 = { - G: function G2(date, token, localize2) { - var era = date.getUTCFullYear() > 0 ? 1 : 0; - switch (token) { - case "G": - case "GG": - case "GGG": - return localize2.era(era, { - width: "abbreviated" - }); - case "GGGGG": - return localize2.era(era, { - width: "narrow" - }); - case "GGGG": - default: - return localize2.era(era, { - width: "wide" - }); - } - }, - y: function y4(date, token, localize2) { - if (token === "yo") { - var signedYear = date.getUTCFullYear(); - var year = signedYear > 0 ? signedYear : 1 - signedYear; - return localize2.ordinalNumber(year, { - unit: "year" - }); - } - return lightFormatters_default.y(date, token); - }, - Y: function Y2(date, token, localize2, options) { - var signedWeekYear = getUTCWeekYear(date, options); - var weekYear = signedWeekYear > 0 ? signedWeekYear : 1 - signedWeekYear; - if (token === "YY") { - var twoDigitYear = weekYear % 100; - return addLeadingZeros(twoDigitYear, 2); - } - if (token === "Yo") { - return localize2.ordinalNumber(weekYear, { - unit: "year" - }); + if (isWindow(target)) { + return target.document; + } + if (!isNode(target)) { + return document; + } + if (isDocument(target)) { + return target; + } + if (isHTMLElement(target)) { + return target.ownerDocument; + } + return document; +} +var useIsomorphicLayoutEffect = canUseDOM ? y2 : p2; +function useEvent(handler) { + const handlerRef = _2(handler); + useIsomorphicLayoutEffect(() => { + handlerRef.current = handler; + }); + return T2(function() { + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; } - return addLeadingZeros(weekYear, token.length); - }, - R: function R2(date, token) { - var isoWeekYear = getUTCISOWeekYear(date); - return addLeadingZeros(isoWeekYear, token.length); - }, - u: function u3(date, token) { - var year = date.getUTCFullYear(); - return addLeadingZeros(year, token.length); - }, - Q: function Q2(date, token, localize2) { - var quarter = Math.ceil((date.getUTCMonth() + 1) / 3); - switch (token) { - case "Q": - return String(quarter); - case "QQ": - return addLeadingZeros(quarter, 2); - case "Qo": - return localize2.ordinalNumber(quarter, { - unit: "quarter" - }); - case "QQQ": - return localize2.quarter(quarter, { - width: "abbreviated", - context: "formatting" - }); - case "QQQQQ": - return localize2.quarter(quarter, { - width: "narrow", - context: "formatting" - }); - case "QQQQ": - default: - return localize2.quarter(quarter, { - width: "wide", - context: "formatting" - }); + return handlerRef.current == null ? void 0 : handlerRef.current(...args); + }, []); +} +function useInterval() { + const intervalRef = _2(null); + const set = T2((listener, duration) => { + intervalRef.current = setInterval(listener, duration); + }, []); + const clear = T2(() => { + if (intervalRef.current !== null) { + clearInterval(intervalRef.current); + intervalRef.current = null; } - }, - q: function q4(date, token, localize2) { - var quarter = Math.ceil((date.getUTCMonth() + 1) / 3); - switch (token) { - case "q": - return String(quarter); - case "qq": - return addLeadingZeros(quarter, 2); - case "qo": - return localize2.ordinalNumber(quarter, { - unit: "quarter" - }); - case "qqq": - return localize2.quarter(quarter, { - width: "abbreviated", - context: "standalone" - }); - case "qqqqq": - return localize2.quarter(quarter, { - width: "narrow", - context: "standalone" - }); - case "qqqq": - default: - return localize2.quarter(quarter, { - width: "wide", - context: "standalone" - }); + }, []); + return [set, clear]; +} +function useLatestValue(value, dependencies) { + if (dependencies === void 0) { + dependencies = [value]; + } + const valueRef = _2(value); + useIsomorphicLayoutEffect(() => { + if (valueRef.current !== value) { + valueRef.current = value; } - }, - M: function M4(date, token, localize2) { - var month = date.getUTCMonth(); - switch (token) { - case "M": - case "MM": - return lightFormatters_default.M(date, token); - case "Mo": - return localize2.ordinalNumber(month + 1, { - unit: "month" - }); - case "MMM": - return localize2.month(month, { - width: "abbreviated", - context: "formatting" - }); - case "MMMMM": - return localize2.month(month, { - width: "narrow", - context: "formatting" - }); - case "MMMM": - default: - return localize2.month(month, { - width: "wide", - context: "formatting" - }); + }, dependencies); + return valueRef; +} +function useLazyMemo(callback, dependencies) { + const valueRef = _2(); + return F2( + () => { + const newValue = callback(valueRef.current); + valueRef.current = newValue; + return newValue; + }, + [...dependencies] + ); +} +function useNodeRef(onChange) { + const onChangeHandler = useEvent(onChange); + const node = _2(null); + const setNodeRef = T2( + (element) => { + if (element !== node.current) { + onChangeHandler == null ? void 0 : onChangeHandler(element, node.current); + } + node.current = element; + }, + [] + ); + return [node, setNodeRef]; +} +function usePrevious(value) { + const ref2 = _2(); + p2(() => { + ref2.current = value; + }, [value]); + return ref2.current; +} +var ids = {}; +function useUniqueId(prefix, value) { + return F2(() => { + if (value) { + return value; } - }, - L: function L3(date, token, localize2) { - var month = date.getUTCMonth(); - switch (token) { - case "L": - return String(month + 1); - case "LL": - return addLeadingZeros(month + 1, 2); - case "Lo": - return localize2.ordinalNumber(month + 1, { - unit: "month" - }); - case "LLL": - return localize2.month(month, { - width: "abbreviated", - context: "standalone" - }); - case "LLLLL": - return localize2.month(month, { - width: "narrow", - context: "standalone" - }); - case "LLLL": - default: - return localize2.month(month, { - width: "wide", - context: "standalone" - }); + const id2 = ids[prefix] == null ? 0 : ids[prefix] + 1; + ids[prefix] = id2; + return prefix + "-" + id2; + }, [prefix, value]); +} +function createAdjustmentFn(modifier) { + return function(object) { + for (var _len = arguments.length, adjustments = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { + adjustments[_key - 1] = arguments[_key]; } - }, - w: function w4(date, token, localize2, options) { - var week = getUTCWeek(date, options); - if (token === "wo") { - return localize2.ordinalNumber(week, { - unit: "week" - }); + return adjustments.reduce((accumulator, adjustment) => { + const entries = Object.entries(adjustment); + for (const [key2, valueAdjustment] of entries) { + const value = accumulator[key2]; + if (value != null) { + accumulator[key2] = value + modifier * valueAdjustment; + } + } + return accumulator; + }, { + ...object + }); + }; +} +var add = /* @__PURE__ */ createAdjustmentFn(1); +var subtract = /* @__PURE__ */ createAdjustmentFn(-1); +function hasViewportRelativeCoordinates(event) { + return "clientX" in event && "clientY" in event; +} +function isKeyboardEvent(event) { + if (!event) { + return false; + } + const { + KeyboardEvent + } = getWindow(event.target); + return KeyboardEvent && event instanceof KeyboardEvent; +} +function isTouchEvent(event) { + if (!event) { + return false; + } + const { + TouchEvent + } = getWindow(event.target); + return TouchEvent && event instanceof TouchEvent; +} +function getEventCoordinates(event) { + if (isTouchEvent(event)) { + if (event.touches && event.touches.length) { + const { + clientX: x5, + clientY: y5 + } = event.touches[0]; + return { + x: x5, + y: y5 + }; + } else if (event.changedTouches && event.changedTouches.length) { + const { + clientX: x5, + clientY: y5 + } = event.changedTouches[0]; + return { + x: x5, + y: y5 + }; } - return addLeadingZeros(week, token.length); - }, - I: function I3(date, token, localize2) { - var isoWeek = getUTCISOWeek(date); - if (token === "Io") { - return localize2.ordinalNumber(isoWeek, { - unit: "week" - }); + } + if (hasViewportRelativeCoordinates(event)) { + return { + x: event.clientX, + y: event.clientY + }; + } + return null; +} +var CSS = /* @__PURE__ */ Object.freeze({ + Translate: { + toString(transform) { + if (!transform) { + return; + } + const { + x: x5, + y: y5 + } = transform; + return "translate3d(" + (x5 ? Math.round(x5) : 0) + "px, " + (y5 ? Math.round(y5) : 0) + "px, 0)"; } - return addLeadingZeros(isoWeek, token.length); }, - d: function d4(date, token, localize2) { - if (token === "do") { - return localize2.ordinalNumber(date.getUTCDate(), { - unit: "date" - }); + Scale: { + toString(transform) { + if (!transform) { + return; + } + const { + scaleX, + scaleY + } = transform; + return "scaleX(" + scaleX + ") scaleY(" + scaleY + ")"; } - return lightFormatters_default.d(date, token); }, - D: function D3(date, token, localize2) { - var dayOfYear = getUTCDayOfYear(date); - if (token === "Do") { - return localize2.ordinalNumber(dayOfYear, { - unit: "dayOfYear" - }); + Transform: { + toString(transform) { + if (!transform) { + return; + } + return [CSS.Translate.toString(transform), CSS.Scale.toString(transform)].join(" "); } - return addLeadingZeros(dayOfYear, token.length); }, - E: function E3(date, token, localize2) { - var dayOfWeek = date.getUTCDay(); - switch (token) { - case "E": - case "EE": - case "EEE": - return localize2.day(dayOfWeek, { - width: "abbreviated", - context: "formatting" - }); - case "EEEEE": - return localize2.day(dayOfWeek, { - width: "narrow", - context: "formatting" - }); - case "EEEEEE": - return localize2.day(dayOfWeek, { - width: "short", - context: "formatting" - }); - case "EEEE": - default: - return localize2.day(dayOfWeek, { - width: "wide", - context: "formatting" - }); + Transition: { + toString(_ref) { + let { + property, + duration, + easing + } = _ref; + return property + " " + duration + "ms " + easing; } - }, - e: function e3(date, token, localize2, options) { - var dayOfWeek = date.getUTCDay(); - var localDayOfWeek = (dayOfWeek - options.weekStartsOn + 8) % 7 || 7; - switch (token) { - case "e": - return String(localDayOfWeek); - case "ee": - return addLeadingZeros(localDayOfWeek, 2); - case "eo": - return localize2.ordinalNumber(localDayOfWeek, { - unit: "day" - }); - case "eee": - return localize2.day(dayOfWeek, { - width: "abbreviated", - context: "formatting" - }); - case "eeeee": - return localize2.day(dayOfWeek, { - width: "narrow", - context: "formatting" - }); - case "eeeeee": - return localize2.day(dayOfWeek, { - width: "short", - context: "formatting" - }); - case "eeee": - default: - return localize2.day(dayOfWeek, { - width: "wide", - context: "formatting" - }); + } +}); +var SELECTOR = "a,frame,iframe,input:not([type=hidden]):not(:disabled),select:not(:disabled),textarea:not(:disabled),button:not(:disabled),*[tabindex]"; +function findFirstFocusableNode(element) { + if (element.matches(SELECTOR)) { + return element; + } + return element.querySelector(SELECTOR); +} + +// node_modules/@dnd-kit/accessibility/dist/accessibility.esm.js +var hiddenStyles = { + display: "none" +}; +function HiddenText(_ref) { + let { + id: id2, + value + } = _ref; + return Cn.createElement("div", { + id: id2, + style: hiddenStyles + }, value); +} +var visuallyHidden = { + position: "fixed", + width: 1, + height: 1, + margin: -1, + border: 0, + padding: 0, + overflow: "hidden", + clip: "rect(0 0 0 0)", + clipPath: "inset(100%)", + whiteSpace: "nowrap" +}; +function LiveRegion(_ref) { + let { + id: id2, + announcement + } = _ref; + return Cn.createElement("div", { + id: id2, + style: visuallyHidden, + role: "status", + "aria-live": "assertive", + "aria-atomic": true + }, announcement); +} +function useAnnouncement() { + const [announcement, setAnnouncement] = h2(""); + const announce = T2((value) => { + if (value != null) { + setAnnouncement(value); } - }, - c: function c3(date, token, localize2, options) { - var dayOfWeek = date.getUTCDay(); - var localDayOfWeek = (dayOfWeek - options.weekStartsOn + 8) % 7 || 7; - switch (token) { - case "c": - return String(localDayOfWeek); - case "cc": - return addLeadingZeros(localDayOfWeek, token.length); - case "co": - return localize2.ordinalNumber(localDayOfWeek, { - unit: "day" - }); - case "ccc": - return localize2.day(dayOfWeek, { - width: "abbreviated", - context: "standalone" - }); - case "ccccc": - return localize2.day(dayOfWeek, { - width: "narrow", - context: "standalone" - }); - case "cccccc": - return localize2.day(dayOfWeek, { - width: "short", - context: "standalone" - }); - case "cccc": - default: - return localize2.day(dayOfWeek, { - width: "wide", - context: "standalone" - }); + }, []); + return { + announce, + announcement + }; +} + +// node_modules/@dnd-kit/core/dist/core.esm.js +var DndMonitorContext = /* @__PURE__ */ F(null); +function useDndMonitor(listener) { + const registerListener = q2(DndMonitorContext); + p2(() => { + if (!registerListener) { + throw new Error("useDndMonitor must be used within a children of "); } + const unsubscribe = registerListener(listener); + return unsubscribe; + }, [listener, registerListener]); +} +function useDndMonitorProvider() { + const [listeners] = h2(() => /* @__PURE__ */ new Set()); + const registerListener = T2((listener) => { + listeners.add(listener); + return () => listeners.delete(listener); + }, [listeners]); + const dispatch = T2((_ref) => { + let { + type, + event + } = _ref; + listeners.forEach((listener) => { + var _listener$type; + return (_listener$type = listener[type]) == null ? void 0 : _listener$type.call(listener, event); + }); + }, [listeners]); + return [dispatch, registerListener]; +} +var defaultScreenReaderInstructions = { + draggable: "\n To pick up a draggable item, press the space bar.\n While dragging, use the arrow keys to move the item.\n Press space again to drop the item in its new position, or press escape to cancel.\n " +}; +var defaultAnnouncements = { + onDragStart(_ref) { + let { + active + } = _ref; + return "Picked up draggable item " + active.id + "."; }, - i: function i3(date, token, localize2) { - var dayOfWeek = date.getUTCDay(); - var isoDayOfWeek = dayOfWeek === 0 ? 7 : dayOfWeek; - switch (token) { - case "i": - return String(isoDayOfWeek); - case "ii": - return addLeadingZeros(isoDayOfWeek, token.length); - case "io": - return localize2.ordinalNumber(isoDayOfWeek, { - unit: "day" - }); - case "iii": - return localize2.day(dayOfWeek, { - width: "abbreviated", - context: "formatting" - }); - case "iiiii": - return localize2.day(dayOfWeek, { - width: "narrow", - context: "formatting" - }); - case "iiiiii": - return localize2.day(dayOfWeek, { - width: "short", - context: "formatting" - }); - case "iiii": - default: - return localize2.day(dayOfWeek, { - width: "wide", - context: "formatting" - }); + onDragOver(_ref2) { + let { + active, + over + } = _ref2; + if (over) { + return "Draggable item " + active.id + " was moved over droppable area " + over.id + "."; } + return "Draggable item " + active.id + " is no longer over a droppable area."; }, - a: function a4(date, token, localize2) { - var hours = date.getUTCHours(); - var dayPeriodEnumValue = hours / 12 >= 1 ? "pm" : "am"; - switch (token) { - case "a": - case "aa": - return localize2.dayPeriod(dayPeriodEnumValue, { - width: "abbreviated", - context: "formatting" - }); - case "aaa": - return localize2.dayPeriod(dayPeriodEnumValue, { - width: "abbreviated", - context: "formatting" - }).toLowerCase(); - case "aaaaa": - return localize2.dayPeriod(dayPeriodEnumValue, { - width: "narrow", - context: "formatting" - }); - case "aaaa": - default: - return localize2.dayPeriod(dayPeriodEnumValue, { - width: "wide", - context: "formatting" - }); + onDragEnd(_ref3) { + let { + active, + over + } = _ref3; + if (over) { + return "Draggable item " + active.id + " was dropped over droppable area " + over.id; } + return "Draggable item " + active.id + " was dropped."; }, - b: function b3(date, token, localize2) { - var hours = date.getUTCHours(); - var dayPeriodEnumValue; - if (hours === 12) { - dayPeriodEnumValue = dayPeriodEnum.noon; - } else if (hours === 0) { - dayPeriodEnumValue = dayPeriodEnum.midnight; - } else { - dayPeriodEnumValue = hours / 12 >= 1 ? "pm" : "am"; + onDragCancel(_ref4) { + let { + active + } = _ref4; + return "Dragging was cancelled. Draggable item " + active.id + " was dropped."; + } +}; +function Accessibility(_ref) { + let { + announcements = defaultAnnouncements, + container, + hiddenTextDescribedById, + screenReaderInstructions = defaultScreenReaderInstructions + } = _ref; + const { + announce, + announcement + } = useAnnouncement(); + const liveRegionId = useUniqueId("DndLiveRegion"); + const [mounted, setMounted] = h2(false); + p2(() => { + setMounted(true); + }, []); + useDndMonitor(F2(() => ({ + onDragStart(_ref2) { + let { + active + } = _ref2; + announce(announcements.onDragStart({ + active + })); + }, + onDragMove(_ref3) { + let { + active, + over + } = _ref3; + if (announcements.onDragMove) { + announce(announcements.onDragMove({ + active, + over + })); + } + }, + onDragOver(_ref4) { + let { + active, + over + } = _ref4; + announce(announcements.onDragOver({ + active, + over + })); + }, + onDragEnd(_ref5) { + let { + active, + over + } = _ref5; + announce(announcements.onDragEnd({ + active, + over + })); + }, + onDragCancel(_ref6) { + let { + active, + over + } = _ref6; + announce(announcements.onDragCancel({ + active, + over + })); } - switch (token) { - case "b": - case "bb": - return localize2.dayPeriod(dayPeriodEnumValue, { - width: "abbreviated", - context: "formatting" - }); - case "bbb": - return localize2.dayPeriod(dayPeriodEnumValue, { - width: "abbreviated", - context: "formatting" - }).toLowerCase(); - case "bbbbb": - return localize2.dayPeriod(dayPeriodEnumValue, { - width: "narrow", - context: "formatting" - }); - case "bbbb": - default: - return localize2.dayPeriod(dayPeriodEnumValue, { - width: "wide", - context: "formatting" - }); + }), [announce, announcements])); + if (!mounted) { + return null; + } + const markup = Cn.createElement(Cn.Fragment, null, Cn.createElement(HiddenText, { + id: hiddenTextDescribedById, + value: screenReaderInstructions.draggable + }), Cn.createElement(LiveRegion, { + id: liveRegionId, + announcement + })); + return container ? z3(markup, container) : markup; +} +var Action; +(function(Action2) { + Action2["DragStart"] = "dragStart"; + Action2["DragMove"] = "dragMove"; + Action2["DragEnd"] = "dragEnd"; + Action2["DragCancel"] = "dragCancel"; + Action2["DragOver"] = "dragOver"; + Action2["RegisterDroppable"] = "registerDroppable"; + Action2["SetDroppableDisabled"] = "setDroppableDisabled"; + Action2["UnregisterDroppable"] = "unregisterDroppable"; +})(Action || (Action = {})); +function noop() { +} +function useSensor(sensor, options) { + return F2( + () => ({ + sensor, + options: options != null ? options : {} + }), + [sensor, options] + ); +} +function useSensors() { + for (var _len = arguments.length, sensors = new Array(_len), _key = 0; _key < _len; _key++) { + sensors[_key] = arguments[_key]; + } + return F2( + () => [...sensors].filter((sensor) => sensor != null), + [...sensors] + ); +} +var defaultCoordinates = /* @__PURE__ */ Object.freeze({ + x: 0, + y: 0 +}); +function distanceBetween(p1, p22) { + return Math.sqrt(Math.pow(p1.x - p22.x, 2) + Math.pow(p1.y - p22.y, 2)); +} +function getRelativeTransformOrigin(event, rect) { + const eventCoordinates = getEventCoordinates(event); + if (!eventCoordinates) { + return "0 0"; + } + const transformOrigin = { + x: (eventCoordinates.x - rect.left) / rect.width * 100, + y: (eventCoordinates.y - rect.top) / rect.height * 100 + }; + return transformOrigin.x + "% " + transformOrigin.y + "%"; +} +function sortCollisionsAsc(_ref, _ref2) { + let { + data: { + value: a5 } - }, - B: function B4(date, token, localize2) { - var hours = date.getUTCHours(); - var dayPeriodEnumValue; - if (hours >= 17) { - dayPeriodEnumValue = dayPeriodEnum.evening; - } else if (hours >= 12) { - dayPeriodEnumValue = dayPeriodEnum.afternoon; - } else if (hours >= 4) { - dayPeriodEnumValue = dayPeriodEnum.morning; - } else { - dayPeriodEnumValue = dayPeriodEnum.night; + } = _ref; + let { + data: { + value: b4 } - switch (token) { - case "B": - case "BB": - case "BBB": - return localize2.dayPeriod(dayPeriodEnumValue, { - width: "abbreviated", - context: "formatting" - }); - case "BBBBB": - return localize2.dayPeriod(dayPeriodEnumValue, { - width: "narrow", - context: "formatting" - }); - case "BBBB": - default: - return localize2.dayPeriod(dayPeriodEnumValue, { - width: "wide", - context: "formatting" - }); + } = _ref2; + return a5 - b4; +} +function sortCollisionsDesc(_ref3, _ref4) { + let { + data: { + value: a5 } - }, - h: function h4(date, token, localize2) { - if (token === "ho") { - var hours = date.getUTCHours() % 12; - if (hours === 0) - hours = 12; - return localize2.ordinalNumber(hours, { - unit: "hour" - }); + } = _ref3; + let { + data: { + value: b4 } - return lightFormatters_default.h(date, token); - }, - H: function H4(date, token, localize2) { - if (token === "Ho") { - return localize2.ordinalNumber(date.getUTCHours(), { - unit: "hour" + } = _ref4; + return b4 - a5; +} +function cornersOfRectangle(_ref5) { + let { + left, + top, + height, + width + } = _ref5; + return [{ + x: left, + y: top + }, { + x: left + width, + y: top + }, { + x: left, + y: top + height + }, { + x: left + width, + y: top + height + }]; +} +function getFirstCollision(collisions, property) { + if (!collisions || collisions.length === 0) { + return null; + } + const [firstCollision] = collisions; + return property ? firstCollision[property] : firstCollision; +} +function centerOfRectangle(rect, left, top) { + if (left === void 0) { + left = rect.left; + } + if (top === void 0) { + top = rect.top; + } + return { + x: left + rect.width * 0.5, + y: top + rect.height * 0.5 + }; +} +var closestCenter = (_ref) => { + let { + collisionRect, + droppableRects, + droppableContainers + } = _ref; + const centerRect = centerOfRectangle(collisionRect, collisionRect.left, collisionRect.top); + const collisions = []; + for (const droppableContainer of droppableContainers) { + const { + id: id2 + } = droppableContainer; + const rect = droppableRects.get(id2); + if (rect) { + const distBetween = distanceBetween(centerOfRectangle(rect), centerRect); + collisions.push({ + id: id2, + data: { + droppableContainer, + value: distBetween + } }); } - return lightFormatters_default.H(date, token); - }, - K: function K2(date, token, localize2) { - var hours = date.getUTCHours() % 12; - if (token === "Ko") { - return localize2.ordinalNumber(hours, { - unit: "hour" + } + return collisions.sort(sortCollisionsAsc); +}; +var closestCorners = (_ref) => { + let { + collisionRect, + droppableRects, + droppableContainers + } = _ref; + const corners = cornersOfRectangle(collisionRect); + const collisions = []; + for (const droppableContainer of droppableContainers) { + const { + id: id2 + } = droppableContainer; + const rect = droppableRects.get(id2); + if (rect) { + const rectCorners = cornersOfRectangle(rect); + const distances = corners.reduce((accumulator, corner, index) => { + return accumulator + distanceBetween(rectCorners[index], corner); + }, 0); + const effectiveDistance = Number((distances / 4).toFixed(4)); + collisions.push({ + id: id2, + data: { + droppableContainer, + value: effectiveDistance + } }); } - return addLeadingZeros(hours, token.length); - }, - k: function k4(date, token, localize2) { - var hours = date.getUTCHours(); - if (hours === 0) - hours = 24; - if (token === "ko") { - return localize2.ordinalNumber(hours, { - unit: "hour" - }); + } + return collisions.sort(sortCollisionsAsc); +}; +function getIntersectionRatio(entry, target) { + const top = Math.max(target.top, entry.top); + const left = Math.max(target.left, entry.left); + const right = Math.min(target.left + target.width, entry.left + entry.width); + const bottom = Math.min(target.top + target.height, entry.top + entry.height); + const width = right - left; + const height = bottom - top; + if (left < right && top < bottom) { + const targetArea = target.width * target.height; + const entryArea = entry.width * entry.height; + const intersectionArea = width * height; + const intersectionRatio = intersectionArea / (targetArea + entryArea - intersectionArea); + return Number(intersectionRatio.toFixed(4)); + } + return 0; +} +var rectIntersection = (_ref) => { + let { + collisionRect, + droppableRects, + droppableContainers + } = _ref; + const collisions = []; + for (const droppableContainer of droppableContainers) { + const { + id: id2 + } = droppableContainer; + const rect = droppableRects.get(id2); + if (rect) { + const intersectionRatio = getIntersectionRatio(rect, collisionRect); + if (intersectionRatio > 0) { + collisions.push({ + id: id2, + data: { + droppableContainer, + value: intersectionRatio + } + }); + } } - return addLeadingZeros(hours, token.length); - }, - m: function m4(date, token, localize2) { - if (token === "mo") { - return localize2.ordinalNumber(date.getUTCMinutes(), { - unit: "minute" - }); + } + return collisions.sort(sortCollisionsDesc); +}; +function adjustScale(transform, rect1, rect2) { + return { + ...transform, + scaleX: rect1 && rect2 ? rect1.width / rect2.width : 1, + scaleY: rect1 && rect2 ? rect1.height / rect2.height : 1 + }; +} +function getRectDelta(rect1, rect2) { + return rect1 && rect2 ? { + x: rect1.left - rect2.left, + y: rect1.top - rect2.top + } : defaultCoordinates; +} +function createRectAdjustmentFn(modifier) { + return function adjustClientRect(rect) { + for (var _len = arguments.length, adjustments = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { + adjustments[_key - 1] = arguments[_key]; } - return lightFormatters_default.m(date, token); - }, - s: function s4(date, token, localize2) { - if (token === "so") { - return localize2.ordinalNumber(date.getUTCSeconds(), { - unit: "second" - }); + return adjustments.reduce((acc, adjustment) => ({ + ...acc, + top: acc.top + modifier * adjustment.y, + bottom: acc.bottom + modifier * adjustment.y, + left: acc.left + modifier * adjustment.x, + right: acc.right + modifier * adjustment.x + }), { + ...rect + }); + }; +} +var getAdjustedRect = /* @__PURE__ */ createRectAdjustmentFn(1); +function parseTransform(transform) { + if (transform.startsWith("matrix3d(")) { + const transformArray = transform.slice(9, -1).split(/, /); + return { + x: +transformArray[12], + y: +transformArray[13], + scaleX: +transformArray[0], + scaleY: +transformArray[5] + }; + } else if (transform.startsWith("matrix(")) { + const transformArray = transform.slice(7, -1).split(/, /); + return { + x: +transformArray[4], + y: +transformArray[5], + scaleX: +transformArray[0], + scaleY: +transformArray[3] + }; + } + return null; +} +function inverseTransform(rect, transform, transformOrigin) { + const parsedTransform = parseTransform(transform); + if (!parsedTransform) { + return rect; + } + const { + scaleX, + scaleY, + x: translateX, + y: translateY + } = parsedTransform; + const x5 = rect.left - translateX - (1 - scaleX) * parseFloat(transformOrigin); + const y5 = rect.top - translateY - (1 - scaleY) * parseFloat(transformOrigin.slice(transformOrigin.indexOf(" ") + 1)); + const w5 = scaleX ? rect.width / scaleX : rect.width; + const h5 = scaleY ? rect.height / scaleY : rect.height; + return { + width: w5, + height: h5, + top: y5, + right: x5 + w5, + bottom: y5 + h5, + left: x5 + }; +} +var defaultOptions2 = { + ignoreTransform: false +}; +function getClientRect(element, options) { + if (options === void 0) { + options = defaultOptions2; + } + let rect = element.getBoundingClientRect(); + if (options.ignoreTransform) { + const { + transform, + transformOrigin + } = getWindow(element).getComputedStyle(element); + if (transform) { + rect = inverseTransform(rect, transform, transformOrigin); } - return lightFormatters_default.s(date, token); - }, - S: function S3(date, token) { - return lightFormatters_default.S(date, token); - }, - X: function X2(date, token, _localize, options) { - var originalDate = options._originalDate || date; - var timezoneOffset = originalDate.getTimezoneOffset(); - if (timezoneOffset === 0) { - return "Z"; + } + const { + top, + left, + width, + height, + bottom, + right + } = rect; + return { + top, + left, + width, + height, + bottom, + right + }; +} +function getTransformAgnosticClientRect(element) { + return getClientRect(element, { + ignoreTransform: true + }); +} +function getWindowClientRect(element) { + const width = element.innerWidth; + const height = element.innerHeight; + return { + top: 0, + left: 0, + right: width, + bottom: height, + width, + height + }; +} +function isFixed(node, computedStyle) { + if (computedStyle === void 0) { + computedStyle = getWindow(node).getComputedStyle(node); + } + return computedStyle.position === "fixed"; +} +function isScrollable(element, computedStyle) { + if (computedStyle === void 0) { + computedStyle = getWindow(element).getComputedStyle(element); + } + const overflowRegex = /(auto|scroll|overlay)/; + const properties2 = ["overflow", "overflowX", "overflowY"]; + return properties2.some((property) => { + const value = computedStyle[property]; + return typeof value === "string" ? overflowRegex.test(value) : false; + }); +} +function getScrollableAncestors(element, limit) { + const scrollParents = []; + function findScrollableAncestors(node) { + if (limit != null && scrollParents.length >= limit) { + return scrollParents; } - switch (token) { - case "X": - return formatTimezoneWithOptionalMinutes(timezoneOffset); - case "XXXX": - case "XX": - return formatTimezone(timezoneOffset); - case "XXXXX": - case "XXX": - default: - return formatTimezone(timezoneOffset, ":"); + if (!node) { + return scrollParents; } - }, - x: function x4(date, token, _localize, options) { - var originalDate = options._originalDate || date; - var timezoneOffset = originalDate.getTimezoneOffset(); - switch (token) { - case "x": - return formatTimezoneWithOptionalMinutes(timezoneOffset); - case "xxxx": - case "xx": - return formatTimezone(timezoneOffset); - case "xxxxx": - case "xxx": - default: - return formatTimezone(timezoneOffset, ":"); + if (isDocument(node) && node.scrollingElement != null && !scrollParents.includes(node.scrollingElement)) { + scrollParents.push(node.scrollingElement); + return scrollParents; } - }, - O: function O3(date, token, _localize, options) { - var originalDate = options._originalDate || date; - var timezoneOffset = originalDate.getTimezoneOffset(); - switch (token) { - case "O": - case "OO": - case "OOO": - return "GMT" + formatTimezoneShort(timezoneOffset, ":"); - case "OOOO": - default: - return "GMT" + formatTimezone(timezoneOffset, ":"); + if (!isHTMLElement(node) || isSVGElement(node)) { + return scrollParents; } - }, - z: function z4(date, token, _localize, options) { - var originalDate = options._originalDate || date; - var timezoneOffset = originalDate.getTimezoneOffset(); - switch (token) { - case "z": - case "zz": - case "zzz": - return "GMT" + formatTimezoneShort(timezoneOffset, ":"); - case "zzzz": - default: - return "GMT" + formatTimezone(timezoneOffset, ":"); + if (scrollParents.includes(node)) { + return scrollParents; } - }, - t: function t3(date, token, _localize, options) { - var originalDate = options._originalDate || date; - var timestamp = Math.floor(originalDate.getTime() / 1e3); - return addLeadingZeros(timestamp, token.length); - }, - T: function T5(date, token, _localize, options) { - var originalDate = options._originalDate || date; - var timestamp = originalDate.getTime(); - return addLeadingZeros(timestamp, token.length); + const computedStyle = getWindow(element).getComputedStyle(node); + if (node !== element) { + if (isScrollable(node, computedStyle)) { + scrollParents.push(node); + } + } + if (isFixed(node, computedStyle)) { + return scrollParents; + } + return findScrollableAncestors(node.parentNode); + } + if (!element) { + return scrollParents; + } + return findScrollableAncestors(element); +} +function getFirstScrollableAncestor(node) { + const [firstScrollableAncestor] = getScrollableAncestors(node, 1); + return firstScrollableAncestor != null ? firstScrollableAncestor : null; +} +function getScrollableElement(element) { + if (!canUseDOM || !element) { + return null; + } + if (isWindow(element)) { + return element; + } + if (!isNode(element)) { + return null; + } + if (isDocument(element) || element === getOwnerDocument(element).scrollingElement) { + return window; + } + if (isHTMLElement(element)) { + return element; + } + return null; +} +function getScrollXCoordinate(element) { + if (isWindow(element)) { + return element.scrollX; + } + return element.scrollLeft; +} +function getScrollYCoordinate(element) { + if (isWindow(element)) { + return element.scrollY; + } + return element.scrollTop; +} +function getScrollCoordinates(element) { + return { + x: getScrollXCoordinate(element), + y: getScrollYCoordinate(element) + }; +} +var Direction2; +(function(Direction3) { + Direction3[Direction3["Forward"] = 1] = "Forward"; + Direction3[Direction3["Backward"] = -1] = "Backward"; +})(Direction2 || (Direction2 = {})); +function isDocumentScrollingElement(element) { + if (!canUseDOM || !element) { + return false; } + return element === document.scrollingElement; +} +function getScrollPosition(scrollingContainer) { + const minScroll = { + x: 0, + y: 0 + }; + const dimensions = isDocumentScrollingElement(scrollingContainer) ? { + height: window.innerHeight, + width: window.innerWidth + } : { + height: scrollingContainer.clientHeight, + width: scrollingContainer.clientWidth + }; + const maxScroll = { + x: scrollingContainer.scrollWidth - dimensions.width, + y: scrollingContainer.scrollHeight - dimensions.height + }; + const isTop = scrollingContainer.scrollTop <= minScroll.y; + const isLeft = scrollingContainer.scrollLeft <= minScroll.x; + const isBottom = scrollingContainer.scrollTop >= maxScroll.y; + const isRight = scrollingContainer.scrollLeft >= maxScroll.x; + return { + isTop, + isLeft, + isBottom, + isRight, + maxScroll, + minScroll + }; +} +var defaultThreshold = { + x: 0.2, + y: 0.2 }; -function formatTimezoneShort(offset, dirtyDelimiter) { - var sign = offset > 0 ? "-" : "+"; - var absOffset = Math.abs(offset); - var hours = Math.floor(absOffset / 60); - var minutes = absOffset % 60; - if (minutes === 0) { - return sign + String(hours); +function getScrollDirectionAndSpeed(scrollContainer, scrollContainerRect, _ref, acceleration, thresholdPercentage) { + let { + top, + left, + right, + bottom + } = _ref; + if (acceleration === void 0) { + acceleration = 10; } - var delimiter = dirtyDelimiter || ""; - return sign + String(hours) + delimiter + addLeadingZeros(minutes, 2); + if (thresholdPercentage === void 0) { + thresholdPercentage = defaultThreshold; + } + const { + isTop, + isBottom, + isLeft, + isRight + } = getScrollPosition(scrollContainer); + const direction = { + x: 0, + y: 0 + }; + const speed = { + x: 0, + y: 0 + }; + const threshold = { + height: scrollContainerRect.height * thresholdPercentage.y, + width: scrollContainerRect.width * thresholdPercentage.x + }; + if (!isTop && top <= scrollContainerRect.top + threshold.height) { + direction.y = Direction2.Backward; + speed.y = acceleration * Math.abs((scrollContainerRect.top + threshold.height - top) / threshold.height); + } else if (!isBottom && bottom >= scrollContainerRect.bottom - threshold.height) { + direction.y = Direction2.Forward; + speed.y = acceleration * Math.abs((scrollContainerRect.bottom - threshold.height - bottom) / threshold.height); + } + if (!isRight && right >= scrollContainerRect.right - threshold.width) { + direction.x = Direction2.Forward; + speed.x = acceleration * Math.abs((scrollContainerRect.right - threshold.width - right) / threshold.width); + } else if (!isLeft && left <= scrollContainerRect.left + threshold.width) { + direction.x = Direction2.Backward; + speed.x = acceleration * Math.abs((scrollContainerRect.left + threshold.width - left) / threshold.width); + } + return { + direction, + speed + }; } -function formatTimezoneWithOptionalMinutes(offset, dirtyDelimiter) { - if (offset % 60 === 0) { - var sign = offset > 0 ? "-" : "+"; - return sign + addLeadingZeros(Math.abs(offset) / 60, 2); +function getScrollElementRect(element) { + if (element === document.scrollingElement) { + const { + innerWidth: innerWidth2, + innerHeight: innerHeight2 + } = window; + return { + top: 0, + left: 0, + right: innerWidth2, + bottom: innerHeight2, + width: innerWidth2, + height: innerHeight2 + }; } - return formatTimezone(offset, dirtyDelimiter); + const { + top, + left, + right, + bottom + } = element.getBoundingClientRect(); + return { + top, + left, + right, + bottom, + width: element.clientWidth, + height: element.clientHeight + }; } -function formatTimezone(offset, dirtyDelimiter) { - var delimiter = dirtyDelimiter || ""; - var sign = offset > 0 ? "-" : "+"; - var absOffset = Math.abs(offset); - var hours = addLeadingZeros(Math.floor(absOffset / 60), 2); - var minutes = addLeadingZeros(absOffset % 60, 2); - return sign + hours + delimiter + minutes; +function getScrollOffsets(scrollableAncestors) { + return scrollableAncestors.reduce((acc, node) => { + return add(acc, getScrollCoordinates(node)); + }, defaultCoordinates); } -var formatters_default = formatters2; - -// node_modules/date-fns/esm/_lib/format/longFormatters/index.js -var dateLongFormatter = function dateLongFormatter2(pattern, formatLong2) { - switch (pattern) { - case "P": - return formatLong2.date({ - width: "short" - }); - case "PP": - return formatLong2.date({ - width: "medium" - }); - case "PPP": - return formatLong2.date({ - width: "long" - }); - case "PPPP": - default: - return formatLong2.date({ - width: "full" - }); +function getScrollXOffset(scrollableAncestors) { + return scrollableAncestors.reduce((acc, node) => { + return acc + getScrollXCoordinate(node); + }, 0); +} +function getScrollYOffset(scrollableAncestors) { + return scrollableAncestors.reduce((acc, node) => { + return acc + getScrollYCoordinate(node); + }, 0); +} +function scrollIntoViewIfNeeded(element, measure) { + if (measure === void 0) { + measure = getClientRect; + } + if (!element) { + return; + } + const { + top, + left, + bottom, + right + } = measure(element); + const firstScrollableAncestor = getFirstScrollableAncestor(element); + if (!firstScrollableAncestor) { + return; + } + if (bottom <= 0 || right <= 0 || top >= window.innerHeight || left >= window.innerWidth) { + element.scrollIntoView({ + block: "center", + inline: "center" + }); + } +} +var properties = [["x", ["left", "right"], getScrollXOffset], ["y", ["top", "bottom"], getScrollYOffset]]; +var Rect = class { + constructor(rect, element) { + this.rect = void 0; + this.width = void 0; + this.height = void 0; + this.top = void 0; + this.bottom = void 0; + this.right = void 0; + this.left = void 0; + const scrollableAncestors = getScrollableAncestors(element); + const scrollOffsets = getScrollOffsets(scrollableAncestors); + this.rect = { + ...rect + }; + this.width = rect.width; + this.height = rect.height; + for (const [axis, keys, getScrollOffset] of properties) { + for (const key2 of keys) { + Object.defineProperty(this, key2, { + get: () => { + const currentOffsets = getScrollOffset(scrollableAncestors); + const scrollOffsetsDeltla = scrollOffsets[axis] - currentOffsets; + return this.rect[key2] + scrollOffsetsDeltla; + }, + enumerable: true + }); + } + } + Object.defineProperty(this, "rect", { + enumerable: false + }); } }; -var timeLongFormatter = function timeLongFormatter2(pattern, formatLong2) { - switch (pattern) { - case "p": - return formatLong2.time({ - width: "short" - }); - case "pp": - return formatLong2.time({ - width: "medium" - }); - case "ppp": - return formatLong2.time({ - width: "long" - }); - case "pppp": - default: - return formatLong2.time({ - width: "full" +var Listeners = class { + constructor(target) { + this.target = void 0; + this.listeners = []; + this.removeAll = () => { + this.listeners.forEach((listener) => { + var _this$target; + return (_this$target = this.target) == null ? void 0 : _this$target.removeEventListener(...listener); }); + }; + this.target = target; + } + add(eventName, handler, options) { + var _this$target2; + (_this$target2 = this.target) == null ? void 0 : _this$target2.addEventListener(eventName, handler, options); + this.listeners.push([eventName, handler, options]); } }; -var dateTimeLongFormatter = function dateTimeLongFormatter2(pattern, formatLong2) { - var matchResult = pattern.match(/(P+)(p+)?/) || []; - var datePattern = matchResult[1]; - var timePattern = matchResult[2]; - if (!timePattern) { - return dateLongFormatter(pattern, formatLong2); +function getEventListenerTarget(target) { + const { + EventTarget + } = getWindow(target); + return target instanceof EventTarget ? target : getOwnerDocument(target); +} +function hasExceededDistance(delta, measurement) { + const dx = Math.abs(delta.x); + const dy = Math.abs(delta.y); + if (typeof measurement === "number") { + return Math.sqrt(dx ** 2 + dy ** 2) > measurement; } - var dateTimeFormat; - switch (datePattern) { - case "P": - dateTimeFormat = formatLong2.dateTime({ - width: "short" - }); - break; - case "PP": - dateTimeFormat = formatLong2.dateTime({ - width: "medium" - }); - break; - case "PPP": - dateTimeFormat = formatLong2.dateTime({ - width: "long" - }); - break; - case "PPPP": - default: - dateTimeFormat = formatLong2.dateTime({ - width: "full" + if ("x" in measurement && "y" in measurement) { + return dx > measurement.x && dy > measurement.y; + } + if ("x" in measurement) { + return dx > measurement.x; + } + if ("y" in measurement) { + return dy > measurement.y; + } + return false; +} +var EventName; +(function(EventName2) { + EventName2["Click"] = "click"; + EventName2["DragStart"] = "dragstart"; + EventName2["Keydown"] = "keydown"; + EventName2["ContextMenu"] = "contextmenu"; + EventName2["Resize"] = "resize"; + EventName2["SelectionChange"] = "selectionchange"; + EventName2["VisibilityChange"] = "visibilitychange"; +})(EventName || (EventName = {})); +function preventDefault(event) { + event.preventDefault(); +} +function stopPropagation(event) { + event.stopPropagation(); +} +var KeyboardCode; +(function(KeyboardCode2) { + KeyboardCode2["Space"] = "Space"; + KeyboardCode2["Down"] = "ArrowDown"; + KeyboardCode2["Right"] = "ArrowRight"; + KeyboardCode2["Left"] = "ArrowLeft"; + KeyboardCode2["Up"] = "ArrowUp"; + KeyboardCode2["Esc"] = "Escape"; + KeyboardCode2["Enter"] = "Enter"; +})(KeyboardCode || (KeyboardCode = {})); +var defaultKeyboardCodes = { + start: [KeyboardCode.Space, KeyboardCode.Enter], + cancel: [KeyboardCode.Esc], + end: [KeyboardCode.Space, KeyboardCode.Enter] +}; +var defaultKeyboardCoordinateGetter = (event, _ref) => { + let { + currentCoordinates + } = _ref; + switch (event.code) { + case KeyboardCode.Right: + return { + ...currentCoordinates, + x: currentCoordinates.x + 25 + }; + case KeyboardCode.Left: + return { + ...currentCoordinates, + x: currentCoordinates.x - 25 + }; + case KeyboardCode.Down: + return { + ...currentCoordinates, + y: currentCoordinates.y + 25 + }; + case KeyboardCode.Up: + return { + ...currentCoordinates, + y: currentCoordinates.y - 25 + }; + } + return void 0; +}; +var KeyboardSensor = class { + constructor(props2) { + this.props = void 0; + this.autoScrollEnabled = false; + this.referenceCoordinates = void 0; + this.listeners = void 0; + this.windowListeners = void 0; + this.props = props2; + const { + event: { + target + } + } = props2; + this.props = props2; + this.listeners = new Listeners(getOwnerDocument(target)); + this.windowListeners = new Listeners(getWindow(target)); + this.handleKeyDown = this.handleKeyDown.bind(this); + this.handleCancel = this.handleCancel.bind(this); + this.attach(); + } + attach() { + this.handleStart(); + this.windowListeners.add(EventName.Resize, this.handleCancel); + this.windowListeners.add(EventName.VisibilityChange, this.handleCancel); + setTimeout(() => this.listeners.add(EventName.Keydown, this.handleKeyDown)); + } + handleStart() { + const { + activeNode, + onStart + } = this.props; + const node = activeNode.node.current; + if (node) { + scrollIntoViewIfNeeded(node); + } + onStart(defaultCoordinates); + } + handleKeyDown(event) { + if (isKeyboardEvent(event)) { + const { + active, + context, + options + } = this.props; + const { + keyboardCodes = defaultKeyboardCodes, + coordinateGetter = defaultKeyboardCoordinateGetter, + scrollBehavior = "smooth" + } = options; + const { + code + } = event; + if (keyboardCodes.end.includes(code)) { + this.handleEnd(event); + return; + } + if (keyboardCodes.cancel.includes(code)) { + this.handleCancel(event); + return; + } + const { + collisionRect + } = context.current; + const currentCoordinates = collisionRect ? { + x: collisionRect.left, + y: collisionRect.top + } : defaultCoordinates; + if (!this.referenceCoordinates) { + this.referenceCoordinates = currentCoordinates; + } + const newCoordinates = coordinateGetter(event, { + active, + context: context.current, + currentCoordinates }); - break; + if (newCoordinates) { + const coordinatesDelta = subtract(newCoordinates, currentCoordinates); + const scrollDelta = { + x: 0, + y: 0 + }; + const { + scrollableAncestors + } = context.current; + for (const scrollContainer of scrollableAncestors) { + const direction = event.code; + const { + isTop, + isRight, + isLeft, + isBottom, + maxScroll, + minScroll + } = getScrollPosition(scrollContainer); + const scrollElementRect = getScrollElementRect(scrollContainer); + const clampedCoordinates = { + x: Math.min(direction === KeyboardCode.Right ? scrollElementRect.right - scrollElementRect.width / 2 : scrollElementRect.right, Math.max(direction === KeyboardCode.Right ? scrollElementRect.left : scrollElementRect.left + scrollElementRect.width / 2, newCoordinates.x)), + y: Math.min(direction === KeyboardCode.Down ? scrollElementRect.bottom - scrollElementRect.height / 2 : scrollElementRect.bottom, Math.max(direction === KeyboardCode.Down ? scrollElementRect.top : scrollElementRect.top + scrollElementRect.height / 2, newCoordinates.y)) + }; + const canScrollX = direction === KeyboardCode.Right && !isRight || direction === KeyboardCode.Left && !isLeft; + const canScrollY = direction === KeyboardCode.Down && !isBottom || direction === KeyboardCode.Up && !isTop; + if (canScrollX && clampedCoordinates.x !== newCoordinates.x) { + const newScrollCoordinates = scrollContainer.scrollLeft + coordinatesDelta.x; + const canScrollToNewCoordinates = direction === KeyboardCode.Right && newScrollCoordinates <= maxScroll.x || direction === KeyboardCode.Left && newScrollCoordinates >= minScroll.x; + if (canScrollToNewCoordinates && !coordinatesDelta.y) { + scrollContainer.scrollTo({ + left: newScrollCoordinates, + behavior: scrollBehavior + }); + return; + } + if (canScrollToNewCoordinates) { + scrollDelta.x = scrollContainer.scrollLeft - newScrollCoordinates; + } else { + scrollDelta.x = direction === KeyboardCode.Right ? scrollContainer.scrollLeft - maxScroll.x : scrollContainer.scrollLeft - minScroll.x; + } + if (scrollDelta.x) { + scrollContainer.scrollBy({ + left: -scrollDelta.x, + behavior: scrollBehavior + }); + } + break; + } else if (canScrollY && clampedCoordinates.y !== newCoordinates.y) { + const newScrollCoordinates = scrollContainer.scrollTop + coordinatesDelta.y; + const canScrollToNewCoordinates = direction === KeyboardCode.Down && newScrollCoordinates <= maxScroll.y || direction === KeyboardCode.Up && newScrollCoordinates >= minScroll.y; + if (canScrollToNewCoordinates && !coordinatesDelta.x) { + scrollContainer.scrollTo({ + top: newScrollCoordinates, + behavior: scrollBehavior + }); + return; + } + if (canScrollToNewCoordinates) { + scrollDelta.y = scrollContainer.scrollTop - newScrollCoordinates; + } else { + scrollDelta.y = direction === KeyboardCode.Down ? scrollContainer.scrollTop - maxScroll.y : scrollContainer.scrollTop - minScroll.y; + } + if (scrollDelta.y) { + scrollContainer.scrollBy({ + top: -scrollDelta.y, + behavior: scrollBehavior + }); + } + break; + } + } + this.handleMove(event, add(subtract(newCoordinates, this.referenceCoordinates), scrollDelta)); + } + } + } + handleMove(event, coordinates) { + const { + onMove + } = this.props; + event.preventDefault(); + onMove(coordinates); } - return dateTimeFormat.replace("{{date}}", dateLongFormatter(datePattern, formatLong2)).replace("{{time}}", timeLongFormatter(timePattern, formatLong2)); -}; -var longFormatters = { - p: timeLongFormatter, - P: dateTimeLongFormatter -}; -var longFormatters_default = longFormatters; - -// node_modules/date-fns/esm/_lib/protectedTokens/index.js -var protectedDayOfYearTokens = ["D", "DD"]; -var protectedWeekYearTokens = ["YY", "YYYY"]; -function isProtectedDayOfYearToken(token) { - return protectedDayOfYearTokens.indexOf(token) !== -1; -} -function isProtectedWeekYearToken(token) { - return protectedWeekYearTokens.indexOf(token) !== -1; -} -function throwProtectedError(token, format2, input) { - if (token === "YYYY") { - throw new RangeError("Use `yyyy` instead of `YYYY` (in `".concat(format2, "`) for formatting years to the input `").concat(input, "`; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md")); - } else if (token === "YY") { - throw new RangeError("Use `yy` instead of `YY` (in `".concat(format2, "`) for formatting years to the input `").concat(input, "`; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md")); - } else if (token === "D") { - throw new RangeError("Use `d` instead of `D` (in `".concat(format2, "`) for formatting days of the month to the input `").concat(input, "`; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md")); - } else if (token === "DD") { - throw new RangeError("Use `dd` instead of `DD` (in `".concat(format2, "`) for formatting days of the month to the input `").concat(input, "`; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md")); + handleEnd(event) { + const { + onEnd + } = this.props; + event.preventDefault(); + this.detach(); + onEnd(); } -} - -// node_modules/date-fns/esm/locale/en-US/_lib/formatDistance/index.js -var formatDistanceLocale = { - lessThanXSeconds: { - one: "less than a second", - other: "less than {{count}} seconds" - }, - xSeconds: { - one: "1 second", - other: "{{count}} seconds" - }, - halfAMinute: "half a minute", - lessThanXMinutes: { - one: "less than a minute", - other: "less than {{count}} minutes" - }, - xMinutes: { - one: "1 minute", - other: "{{count}} minutes" - }, - aboutXHours: { - one: "about 1 hour", - other: "about {{count}} hours" - }, - xHours: { - one: "1 hour", - other: "{{count}} hours" - }, - xDays: { - one: "1 day", - other: "{{count}} days" - }, - aboutXWeeks: { - one: "about 1 week", - other: "about {{count}} weeks" - }, - xWeeks: { - one: "1 week", - other: "{{count}} weeks" - }, - aboutXMonths: { - one: "about 1 month", - other: "about {{count}} months" - }, - xMonths: { - one: "1 month", - other: "{{count}} months" - }, - aboutXYears: { - one: "about 1 year", - other: "about {{count}} years" - }, - xYears: { - one: "1 year", - other: "{{count}} years" - }, - overXYears: { - one: "over 1 year", - other: "over {{count}} years" - }, - almostXYears: { - one: "almost 1 year", - other: "almost {{count}} years" + handleCancel(event) { + const { + onCancel + } = this.props; + event.preventDefault(); + this.detach(); + onCancel(); } -}; -var formatDistance = function formatDistance2(token, count2, options) { - var result; - var tokenValue = formatDistanceLocale[token]; - if (typeof tokenValue === "string") { - result = tokenValue; - } else if (count2 === 1) { - result = tokenValue.one; - } else { - result = tokenValue.other.replace("{{count}}", count2.toString()); + detach() { + this.listeners.removeAll(); + this.windowListeners.removeAll(); } - if (options !== null && options !== void 0 && options.addSuffix) { - if (options.comparison && options.comparison > 0) { - return "in " + result; - } else { - return result + " ago"; +}; +KeyboardSensor.activators = [{ + eventName: "onKeyDown", + handler: (event, _ref, _ref2) => { + let { + keyboardCodes = defaultKeyboardCodes, + onActivation + } = _ref; + let { + active + } = _ref2; + const { + code + } = event.nativeEvent; + if (keyboardCodes.start.includes(code)) { + const activator = active.activatorNode.current; + if (activator && event.target !== activator) { + return false; + } + event.preventDefault(); + onActivation == null ? void 0 : onActivation({ + event: event.nativeEvent + }); + return true; } + return false; } - return result; -}; -var formatDistance_default = formatDistance; - -// node_modules/date-fns/esm/locale/_lib/buildFormatLongFn/index.js -function buildFormatLongFn(args) { - return function() { - var options = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {}; - var width = options.width ? String(options.width) : args.defaultWidth; - var format2 = args.formats[width] || args.formats[args.defaultWidth]; - return format2; - }; +}]; +function isDistanceConstraint(constraint) { + return Boolean(constraint && "distance" in constraint); } - -// node_modules/date-fns/esm/locale/en-US/_lib/formatLong/index.js -var dateFormats = { - full: "EEEE, MMMM do, y", - long: "MMMM do, y", - medium: "MMM d, y", - short: "MM/dd/yyyy" -}; -var timeFormats = { - full: "h:mm:ss a zzzz", - long: "h:mm:ss a z", - medium: "h:mm:ss a", - short: "h:mm a" -}; -var dateTimeFormats = { - full: "{{date}} 'at' {{time}}", - long: "{{date}} 'at' {{time}}", - medium: "{{date}}, {{time}}", - short: "{{date}}, {{time}}" -}; -var formatLong = { - date: buildFormatLongFn({ - formats: dateFormats, - defaultWidth: "full" - }), - time: buildFormatLongFn({ - formats: timeFormats, - defaultWidth: "full" - }), - dateTime: buildFormatLongFn({ - formats: dateTimeFormats, - defaultWidth: "full" - }) -}; -var formatLong_default = formatLong; - -// node_modules/date-fns/esm/locale/en-US/_lib/formatRelative/index.js -var formatRelativeLocale = { - lastWeek: "'last' eeee 'at' p", - yesterday: "'yesterday at' p", - today: "'today at' p", - tomorrow: "'tomorrow at' p", - nextWeek: "eeee 'at' p", - other: "P" -}; -var formatRelative = function formatRelative2(token, _date, _baseDate, _options) { - return formatRelativeLocale[token]; -}; -var formatRelative_default = formatRelative; - -// node_modules/date-fns/esm/locale/_lib/buildLocalizeFn/index.js -function buildLocalizeFn(args) { - return function(dirtyIndex, options) { - var context = options !== null && options !== void 0 && options.context ? String(options.context) : "standalone"; - var valuesArray; - if (context === "formatting" && args.formattingValues) { - var defaultWidth = args.defaultFormattingWidth || args.defaultWidth; - var width = options !== null && options !== void 0 && options.width ? String(options.width) : defaultWidth; - valuesArray = args.formattingValues[width] || args.formattingValues[defaultWidth]; - } else { - var _defaultWidth = args.defaultWidth; - var _width = options !== null && options !== void 0 && options.width ? String(options.width) : args.defaultWidth; - valuesArray = args.values[_width] || args.values[_defaultWidth]; - } - var index = args.argumentCallback ? args.argumentCallback(dirtyIndex) : dirtyIndex; - return valuesArray[index]; - }; +function isDelayConstraint(constraint) { + return Boolean(constraint && "delay" in constraint); } - -// node_modules/date-fns/esm/locale/en-US/_lib/localize/index.js -var eraValues = { - narrow: ["B", "A"], - abbreviated: ["BC", "AD"], - wide: ["Before Christ", "Anno Domini"] -}; -var quarterValues = { - narrow: ["1", "2", "3", "4"], - abbreviated: ["Q1", "Q2", "Q3", "Q4"], - wide: ["1st quarter", "2nd quarter", "3rd quarter", "4th quarter"] -}; -var monthValues = { - narrow: ["J", "F", "M", "A", "M", "J", "J", "A", "S", "O", "N", "D"], - abbreviated: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"], - wide: ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"] -}; -var dayValues = { - narrow: ["S", "M", "T", "W", "T", "F", "S"], - short: ["Su", "Mo", "Tu", "We", "Th", "Fr", "Sa"], - abbreviated: ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"], - wide: ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"] -}; -var dayPeriodValues = { - narrow: { - am: "a", - pm: "p", - midnight: "mi", - noon: "n", - morning: "morning", - afternoon: "afternoon", - evening: "evening", - night: "night" - }, - abbreviated: { - am: "AM", - pm: "PM", - midnight: "midnight", - noon: "noon", - morning: "morning", - afternoon: "afternoon", - evening: "evening", - night: "night" - }, - wide: { - am: "a.m.", - pm: "p.m.", - midnight: "midnight", - noon: "noon", - morning: "morning", - afternoon: "afternoon", - evening: "evening", - night: "night" +var AbstractPointerSensor = class { + constructor(props2, events2, listenerTarget) { + var _getEventCoordinates; + if (listenerTarget === void 0) { + listenerTarget = getEventListenerTarget(props2.event.target); + } + this.props = void 0; + this.events = void 0; + this.autoScrollEnabled = true; + this.document = void 0; + this.activated = false; + this.initialCoordinates = void 0; + this.timeoutId = null; + this.listeners = void 0; + this.documentListeners = void 0; + this.windowListeners = void 0; + this.props = props2; + this.events = events2; + const { + event + } = props2; + const { + target + } = event; + this.props = props2; + this.events = events2; + this.document = getOwnerDocument(target); + this.documentListeners = new Listeners(this.document); + this.listeners = new Listeners(listenerTarget); + this.windowListeners = new Listeners(getWindow(target)); + this.initialCoordinates = (_getEventCoordinates = getEventCoordinates(event)) != null ? _getEventCoordinates : defaultCoordinates; + this.handleStart = this.handleStart.bind(this); + this.handleMove = this.handleMove.bind(this); + this.handleEnd = this.handleEnd.bind(this); + this.handleCancel = this.handleCancel.bind(this); + this.handleKeydown = this.handleKeydown.bind(this); + this.removeTextSelection = this.removeTextSelection.bind(this); + this.attach(); } -}; -var formattingDayPeriodValues = { - narrow: { - am: "a", - pm: "p", - midnight: "mi", - noon: "n", - morning: "in the morning", - afternoon: "in the afternoon", - evening: "in the evening", - night: "at night" - }, - abbreviated: { - am: "AM", - pm: "PM", - midnight: "midnight", - noon: "noon", - morning: "in the morning", - afternoon: "in the afternoon", - evening: "in the evening", - night: "at night" - }, - wide: { - am: "a.m.", - pm: "p.m.", - midnight: "midnight", - noon: "noon", - morning: "in the morning", - afternoon: "in the afternoon", - evening: "in the evening", - night: "at night" + attach() { + const { + events: events2, + props: { + options: { + activationConstraint + } + } + } = this; + this.listeners.add(events2.move.name, this.handleMove, { + passive: false + }); + this.listeners.add(events2.end.name, this.handleEnd); + this.windowListeners.add(EventName.Resize, this.handleCancel); + this.windowListeners.add(EventName.DragStart, preventDefault); + this.windowListeners.add(EventName.VisibilityChange, this.handleCancel); + this.windowListeners.add(EventName.ContextMenu, preventDefault); + this.documentListeners.add(EventName.Keydown, this.handleKeydown); + if (activationConstraint) { + if (isDistanceConstraint(activationConstraint)) { + return; + } + if (isDelayConstraint(activationConstraint)) { + this.timeoutId = setTimeout(this.handleStart, activationConstraint.delay); + return; + } + } + this.handleStart(); } -}; -var ordinalNumber = function ordinalNumber2(dirtyNumber, _options) { - var number = Number(dirtyNumber); - var rem100 = number % 100; - if (rem100 > 20 || rem100 < 10) { - switch (rem100 % 10) { - case 1: - return number + "st"; - case 2: - return number + "nd"; - case 3: - return number + "rd"; + detach() { + this.listeners.removeAll(); + this.windowListeners.removeAll(); + setTimeout(this.documentListeners.removeAll, 50); + if (this.timeoutId !== null) { + clearTimeout(this.timeoutId); + this.timeoutId = null; } } - return number + "th"; -}; -var localize = { - ordinalNumber, - era: buildLocalizeFn({ - values: eraValues, - defaultWidth: "wide" - }), - quarter: buildLocalizeFn({ - values: quarterValues, - defaultWidth: "wide", - argumentCallback: function argumentCallback(quarter) { - return quarter - 1; + handleStart() { + const { + initialCoordinates + } = this; + const { + onStart + } = this.props; + if (initialCoordinates) { + this.activated = true; + this.documentListeners.add(EventName.Click, stopPropagation, { + capture: true + }); + this.removeTextSelection(); + this.documentListeners.add(EventName.SelectionChange, this.removeTextSelection); + onStart(initialCoordinates); } - }), - month: buildLocalizeFn({ - values: monthValues, - defaultWidth: "wide" - }), - day: buildLocalizeFn({ - values: dayValues, - defaultWidth: "wide" - }), - dayPeriod: buildLocalizeFn({ - values: dayPeriodValues, - defaultWidth: "wide", - formattingValues: formattingDayPeriodValues, - defaultFormattingWidth: "wide" - }) -}; -var localize_default = localize; - -// node_modules/date-fns/esm/locale/_lib/buildMatchFn/index.js -function buildMatchFn(args) { - return function(string) { - var options = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {}; - var width = options.width; - var matchPattern = width && args.matchPatterns[width] || args.matchPatterns[args.defaultMatchWidth]; - var matchResult = string.match(matchPattern); - if (!matchResult) { - return null; + } + handleMove(event) { + var _getEventCoordinates2; + const { + activated, + initialCoordinates, + props: props2 + } = this; + const { + onMove, + options: { + activationConstraint + } + } = props2; + if (!initialCoordinates) { + return; } - var matchedString = matchResult[0]; - var parsePatterns = width && args.parsePatterns[width] || args.parsePatterns[args.defaultParseWidth]; - var key2 = Array.isArray(parsePatterns) ? findIndex(parsePatterns, function(pattern) { - return pattern.test(matchedString); - }) : findKey(parsePatterns, function(pattern) { - return pattern.test(matchedString); - }); - var value; - value = args.valueCallback ? args.valueCallback(key2) : key2; - value = options.valueCallback ? options.valueCallback(value) : value; - var rest = string.slice(matchedString.length); - return { - value, - rest - }; - }; -} -function findKey(object, predicate) { - for (var key2 in object) { - if (object.hasOwnProperty(key2) && predicate(object[key2])) { - return key2; + const coordinates = (_getEventCoordinates2 = getEventCoordinates(event)) != null ? _getEventCoordinates2 : defaultCoordinates; + const delta = subtract(initialCoordinates, coordinates); + if (!activated && activationConstraint) { + if (isDelayConstraint(activationConstraint)) { + if (hasExceededDistance(delta, activationConstraint.tolerance)) { + return this.handleCancel(); + } + return; + } + if (isDistanceConstraint(activationConstraint)) { + if (activationConstraint.tolerance != null && hasExceededDistance(delta, activationConstraint.tolerance)) { + return this.handleCancel(); + } + if (hasExceededDistance(delta, activationConstraint.distance)) { + return this.handleStart(); + } + return; + } + } + if (event.cancelable) { + event.preventDefault(); } + onMove(coordinates); } - return void 0; -} -function findIndex(array, predicate) { - for (var key2 = 0; key2 < array.length; key2++) { - if (predicate(array[key2])) { - return key2; + handleEnd() { + const { + onEnd + } = this.props; + this.detach(); + onEnd(); + } + handleCancel() { + const { + onCancel + } = this.props; + this.detach(); + onCancel(); + } + handleKeydown(event) { + if (event.code === KeyboardCode.Esc) { + this.handleCancel(); } } - return void 0; -} - -// node_modules/date-fns/esm/locale/_lib/buildMatchPatternFn/index.js -function buildMatchPatternFn(args) { - return function(string) { - var options = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {}; - var matchResult = string.match(args.matchPattern); - if (!matchResult) - return null; - var matchedString = matchResult[0]; - var parseResult = string.match(args.parsePattern); - if (!parseResult) - return null; - var value = args.valueCallback ? args.valueCallback(parseResult[0]) : parseResult[0]; - value = options.valueCallback ? options.valueCallback(value) : value; - var rest = string.slice(matchedString.length); - return { - value, - rest - }; - }; -} - -// node_modules/date-fns/esm/locale/en-US/_lib/match/index.js -var matchOrdinalNumberPattern = /^(\d+)(th|st|nd|rd)?/i; -var parseOrdinalNumberPattern = /\d+/i; -var matchEraPatterns = { - narrow: /^(b|a)/i, - abbreviated: /^(b\.?\s?c\.?|b\.?\s?c\.?\s?e\.?|a\.?\s?d\.?|c\.?\s?e\.?)/i, - wide: /^(before christ|before common era|anno domini|common era)/i -}; -var parseEraPatterns = { - any: [/^b/i, /^(a|c)/i] -}; -var matchQuarterPatterns = { - narrow: /^[1234]/i, - abbreviated: /^q[1234]/i, - wide: /^[1234](th|st|nd|rd)? quarter/i -}; -var parseQuarterPatterns = { - any: [/1/i, /2/i, /3/i, /4/i] -}; -var matchMonthPatterns = { - narrow: /^[jfmasond]/i, - abbreviated: /^(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)/i, - wide: /^(january|february|march|april|may|june|july|august|september|october|november|december)/i -}; -var parseMonthPatterns = { - narrow: [/^j/i, /^f/i, /^m/i, /^a/i, /^m/i, /^j/i, /^j/i, /^a/i, /^s/i, /^o/i, /^n/i, /^d/i], - any: [/^ja/i, /^f/i, /^mar/i, /^ap/i, /^may/i, /^jun/i, /^jul/i, /^au/i, /^s/i, /^o/i, /^n/i, /^d/i] -}; -var matchDayPatterns = { - narrow: /^[smtwf]/i, - short: /^(su|mo|tu|we|th|fr|sa)/i, - abbreviated: /^(sun|mon|tue|wed|thu|fri|sat)/i, - wide: /^(sunday|monday|tuesday|wednesday|thursday|friday|saturday)/i -}; -var parseDayPatterns = { - narrow: [/^s/i, /^m/i, /^t/i, /^w/i, /^t/i, /^f/i, /^s/i], - any: [/^su/i, /^m/i, /^tu/i, /^w/i, /^th/i, /^f/i, /^sa/i] + removeTextSelection() { + var _this$document$getSel; + (_this$document$getSel = this.document.getSelection()) == null ? void 0 : _this$document$getSel.removeAllRanges(); + } }; -var matchDayPeriodPatterns = { - narrow: /^(a|p|mi|n|(in the|at) (morning|afternoon|evening|night))/i, - any: /^([ap]\.?\s?m\.?|midnight|noon|(in the|at) (morning|afternoon|evening|night))/i +var events = { + move: { + name: "pointermove" + }, + end: { + name: "pointerup" + } }; -var parseDayPeriodPatterns = { - any: { - am: /^a/i, - pm: /^p/i, - midnight: /^mi/i, - noon: /^no/i, - morning: /morning/i, - afternoon: /afternoon/i, - evening: /evening/i, - night: /night/i +var PointerSensor = class extends AbstractPointerSensor { + constructor(props2) { + const { + event + } = props2; + const listenerTarget = getOwnerDocument(event.target); + super(props2, events, listenerTarget); } }; -var match = { - ordinalNumber: buildMatchPatternFn({ - matchPattern: matchOrdinalNumberPattern, - parsePattern: parseOrdinalNumberPattern, - valueCallback: function valueCallback(value) { - return parseInt(value, 10); - } - }), - era: buildMatchFn({ - matchPatterns: matchEraPatterns, - defaultMatchWidth: "wide", - parsePatterns: parseEraPatterns, - defaultParseWidth: "any" - }), - quarter: buildMatchFn({ - matchPatterns: matchQuarterPatterns, - defaultMatchWidth: "wide", - parsePatterns: parseQuarterPatterns, - defaultParseWidth: "any", - valueCallback: function valueCallback2(index) { - return index + 1; +PointerSensor.activators = [{ + eventName: "onPointerDown", + handler: (_ref, _ref2) => { + let { + nativeEvent: event + } = _ref; + let { + onActivation + } = _ref2; + if (!event.isPrimary || event.button !== 0) { + return false; } - }), - month: buildMatchFn({ - matchPatterns: matchMonthPatterns, - defaultMatchWidth: "wide", - parsePatterns: parseMonthPatterns, - defaultParseWidth: "any" - }), - day: buildMatchFn({ - matchPatterns: matchDayPatterns, - defaultMatchWidth: "wide", - parsePatterns: parseDayPatterns, - defaultParseWidth: "any" - }), - dayPeriod: buildMatchFn({ - matchPatterns: matchDayPeriodPatterns, - defaultMatchWidth: "any", - parsePatterns: parseDayPeriodPatterns, - defaultParseWidth: "any" - }) + onActivation == null ? void 0 : onActivation({ + event + }); + return true; + } +}]; +var events$1 = { + move: { + name: "mousemove" + }, + end: { + name: "mouseup" + } }; -var match_default = match; - -// node_modules/date-fns/esm/locale/en-US/index.js -var locale = { - code: "en-US", - formatDistance: formatDistance_default, - formatLong: formatLong_default, - formatRelative: formatRelative_default, - localize: localize_default, - match: match_default, - options: { - weekStartsOn: 0, - firstWeekContainsDate: 1 +var MouseButton; +(function(MouseButton2) { + MouseButton2[MouseButton2["RightClick"] = 2] = "RightClick"; +})(MouseButton || (MouseButton = {})); +var MouseSensor = class extends AbstractPointerSensor { + constructor(props2) { + super(props2, events$1, getOwnerDocument(props2.event.target)); } }; -var en_US_default = locale; - -// node_modules/date-fns/esm/_lib/defaultLocale/index.js -var defaultLocale_default = en_US_default; - -// node_modules/date-fns/esm/format/index.js -var formattingTokensRegExp = /[yYQqMLwIdDecihHKkms]o|(\w)\1*|''|'(''|[^'])+('|$)|./g; -var longFormattingTokensRegExp = /P+p+|P+|p+|''|'(''|[^'])+('|$)|./g; -var escapedStringRegExp = /^'([^]*?)'?$/; -var doubleQuoteRegExp = /''/g; -var unescapedLatinCharacterRegExp = /[a-zA-Z]/; -function format(dirtyDate, dirtyFormatStr, options) { - var _ref, _options$locale, _ref2, _ref3, _ref4, _options$firstWeekCon, _options$locale2, _options$locale2$opti, _defaultOptions$local, _defaultOptions$local2, _ref5, _ref6, _ref7, _options$weekStartsOn, _options$locale3, _options$locale3$opti, _defaultOptions$local3, _defaultOptions$local4; - requiredArgs(2, arguments); - var formatStr = String(dirtyFormatStr); - var defaultOptions3 = getDefaultOptions(); - var locale2 = (_ref = (_options$locale = options === null || options === void 0 ? void 0 : options.locale) !== null && _options$locale !== void 0 ? _options$locale : defaultOptions3.locale) !== null && _ref !== void 0 ? _ref : defaultLocale_default; - var firstWeekContainsDate = toInteger((_ref2 = (_ref3 = (_ref4 = (_options$firstWeekCon = options === null || options === void 0 ? void 0 : options.firstWeekContainsDate) !== null && _options$firstWeekCon !== void 0 ? _options$firstWeekCon : options === null || options === void 0 ? void 0 : (_options$locale2 = options.locale) === null || _options$locale2 === void 0 ? void 0 : (_options$locale2$opti = _options$locale2.options) === null || _options$locale2$opti === void 0 ? void 0 : _options$locale2$opti.firstWeekContainsDate) !== null && _ref4 !== void 0 ? _ref4 : defaultOptions3.firstWeekContainsDate) !== null && _ref3 !== void 0 ? _ref3 : (_defaultOptions$local = defaultOptions3.locale) === null || _defaultOptions$local === void 0 ? void 0 : (_defaultOptions$local2 = _defaultOptions$local.options) === null || _defaultOptions$local2 === void 0 ? void 0 : _defaultOptions$local2.firstWeekContainsDate) !== null && _ref2 !== void 0 ? _ref2 : 1); - if (!(firstWeekContainsDate >= 1 && firstWeekContainsDate <= 7)) { - throw new RangeError("firstWeekContainsDate must be between 1 and 7 inclusively"); +MouseSensor.activators = [{ + eventName: "onMouseDown", + handler: (_ref, _ref2) => { + let { + nativeEvent: event + } = _ref; + let { + onActivation + } = _ref2; + if (event.button === MouseButton.RightClick) { + return false; + } + onActivation == null ? void 0 : onActivation({ + event + }); + return true; } - var weekStartsOn = toInteger((_ref5 = (_ref6 = (_ref7 = (_options$weekStartsOn = options === null || options === void 0 ? void 0 : options.weekStartsOn) !== null && _options$weekStartsOn !== void 0 ? _options$weekStartsOn : options === null || options === void 0 ? void 0 : (_options$locale3 = options.locale) === null || _options$locale3 === void 0 ? void 0 : (_options$locale3$opti = _options$locale3.options) === null || _options$locale3$opti === void 0 ? void 0 : _options$locale3$opti.weekStartsOn) !== null && _ref7 !== void 0 ? _ref7 : defaultOptions3.weekStartsOn) !== null && _ref6 !== void 0 ? _ref6 : (_defaultOptions$local3 = defaultOptions3.locale) === null || _defaultOptions$local3 === void 0 ? void 0 : (_defaultOptions$local4 = _defaultOptions$local3.options) === null || _defaultOptions$local4 === void 0 ? void 0 : _defaultOptions$local4.weekStartsOn) !== null && _ref5 !== void 0 ? _ref5 : 0); - if (!(weekStartsOn >= 0 && weekStartsOn <= 6)) { - throw new RangeError("weekStartsOn must be between 0 and 6 inclusively"); +}]; +var events$2 = { + move: { + name: "touchmove" + }, + end: { + name: "touchend" } - if (!locale2.localize) { - throw new RangeError("locale must contain localize property"); +}; +var TouchSensor = class extends AbstractPointerSensor { + constructor(props2) { + super(props2, events$2); } - if (!locale2.formatLong) { - throw new RangeError("locale must contain formatLong property"); + static setup() { + window.addEventListener(events$2.move.name, noop3, { + capture: false, + passive: false + }); + return function teardown() { + window.removeEventListener(events$2.move.name, noop3); + }; + function noop3() { + } } - var originalDate = toDate(dirtyDate); - if (!isValid(originalDate)) { - throw new RangeError("Invalid time value"); +}; +TouchSensor.activators = [{ + eventName: "onTouchStart", + handler: (_ref, _ref2) => { + let { + nativeEvent: event + } = _ref; + let { + onActivation + } = _ref2; + const { + touches + } = event; + if (touches.length > 1) { + return false; + } + onActivation == null ? void 0 : onActivation({ + event + }); + return true; } - var timezoneOffset = getTimezoneOffsetInMilliseconds(originalDate); - var utcDate = subMilliseconds(originalDate, timezoneOffset); - var formatterOptions = { - firstWeekContainsDate, - weekStartsOn, - locale: locale2, - _originalDate: originalDate - }; - var result = formatStr.match(longFormattingTokensRegExp).map(function(substring) { - var firstCharacter = substring[0]; - if (firstCharacter === "p" || firstCharacter === "P") { - var longFormatter = longFormatters_default[firstCharacter]; - return longFormatter(substring, locale2.formatLong); +}]; +var AutoScrollActivator; +(function(AutoScrollActivator2) { + AutoScrollActivator2[AutoScrollActivator2["Pointer"] = 0] = "Pointer"; + AutoScrollActivator2[AutoScrollActivator2["DraggableRect"] = 1] = "DraggableRect"; +})(AutoScrollActivator || (AutoScrollActivator = {})); +var TraversalOrder; +(function(TraversalOrder2) { + TraversalOrder2[TraversalOrder2["TreeOrder"] = 0] = "TreeOrder"; + TraversalOrder2[TraversalOrder2["ReversedTreeOrder"] = 1] = "ReversedTreeOrder"; +})(TraversalOrder || (TraversalOrder = {})); +function useAutoScroller(_ref) { + let { + acceleration, + activator = AutoScrollActivator.Pointer, + canScroll, + draggingRect, + enabled, + interval = 5, + order = TraversalOrder.TreeOrder, + pointerCoordinates, + scrollableAncestors, + scrollableAncestorRects, + delta, + threshold + } = _ref; + const scrollIntent = useScrollIntent({ + delta, + disabled: !enabled + }); + const [setAutoScrollInterval, clearAutoScrollInterval] = useInterval(); + const scrollSpeed = _2({ + x: 0, + y: 0 + }); + const scrollDirection = _2({ + x: 0, + y: 0 + }); + const rect = F2(() => { + switch (activator) { + case AutoScrollActivator.Pointer: + return pointerCoordinates ? { + top: pointerCoordinates.y, + bottom: pointerCoordinates.y, + left: pointerCoordinates.x, + right: pointerCoordinates.x + } : null; + case AutoScrollActivator.DraggableRect: + return draggingRect; + } + }, [activator, draggingRect, pointerCoordinates]); + const scrollContainerRef = _2(null); + const autoScroll = T2(() => { + const scrollContainer = scrollContainerRef.current; + if (!scrollContainer) { + return; + } + const scrollLeft = scrollSpeed.current.x * scrollDirection.current.x; + const scrollTop = scrollSpeed.current.y * scrollDirection.current.y; + scrollContainer.scrollBy(scrollLeft, scrollTop); + }, []); + const sortedScrollableAncestors = F2(() => order === TraversalOrder.TreeOrder ? [...scrollableAncestors].reverse() : scrollableAncestors, [order, scrollableAncestors]); + p2( + () => { + if (!enabled || !scrollableAncestors.length || !rect) { + clearAutoScrollInterval(); + return; + } + for (const scrollContainer of sortedScrollableAncestors) { + if ((canScroll == null ? void 0 : canScroll(scrollContainer)) === false) { + continue; + } + const index = scrollableAncestors.indexOf(scrollContainer); + const scrollContainerRect = scrollableAncestorRects[index]; + if (!scrollContainerRect) { + continue; + } + const { + direction, + speed + } = getScrollDirectionAndSpeed(scrollContainer, scrollContainerRect, rect, acceleration, threshold); + for (const axis of ["x", "y"]) { + if (!scrollIntent[axis][direction[axis]]) { + speed[axis] = 0; + direction[axis] = 0; + } + } + if (speed.x > 0 || speed.y > 0) { + clearAutoScrollInterval(); + scrollContainerRef.current = scrollContainer; + setAutoScrollInterval(autoScroll, interval); + scrollSpeed.current = speed; + scrollDirection.current = direction; + return; + } + } + scrollSpeed.current = { + x: 0, + y: 0 + }; + scrollDirection.current = { + x: 0, + y: 0 + }; + clearAutoScrollInterval(); + }, + [ + acceleration, + autoScroll, + canScroll, + clearAutoScrollInterval, + enabled, + interval, + JSON.stringify(rect), + JSON.stringify(scrollIntent), + setAutoScrollInterval, + scrollableAncestors, + sortedScrollableAncestors, + scrollableAncestorRects, + JSON.stringify(threshold) + ] + ); +} +var defaultScrollIntent = { + x: { + [Direction2.Backward]: false, + [Direction2.Forward]: false + }, + y: { + [Direction2.Backward]: false, + [Direction2.Forward]: false + } +}; +function useScrollIntent(_ref2) { + let { + delta, + disabled + } = _ref2; + const previousDelta = usePrevious(delta); + return useLazyMemo((previousIntent) => { + if (disabled || !previousDelta || !previousIntent) { + return defaultScrollIntent; + } + const direction = { + x: Math.sign(delta.x - previousDelta.x), + y: Math.sign(delta.y - previousDelta.y) + }; + return { + x: { + [Direction2.Backward]: previousIntent.x[Direction2.Backward] || direction.x === -1, + [Direction2.Forward]: previousIntent.x[Direction2.Forward] || direction.x === 1 + }, + y: { + [Direction2.Backward]: previousIntent.y[Direction2.Backward] || direction.y === -1, + [Direction2.Forward]: previousIntent.y[Direction2.Forward] || direction.y === 1 + } + }; + }, [disabled, delta, previousDelta]); +} +function useCachedNode(draggableNodes, id2) { + const draggableNode = id2 !== null ? draggableNodes.get(id2) : void 0; + const node = draggableNode ? draggableNode.node.current : null; + return useLazyMemo((cachedNode) => { + var _ref; + if (id2 === null) { + return null; + } + return (_ref = node != null ? node : cachedNode) != null ? _ref : null; + }, [node, id2]); +} +function useCombineActivators(sensors, getSyntheticHandler) { + return F2(() => sensors.reduce((accumulator, sensor) => { + const { + sensor: Sensor + } = sensor; + const sensorActivators = Sensor.activators.map((activator) => ({ + eventName: activator.eventName, + handler: getSyntheticHandler(activator.handler, sensor) + })); + return [...accumulator, ...sensorActivators]; + }, []), [sensors, getSyntheticHandler]); +} +var MeasuringStrategy; +(function(MeasuringStrategy2) { + MeasuringStrategy2[MeasuringStrategy2["Always"] = 0] = "Always"; + MeasuringStrategy2[MeasuringStrategy2["BeforeDragging"] = 1] = "BeforeDragging"; + MeasuringStrategy2[MeasuringStrategy2["WhileDragging"] = 2] = "WhileDragging"; +})(MeasuringStrategy || (MeasuringStrategy = {})); +var MeasuringFrequency; +(function(MeasuringFrequency2) { + MeasuringFrequency2["Optimized"] = "optimized"; +})(MeasuringFrequency || (MeasuringFrequency = {})); +var defaultValue = /* @__PURE__ */ new Map(); +function useDroppableMeasuring(containers, _ref) { + let { + dragging, + dependencies, + config + } = _ref; + const [queue, setQueue] = h2(null); + const { + frequency, + measure, + strategy + } = config; + const containersRef = _2(containers); + const disabled = isDisabled(); + const disabledRef = useLatestValue(disabled); + const measureDroppableContainers = T2(function(ids2) { + if (ids2 === void 0) { + ids2 = []; + } + if (disabledRef.current) { + return; } - return substring; - }).join("").match(formattingTokensRegExp).map(function(substring) { - if (substring === "''") { - return "'"; + setQueue((value) => { + if (value === null) { + return ids2; + } + return value.concat(ids2.filter((id2) => !value.includes(id2))); + }); + }, [disabledRef]); + const timeoutId = _2(null); + const droppableRects = useLazyMemo((previousValue) => { + if (disabled && !dragging) { + return defaultValue; } - var firstCharacter = substring[0]; - if (firstCharacter === "'") { - return cleanEscapedString(substring); + if (!previousValue || previousValue === defaultValue || containersRef.current !== containers || queue != null) { + const map = /* @__PURE__ */ new Map(); + for (let container of containers) { + if (!container) { + continue; + } + if (queue && queue.length > 0 && !queue.includes(container.id) && container.rect.current) { + map.set(container.id, container.rect.current); + continue; + } + const node = container.node.current; + const rect = node ? new Rect(measure(node), node) : null; + container.rect.current = rect; + if (rect) { + map.set(container.id, rect); + } + } + return map; } - var formatter = formatters_default[firstCharacter]; - if (formatter) { - if (!(options !== null && options !== void 0 && options.useAdditionalWeekYearTokens) && isProtectedWeekYearToken(substring)) { - throwProtectedError(substring, dirtyFormatStr, String(dirtyDate)); + return previousValue; + }, [containers, queue, dragging, disabled, measure]); + p2(() => { + containersRef.current = containers; + }, [containers]); + p2( + () => { + if (disabled) { + return; } - if (!(options !== null && options !== void 0 && options.useAdditionalDayOfYearTokens) && isProtectedDayOfYearToken(substring)) { - throwProtectedError(substring, dirtyFormatStr, String(dirtyDate)); + measureDroppableContainers(); + }, + [dragging, disabled] + ); + p2( + () => { + if (queue && queue.length > 0) { + setQueue(null); } - return formatter(utcDate, substring, locale2.localize, formatterOptions); + }, + [JSON.stringify(queue)] + ); + p2( + () => { + if (disabled || typeof frequency !== "number" || timeoutId.current !== null) { + return; + } + timeoutId.current = setTimeout(() => { + measureDroppableContainers(); + timeoutId.current = null; + }, frequency); + }, + [frequency, disabled, measureDroppableContainers, ...dependencies] + ); + return { + droppableRects, + measureDroppableContainers, + measuringScheduled: queue != null + }; + function isDisabled() { + switch (strategy) { + case MeasuringStrategy.Always: + return false; + case MeasuringStrategy.BeforeDragging: + return dragging; + default: + return !dragging; } - if (firstCharacter.match(unescapedLatinCharacterRegExp)) { - throw new RangeError("Format string contains an unescaped latin alphabet character `" + firstCharacter + "`"); + } +} +function useInitialValue(value, computeFn) { + return useLazyMemo((previousValue) => { + if (!value) { + return null; } - return substring; - }).join(""); - return result; + if (previousValue) { + return previousValue; + } + return typeof computeFn === "function" ? computeFn(value) : value; + }, [computeFn, value]); } -function cleanEscapedString(input) { - var matched = input.match(escapedStringRegExp); - if (!matched) { - return input; - } - return matched[1].replace(doubleQuoteRegExp, "'"); +function useInitialRect(node, measure) { + return useInitialValue(node, measure); } - -// node_modules/date-fns/esm/_lib/assign/index.js -function assign(target, object) { - if (target == null) { - throw new TypeError("assign requires that input parameter not be null or undefined"); - } - for (var property in object) { - if (Object.prototype.hasOwnProperty.call(object, property)) { - ; - target[property] = object[property]; +function useMutationObserver(_ref) { + let { + callback, + disabled + } = _ref; + const handleMutations = useEvent(callback); + const mutationObserver = F2(() => { + if (disabled || typeof window === "undefined" || typeof window.MutationObserver === "undefined") { + return void 0; } - } - return target; + const { + MutationObserver + } = window; + return new MutationObserver(handleMutations); + }, [handleMutations, disabled]); + p2(() => { + return () => mutationObserver == null ? void 0 : mutationObserver.disconnect(); + }, [mutationObserver]); + return mutationObserver; } - -// node_modules/date-fns/esm/_lib/cloneObject/index.js -function cloneObject(object) { - return assign({}, object); +function useResizeObserver(_ref) { + let { + callback, + disabled + } = _ref; + const handleResize = useEvent(callback); + const resizeObserver = F2( + () => { + if (disabled || typeof window === "undefined" || typeof window.ResizeObserver === "undefined") { + return void 0; + } + const { + ResizeObserver + } = window; + return new ResizeObserver(handleResize); + }, + [disabled] + ); + p2(() => { + return () => resizeObserver == null ? void 0 : resizeObserver.disconnect(); + }, [resizeObserver]); + return resizeObserver; } - -// node_modules/date-fns/esm/formatDistance/index.js -var MINUTES_IN_DAY = 1440; -var MINUTES_IN_ALMOST_TWO_DAYS = 2520; -var MINUTES_IN_MONTH = 43200; -var MINUTES_IN_TWO_MONTHS = 86400; -function formatDistance3(dirtyDate, dirtyBaseDate, options) { - var _ref, _options$locale; - requiredArgs(2, arguments); - var defaultOptions3 = getDefaultOptions(); - var locale2 = (_ref = (_options$locale = options === null || options === void 0 ? void 0 : options.locale) !== null && _options$locale !== void 0 ? _options$locale : defaultOptions3.locale) !== null && _ref !== void 0 ? _ref : defaultLocale_default; - if (!locale2.formatDistance) { - throw new RangeError("locale must contain formatDistance property"); - } - var comparison = compareAsc(dirtyDate, dirtyBaseDate); - if (isNaN(comparison)) { - throw new RangeError("Invalid time value"); - } - var localizeOptions = assign(cloneObject(options), { - addSuffix: Boolean(options === null || options === void 0 ? void 0 : options.addSuffix), - comparison - }); - var dateLeft; - var dateRight; - if (comparison > 0) { - dateLeft = toDate(dirtyBaseDate); - dateRight = toDate(dirtyDate); - } else { - dateLeft = toDate(dirtyDate); - dateRight = toDate(dirtyBaseDate); +function defaultMeasure(element) { + return new Rect(getClientRect(element), element); +} +function useRect(element, measure, fallbackRect) { + if (measure === void 0) { + measure = defaultMeasure; } - var seconds = differenceInSeconds(dateRight, dateLeft); - var offsetInSeconds = (getTimezoneOffsetInMilliseconds(dateRight) - getTimezoneOffsetInMilliseconds(dateLeft)) / 1e3; - var minutes = Math.round((seconds - offsetInSeconds) / 60); - var months; - if (minutes < 2) { - if (options !== null && options !== void 0 && options.includeSeconds) { - if (seconds < 5) { - return locale2.formatDistance("lessThanXSeconds", 5, localizeOptions); - } else if (seconds < 10) { - return locale2.formatDistance("lessThanXSeconds", 10, localizeOptions); - } else if (seconds < 20) { - return locale2.formatDistance("lessThanXSeconds", 20, localizeOptions); - } else if (seconds < 40) { - return locale2.formatDistance("halfAMinute", 0, localizeOptions); - } else if (seconds < 60) { - return locale2.formatDistance("lessThanXMinutes", 1, localizeOptions); - } else { - return locale2.formatDistance("xMinutes", 1, localizeOptions); + const [rect, measureRect] = s2(reducer3, null); + const mutationObserver = useMutationObserver({ + callback(records) { + if (!element) { + return; } - } else { - if (minutes === 0) { - return locale2.formatDistance("lessThanXMinutes", 1, localizeOptions); - } else { - return locale2.formatDistance("xMinutes", minutes, localizeOptions); + for (const record of records) { + const { + type, + target + } = record; + if (type === "childList" && target instanceof HTMLElement && target.contains(element)) { + measureRect(); + break; + } } } - } else if (minutes < 45) { - return locale2.formatDistance("xMinutes", minutes, localizeOptions); - } else if (minutes < 90) { - return locale2.formatDistance("aboutXHours", 1, localizeOptions); - } else if (minutes < MINUTES_IN_DAY) { - var hours = Math.round(minutes / 60); - return locale2.formatDistance("aboutXHours", hours, localizeOptions); - } else if (minutes < MINUTES_IN_ALMOST_TWO_DAYS) { - return locale2.formatDistance("xDays", 1, localizeOptions); - } else if (minutes < MINUTES_IN_MONTH) { - var days = Math.round(minutes / MINUTES_IN_DAY); - return locale2.formatDistance("xDays", days, localizeOptions); - } else if (minutes < MINUTES_IN_TWO_MONTHS) { - months = Math.round(minutes / MINUTES_IN_MONTH); - return locale2.formatDistance("aboutXMonths", months, localizeOptions); - } - months = differenceInMonths(dateRight, dateLeft); - if (months < 12) { - var nearestMonth = Math.round(minutes / MINUTES_IN_MONTH); - return locale2.formatDistance("xMonths", nearestMonth, localizeOptions); - } else { - var monthsSinceStartOfYear = months % 12; - var years = Math.floor(months / 12); - if (monthsSinceStartOfYear < 3) { - return locale2.formatDistance("aboutXYears", years, localizeOptions); - } else if (monthsSinceStartOfYear < 9) { - return locale2.formatDistance("overXYears", years, localizeOptions); + }); + const resizeObserver = useResizeObserver({ + callback: measureRect + }); + useIsomorphicLayoutEffect(() => { + measureRect(); + if (element) { + resizeObserver == null ? void 0 : resizeObserver.observe(element); + mutationObserver == null ? void 0 : mutationObserver.observe(document.body, { + childList: true, + subtree: true + }); } else { - return locale2.formatDistance("almostXYears", years + 1, localizeOptions); + resizeObserver == null ? void 0 : resizeObserver.disconnect(); + mutationObserver == null ? void 0 : mutationObserver.disconnect(); + } + }, [element]); + return rect; + function reducer3(currentRect) { + if (!element) { + return null; + } + if (element.isConnected === false) { + var _ref; + return (_ref = currentRect != null ? currentRect : fallbackRect) != null ? _ref : null; + } + const newRect = measure(element); + if (JSON.stringify(currentRect) === JSON.stringify(newRect)) { + return currentRect; } + return newRect; } } - -// node_modules/date-fns/esm/getDaysInMonth/index.js -function getDaysInMonth(dirtyDate) { - requiredArgs(1, arguments); - var date = toDate(dirtyDate); - var year = date.getFullYear(); - var monthIndex = date.getMonth(); - var lastDayOfMonth2 = new Date(0); - lastDayOfMonth2.setFullYear(year, monthIndex + 1, 0); - lastDayOfMonth2.setHours(0, 0, 0, 0); - return lastDayOfMonth2.getDate(); -} - -// node_modules/date-fns/esm/getISOWeek/index.js -var MILLISECONDS_IN_WEEK4 = 6048e5; -function getISOWeek(dirtyDate) { - requiredArgs(1, arguments); - var date = toDate(dirtyDate); - var diff = startOfISOWeek(date).getTime() - startOfISOWeekYear(date).getTime(); - return Math.round(diff / MILLISECONDS_IN_WEEK4) + 1; +function useRectDelta(rect) { + const initialRect = useInitialValue(rect); + return getRectDelta(rect, initialRect); } - -// node_modules/date-fns/esm/getTime/index.js -function getTime(dirtyDate) { - requiredArgs(1, arguments); - var date = toDate(dirtyDate); - var timestamp = date.getTime(); - return timestamp; +var defaultValue$1 = []; +function useScrollableAncestors(node) { + const previousNode = _2(node); + const ancestors = useLazyMemo((previousValue) => { + if (!node) { + return defaultValue$1; + } + if (previousValue && previousValue !== defaultValue$1 && node && previousNode.current && node.parentNode === previousNode.current.parentNode) { + return previousValue; + } + return getScrollableAncestors(node); + }, [node]); + p2(() => { + previousNode.current = node; + }, [node]); + return ancestors; } - -// node_modules/date-fns/esm/getUnixTime/index.js -function getUnixTime(dirtyDate) { - requiredArgs(1, arguments); - return Math.floor(getTime(dirtyDate) / 1e3); +function useScrollOffsets(elements) { + const [scrollCoordinates, setScrollCoordinates] = h2(null); + const prevElements = _2(elements); + const handleScroll = T2((event) => { + const scrollingElement = getScrollableElement(event.target); + if (!scrollingElement) { + return; + } + setScrollCoordinates((scrollCoordinates2) => { + if (!scrollCoordinates2) { + return null; + } + scrollCoordinates2.set(scrollingElement, getScrollCoordinates(scrollingElement)); + return new Map(scrollCoordinates2); + }); + }, []); + p2(() => { + const previousElements = prevElements.current; + if (elements !== previousElements) { + cleanup(previousElements); + const entries = elements.map((element) => { + const scrollableElement = getScrollableElement(element); + if (scrollableElement) { + scrollableElement.addEventListener("scroll", handleScroll, { + passive: true + }); + return [scrollableElement, getScrollCoordinates(scrollableElement)]; + } + return null; + }).filter((entry) => entry != null); + setScrollCoordinates(entries.length ? new Map(entries) : null); + prevElements.current = elements; + } + return () => { + cleanup(elements); + cleanup(previousElements); + }; + function cleanup(elements2) { + elements2.forEach((element) => { + const scrollableElement = getScrollableElement(element); + scrollableElement == null ? void 0 : scrollableElement.removeEventListener("scroll", handleScroll); + }); + } + }, [handleScroll, elements]); + return F2(() => { + if (elements.length) { + return scrollCoordinates ? Array.from(scrollCoordinates.values()).reduce((acc, coordinates) => add(acc, coordinates), defaultCoordinates) : getScrollOffsets(elements); + } + return defaultCoordinates; + }, [elements, scrollCoordinates]); } - -// node_modules/date-fns/esm/getWeekYear/index.js -function getWeekYear(dirtyDate, options) { - var _ref, _ref2, _ref3, _options$firstWeekCon, _options$locale, _options$locale$optio, _defaultOptions$local, _defaultOptions$local2; - requiredArgs(1, arguments); - var date = toDate(dirtyDate); - var year = date.getFullYear(); - var defaultOptions3 = getDefaultOptions(); - var firstWeekContainsDate = toInteger((_ref = (_ref2 = (_ref3 = (_options$firstWeekCon = options === null || options === void 0 ? void 0 : options.firstWeekContainsDate) !== null && _options$firstWeekCon !== void 0 ? _options$firstWeekCon : options === null || options === void 0 ? void 0 : (_options$locale = options.locale) === null || _options$locale === void 0 ? void 0 : (_options$locale$optio = _options$locale.options) === null || _options$locale$optio === void 0 ? void 0 : _options$locale$optio.firstWeekContainsDate) !== null && _ref3 !== void 0 ? _ref3 : defaultOptions3.firstWeekContainsDate) !== null && _ref2 !== void 0 ? _ref2 : (_defaultOptions$local = defaultOptions3.locale) === null || _defaultOptions$local === void 0 ? void 0 : (_defaultOptions$local2 = _defaultOptions$local.options) === null || _defaultOptions$local2 === void 0 ? void 0 : _defaultOptions$local2.firstWeekContainsDate) !== null && _ref !== void 0 ? _ref : 1); - if (!(firstWeekContainsDate >= 1 && firstWeekContainsDate <= 7)) { - throw new RangeError("firstWeekContainsDate must be between 1 and 7 inclusively"); - } - var firstWeekOfNextYear = new Date(0); - firstWeekOfNextYear.setFullYear(year + 1, 0, firstWeekContainsDate); - firstWeekOfNextYear.setHours(0, 0, 0, 0); - var startOfNextYear = startOfWeek(firstWeekOfNextYear, options); - var firstWeekOfThisYear = new Date(0); - firstWeekOfThisYear.setFullYear(year, 0, firstWeekContainsDate); - firstWeekOfThisYear.setHours(0, 0, 0, 0); - var startOfThisYear = startOfWeek(firstWeekOfThisYear, options); - if (date.getTime() >= startOfNextYear.getTime()) { - return year + 1; - } else if (date.getTime() >= startOfThisYear.getTime()) { - return year; - } else { - return year - 1; +function useScrollOffsetsDelta(scrollOffsets, dependencies) { + if (dependencies === void 0) { + dependencies = []; } + const initialScrollOffsets = _2(null); + p2( + () => { + initialScrollOffsets.current = null; + }, + dependencies + ); + p2(() => { + const hasScrollOffsets = scrollOffsets !== defaultCoordinates; + if (hasScrollOffsets && !initialScrollOffsets.current) { + initialScrollOffsets.current = scrollOffsets; + } + if (!hasScrollOffsets && initialScrollOffsets.current) { + initialScrollOffsets.current = null; + } + }, [scrollOffsets]); + return initialScrollOffsets.current ? subtract(scrollOffsets, initialScrollOffsets.current) : defaultCoordinates; } - -// node_modules/date-fns/esm/startOfWeekYear/index.js -function startOfWeekYear(dirtyDate, options) { - var _ref, _ref2, _ref3, _options$firstWeekCon, _options$locale, _options$locale$optio, _defaultOptions$local, _defaultOptions$local2; - requiredArgs(1, arguments); - var defaultOptions3 = getDefaultOptions(); - var firstWeekContainsDate = toInteger((_ref = (_ref2 = (_ref3 = (_options$firstWeekCon = options === null || options === void 0 ? void 0 : options.firstWeekContainsDate) !== null && _options$firstWeekCon !== void 0 ? _options$firstWeekCon : options === null || options === void 0 ? void 0 : (_options$locale = options.locale) === null || _options$locale === void 0 ? void 0 : (_options$locale$optio = _options$locale.options) === null || _options$locale$optio === void 0 ? void 0 : _options$locale$optio.firstWeekContainsDate) !== null && _ref3 !== void 0 ? _ref3 : defaultOptions3.firstWeekContainsDate) !== null && _ref2 !== void 0 ? _ref2 : (_defaultOptions$local = defaultOptions3.locale) === null || _defaultOptions$local === void 0 ? void 0 : (_defaultOptions$local2 = _defaultOptions$local.options) === null || _defaultOptions$local2 === void 0 ? void 0 : _defaultOptions$local2.firstWeekContainsDate) !== null && _ref !== void 0 ? _ref : 1); - var year = getWeekYear(dirtyDate, options); - var firstWeek = new Date(0); - firstWeek.setFullYear(year, 0, firstWeekContainsDate); - firstWeek.setHours(0, 0, 0, 0); - var date = startOfWeek(firstWeek, options); - return date; -} - -// node_modules/date-fns/esm/getWeek/index.js -var MILLISECONDS_IN_WEEK5 = 6048e5; -function getWeek(dirtyDate, options) { - requiredArgs(1, arguments); - var date = toDate(dirtyDate); - var diff = startOfWeek(date, options).getTime() - startOfWeekYear(date, options).getTime(); - return Math.round(diff / MILLISECONDS_IN_WEEK5) + 1; -} - -// node_modules/date-fns/esm/lastDayOfMonth/index.js -function lastDayOfMonth(dirtyDate) { - requiredArgs(1, arguments); - var date = toDate(dirtyDate); - var month = date.getMonth(); - date.setFullYear(date.getFullYear(), month + 1, 0); - date.setHours(0, 0, 0, 0); - return date; -} - -// node_modules/date-fns/esm/getWeeksInMonth/index.js -function getWeeksInMonth(date, options) { - requiredArgs(1, arguments); - return differenceInCalendarWeeks(lastDayOfMonth(date), startOfMonth(date), options) + 1; -} - -// node_modules/date-fns/esm/isAfter/index.js -function isAfter(dirtyDate, dirtyDateToCompare) { - requiredArgs(2, arguments); - var date = toDate(dirtyDate); - var dateToCompare = toDate(dirtyDateToCompare); - return date.getTime() > dateToCompare.getTime(); -} - -// node_modules/date-fns/esm/isBefore/index.js -function isBefore(dirtyDate, dirtyDateToCompare) { - requiredArgs(2, arguments); - var date = toDate(dirtyDate); - var dateToCompare = toDate(dirtyDateToCompare); - return date.getTime() < dateToCompare.getTime(); -} - -// node_modules/date-fns/esm/isSameMonth/index.js -function isSameMonth(dirtyDateLeft, dirtyDateRight) { - requiredArgs(2, arguments); - var dateLeft = toDate(dirtyDateLeft); - var dateRight = toDate(dirtyDateRight); - return dateLeft.getFullYear() === dateRight.getFullYear() && dateLeft.getMonth() === dateRight.getMonth(); +function useSensorSetup(sensors) { + p2( + () => { + if (!canUseDOM) { + return; + } + const teardownFns = sensors.map((_ref) => { + let { + sensor + } = _ref; + return sensor.setup == null ? void 0 : sensor.setup(); + }); + return () => { + for (const teardown of teardownFns) { + teardown == null ? void 0 : teardown(); + } + }; + }, + sensors.map((_ref2) => { + let { + sensor + } = _ref2; + return sensor; + }) + ); } - -// node_modules/date-fns/esm/isSameYear/index.js -function isSameYear(dirtyDateLeft, dirtyDateRight) { - requiredArgs(2, arguments); - var dateLeft = toDate(dirtyDateLeft); - var dateRight = toDate(dirtyDateRight); - return dateLeft.getFullYear() === dateRight.getFullYear(); +function useSyntheticListeners(listeners, id2) { + return F2(() => { + return listeners.reduce((acc, _ref) => { + let { + eventName, + handler + } = _ref; + acc[eventName] = (event) => { + handler(event, id2); + }; + return acc; + }, {}); + }, [listeners, id2]); } - -// node_modules/date-fns/esm/subDays/index.js -function subDays(dirtyDate, dirtyAmount) { - requiredArgs(2, arguments); - var amount = toInteger(dirtyAmount); - return addDays(dirtyDate, -amount); +function useWindowRect(element) { + return F2(() => element ? getWindowClientRect(element) : null, [element]); } - -// node_modules/date-fns/esm/setMonth/index.js -function setMonth(dirtyDate, dirtyMonth) { - requiredArgs(2, arguments); - var date = toDate(dirtyDate); - var month = toInteger(dirtyMonth); - var year = date.getFullYear(); - var day = date.getDate(); - var dateWithDesiredMonth = new Date(0); - dateWithDesiredMonth.setFullYear(year, month, 15); - dateWithDesiredMonth.setHours(0, 0, 0, 0); - var daysInMonth = getDaysInMonth(dateWithDesiredMonth); - date.setMonth(month, Math.min(day, daysInMonth)); - return date; +var defaultValue$2 = []; +function useRects(elements, measure) { + if (measure === void 0) { + measure = getClientRect; + } + const [firstElement] = elements; + const windowRect = useWindowRect(firstElement ? getWindow(firstElement) : null); + const [rects, measureRects] = s2(reducer3, defaultValue$2); + const resizeObserver = useResizeObserver({ + callback: measureRects + }); + if (elements.length > 0 && rects === defaultValue$2) { + measureRects(); + } + useIsomorphicLayoutEffect(() => { + if (elements.length) { + elements.forEach((element) => resizeObserver == null ? void 0 : resizeObserver.observe(element)); + } else { + resizeObserver == null ? void 0 : resizeObserver.disconnect(); + measureRects(); + } + }, [elements]); + return rects; + function reducer3() { + if (!elements.length) { + return defaultValue$2; + } + return elements.map((element) => isDocumentScrollingElement(element) ? windowRect : new Rect(measure(element), element)); + } } - -// node_modules/date-fns/esm/setYear/index.js -function setYear(dirtyDate, dirtyYear) { - requiredArgs(2, arguments); - var date = toDate(dirtyDate); - var year = toInteger(dirtyYear); - if (isNaN(date.getTime())) { - return new Date(NaN); +function getMeasurableNode(node) { + if (!node) { + return null; } - date.setFullYear(year); - return date; + if (node.children.length > 1) { + return node; + } + const firstChild = node.children[0]; + return isHTMLElement(firstChild) ? firstChild : node; } - -// src/utils/metadata/frontmatter/fm.ts -var import_lodash = __toESM(require_lodash()); -var import_obsidian5 = require("obsidian"); - -// src/utils/metadata/dv.ts -var import_obsidian4 = require("obsidian"); -var LocationWrapper = { - fullLine: { start: "", end: "" }, - brackets: { start: "[", end: "]" }, - parenthesis: { start: "(", end: ")" } +function useDragOverlayMeasuring(_ref) { + let { + measure + } = _ref; + const [rect, setRect] = h2(null); + const handleResize = T2((entries) => { + for (const { + target + } of entries) { + if (isHTMLElement(target)) { + setRect((rect2) => { + const newRect = measure(target); + return rect2 ? { + ...rect2, + width: newRect.width, + height: newRect.height + } : newRect; + }); + break; + } + } + }, [measure]); + const resizeObserver = useResizeObserver({ + callback: handleResize + }); + const handleNodeChange = T2((element) => { + const node = getMeasurableNode(element); + resizeObserver == null ? void 0 : resizeObserver.disconnect(); + if (node) { + resizeObserver == null ? void 0 : resizeObserver.observe(node); + } + setRect(node ? measure(node) : null); + }, [measure, resizeObserver]); + const [nodeRef, setRef] = useNodeRef(handleNodeChange); + return F2(() => ({ + nodeRef, + rect, + setRef + }), [rect, nodeRef, setRef]); +} +var defaultSensors = [{ + sensor: PointerSensor, + options: {} +}, { + sensor: KeyboardSensor, + options: {} +}]; +var defaultData = { + current: {} }; -var fieldComponents = [ - "inQuote", - "inList", - "startStyle", - "attribute", - "endStyle", - "beforeSeparatorSpacer", - "afterSeparatorSpacer", - "values" -]; -var genericFieldRegex = "(?>(\\s+)?)?(?- )?(?[_\\*~`]*)(?[0-9\\w\\p{Letter}\\p{Emoji_Presentation}][-0-9\\w\\p{Letter}\\p{Emoji_Presentation}\\s]*)(?[_\\*~`]*)(?\\s*)"; -var inlineFieldRegex = (attribute) => `(?>(\\s+)?)?(?- )?(?[_\\*~\`]*)(?${attribute})(?[_\\*~\`]*)(?\\s*)::(?\\s*)`; -var fullLineRegex = new RegExp( - `^${genericFieldRegex}::\\s*(?.*)?`, - "u" -); -var inSentenceRegexBrackets = new RegExp( - `\\[${genericFieldRegex}::\\s*(?[^\\]]+)?\\]`, - "gu" -); -var inSentenceRegexPar = new RegExp( - `\\(${genericFieldRegex}::\\s*(?[^\\)]+)?\\)`, - "gu" -); -var encodeLink = (value) => { - return value ? value.replace(/\[\[/g, "\u{1F54C}\u{1F527}").replace(/\]\]/g, "\u{1F413}\u{1F400}") : value; +var defaultMeasuringConfiguration = { + draggable: { + measure: getTransformAgnosticClientRect + }, + droppable: { + measure: getTransformAgnosticClientRect, + strategy: MeasuringStrategy.WhileDragging, + frequency: MeasuringFrequency.Optimized + }, + dragOverlay: { + measure: getClientRect + } }; -var decodeLink = (value) => { - return value ? value.replace(/🕌🔧/gu, "[[").replace(/🐓🐀/gu, "]]") : value; +var DroppableContainersMap = class extends Map { + get(id2) { + var _super$get; + return id2 != null ? (_super$get = super.get(id2)) != null ? _super$get : void 0 : void 0; + } + toArray() { + return Array.from(this.values()); + } + getEnabled() { + return this.toArray().filter((_ref) => { + let { + disabled + } = _ref; + return !disabled; + }); + } + getNodeFor(id2) { + var _this$get$node$curren, _this$get; + return (_this$get$node$curren = (_this$get = this.get(id2)) == null ? void 0 : _this$get.node.current) != null ? _this$get$node$curren : void 0; + } }; -var matchInlineFields = (regex, line, attribute, input, location = "fullLine") => { - const sR = line.matchAll(regex); - let next = sR.next(); - const newFields = []; - while (!next.done) { - const match2 = next.value; - if (match2.groups && Object.keys(match2.groups).every((j4) => fieldComponents.includes(j4))) { +var defaultPublicContext = { + activatorEvent: null, + active: null, + activeNode: null, + activeNodeRect: null, + collisions: null, + containerNodeRect: null, + draggableNodes: /* @__PURE__ */ new Map(), + droppableRects: /* @__PURE__ */ new Map(), + droppableContainers: /* @__PURE__ */ new DroppableContainersMap(), + over: null, + dragOverlay: { + nodeRef: { + current: null + }, + rect: null, + setRef: noop + }, + scrollableAncestors: [], + scrollableAncestorRects: [], + measuringConfiguration: defaultMeasuringConfiguration, + measureDroppableContainers: noop, + windowRect: null, + measuringScheduled: false +}; +var defaultInternalContext = { + activatorEvent: null, + activators: [], + active: null, + activeNodeRect: null, + ariaDescribedById: { + draggable: "" + }, + dispatch: noop, + draggableNodes: /* @__PURE__ */ new Map(), + over: null, + measureDroppableContainers: noop +}; +var InternalContext = /* @__PURE__ */ F(defaultInternalContext); +var PublicContext = /* @__PURE__ */ F(defaultPublicContext); +function getInitialState() { + return { + draggable: { + active: null, + initialCoordinates: { + x: 0, + y: 0 + }, + nodes: /* @__PURE__ */ new Map(), + translate: { + x: 0, + y: 0 + } + }, + droppable: { + containers: new DroppableContainersMap() + } + }; +} +function reducer(state, action) { + switch (action.type) { + case Action.DragStart: + return { + ...state, + draggable: { + ...state.draggable, + initialCoordinates: action.initialCoordinates, + active: action.active + } + }; + case Action.DragMove: + if (!state.draggable.active) { + return state; + } + return { + ...state, + draggable: { + ...state.draggable, + translate: { + x: action.coordinates.x - state.draggable.initialCoordinates.x, + y: action.coordinates.y - state.draggable.initialCoordinates.y + } + } + }; + case Action.DragEnd: + case Action.DragCancel: + return { + ...state, + draggable: { + ...state.draggable, + active: null, + initialCoordinates: { + x: 0, + y: 0 + }, + translate: { + x: 0, + y: 0 + } + } + }; + case Action.RegisterDroppable: { const { - inList, - inQuote, - startStyle, - endStyle, - beforeSeparatorSpacer, - afterSeparatorSpacer, - values - } = match2.groups; - const inputArray = input ? input.replace(/(\,\s+)/g, ",").split(",") : [""]; - const newValue = inputArray.length == 1 ? inputArray[0] : `${serializeMultiDisplayString(inputArray)}`; - const start = LocationWrapper[location].start; - const end = LocationWrapper[location].end; - newFields.push({ - oldField: match2[0], - newField: `${inQuote || ""}${start}${inList || ""}${startStyle}${attribute}${endStyle}${beforeSeparatorSpacer}::${afterSeparatorSpacer}${newValue}${end}` + element + } = action; + const { + id: id2 + } = element; + const containers = new DroppableContainersMap(state.droppable.containers); + containers.set(id2, element); + return { + ...state, + droppable: { + ...state.droppable, + containers + } + }; + } + case Action.SetDroppableDisabled: { + const { + id: id2, + key: key2, + disabled + } = action; + const element = state.droppable.containers.get(id2); + if (!element || key2 !== element.key) { + return state; + } + const containers = new DroppableContainersMap(state.droppable.containers); + containers.set(id2, { + ...element, + disabled }); + return { + ...state, + droppable: { + ...state.droppable, + containers + } + }; } - next = sR.next(); - } - return newFields; -}; -async function replaceValues(plugin, fileOrFilePath, attribute, input, previousItemsCount = 0) { - var _a2, _b2; - let file; - if (fileOrFilePath instanceof import_obsidian4.TFile) { - file = fileOrFilePath; - } else { - const _file = plugin.app.vault.getAbstractFileByPath(fileOrFilePath); - if (_file instanceof import_obsidian4.TFile && _file.extension == "md") { - file = _file; - } else { - throw Error("path doesn't correspond to a proper file"); + case Action.UnregisterDroppable: { + const { + id: id2, + key: key2 + } = action; + const element = state.droppable.containers.get(id2); + if (!element || key2 !== element.key) { + return state; + } + const containers = new DroppableContainersMap(state.droppable.containers); + containers.delete(id2); + return { + ...state, + droppable: { + ...state.droppable, + containers + } + }; + } + default: { + return state; } } - const content = (await plugin.app.vault.read(file)).split("\n"); - const frontmatter = (_a2 = plugin.app.metadataCache.getFileCache(file)) == null ? void 0 : _a2.frontmatter; - const skippedLines = []; +} +function RestoreFocus(_ref) { + let { + disabled + } = _ref; const { - position: { start, end } - } = frontmatter ? frontmatter : { position: { start: void 0, end: void 0 } }; - const newContent = content.map((line, i4) => { - const encodedInput = encodeLink(input); - let encodedLine = encodeLink(line); - const fullLineRegex2 = new RegExp( - `^${inlineFieldRegex(attribute)}(?[^\\]]*)`, - "u" - ); - const fR = encodedLine.match(fullLineRegex2); - if ((fR == null ? void 0 : fR.groups) && Object.keys(fR.groups).every((j4) => fieldComponents.includes(j4))) { + active, + activatorEvent, + draggableNodes + } = q2(InternalContext); + const previousActivatorEvent = usePrevious(activatorEvent); + const previousActiveId = usePrevious(active == null ? void 0 : active.id); + p2(() => { + if (disabled) { + return; + } + if (!activatorEvent && previousActivatorEvent && previousActiveId != null) { + if (!isKeyboardEvent(previousActivatorEvent)) { + return; + } + if (document.activeElement === previousActivatorEvent.target) { + return; + } + const draggableNode = draggableNodes.get(previousActiveId); + if (!draggableNode) { + return; + } const { - inList, - inQuote, - startStyle, - endStyle, - beforeSeparatorSpacer, - afterSeparatorSpacer, - values - } = fR.groups; - const inputArray = input ? input.replace(/(\,\s+)/g, ",").split(",").sort() : []; - let newValue; - let hiddenValue = ""; - newValue = inputArray.length == 1 ? inputArray[0] : `${serializeMultiDisplayString(inputArray)}`; - return `${inQuote || ""}${inList || ""}${startStyle}${attribute}${endStyle}${beforeSeparatorSpacer}::${afterSeparatorSpacer}${hiddenValue + newValue}`; - } else { - const newFields = []; - const inSentenceRegexBrackets2 = new RegExp( - `\\[${inlineFieldRegex(attribute)}(?[^\\]]+)?\\]`, - "gu" - ); - const inSentenceRegexPar2 = new RegExp( - `\\(${inlineFieldRegex(attribute)}(?[^\\)]+)?\\)`, - "gu" - ); - newFields.push( - ...matchInlineFields( - inSentenceRegexBrackets2, - encodedLine, - attribute, - encodedInput, - "brackets" /* brackets */ - ) - ); - newFields.push( - ...matchInlineFields( - inSentenceRegexPar2, - encodedLine, - attribute, - encodedInput, - "parenthesis" /* parenthesis */ - ) - ); - newFields.forEach((field) => { - const fieldRegex = new RegExp( - field.oldField.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"), - "u" - ); - encodedLine = encodedLine.replace(fieldRegex, field.newField); + activatorNode, + node + } = draggableNode; + if (!activatorNode.current && !node.current) { + return; + } + requestAnimationFrame(() => { + for (const element of [activatorNode.current, node.current]) { + if (!element) { + continue; + } + const focusableNode = findFirstFocusableNode(element); + if (focusableNode) { + focusableNode.focus(); + break; + } + } }); - return decodeLink(encodedLine); } - }); - await plugin.app.vault.modify( - file, - newContent.filter((line, i4) => !skippedLines.includes(i4)).join("\n") - ); - const editor = (_b2 = plugin.app.workspace.getActiveViewOfType(import_obsidian4.MarkdownView)) == null ? void 0 : _b2.editor; - if (editor) { - const lineNumber = editor.getCursor().line; - editor.setCursor({ - line: editor.getCursor().line, - ch: editor.getLine(lineNumber).length + }, [activatorEvent, disabled, draggableNodes, previousActiveId, previousActivatorEvent]); + return null; +} +function applyModifiers(modifiers, _ref) { + let { + transform, + ...args + } = _ref; + return modifiers != null && modifiers.length ? modifiers.reduce((accumulator, modifier) => { + return modifier({ + transform: accumulator, + ...args }); - } + }, transform) : transform; } - -// src/utils/metadata/frontmatter/detectYAMLType.ts -var detectYAMLType = (value, key2) => { - if (typeof value === "string") { - if (/\/\/(\S+?(?:jpe?g|png|gif|svg))/gi.test(value) || value.includes("unsplash")) { - return "image"; +function useMeasuringConfiguration(config) { + return F2( + () => ({ + draggable: { + ...defaultMeasuringConfiguration.draggable, + ...config == null ? void 0 : config.draggable + }, + droppable: { + ...defaultMeasuringConfiguration.droppable, + ...config == null ? void 0 : config.droppable + }, + dragOverlay: { + ...defaultMeasuringConfiguration.dragOverlay, + ...config == null ? void 0 : config.dragOverlay + } + }), + [config == null ? void 0 : config.draggable, config == null ? void 0 : config.droppable, config == null ? void 0 : config.dragOverlay] + ); +} +function useLayoutShiftScrollCompensation(_ref) { + let { + activeNode, + measure, + initialRect, + config = true + } = _ref; + const initialized = _2(false); + const { + x: x5, + y: y5 + } = typeof config === "boolean" ? { + x: config, + y: config + } : config; + useIsomorphicLayoutEffect(() => { + const disabled = !x5 && !y5; + if (disabled || !activeNode) { + initialized.current = false; + return; } - if (/^\d{4}-\d{2}-\d{2}$/.test(value)) { - return "date"; + if (initialized.current || !initialRect) { + return; } - if (key2 == "tag" || key2 == "tags") { - return "tag"; + const node = activeNode == null ? void 0 : activeNode.node.current; + if (!node || node.isConnected === false) { + return; } - if (/\[\[.*?\]\]/.test(value)) { - return "link"; + const rect = measure(node); + const rectDelta = getRectDelta(rect, initialRect); + if (!x5) { + rectDelta.x = 0; } - } else if (typeof value === "number") { - return "number"; - } else if (typeof value === "boolean") { - return "boolean"; - } else if (!value) { - return "unknown"; - } else if (Array.isArray(value) || typeof value === "string" && value.indexOf(",") > -1) { - let arrayValue = Array.isArray(value) ? value : []; - if (typeof value === "string" && value.indexOf(",") > -1) { - arrayValue = parseMultiString(value); + if (!y5) { + rectDelta.y = 0; } - if (key2 == "tag" || key2 == "tags") { - return "tag-multi"; + initialized.current = true; + if (Math.abs(rectDelta.x) > 0 || Math.abs(rectDelta.y) > 0) { + const firstScrollableAncestor = getFirstScrollableAncestor(node); + if (firstScrollableAncestor) { + firstScrollableAncestor.scrollBy({ + top: rectDelta.y, + left: rectDelta.x + }); + } } - if (arrayValue.length == 1 && Array.isArray(arrayValue[0]) && arrayValue[0].length == 1 && typeof arrayValue[0][0] === "string") { - return "link"; + }, [activeNode, x5, y5, initialRect, measure]); +} +var ActiveDraggableContext = /* @__PURE__ */ F({ + ...defaultCoordinates, + scaleX: 1, + scaleY: 1 +}); +var Status; +(function(Status2) { + Status2[Status2["Uninitialized"] = 0] = "Uninitialized"; + Status2[Status2["Initializing"] = 1] = "Initializing"; + Status2[Status2["Initialized"] = 2] = "Initialized"; +})(Status || (Status = {})); +var DndContext = /* @__PURE__ */ x3(function DndContext2(_ref) { + var _sensorContext$curren, _dragOverlay$nodeRef$, _dragOverlay$rect, _over$rect; + let { + id: id2, + accessibility, + autoScroll = true, + children, + sensors = defaultSensors, + collisionDetection = rectIntersection, + measuring, + modifiers, + ...props2 + } = _ref; + const store = s2(reducer, void 0, getInitialState); + const [state, dispatch] = store; + const [dispatchMonitorEvent, registerMonitorListener] = useDndMonitorProvider(); + const [status, setStatus] = h2(Status.Uninitialized); + const isInitialized = status === Status.Initialized; + const { + draggable: { + active: activeId, + nodes: draggableNodes, + translate + }, + droppable: { + containers: droppableContainers } - const types = uniq(arrayValue.map((f4) => detectYAMLType(f4, key2))); - if (types.length == 1 && types[0] == "link") { - return "link-multi"; + } = state; + const node = activeId ? draggableNodes.get(activeId) : null; + const activeRects = _2({ + initial: null, + translated: null + }); + const active = F2(() => { + var _node$data; + return activeId != null ? { + id: activeId, + data: (_node$data = node == null ? void 0 : node.data) != null ? _node$data : defaultData, + rect: activeRects + } : null; + }, [activeId, node]); + const activeRef = _2(null); + const [activeSensor, setActiveSensor] = h2(null); + const [activatorEvent, setActivatorEvent] = h2(null); + const latestProps = useLatestValue(props2, Object.values(props2)); + const draggableDescribedById = useUniqueId("DndDescribedBy", id2); + const enabledDroppableContainers = F2(() => droppableContainers.getEnabled(), [droppableContainers]); + const measuringConfiguration = useMeasuringConfiguration(measuring); + const { + droppableRects, + measureDroppableContainers, + measuringScheduled + } = useDroppableMeasuring(enabledDroppableContainers, { + dragging: isInitialized, + dependencies: [translate.x, translate.y], + config: measuringConfiguration.droppable + }); + const activeNode = useCachedNode(draggableNodes, activeId); + const activationCoordinates = F2(() => activatorEvent ? getEventCoordinates(activatorEvent) : null, [activatorEvent]); + const autoScrollOptions = getAutoScrollerOptions(); + const initialActiveNodeRect = useInitialRect(activeNode, measuringConfiguration.draggable.measure); + useLayoutShiftScrollCompensation({ + activeNode: activeId ? draggableNodes.get(activeId) : null, + config: autoScrollOptions.layoutShiftCompensation, + initialRect: initialActiveNodeRect, + measure: measuringConfiguration.draggable.measure + }); + const activeNodeRect = useRect(activeNode, measuringConfiguration.draggable.measure, initialActiveNodeRect); + const containerNodeRect = useRect(activeNode ? activeNode.parentElement : null); + const sensorContext = _2({ + activatorEvent: null, + active: null, + activeNode, + collisionRect: null, + collisions: null, + droppableRects, + draggableNodes, + draggingNode: null, + draggingNodeRect: null, + droppableContainers, + over: null, + scrollableAncestors: [], + scrollAdjustedTranslate: null + }); + const overNode = droppableContainers.getNodeFor((_sensorContext$curren = sensorContext.current.over) == null ? void 0 : _sensorContext$curren.id); + const dragOverlay = useDragOverlayMeasuring({ + measure: measuringConfiguration.dragOverlay.measure + }); + const draggingNode = (_dragOverlay$nodeRef$ = dragOverlay.nodeRef.current) != null ? _dragOverlay$nodeRef$ : activeNode; + const draggingNodeRect = isInitialized ? (_dragOverlay$rect = dragOverlay.rect) != null ? _dragOverlay$rect : activeNodeRect : null; + const usesDragOverlay = Boolean(dragOverlay.nodeRef.current && dragOverlay.rect); + const nodeRectDelta = useRectDelta(usesDragOverlay ? null : activeNodeRect); + const windowRect = useWindowRect(draggingNode ? getWindow(draggingNode) : null); + const scrollableAncestors = useScrollableAncestors(isInitialized ? overNode != null ? overNode : activeNode : null); + const scrollableAncestorRects = useRects(scrollableAncestors); + const modifiedTranslate = applyModifiers(modifiers, { + transform: { + x: translate.x - nodeRectDelta.x, + y: translate.y - nodeRectDelta.y, + scaleX: 1, + scaleY: 1 + }, + activatorEvent, + active, + activeNodeRect, + containerNodeRect, + draggingNodeRect, + over: sensorContext.current.over, + overlayNodeRect: dragOverlay.rect, + scrollableAncestors, + scrollableAncestorRects, + windowRect + }); + const pointerCoordinates = activationCoordinates ? add(activationCoordinates, translate) : null; + const scrollOffsets = useScrollOffsets(scrollableAncestors); + const scrollAdjustment = useScrollOffsetsDelta(scrollOffsets); + const activeNodeScrollDelta = useScrollOffsetsDelta(scrollOffsets, [activeNodeRect]); + const scrollAdjustedTranslate = add(modifiedTranslate, scrollAdjustment); + const collisionRect = draggingNodeRect ? getAdjustedRect(draggingNodeRect, modifiedTranslate) : null; + const collisions = active && collisionRect ? collisionDetection({ + active, + collisionRect, + droppableRects, + droppableContainers: enabledDroppableContainers, + pointerCoordinates + }) : null; + const overId = getFirstCollision(collisions, "id"); + const [over, setOver] = h2(null); + const appliedTranslate = usesDragOverlay ? modifiedTranslate : add(modifiedTranslate, activeNodeScrollDelta); + const transform = adjustScale(appliedTranslate, (_over$rect = over == null ? void 0 : over.rect) != null ? _over$rect : null, activeNodeRect); + const instantiateSensor = T2( + (event, _ref2) => { + let { + sensor: Sensor, + options + } = _ref2; + if (activeRef.current == null) { + return; + } + const activeNode2 = draggableNodes.get(activeRef.current); + if (!activeNode2) { + return; + } + const activatorEvent2 = event.nativeEvent; + const sensorInstance = new Sensor({ + active: activeRef.current, + activeNode: activeNode2, + event: activatorEvent2, + options, + context: sensorContext, + onStart(initialCoordinates) { + const id3 = activeRef.current; + if (id3 == null) { + return; + } + const draggableNode = draggableNodes.get(id3); + if (!draggableNode) { + return; + } + const { + onDragStart + } = latestProps.current; + const event2 = { + active: { + id: id3, + data: draggableNode.data, + rect: activeRects + } + }; + dn(() => { + onDragStart == null ? void 0 : onDragStart(event2); + setStatus(Status.Initializing); + dispatch({ + type: Action.DragStart, + initialCoordinates, + active: id3 + }); + dispatchMonitorEvent({ + type: "onDragStart", + event: event2 + }); + }); + }, + onMove(coordinates) { + dispatch({ + type: Action.DragMove, + coordinates + }); + }, + onEnd: createHandler(Action.DragEnd), + onCancel: createHandler(Action.DragCancel) + }); + dn(() => { + setActiveSensor(sensorInstance); + setActivatorEvent(event.nativeEvent); + }); + function createHandler(type) { + return async function handler() { + const { + active: active2, + collisions: collisions2, + over: over2, + scrollAdjustedTranslate: scrollAdjustedTranslate2 + } = sensorContext.current; + let event2 = null; + if (active2 && scrollAdjustedTranslate2) { + const { + cancelDrop + } = latestProps.current; + event2 = { + activatorEvent: activatorEvent2, + active: active2, + collisions: collisions2, + delta: scrollAdjustedTranslate2, + over: over2 + }; + if (type === Action.DragEnd && typeof cancelDrop === "function") { + const shouldCancel = await Promise.resolve(cancelDrop(event2)); + if (shouldCancel) { + type = Action.DragCancel; + } + } + } + activeRef.current = null; + dn(() => { + dispatch({ + type + }); + setStatus(Status.Uninitialized); + setOver(null); + setActiveSensor(null); + setActivatorEvent(null); + const eventName = type === Action.DragEnd ? "onDragEnd" : "onDragCancel"; + if (event2) { + const handler2 = latestProps.current[eventName]; + handler2 == null ? void 0 : handler2(event2); + dispatchMonitorEvent({ + type: eventName, + event: event2 + }); + } + }); + }; + } + }, + [draggableNodes] + ); + const bindActivatorToSensorInstantiator = T2((handler, sensor) => { + return (event, active2) => { + const nativeEvent = event.nativeEvent; + const activeDraggableNode = draggableNodes.get(active2); + if (activeRef.current !== null || !activeDraggableNode || nativeEvent.dndKit || nativeEvent.defaultPrevented) { + return; + } + const activationContext = { + active: activeDraggableNode + }; + const shouldActivate = handler(event, sensor.options, activationContext); + if (shouldActivate === true) { + nativeEvent.dndKit = { + capturedBy: sensor.sensor + }; + activeRef.current = active2; + instantiateSensor(event, sensor); + } + }; + }, [draggableNodes, instantiateSensor]); + const activators = useCombineActivators(sensors, bindActivatorToSensorInstantiator); + useSensorSetup(sensors); + useIsomorphicLayoutEffect(() => { + if (activeNodeRect && status === Status.Initializing) { + setStatus(Status.Initialized); + } + }, [activeNodeRect, status]); + p2( + () => { + const { + onDragMove + } = latestProps.current; + const { + active: active2, + activatorEvent: activatorEvent2, + collisions: collisions2, + over: over2 + } = sensorContext.current; + if (!active2 || !activatorEvent2) { + return; + } + const event = { + active: active2, + activatorEvent: activatorEvent2, + collisions: collisions2, + delta: { + x: scrollAdjustedTranslate.x, + y: scrollAdjustedTranslate.y + }, + over: over2 + }; + dn(() => { + onDragMove == null ? void 0 : onDragMove(event); + dispatchMonitorEvent({ + type: "onDragMove", + event + }); + }); + }, + [scrollAdjustedTranslate.x, scrollAdjustedTranslate.y] + ); + p2( + () => { + const { + active: active2, + activatorEvent: activatorEvent2, + collisions: collisions2, + droppableContainers: droppableContainers2, + scrollAdjustedTranslate: scrollAdjustedTranslate2 + } = sensorContext.current; + if (!active2 || activeRef.current == null || !activatorEvent2 || !scrollAdjustedTranslate2) { + return; + } + const { + onDragOver + } = latestProps.current; + const overContainer = droppableContainers2.get(overId); + const over2 = overContainer && overContainer.rect.current ? { + id: overContainer.id, + rect: overContainer.rect.current, + data: overContainer.data, + disabled: overContainer.disabled + } : null; + const event = { + active: active2, + activatorEvent: activatorEvent2, + collisions: collisions2, + delta: { + x: scrollAdjustedTranslate2.x, + y: scrollAdjustedTranslate2.y + }, + over: over2 + }; + dn(() => { + setOver(over2); + onDragOver == null ? void 0 : onDragOver(event); + dispatchMonitorEvent({ + type: "onDragOver", + event + }); + }); + }, + [overId] + ); + useIsomorphicLayoutEffect(() => { + sensorContext.current = { + activatorEvent, + active, + activeNode, + collisionRect, + collisions, + droppableRects, + draggableNodes, + draggingNode, + draggingNodeRect, + droppableContainers, + over, + scrollableAncestors, + scrollAdjustedTranslate + }; + activeRects.current = { + initial: draggingNodeRect, + translated: collisionRect + }; + }, [active, activeNode, collisions, collisionRect, draggableNodes, draggingNode, draggingNodeRect, droppableRects, droppableContainers, over, scrollableAncestors, scrollAdjustedTranslate]); + useAutoScroller({ + ...autoScrollOptions, + delta: translate, + draggingRect: collisionRect, + pointerCoordinates, + scrollableAncestors, + scrollableAncestorRects + }); + const publicContext = F2(() => { + const context = { + active, + activeNode, + activeNodeRect, + activatorEvent, + collisions, + containerNodeRect, + dragOverlay, + draggableNodes, + droppableContainers, + droppableRects, + over, + measureDroppableContainers, + scrollableAncestors, + scrollableAncestorRects, + measuringConfiguration, + measuringScheduled, + windowRect + }; + return context; + }, [active, activeNode, activeNodeRect, activatorEvent, collisions, containerNodeRect, dragOverlay, draggableNodes, droppableContainers, droppableRects, over, measureDroppableContainers, scrollableAncestors, scrollableAncestorRects, measuringConfiguration, measuringScheduled, windowRect]); + const internalContext = F2(() => { + const context = { + activatorEvent, + activators, + active, + activeNodeRect, + ariaDescribedById: { + draggable: draggableDescribedById + }, + dispatch, + draggableNodes, + over, + measureDroppableContainers + }; + return context; + }, [activatorEvent, activators, active, activeNodeRect, dispatch, draggableDescribedById, draggableNodes, over, measureDroppableContainers]); + return Cn.createElement(DndMonitorContext.Provider, { + value: registerMonitorListener + }, Cn.createElement(InternalContext.Provider, { + value: internalContext + }, Cn.createElement(PublicContext.Provider, { + value: publicContext + }, Cn.createElement(ActiveDraggableContext.Provider, { + value: transform + }, children)), Cn.createElement(RestoreFocus, { + disabled: (accessibility == null ? void 0 : accessibility.restoreFocus) === false + })), Cn.createElement(Accessibility, { + ...accessibility, + hiddenTextDescribedById: draggableDescribedById + })); + function getAutoScrollerOptions() { + const activeSensorDisablesAutoscroll = (activeSensor == null ? void 0 : activeSensor.autoScrollEnabled) === false; + const autoScrollGloballyDisabled = typeof autoScroll === "object" ? autoScroll.enabled === false : autoScroll === false; + const enabled = isInitialized && !activeSensorDisablesAutoscroll && !autoScrollGloballyDisabled; + if (typeof autoScroll === "object") { + return { + ...autoScroll, + enabled + }; } - return "option-multi"; - } else if (value.isLuxonDateTime) { - return "date"; - } else if (value.isLuxonDuration) { - return "duration"; - } else if (value.type == "file") { - return "link"; - } else if (typeof value === "object" && !Array.isArray(value) && value !== null) { - return "object"; - } - return "text"; -}; - -// src/utils/metadata/frontmatter/frontMatterKeys.ts -var frontMatterKeys = (fm) => { - return Object.keys(fm != null ? fm : {}).filter((f4) => f4 != "position").filter((f4) => f4 != "tag" && f4 != "tags"); -}; - -// src/utils/metadata/frontmatter/yamlTypeToMDBType.ts -var yamlTypeToMDBType = (YAMLtype) => { - switch (YAMLtype) { - case "duration": - return "text"; - break; - case "unknown": - return "text"; - break; + return { + enabled + }; } - return YAMLtype; -}; - -// src/utils/metadata/frontmatter/fm.ts -var saveContextToFile = (file, cols, context, plugin) => { - if (app.fileManager.processFrontMatter) { - app.fileManager.processFrontMatter(file, (frontmatter) => { - Object.keys(context).filter( - (f4) => cols.find((c4) => c4.name == f4) && cols.find((c4) => c4.name == f4).hidden != "true" && !cols.find((c4) => c4.name == f4).type.contains("file") && context[f4] - ).forEach((f4) => { - const col = cols.find((c4) => c4.name == f4); - frontmatter[f4] = valueForFrontmatter(col.type, context[f4]); - frontmatter[f4] = valueForFrontmatter(col.type, context[f4]); +}); +var NullContext = /* @__PURE__ */ F(null); +var defaultRole = "button"; +var ID_PREFIX = "Droppable"; +function useDraggable(_ref) { + let { + id: id2, + data: data2, + disabled = false, + attributes + } = _ref; + const key2 = useUniqueId(ID_PREFIX); + const { + activators, + activatorEvent, + active, + activeNodeRect, + ariaDescribedById, + draggableNodes, + over + } = q2(InternalContext); + const { + role = defaultRole, + roleDescription = "draggable", + tabIndex = 0 + } = attributes != null ? attributes : {}; + const isDragging = (active == null ? void 0 : active.id) === id2; + const transform = q2(isDragging ? ActiveDraggableContext : NullContext); + const [node, setNodeRef] = useNodeRef(); + const [activatorNode, setActivatorNodeRef] = useNodeRef(); + const listeners = useSyntheticListeners(activators, id2); + const dataRef = useLatestValue(data2); + useIsomorphicLayoutEffect( + () => { + draggableNodes.set(id2, { + id: id2, + key: key2, + node, + activatorNode, + data: dataRef }); - }); - } -}; -var frontMatterForFile = (file) => { - let currentCache; - if (file instanceof import_obsidian5.TFile && app.metadataCache.getFileCache(file) !== null) { - currentCache = app.metadataCache.getFileCache(file); - } - return currentCache == null ? void 0 : currentCache.frontmatter; -}; -var mergeTableData = (mdb, yamlmdb, types) => { + return () => { + const node2 = draggableNodes.get(id2); + if (node2 && node2.key === key2) { + draggableNodes.delete(id2); + } + }; + }, + [draggableNodes, id2] + ); + const memoizedAttributes = F2(() => ({ + role, + tabIndex, + "aria-disabled": disabled, + "aria-pressed": isDragging && role === defaultRole ? true : void 0, + "aria-roledescription": roleDescription, + "aria-describedby": ariaDescribedById.draggable + }), [disabled, role, tabIndex, isDragging, roleDescription, ariaDescribedById.draggable]); return { - ...mdb, - cols: [ - ...mdb.cols, - ...yamlmdb.cols.filter( - (f4) => !mdb.cols.find((g4) => g4.name.toLowerCase() == f4.toLowerCase()) - ).map((f4) => ({ - name: f4, - schemaId: mdb.schema.id, - type: yamlTypeToMDBType(types[f4]) - })) - ].filter(onlyUniquePropCaseInsensitive("name")), - rows: mdb.rows.map((r3) => { - const fmRow = yamlmdb.rows.find((f4) => f4.File == r3.File); - if (fmRow) { - return { - ...r3, - ...fmRow - }; - } - return r3; - }) + active, + activatorEvent, + activeNodeRect, + attributes: memoizedAttributes, + isDragging, + listeners: disabled ? void 0 : listeners, + node, + over, + setNodeRef, + setActivatorNodeRef, + transform }; +} +function useDndContext() { + return q2(PublicContext); +} +var ID_PREFIX$1 = "Droppable"; +var defaultResizeObserverConfig = { + timeout: 25 }; -var guestimateTypes = (_files, plugin, dv) => { - const typesArray = _files.map((f4) => getAbstractFileAtPath(app, f4)).filter((f4) => f4).map((k5) => { - const fm = dv && plugin.dataViewAPI() ? plugin.dataViewAPI().page(k5.path) : frontMatterForFile(k5); - const fmKeys = dv ? Object.keys(fm != null ? fm : {}).filter( - (f4, i4, self2) => !self2.find( - (g4, j4) => g4.toLowerCase().replace(/\s/g, "-") == f4.toLowerCase().replace(/\s/g, "-") && i4 > j4 - ) ? true : false - ).filter((f4) => f4 != "file") : frontMatterKeys(fm); - return fmKeys.reduce( - (pk, ck) => ({ ...pk, [ck]: detectYAMLType(fm[ck], ck) }), - {} - ); +function useDroppable(_ref) { + let { + data: data2, + disabled = false, + id: id2, + resizeObserverConfig + } = _ref; + const key2 = useUniqueId(ID_PREFIX$1); + const { + active, + dispatch, + over, + measureDroppableContainers + } = q2(InternalContext); + const previous = _2({ + disabled }); - const types = typesArray.reduce( - (p3, c4) => { - const newSet = Object.keys(c4).reduce( - (pk, ck) => { - var _a2; - return { ...pk, [ck]: [...(_a2 = p3 == null ? void 0 : p3[ck]) != null ? _a2 : [], c4[ck]] }; - }, - { ...p3 } - ); - return newSet; + const resizeObserverConnected = _2(false); + const rect = _2(null); + const callbackId = _2(null); + const { + disabled: resizeObserverDisabled, + updateMeasurementsFor, + timeout: resizeObserverTimeout + } = { + ...defaultResizeObserverConfig, + ...resizeObserverConfig + }; + const ids2 = useLatestValue(updateMeasurementsFor != null ? updateMeasurementsFor : id2); + const handleResize = T2( + () => { + if (!resizeObserverConnected.current) { + resizeObserverConnected.current = true; + return; + } + if (callbackId.current != null) { + clearTimeout(callbackId.current); + } + callbackId.current = setTimeout(() => { + measureDroppableContainers(Array.isArray(ids2.current) ? ids2.current : [ids2.current]); + callbackId.current = null; + }, resizeObserverTimeout); }, - {} + [resizeObserverTimeout] ); - const guessType = (ts) => { - return import_lodash.default.head((0, import_lodash.default)(ts).countBy().entries().maxBy(import_lodash.default.last)); - }; - const guessedTypes = Object.keys(types).reduce((p3, c4) => { - return { ...p3, [c4]: guessType(types[c4]) }; - }, {}); - return guessedTypes; -}; -var valueForFrontmatter = (type, value) => { - if (type == "number") { - return parseFloat(value); - } else if (type == "boolean") { - return value == "true"; - } else if (type.contains("multi")) { - return parseMultiString(value).map( - (f4) => valueForFrontmatter(type.replace("-multi", ""), f4) - ); - } else if (type.contains("link") || type.contains("context")) { - return `[[${value}]]`; - } - return value; -}; -var valueForDataview = (type, value) => { - if (type.contains("link") || type.contains("context")) { - return `[[${value}]]`; - } - return value; -}; -var renameFrontmatterKey = (plugin, path, key2, name) => { - const afile = getAbstractFileAtPath(app, path); - if (afile && afile instanceof import_obsidian5.TFile) { - if (app.fileManager.processFrontMatter) { - app.fileManager.processFrontMatter(afile, (frontmatter) => { - if (key2 in frontmatter) { - frontmatter[name] = frontmatter[key2]; - delete frontmatter[key2]; - } - }); - } - } -}; -var defaultValueForType = (value, type) => { - if (type == "date") { - return format(Date.now(), "yyyy-MM-dd"); - } - if (type == "number") { - return 0; - } - if (type == "boolean") { - return true; - } - if (type == "link") { - return "[[Select Note]]"; - } - if (type == "option") { - return "one, two"; - } - if (type == "text") { - return " "; - } - if (type == "image") { - return "https://images.unsplash.com/photo-1675789652575-0a5d2425b6c2?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=2070&q=80"; - } -}; -var changeFrontmatterType = (plugin, path, key2, type) => { - const afile = getAbstractFileAtPath(app, path); - if (afile && afile instanceof import_obsidian5.TFile) { - if (app.fileManager.processFrontMatter) { - app.fileManager.processFrontMatter(afile, (frontmatter) => { - if (key2 in frontmatter) { - frontmatter[key2] = defaultValueForType(frontmatter[key2], type); - } - }); + const resizeObserver = useResizeObserver({ + callback: handleResize, + disabled: resizeObserverDisabled || !active + }); + const handleNodeChange = T2((newElement, previousElement) => { + if (!resizeObserver) { + return; } - } -}; -var deleteFrontmatterValue = (plugin, path, key2) => { - const afile = getAbstractFileAtPath(app, path); - if (afile && afile instanceof import_obsidian5.TFile) { - if (app.fileManager.processFrontMatter) { - app.fileManager.processFrontMatter(afile, (frontmatter) => { - if (plugin.dataViewAPI()) { - if (plugin.dataViewAPI().page(path)[key2] && !frontmatter[key2]) { - replaceValues(plugin, path, key2, ""); - } else { - if (key2 in frontmatter) { - delete frontmatter[key2]; - } - } - } else { - if (key2 in frontmatter) { - delete frontmatter[key2]; - } - } - }); + if (previousElement) { + resizeObserver.unobserve(previousElement); + resizeObserverConnected.current = false; } - } -}; -var saveFrontmatterValue = (plugin, path, key2, value, type, forceSave) => { - let afile = getAbstractFileAtPath(app, path); - const fileCache = plugin.index.filesIndex.get(path); - if (afile) { - if (fileCache && fileCache.isFolder && fileCache.folderNote) { - afile = getAbstractFileAtPath(app, fileCache.folderNote.folderNotePath); + if (newElement) { + resizeObserver.observe(newElement); } - if (afile instanceof import_obsidian5.TFile) { - if (app.fileManager.processFrontMatter) { - app.fileManager.processFrontMatter(afile, (frontmatter) => { - var _a2; - if (plugin.dataViewAPI()) { - if (((_a2 = plugin.dataViewAPI().page(afile.path)) == null ? void 0 : _a2[key2]) && !frontmatter[key2]) { - replaceValues(plugin, afile.path, key2, valueForDataview(type, value)); - } else { - if (key2 in frontmatter || forceSave) { - frontmatter[key2] = valueForFrontmatter(type, value); - } - } - } else { - if (key2 in frontmatter || forceSave) { - frontmatter[key2] = valueForFrontmatter(type, value); - } - } - }); - } + }, [resizeObserver]); + const [nodeRef, setNodeRef] = useNodeRef(handleNodeChange); + const dataRef = useLatestValue(data2); + p2(() => { + if (!resizeObserver || !nodeRef.current) { + return; } - } -}; - -// src/utils/metadata/frontmatter/parseFrontMatter.ts -var parseFrontMatter = (field, value) => { - const YAMLtype = detectYAMLType(value, field); - switch (YAMLtype) { - case "object": - return JSON.stringify(value); - break; - case "number": - return value.toString(); - break; - case "boolean": - return value ? "true" : "false"; - break; - case "date": - return value; - break; - case "duration": - return serializeMultiDisplayString(Object.keys(value.values).reduce( - (p3, c4) => [ - ...p3, - ...value.values[c4] > 0 ? [value.values[c4] + " " + c4] : [] - ], - [] - )); - break; - case "option-multi": - case "link-multi": - if (typeof value === "string") { - return value; - } - return serializeMultiString( - value.map((v3) => { - if (!v3) { - return ""; - } - if (typeof v3 === "string") { - return v3; - } - if (v3.path) { - return v3.path; - } - if (Array.isArray(value) && v3.length == 1 && Array.isArray(v3[0]) && v3[0].length == 1 && typeof v3[0][0] === "string") { - return v3[0][0]; - } - return JSON.stringify(v3); - }) - ); - break; - case "link": - { - if (Array.isArray(value) && value.length == 1 && Array.isArray(value[0]) && value[0].length == 1 && typeof value[0][0] === "string") { - return value[0][0]; - } else if (typeof value === "string") { - return value; + resizeObserver.disconnect(); + resizeObserverConnected.current = false; + resizeObserver.observe(nodeRef.current); + }, [nodeRef, resizeObserver]); + useIsomorphicLayoutEffect( + () => { + dispatch({ + type: Action.RegisterDroppable, + element: { + id: id2, + key: key2, + disabled, + node: nodeRef, + rect, + data: dataRef } - return value.path; - } - break; - case "text": - case "tag": - case "image": - return value; - break; - } - return ""; -}; - -// src/utils/path.ts -var import_obsidian6 = require("obsidian"); - -// src/utils/regex.ts -var urlRegex = /https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*)/gi; - -// src/utils/path.ts -var openPath = (plugin, _path, modifiers) => { - const { type, path } = _path; - const target = modifiers.ctrlKey || modifiers.metaKey ? modifiers.altKey ? "split" : "tab" : false; - if (type == "file" || type == "folder") { - const afile = getAbstractFileAtPath(app, path); - if (afile) { - openAFile(afile, plugin, target); - } else { - if (type == "file") - createNewMarkdownFile( - plugin, - defaultNoteFolder(plugin, null), - path - ); + }); + return () => dispatch({ + type: Action.UnregisterDroppable, + key: key2, + id: id2 + }); + }, + [id2] + ); + p2(() => { + if (disabled !== previous.current.disabled) { + dispatch({ + type: Action.SetDroppableDisabled, + id: id2, + key: key2, + disabled + }); + previous.current.disabled = disabled; } - return; - } - if (type == "tag") { - openTagContext(path, plugin, target); - return; - } - if (type == "url") { - openURL(path); - return; + }, [id2, key2, disabled, dispatch]); + return { + active, + rect, + isOver: (over == null ? void 0 : over.id) === id2, + node: nodeRef, + over, + setNodeRef + }; +} +function AnimationManager(_ref) { + let { + animation, + children + } = _ref; + const [clonedChildren, setClonedChildren] = h2(null); + const [element, setElement] = h2(null); + const previousChildren = usePrevious(children); + if (!children && !clonedChildren && previousChildren) { + setClonedChildren(previousChildren); } + useIsomorphicLayoutEffect(() => { + if (!element) { + return; + } + const key2 = clonedChildren == null ? void 0 : clonedChildren.key; + const id2 = clonedChildren == null ? void 0 : clonedChildren.props.id; + if (key2 == null || id2 == null) { + setClonedChildren(null); + return; + } + Promise.resolve(animation(id2, element)).then(() => { + setClonedChildren(null); + }); + }, [animation, clonedChildren, element]); + return Cn.createElement(Cn.Fragment, null, children, clonedChildren ? sn(clonedChildren, { + ref: setElement + }) : null); +} +var defaultTransform = { + x: 0, + y: 0, + scaleX: 1, + scaleY: 1 }; -var pathByString = (path, source) => { - const [str, alias] = path.split("|"); - const refIndex = str.lastIndexOf("#"); - const [link, ref] = refIndex > 0 ? [str.substring(0, refIndex), str.substring(refIndex + 1)] : [str, void 0]; - const type = pathTypeByString(link, source); - return { - fullPath: path, - path: link, - type, - alias, - ref - }; +function NullifiedContextProvider(_ref) { + let { + children + } = _ref; + return Cn.createElement(InternalContext.Provider, { + value: defaultInternalContext + }, Cn.createElement(ActiveDraggableContext.Provider, { + value: defaultTransform + }, children)); +} +var baseStyles = { + position: "fixed", + touchAction: "none" }; -var pathTypeByString = (file, source) => { - if (file.charAt(0) == "#") { - return "tag"; - } - if (file.slice(-2) == "//") { - return "space"; - } - if (file.charAt(file.length - 1) == "/") { - return "folder"; +var defaultTransition = (activatorEvent) => { + const isKeyboardActivator = isKeyboardEvent(activatorEvent); + return isKeyboardActivator ? "transform 250ms ease" : void 0; +}; +var PositionedOverlay = /* @__PURE__ */ k3((_ref, ref2) => { + let { + as, + activatorEvent, + adjustScale: adjustScale2, + children, + className, + rect, + style, + transform, + transition = defaultTransition + } = _ref; + if (!rect) { + return null; } - let portalFile; - if (source) { - portalFile = app.metadataCache.getFirstLinkpathDest(file, source); - } else { - portalFile = app.vault.getAbstractFileByPath(file); + const scaleAdjustedTransform = adjustScale2 ? transform : { + ...transform, + scaleX: 1, + scaleY: 1 + }; + const styles2 = { + ...baseStyles, + width: rect.width, + height: rect.height, + top: rect.top, + left: rect.left, + transform: CSS.Transform.toString(scaleAdjustedTransform), + transformOrigin: adjustScale2 && activatorEvent ? getRelativeTransformOrigin(activatorEvent, rect) : void 0, + transition: typeof transition === "function" ? transition(activatorEvent) : transition, + ...style + }; + return Cn.createElement(as, { + className, + style: styles2, + ref: ref2 + }, children); +}); +var defaultDropAnimationSideEffects = (options) => (_ref) => { + let { + active, + dragOverlay + } = _ref; + const originalStyles = {}; + const { + styles: styles2, + className + } = options; + if (styles2 != null && styles2.active) { + for (const [key2, value] of Object.entries(styles2.active)) { + if (value === void 0) { + continue; + } + originalStyles[key2] = active.node.style.getPropertyValue(key2); + active.node.style.setProperty(key2, value); + } } - if (portalFile instanceof import_obsidian6.TFolder) { - return "folder"; + if (styles2 != null && styles2.dragOverlay) { + for (const [key2, value] of Object.entries(styles2.dragOverlay)) { + if (value === void 0) { + continue; + } + dragOverlay.node.style.setProperty(key2, value); + } } - if (portalFile instanceof import_obsidian6.TFile) { - return "file"; + if (className != null && className.active) { + active.node.classList.add(className.active); } - if (file.match(urlRegex)) - return "url"; - return "unknown"; -}; - -// src/utils/contexts/predicate/predicate.tsx -var defaultPredicateFnForType = (type, types) => { - const fnType = Object.keys(types).find( - (f4) => types[f4].type.find((g4) => g4 == type) - ); - return fnType; -}; -var predicateFnsForType = (type, types) => { - const fnTypes = Object.keys(types).filter( - (f4) => types[f4].type.find((g4) => g4 == type) - ); - return fnTypes; -}; -var cleanPredicateType = (type, definedTypes) => { - return type.filter((f4) => Object.keys(definedTypes).find((g4) => g4 == f4.fn)); -}; -var validatePredicate = (prevPredicate) => { - if (!prevPredicate) { - return defaultPredicate; + if (className != null && className.dragOverlay) { + dragOverlay.node.classList.add(className.dragOverlay); } - return { - ...defaultPredicate, - filters: Array.isArray(prevPredicate.filters) ? cleanPredicateType(prevPredicate.filters, filterFnTypes) : [], - sort: Array.isArray(prevPredicate.sort) ? cleanPredicateType(prevPredicate.sort, sortFnTypes) : [], - groupBy: Array.isArray(prevPredicate.groupBy) ? prevPredicate.groupBy : [], - colsOrder: Array.isArray(prevPredicate.colsOrder) ? prevPredicate.colsOrder : [], - colsHidden: Array.isArray(prevPredicate.colsHidden) ? prevPredicate.colsHidden : [], - colsSize: prevPredicate.colsSize + return function cleanup() { + for (const [key2, value] of Object.entries(originalStyles)) { + active.node.style.setProperty(key2, value); + } + if (className != null && className.active) { + active.node.classList.remove(className.active); + } }; }; -var defaultPredicate = { - filters: [], - sort: [], - groupBy: [], - colsOrder: [], - colsHidden: [], - colsSize: {} +var defaultKeyframeResolver = (_ref2) => { + let { + transform: { + initial, + final + } + } = _ref2; + return [{ + transform: CSS.Transform.toString(initial) + }, { + transform: CSS.Transform.toString(final) + }]; }; - -// src/components/ContextView/MDBContext.tsx -var MDBContext = F({ - def: [], - tables: [], - cols: [], - sortedColumns: [], - data: [], - filteredData: [], - tableData: null, - contextTable: {}, - selectedRows: [], - selectRows: () => { - }, - setContextTable: () => { - }, - predicate: defaultPredicate, - savePredicate: () => { - }, - saveDB: () => null, - saveContextDB: () => null, - schema: null, - dbSchema: null, - setSchema: () => { - }, - setDBSchema: () => { - }, - hideColumn: () => { - }, - saveColumn: () => false, - newColumn: () => false, - sortColumn: () => { - }, - delColumn: () => { - }, - saveSchema: () => null, - deleteSchema: () => null, - tagContexts: [], - contextInfo: null, - dbFileExists: false, - readMode: false, - searchString: "", - setSearchString: () => { - }, - loadContextFields: () => { - }, - updateValue: () => { - }, - updateFieldValue: () => { - } -}); -var MDBProvider = (props2) => { - var _a2; - const [readMode, setReadMode] = h2(props2.context.readOnly); - const [dbFileExists, setDBFileExists] = h2(false); - const [schema, setSchema] = h2(null); - const [searchString, setSearchString] = h2(null); - const [schemaTable, setSchemaTable] = h2(null); - const tables = (_a2 = schemaTable == null ? void 0 : schemaTable.rows) != null ? _a2 : []; - const [tableData, setTableData] = h2(null); - const [dbSchema, setDBSchema] = h2(null); - const [contextTable, setContextTable] = h2({}); - const [predicate, setPredicate] = h2(defaultPredicate); - const def = F2(() => parseContextDefString(dbSchema == null ? void 0 : dbSchema.def), [dbSchema]); - const [selectedRows, setSelectedRows] = h2([]); - const [metadataCache, setMetadataCache] = h2(null); - const defaultSchema = props2.context.type == "tag" ? defaultTagSchema : defaultFolderSchema; - const contextInfo = F2(() => { - return props2.context; - }, [props2.context]); - const tagContexts = F2( - () => { - var _a3; - return (_a3 = def.filter((f4) => f4.type == "tag").map((f4) => f4.value).filter((f4) => f4)) != null ? _a3 : []; - }, - [def] - ); - const cols = F2( - () => { - var _a3; - return tableData ? [ - ...(_a3 = tableData.cols.map((f4) => ({ ...f4, table: "" }))) != null ? _a3 : [], - ...tagContexts.reduce( - (p3, c4) => { - var _a4, _b2; - return [ - ...p3, - ...(_b2 = (_a4 = contextTable[c4]) == null ? void 0 : _a4.cols.filter( - (f4) => f4.name != FilePropertyName && f4.type != "fileprop" - ).map((f4) => ({ ...f4, table: c4 }))) != null ? _b2 : [] - ]; - }, - [] - ) - ] : []; - }, - [tableData, schema, contextTable, tagContexts] - ); - const data = F2( - () => { - var _a3; - return (_a3 = tableData == null ? void 0 : tableData.rows.map( - (r3, index) => linkContextRow( - props2.plugin, - { - _index: index.toString(), - ...r3, - ...tagContexts.reduce((p3, c4) => { - var _a4, _b2, _c2, _d2; - const contextRowIndexByFile = (_b2 = (_a4 = contextTable[c4]) == null ? void 0 : _a4.rows.findIndex((f4) => f4.File == r3.File)) != null ? _b2 : -1; - const contextRowsByFile = (_d2 = (_c2 = contextTable[c4]) == null ? void 0 : _c2.rows[contextRowIndexByFile]) != null ? _d2 : {}; - const contextRowsWithKeysAppended = Object.keys( - contextRowsByFile - ).reduce( - (pa, ca) => ({ ...pa, [ca + c4]: contextRowsByFile[ca] }), - { - ["_index" + c4]: contextRowIndexByFile.toString() - } - ); - return { ...p3, ...contextRowsWithKeysAppended }; - }, {}) - }, - cols - ) - )) != null ? _a3 : []; - }, - [tableData, schema, contextTable] - ); - const sortedColumns = F2(() => { - return cols.filter( - (f4) => f4.hidden != "true" && !predicate.colsHidden.some((c4) => c4 == f4.name + f4.table) - ).sort( - (a5, b4) => predicate.colsOrder.findIndex((x5) => x5 == a5.name + a5.table) - predicate.colsOrder.findIndex((x5) => x5 == b4.name + b4.table) - ); - }, [cols, predicate]); - const filteredData = F2( - () => data.filter((f4) => { - return predicate.filters.reduce((p3, c4) => { - return p3 ? filterReturnForCol( - cols.find((col) => col.name + col.table == c4.field), - c4, - f4 - ) : p3; - }, true); - }).filter( - (f4) => (searchString == null ? void 0 : searchString.length) > 0 ? matchAny(searchString).test( - Object.keys(f4).filter((g4) => g4.charAt(0) != "_").map((g4) => f4[g4]).join("|") - ) : true - ).sort((a5, b4) => { - return predicate.sort.reduce((p3, c4) => { - return p3 == 0 ? sortReturnForCol( - cols.find((col) => col.name + col.table == c4.field), - c4, - a5, - b4 - ) : p3; - }, 0); - }), - [predicate, data, cols, searchString] - ); - const deleteSchema = async (table) => { - if (table.primary) - return; - const deleteResult = await deleteMDBTable( - props2.plugin, - contextInfo, - table.id - ); - if (deleteResult) { - const newSchemaTable = { - ...schemaTable, - rows: schemaTable.rows.filter( - (f4) => f4.id != table.id && f4.def != table.id - ) - }; - setSchemaTable(newSchemaTable); - if (dbSchema.id == table.id) { - setDBSchema( - newSchemaTable.rows.find((g4) => g4.type == "db") - ); +var defaultDropAnimationConfiguration = { + duration: 250, + easing: "ease", + keyframes: defaultKeyframeResolver, + sideEffects: /* @__PURE__ */ defaultDropAnimationSideEffects({ + styles: { + active: { + opacity: "0" } } - }; - const saveSchema = async (table) => { - const newSchema = schemaTable.rows.find((f4) => f4.id == table.id) ? true : false; - const newSchemaTable = newSchema ? { - ...schemaTable, - rows: schemaTable.rows.map((f4) => f4.id == table.id ? table : f4) - } : { - ...schemaTable, - rows: [...schemaTable.rows, table] - }; - if (!contextInfo.readOnly) { - await saveDBToPath(props2.plugin, contextInfo.dbPath, { - m_schema: newSchemaTable - }); - if (!dbFileExists) { - saveDB2(tableData); - } + }) +}; +function useDropAnimation(_ref3) { + let { + config, + draggableNodes, + droppableContainers, + measuringConfiguration + } = _ref3; + return useEvent((id2, node) => { + if (config === null) { + return; } - if (table.id == (schema == null ? void 0 : schema.id)) { - setSchema(table); + const activeDraggable = draggableNodes.get(id2); + if (!activeDraggable) { + return; } - if (table.id == (dbSchema == null ? void 0 : dbSchema.id)) { - setDBSchema(table); - setTableData((f4) => ({ - ...f4, - schema: table - })); + const activeNode = activeDraggable.node.current; + if (!activeNode) { + return; } - setSchemaTable(newSchemaTable); - }; - const updateValue2 = (column, value, table, index, file) => { - var _a3, _b2; - const col = (_a3 = table == "" ? tableData : contextTable[table]) == null ? void 0 : _a3.cols.find( - (f4) => f4.name == column - ); - if (col) - saveFrontmatterValue( - props2.plugin, - file != null ? file : (_b2 = tableData.rows[index]) == null ? void 0 : _b2.File, - column, - value, - col.type, - props2.plugin.settings.saveAllContextToFrontmatter - ); - if (table == "") { - saveDB2({ - ...tableData, - rows: tableData.rows.map( - (r3, i4) => i4 == index ? { - ...r3, - [column]: value - } : r3 - ) - }); - } else if (contextTable[table]) { - saveContextDB( - { - ...contextTable[table], - rows: contextTable[table].rows.map( - (r3, i4) => i4 == index ? { - ...r3, - [column]: value - } : r3 - ) - }, - table - ); + const measurableNode = getMeasurableNode(node); + if (!measurableNode) { + return; } - }; - const sortColumn = (sort) => { - savePredicate({ - ...predicate, - sort: [sort] - }); - }; - const hideColumn = (col, hidden) => { - savePredicate({ - ...predicate, - colsHidden: hidden ? [ - ...predicate.colsHidden.filter((s5) => s5 != col.name + col.table), - col.name + col.table - ] : predicate.colsHidden.filter((s5) => s5 != col.name + col.table) - }); - }; - const updateFieldValue = (column, fieldValue, value, table, index, file) => { - var _a3; - const col = tableData.cols.find((f4) => f4.name == column); - saveFrontmatterValue( - props2.plugin, - file != null ? file : (_a3 = tableData.rows[index]) == null ? void 0 : _a3.File, - column, - value, - col.type, - props2.plugin.settings.saveAllContextToFrontmatter - ); - if (table == "") { - const newTable = { - ...tableData, - cols: tableData.cols.map( - (m5) => m5.name == column ? { - ...m5, - value: fieldValue - } : m5 - ), - rows: tableData.rows.map( - (r3, i4) => i4 == index ? { - ...r3, - [column]: value - } : r3 - ) - }; - saveDB2(newTable); - } else if (contextTable[table]) { - saveContextDB( - { - ...contextTable[table], - cols: contextTable[table].cols.map( - (m5) => m5.name == column ? { - ...m5, - value: fieldValue - } : m5 - ), - rows: contextTable[table].rows.map( - (r3, i4) => i4 == index ? { - ...r3, - [column]: value - } : r3 - ) - }, - table - ); + const { + transform + } = getWindow(node).getComputedStyle(node); + const parsedTransform = parseTransform(transform); + if (!parsedTransform) { + return; } + const animation = typeof config === "function" ? config : createDefaultDropAnimation(config); + scrollIntoViewIfNeeded(activeNode, measuringConfiguration.draggable.measure); + return animation({ + active: { + id: id2, + data: activeDraggable.data, + node: activeNode, + rect: measuringConfiguration.draggable.measure(activeNode) + }, + draggableNodes, + dragOverlay: { + node, + rect: measuringConfiguration.dragOverlay.measure(measurableNode) + }, + droppableContainers, + measuringConfiguration, + transform: parsedTransform + }); + }); +} +function createDefaultDropAnimation(options) { + const { + duration, + easing, + sideEffects, + keyframes + } = { + ...defaultDropAnimationConfiguration, + ...options }; - const syncAllMetadata = (f4) => { - const files = f4.rows.map((f5) => f5.File); - const importYAML = (files2, fmKeys) => { - return files2.map((f5) => getAbstractFileAtPath(app, f5)).filter((f5) => f5).reduce( - (p3, c4) => { - const fm = frontMatterForFile(c4); - if (!fm) - return p3; - return { - uniques: [], - cols: uniq([...p3.cols, ...fmKeys]), - rows: [ - ...p3.rows, - { - File: c4.path, - ...fmKeys.reduce((p4, c5) => { - const value = parseFrontMatter(c5, fm[c5]); - if ((value == null ? void 0 : value.length) > 0) - return { ...p4, [c5]: value }; - return p4; - }, {}) - } - ] - }; - }, - { uniques: [], cols: [], rows: [] } - ); + return (_ref4) => { + let { + active, + dragOverlay, + transform, + ...rest + } = _ref4; + if (!duration) { + return; + } + const delta = { + x: dragOverlay.rect.left - active.rect.left, + y: dragOverlay.rect.top - active.rect.top }; - const yamlTableData = importYAML( - files, - f4.cols.filter((f5) => !f5.type.contains("file")).map((f5) => f5.name) - ); - const newRows = f4.rows.map((r3) => { - const fmRow = yamlTableData.rows.find((f5) => f5.File == r3.File); - if (fmRow) { - return { - ...r3, - ...fmRow - }; + const scale = { + scaleX: transform.scaleX !== 1 ? active.rect.width * transform.scaleX / dragOverlay.rect.width : 1, + scaleY: transform.scaleY !== 1 ? active.rect.height * transform.scaleY / dragOverlay.rect.height : 1 + }; + const finalTransform = { + x: transform.x - delta.x, + y: transform.y - delta.y, + ...scale + }; + const animationKeyframes = keyframes({ + ...rest, + active, + dragOverlay, + transform: { + initial: transform, + final: finalTransform } - return r3; }); - const rowsChanged = !import_lodash2.default.isEqual(newRows, tableData == null ? void 0 : tableData.rows); - const colsChanged = !import_lodash2.default.isEqual(tableData == null ? void 0 : tableData.cols, f4.cols); - if (rowsChanged || colsChanged) { - saveDB2({ - ...f4, - rows: newRows - }); + const [firstKeyframe] = animationKeyframes; + const lastKeyframe = animationKeyframes[animationKeyframes.length - 1]; + if (JSON.stringify(firstKeyframe) === JSON.stringify(lastKeyframe)) { + return; } + const cleanup = sideEffects == null ? void 0 : sideEffects({ + active, + dragOverlay, + ...rest + }); + const animation = dragOverlay.node.animate(animationKeyframes, { + duration, + easing, + fill: "forwards" + }); + return new Promise((resolve) => { + animation.onfinish = () => { + cleanup == null ? void 0 : cleanup(); + resolve(); + }; + }); }; - p2(() => { - var _a3, _b2; - if (schemaTable) { - if (props2.schema) { - if ((dbSchema == null ? void 0 : dbSchema.id) != props2.schema) { - const preselectSchema = schemaTable.rows.find( - (g4) => g4.id == props2.schema - ); - if (preselectSchema) { - if (preselectSchema.type == "db") { - setDBSchema(preselectSchema); - return; - } else { - const preselectDBSchema = schemaTable.rows.find( - (g4) => g4.id == preselectSchema.def - ); - if (preselectDBSchema) { - setDBSchema(preselectDBSchema); - return; - } - } - } else { - const newSchema = { - id: uniqueNameFromString( - sanitizeTableName(props2.schema), - schemaTable.rows.map((g4) => g4.id) - ), - name: props2.schema, - type: "db" - }; - setDBSchema(newSchema); - saveSchema(newSchema).then((f4) => { - saveDB2({ - schema: newSchema, - cols: defaultTableFields.map((g4) => ({ - ...g4, - schemaId: newSchema.id - })), - rows: [] - }); - }); - } - } - } else { - if (!dbSchema) { - setDBSchema( - (_a3 = schemaTable.rows) == null ? void 0 : _a3.find((g4) => g4.type == "db") - ); - } else { - setDBSchema( - (_b2 = schemaTable.rows) == null ? void 0 : _b2.find((g4) => g4.id == dbSchema.id) - ); - } - } +} +var key = 0; +function useKey(id2) { + return F2(() => { + if (id2 == null) { + return; } - }, [schemaTable]); - const loadTables = async () => { - if (getAbstractFileAtPath(app, contextInfo.dbPath) || contextInfo.isRemote) { - setDBFileExists(true); - getMDBTableSchemas(props2.plugin, contextInfo).then((f4) => { - setSchemaTable((prev) => ({ - ...defaultSchema, - rows: f4 - })); - }); - } else { - if (props2.schema) { - saveDB2(defaultTableDataForContext(props2.plugin, contextInfo)).then( - (f4) => { - setSchemaTable((prev) => defaultSchema); - } - ); - } else { - setSchemaTable((prev) => defaultSchema); - setDBSchema((prev) => defaultFileDBSchema); - } + key++; + return key; + }, [id2]); +} +var DragOverlay = /* @__PURE__ */ Cn.memo((_ref) => { + let { + adjustScale: adjustScale2 = false, + children, + dropAnimation: dropAnimationConfig, + style, + transition, + modifiers, + wrapperElement = "div", + className, + zIndex = 999 + } = _ref; + const { + activatorEvent, + active, + activeNodeRect, + containerNodeRect, + draggableNodes, + droppableContainers, + dragOverlay, + over, + measuringConfiguration, + scrollableAncestors, + scrollableAncestorRects, + windowRect + } = useDndContext(); + const transform = q2(ActiveDraggableContext); + const key2 = useKey(active == null ? void 0 : active.id); + const modifiedTransform = applyModifiers(modifiers, { + activatorEvent, + active, + activeNodeRect, + containerNodeRect, + draggingNodeRect: dragOverlay.rect, + over, + overlayNodeRect: dragOverlay.rect, + scrollableAncestors, + scrollableAncestorRects, + transform, + windowRect + }); + const initialRect = useInitialValue(activeNodeRect); + const dropAnimation = useDropAnimation({ + config: dropAnimationConfig, + draggableNodes, + droppableContainers, + measuringConfiguration + }); + const ref2 = initialRect ? dragOverlay.setRef : void 0; + return Cn.createElement(NullifiedContextProvider, null, Cn.createElement(AnimationManager, { + animation: dropAnimation + }, active && key2 ? Cn.createElement(PositionedOverlay, { + key: key2, + id: active.id, + ref: ref2, + as: wrapperElement, + activatorEvent, + adjustScale: adjustScale2, + className, + transition, + rect: initialRect, + style: { + zIndex, + ...style + }, + transform: modifiedTransform + }, children) : null)); +}); + +// node_modules/@dnd-kit/sortable/dist/sortable.esm.js +function arrayMove(array, from, to) { + const newArray = array.slice(); + newArray.splice(to < 0 ? newArray.length + to : to, 0, newArray.splice(from, 1)[0]); + return newArray; +} +function getSortedRects(items, rects) { + return items.reduce((accumulator, id2, index) => { + const rect = rects.get(id2); + if (rect) { + accumulator[index] = rect; + } + return accumulator; + }, Array(items.length)); +} +function isValidIndex(index) { + return index !== null && index >= 0; +} +function itemsEqual(a5, b4) { + if (a5 === b4) { + return true; + } + if (a5.length !== b4.length) { + return false; + } + for (let i4 = 0; i4 < a5.length; i4++) { + if (a5[i4] !== b4[i4]) { + return false; + } + } + return true; +} +function normalizeDisabled(disabled) { + if (typeof disabled === "boolean") { + return { + draggable: disabled, + droppable: disabled + }; + } + return disabled; +} +var defaultScale = { + scaleX: 1, + scaleY: 1 +}; +var horizontalListSortingStrategy = (_ref) => { + var _rects$activeIndex; + let { + rects, + activeNodeRect: fallbackActiveRect, + activeIndex, + overIndex, + index + } = _ref; + const activeNodeRect = (_rects$activeIndex = rects[activeIndex]) != null ? _rects$activeIndex : fallbackActiveRect; + if (!activeNodeRect) { + return null; + } + const itemGap = getItemGap(rects, index, activeIndex); + if (index === activeIndex) { + const newIndexRect = rects[overIndex]; + if (!newIndexRect) { + return null; } + return { + x: activeIndex < overIndex ? newIndexRect.left + newIndexRect.width - (activeNodeRect.left + activeNodeRect.width) : newIndexRect.left - activeNodeRect.left, + y: 0, + ...defaultScale + }; + } + if (index > activeIndex && index <= overIndex) { + return { + x: -activeNodeRect.width - itemGap, + y: 0, + ...defaultScale + }; + } + if (index < activeIndex && index >= overIndex) { + return { + x: activeNodeRect.width + itemGap, + y: 0, + ...defaultScale + }; + } + return { + x: 0, + y: 0, + ...defaultScale }; - const refreshFile = async (file) => { - var _a3; - if (file.path == props2.file && dbSchema) { - const fCache = (_a3 = app.metadataCache.getCache(file.path)) == null ? void 0 : _a3.frontmatter; - if ((0, import_lodash2.isEqual)(fCache, metadataCache)) - return; - setMetadataCache(fCache); - if (dbSchema.primary) { - runDef(); - } else { - getMDBData(); - } +}; +function getItemGap(rects, index, activeIndex) { + const currentRect = rects[index]; + const previousRect = rects[index - 1]; + const nextRect = rects[index + 1]; + if (!currentRect || !previousRect && !nextRect) { + return 0; + } + if (activeIndex < index) { + return previousRect ? currentRect.left - (previousRect.left + previousRect.width) : nextRect.left - (currentRect.left + currentRect.width); + } + return nextRect ? nextRect.left - (currentRect.left + currentRect.width) : currentRect.left - (previousRect.left + previousRect.width); +} +var rectSortingStrategy = (_ref) => { + let { + rects, + activeIndex, + overIndex, + index + } = _ref; + const newRects = arrayMove(rects, overIndex, activeIndex); + const oldRect = rects[index]; + const newRect = newRects[index]; + if (!newRect || !oldRect) { + return null; + } + return { + x: newRect.left - oldRect.left, + y: newRect.top - oldRect.top, + scaleX: newRect.width / oldRect.width, + scaleY: newRect.height / oldRect.height + }; +}; +var defaultScale$1 = { + scaleX: 1, + scaleY: 1 +}; +var verticalListSortingStrategy = (_ref) => { + var _rects$activeIndex; + let { + activeIndex, + activeNodeRect: fallbackActiveRect, + index, + rects, + overIndex + } = _ref; + const activeNodeRect = (_rects$activeIndex = rects[activeIndex]) != null ? _rects$activeIndex : fallbackActiveRect; + if (!activeNodeRect) { + return null; + } + if (index === activeIndex) { + const overIndexRect = rects[overIndex]; + if (!overIndexRect) { + return null; } + return { + x: 0, + y: activeIndex < overIndex ? overIndexRect.top + overIndexRect.height - (activeNodeRect.top + activeNodeRect.height) : overIndexRect.top - activeNodeRect.top, + ...defaultScale$1 + }; + } + const itemGap = getItemGap$1(rects, index, activeIndex); + if (index > activeIndex && index <= overIndex) { + return { + x: 0, + y: -activeNodeRect.height - itemGap, + ...defaultScale$1 + }; + } + if (index < activeIndex && index >= overIndex) { + return { + x: 0, + y: activeNodeRect.height + itemGap, + ...defaultScale$1 + }; + } + return { + x: 0, + y: 0, + ...defaultScale$1 }; - const refreshTags = async (tags) => { - if (tagContexts.some((f4) => tags.some((g4) => g4 == f4))) - if (dbSchema.primary) { - runDef(); - } else { - getMDBData(); +}; +function getItemGap$1(clientRects, index, activeIndex) { + const currentRect = clientRects[index]; + const previousRect = clientRects[index - 1]; + const nextRect = clientRects[index + 1]; + if (!currentRect) { + return 0; + } + if (activeIndex < index) { + return previousRect ? currentRect.top - (previousRect.top + previousRect.height) : nextRect ? nextRect.top - (currentRect.top + currentRect.height) : 0; + } + return nextRect ? nextRect.top - (currentRect.top + currentRect.height) : previousRect ? currentRect.top - (previousRect.top + previousRect.height) : 0; +} +var ID_PREFIX2 = "Sortable"; +var Context = /* @__PURE__ */ Cn.createContext({ + activeIndex: -1, + containerId: ID_PREFIX2, + disableTransforms: false, + items: [], + overIndex: -1, + useDragOverlay: false, + sortedRects: [], + strategy: rectSortingStrategy, + disabled: { + draggable: false, + droppable: false + } +}); +function SortableContext(_ref) { + let { + children, + id: id2, + items: userDefinedItems, + strategy = rectSortingStrategy, + disabled: disabledProp = false + } = _ref; + const { + active, + dragOverlay, + droppableRects, + over, + measureDroppableContainers + } = useDndContext(); + const containerId = useUniqueId(ID_PREFIX2, id2); + const useDragOverlay = Boolean(dragOverlay.rect !== null); + const items = F2(() => userDefinedItems.map((item) => typeof item === "object" && "id" in item ? item.id : item), [userDefinedItems]); + const isDragging = active != null; + const activeIndex = active ? items.indexOf(active.id) : -1; + const overIndex = over ? items.indexOf(over.id) : -1; + const previousItemsRef = _2(items); + const itemsHaveChanged = !itemsEqual(items, previousItemsRef.current); + const disableTransforms = overIndex !== -1 && activeIndex === -1 || itemsHaveChanged; + const disabled = normalizeDisabled(disabledProp); + useIsomorphicLayoutEffect(() => { + if (itemsHaveChanged && isDragging) { + measureDroppableContainers(items); + } + }, [itemsHaveChanged, items, isDragging, measureDroppableContainers]); + p2(() => { + previousItemsRef.current = items; + }, [items]); + const contextValue = F2( + () => ({ + activeIndex, + containerId, + disabled, + disableTransforms, + items, + overIndex, + useDragOverlay, + sortedRects: getSortedRects(items, droppableRects), + strategy + }), + [activeIndex, containerId, disabled.draggable, disabled.droppable, disableTransforms, items, overIndex, droppableRects, useDragOverlay, strategy] + ); + return Cn.createElement(Context.Provider, { + value: contextValue + }, children); +} +var defaultNewIndexGetter = (_ref) => { + let { + id: id2, + items, + activeIndex, + overIndex + } = _ref; + return arrayMove(items, activeIndex, overIndex).indexOf(id2); +}; +var defaultAnimateLayoutChanges = (_ref2) => { + let { + containerId, + isSorting, + wasDragging, + index, + items, + newIndex, + previousItems, + previousContainerId, + transition + } = _ref2; + if (!transition || !wasDragging) { + return false; + } + if (previousItems !== items && index === newIndex) { + return false; + } + if (isSorting) { + return true; + } + return newIndex !== index && containerId === previousContainerId; +}; +var defaultTransition2 = { + duration: 200, + easing: "ease" +}; +var transitionProperty = "transform"; +var disabledTransition = /* @__PURE__ */ CSS.Transition.toString({ + property: transitionProperty, + duration: 0, + easing: "linear" +}); +var defaultAttributes = { + roleDescription: "sortable" +}; +function useDerivedTransform(_ref) { + let { + disabled, + index, + node, + rect + } = _ref; + const [derivedTransform, setDerivedtransform] = h2(null); + const previousIndex = _2(index); + useIsomorphicLayoutEffect(() => { + if (!disabled && index !== previousIndex.current && node.current) { + const initial = rect.current; + if (initial) { + const current2 = getClientRect(node.current, { + ignoreTransform: true + }); + const delta = { + x: initial.left - current2.left, + y: initial.top - current2.top, + scaleX: initial.width / current2.width, + scaleY: initial.height / current2.height + }; + if (delta.x || delta.y) { + setDerivedtransform(delta); + } } - }; - const refreshSpace = async (evt) => { - if (evt.detail.type == "context") { - refreshMDB(evt.detail.name); - return; - } - if (evt.detail.type == "file") { - refreshFile(getAbstractFileAtPath(app, evt.detail.name)); - return; } - if ((evt.detail.type == "space" || evt.detail.type == "vault") && !dbFileExists) { - const defaultTable = defaultTableDataForContext( - props2.plugin, - contextInfo - ); - if (defaultTable) - setTableData(defaultTable); - } else if (evt.detail.type == "vault") { - refreshMDB(contextInfo.contextPath); + if (index !== previousIndex.current) { + previousIndex.current = index; } - }; - const getMDBData = () => { - getMDBTable(props2.plugin, contextInfo, dbSchema.id).then((f4) => { - setTableData(f4); - }); - }; - const refreshMDB = async (contextPath) => { - if (!dbFileExists || (dbSchema == null ? void 0 : dbSchema.primary) != "true") { - return; + }, [disabled, index, node, rect]); + p2(() => { + if (derivedTransform) { + setDerivedtransform(null); } - if (contextPath == contextInfo.contextPath) { - if (dbSchema) { - loadTables(); - } - } else { - const tag = Object.keys(contextTable).find( - (t4) => tagContextFromTag(props2.plugin, t4).contextPath == contextPath - ); - if (tag) - loadContextFields(tag); + }, [derivedTransform]); + return derivedTransform; +} +function useSortable(_ref) { + let { + animateLayoutChanges: animateLayoutChanges4 = defaultAnimateLayoutChanges, + attributes: userDefinedAttributes, + disabled: localDisabled, + data: customData, + getNewIndex = defaultNewIndexGetter, + id: id2, + strategy: localStrategy, + resizeObserverConfig, + transition = defaultTransition2 + } = _ref; + const { + items, + containerId, + activeIndex, + disabled: globalDisabled, + disableTransforms, + sortedRects, + overIndex, + useDragOverlay, + strategy: globalStrategy + } = q2(Context); + const disabled = normalizeLocalDisabled(localDisabled, globalDisabled); + const index = items.indexOf(id2); + const data2 = F2(() => ({ + sortable: { + containerId, + index, + items + }, + ...customData + }), [containerId, customData, index, items]); + const itemsAfterCurrentSortable = F2(() => items.slice(items.indexOf(id2)), [items, id2]); + const { + rect, + node, + isOver, + setNodeRef: setDroppableNodeRef + } = useDroppable({ + id: id2, + data: data2, + disabled: disabled.droppable, + resizeObserverConfig: { + updateMeasurementsFor: itemsAfterCurrentSortable, + ...resizeObserverConfig } - }; - p2(() => { - window.addEventListener(eventTypes.spacesChange, refreshSpace); - return () => { - window.removeEventListener(eventTypes.spacesChange, refreshSpace); - }; - }, [refreshSpace]); + }); + const { + active, + activatorEvent, + activeNodeRect, + attributes, + setNodeRef: setDraggableNodeRef, + listeners, + isDragging, + over, + setActivatorNodeRef, + transform + } = useDraggable({ + id: id2, + data: data2, + attributes: { + ...defaultAttributes, + ...userDefinedAttributes + }, + disabled: disabled.draggable + }); + const setNodeRef = useCombinedRefs(setDroppableNodeRef, setDraggableNodeRef); + const isSorting = Boolean(active); + const displaceItem = isSorting && !disableTransforms && isValidIndex(activeIndex) && isValidIndex(overIndex); + const shouldDisplaceDragSource = !useDragOverlay && isDragging; + const dragSourceDisplacement = shouldDisplaceDragSource && displaceItem ? transform : null; + const strategy = localStrategy != null ? localStrategy : globalStrategy; + const finalTransform = displaceItem ? dragSourceDisplacement != null ? dragSourceDisplacement : strategy({ + rects: sortedRects, + activeNodeRect, + activeIndex, + overIndex, + index + }) : null; + const newIndex = isValidIndex(activeIndex) && isValidIndex(overIndex) ? getNewIndex({ + id: id2, + items, + activeIndex, + overIndex + }) : index; + const activeId = active == null ? void 0 : active.id; + const previous = _2({ + activeId, + items, + newIndex, + containerId + }); + const itemsHaveChanged = items !== previous.current.items; + const shouldAnimateLayoutChanges = animateLayoutChanges4({ + active, + containerId, + isDragging, + isSorting, + id: id2, + index, + items, + newIndex: previous.current.newIndex, + previousItems: previous.current.items, + previousContainerId: previous.current.containerId, + transition, + wasDragging: previous.current.activeId != null + }); + const derivedTransform = useDerivedTransform({ + disabled: !shouldAnimateLayoutChanges, + index, + node, + rect + }); p2(() => { - loadTables(); - }, [contextInfo]); - const saveDB2 = async (newTable) => { - var _a3; - if (contextInfo.readOnly) - return; - if (!dbFileExists) { - const defaultFields = defaultFieldsForContext(contextInfo); - const defaultTable = defaultTablesForContext(contextInfo); - const dbField = { - ...defaultTable, - m_fields: { - uniques: defaultFields.uniques, - cols: defaultFields.cols, - rows: [...(_a3 = defaultFields.rows) != null ? _a3 : [], ...newTable.cols] - }, - [newTable.schema.id]: { - uniques: newTable.cols.filter((c4) => c4.unique == "true").map((c4) => c4.name), - cols: newTable.cols.map((c4) => c4.name), - rows: newTable.rows - } - }; - await saveDBToPath(props2.plugin, contextInfo.dbPath, dbField).then( - (f4) => { - setDBFileExists(true); - f4 ? setTableData(newTable) : new import_obsidian7.Notice("DB ERROR"); - } - ); - } else { - await saveMDBToPath(props2.plugin, contextInfo, newTable).then((f4) => { - setDBFileExists(true); - f4 ? setTableData(newTable) : new import_obsidian7.Notice("DB ERROR"); - }); + if (isSorting && previous.current.newIndex !== newIndex) { + previous.current.newIndex = newIndex; } - }; - p2(() => { - var _a3; - if (!schemaTable || !dbSchema) - return; - const _schema = (schema == null ? void 0 : schema.def) == dbSchema.id ? schemaTable.rows.find((f4) => f4.id == schema.id) : (_a3 = schemaTable.rows.find((f4) => f4.def == dbSchema.id)) != null ? _a3 : { - ...dbSchema, - id: uniqueNameFromString( - dbSchema.id + "View", - schemaTable.rows.map((f4) => f4.id) - ), - type: "table", - def: dbSchema.id - }; - if (_schema) { - setSchema(_schema); - if (dbFileExists) { - if (dbSchema.primary) { - runDef(); - } else { - getMDBData(); - } - } else { - const defaultTable = defaultTableDataForContext( - props2.plugin, - contextInfo - ); - if (defaultTable) - setTableData(defaultTable); - } + if (containerId !== previous.current.containerId) { + previous.current.containerId = containerId; } - }, [dbSchema]); - p2(() => { - if (dbFileExists && schema) { - parsePredicate(schema.predicate); + if (items !== previous.current.items) { + previous.current.items = items; } - }, [schema]); + }, [isSorting, newIndex, containerId, items]); p2(() => { - if (dbFileExists && tableData) - getContextTags(tableData); - }, [tableData]); - const selectRows = (lastSelected, rows) => { - setSelectedRows(rows); - if (!((dbSchema == null ? void 0 : dbSchema.primary) == "true")) + if (activeId === previous.current.activeId) { return; - if (lastSelected) { - const path = tableData.rows[parseInt(lastSelected)].File; - let evt = new CustomEvent(eventTypes.activePathChange, { - detail: { - selection: path, - path: { - ...pathByString(contextInfo.contextPath), - ref: schema == null ? void 0 : schema.id - } - } - }); - window.dispatchEvent(evt); - } else { - let evt = new CustomEvent(eventTypes.activePathChange, { - detail: { - path: { - ...pathByString(contextInfo.contextPath), - ref: schema == null ? void 0 : schema.id - }, - selection: null - } - }); - window.dispatchEvent(evt); } - }; - const getContextTags = async (_tableData) => { - const contextFields = _tableData.cols.filter((f4) => f4.type.contains("context")).map((f4) => f4.value).filter((f4) => !tagContexts.some((g4) => g4 == f4)); - for (let c4 of contextFields) { - loadContextFields(c4); + if (activeId && !previous.current.activeId) { + previous.current.activeId = activeId; + return; } + const timeoutId = setTimeout(() => { + previous.current.activeId = activeId; + }, 50); + return () => clearTimeout(timeoutId); + }, [activeId]); + return { + active, + activeIndex, + attributes, + data: data2, + rect, + index, + newIndex, + items, + isOver, + isSorting, + isDragging, + listeners, + node, + overIndex, + over, + setNodeRef, + setActivatorNodeRef, + setDroppableNodeRef, + setDraggableNodeRef, + transform: derivedTransform != null ? derivedTransform : finalTransform, + transition: getTransition() }; - const runDef = async () => { - if (contextInfo.type == "folder") { - getMDBTable(props2.plugin, contextInfo, "files").then((f4) => { - for (let c4 of tagContexts) { - loadTagContext(c4, f4.rows); - } - setTableData(f4); - return f4; - }); - } else if (contextInfo.type == "tag") { - getMDBTable(props2.plugin, contextInfo, "files").then((f4) => { - for (let c4 of tagContexts) { - loadTagContext(c4, f4.rows); - } - setTableData(f4); - return f4; - }); - } else if (contextInfo.type == "space") { - getMDBTable(props2.plugin, contextInfo, "files").then((f4) => { - setTableData(f4); - return f4; - }); - } else { - getMDBTable(props2.plugin, contextInfo, dbSchema.id).then( - (f4) => setTableData(f4) - ); + function getTransition() { + if (derivedTransform || itemsHaveChanged && previous.current.newIndex === index) { + return disabledTransition; } - }; - const loadTagContext = async (tag, files) => { - getMDBTable( - props2.plugin, - tagContextFromTag(props2.plugin, tag), - "files" - ).then((f4) => { - if (f4) { - const contextFields = f4.cols.filter((g4) => g4.type.contains("context")).map((g4) => g4.value).filter((g4) => !tagContexts.some((h5) => h5 == g4)); - for (let c4 of contextFields) { - loadContextFields(c4); - } - setContextTable((t4) => ({ - ...t4, - [tag]: f4 - })); - } - }); - }; - const loadContextFields = async (tag) => { - getMDBTable( - props2.plugin, - tagContextFromTag(props2.plugin, tag), - "files" - ).then((f4) => { - setContextTable((t4) => ({ - ...t4, - [tag]: f4 - })); - }); - }; - const saveContextDB = async (newTable, tag) => { - const context = tagContextFromTag(props2.plugin, tag); - await saveMDBToPath(props2.plugin, context, newTable).then( - (f4) => f4 && setContextTable((t4) => ({ - ...t4, - [tag]: newTable - })) - ); - }; - const savePredicate = (newPredicate) => { - const cleanedPredicate = validatePredicate(newPredicate); - saveSchema({ - ...schema, - predicate: JSON.stringify(cleanedPredicate) - }); - setPredicate(cleanedPredicate); - }; - p2(() => { - setPredicate((p3) => ({ - ...p3, - colsOrder: uniq([ - ...p3.colsOrder, - ...cols.filter((f4) => f4.hidden != "true").map((c4) => c4.name + c4.table) - ]) - })); - }, [cols]); - const parsePredicate = (predicateStr) => { - const newPredicate = safelyParseJSON(predicateStr); - setPredicate(validatePredicate(newPredicate)); - }; - const delColumn = (column) => { - let mdbtable; - const table = column.table; - if (table == "") { - mdbtable = tableData; - } else if (contextTable[table]) { - mdbtable = contextTable[table]; + if (shouldDisplaceDragSource && !isKeyboardEvent(activatorEvent) || !transition) { + return void 0; } - const newFields = mdbtable.cols.filter( - (f4, i4) => f4.name != column.name - ); - const newTable = { - ...mdbtable, - cols: newFields, - rows: mdbtable.rows.map((r3) => { - const { [column.name]: val, ...rest } = r3; - return rest; - }) - }; - if (table == "") { - saveDB2(newTable); - } else if (contextTable[table]) { - saveContextDB(newTable, table); + if (isSorting || shouldAnimateLayoutChanges) { + return CSS.Transition.toString({ + ...transition, + property: transitionProperty + }); } - }; - const newColumn = (col) => { - return saveColumn(col); - }; - const saveColumn = (newColumn2, oldColumn) => { - let mdbtable; - const column = { - ...newColumn2, - name: sanitizeColumnName(newColumn2.name) + return void 0; + } +} +function normalizeLocalDisabled(localDisabled, globalDisabled) { + var _localDisabled$dragga, _localDisabled$droppa; + if (typeof localDisabled === "boolean") { + return { + draggable: localDisabled, + droppable: false }; - const table = column.table; - if (table == "") { - mdbtable = tableData; - } else if (contextTable[table]) { - mdbtable = contextTable[table]; - } - if (column.name == "") { - new import_obsidian7.Notice(i18n_default.notice.noPropertyName); - return false; - } - if (!oldColumn && mdbtable.cols.find( - (f4) => f4.name.toLowerCase() == column.name.toLowerCase() - ) || oldColumn && oldColumn.name != column.name && mdbtable.cols.find( - (f4) => f4.name.toLowerCase() == column.name.toLowerCase() - )) { - new import_obsidian7.Notice(i18n_default.notice.duplicatePropertyName); - return false; + } + return { + draggable: (_localDisabled$dragga = localDisabled == null ? void 0 : localDisabled.draggable) != null ? _localDisabled$dragga : globalDisabled.draggable, + droppable: (_localDisabled$droppa = localDisabled == null ? void 0 : localDisabled.droppable) != null ? _localDisabled$droppa : globalDisabled.droppable + }; +} +function hasSortableData(entry) { + if (!entry) { + return false; + } + const data2 = entry.data.current; + if (data2 && "sortable" in data2 && typeof data2.sortable === "object" && "containerId" in data2.sortable && "items" in data2.sortable && "index" in data2.sortable) { + return true; + } + return false; +} +var directions = [KeyboardCode.Down, KeyboardCode.Right, KeyboardCode.Up, KeyboardCode.Left]; +var sortableKeyboardCoordinates = (event, _ref) => { + let { + context: { + active, + collisionRect, + droppableRects, + droppableContainers, + over, + scrollableAncestors } - const oldFieldIndex = oldColumn ? mdbtable.cols.findIndex((f4) => f4.name == oldColumn.name) : -1; - const newFields = oldFieldIndex == -1 ? [...mdbtable.cols, column] : mdbtable.cols.map((f4, i4) => i4 == oldFieldIndex ? column : f4); - const newTable = { - ...mdbtable, - cols: newFields, - rows: mdbtable.rows.map( - (f4) => oldColumn ? { - ...f4, - [column.name]: f4[oldColumn.name], - oldColumn: void 0 - } : f4 - ) - }; - if (oldColumn) - savePredicate({ - filters: predicate.filters.map( - (f4) => f4.field == oldColumn.name + oldColumn.table ? { ...f4, field: column.name + column.table } : f4 - ), - sort: predicate.sort.map( - (f4) => f4.field == oldColumn.name + oldColumn.table ? { ...f4, field: column.name + column.table } : f4 - ), - groupBy: predicate.groupBy.map( - (f4) => f4 == oldColumn.name + oldColumn.table ? column.name + column.table : f4 - ), - colsHidden: predicate.colsHidden.map( - (f4) => f4 == oldColumn.name + oldColumn.table ? column.name + column.table : f4 - ), - colsOrder: predicate.colsOrder.map( - (f4) => f4 == oldColumn.name + oldColumn.table ? column.name + column.table : f4 - ), - colsSize: { - ...predicate.colsSize, - [column.name + column.table]: predicate.colsSize[oldColumn.name + oldColumn.table], - [oldColumn.name + oldColumn.table]: void 0 - } - }); - if (table == "") { - syncAllMetadata(newTable); - } else if (contextTable[table]) { - saveContextDB(newTable, table); + } = _ref; + if (directions.includes(event.code)) { + event.preventDefault(); + if (!active || !collisionRect) { + return; } - return true; - }; - return /* @__PURE__ */ Cn.createElement(MDBContext.Provider, { - value: { - def, - readMode, - contextInfo, - data, - filteredData, - loadContextFields, - selectedRows, - selectRows, - tableData, - cols, - sortedColumns, - contextTable, - setContextTable, - predicate, - savePredicate, - saveDB: saveDB2, - saveContextDB, - schema, - saveColumn, - hideColumn, - sortColumn, - delColumn, - newColumn, - tagContexts, - tables, - setSchema, - saveSchema, - deleteSchema, - dbFileExists, - dbSchema, - searchString, - setSearchString, - setDBSchema, - updateValue: updateValue2, - updateFieldValue + const filteredContainers = []; + droppableContainers.getEnabled().forEach((entry) => { + if (!entry || entry != null && entry.disabled) { + return; + } + const rect = droppableRects.get(entry.id); + if (!rect) { + return; + } + switch (event.code) { + case KeyboardCode.Down: + if (collisionRect.top < rect.top) { + filteredContainers.push(entry); + } + break; + case KeyboardCode.Up: + if (collisionRect.top > rect.top) { + filteredContainers.push(entry); + } + break; + case KeyboardCode.Left: + if (collisionRect.left > rect.left) { + filteredContainers.push(entry); + } + break; + case KeyboardCode.Right: + if (collisionRect.left < rect.left) { + filteredContainers.push(entry); + } + break; + } + }); + const collisions = closestCorners({ + active, + collisionRect, + droppableRects, + droppableContainers: filteredContainers, + pointerCoordinates: null + }); + let closestId = getFirstCollision(collisions, "id"); + if (closestId === (over == null ? void 0 : over.id) && collisions.length > 1) { + closestId = collisions[1].id; } - }, props2.children); + if (closestId != null) { + const activeDroppable = droppableContainers.get(active.id); + const newDroppable = droppableContainers.get(closestId); + const newRect = newDroppable ? droppableRects.get(newDroppable.id) : null; + const newNode = newDroppable == null ? void 0 : newDroppable.node.current; + if (newNode && newRect && activeDroppable && newDroppable) { + const newScrollAncestors = getScrollableAncestors(newNode); + const hasDifferentScrollAncestors = newScrollAncestors.some((element, index) => scrollableAncestors[index] !== element); + const hasSameContainer = isSameContainer(activeDroppable, newDroppable); + const isAfterActive = isAfter(activeDroppable, newDroppable); + const offset2 = hasDifferentScrollAncestors || !hasSameContainer ? { + x: 0, + y: 0 + } : { + x: isAfterActive ? collisionRect.width - newRect.width : 0, + y: isAfterActive ? collisionRect.height - newRect.height : 0 + }; + const rectCoordinates = { + x: newRect.left, + y: newRect.top + }; + const newCoordinates = offset2.x && offset2.y ? rectCoordinates : subtract(rectCoordinates, offset2); + return newCoordinates; + } + } + } + return void 0; }; +function isSameContainer(a5, b4) { + if (!hasSortableData(a5) || !hasSortableData(b4)) { + return false; + } + return a5.data.current.sortable.containerId === b4.data.current.sortable.containerId; +} +function isAfter(a5, b4) { + if (!hasSortableData(a5) || !hasSortableData(b4)) { + return false; + } + if (!isSameContainer(a5, b4)) { + return false; + } + return a5.data.current.sortable.index < b4.data.current.sortable.index; +} + +// src/components/UI/menus/propertyMenu/newPropertyMenu.tsx +var import_obsidian16 = require("obsidian"); -// src/components/ui/menus/menuItems.tsx +// src/components/UI/menus/menuItems.tsx var import_obsidian8 = require("obsidian"); -// src/components/ui/menus/selectMenu/SelectMenuComponent.tsx +// src/components/UI/menus/selectMenu/SelectMenuComponent.tsx var import_fuzzysort = __toESM(require_fuzzysort()); -var import_lodash3 = __toESM(require_lodash()); +var import_lodash = __toESM(require_lodash()); -// src/components/ui/menus/selectMenu/SelectMenuInput.tsx +// src/components/UI/menus/selectMenu/SelectMenuInput.tsx var SIZER_STYLES = { position: "absolute", width: 0, @@ -20116,94 +27397,1456 @@ var STYLE_PROPS = [ "letterSpacing", "textTransform" ]; -var SelectMenuInput = k3( - (props2, input) => { - const { classNames: classNames9, inputAttributes, inputEventHandlers, index } = props2; - const sizer = _2(null); - const [inputWidth, setInputWidth] = h2(null); - const [query, setQuery] = h2(""); - const [placeholderText, setPlaceholderText] = h2(""); - p2(() => { - copyInputStyles(); - updateInputWidth(); - setTimeout(() => { - input.current.focus(); - }, 50); - }, []); - p2(() => { - if (query !== props2.query || placeholderText !== props2.placeholderText) { - setQuery(props2.query); - setPlaceholderText(props2.placeholderText); - updateInputWidth(); - } - }, [props2.query, props2.placeholderText]); - const copyInputStyles = () => { - const inputStyle = window.getComputedStyle(input.current); - STYLE_PROPS.forEach((prop) => { - sizer.current.style[prop] = inputStyle[prop]; - }); - }; - const updateInputWidth = () => { - let _inputWidth; - _inputWidth = Math.ceil(sizer.current.scrollWidth) + 2; - if (_inputWidth !== inputWidth) { - setInputWidth(_inputWidth); - } - }; - return /* @__PURE__ */ Cn.createElement("div", { - className: classNames9.searchWrapper - }, /* @__PURE__ */ Cn.createElement("input", { - ...inputAttributes, - ...inputEventHandlers, - ref: input, - value: query, - placeholder: placeholderText, - className: classNames9.searchInput, - role: "combobox", - style: { width: "100%" } - }), /* @__PURE__ */ Cn.createElement("div", { - ref: sizer, - style: SIZER_STYLES - }, query || placeholderText)); +var SelectMenuInput = k3( + (props2, input) => { + const { classNames: classNames9, inputAttributes, inputEventHandlers, index } = props2; + const sizer = _2(null); + const [inputWidth, setInputWidth] = h2(null); + const [query, setQuery] = h2(""); + const [placeholderText, setPlaceholderText] = h2(""); + p2(() => { + copyInputStyles(); + updateInputWidth(); + setTimeout(() => { + input.current.focus(); + }, 50); + }, []); + p2(() => { + if (query !== props2.query || placeholderText !== props2.placeholderText) { + setQuery(props2.query); + setPlaceholderText(props2.placeholderText); + updateInputWidth(); + } + }, [props2.query, props2.placeholderText]); + const copyInputStyles = () => { + const inputStyle = window.getComputedStyle(input.current); + STYLE_PROPS.forEach((prop) => { + sizer.current.style[prop] = inputStyle[prop]; + }); + }; + const updateInputWidth = () => { + let _inputWidth; + _inputWidth = Math.ceil(sizer.current.scrollWidth) + 2; + if (_inputWidth !== inputWidth) { + setInputWidth(_inputWidth); + } + }; + return /* @__PURE__ */ Cn.createElement("div", { + className: classNames9.searchWrapper + }, /* @__PURE__ */ Cn.createElement("input", { + ...inputAttributes, + ...inputEventHandlers, + ref: input, + value: query, + placeholder: placeholderText, + className: classNames9.searchInput, + role: "combobox", + style: { width: "100%" } + }), /* @__PURE__ */ Cn.createElement("div", { + ref: sizer, + style: SIZER_STYLES + }, query || placeholderText)); + } +); +var SelectMenuInput_default = SelectMenuInput; + +// src/components/UI/menus/selectMenu/SelectMenuPill.tsx +var SelectMenuPillComponent = (props2) => { + return /* @__PURE__ */ Cn.createElement("button", { + type: "button", + className: props2.classNames.selectedTag, + onClick: props2.onDelete + }, /* @__PURE__ */ Cn.createElement("span", { + className: props2.classNames.selectedTagName + }, props2.tag.name)); +}; +var SelectMenuPill_default = SelectMenuPillComponent; + +// src/utils/sticker.ts +var import_obsidian7 = require("obsidian"); + +// src/utils/icons.ts +var import_obsidian6 = require("obsidian"); +var iconForSpaceType = (type, path, force) => { + return type == "folder" ? "ui//mk-ui-folder" : type == "tag" ? force ? "lucide//tags" : "" : type == "vault" ? "lucide//vault" : "lucide//layout-grid"; +}; +var lucideIcon = (value) => { + var _a2; + return (_a2 = (0, import_obsidian6.getIcon)(value)) == null ? void 0 : _a2.outerHTML; +}; +var uiIconSet = { + "mk-ui-rows": ``, + "mk-ui-close": ` + + `, + "mk-ui-flow-hover": ` + + `, + "mk-ui-folder": ` + + `, + "mk-ui-open-link": ` + + `, + "mk-ui-file": ` + +`, + "mk-ui-expand": ` + +`, + "mk-ui-new-folder": ``, + "mk-ui-new-note": ``, + "mk-ui-collapse": ` + +`, + "mk-ui-options": ` + +`, + "mk-ui-plus": ` + +`, + "mk-ui-collapse-sm": ` + +`, + "mk-ui-search": ` + + +`, + "mk-ui-view-options": ` + + +`, + "mk-ui-clear": ` + + +`, + "mk-ui-new-file": ` + + +`, + "mk-ui-blink": ` + + + + +`, + "mk-ui-spaces": ` + +`, + "mk-ui-home": ` + +`, + "mk-ui-tags": ` + +`, + "mk-ui-handle": ` + + + + + + + +`, + "mk-ui-new-space": ` + + +`, + "mk-ui-file-solid": ` + + + +`, + "mk-ui-folder-solid": ` + + +`, + "mk-ui-sync": ` + + +`, + "mk-ui-stack": ` + + +`, + "mk-ui-cut": ` + + +`, + "mk-ui-backlink": ` + + +`, + "mk-ui-canvas": ` + + + + + +`, + "mk-ui-video": ` + + +`, + "mk-ui-edit": ` + + +`, + "mk-ui-list": ` + + + +`, + "mk-ui-build": ` + + +`, + "mk-ui-check": ` + + +`, + "mk-ui-layout": ` + + +`, + "mk-ui-colors": ` + + +`, + "mk-make-todo": ` + + + +`, + "mk-make-list": ` + + + + + + + +`, + "mk-make-ordered": ` + + + + + + + +`, + "mk-make-h1": ` + + + +`, + "mk-make-h2": ` + + + +`, + "mk-make-h3": ` + + + +`, + "mk-make-quote": ` + + + + + +`, + "mk-make-hr": ` + + +`, + "mk-make-link": ` + + +`, + "mk-make-image": ` + + + + + +`, + "mk-make-codeblock": ` + + + + +`, + "mk-make-callout": ` + + + +`, + "mk-make-note": ` + + + + + +`, + "mk-make-flow": ` + + +`, + "mk-make-tag": ` + + +`, + "mk-make-table": ` + + + + +`, + "mk-make-date": ` + + +`, + "mk-make-indent": ` + + + + + + +`, + "mk-make-unindent": ` + + + + + +`, + "mk-mark-strong": ` + + +`, + "mk-mark-em": ` + +`, + "mk-mark-strikethrough": ` + + + +`, + "mk-mark-code": ` + + + + +`, + "mk-mark-link": ` + +`, + "mk-mark-blocklink": ` + + + + +`, + "mk-mark-highlight": ` + + + + + +`, + "mk-make-attach": ` + + + + +`, + "mk-make-keyboard": ` + + + +`, + "mk-make-slash": ` + + + +`, + "mk-make-style": ` + +`, + "mk-mark-color": ` + + +`, + "mk-ui-any": ` + + +`, + "mk-ui-all": ` + + + +`, + "mk-ui-context": ` + + + + + +`, + "mk-ui-full-width": `` +}; +var mkLogo = ` + + +`; +var lucideIcons = [ + "accessibility", + "activity", + "air-vent", + "airplay", + "alarm-check", + "alarm-clock-off", + "alarm-clock", + "alarm-minus", + "alarm-plus", + "album", + "alert-circle", + "alert-octagon", + "alert-triangle", + "align-center-horizontal", + "align-center-vertical", + "align-center", + "align-end-horizontal", + "align-end-vertical", + "align-horizontal-distribute-center", + "align-horizontal-distribute-end", + "align-horizontal-distribute-start", + "align-horizontal-justify-center", + "align-horizontal-justify-end", + "align-horizontal-justify-start", + "align-horizontal-space-around", + "align-horizontal-space-between", + "align-justify", + "align-left", + "align-right", + "align-start-horizontal", + "align-start-vertical", + "align-vertical-distribute-center", + "align-vertical-distribute-end", + "align-vertical-distribute-start", + "align-vertical-justify-center", + "align-vertical-justify-end", + "align-vertical-justify-start", + "align-vertical-space-around", + "align-vertical-space-between", + "anchor", + "angry", + "annoyed", + "aperture", + "apple", + "archive-restore", + "archive", + "armchair", + "arrow-big-down", + "arrow-big-left", + "arrow-big-right", + "arrow-big-up", + "arrow-down-circle", + "arrow-down-left-from-circle", + "arrow-down-left", + "arrow-down-right-from-circle", + "arrow-down-right", + "arrow-down", + "arrow-left-circle", + "arrow-left-right", + "arrow-left", + "arrow-right-circle", + "arrow-right", + "arrow-up-circle", + "arrow-up-down", + "arrow-up-left-from-circle", + "arrow-up-left", + "arrow-up-right-from-circle", + "arrow-up-right", + "arrow-up", + "asterisk", + "at-sign", + "atom", + "award", + "axe", + "axis-3d", + "baby", + "backpack", + "baggage-claim", + "ban", + "banana", + "banknote", + "bar-chart-2", + "bar-chart-3", + "bar-chart-4", + "bar-chart-horizontal", + "bar-chart", + "baseline", + "bath", + "battery-charging", + "battery-full", + "battery-low", + "battery-medium", + "battery-warning", + "battery", + "beaker", + "bean-off", + "bean", + "bed-double", + "bed-single", + "bed", + "beef", + "beer", + "bell-minus", + "bell-off", + "bell-plus", + "bell-ring", + "bell", + "bike", + "binary", + "bird", + "bitcoin", + "blinds", + "bluetooth-connected", + "bluetooth-off", + "bluetooth-searching", + "bluetooth", + "bold", + "bomb", + "bone", + "book-copy", + "book-down", + "book-key", + "book-lock", + "book-marked", + "book-minus", + "book-open-check", + "book-open", + "book-plus", + "book-template", + "book-up", + "book-x", + "book", + "bookmark-minus", + "bookmark-plus", + "bookmark", + "bot", + "box-select", + "box", + "boxes", + "brain-circuit", + "brain-cog", + "brain", + "briefcase", + "brush", + "bug", + "building-2", + "building", + "bus", + "cake", + "calculator", + "calendar-check-2", + "calendar-check", + "calendar-clock", + "calendar-days", + "calendar-heart", + "calendar-minus", + "calendar-off", + "calendar-plus", + "calendar-range", + "calendar-search", + "calendar-x2", + "calendar-x", + "calendar", + "camera-off", + "camera", + "candy-off", + "candy", + "car", + "carrot", + "case-lower", + "case-sensitive", + "case-upper", + "cast", + "castle", + "cat", + "check-check", + "check-circle-2", + "check-circle", + "check-square", + "check", + "chef-hat", + "cherry", + "chevron-down-square", + "chevron-down", + "chevron-first", + "chevron-last", + "chevron-left-square", + "chevron-left", + "chevron-right-square", + "chevron-right", + "chevron-up-square", + "chevron-up", + "chevrons-down-up", + "chevrons-down", + "chevrons-left-right", + "chevrons-left", + "chevrons-right-left", + "chevrons-right", + "chevrons-up-down", + "chevrons-up", + "chrome", + "church", + "cigarette-off", + "cigarette", + "circle-dot", + "circle-ellipsis", + "circle-equal", + "circle-off", + "circle-slash-2", + "circle-slash", + "circle", + "circuit-board", + "citrus", + "clapperboard", + "clipboard-check", + "clipboard-copy", + "clipboard-edit", + "clipboard-list", + "clipboard-paste", + "clipboard-signature", + "clipboard-type", + "clipboard-x", + "clipboard", + "clock-1", + "clock-10", + "clock-11", + "clock-12", + "clock-2", + "clock-3", + "clock-4", + "clock-5", + "clock-6", + "clock-7", + "clock-8", + "clock-9", + "clock", + "cloud-cog", + "cloud-drizzle", + "cloud-fog", + "cloud-hail", + "cloud-lightning", + "cloud-moon-rain", + "cloud-moon", + "cloud-off", + "cloud-rain-wind", + "cloud-rain", + "cloud-snow", + "cloud-sun-rain", + "cloud-sun", + "cloud", + "cloudy", + "clover", + "code-2", + "code", + "codepen", + "codesandbox", + "coffee", + "cog", + "coins", + "columns", + "command", + "compass", + "component", + "concierge-bell", + "construction", + "contact", + "contrast", + "cookie", + "copy-check", + "copy-minus", + "copy-plus", + "copy-slash", + "copy-x", + "copy", + "copyleft", + "copyright", + "corner-down-left", + "corner-down-right", + "corner-left-down", + "corner-left-up", + "corner-right-down", + "corner-right-up", + "corner-up-left", + "corner-up-right", + "cpu", + "creative-commons", + "credit-card", + "croissant", + "crop", + "cross", + "crosshair", + "crown", + "cup-soda", + "curly-braces", + "currency", + "database-backup", + "database", + "delete", + "diamond", + "dice-1", + "dice-2", + "dice-3", + "dice-4", + "dice-5", + "dice-6", + "dices", + "diff", + "disc-2", + "disc", + "divide-circle", + "divide-square", + "divide", + "dna-off", + "dna", + "dog", + "dollar-sign", + "door-closed", + "door-open", + "download-cloud", + "download", + "dribbble", + "droplet", + "droplets", + "drumstick", + "dumbbell", + "ear-off", + "ear", + "edit-2", + "edit-3", + "edit", + "egg-fried", + "egg-off", + "egg", + "equal-not", + "equal", + "eraser", + "euro", + "expand", + "external-link", + "eye-off", + "eye", + "facebook", + "factory", + "fan", + "fast-forward", + "feather", + "figma", + "file-archive", + "file-audio-2", + "file-audio", + "file-axis-3d", + "file-badge-2", + "file-badge", + "file-bar-chart-2", + "file-bar-chart", + "file-box", + "file-check-2", + "file-check", + "file-clock", + "file-code", + "file-cog-2", + "file-cog", + "file-diff", + "file-digit", + "file-down", + "file-edit", + "file-heart", + "file-image", + "file-input", + "file-json-2", + "file-json", + "file-key-2", + "file-key", + "file-line-chart", + "file-lock-2", + "file-lock", + "file-minus-2", + "file-minus", + "file-output", + "file-pie-chart", + "file-plus-2", + "file-plus", + "file-question", + "file-scan", + "file-search-2", + "file-search", + "file-signature", + "file-spreadsheet", + "file-symlink", + "file-terminal", + "file-text", + "file-type-2", + "file-type", + "file-up", + "file-video-2", + "file-video", + "file-volume-2", + "file-volume", + "file-warning", + "file-x2", + "file-x", + "file", + "files", + "film", + "filter-x", + "filter", + "fingerprint", + "fish-off", + "fish", + "flag-off", + "flag-triangle-left", + "flag-triangle-right", + "flag", + "flame", + "flashlight-off", + "flashlight", + "flask-conical-off", + "flask-conical", + "flask-round", + "flip-horizontal-2", + "flip-horizontal", + "flip-vertical-2", + "flip-vertical", + "flower-2", + "flower", + "focus", + "folder-archive", + "folder-check", + "folder-clock", + "folder-closed", + "folder-cog-2", + "folder-cog", + "folder-down", + "folder-edit", + "folder-git-2", + "folder-git", + "folder-heart", + "folder-input", + "folder-key", + "folder-lock", + "folder-minus", + "folder-open", + "folder-output", + "folder-plus", + "folder-search-2", + "folder-search", + "folder-symlink", + "folder-tree", + "folder-up", + "folder-x", + "folder", + "folders", + "footprints", + "forklift", + "form-input", + "forward", + "frame", + "framer", + "frown", + "fuel", + "function-square", + "gamepad-2", + "gamepad", + "gauge", + "gavel", + "gem", + "ghost", + "gift", + "git-branch-plus", + "git-branch", + "git-commit", + "git-compare", + "git-fork", + "git-merge", + "git-pull-request-closed", + "git-pull-request-draft", + "git-pull-request", + "github", + "gitlab", + "glass-water", + "glasses", + "globe-2", + "globe", + "grab", + "graduation-cap", + "grape", + "grid", + "grip-horizontal", + "grip-vertical", + "grip", + "hammer", + "hand-metal", + "hand", + "hard-drive", + "hard-hat", + "hash", + "haze", + "heading-1", + "heading-2", + "heading-3", + "heading-4", + "heading-5", + "heading-6", + "heading", + "headphones", + "heart-crack", + "heart-handshake", + "heart-off", + "heart-pulse", + "heart", + "help-circle", + "helping-hand", + "hexagon", + "highlighter", + "history", + "home", + "hop-off", + "hop", + "hotel", + "hourglass", + "ice-cream-2", + "ice-cream", + "image-minus", + "image-off", + "image-plus", + "image", + "import", + "inbox", + "indent", + "indian-rupee", + "infinity", + "info", + "inspect", + "instagram", + "italic", + "japanese-yen", + "joystick", + "key", + "keyboard", + "lamp-ceiling", + "lamp-desk", + "lamp-floor", + "lamp-wall-down", + "lamp-wall-up", + "lamp", + "landmark", + "languages", + "laptop-2", + "laptop", + "lasso-select", + "lasso", + "laugh", + "layers", + "layout-dashboard", + "layout-grid", + "layout-list", + "layout-template", + "layout", + "leaf", + "library", + "life-buoy", + "lightbulb-off", + "lightbulb", + "line-chart", + "link-2off", + "link-2", + "link", + "linkedin", + "list-checks", + "list-end", + "list-minus", + "list-music", + "list-ordered", + "list-plus", + "list-start", + "list-tree", + "list-video", + "list-x", + "list", + "loader-2", + "loader", + "locate-fixed", + "locate-off", + "locate", + "lock", + "log-in", + "log-out", + "luggage", + "magnet", + "mail-check", + "mail-minus", + "mail-open", + "mail-plus", + "mail-question", + "mail-search", + "mail-warning", + "mail-x", + "mail", + "mailbox", + "mails", + "map-pin-off", + "map-pin", + "map", + "martini", + "maximize-2", + "maximize", + "medal", + "megaphone-off", + "megaphone", + "meh", + "menu", + "message-circle", + "message-square-dashed", + "message-square-plus", + "message-square", + "messages-square", + "mic-2", + "mic-off", + "mic", + "microscope", + "microwave", + "milestone", + "milk-off", + "milk", + "minimize-2", + "minimize", + "minus-circle", + "minus-square", + "minus", + "monitor-off", + "monitor-smartphone", + "monitor-speaker", + "monitor", + "moon", + "more-horizontal", + "more-vertical", + "mountain-snow", + "mountain", + "mouse-pointer-2", + "mouse-pointer-click", + "mouse-pointer", + "mouse", + "move-3d", + "move-diagonal-2", + "move-diagonal", + "move-horizontal", + "move-vertical", + "move", + "music-2", + "music-3", + "music-4", + "music", + "navigation-2off", + "navigation-2", + "navigation-off", + "navigation", + "network", + "newspaper", + "nfc", + "nut-off", + "nut", + "octagon", + "option", + "orbit", + "outdent", + "package-2", + "package-check", + "package-minus", + "package-open", + "package-plus", + "package-search", + "package-x", + "package", + "paint-bucket", + "paintbrush-2", + "paintbrush", + "palette", + "palmtree", + "paperclip", + "parking-circle-off", + "parking-circle", + "parking-square-off", + "parking-square", + "party-popper", + "pause-circle", + "pause-octagon", + "pause", + "pen-tool", + "pencil", + "percent", + "person-standing", + "phone-call", + "phone-forwarded", + "phone-incoming", + "phone-missed", + "phone-off", + "phone-outgoing", + "phone", + "picture-in-picture-2", + "picture-in-picture", + "pie-chart", + "piggy-bank", + "pilcrow", + "pill", + "pin-off", + "pin", + "pipette", + "pizza", + "plane-landing", + "plane-takeoff", + "plane", + "play-circle", + "play", + "plug-2", + "plug-zap", + "plug", + "plus-circle", + "plus-square", + "plus", + "pocket", + "podcast", + "pointer", + "pound-sterling", + "power-off", + "power", + "printer", + "puzzle", + "qr-code", + "quote", + "radio-receiver", + "radio-tower", + "radio", + "rat", + "receipt", + "rectangle-horizontal", + "rectangle-vertical", + "recycle", + "redo-2", + "redo", + "refresh-ccw", + "refresh-cw", + "refrigerator", + "regex", + "remove-formatting", + "repeat-1", + "repeat", + "replace-all", + "replace", + "reply-all", + "reply", + "rewind", + "rocket", + "rocking-chair", + "rotate-3d", + "rotate-ccw", + "rotate-cw", + "router", + "rss", + "ruler", + "russian-ruble", + "sailboat", + "salad", + "sandwich", + "save", + "scale-3d", + "scale", + "scaling", + "scan-face", + "scan-line", + "scan", + "school-2", + "school", + "scissors", + "screen-share-off", + "screen-share", + "scroll", + "search", + "send", + "separator-horizontal", + "separator-vertical", + "server-cog", + "server-crash", + "server-off", + "server", + "settings-2", + "settings", + "share-2", + "share", + "sheet", + "shield-alert", + "shield-check", + "shield-close", + "shield-off", + "shield-question", + "shield", + "ship", + "shirt", + "shopping-bag", + "shopping-cart", + "shovel", + "shower-head", + "shrink", + "shrub", + "shuffle", + "sidebar-close", + "sidebar-open", + "sidebar", + "sigma", + "signal-high", + "signal-low", + "signal-medium", + "signal-zero", + "signal", + "siren", + "skip-back", + "skip-forward", + "skull", + "slack", + "slice", + "sliders-horizontal", + "sliders", + "smartphone-charging", + "smartphone-nfc", + "smartphone", + "smile-plus", + "smile", + "snowflake", + "sofa", + "sort-asc", + "sort-desc", + "soup", + "space", + "speaker", + "spline", + "split-square-horizontal", + "split-square-vertical", + "sprout", + "square", + "stamp", + "star-half", + "star-off", + "star", + "step-back", + "step-forward", + "stethoscope", + "sticker", + "sticky-note", + "stop-circle", + "store", + "stretch-horizontal", + "stretch-vertical", + "strikethrough", + "subscript", + "subtitles", + "sun-dim", + "sun-medium", + "sun-moon", + "sun-snow", + "sun", + "sunrise", + "sunset", + "superscript", + "swiss-franc", + "switch-camera", + "sword", + "swords", + "syringe", + "table-2", + "table", + "tablet", + "tablets", + "tag", + "tags", + "target", + "tent", + "terminal-square", + "terminal", + "test-tube-2", + "test-tube", + "test-tubes", + "text-cursor-input", + "text-cursor", + "text-selection", + "text", + "thermometer-snowflake", + "thermometer-sun", + "thermometer", + "thumbs-down", + "thumbs-up", + "ticket", + "timer-off", + "timer-reset", + "timer", + "toggle-left", + "toggle-right", + "tornado", + "tower-control", + "toy-brick", + "train", + "trash-2", + "trash", + "tree-deciduous", + "tree-pine", + "trees", + "trello", + "trending-down", + "trending-up", + "triangle", + "trophy", + "truck", + "tv-2", + "tv", + "twitch", + "twitter", + "type", + "umbrella", + "underline", + "undo-2", + "undo", + "unlink-2", + "unlink", + "unlock", + "upload-cloud", + "upload", + "usb", + "user-check", + "user-cog", + "user-minus", + "user-plus", + "user-x", + "user", + "users", + "utensils-crossed", + "utensils", + "utility-pole", + "vault", + "vegan", + "venetian-mask", + "verified", + "vibrate-off", + "vibrate", + "video-off", + "video", + "view", + "voicemail", + "volume-1", + "volume-2", + "volume-x", + "volume", + "vote", + "wallet", + "wand-2", + "wand", + "warehouse", + "watch", + "waves", + "webcam", + "webhook", + "wheat-off", + "wheat", + "whole-word", + "wifi-off", + "wifi", + "wind", + "wine-off", + "wine", + "wrap-text", + "wrench", + "x-circle", + "x-octagon", + "x-square", + "x", + "youtube", + "zap-off", + "zap", + "zoom-in", + "zoom-out" +]; + +// src/utils/sticker.ts +var stickerFromString = (sticker, plugin) => { + var _a2; + if (!sticker || typeof sticker != "string") + return ""; + const [type, value] = parseStickerString(sticker); + if (type == "" || type == "emoji") { + return emojiFromString(value); + } else if (type == "ui") { + return uiIconSet[value]; + } else if (type == "lucide") { + return (_a2 = (0, import_obsidian7.getIcon)(value)) == null ? void 0 : _a2.outerHTML; + } else { + return plugin.index.iconsCache.get(value); } -); -var SelectMenuInput_default = SelectMenuInput; +}; -// src/components/ui/menus/selectMenu/SelectMenuPill.tsx -var SelectMenuPillComponent = (props2) => { - return /* @__PURE__ */ Cn.createElement("button", { - type: "button", - className: props2.classNames.selectedTag, - onClick: props2.onDelete - }, /* @__PURE__ */ Cn.createElement("span", { - className: props2.classNames.selectedTagName - }, props2.tag.name)); +// src/components/UI/Sticker.tsx +var Sticker = (props2) => { + return /* @__PURE__ */ Cn.createElement("div", { + className: "mk-sticker", + dangerouslySetInnerHTML: { + __html: stickerFromString(props2.sticker, props2.plugin) + } + }); }; -var SelectMenuPill_default = SelectMenuPillComponent; -// src/components/ui/menus/selectMenu/SelectMenuSuggestions.tsx +// src/components/UI/menus/selectMenu/concerns/matchers.js +function escapeForRegExp(string) { + return string.replace(/[-\\^$*+?.()|[\]{}]/g, "\\$&"); +} +function matchAny(string) { + return new RegExp(escapeForRegExp(string), "gi"); +} +function matchExact(string) { + return new RegExp(`^${escapeForRegExp(string)}$`, "i"); +} + +// src/components/UI/menus/selectMenu/SelectMenuSuggestions.tsx function markIt(name, query) { const regexp = matchAny(query); return name.replace(regexp, "$&"); } var SelectMenuSuggestionsComponent = (props2) => { - const ref = _2(null); + const ref2 = _2(null); p2(() => { var _a2; if (props2.active) { - (_a2 = ref == null ? void 0 : ref.current) == null ? void 0 : _a2.scrollIntoViewIfNeeded(); + (_a2 = ref2 == null ? void 0 : ref2.current) == null ? void 0 : _a2.scrollIntoViewIfNeeded(); } }, [props2.active]); - return /* @__PURE__ */ Cn.createElement(Cn.Fragment, null, /* @__PURE__ */ Cn.createElement("div", { + return /* @__PURE__ */ Cn.createElement(Cn.Fragment, null, props2.item.icon && /* @__PURE__ */ Cn.createElement(Sticker, { + plugin: props2.plugin, + sticker: props2.item.icon + }), /* @__PURE__ */ Cn.createElement("div", { className: "mk-options-menu-inner" }, props2.item.onToggle && /* @__PURE__ */ Cn.createElement("div", null, "Toggle"), /* @__PURE__ */ Cn.createElement("span", { - ref, + ref: ref2, dangerouslySetInnerHTML: { __html: markIt(props2.item.name, props2.query) } }), props2.item.description && /* @__PURE__ */ Cn.createElement("span", { className: "mk-description", - ref, + ref: ref2, dangerouslySetInnerHTML: { __html: markIt(props2.item.description, props2.query) } @@ -20251,6 +28894,7 @@ var SelectMenuSuggestions = (props2) => { onMouseOver: (e4) => mouseOver(e4, index), onMouseOut: (e4) => props2.hoverSelect && clearTimeout(timer.current) }, /* @__PURE__ */ Cn.createElement(SelectMenuSuggestionsComponent, { + plugin: props2.plugin, item, query: props2.query, active: index == props2.index, @@ -20277,7 +28921,7 @@ var SelectMenuSuggestions = (props2) => { }; var SelectMenuSuggestions_default = SelectMenuSuggestions; -// src/components/ui/menus/selectMenu/concerns/focusNextElement.js +// src/components/UI/menus/selectMenu/concerns/focusNextElement.js function focusNextElement(scope, currentTarget) { const interactiveEls = scope.querySelectorAll("a,button,input"); const currentEl = Array.prototype.findIndex.call( @@ -20290,7 +28934,7 @@ function focusNextElement(scope, currentTarget) { } } -// src/components/ui/menus/selectMenu/SelectMenuComponent.tsx +// src/components/UI/menus/selectMenu/SelectMenuComponent.tsx var KEYS = { ENTER: "Enter", TAB: "Tab", @@ -20314,6 +28958,7 @@ var CLASS_NAMES = { suggestionDisabled: "is-disabled" }; var defaultProps = { + plugin: null, id: "SelectMenu", tags: [], suggestionsOnly: false, @@ -20333,15 +28978,15 @@ var defaultProps = { var findMatchIndex = (options, query) => { return options.findIndex((option) => matchExact(query).test(option.name)); }; -var pressDelimiter = (props2, query, index, options, addTag2, modifiers) => { +var pressDelimiter = (props2, query, index, options, addTag, modifiers) => { if (query.length >= props2.minQueryLength) { const match2 = findMatchIndex(options, query); const _index = index === -1 ? match2 : index; const tag = _index > -1 ? options[_index] : null; if (tag) { - addTag2(tag, modifiers); + addTag(tag, modifiers); } else { - addTag2({ name: query, value: query }, modifiers); + addTag({ name: query, value: query }, modifiers); } } }; @@ -20349,9 +28994,13 @@ function defaultSuggestionsFilter(item, query) { const regexp = matchAny(query); return regexp.test(item.name); } -function getOptions(props2, query) { +function getOptions2(props2, query, section) { let options; - options = query.length == 0 ? props2.suggestions : import_fuzzysort.default.go(query, props2.suggestions, { + let suggestions = props2.suggestions; + if (section.length > 0) { + suggestions = props2.suggestions.filter((f4) => f4.section == section); + } + options = query.length == 0 ? suggestions : import_fuzzysort.default.go(query, suggestions, { keys: ["name", "value"] }).map((result) => result.obj); options = options.slice(0, props2.maxSuggestionsLength); @@ -20368,17 +29017,27 @@ function getOptions(props2, query) { return options; } var SelectMenuComponent = Cn.forwardRef( - (_props, ref) => { + (_props, ref2) => { const props2 = { ...defaultProps, ..._props }; const [options, setOptions] = h2([]); + const sections = F2(() => { + var _a2; + if (!props2.showSections) + return []; + return [ + "", + ...(_a2 = props2.sections) != null ? _a2 : uniq(props2.suggestions.map((f4) => f4.section)).filter((f4) => f4) + ]; + }, [props2.showSections, props2.sections, props2.suggestions]); const inputRef = _2(null); + const [section, setSection] = h2(""); const [query, setQuery] = h2(""); const [focused, setFocused] = h2(false); const [index, setIndex] = h2(0); const onComposition = _2(false); p2(() => { - if (ref) { - ref.current = () => { + if (ref2) { + ref2.current = () => { var _a2; if (!focused) { (_a2 = inputRef == null ? void 0 : inputRef.current) == null ? void 0 : _a2.focus(); @@ -20396,7 +29055,7 @@ var SelectMenuComponent = Cn.forwardRef( } }, [index, options]); const debounceFn = T2( - (0, import_lodash3.debounce)(handleDebounceFn, 300, { + (0, import_lodash.debounce)(handleDebounceFn, 300, { leading: false }), [] @@ -20409,8 +29068,8 @@ var SelectMenuComponent = Cn.forwardRef( setOptions(props2.defaultSuggestions); return; } - setOptions(getOptions(props2, query)); - }, [query, props2.suggestions]); + setOptions(getOptions2(props2, query, section)); + }, [query, props2.suggestions, section, props2]); const container = _2(null); const onInput = (e4) => { if (e4.type === "compositionstart") { @@ -20428,7 +29087,7 @@ var SelectMenuComponent = Cn.forwardRef( props2.onInput(_query); } if (_query.length === query.length + 1 && props2.delimiters.indexOf(query.slice(-1)) > -1) { - pressDelimiter(props2, query, index, options, addTag2, {}); + pressDelimiter(props2, query, index, options, addTag, {}); } else if (_query !== query) { setQuery(_query); } @@ -20438,13 +29097,16 @@ var SelectMenuComponent = Cn.forwardRef( if (query || index > -1) { e4.preventDefault(); } - pressDelimiter(props2, query, index, options, addTag2, { + pressDelimiter(props2, query, index, options, addTag, { ctrlKey: e4.ctrlKey, metaKey: e4.metaKey, altKey: e4.altKey, shiftKey: e4.shiftKey }); } + if (e4.key === KEYS.TAB) { + pressTabKey(e4); + } if (e4.key === KEYS.BACKSPACE) { pressBackspaceKey(); } @@ -20471,9 +29133,9 @@ var SelectMenuComponent = Cn.forwardRef( if (container.current) { focusNextElement(container.current, event.currentTarget); } - deleteTag2(index2); + deleteTag(index2); }; - const addTag2 = (tag, modifiers) => { + const addTag = (tag, modifiers) => { if (tag.disabled) { return; } @@ -20483,7 +29145,7 @@ var SelectMenuComponent = Cn.forwardRef( props2.onAddition(tag, modifiers); clearInput(); }; - const deleteTag2 = (i4) => { + const deleteTag = (i4) => { props2.onDelete(i4); }; const clearInput = () => { @@ -20505,7 +29167,26 @@ var SelectMenuComponent = Cn.forwardRef( }; function pressBackspaceKey() { if (!query.length) { - deleteTag2(props2.tags.length - 1); + deleteTag(props2.tags.length - 1); + } + } + function pressTabKey(e4) { + if (props2.showSections) { + e4.preventDefault(); + e4.stopPropagation(); + setSection((p3) => { + const sectionIndex = sections.findIndex((g4) => g4 == p3); + if (e4.shiftKey) { + if (sectionIndex == 0) { + return p3; + } + return sections[sectionIndex - 1]; + } + if (sectionIndex == sections.length - 1) { + return p3; + } + return sections[sectionIndex + 1]; + }); } } const focusInput = () => { @@ -20549,7 +29230,14 @@ var SelectMenuComponent = Cn.forwardRef( inputEventHandlers, expanded, placeholderText: props2.placeholderText - }))) : null, options.length || props2.allowNew ? /* @__PURE__ */ Cn.createElement(SelectMenuSuggestions_default, { + }))) : null, props2.showSections ? /* @__PURE__ */ Cn.createElement("div", { + className: "mk-options-menu-sections" + }, sections.map((f4, i4) => /* @__PURE__ */ Cn.createElement("div", { + key: i4, + onClick: () => setSection(f4), + className: `${section == f4 ? "is-active" : ""} mk-options-menu-section` + }, f4 == "" ? "All" : f4))) : /* @__PURE__ */ Cn.createElement(Cn.Fragment, null), options.length || props2.allowNew ? /* @__PURE__ */ Cn.createElement(SelectMenuSuggestions_default, { + plugin: props2.plugin, options, hoverSelect: props2.hoverSelect, query, @@ -20558,7 +29246,7 @@ var SelectMenuComponent = Cn.forwardRef( id: props2.id, classNames: classNames9, expanded, - addTag: addTag2, + addTag, allowNew: props2.allowNew, deleteOption: props2.onDeleteOption }) : null, props2.previewComponent); @@ -20567,9 +29255,9 @@ var SelectMenuComponent = Cn.forwardRef( SelectMenuComponent.displayName = "SelectMenuComponent"; var SelectMenuComponent_default = SelectMenuComponent; -// src/components/ui/menus/selectMenu.tsx +// src/components/UI/menus/selectMenu.tsx var SelectMenu = Cn.forwardRef( - (props2, ref) => { + (props2, ref2) => { var _a2; const initialOptions = props2.options.map((o3, i4) => { return { @@ -20602,12 +29290,12 @@ var SelectMenu = Cn.forwardRef( ); const onDelete = T2( (tagIndex) => { - const newTags = tags.filter((_9, i4) => i4 !== tagIndex); + const newTags = tags.filter((_12, i4) => i4 !== tagIndex); setTags(newTags); props2.saveOptions( suggestions.map((f4) => f4.value), newTags.map((f4) => f4.value), - {} + false ); }, [suggestions, tags, props2] @@ -20651,7 +29339,7 @@ var SelectMenu = Cn.forwardRef( props2.saveOptions( newSuggestions.map((f4) => f4.value), newTags.map((f4) => f4.value), - modifiers + true ); if (!props2.multi) { props2.hide(); @@ -20674,7 +29362,8 @@ var SelectMenu = Cn.forwardRef( return /* @__PURE__ */ Cn.createElement(SelectMenuComponent_default, { tags: props2.multi ? tags : [], suggestions, - ref, + plugin: props2.plugin, + ref: ref2, onDelete, onDeleteOption, onAddition, @@ -20684,7 +29373,9 @@ var SelectMenu = Cn.forwardRef( minQueryLength: 0, onHover: props2.onHover, hoverSelect: props2.onHover ? true : false, - maxSuggestionsLength: props2.showAll ? Math.min(50, props2.options.length) : 8, + showSections: props2.showSections, + sections: props2.sections, + maxSuggestionsLength: props2.showAll ? Math.min(50, props2.options.length) : 25, suggestionsOnly: !props2.searchable && !props2.editable, allowNew: props2.editable, previewComponent: props2.previewComponent @@ -20694,7 +29385,7 @@ var SelectMenu = Cn.forwardRef( SelectMenu.displayName = "SelectMenu"; var selectMenu_default = SelectMenu; -// src/components/ui/menus/menuItems.tsx +// src/components/UI/menus/menuItems.tsx var inputMenuItem = (menuItem, value, setValue) => { const frag = document.createDocumentFragment(); const spanEl = frag.createEl("span"); @@ -20761,7 +29452,7 @@ var showSelectMenu = (point, optionProps) => { menu.showAtPosition(point); return menu; }; -var disclosureMenuItem = (menuItem, multi, editable, title, value, options, saveOptions) => { +var disclosureMenuItem = (plugin, menuItem, multi, editable, title, value, options, saveOptions) => { const frag = document.createDocumentFragment(); const div = frag.createDiv("title"); div.textContent = title; @@ -20771,10 +29462,11 @@ var disclosureMenuItem = (menuItem, multi, editable, title, value, options, save menuItem.onClick((ev) => { var _a2; ev.stopPropagation(); - const offset = menuItem.dom.getBoundingClientRect(); + const offset2 = menuItem.dom.getBoundingClientRect(); showSelectMenu( - { x: offset.right + 10, y: offset.top }, + { x: offset2.right + 10, y: offset2.top }, { + plugin, multi, editable, value: (_a2 = parseMultiString(value)) != null ? _a2 : [], @@ -20788,68 +29480,99 @@ var disclosureMenuItem = (menuItem, multi, editable, title, value, options, save return menuItem; }; -// src/components/ContextView/TagsView/TagsView.tsx -var import_obsidian9 = require("obsidian"); -var TagsView = (props2) => { - const showTagMenu = (e4, tag) => { - e4.stopPropagation(); - e4.preventDefault(); - const menu = new import_obsidian9.Menu(); - menu.addItem((menuItem) => { - menuItem.setIcon("hash"); - menuItem.setTitle(i18n_default.menu.openTag); - menuItem.onClick(() => { - openTagContext(tag, props2.plugin, e4.metaKey); - }); - }); - if (props2.removeTag) - menu.addItem((menuItem) => { - menuItem.setIcon("trash"); - menuItem.setTitle(i18n_default.menu.removeTag); - menuItem.onClick(() => { - props2.removeTag(tag); - }); - }); - const offset = e4.target.getBoundingClientRect(); - menu.showAtPosition({ x: offset.left, y: offset.top + 30 }); - }; - const showContextMenu = (e4) => { - const offset = e4.target.getBoundingClientRect(); - const f4 = loadTags(props2.plugin); - showSelectMenu( - { x: offset.left, y: offset.top + 30 }, - { - multi: false, - editable: true, - value: [], - options: f4.map((m5) => ({ name: m5, value: m5 })), - saveOptions: (_9, value) => props2.addTag(value[0]), - placeholder: i18n_default.labels.contextItemSelectPlaceholder, - searchable: true, - showAll: true - } - ); - }; - return /* @__PURE__ */ Cn.createElement("div", { - className: "mk-tag-selector" - }, props2.tags.filter((f4) => f4).map((f4, i4) => /* @__PURE__ */ Cn.createElement("div", { - key: i4, - onContextMenu: (e4) => showTagMenu(e4, f4), - onClick: (e4) => !props2.canOpen ? showTagMenu(e4, f4) : openTagContext(f4, props2.plugin, e4.metaKey) - }, /* @__PURE__ */ Cn.createElement("span", { - className: "cm-hashtag cm-hashtag-begin" - }, "#"), /* @__PURE__ */ Cn.createElement("span", { - className: "cm-hashtag cm-hashtag-end" - }, stringFromTag(f4)))), props2.addTag && /* @__PURE__ */ Cn.createElement("div", { - "aria-label": i18n_default.buttons.addTag, - onClick: (e4) => showContextMenu(e4) - }, /* @__PURE__ */ Cn.createElement("div", { - className: "mk-icon-xsmall", - dangerouslySetInnerHTML: { __html: uiIconSet["mk-ui-plus"] } - }))); +// src/components/UI/menus/propertyMenu/propertyMenu.tsx +var import_obsidian10 = require("obsidian"); + +// src/utils/contexts/predicate/sort.ts +var simpleSort = (a5, b4) => { + if (a5 < b4) + return -1; + if (a5 > b4) + return 1; + return 0; +}; +var stringSort = (value, filterValue) => simpleSort(value, filterValue); +var numSort = (value, filterValue) => simpleSort(parseFloat(value), parseFloat(filterValue)); +var boolSort = (value, filterValue) => simpleSort(value == "true" ? 1 : 0, filterValue == "true" ? 1 : 0); +var countSort = (value, filterValue) => simpleSort(parseMultiString(value).length, parseMultiString(filterValue).length); +var normalizedSortForType = (type, desc) => { + return Object.keys(sortFnTypes).find( + (f4) => sortFnTypes[f4].type.some((g4) => g4 == type) && sortFnTypes[f4].desc == desc + ); +}; +var sortFnTypes = { + alphabetical: { + type: ["text", "file", "link", "context", "fileprop"], + fn: stringSort, + label: i18n_default.sortTypes.alphaAsc, + desc: false + }, + reverseAlphabetical: { + type: ["text", "file", "link", "context", "fileprop"], + fn: (v3, f4) => stringSort(v3, f4) * -1, + label: i18n_default.sortTypes.alphaDesc, + desc: true + }, + earliest: { + type: ["date", "fileprop"], + fn: stringSort, + label: i18n_default.sortTypes.earliest, + desc: false + }, + latest: { + type: ["date", "fileprop"], + fn: (v3, f4) => stringSort(v3, f4) * -1, + label: i18n_default.sortTypes.latest, + desc: true + }, + boolean: { + type: ["boolean"], + fn: boolSort, + label: i18n_default.sortTypes.checkAsc, + desc: false + }, + booleanReverse: { + type: ["boolean"], + fn: (v3, f4) => boolSort(v3, f4) * -1, + label: i18n_default.sortTypes.checkDesc, + desc: true + }, + number: { + type: ["number", "fileprop"], + fn: numSort, + label: "1 \u2192 9", + desc: false + }, + reverseNumber: { + type: ["number", "fileprop"], + fn: (v3, f4) => numSort(v3, f4) * -1, + label: "9 \u2192 1", + desc: true + }, + count: { + type: ["option-multi", "context-multi", "link-multi"], + fn: countSort, + label: i18n_default.sortTypes.itemsDesc, + desc: true + }, + reverseCount: { + type: ["option-multi", "context-multi", "link-multi"], + fn: (v3, f4) => countSort(v3, f4) * -1, + label: i18n_default.sortTypes.itemsAsc, + desc: false + } +}; +var sortReturnForCol = (col, sort, row, row2) => { + if (!col) + return 0; + const sortType = sortFnTypes[sort.fn]; + if (sortType) { + return sortType.fn(row[sort.field], row2[sort.field]); + } + return 0; }; -// src/components/StickerMenu/emojis/default.ts +// src/components/SpaceView/Editor/StickerMenu/emojis/default.ts var emojis = { smileys_people: [ { n: ["grinning", "grinning face"], u: "1f600" }, @@ -26241,15 +34964,15 @@ var emojis = { ] }; -// src/components/ui/modals/stickerModal.tsx -var import_obsidian10 = require("obsidian"); +// src/components/UI/modals/stickerModal.tsx +var import_obsidian9 = require("obsidian"); var htmlFromSticker = (sticker) => { if (sticker.type == "emoji") { return emojiFromString(sticker.html); } return sticker.html; }; -var stickerModal = class extends import_obsidian10.FuzzySuggestModal { +var stickerModal = class extends import_obsidian9.FuzzySuggestModal { constructor(app2, plugin, setIcon) { super(app2); this.plugin = plugin; @@ -26272,7 +34995,7 @@ var stickerModal = class extends import_obsidian10.FuzzySuggestModal { type: "lucide", keywords: f4, value: f4, - html: (0, import_obsidian10.getIcon)(f4).outerHTML + html: (0, import_obsidian9.getIcon)(f4).outerHTML })); const allCustom = [...this.plugin.index.iconsCache.keys()].map( (f4) => ({ @@ -26283,6 +35006,13 @@ var stickerModal = class extends import_obsidian10.FuzzySuggestModal { html: this.plugin.index.iconsCache.get(f4) }) ); + const allUI = [...Object.keys(uiIconSet)].map((f4) => ({ + name: f4, + type: "ui", + keywords: f4, + value: f4, + html: uiIconSet[f4] + })); const allEmojis = Object.keys(emojis).reduce( (p3, c4) => [ ...p3, @@ -26295,3787 +35025,4203 @@ var stickerModal = class extends import_obsidian10.FuzzySuggestModal { ], [] ); - return [...allCustom, ...allEmojis, ...allLucide]; + return [...allCustom, ...allEmojis, ...allLucide, ...allUI]; } onChooseItem(item, evt) { this.setIcon(item.type + "//" + item.value); } }; -// src/hooks/useLongPress.tsx -function isMouseEvent(e4) { - return e4 && "screenX" in e4; -} - -// src/components/FileSticker/FileSticker.tsx -var import_obsidian12 = require("obsidian"); - -// src/utils/emoji.ts -var saveFileIcons = (plugin, files, icon) => { - files.forEach((file) => { - saveFileSticker(plugin, file, icon); - }); +// src/components/UI/menus/propertyMenu/propertyMenu.tsx +var selectPropertyTypeMenu = (e4, plugin, selectedType) => { + showSelectMenu(e4.target.getBoundingClientRect(), { + plugin, + multi: false, + editable: false, + searchable: false, + saveOptions: selectedType, + value: [], + showAll: true, + options: fieldTypes.filter((f4) => !f4.restricted).map((f4, i4) => ({ + id: i4 + 1, + name: f4.label, + value: f4.type, + icon: f4.icon + })) + }); +}; +var PropertyMenuComponent = (props2) => { + var _a2; + const [field, setField] = h2(props2.field); + const selectedType = (_12, value) => { + const newField = { + ...field, + type: value[0], + value: JSON.stringify(getNewValueForType(field, value)) + }; + setField(newField); + props2.saveField(newField); + }; + const selectedValue = (value) => { + const newField = { ...field, value }; + setField(newField); + props2.saveField(newField); + }; + const toggleMulti = () => { + const newField = { + ...field, + type: field.type == fieldType.multiType ? fieldType.type : fieldType.multiType + }; + setField(newField); + props2.saveField(newField); + }; + const fieldType = (_a2 = fieldTypeForType(field.type)) != null ? _a2 : fieldTypes[0]; + const getNewValueForType = (f4, value) => { + if (value[0].startsWith("option")) { + return JSON.stringify({ + options: props2.options.map((f5) => ({ + name: f5, + value: f5 + })) + }); + } + return value[0] == fieldType.type || value[0] == fieldType.multiType ? f4.value : null; + }; + return /* @__PURE__ */ Cn.createElement(Cn.Fragment, null, /* @__PURE__ */ Cn.createElement("div", { + className: "menu-item", + onClick: (e4) => selectPropertyTypeMenu(e4, props2.plugin, selectedType) + }, /* @__PURE__ */ Cn.createElement("span", null, i18n_default.labels.propertyType), /* @__PURE__ */ Cn.createElement("span", null, fieldType.label)), fieldType.multi ? /* @__PURE__ */ Cn.createElement("div", { + className: "menu-item" + }, /* @__PURE__ */ Cn.createElement("span", null, i18n_default.labels.multiple), /* @__PURE__ */ Cn.createElement("input", { + type: "checkbox", + checked: field.type == fieldType.multiType, + onChange: () => toggleMulti() + })) : /* @__PURE__ */ Cn.createElement(Cn.Fragment, null), /* @__PURE__ */ Cn.createElement("div", { + className: "menu-separator" + }), /* @__PURE__ */ Cn.createElement(PropertyValueComponent, { + plugin: props2.plugin, + name: field.name, + table: field.table, + fields: props2.fields, + fieldType: fieldType.type, + value: field.value, + contextPath: props2.contextPath, + saveValue: selectedValue + })); +}; +var showPropertyMenu = (props2) => { + const { + plugin, + position, + editable, + options, + field, + fields, + contextPath, + saveField, + hide, + deleteColumn, + sortColumn, + editCode, + hidden + } = props2; + const menu = new import_obsidian10.Menu(); + menu.setUseNativeMenu(false); + if (editable) { + menu.addItem((menuItem) => { + var _a2; + inputMenuItem( + menuItem, + (_a2 = field == null ? void 0 : field.name) != null ? _a2 : "", + (value) => saveField({ ...field, name: value }) + ); + menuItem.setIcon("type"); + }); + menu.addSeparator(); + const frag = document.createDocumentFragment(); + const div = frag.createDiv(); + div.addEventListener("click", (e4) => { + e4.stopImmediatePropagation(); + }); + div.addEventListener("keydown", (e4) => { + }); + const root = createRoot(div); + root.render( + /* @__PURE__ */ Cn.createElement(Cn.Fragment, null, /* @__PURE__ */ Cn.createElement(PropertyMenuComponent, { + plugin, + field, + fields, + contextPath, + options, + saveField + })) + ); + menu.addItem((menuItem) => { + menuItem.setTitle(frag); + menuItem.dom.toggleClass("mk-properties", true); + }); + menu.addSeparator(); + menu.addItem((menuItem) => { + menuItem.setIcon("gem"); + menuItem.setTitle("Set Icon"); + menuItem.onClick(() => { + const vaultChangeModal = new stickerModal( + props2.plugin.app, + props2.plugin, + (emoji) => saveField({ ...field, attrs: emoji }) + ); + vaultChangeModal.open(); + }); + }); + if (hide) { + if (!hidden) { + menu.addItem((menuItem) => { + menuItem.setTitle(i18n_default.menu.hideProperty); + menuItem.onClick(() => { + hide(field, true); + }); + menuItem.setIcon("eye-off"); + }); + } else { + menu.addItem((menuItem) => { + menuItem.setTitle(i18n_default.menu.unhideProperty); + menuItem.onClick(() => { + hide(field, false); + }); + menuItem.setIcon("eye"); + }); + } + } + if (editCode) { + menu.addItem((menuItem) => { + menuItem.setTitle(i18n_default.menu.editCode); + menuItem.onClick(() => { + editCode(); + }); + menuItem.setIcon("code"); + }); + } + if (deleteColumn) { + menu.addItem((menuItem) => { + menuItem.setTitle(i18n_default.menu.deleteProperty); + menuItem.onClick(() => { + deleteColumn(field); + }); + menuItem.setIcon("trash-2"); + }); + } + menu.addSeparator(); + } + const sortableString = normalizedSortForType(field.type, false); + if (sortableString && sortColumn) { + menu.addItem((menuItem) => { + menuItem.setTitle(i18n_default.menu.sortAscending); + menuItem.setIcon("sort-asc"); + menuItem.onClick(() => { + sortColumn({ + field: field.name + field.table, + fn: normalizedSortForType(field.type, false) + }); + }); + }); + menu.addItem((menuItem) => { + menuItem.setTitle(i18n_default.menu.sortDescending); + menuItem.setIcon("sort-desc"); + menuItem.onClick(() => { + sortColumn({ + field: field.name + field.table, + fn: normalizedSortForType(field.type, true) + }); + }); + }); + } + menu.showAtPosition(position); + return menu; +}; + +// src/context/ContextEditorContext.tsx +var import_lodash4 = __toESM(require_lodash()); +var import_obsidian14 = require("obsidian"); + +// src/utils/contexts/predicate/filterFns/filterFnTypes.ts +var filterFnTypes = { + isNotEmpty: { + type: ["text", "file", "link", "link-multi", "fileprop", "image"], + fn: (v3, f4) => !empty2(v3, ""), + valueType: "none" + }, + isEmpty: { + type: ["text", "file", "link", "link-multi", "fileprop", "image"], + fn: (v3, f4) => empty2(v3, ""), + valueType: "none" + }, + include: { + fn: (v3, f4) => stringCompare(v3, f4), + type: ["text", "file", "link", "link-multi", "fileprop", "image"], + valueType: "text" + }, + notInclude: { + type: ["text", "file", "link", "link-multi", "fileprop", "image"], + fn: (v3, f4) => !stringCompare(v3, f4), + valueType: "text" + }, + is: { + type: ["text", "file", "link", "context", "fileprop"], + fn: (v3, f4) => stringEqual(v3, f4), + valueType: "text" + }, + isNot: { + type: ["text", "file", "link", "context", "fileprop"], + fn: (v3, f4) => !stringEqual(v3, f4), + valueType: "text" + }, + equal: { + type: ["number"], + fn: (v3, f4) => stringEqual(v3, f4), + valueType: "number" + }, + isGreatThan: { + type: ["number"], + fn: (v3, f4) => greaterThan(v3, f4), + valueType: "number" + }, + isLessThan: { + type: ["number"], + fn: (v3, f4) => lessThan(v3, f4), + valueType: "number" + }, + isLessThanOrEqual: { + type: ["number"], + fn: (v3, f4) => !greaterThan(v3, f4), + valueType: "number" + }, + isGreatThanOrEqual: { + type: ["number"], + fn: (v3, f4) => !lessThan(v3, f4), + valueType: "number" + }, + dateBefore: { + type: ["date", "fileprop"], + fn: (v3, f4) => lessThan(v3, f4), + valueType: "date" + }, + dateAfter: { + type: ["date", "fileprop"], + fn: (v3, f4) => greaterThan(v3, f4), + valueType: "date" + }, + isSameDateAsToday: { + type: ["date"], + fn: (v3, f4) => isSameDayAsToday(v3, f4), + valueType: "none" + }, + isAnyInList: { + type: ["option", "context", "option-multi", "context-multi", "tags-multi", "tags"], + fn: (v3, f4) => listIncludes(v3, f4), + valueType: "list" + }, + isNoneInList: { + type: ["option", "context", "option-multi", "context-multi", "tags-multi", "tags"], + fn: (v3, f4) => !listIncludes(v3, f4), + valueType: "list" + }, + isTrue: { + type: ["boolean"], + fn: (v3, f4) => v3 == "true", + valueType: "none" + }, + isFalse: { + type: ["boolean"], + fn: (v3, f4) => v3 != "true", + valueType: "none" + } +}; + +// src/utils/contexts/predicate/filter.ts +var stringEqual = (value, filterValue) => { + return value == filterValue; }; -var saveFileColors = (plugin, files, icon) => { - files.forEach((file) => { - saveFileColor(plugin, file, icon); - }); +var empty2 = (value, filterValue) => { + return (value != null ? value : "").length == 0; }; -var saveSpaceIcon = (plugin, space, icon) => { - saveSpaceSticker(plugin, space, icon); +var stringCompare = (value, filterValue) => { + return (value != null ? value : "").toLowerCase().includes((filterValue != null ? filterValue : "").toLowerCase()); }; -var removeSpaceIcon = (plugin, space) => { - saveSpaceSticker(plugin, space, ""); +var greaterThan = (value, filterValue) => { + return parseFloat(value) > parseFloat(filterValue); }; -var saveFileIcon = (plugin, data, icon) => { - saveFileSticker(plugin, data.path, icon); +var lessThan = (value, filterValue) => { + return parseInt(value) > parseInt(filterValue); }; -var removeFileIcons = (plugin, files) => { - files.forEach((file) => { - saveFileSticker(plugin, file, ""); - }); +var listIncludes = (value, filterValue) => { + const valueList = value ? parseMultiString(value) : []; + const strings = filterValue ? parseMultiString(filterValue) : []; + return strings.some((f4) => valueList.some((g4) => g4 == f4)); }; -var removeFileIcon = (plugin, data) => { - saveFileSticker(plugin, data.path, ""); +var isSameDayAsToday = (value) => { + const inputDate = new Date(`${value}T00:00`); + const currentDate = new Date(); + return inputDate.getMonth() === currentDate.getMonth() && inputDate.getDate() === currentDate.getDate(); }; - -// src/utils/sticker.ts -var import_obsidian11 = require("obsidian"); -var stickerFromString = (sticker, plugin) => { - var _a2; - const [type, value] = parseStickerString(sticker); - if (type == "" || type == "emoji") { - return emojiFromString(value); - } else if (type == "ui") { - return uiIconSet[value]; - } else if (type == "lucide") { - return (_a2 = (0, import_obsidian11.getIcon)(value)) == null ? void 0 : _a2.outerHTML; - } else { - return plugin.index.iconsCache.get(value); +var filterReturnForCol = (col, filter, row) => { + if (!col) + return true; + const filterType = filterFnTypes[filter == null ? void 0 : filter.fn]; + let result = true; + if (filterType && filterType.fn) { + result = filterType.fn(row[filter.field], filter.value); } + return result; }; -// src/components/FileSticker/FileSticker.tsx -var FileSticker = (props2) => { - var _a2; - const { fileCache } = props2; - const triggerStickerContextMenu = (e4) => { - if (!fileCache) - return; - e4.preventDefault(); - const fileMenu = new import_obsidian12.Menu(); - fileMenu.addSeparator(); - fileMenu.addItem((menuItem) => { - menuItem.setTitle(i18n_default.buttons.changeIcon); - menuItem.setIcon("lucide-sticker"); - menuItem.onClick((ev) => { - let vaultChangeModal = new stickerModal( - props2.plugin.app, - props2.plugin, - (emoji) => saveFileSticker(props2.plugin, fileCache == null ? void 0 : fileCache.path, emoji) - ); - vaultChangeModal.open(); - }); - }); - fileMenu.addItem((menuItem) => { - menuItem.setTitle(i18n_default.buttons.removeIcon); - menuItem.setIcon("lucide-file-minus"); - menuItem.onClick((ev) => { - removeFileIcons(props2.plugin, [fileCache.path]); - }); - }); - if (isMouseEvent(e4)) { - fileMenu.showAtPosition({ x: e4.pageX, y: e4.pageY }); - } else { - fileMenu.showAtPosition({ - x: e4.nativeEvent.locationX, - y: e4.nativeEvent.locationY - }); - } - return false; - }; - const triggerStickerMenu = (e4) => { - e4.stopPropagation(); - const vaultChangeModal = new stickerModal( - props2.plugin.app, - props2.plugin, - (emoji) => saveFileSticker(props2.plugin, fileCache.path, emoji) - ); - vaultChangeModal.open(); - }; - return /* @__PURE__ */ Cn.createElement("div", { - className: `mk-file-icon ${(fileCache == null ? void 0 : fileCache.sticker) ? "" : "mk-file-icon-placeholder"}` - }, /* @__PURE__ */ Cn.createElement("button", { - "aria-label": i18n_default.buttons.changeIcon, - onContextMenu: triggerStickerContextMenu, - style: ((_a2 = fileCache == null ? void 0 : fileCache.color) == null ? void 0 : _a2.length) > 0 ? { - "--label-color": `${fileCache.color}`, - "--icon-color": `#ffffff` - } : { - "--icon-color": `var(--text-muted)` - }, - dangerouslySetInnerHTML: (fileCache == null ? void 0 : fileCache.sticker) ? { __html: stickerFromString(fileCache.sticker, props2.plugin) } : { - __html: defaultIconForExtension( - fileCache == null ? void 0 : fileCache.extension, - (fileCache == null ? void 0 : fileCache.color) ? true : false - ) - }, - onClick: (e4) => triggerStickerMenu(e4) - })); -}; +// node_modules/date-fns/esm/_lib/toInteger/index.js +function toInteger(dirtyNumber) { + if (dirtyNumber === null || dirtyNumber === true || dirtyNumber === false) { + return NaN; + } + var number = Number(dirtyNumber); + if (isNaN(number)) { + return number; + } + return number < 0 ? Math.ceil(number) : Math.floor(number); +} -// src/components/ui/menus/newPropertyMenu.tsx -var import_obsidian15 = require("obsidian"); +// node_modules/date-fns/esm/_lib/requiredArgs/index.js +function requiredArgs(required, args) { + if (args.length < required) { + throw new TypeError(required + " argument" + (required > 1 ? "s" : "") + " required, but only " + args.length + " present"); + } +} -// node_modules/@dnd-kit/utilities/dist/utilities.esm.js -function useCombinedRefs() { - for (var _len = arguments.length, refs = new Array(_len), _key = 0; _key < _len; _key++) { - refs[_key] = arguments[_key]; +// node_modules/date-fns/esm/toDate/index.js +function _typeof(obj) { + "@babel/helpers - typeof"; + if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { + _typeof = function _typeof5(obj2) { + return typeof obj2; + }; + } else { + _typeof = function _typeof5(obj2) { + return obj2 && typeof Symbol === "function" && obj2.constructor === Symbol && obj2 !== Symbol.prototype ? "symbol" : typeof obj2; + }; } - return F2( - () => (node) => { - refs.forEach((ref) => ref(node)); - }, - refs - ); + return _typeof(obj); } -var canUseDOM = typeof window !== "undefined" && typeof window.document !== "undefined" && typeof window.document.createElement !== "undefined"; -function isWindow(element) { - const elementString = Object.prototype.toString.call(element); - return elementString === "[object Window]" || elementString === "[object global]"; +function toDate(argument) { + requiredArgs(1, arguments); + var argStr = Object.prototype.toString.call(argument); + if (argument instanceof Date || _typeof(argument) === "object" && argStr === "[object Date]") { + return new Date(argument.getTime()); + } else if (typeof argument === "number" || argStr === "[object Number]") { + return new Date(argument); + } else { + if ((typeof argument === "string" || argStr === "[object String]") && typeof console !== "undefined") { + console.warn("Starting with v2.0.0-beta.1 date-fns doesn't accept strings as date arguments. Please use `parseISO` to parse strings. See: https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#string-arguments"); + console.warn(new Error().stack); + } + return new Date(NaN); + } } -function isNode(node) { - return "nodeType" in node; + +// node_modules/date-fns/esm/addDays/index.js +function addDays(dirtyDate, dirtyAmount) { + requiredArgs(2, arguments); + var date = toDate(dirtyDate); + var amount = toInteger(dirtyAmount); + if (isNaN(amount)) { + return new Date(NaN); + } + if (!amount) { + return date; + } + date.setDate(date.getDate() + amount); + return date; } -function getWindow(target) { - var _target$ownerDocument, _target$ownerDocument2; - if (!target) { - return window; + +// node_modules/date-fns/esm/addMonths/index.js +function addMonths(dirtyDate, dirtyAmount) { + requiredArgs(2, arguments); + var date = toDate(dirtyDate); + var amount = toInteger(dirtyAmount); + if (isNaN(amount)) { + return new Date(NaN); } - if (isWindow(target)) { - return target; + if (!amount) { + return date; } - if (!isNode(target)) { - return window; + var dayOfMonth = date.getDate(); + var endOfDesiredMonth = new Date(date.getTime()); + endOfDesiredMonth.setMonth(date.getMonth() + amount + 1, 0); + var daysInMonth = endOfDesiredMonth.getDate(); + if (dayOfMonth >= daysInMonth) { + return endOfDesiredMonth; + } else { + date.setFullYear(endOfDesiredMonth.getFullYear(), endOfDesiredMonth.getMonth(), dayOfMonth); + return date; } - return (_target$ownerDocument = (_target$ownerDocument2 = target.ownerDocument) == null ? void 0 : _target$ownerDocument2.defaultView) != null ? _target$ownerDocument : window; } -function isDocument(node) { - const { - Document - } = getWindow(node); - return node instanceof Document; + +// node_modules/date-fns/esm/addMilliseconds/index.js +function addMilliseconds(dirtyDate, dirtyAmount) { + requiredArgs(2, arguments); + var timestamp = toDate(dirtyDate).getTime(); + var amount = toInteger(dirtyAmount); + return new Date(timestamp + amount); } -function isHTMLElement(node) { - if (isWindow(node)) { - return false; + +// node_modules/date-fns/esm/_lib/defaultOptions/index.js +var defaultOptions3 = {}; +function getDefaultOptions() { + return defaultOptions3; +} + +// node_modules/date-fns/esm/startOfWeek/index.js +function startOfWeek(dirtyDate, options) { + var _ref, _ref2, _ref3, _options$weekStartsOn, _options$locale, _options$locale$optio, _defaultOptions$local, _defaultOptions$local2; + requiredArgs(1, arguments); + var defaultOptions4 = getDefaultOptions(); + var weekStartsOn = toInteger((_ref = (_ref2 = (_ref3 = (_options$weekStartsOn = options === null || options === void 0 ? void 0 : options.weekStartsOn) !== null && _options$weekStartsOn !== void 0 ? _options$weekStartsOn : options === null || options === void 0 ? void 0 : (_options$locale = options.locale) === null || _options$locale === void 0 ? void 0 : (_options$locale$optio = _options$locale.options) === null || _options$locale$optio === void 0 ? void 0 : _options$locale$optio.weekStartsOn) !== null && _ref3 !== void 0 ? _ref3 : defaultOptions4.weekStartsOn) !== null && _ref2 !== void 0 ? _ref2 : (_defaultOptions$local = defaultOptions4.locale) === null || _defaultOptions$local === void 0 ? void 0 : (_defaultOptions$local2 = _defaultOptions$local.options) === null || _defaultOptions$local2 === void 0 ? void 0 : _defaultOptions$local2.weekStartsOn) !== null && _ref !== void 0 ? _ref : 0); + if (!(weekStartsOn >= 0 && weekStartsOn <= 6)) { + throw new RangeError("weekStartsOn must be between 0 and 6 inclusively"); } - return node instanceof getWindow(node).HTMLElement; + var date = toDate(dirtyDate); + var day = date.getDay(); + var diff = (day < weekStartsOn ? 7 : 0) + day - weekStartsOn; + date.setDate(date.getDate() - diff); + date.setHours(0, 0, 0, 0); + return date; } -function isSVGElement(node) { - return node instanceof getWindow(node).SVGElement; + +// node_modules/date-fns/esm/startOfISOWeek/index.js +function startOfISOWeek(dirtyDate) { + requiredArgs(1, arguments); + return startOfWeek(dirtyDate, { + weekStartsOn: 1 + }); } -function getOwnerDocument(target) { - if (!target) { - return document; - } - if (isWindow(target)) { - return target.document; - } - if (!isNode(target)) { - return document; - } - if (isDocument(target)) { - return target; - } - if (isHTMLElement(target)) { - return target.ownerDocument; + +// node_modules/date-fns/esm/getISOWeekYear/index.js +function getISOWeekYear(dirtyDate) { + requiredArgs(1, arguments); + var date = toDate(dirtyDate); + var year = date.getFullYear(); + var fourthOfJanuaryOfNextYear = new Date(0); + fourthOfJanuaryOfNextYear.setFullYear(year + 1, 0, 4); + fourthOfJanuaryOfNextYear.setHours(0, 0, 0, 0); + var startOfNextYear = startOfISOWeek(fourthOfJanuaryOfNextYear); + var fourthOfJanuaryOfThisYear = new Date(0); + fourthOfJanuaryOfThisYear.setFullYear(year, 0, 4); + fourthOfJanuaryOfThisYear.setHours(0, 0, 0, 0); + var startOfThisYear = startOfISOWeek(fourthOfJanuaryOfThisYear); + if (date.getTime() >= startOfNextYear.getTime()) { + return year + 1; + } else if (date.getTime() >= startOfThisYear.getTime()) { + return year; + } else { + return year - 1; } - return document; } -var useIsomorphicLayoutEffect = canUseDOM ? y2 : p2; -function useEvent(handler) { - const handlerRef = _2(handler); - useIsomorphicLayoutEffect(() => { - handlerRef.current = handler; - }); - return T2(function() { - for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { - args[_key] = arguments[_key]; - } - return handlerRef.current == null ? void 0 : handlerRef.current(...args); - }, []); + +// node_modules/date-fns/esm/startOfISOWeekYear/index.js +function startOfISOWeekYear(dirtyDate) { + requiredArgs(1, arguments); + var year = getISOWeekYear(dirtyDate); + var fourthOfJanuary = new Date(0); + fourthOfJanuary.setFullYear(year, 0, 4); + fourthOfJanuary.setHours(0, 0, 0, 0); + var date = startOfISOWeek(fourthOfJanuary); + return date; } -function useInterval() { - const intervalRef = _2(null); - const set = T2((listener, duration) => { - intervalRef.current = setInterval(listener, duration); - }, []); - const clear = T2(() => { - if (intervalRef.current !== null) { - clearInterval(intervalRef.current); - intervalRef.current = null; - } - }, []); - return [set, clear]; + +// node_modules/date-fns/esm/_lib/getTimezoneOffsetInMilliseconds/index.js +function getTimezoneOffsetInMilliseconds(date) { + var utcDate = new Date(Date.UTC(date.getFullYear(), date.getMonth(), date.getDate(), date.getHours(), date.getMinutes(), date.getSeconds(), date.getMilliseconds())); + utcDate.setUTCFullYear(date.getFullYear()); + return date.getTime() - utcDate.getTime(); } -function useLatestValue(value, dependencies) { - if (dependencies === void 0) { - dependencies = [value]; - } - const valueRef = _2(value); - useIsomorphicLayoutEffect(() => { - if (valueRef.current !== value) { - valueRef.current = value; - } - }, dependencies); - return valueRef; + +// node_modules/date-fns/esm/startOfDay/index.js +function startOfDay(dirtyDate) { + requiredArgs(1, arguments); + var date = toDate(dirtyDate); + date.setHours(0, 0, 0, 0); + return date; } -function useLazyMemo(callback, dependencies) { - const valueRef = _2(); - return F2( - () => { - const newValue = callback(valueRef.current); - valueRef.current = newValue; - return newValue; - }, - [...dependencies] - ); + +// node_modules/date-fns/esm/differenceInCalendarDays/index.js +var MILLISECONDS_IN_DAY = 864e5; +function differenceInCalendarDays(dirtyDateLeft, dirtyDateRight) { + requiredArgs(2, arguments); + var startOfDayLeft = startOfDay(dirtyDateLeft); + var startOfDayRight = startOfDay(dirtyDateRight); + var timestampLeft = startOfDayLeft.getTime() - getTimezoneOffsetInMilliseconds(startOfDayLeft); + var timestampRight = startOfDayRight.getTime() - getTimezoneOffsetInMilliseconds(startOfDayRight); + return Math.round((timestampLeft - timestampRight) / MILLISECONDS_IN_DAY); } -function useNodeRef(onChange) { - const onChangeHandler = useEvent(onChange); - const node = _2(null); - const setNodeRef = T2( - (element) => { - if (element !== node.current) { - onChangeHandler == null ? void 0 : onChangeHandler(element, node.current); - } - node.current = element; - }, - [] - ); - return [node, setNodeRef]; + +// node_modules/date-fns/esm/addWeeks/index.js +function addWeeks(dirtyDate, dirtyAmount) { + requiredArgs(2, arguments); + var amount = toInteger(dirtyAmount); + var days = amount * 7; + return addDays(dirtyDate, days); } -function usePrevious(value) { - const ref = _2(); - p2(() => { - ref.current = value; - }, [value]); - return ref.current; + +// node_modules/date-fns/esm/addYears/index.js +function addYears(dirtyDate, dirtyAmount) { + requiredArgs(2, arguments); + var amount = toInteger(dirtyAmount); + return addMonths(dirtyDate, amount * 12); } -var ids = {}; -function useUniqueId(prefix, value) { - return F2(() => { - if (value) { - return value; + +// node_modules/date-fns/esm/max/index.js +function _typeof2(obj) { + "@babel/helpers - typeof"; + if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { + _typeof2 = function _typeof5(obj2) { + return typeof obj2; + }; + } else { + _typeof2 = function _typeof5(obj2) { + return obj2 && typeof Symbol === "function" && obj2.constructor === Symbol && obj2 !== Symbol.prototype ? "symbol" : typeof obj2; + }; + } + return _typeof2(obj); +} +function max(dirtyDatesArray) { + requiredArgs(1, arguments); + var datesArray; + if (dirtyDatesArray && typeof dirtyDatesArray.forEach === "function") { + datesArray = dirtyDatesArray; + } else if (_typeof2(dirtyDatesArray) === "object" && dirtyDatesArray !== null) { + datesArray = Array.prototype.slice.call(dirtyDatesArray); + } else { + return new Date(NaN); + } + var result; + datesArray.forEach(function(dirtyDate) { + var currentDate = toDate(dirtyDate); + if (result === void 0 || result < currentDate || isNaN(Number(currentDate))) { + result = currentDate; } - const id2 = ids[prefix] == null ? 0 : ids[prefix] + 1; - ids[prefix] = id2; - return prefix + "-" + id2; - }, [prefix, value]); + }); + return result || new Date(NaN); } -function createAdjustmentFn(modifier) { - return function(object) { - for (var _len = arguments.length, adjustments = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { - adjustments[_key - 1] = arguments[_key]; + +// node_modules/date-fns/esm/min/index.js +function _typeof3(obj) { + "@babel/helpers - typeof"; + if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { + _typeof3 = function _typeof5(obj2) { + return typeof obj2; + }; + } else { + _typeof3 = function _typeof5(obj2) { + return obj2 && typeof Symbol === "function" && obj2.constructor === Symbol && obj2 !== Symbol.prototype ? "symbol" : typeof obj2; + }; + } + return _typeof3(obj); +} +function min(dirtyDatesArray) { + requiredArgs(1, arguments); + var datesArray; + if (dirtyDatesArray && typeof dirtyDatesArray.forEach === "function") { + datesArray = dirtyDatesArray; + } else if (_typeof3(dirtyDatesArray) === "object" && dirtyDatesArray !== null) { + datesArray = Array.prototype.slice.call(dirtyDatesArray); + } else { + return new Date(NaN); + } + var result; + datesArray.forEach(function(dirtyDate) { + var currentDate = toDate(dirtyDate); + if (result === void 0 || result > currentDate || isNaN(currentDate.getDate())) { + result = currentDate; } - return adjustments.reduce((accumulator, adjustment) => { - const entries = Object.entries(adjustment); - for (const [key2, valueAdjustment] of entries) { - const value = accumulator[key2]; - if (value != null) { - accumulator[key2] = value + modifier * valueAdjustment; - } - } - return accumulator; - }, { - ...object - }); - }; + }); + return result || new Date(NaN); +} + +// node_modules/date-fns/esm/compareAsc/index.js +function compareAsc(dirtyDateLeft, dirtyDateRight) { + requiredArgs(2, arguments); + var dateLeft = toDate(dirtyDateLeft); + var dateRight = toDate(dirtyDateRight); + var diff = dateLeft.getTime() - dateRight.getTime(); + if (diff < 0) { + return -1; + } else if (diff > 0) { + return 1; + } else { + return diff; + } } -var add = /* @__PURE__ */ createAdjustmentFn(1); -var subtract = /* @__PURE__ */ createAdjustmentFn(-1); -function hasViewportRelativeCoordinates(event) { - return "clientX" in event && "clientY" in event; + +// node_modules/date-fns/esm/isSameDay/index.js +function isSameDay(dirtyDateLeft, dirtyDateRight) { + requiredArgs(2, arguments); + var dateLeftStartOfDay = startOfDay(dirtyDateLeft); + var dateRightStartOfDay = startOfDay(dirtyDateRight); + return dateLeftStartOfDay.getTime() === dateRightStartOfDay.getTime(); } -function isKeyboardEvent(event) { - if (!event) { - return false; + +// node_modules/date-fns/esm/isDate/index.js +function _typeof4(obj) { + "@babel/helpers - typeof"; + if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { + _typeof4 = function _typeof5(obj2) { + return typeof obj2; + }; + } else { + _typeof4 = function _typeof5(obj2) { + return obj2 && typeof Symbol === "function" && obj2.constructor === Symbol && obj2 !== Symbol.prototype ? "symbol" : typeof obj2; + }; } - const { - KeyboardEvent - } = getWindow(event.target); - return KeyboardEvent && event instanceof KeyboardEvent; + return _typeof4(obj); } -function isTouchEvent(event) { - if (!event) { +function isDate(value) { + requiredArgs(1, arguments); + return value instanceof Date || _typeof4(value) === "object" && Object.prototype.toString.call(value) === "[object Date]"; +} + +// node_modules/date-fns/esm/isValid/index.js +function isValid(dirtyDate) { + requiredArgs(1, arguments); + if (!isDate(dirtyDate) && typeof dirtyDate !== "number") { return false; } - const { - TouchEvent - } = getWindow(event.target); - return TouchEvent && event instanceof TouchEvent; + var date = toDate(dirtyDate); + return !isNaN(Number(date)); } -function getEventCoordinates(event) { - if (isTouchEvent(event)) { - if (event.touches && event.touches.length) { - const { - clientX: x5, - clientY: y5 - } = event.touches[0]; - return { - x: x5, - y: y5 - }; - } else if (event.changedTouches && event.changedTouches.length) { - const { - clientX: x5, - clientY: y5 - } = event.changedTouches[0]; - return { - x: x5, - y: y5 - }; - } - } - if (hasViewportRelativeCoordinates(event)) { - return { - x: event.clientX, - y: event.clientY - }; - } - return null; + +// node_modules/date-fns/esm/differenceInCalendarMonths/index.js +function differenceInCalendarMonths(dirtyDateLeft, dirtyDateRight) { + requiredArgs(2, arguments); + var dateLeft = toDate(dirtyDateLeft); + var dateRight = toDate(dirtyDateRight); + var yearDiff = dateLeft.getFullYear() - dateRight.getFullYear(); + var monthDiff = dateLeft.getMonth() - dateRight.getMonth(); + return yearDiff * 12 + monthDiff; } -var CSS = /* @__PURE__ */ Object.freeze({ - Translate: { - toString(transform) { - if (!transform) { - return; - } - const { - x: x5, - y: y5 - } = transform; - return "translate3d(" + (x5 ? Math.round(x5) : 0) + "px, " + (y5 ? Math.round(y5) : 0) + "px, 0)"; - } - }, - Scale: { - toString(transform) { - if (!transform) { - return; - } - const { - scaleX, - scaleY - } = transform; - return "scaleX(" + scaleX + ") scaleY(" + scaleY + ")"; - } - }, - Transform: { - toString(transform) { - if (!transform) { - return; - } - return [CSS.Translate.toString(transform), CSS.Scale.toString(transform)].join(" "); - } - }, - Transition: { - toString(_ref) { - let { - property, - duration, - easing - } = _ref; - return property + " " + duration + "ms " + easing; - } - } -}); -var SELECTOR = "a,frame,iframe,input:not([type=hidden]):not(:disabled),select:not(:disabled),textarea:not(:disabled),button:not(:disabled),*[tabindex]"; -function findFirstFocusableNode(element) { - if (element.matches(SELECTOR)) { - return element; - } - return element.querySelector(SELECTOR); + +// node_modules/date-fns/esm/differenceInCalendarWeeks/index.js +var MILLISECONDS_IN_WEEK = 6048e5; +function differenceInCalendarWeeks(dirtyDateLeft, dirtyDateRight, options) { + requiredArgs(2, arguments); + var startOfWeekLeft = startOfWeek(dirtyDateLeft, options); + var startOfWeekRight = startOfWeek(dirtyDateRight, options); + var timestampLeft = startOfWeekLeft.getTime() - getTimezoneOffsetInMilliseconds(startOfWeekLeft); + var timestampRight = startOfWeekRight.getTime() - getTimezoneOffsetInMilliseconds(startOfWeekRight); + return Math.round((timestampLeft - timestampRight) / MILLISECONDS_IN_WEEK); } -// node_modules/@dnd-kit/accessibility/dist/accessibility.esm.js -var hiddenStyles = { - display: "none" -}; -function HiddenText(_ref) { - let { - id: id2, - value - } = _ref; - return Cn.createElement("div", { - id: id2, - style: hiddenStyles - }, value); +// node_modules/date-fns/esm/differenceInMilliseconds/index.js +function differenceInMilliseconds(dateLeft, dateRight) { + requiredArgs(2, arguments); + return toDate(dateLeft).getTime() - toDate(dateRight).getTime(); } -var visuallyHidden = { - position: "fixed", - width: 1, - height: 1, - margin: -1, - border: 0, - padding: 0, - overflow: "hidden", - clip: "rect(0 0 0 0)", - clipPath: "inset(100%)", - whiteSpace: "nowrap" + +// node_modules/date-fns/esm/_lib/roundingMethods/index.js +var roundingMap = { + ceil: Math.ceil, + round: Math.round, + floor: Math.floor, + trunc: function trunc(value) { + return value < 0 ? Math.ceil(value) : Math.floor(value); + } }; -function LiveRegion(_ref) { - let { - id: id2, - announcement - } = _ref; - return Cn.createElement("div", { - id: id2, - style: visuallyHidden, - role: "status", - "aria-live": "assertive", - "aria-atomic": true - }, announcement); +var defaultRoundingMethod = "trunc"; +function getRoundingMethod(method) { + return method ? roundingMap[method] : roundingMap[defaultRoundingMethod]; } -function useAnnouncement() { - const [announcement, setAnnouncement] = h2(""); - const announce = T2((value) => { - if (value != null) { - setAnnouncement(value); - } - }, []); - return { - announce, - announcement - }; + +// node_modules/date-fns/esm/endOfDay/index.js +function endOfDay(dirtyDate) { + requiredArgs(1, arguments); + var date = toDate(dirtyDate); + date.setHours(23, 59, 59, 999); + return date; } -// node_modules/@dnd-kit/core/dist/core.esm.js -var DndMonitorContext = /* @__PURE__ */ F(null); -function useDndMonitor(listener) { - const registerListener = q2(DndMonitorContext); - p2(() => { - if (!registerListener) { - throw new Error("useDndMonitor must be used within a children of "); - } - const unsubscribe = registerListener(listener); - return unsubscribe; - }, [listener, registerListener]); +// node_modules/date-fns/esm/endOfMonth/index.js +function endOfMonth(dirtyDate) { + requiredArgs(1, arguments); + var date = toDate(dirtyDate); + var month = date.getMonth(); + date.setFullYear(date.getFullYear(), month + 1, 0); + date.setHours(23, 59, 59, 999); + return date; } -function useDndMonitorProvider() { - const [listeners] = h2(() => /* @__PURE__ */ new Set()); - const registerListener = T2((listener) => { - listeners.add(listener); - return () => listeners.delete(listener); - }, [listeners]); - const dispatch = T2((_ref) => { - let { - type, - event - } = _ref; - listeners.forEach((listener) => { - var _listener$type; - return (_listener$type = listener[type]) == null ? void 0 : _listener$type.call(listener, event); - }); - }, [listeners]); - return [dispatch, registerListener]; + +// node_modules/date-fns/esm/isLastDayOfMonth/index.js +function isLastDayOfMonth(dirtyDate) { + requiredArgs(1, arguments); + var date = toDate(dirtyDate); + return endOfDay(date).getTime() === endOfMonth(date).getTime(); } -var defaultScreenReaderInstructions = { - draggable: "\n To pick up a draggable item, press the space bar.\n While dragging, use the arrow keys to move the item.\n Press space again to drop the item in its new position, or press escape to cancel.\n " -}; -var defaultAnnouncements = { - onDragStart(_ref) { - let { - active - } = _ref; - return "Picked up draggable item " + active.id + "."; - }, - onDragOver(_ref2) { - let { - active, - over - } = _ref2; - if (over) { - return "Draggable item " + active.id + " was moved over droppable area " + over.id + "."; + +// node_modules/date-fns/esm/differenceInMonths/index.js +function differenceInMonths(dirtyDateLeft, dirtyDateRight) { + requiredArgs(2, arguments); + var dateLeft = toDate(dirtyDateLeft); + var dateRight = toDate(dirtyDateRight); + var sign = compareAsc(dateLeft, dateRight); + var difference = Math.abs(differenceInCalendarMonths(dateLeft, dateRight)); + var result; + if (difference < 1) { + result = 0; + } else { + if (dateLeft.getMonth() === 1 && dateLeft.getDate() > 27) { + dateLeft.setDate(30); } - return "Draggable item " + active.id + " is no longer over a droppable area."; - }, - onDragEnd(_ref3) { - let { - active, - over - } = _ref3; - if (over) { - return "Draggable item " + active.id + " was dropped over droppable area " + over.id; + dateLeft.setMonth(dateLeft.getMonth() - sign * difference); + var isLastMonthNotFull = compareAsc(dateLeft, dateRight) === -sign; + if (isLastDayOfMonth(toDate(dirtyDateLeft)) && difference === 1 && compareAsc(dirtyDateLeft, dateRight) === 1) { + isLastMonthNotFull = false; } - return "Draggable item " + active.id + " was dropped."; - }, - onDragCancel(_ref4) { - let { - active - } = _ref4; - return "Dragging was cancelled. Draggable item " + active.id + " was dropped."; + result = sign * (difference - Number(isLastMonthNotFull)); } -}; -function Accessibility(_ref) { - let { - announcements = defaultAnnouncements, - container, - hiddenTextDescribedById, - screenReaderInstructions = defaultScreenReaderInstructions - } = _ref; - const { - announce, - announcement - } = useAnnouncement(); - const liveRegionId = useUniqueId("DndLiveRegion"); - const [mounted, setMounted] = h2(false); - p2(() => { - setMounted(true); - }, []); - useDndMonitor(F2(() => ({ - onDragStart(_ref2) { - let { - active - } = _ref2; - announce(announcements.onDragStart({ - active - })); - }, - onDragMove(_ref3) { - let { - active, - over - } = _ref3; - if (announcements.onDragMove) { - announce(announcements.onDragMove({ - active, - over - })); - } - }, - onDragOver(_ref4) { - let { - active, - over - } = _ref4; - announce(announcements.onDragOver({ - active, - over - })); - }, - onDragEnd(_ref5) { - let { - active, - over - } = _ref5; - announce(announcements.onDragEnd({ - active, - over - })); - }, - onDragCancel(_ref6) { - let { - active, - over - } = _ref6; - announce(announcements.onDragCancel({ - active, - over - })); - } - }), [announce, announcements])); - if (!mounted) { - return null; + return result === 0 ? 0 : result; +} + +// node_modules/date-fns/esm/differenceInSeconds/index.js +function differenceInSeconds(dateLeft, dateRight, options) { + requiredArgs(2, arguments); + var diff = differenceInMilliseconds(dateLeft, dateRight) / 1e3; + return getRoundingMethod(options === null || options === void 0 ? void 0 : options.roundingMethod)(diff); +} + +// node_modules/date-fns/esm/startOfMonth/index.js +function startOfMonth(dirtyDate) { + requiredArgs(1, arguments); + var date = toDate(dirtyDate); + date.setDate(1); + date.setHours(0, 0, 0, 0); + return date; +} + +// node_modules/date-fns/esm/startOfYear/index.js +function startOfYear(dirtyDate) { + requiredArgs(1, arguments); + var cleanDate = toDate(dirtyDate); + var date = new Date(0); + date.setFullYear(cleanDate.getFullYear(), 0, 1); + date.setHours(0, 0, 0, 0); + return date; +} + +// node_modules/date-fns/esm/endOfWeek/index.js +function endOfWeek(dirtyDate, options) { + var _ref, _ref2, _ref3, _options$weekStartsOn, _options$locale, _options$locale$optio, _defaultOptions$local, _defaultOptions$local2; + requiredArgs(1, arguments); + var defaultOptions4 = getDefaultOptions(); + var weekStartsOn = toInteger((_ref = (_ref2 = (_ref3 = (_options$weekStartsOn = options === null || options === void 0 ? void 0 : options.weekStartsOn) !== null && _options$weekStartsOn !== void 0 ? _options$weekStartsOn : options === null || options === void 0 ? void 0 : (_options$locale = options.locale) === null || _options$locale === void 0 ? void 0 : (_options$locale$optio = _options$locale.options) === null || _options$locale$optio === void 0 ? void 0 : _options$locale$optio.weekStartsOn) !== null && _ref3 !== void 0 ? _ref3 : defaultOptions4.weekStartsOn) !== null && _ref2 !== void 0 ? _ref2 : (_defaultOptions$local = defaultOptions4.locale) === null || _defaultOptions$local === void 0 ? void 0 : (_defaultOptions$local2 = _defaultOptions$local.options) === null || _defaultOptions$local2 === void 0 ? void 0 : _defaultOptions$local2.weekStartsOn) !== null && _ref !== void 0 ? _ref : 0); + if (!(weekStartsOn >= 0 && weekStartsOn <= 6)) { + throw new RangeError("weekStartsOn must be between 0 and 6 inclusively"); } - const markup = Cn.createElement(Cn.Fragment, null, Cn.createElement(HiddenText, { - id: hiddenTextDescribedById, - value: screenReaderInstructions.draggable - }), Cn.createElement(LiveRegion, { - id: liveRegionId, - announcement - })); - return container ? z3(markup, container) : markup; + var date = toDate(dirtyDate); + var day = date.getDay(); + var diff = (day < weekStartsOn ? -7 : 0) + 6 - (day - weekStartsOn); + date.setDate(date.getDate() + diff); + date.setHours(23, 59, 59, 999); + return date; } -var Action; -(function(Action2) { - Action2["DragStart"] = "dragStart"; - Action2["DragMove"] = "dragMove"; - Action2["DragEnd"] = "dragEnd"; - Action2["DragCancel"] = "dragCancel"; - Action2["DragOver"] = "dragOver"; - Action2["RegisterDroppable"] = "registerDroppable"; - Action2["SetDroppableDisabled"] = "setDroppableDisabled"; - Action2["UnregisterDroppable"] = "unregisterDroppable"; -})(Action || (Action = {})); -function noop() { + +// node_modules/date-fns/esm/endOfISOWeek/index.js +function endOfISOWeek(dirtyDate) { + requiredArgs(1, arguments); + return endOfWeek(dirtyDate, { + weekStartsOn: 1 + }); } -function useSensor(sensor, options) { - return F2( - () => ({ - sensor, - options: options != null ? options : {} - }), - [sensor, options] - ); + +// node_modules/date-fns/esm/subMilliseconds/index.js +function subMilliseconds(dirtyDate, dirtyAmount) { + requiredArgs(2, arguments); + var amount = toInteger(dirtyAmount); + return addMilliseconds(dirtyDate, -amount); } -function useSensors() { - for (var _len = arguments.length, sensors = new Array(_len), _key = 0; _key < _len; _key++) { - sensors[_key] = arguments[_key]; + +// node_modules/date-fns/esm/_lib/getUTCDayOfYear/index.js +var MILLISECONDS_IN_DAY2 = 864e5; +function getUTCDayOfYear(dirtyDate) { + requiredArgs(1, arguments); + var date = toDate(dirtyDate); + var timestamp = date.getTime(); + date.setUTCMonth(0, 1); + date.setUTCHours(0, 0, 0, 0); + var startOfYearTimestamp = date.getTime(); + var difference = timestamp - startOfYearTimestamp; + return Math.floor(difference / MILLISECONDS_IN_DAY2) + 1; +} + +// node_modules/date-fns/esm/_lib/startOfUTCISOWeek/index.js +function startOfUTCISOWeek(dirtyDate) { + requiredArgs(1, arguments); + var weekStartsOn = 1; + var date = toDate(dirtyDate); + var day = date.getUTCDay(); + var diff = (day < weekStartsOn ? 7 : 0) + day - weekStartsOn; + date.setUTCDate(date.getUTCDate() - diff); + date.setUTCHours(0, 0, 0, 0); + return date; +} + +// node_modules/date-fns/esm/_lib/getUTCISOWeekYear/index.js +function getUTCISOWeekYear(dirtyDate) { + requiredArgs(1, arguments); + var date = toDate(dirtyDate); + var year = date.getUTCFullYear(); + var fourthOfJanuaryOfNextYear = new Date(0); + fourthOfJanuaryOfNextYear.setUTCFullYear(year + 1, 0, 4); + fourthOfJanuaryOfNextYear.setUTCHours(0, 0, 0, 0); + var startOfNextYear = startOfUTCISOWeek(fourthOfJanuaryOfNextYear); + var fourthOfJanuaryOfThisYear = new Date(0); + fourthOfJanuaryOfThisYear.setUTCFullYear(year, 0, 4); + fourthOfJanuaryOfThisYear.setUTCHours(0, 0, 0, 0); + var startOfThisYear = startOfUTCISOWeek(fourthOfJanuaryOfThisYear); + if (date.getTime() >= startOfNextYear.getTime()) { + return year + 1; + } else if (date.getTime() >= startOfThisYear.getTime()) { + return year; + } else { + return year - 1; } - return F2( - () => [...sensors].filter((sensor) => sensor != null), - [...sensors] - ); } -var defaultCoordinates = /* @__PURE__ */ Object.freeze({ - x: 0, - y: 0 -}); -function distanceBetween(p1, p22) { - return Math.sqrt(Math.pow(p1.x - p22.x, 2) + Math.pow(p1.y - p22.y, 2)); + +// node_modules/date-fns/esm/_lib/startOfUTCISOWeekYear/index.js +function startOfUTCISOWeekYear(dirtyDate) { + requiredArgs(1, arguments); + var year = getUTCISOWeekYear(dirtyDate); + var fourthOfJanuary = new Date(0); + fourthOfJanuary.setUTCFullYear(year, 0, 4); + fourthOfJanuary.setUTCHours(0, 0, 0, 0); + var date = startOfUTCISOWeek(fourthOfJanuary); + return date; } -function getRelativeTransformOrigin(event, rect) { - const eventCoordinates = getEventCoordinates(event); - if (!eventCoordinates) { - return "0 0"; - } - const transformOrigin = { - x: (eventCoordinates.x - rect.left) / rect.width * 100, - y: (eventCoordinates.y - rect.top) / rect.height * 100 - }; - return transformOrigin.x + "% " + transformOrigin.y + "%"; + +// node_modules/date-fns/esm/_lib/getUTCISOWeek/index.js +var MILLISECONDS_IN_WEEK2 = 6048e5; +function getUTCISOWeek(dirtyDate) { + requiredArgs(1, arguments); + var date = toDate(dirtyDate); + var diff = startOfUTCISOWeek(date).getTime() - startOfUTCISOWeekYear(date).getTime(); + return Math.round(diff / MILLISECONDS_IN_WEEK2) + 1; } -function sortCollisionsAsc(_ref, _ref2) { - let { - data: { - value: a5 - } - } = _ref; - let { - data: { - value: b4 - } - } = _ref2; - return a5 - b4; + +// node_modules/date-fns/esm/_lib/startOfUTCWeek/index.js +function startOfUTCWeek(dirtyDate, options) { + var _ref, _ref2, _ref3, _options$weekStartsOn, _options$locale, _options$locale$optio, _defaultOptions$local, _defaultOptions$local2; + requiredArgs(1, arguments); + var defaultOptions4 = getDefaultOptions(); + var weekStartsOn = toInteger((_ref = (_ref2 = (_ref3 = (_options$weekStartsOn = options === null || options === void 0 ? void 0 : options.weekStartsOn) !== null && _options$weekStartsOn !== void 0 ? _options$weekStartsOn : options === null || options === void 0 ? void 0 : (_options$locale = options.locale) === null || _options$locale === void 0 ? void 0 : (_options$locale$optio = _options$locale.options) === null || _options$locale$optio === void 0 ? void 0 : _options$locale$optio.weekStartsOn) !== null && _ref3 !== void 0 ? _ref3 : defaultOptions4.weekStartsOn) !== null && _ref2 !== void 0 ? _ref2 : (_defaultOptions$local = defaultOptions4.locale) === null || _defaultOptions$local === void 0 ? void 0 : (_defaultOptions$local2 = _defaultOptions$local.options) === null || _defaultOptions$local2 === void 0 ? void 0 : _defaultOptions$local2.weekStartsOn) !== null && _ref !== void 0 ? _ref : 0); + if (!(weekStartsOn >= 0 && weekStartsOn <= 6)) { + throw new RangeError("weekStartsOn must be between 0 and 6 inclusively"); + } + var date = toDate(dirtyDate); + var day = date.getUTCDay(); + var diff = (day < weekStartsOn ? 7 : 0) + day - weekStartsOn; + date.setUTCDate(date.getUTCDate() - diff); + date.setUTCHours(0, 0, 0, 0); + return date; } -function sortCollisionsDesc(_ref3, _ref4) { - let { - data: { - value: a5 - } - } = _ref3; - let { - data: { - value: b4 - } - } = _ref4; - return b4 - a5; + +// node_modules/date-fns/esm/_lib/getUTCWeekYear/index.js +function getUTCWeekYear(dirtyDate, options) { + var _ref, _ref2, _ref3, _options$firstWeekCon, _options$locale, _options$locale$optio, _defaultOptions$local, _defaultOptions$local2; + requiredArgs(1, arguments); + var date = toDate(dirtyDate); + var year = date.getUTCFullYear(); + var defaultOptions4 = getDefaultOptions(); + var firstWeekContainsDate = toInteger((_ref = (_ref2 = (_ref3 = (_options$firstWeekCon = options === null || options === void 0 ? void 0 : options.firstWeekContainsDate) !== null && _options$firstWeekCon !== void 0 ? _options$firstWeekCon : options === null || options === void 0 ? void 0 : (_options$locale = options.locale) === null || _options$locale === void 0 ? void 0 : (_options$locale$optio = _options$locale.options) === null || _options$locale$optio === void 0 ? void 0 : _options$locale$optio.firstWeekContainsDate) !== null && _ref3 !== void 0 ? _ref3 : defaultOptions4.firstWeekContainsDate) !== null && _ref2 !== void 0 ? _ref2 : (_defaultOptions$local = defaultOptions4.locale) === null || _defaultOptions$local === void 0 ? void 0 : (_defaultOptions$local2 = _defaultOptions$local.options) === null || _defaultOptions$local2 === void 0 ? void 0 : _defaultOptions$local2.firstWeekContainsDate) !== null && _ref !== void 0 ? _ref : 1); + if (!(firstWeekContainsDate >= 1 && firstWeekContainsDate <= 7)) { + throw new RangeError("firstWeekContainsDate must be between 1 and 7 inclusively"); + } + var firstWeekOfNextYear = new Date(0); + firstWeekOfNextYear.setUTCFullYear(year + 1, 0, firstWeekContainsDate); + firstWeekOfNextYear.setUTCHours(0, 0, 0, 0); + var startOfNextYear = startOfUTCWeek(firstWeekOfNextYear, options); + var firstWeekOfThisYear = new Date(0); + firstWeekOfThisYear.setUTCFullYear(year, 0, firstWeekContainsDate); + firstWeekOfThisYear.setUTCHours(0, 0, 0, 0); + var startOfThisYear = startOfUTCWeek(firstWeekOfThisYear, options); + if (date.getTime() >= startOfNextYear.getTime()) { + return year + 1; + } else if (date.getTime() >= startOfThisYear.getTime()) { + return year; + } else { + return year - 1; + } } -function cornersOfRectangle(_ref5) { - let { - left, - top, - height, - width - } = _ref5; - return [{ - x: left, - y: top - }, { - x: left + width, - y: top - }, { - x: left, - y: top + height - }, { - x: left + width, - y: top + height - }]; + +// node_modules/date-fns/esm/_lib/startOfUTCWeekYear/index.js +function startOfUTCWeekYear(dirtyDate, options) { + var _ref, _ref2, _ref3, _options$firstWeekCon, _options$locale, _options$locale$optio, _defaultOptions$local, _defaultOptions$local2; + requiredArgs(1, arguments); + var defaultOptions4 = getDefaultOptions(); + var firstWeekContainsDate = toInteger((_ref = (_ref2 = (_ref3 = (_options$firstWeekCon = options === null || options === void 0 ? void 0 : options.firstWeekContainsDate) !== null && _options$firstWeekCon !== void 0 ? _options$firstWeekCon : options === null || options === void 0 ? void 0 : (_options$locale = options.locale) === null || _options$locale === void 0 ? void 0 : (_options$locale$optio = _options$locale.options) === null || _options$locale$optio === void 0 ? void 0 : _options$locale$optio.firstWeekContainsDate) !== null && _ref3 !== void 0 ? _ref3 : defaultOptions4.firstWeekContainsDate) !== null && _ref2 !== void 0 ? _ref2 : (_defaultOptions$local = defaultOptions4.locale) === null || _defaultOptions$local === void 0 ? void 0 : (_defaultOptions$local2 = _defaultOptions$local.options) === null || _defaultOptions$local2 === void 0 ? void 0 : _defaultOptions$local2.firstWeekContainsDate) !== null && _ref !== void 0 ? _ref : 1); + var year = getUTCWeekYear(dirtyDate, options); + var firstWeek = new Date(0); + firstWeek.setUTCFullYear(year, 0, firstWeekContainsDate); + firstWeek.setUTCHours(0, 0, 0, 0); + var date = startOfUTCWeek(firstWeek, options); + return date; } -function getFirstCollision(collisions, property) { - if (!collisions || collisions.length === 0) { - return null; - } - const [firstCollision] = collisions; - return property ? firstCollision[property] : firstCollision; + +// node_modules/date-fns/esm/_lib/getUTCWeek/index.js +var MILLISECONDS_IN_WEEK3 = 6048e5; +function getUTCWeek(dirtyDate, options) { + requiredArgs(1, arguments); + var date = toDate(dirtyDate); + var diff = startOfUTCWeek(date, options).getTime() - startOfUTCWeekYear(date, options).getTime(); + return Math.round(diff / MILLISECONDS_IN_WEEK3) + 1; } -function centerOfRectangle(rect, left, top) { - if (left === void 0) { - left = rect.left; - } - if (top === void 0) { - top = rect.top; + +// node_modules/date-fns/esm/_lib/addLeadingZeros/index.js +function addLeadingZeros(number, targetLength) { + var sign = number < 0 ? "-" : ""; + var output = Math.abs(number).toString(); + while (output.length < targetLength) { + output = "0" + output; } - return { - x: left + rect.width * 0.5, - y: top + rect.height * 0.5 - }; + return sign + output; } -var closestCenter = (_ref) => { - let { - collisionRect, - droppableRects, - droppableContainers - } = _ref; - const centerRect = centerOfRectangle(collisionRect, collisionRect.left, collisionRect.top); - const collisions = []; - for (const droppableContainer of droppableContainers) { - const { - id: id2 - } = droppableContainer; - const rect = droppableRects.get(id2); - if (rect) { - const distBetween = distanceBetween(centerOfRectangle(rect), centerRect); - collisions.push({ - id: id2, - data: { - droppableContainer, - value: distBetween - } - }); + +// node_modules/date-fns/esm/_lib/format/lightFormatters/index.js +var formatters = { + y: function y3(date, token) { + var signedYear = date.getUTCFullYear(); + var year = signedYear > 0 ? signedYear : 1 - signedYear; + return addLeadingZeros(token === "yy" ? year % 100 : year, token.length); + }, + M: function M3(date, token) { + var month = date.getUTCMonth(); + return token === "M" ? String(month + 1) : addLeadingZeros(month + 1, 2); + }, + d: function d3(date, token) { + return addLeadingZeros(date.getUTCDate(), token.length); + }, + a: function a3(date, token) { + var dayPeriodEnumValue = date.getUTCHours() / 12 >= 1 ? "pm" : "am"; + switch (token) { + case "a": + case "aa": + return dayPeriodEnumValue.toUpperCase(); + case "aaa": + return dayPeriodEnumValue; + case "aaaaa": + return dayPeriodEnumValue[0]; + case "aaaa": + default: + return dayPeriodEnumValue === "am" ? "a.m." : "p.m."; } + }, + h: function h3(date, token) { + return addLeadingZeros(date.getUTCHours() % 12 || 12, token.length); + }, + H: function H3(date, token) { + return addLeadingZeros(date.getUTCHours(), token.length); + }, + m: function m3(date, token) { + return addLeadingZeros(date.getUTCMinutes(), token.length); + }, + s: function s3(date, token) { + return addLeadingZeros(date.getUTCSeconds(), token.length); + }, + S: function S2(date, token) { + var numberOfDigits = token.length; + var milliseconds = date.getUTCMilliseconds(); + var fractionalSeconds = Math.floor(milliseconds * Math.pow(10, numberOfDigits - 3)); + return addLeadingZeros(fractionalSeconds, token.length); } - return collisions.sort(sortCollisionsAsc); }; -var closestCorners = (_ref) => { - let { - collisionRect, - droppableRects, - droppableContainers - } = _ref; - const corners = cornersOfRectangle(collisionRect); - const collisions = []; - for (const droppableContainer of droppableContainers) { - const { - id: id2 - } = droppableContainer; - const rect = droppableRects.get(id2); - if (rect) { - const rectCorners = cornersOfRectangle(rect); - const distances = corners.reduce((accumulator, corner, index) => { - return accumulator + distanceBetween(rectCorners[index], corner); - }, 0); - const effectiveDistance = Number((distances / 4).toFixed(4)); - collisions.push({ - id: id2, - data: { - droppableContainer, - value: effectiveDistance - } - }); - } - } - return collisions.sort(sortCollisionsAsc); +var lightFormatters_default = formatters; + +// node_modules/date-fns/esm/_lib/format/formatters/index.js +var dayPeriodEnum = { + am: "am", + pm: "pm", + midnight: "midnight", + noon: "noon", + morning: "morning", + afternoon: "afternoon", + evening: "evening", + night: "night" }; -function getIntersectionRatio(entry, target) { - const top = Math.max(target.top, entry.top); - const left = Math.max(target.left, entry.left); - const right = Math.min(target.left + target.width, entry.left + entry.width); - const bottom = Math.min(target.top + target.height, entry.top + entry.height); - const width = right - left; - const height = bottom - top; - if (left < right && top < bottom) { - const targetArea = target.width * target.height; - const entryArea = entry.width * entry.height; - const intersectionArea = width * height; - const intersectionRatio = intersectionArea / (targetArea + entryArea - intersectionArea); - return Number(intersectionRatio.toFixed(4)); - } - return 0; -} -var rectIntersection = (_ref) => { - let { - collisionRect, - droppableRects, - droppableContainers - } = _ref; - const collisions = []; - for (const droppableContainer of droppableContainers) { - const { - id: id2 - } = droppableContainer; - const rect = droppableRects.get(id2); - if (rect) { - const intersectionRatio = getIntersectionRatio(rect, collisionRect); - if (intersectionRatio > 0) { - collisions.push({ - id: id2, - data: { - droppableContainer, - value: intersectionRatio - } +var formatters2 = { + G: function G2(date, token, localize2) { + var era = date.getUTCFullYear() > 0 ? 1 : 0; + switch (token) { + case "G": + case "GG": + case "GGG": + return localize2.era(era, { + width: "abbreviated" + }); + case "GGGGG": + return localize2.era(era, { + width: "narrow" + }); + case "GGGG": + default: + return localize2.era(era, { + width: "wide" }); - } } - } - return collisions.sort(sortCollisionsDesc); -}; -function adjustScale(transform, rect1, rect2) { - return { - ...transform, - scaleX: rect1 && rect2 ? rect1.width / rect2.width : 1, - scaleY: rect1 && rect2 ? rect1.height / rect2.height : 1 - }; -} -function getRectDelta(rect1, rect2) { - return rect1 && rect2 ? { - x: rect1.left - rect2.left, - y: rect1.top - rect2.top - } : defaultCoordinates; -} -function createRectAdjustmentFn(modifier) { - return function adjustClientRect(rect) { - for (var _len = arguments.length, adjustments = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { - adjustments[_key - 1] = arguments[_key]; + }, + y: function y4(date, token, localize2) { + if (token === "yo") { + var signedYear = date.getUTCFullYear(); + var year = signedYear > 0 ? signedYear : 1 - signedYear; + return localize2.ordinalNumber(year, { + unit: "year" + }); } - return adjustments.reduce((acc, adjustment) => ({ - ...acc, - top: acc.top + modifier * adjustment.y, - bottom: acc.bottom + modifier * adjustment.y, - left: acc.left + modifier * adjustment.x, - right: acc.right + modifier * adjustment.x - }), { - ...rect - }); - }; -} -var getAdjustedRect = /* @__PURE__ */ createRectAdjustmentFn(1); -function parseTransform(transform) { - if (transform.startsWith("matrix3d(")) { - const transformArray = transform.slice(9, -1).split(/, /); - return { - x: +transformArray[12], - y: +transformArray[13], - scaleX: +transformArray[0], - scaleY: +transformArray[5] - }; - } else if (transform.startsWith("matrix(")) { - const transformArray = transform.slice(7, -1).split(/, /); - return { - x: +transformArray[4], - y: +transformArray[5], - scaleX: +transformArray[0], - scaleY: +transformArray[3] - }; - } - return null; -} -function inverseTransform(rect, transform, transformOrigin) { - const parsedTransform = parseTransform(transform); - if (!parsedTransform) { - return rect; - } - const { - scaleX, - scaleY, - x: translateX, - y: translateY - } = parsedTransform; - const x5 = rect.left - translateX - (1 - scaleX) * parseFloat(transformOrigin); - const y5 = rect.top - translateY - (1 - scaleY) * parseFloat(transformOrigin.slice(transformOrigin.indexOf(" ") + 1)); - const w5 = scaleX ? rect.width / scaleX : rect.width; - const h5 = scaleY ? rect.height / scaleY : rect.height; - return { - width: w5, - height: h5, - top: y5, - right: x5 + w5, - bottom: y5 + h5, - left: x5 - }; -} -var defaultOptions2 = { - ignoreTransform: false -}; -function getClientRect(element, options) { - if (options === void 0) { - options = defaultOptions2; - } - let rect = element.getBoundingClientRect(); - if (options.ignoreTransform) { - const { - transform, - transformOrigin - } = getWindow(element).getComputedStyle(element); - if (transform) { - rect = inverseTransform(rect, transform, transformOrigin); + return lightFormatters_default.y(date, token); + }, + Y: function Y2(date, token, localize2, options) { + var signedWeekYear = getUTCWeekYear(date, options); + var weekYear = signedWeekYear > 0 ? signedWeekYear : 1 - signedWeekYear; + if (token === "YY") { + var twoDigitYear = weekYear % 100; + return addLeadingZeros(twoDigitYear, 2); + } + if (token === "Yo") { + return localize2.ordinalNumber(weekYear, { + unit: "year" + }); + } + return addLeadingZeros(weekYear, token.length); + }, + R: function R2(date, token) { + var isoWeekYear = getUTCISOWeekYear(date); + return addLeadingZeros(isoWeekYear, token.length); + }, + u: function u3(date, token) { + var year = date.getUTCFullYear(); + return addLeadingZeros(year, token.length); + }, + Q: function Q2(date, token, localize2) { + var quarter = Math.ceil((date.getUTCMonth() + 1) / 3); + switch (token) { + case "Q": + return String(quarter); + case "QQ": + return addLeadingZeros(quarter, 2); + case "Qo": + return localize2.ordinalNumber(quarter, { + unit: "quarter" + }); + case "QQQ": + return localize2.quarter(quarter, { + width: "abbreviated", + context: "formatting" + }); + case "QQQQQ": + return localize2.quarter(quarter, { + width: "narrow", + context: "formatting" + }); + case "QQQQ": + default: + return localize2.quarter(quarter, { + width: "wide", + context: "formatting" + }); + } + }, + q: function q4(date, token, localize2) { + var quarter = Math.ceil((date.getUTCMonth() + 1) / 3); + switch (token) { + case "q": + return String(quarter); + case "qq": + return addLeadingZeros(quarter, 2); + case "qo": + return localize2.ordinalNumber(quarter, { + unit: "quarter" + }); + case "qqq": + return localize2.quarter(quarter, { + width: "abbreviated", + context: "standalone" + }); + case "qqqqq": + return localize2.quarter(quarter, { + width: "narrow", + context: "standalone" + }); + case "qqqq": + default: + return localize2.quarter(quarter, { + width: "wide", + context: "standalone" + }); } - } - const { - top, - left, - width, - height, - bottom, - right - } = rect; - return { - top, - left, - width, - height, - bottom, - right - }; -} -function getTransformAgnosticClientRect(element) { - return getClientRect(element, { - ignoreTransform: true - }); -} -function getWindowClientRect(element) { - const width = element.innerWidth; - const height = element.innerHeight; - return { - top: 0, - left: 0, - right: width, - bottom: height, - width, - height - }; -} -function isFixed(node, computedStyle) { - if (computedStyle === void 0) { - computedStyle = getWindow(node).getComputedStyle(node); - } - return computedStyle.position === "fixed"; -} -function isScrollable(element, computedStyle) { - if (computedStyle === void 0) { - computedStyle = getWindow(element).getComputedStyle(element); - } - const overflowRegex = /(auto|scroll|overlay)/; - const properties2 = ["overflow", "overflowX", "overflowY"]; - return properties2.some((property) => { - const value = computedStyle[property]; - return typeof value === "string" ? overflowRegex.test(value) : false; - }); -} -function getScrollableAncestors(element, limit) { - const scrollParents = []; - function findScrollableAncestors(node) { - if (limit != null && scrollParents.length >= limit) { - return scrollParents; + }, + M: function M4(date, token, localize2) { + var month = date.getUTCMonth(); + switch (token) { + case "M": + case "MM": + return lightFormatters_default.M(date, token); + case "Mo": + return localize2.ordinalNumber(month + 1, { + unit: "month" + }); + case "MMM": + return localize2.month(month, { + width: "abbreviated", + context: "formatting" + }); + case "MMMMM": + return localize2.month(month, { + width: "narrow", + context: "formatting" + }); + case "MMMM": + default: + return localize2.month(month, { + width: "wide", + context: "formatting" + }); } - if (!node) { - return scrollParents; + }, + L: function L3(date, token, localize2) { + var month = date.getUTCMonth(); + switch (token) { + case "L": + return String(month + 1); + case "LL": + return addLeadingZeros(month + 1, 2); + case "Lo": + return localize2.ordinalNumber(month + 1, { + unit: "month" + }); + case "LLL": + return localize2.month(month, { + width: "abbreviated", + context: "standalone" + }); + case "LLLLL": + return localize2.month(month, { + width: "narrow", + context: "standalone" + }); + case "LLLL": + default: + return localize2.month(month, { + width: "wide", + context: "standalone" + }); } - if (isDocument(node) && node.scrollingElement != null && !scrollParents.includes(node.scrollingElement)) { - scrollParents.push(node.scrollingElement); - return scrollParents; + }, + w: function w4(date, token, localize2, options) { + var week = getUTCWeek(date, options); + if (token === "wo") { + return localize2.ordinalNumber(week, { + unit: "week" + }); } - if (!isHTMLElement(node) || isSVGElement(node)) { - return scrollParents; + return addLeadingZeros(week, token.length); + }, + I: function I3(date, token, localize2) { + var isoWeek = getUTCISOWeek(date); + if (token === "Io") { + return localize2.ordinalNumber(isoWeek, { + unit: "week" + }); } - if (scrollParents.includes(node)) { - return scrollParents; + return addLeadingZeros(isoWeek, token.length); + }, + d: function d4(date, token, localize2) { + if (token === "do") { + return localize2.ordinalNumber(date.getUTCDate(), { + unit: "date" + }); } - const computedStyle = getWindow(element).getComputedStyle(node); - if (node !== element) { - if (isScrollable(node, computedStyle)) { - scrollParents.push(node); - } + return lightFormatters_default.d(date, token); + }, + D: function D3(date, token, localize2) { + var dayOfYear = getUTCDayOfYear(date); + if (token === "Do") { + return localize2.ordinalNumber(dayOfYear, { + unit: "dayOfYear" + }); } - if (isFixed(node, computedStyle)) { - return scrollParents; + return addLeadingZeros(dayOfYear, token.length); + }, + E: function E3(date, token, localize2) { + var dayOfWeek = date.getUTCDay(); + switch (token) { + case "E": + case "EE": + case "EEE": + return localize2.day(dayOfWeek, { + width: "abbreviated", + context: "formatting" + }); + case "EEEEE": + return localize2.day(dayOfWeek, { + width: "narrow", + context: "formatting" + }); + case "EEEEEE": + return localize2.day(dayOfWeek, { + width: "short", + context: "formatting" + }); + case "EEEE": + default: + return localize2.day(dayOfWeek, { + width: "wide", + context: "formatting" + }); } - return findScrollableAncestors(node.parentNode); - } - if (!element) { - return scrollParents; - } - return findScrollableAncestors(element); -} -function getFirstScrollableAncestor(node) { - const [firstScrollableAncestor] = getScrollableAncestors(node, 1); - return firstScrollableAncestor != null ? firstScrollableAncestor : null; -} -function getScrollableElement(element) { - if (!canUseDOM || !element) { - return null; - } - if (isWindow(element)) { - return element; - } - if (!isNode(element)) { - return null; - } - if (isDocument(element) || element === getOwnerDocument(element).scrollingElement) { - return window; - } - if (isHTMLElement(element)) { - return element; - } - return null; -} -function getScrollXCoordinate(element) { - if (isWindow(element)) { - return element.scrollX; - } - return element.scrollLeft; -} -function getScrollYCoordinate(element) { - if (isWindow(element)) { - return element.scrollY; - } - return element.scrollTop; -} -function getScrollCoordinates(element) { - return { - x: getScrollXCoordinate(element), - y: getScrollYCoordinate(element) - }; -} -var Direction2; -(function(Direction3) { - Direction3[Direction3["Forward"] = 1] = "Forward"; - Direction3[Direction3["Backward"] = -1] = "Backward"; -})(Direction2 || (Direction2 = {})); -function isDocumentScrollingElement(element) { - if (!canUseDOM || !element) { - return false; - } - return element === document.scrollingElement; -} -function getScrollPosition(scrollingContainer) { - const minScroll = { - x: 0, - y: 0 - }; - const dimensions = isDocumentScrollingElement(scrollingContainer) ? { - height: window.innerHeight, - width: window.innerWidth - } : { - height: scrollingContainer.clientHeight, - width: scrollingContainer.clientWidth - }; - const maxScroll = { - x: scrollingContainer.scrollWidth - dimensions.width, - y: scrollingContainer.scrollHeight - dimensions.height - }; - const isTop = scrollingContainer.scrollTop <= minScroll.y; - const isLeft = scrollingContainer.scrollLeft <= minScroll.x; - const isBottom = scrollingContainer.scrollTop >= maxScroll.y; - const isRight = scrollingContainer.scrollLeft >= maxScroll.x; - return { - isTop, - isLeft, - isBottom, - isRight, - maxScroll, - minScroll - }; -} -var defaultThreshold = { - x: 0.2, - y: 0.2 -}; -function getScrollDirectionAndSpeed(scrollContainer, scrollContainerRect, _ref, acceleration, thresholdPercentage) { - let { - top, - left, - right, - bottom - } = _ref; - if (acceleration === void 0) { - acceleration = 10; - } - if (thresholdPercentage === void 0) { - thresholdPercentage = defaultThreshold; - } - const { - isTop, - isBottom, - isLeft, - isRight - } = getScrollPosition(scrollContainer); - const direction = { - x: 0, - y: 0 - }; - const speed = { - x: 0, - y: 0 - }; - const threshold = { - height: scrollContainerRect.height * thresholdPercentage.y, - width: scrollContainerRect.width * thresholdPercentage.x - }; - if (!isTop && top <= scrollContainerRect.top + threshold.height) { - direction.y = Direction2.Backward; - speed.y = acceleration * Math.abs((scrollContainerRect.top + threshold.height - top) / threshold.height); - } else if (!isBottom && bottom >= scrollContainerRect.bottom - threshold.height) { - direction.y = Direction2.Forward; - speed.y = acceleration * Math.abs((scrollContainerRect.bottom - threshold.height - bottom) / threshold.height); - } - if (!isRight && right >= scrollContainerRect.right - threshold.width) { - direction.x = Direction2.Forward; - speed.x = acceleration * Math.abs((scrollContainerRect.right - threshold.width - right) / threshold.width); - } else if (!isLeft && left <= scrollContainerRect.left + threshold.width) { - direction.x = Direction2.Backward; - speed.x = acceleration * Math.abs((scrollContainerRect.left + threshold.width - left) / threshold.width); - } - return { - direction, - speed - }; -} -function getScrollElementRect(element) { - if (element === document.scrollingElement) { - const { - innerWidth: innerWidth2, - innerHeight: innerHeight2 - } = window; - return { - top: 0, - left: 0, - right: innerWidth2, - bottom: innerHeight2, - width: innerWidth2, - height: innerHeight2 - }; - } - const { - top, - left, - right, - bottom - } = element.getBoundingClientRect(); - return { - top, - left, - right, - bottom, - width: element.clientWidth, - height: element.clientHeight - }; -} -function getScrollOffsets(scrollableAncestors) { - return scrollableAncestors.reduce((acc, node) => { - return add(acc, getScrollCoordinates(node)); - }, defaultCoordinates); -} -function getScrollXOffset(scrollableAncestors) { - return scrollableAncestors.reduce((acc, node) => { - return acc + getScrollXCoordinate(node); - }, 0); -} -function getScrollYOffset(scrollableAncestors) { - return scrollableAncestors.reduce((acc, node) => { - return acc + getScrollYCoordinate(node); - }, 0); -} -function scrollIntoViewIfNeeded(element, measure) { - if (measure === void 0) { - measure = getClientRect; - } - if (!element) { - return; - } - const { - top, - left, - bottom, - right - } = measure(element); - const firstScrollableAncestor = getFirstScrollableAncestor(element); - if (!firstScrollableAncestor) { - return; - } - if (bottom <= 0 || right <= 0 || top >= window.innerHeight || left >= window.innerWidth) { - element.scrollIntoView({ - block: "center", - inline: "center" - }); - } -} -var properties = [["x", ["left", "right"], getScrollXOffset], ["y", ["top", "bottom"], getScrollYOffset]]; -var Rect = class { - constructor(rect, element) { - this.rect = void 0; - this.width = void 0; - this.height = void 0; - this.top = void 0; - this.bottom = void 0; - this.right = void 0; - this.left = void 0; - const scrollableAncestors = getScrollableAncestors(element); - const scrollOffsets = getScrollOffsets(scrollableAncestors); - this.rect = { - ...rect - }; - this.width = rect.width; - this.height = rect.height; - for (const [axis, keys, getScrollOffset] of properties) { - for (const key2 of keys) { - Object.defineProperty(this, key2, { - get: () => { - const currentOffsets = getScrollOffset(scrollableAncestors); - const scrollOffsetsDeltla = scrollOffsets[axis] - currentOffsets; - return this.rect[key2] + scrollOffsetsDeltla; - }, - enumerable: true + }, + e: function e3(date, token, localize2, options) { + var dayOfWeek = date.getUTCDay(); + var localDayOfWeek = (dayOfWeek - options.weekStartsOn + 8) % 7 || 7; + switch (token) { + case "e": + return String(localDayOfWeek); + case "ee": + return addLeadingZeros(localDayOfWeek, 2); + case "eo": + return localize2.ordinalNumber(localDayOfWeek, { + unit: "day" + }); + case "eee": + return localize2.day(dayOfWeek, { + width: "abbreviated", + context: "formatting" + }); + case "eeeee": + return localize2.day(dayOfWeek, { + width: "narrow", + context: "formatting" + }); + case "eeeeee": + return localize2.day(dayOfWeek, { + width: "short", + context: "formatting" + }); + case "eeee": + default: + return localize2.day(dayOfWeek, { + width: "wide", + context: "formatting" + }); + } + }, + c: function c3(date, token, localize2, options) { + var dayOfWeek = date.getUTCDay(); + var localDayOfWeek = (dayOfWeek - options.weekStartsOn + 8) % 7 || 7; + switch (token) { + case "c": + return String(localDayOfWeek); + case "cc": + return addLeadingZeros(localDayOfWeek, token.length); + case "co": + return localize2.ordinalNumber(localDayOfWeek, { + unit: "day" + }); + case "ccc": + return localize2.day(dayOfWeek, { + width: "abbreviated", + context: "standalone" + }); + case "ccccc": + return localize2.day(dayOfWeek, { + width: "narrow", + context: "standalone" + }); + case "cccccc": + return localize2.day(dayOfWeek, { + width: "short", + context: "standalone" + }); + case "cccc": + default: + return localize2.day(dayOfWeek, { + width: "wide", + context: "standalone" + }); + } + }, + i: function i3(date, token, localize2) { + var dayOfWeek = date.getUTCDay(); + var isoDayOfWeek = dayOfWeek === 0 ? 7 : dayOfWeek; + switch (token) { + case "i": + return String(isoDayOfWeek); + case "ii": + return addLeadingZeros(isoDayOfWeek, token.length); + case "io": + return localize2.ordinalNumber(isoDayOfWeek, { + unit: "day" + }); + case "iii": + return localize2.day(dayOfWeek, { + width: "abbreviated", + context: "formatting" + }); + case "iiiii": + return localize2.day(dayOfWeek, { + width: "narrow", + context: "formatting" + }); + case "iiiiii": + return localize2.day(dayOfWeek, { + width: "short", + context: "formatting" + }); + case "iiii": + default: + return localize2.day(dayOfWeek, { + width: "wide", + context: "formatting" }); - } } - Object.defineProperty(this, "rect", { - enumerable: false - }); - } -}; -var Listeners = class { - constructor(target) { - this.target = void 0; - this.listeners = []; - this.removeAll = () => { - this.listeners.forEach((listener) => { - var _this$target; - return (_this$target = this.target) == null ? void 0 : _this$target.removeEventListener(...listener); + }, + a: function a4(date, token, localize2) { + var hours = date.getUTCHours(); + var dayPeriodEnumValue = hours / 12 >= 1 ? "pm" : "am"; + switch (token) { + case "a": + case "aa": + return localize2.dayPeriod(dayPeriodEnumValue, { + width: "abbreviated", + context: "formatting" + }); + case "aaa": + return localize2.dayPeriod(dayPeriodEnumValue, { + width: "abbreviated", + context: "formatting" + }).toLowerCase(); + case "aaaaa": + return localize2.dayPeriod(dayPeriodEnumValue, { + width: "narrow", + context: "formatting" + }); + case "aaaa": + default: + return localize2.dayPeriod(dayPeriodEnumValue, { + width: "wide", + context: "formatting" + }); + } + }, + b: function b3(date, token, localize2) { + var hours = date.getUTCHours(); + var dayPeriodEnumValue; + if (hours === 12) { + dayPeriodEnumValue = dayPeriodEnum.noon; + } else if (hours === 0) { + dayPeriodEnumValue = dayPeriodEnum.midnight; + } else { + dayPeriodEnumValue = hours / 12 >= 1 ? "pm" : "am"; + } + switch (token) { + case "b": + case "bb": + return localize2.dayPeriod(dayPeriodEnumValue, { + width: "abbreviated", + context: "formatting" + }); + case "bbb": + return localize2.dayPeriod(dayPeriodEnumValue, { + width: "abbreviated", + context: "formatting" + }).toLowerCase(); + case "bbbbb": + return localize2.dayPeriod(dayPeriodEnumValue, { + width: "narrow", + context: "formatting" + }); + case "bbbb": + default: + return localize2.dayPeriod(dayPeriodEnumValue, { + width: "wide", + context: "formatting" + }); + } + }, + B: function B4(date, token, localize2) { + var hours = date.getUTCHours(); + var dayPeriodEnumValue; + if (hours >= 17) { + dayPeriodEnumValue = dayPeriodEnum.evening; + } else if (hours >= 12) { + dayPeriodEnumValue = dayPeriodEnum.afternoon; + } else if (hours >= 4) { + dayPeriodEnumValue = dayPeriodEnum.morning; + } else { + dayPeriodEnumValue = dayPeriodEnum.night; + } + switch (token) { + case "B": + case "BB": + case "BBB": + return localize2.dayPeriod(dayPeriodEnumValue, { + width: "abbreviated", + context: "formatting" + }); + case "BBBBB": + return localize2.dayPeriod(dayPeriodEnumValue, { + width: "narrow", + context: "formatting" + }); + case "BBBB": + default: + return localize2.dayPeriod(dayPeriodEnumValue, { + width: "wide", + context: "formatting" + }); + } + }, + h: function h4(date, token, localize2) { + if (token === "ho") { + var hours = date.getUTCHours() % 12; + if (hours === 0) + hours = 12; + return localize2.ordinalNumber(hours, { + unit: "hour" }); - }; - this.target = target; - } - add(eventName, handler, options) { - var _this$target2; - (_this$target2 = this.target) == null ? void 0 : _this$target2.addEventListener(eventName, handler, options); - this.listeners.push([eventName, handler, options]); - } -}; -function getEventListenerTarget(target) { - const { - EventTarget - } = getWindow(target); - return target instanceof EventTarget ? target : getOwnerDocument(target); -} -function hasExceededDistance(delta, measurement) { - const dx = Math.abs(delta.x); - const dy = Math.abs(delta.y); - if (typeof measurement === "number") { - return Math.sqrt(dx ** 2 + dy ** 2) > measurement; - } - if ("x" in measurement && "y" in measurement) { - return dx > measurement.x && dy > measurement.y; - } - if ("x" in measurement) { - return dx > measurement.x; - } - if ("y" in measurement) { - return dy > measurement.y; - } - return false; -} -var EventName; -(function(EventName2) { - EventName2["Click"] = "click"; - EventName2["DragStart"] = "dragstart"; - EventName2["Keydown"] = "keydown"; - EventName2["ContextMenu"] = "contextmenu"; - EventName2["Resize"] = "resize"; - EventName2["SelectionChange"] = "selectionchange"; - EventName2["VisibilityChange"] = "visibilitychange"; -})(EventName || (EventName = {})); -function preventDefault(event) { - event.preventDefault(); -} -function stopPropagation(event) { - event.stopPropagation(); -} -var KeyboardCode; -(function(KeyboardCode2) { - KeyboardCode2["Space"] = "Space"; - KeyboardCode2["Down"] = "ArrowDown"; - KeyboardCode2["Right"] = "ArrowRight"; - KeyboardCode2["Left"] = "ArrowLeft"; - KeyboardCode2["Up"] = "ArrowUp"; - KeyboardCode2["Esc"] = "Escape"; - KeyboardCode2["Enter"] = "Enter"; -})(KeyboardCode || (KeyboardCode = {})); -var defaultKeyboardCodes = { - start: [KeyboardCode.Space, KeyboardCode.Enter], - cancel: [KeyboardCode.Esc], - end: [KeyboardCode.Space, KeyboardCode.Enter] -}; -var defaultKeyboardCoordinateGetter = (event, _ref) => { - let { - currentCoordinates - } = _ref; - switch (event.code) { - case KeyboardCode.Right: - return { - ...currentCoordinates, - x: currentCoordinates.x + 25 - }; - case KeyboardCode.Left: - return { - ...currentCoordinates, - x: currentCoordinates.x - 25 - }; - case KeyboardCode.Down: - return { - ...currentCoordinates, - y: currentCoordinates.y + 25 - }; - case KeyboardCode.Up: - return { - ...currentCoordinates, - y: currentCoordinates.y - 25 - }; - } - return void 0; -}; -var KeyboardSensor = class { - constructor(props2) { - this.props = void 0; - this.autoScrollEnabled = false; - this.referenceCoordinates = void 0; - this.listeners = void 0; - this.windowListeners = void 0; - this.props = props2; - const { - event: { - target - } - } = props2; - this.props = props2; - this.listeners = new Listeners(getOwnerDocument(target)); - this.windowListeners = new Listeners(getWindow(target)); - this.handleKeyDown = this.handleKeyDown.bind(this); - this.handleCancel = this.handleCancel.bind(this); - this.attach(); - } - attach() { - this.handleStart(); - this.windowListeners.add(EventName.Resize, this.handleCancel); - this.windowListeners.add(EventName.VisibilityChange, this.handleCancel); - setTimeout(() => this.listeners.add(EventName.Keydown, this.handleKeyDown)); - } - handleStart() { - const { - activeNode, - onStart - } = this.props; - const node = activeNode.node.current; - if (node) { - scrollIntoViewIfNeeded(node); } - onStart(defaultCoordinates); - } - handleKeyDown(event) { - if (isKeyboardEvent(event)) { - const { - active, - context, - options - } = this.props; - const { - keyboardCodes = defaultKeyboardCodes, - coordinateGetter = defaultKeyboardCoordinateGetter, - scrollBehavior = "smooth" - } = options; - const { - code - } = event; - if (keyboardCodes.end.includes(code)) { - this.handleEnd(event); - return; - } - if (keyboardCodes.cancel.includes(code)) { - this.handleCancel(event); - return; - } - const { - collisionRect - } = context.current; - const currentCoordinates = collisionRect ? { - x: collisionRect.left, - y: collisionRect.top - } : defaultCoordinates; - if (!this.referenceCoordinates) { - this.referenceCoordinates = currentCoordinates; - } - const newCoordinates = coordinateGetter(event, { - active, - context: context.current, - currentCoordinates + return lightFormatters_default.h(date, token); + }, + H: function H4(date, token, localize2) { + if (token === "Ho") { + return localize2.ordinalNumber(date.getUTCHours(), { + unit: "hour" }); - if (newCoordinates) { - const coordinatesDelta = subtract(newCoordinates, currentCoordinates); - const scrollDelta = { - x: 0, - y: 0 - }; - const { - scrollableAncestors - } = context.current; - for (const scrollContainer of scrollableAncestors) { - const direction = event.code; - const { - isTop, - isRight, - isLeft, - isBottom, - maxScroll, - minScroll - } = getScrollPosition(scrollContainer); - const scrollElementRect = getScrollElementRect(scrollContainer); - const clampedCoordinates = { - x: Math.min(direction === KeyboardCode.Right ? scrollElementRect.right - scrollElementRect.width / 2 : scrollElementRect.right, Math.max(direction === KeyboardCode.Right ? scrollElementRect.left : scrollElementRect.left + scrollElementRect.width / 2, newCoordinates.x)), - y: Math.min(direction === KeyboardCode.Down ? scrollElementRect.bottom - scrollElementRect.height / 2 : scrollElementRect.bottom, Math.max(direction === KeyboardCode.Down ? scrollElementRect.top : scrollElementRect.top + scrollElementRect.height / 2, newCoordinates.y)) - }; - const canScrollX = direction === KeyboardCode.Right && !isRight || direction === KeyboardCode.Left && !isLeft; - const canScrollY = direction === KeyboardCode.Down && !isBottom || direction === KeyboardCode.Up && !isTop; - if (canScrollX && clampedCoordinates.x !== newCoordinates.x) { - const newScrollCoordinates = scrollContainer.scrollLeft + coordinatesDelta.x; - const canScrollToNewCoordinates = direction === KeyboardCode.Right && newScrollCoordinates <= maxScroll.x || direction === KeyboardCode.Left && newScrollCoordinates >= minScroll.x; - if (canScrollToNewCoordinates && !coordinatesDelta.y) { - scrollContainer.scrollTo({ - left: newScrollCoordinates, - behavior: scrollBehavior - }); - return; - } - if (canScrollToNewCoordinates) { - scrollDelta.x = scrollContainer.scrollLeft - newScrollCoordinates; - } else { - scrollDelta.x = direction === KeyboardCode.Right ? scrollContainer.scrollLeft - maxScroll.x : scrollContainer.scrollLeft - minScroll.x; - } - if (scrollDelta.x) { - scrollContainer.scrollBy({ - left: -scrollDelta.x, - behavior: scrollBehavior - }); - } - break; - } else if (canScrollY && clampedCoordinates.y !== newCoordinates.y) { - const newScrollCoordinates = scrollContainer.scrollTop + coordinatesDelta.y; - const canScrollToNewCoordinates = direction === KeyboardCode.Down && newScrollCoordinates <= maxScroll.y || direction === KeyboardCode.Up && newScrollCoordinates >= minScroll.y; - if (canScrollToNewCoordinates && !coordinatesDelta.x) { - scrollContainer.scrollTo({ - top: newScrollCoordinates, - behavior: scrollBehavior - }); - return; - } - if (canScrollToNewCoordinates) { - scrollDelta.y = scrollContainer.scrollTop - newScrollCoordinates; - } else { - scrollDelta.y = direction === KeyboardCode.Down ? scrollContainer.scrollTop - maxScroll.y : scrollContainer.scrollTop - minScroll.y; - } - if (scrollDelta.y) { - scrollContainer.scrollBy({ - top: -scrollDelta.y, - behavior: scrollBehavior - }); - } - break; - } - } - this.handleMove(event, add(subtract(newCoordinates, this.referenceCoordinates), scrollDelta)); - } } - } - handleMove(event, coordinates) { - const { - onMove - } = this.props; - event.preventDefault(); - onMove(coordinates); - } - handleEnd(event) { - const { - onEnd - } = this.props; - event.preventDefault(); - this.detach(); - onEnd(); - } - handleCancel(event) { - const { - onCancel - } = this.props; - event.preventDefault(); - this.detach(); - onCancel(); - } - detach() { - this.listeners.removeAll(); - this.windowListeners.removeAll(); + return lightFormatters_default.H(date, token); + }, + K: function K2(date, token, localize2) { + var hours = date.getUTCHours() % 12; + if (token === "Ko") { + return localize2.ordinalNumber(hours, { + unit: "hour" + }); + } + return addLeadingZeros(hours, token.length); + }, + k: function k4(date, token, localize2) { + var hours = date.getUTCHours(); + if (hours === 0) + hours = 24; + if (token === "ko") { + return localize2.ordinalNumber(hours, { + unit: "hour" + }); + } + return addLeadingZeros(hours, token.length); + }, + m: function m4(date, token, localize2) { + if (token === "mo") { + return localize2.ordinalNumber(date.getUTCMinutes(), { + unit: "minute" + }); + } + return lightFormatters_default.m(date, token); + }, + s: function s4(date, token, localize2) { + if (token === "so") { + return localize2.ordinalNumber(date.getUTCSeconds(), { + unit: "second" + }); + } + return lightFormatters_default.s(date, token); + }, + S: function S3(date, token) { + return lightFormatters_default.S(date, token); + }, + X: function X2(date, token, _localize, options) { + var originalDate = options._originalDate || date; + var timezoneOffset = originalDate.getTimezoneOffset(); + if (timezoneOffset === 0) { + return "Z"; + } + switch (token) { + case "X": + return formatTimezoneWithOptionalMinutes(timezoneOffset); + case "XXXX": + case "XX": + return formatTimezone(timezoneOffset); + case "XXXXX": + case "XXX": + default: + return formatTimezone(timezoneOffset, ":"); + } + }, + x: function x4(date, token, _localize, options) { + var originalDate = options._originalDate || date; + var timezoneOffset = originalDate.getTimezoneOffset(); + switch (token) { + case "x": + return formatTimezoneWithOptionalMinutes(timezoneOffset); + case "xxxx": + case "xx": + return formatTimezone(timezoneOffset); + case "xxxxx": + case "xxx": + default: + return formatTimezone(timezoneOffset, ":"); + } + }, + O: function O3(date, token, _localize, options) { + var originalDate = options._originalDate || date; + var timezoneOffset = originalDate.getTimezoneOffset(); + switch (token) { + case "O": + case "OO": + case "OOO": + return "GMT" + formatTimezoneShort(timezoneOffset, ":"); + case "OOOO": + default: + return "GMT" + formatTimezone(timezoneOffset, ":"); + } + }, + z: function z4(date, token, _localize, options) { + var originalDate = options._originalDate || date; + var timezoneOffset = originalDate.getTimezoneOffset(); + switch (token) { + case "z": + case "zz": + case "zzz": + return "GMT" + formatTimezoneShort(timezoneOffset, ":"); + case "zzzz": + default: + return "GMT" + formatTimezone(timezoneOffset, ":"); + } + }, + t: function t3(date, token, _localize, options) { + var originalDate = options._originalDate || date; + var timestamp = Math.floor(originalDate.getTime() / 1e3); + return addLeadingZeros(timestamp, token.length); + }, + T: function T5(date, token, _localize, options) { + var originalDate = options._originalDate || date; + var timestamp = originalDate.getTime(); + return addLeadingZeros(timestamp, token.length); } }; -KeyboardSensor.activators = [{ - eventName: "onKeyDown", - handler: (event, _ref, _ref2) => { - let { - keyboardCodes = defaultKeyboardCodes, - onActivation - } = _ref; - let { - active - } = _ref2; - const { - code - } = event.nativeEvent; - if (keyboardCodes.start.includes(code)) { - const activator = active.activatorNode.current; - if (activator && event.target !== activator) { - return false; - } - event.preventDefault(); - onActivation == null ? void 0 : onActivation({ - event: event.nativeEvent - }); - return true; - } - return false; +function formatTimezoneShort(offset2, dirtyDelimiter) { + var sign = offset2 > 0 ? "-" : "+"; + var absOffset = Math.abs(offset2); + var hours = Math.floor(absOffset / 60); + var minutes = absOffset % 60; + if (minutes === 0) { + return sign + String(hours); } -}]; -function isDistanceConstraint(constraint) { - return Boolean(constraint && "distance" in constraint); + var delimiter = dirtyDelimiter || ""; + return sign + String(hours) + delimiter + addLeadingZeros(minutes, 2); } -function isDelayConstraint(constraint) { - return Boolean(constraint && "delay" in constraint); +function formatTimezoneWithOptionalMinutes(offset2, dirtyDelimiter) { + if (offset2 % 60 === 0) { + var sign = offset2 > 0 ? "-" : "+"; + return sign + addLeadingZeros(Math.abs(offset2) / 60, 2); + } + return formatTimezone(offset2, dirtyDelimiter); } -var AbstractPointerSensor = class { - constructor(props2, events2, listenerTarget) { - var _getEventCoordinates; - if (listenerTarget === void 0) { - listenerTarget = getEventListenerTarget(props2.event.target); - } - this.props = void 0; - this.events = void 0; - this.autoScrollEnabled = true; - this.document = void 0; - this.activated = false; - this.initialCoordinates = void 0; - this.timeoutId = null; - this.listeners = void 0; - this.documentListeners = void 0; - this.windowListeners = void 0; - this.props = props2; - this.events = events2; - const { - event - } = props2; - const { - target - } = event; - this.props = props2; - this.events = events2; - this.document = getOwnerDocument(target); - this.documentListeners = new Listeners(this.document); - this.listeners = new Listeners(listenerTarget); - this.windowListeners = new Listeners(getWindow(target)); - this.initialCoordinates = (_getEventCoordinates = getEventCoordinates(event)) != null ? _getEventCoordinates : defaultCoordinates; - this.handleStart = this.handleStart.bind(this); - this.handleMove = this.handleMove.bind(this); - this.handleEnd = this.handleEnd.bind(this); - this.handleCancel = this.handleCancel.bind(this); - this.handleKeydown = this.handleKeydown.bind(this); - this.removeTextSelection = this.removeTextSelection.bind(this); - this.attach(); +function formatTimezone(offset2, dirtyDelimiter) { + var delimiter = dirtyDelimiter || ""; + var sign = offset2 > 0 ? "-" : "+"; + var absOffset = Math.abs(offset2); + var hours = addLeadingZeros(Math.floor(absOffset / 60), 2); + var minutes = addLeadingZeros(absOffset % 60, 2); + return sign + hours + delimiter + minutes; +} +var formatters_default = formatters2; + +// node_modules/date-fns/esm/_lib/format/longFormatters/index.js +var dateLongFormatter = function dateLongFormatter2(pattern, formatLong2) { + switch (pattern) { + case "P": + return formatLong2.date({ + width: "short" + }); + case "PP": + return formatLong2.date({ + width: "medium" + }); + case "PPP": + return formatLong2.date({ + width: "long" + }); + case "PPPP": + default: + return formatLong2.date({ + width: "full" + }); } - attach() { - const { - events: events2, - props: { - options: { - activationConstraint - } - } - } = this; - this.listeners.add(events2.move.name, this.handleMove, { - passive: false - }); - this.listeners.add(events2.end.name, this.handleEnd); - this.windowListeners.add(EventName.Resize, this.handleCancel); - this.windowListeners.add(EventName.DragStart, preventDefault); - this.windowListeners.add(EventName.VisibilityChange, this.handleCancel); - this.windowListeners.add(EventName.ContextMenu, preventDefault); - this.documentListeners.add(EventName.Keydown, this.handleKeydown); - if (activationConstraint) { - if (isDistanceConstraint(activationConstraint)) { - return; - } - if (isDelayConstraint(activationConstraint)) { - this.timeoutId = setTimeout(this.handleStart, activationConstraint.delay); - return; - } - } - this.handleStart(); +}; +var timeLongFormatter = function timeLongFormatter2(pattern, formatLong2) { + switch (pattern) { + case "p": + return formatLong2.time({ + width: "short" + }); + case "pp": + return formatLong2.time({ + width: "medium" + }); + case "ppp": + return formatLong2.time({ + width: "long" + }); + case "pppp": + default: + return formatLong2.time({ + width: "full" + }); } - detach() { - this.listeners.removeAll(); - this.windowListeners.removeAll(); - setTimeout(this.documentListeners.removeAll, 50); - if (this.timeoutId !== null) { - clearTimeout(this.timeoutId); - this.timeoutId = null; - } +}; +var dateTimeLongFormatter = function dateTimeLongFormatter2(pattern, formatLong2) { + var matchResult = pattern.match(/(P+)(p+)?/) || []; + var datePattern = matchResult[1]; + var timePattern = matchResult[2]; + if (!timePattern) { + return dateLongFormatter(pattern, formatLong2); } - handleStart() { - const { - initialCoordinates - } = this; - const { - onStart - } = this.props; - if (initialCoordinates) { - this.activated = true; - this.documentListeners.add(EventName.Click, stopPropagation, { - capture: true + var dateTimeFormat; + switch (datePattern) { + case "P": + dateTimeFormat = formatLong2.dateTime({ + width: "short" }); - this.removeTextSelection(); - this.documentListeners.add(EventName.SelectionChange, this.removeTextSelection); - onStart(initialCoordinates); - } + break; + case "PP": + dateTimeFormat = formatLong2.dateTime({ + width: "medium" + }); + break; + case "PPP": + dateTimeFormat = formatLong2.dateTime({ + width: "long" + }); + break; + case "PPPP": + default: + dateTimeFormat = formatLong2.dateTime({ + width: "full" + }); + break; } - handleMove(event) { - var _getEventCoordinates2; - const { - activated, - initialCoordinates, - props: props2 - } = this; - const { - onMove, - options: { - activationConstraint - } - } = props2; - if (!initialCoordinates) { - return; - } - const coordinates = (_getEventCoordinates2 = getEventCoordinates(event)) != null ? _getEventCoordinates2 : defaultCoordinates; - const delta = subtract(initialCoordinates, coordinates); - if (!activated && activationConstraint) { - if (isDelayConstraint(activationConstraint)) { - if (hasExceededDistance(delta, activationConstraint.tolerance)) { - return this.handleCancel(); - } - return; - } - if (isDistanceConstraint(activationConstraint)) { - if (activationConstraint.tolerance != null && hasExceededDistance(delta, activationConstraint.tolerance)) { - return this.handleCancel(); - } - if (hasExceededDistance(delta, activationConstraint.distance)) { - return this.handleStart(); - } - return; - } - } - if (event.cancelable) { - event.preventDefault(); - } - onMove(coordinates); + return dateTimeFormat.replace("{{date}}", dateLongFormatter(datePattern, formatLong2)).replace("{{time}}", timeLongFormatter(timePattern, formatLong2)); +}; +var longFormatters = { + p: timeLongFormatter, + P: dateTimeLongFormatter +}; +var longFormatters_default = longFormatters; + +// node_modules/date-fns/esm/_lib/protectedTokens/index.js +var protectedDayOfYearTokens = ["D", "DD"]; +var protectedWeekYearTokens = ["YY", "YYYY"]; +function isProtectedDayOfYearToken(token) { + return protectedDayOfYearTokens.indexOf(token) !== -1; +} +function isProtectedWeekYearToken(token) { + return protectedWeekYearTokens.indexOf(token) !== -1; +} +function throwProtectedError(token, format2, input) { + if (token === "YYYY") { + throw new RangeError("Use `yyyy` instead of `YYYY` (in `".concat(format2, "`) for formatting years to the input `").concat(input, "`; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md")); + } else if (token === "YY") { + throw new RangeError("Use `yy` instead of `YY` (in `".concat(format2, "`) for formatting years to the input `").concat(input, "`; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md")); + } else if (token === "D") { + throw new RangeError("Use `d` instead of `D` (in `".concat(format2, "`) for formatting days of the month to the input `").concat(input, "`; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md")); + } else if (token === "DD") { + throw new RangeError("Use `dd` instead of `DD` (in `".concat(format2, "`) for formatting days of the month to the input `").concat(input, "`; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md")); } - handleEnd() { - const { - onEnd - } = this.props; - this.detach(); - onEnd(); +} + +// node_modules/date-fns/esm/locale/en-US/_lib/formatDistance/index.js +var formatDistanceLocale = { + lessThanXSeconds: { + one: "less than a second", + other: "less than {{count}} seconds" + }, + xSeconds: { + one: "1 second", + other: "{{count}} seconds" + }, + halfAMinute: "half a minute", + lessThanXMinutes: { + one: "less than a minute", + other: "less than {{count}} minutes" + }, + xMinutes: { + one: "1 minute", + other: "{{count}} minutes" + }, + aboutXHours: { + one: "about 1 hour", + other: "about {{count}} hours" + }, + xHours: { + one: "1 hour", + other: "{{count}} hours" + }, + xDays: { + one: "1 day", + other: "{{count}} days" + }, + aboutXWeeks: { + one: "about 1 week", + other: "about {{count}} weeks" + }, + xWeeks: { + one: "1 week", + other: "{{count}} weeks" + }, + aboutXMonths: { + one: "about 1 month", + other: "about {{count}} months" + }, + xMonths: { + one: "1 month", + other: "{{count}} months" + }, + aboutXYears: { + one: "about 1 year", + other: "about {{count}} years" + }, + xYears: { + one: "1 year", + other: "{{count}} years" + }, + overXYears: { + one: "over 1 year", + other: "over {{count}} years" + }, + almostXYears: { + one: "almost 1 year", + other: "almost {{count}} years" } - handleCancel() { - const { - onCancel - } = this.props; - this.detach(); - onCancel(); +}; +var formatDistance = function formatDistance2(token, count2, options) { + var result; + var tokenValue = formatDistanceLocale[token]; + if (typeof tokenValue === "string") { + result = tokenValue; + } else if (count2 === 1) { + result = tokenValue.one; + } else { + result = tokenValue.other.replace("{{count}}", count2.toString()); } - handleKeydown(event) { - if (event.code === KeyboardCode.Esc) { - this.handleCancel(); + if (options !== null && options !== void 0 && options.addSuffix) { + if (options.comparison && options.comparison > 0) { + return "in " + result; + } else { + return result + " ago"; } } - removeTextSelection() { - var _this$document$getSel; - (_this$document$getSel = this.document.getSelection()) == null ? void 0 : _this$document$getSel.removeAllRanges(); + return result; +}; +var formatDistance_default = formatDistance; + +// node_modules/date-fns/esm/locale/_lib/buildFormatLongFn/index.js +function buildFormatLongFn(args) { + return function() { + var options = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {}; + var width = options.width ? String(options.width) : args.defaultWidth; + var format2 = args.formats[width] || args.formats[args.defaultWidth]; + return format2; + }; +} + +// node_modules/date-fns/esm/locale/en-US/_lib/formatLong/index.js +var dateFormats = { + full: "EEEE, MMMM do, y", + long: "MMMM do, y", + medium: "MMM d, y", + short: "MM/dd/yyyy" +}; +var timeFormats = { + full: "h:mm:ss a zzzz", + long: "h:mm:ss a z", + medium: "h:mm:ss a", + short: "h:mm a" +}; +var dateTimeFormats = { + full: "{{date}} 'at' {{time}}", + long: "{{date}} 'at' {{time}}", + medium: "{{date}}, {{time}}", + short: "{{date}}, {{time}}" +}; +var formatLong = { + date: buildFormatLongFn({ + formats: dateFormats, + defaultWidth: "full" + }), + time: buildFormatLongFn({ + formats: timeFormats, + defaultWidth: "full" + }), + dateTime: buildFormatLongFn({ + formats: dateTimeFormats, + defaultWidth: "full" + }) +}; +var formatLong_default = formatLong; + +// node_modules/date-fns/esm/locale/en-US/_lib/formatRelative/index.js +var formatRelativeLocale = { + lastWeek: "'last' eeee 'at' p", + yesterday: "'yesterday at' p", + today: "'today at' p", + tomorrow: "'tomorrow at' p", + nextWeek: "eeee 'at' p", + other: "P" +}; +var formatRelative = function formatRelative2(token, _date, _baseDate, _options) { + return formatRelativeLocale[token]; +}; +var formatRelative_default = formatRelative; + +// node_modules/date-fns/esm/locale/_lib/buildLocalizeFn/index.js +function buildLocalizeFn(args) { + return function(dirtyIndex, options) { + var context = options !== null && options !== void 0 && options.context ? String(options.context) : "standalone"; + var valuesArray; + if (context === "formatting" && args.formattingValues) { + var defaultWidth = args.defaultFormattingWidth || args.defaultWidth; + var width = options !== null && options !== void 0 && options.width ? String(options.width) : defaultWidth; + valuesArray = args.formattingValues[width] || args.formattingValues[defaultWidth]; + } else { + var _defaultWidth = args.defaultWidth; + var _width = options !== null && options !== void 0 && options.width ? String(options.width) : args.defaultWidth; + valuesArray = args.values[_width] || args.values[_defaultWidth]; + } + var index = args.argumentCallback ? args.argumentCallback(dirtyIndex) : dirtyIndex; + return valuesArray[index]; + }; +} + +// node_modules/date-fns/esm/locale/en-US/_lib/localize/index.js +var eraValues = { + narrow: ["B", "A"], + abbreviated: ["BC", "AD"], + wide: ["Before Christ", "Anno Domini"] +}; +var quarterValues = { + narrow: ["1", "2", "3", "4"], + abbreviated: ["Q1", "Q2", "Q3", "Q4"], + wide: ["1st quarter", "2nd quarter", "3rd quarter", "4th quarter"] +}; +var monthValues = { + narrow: ["J", "F", "M", "A", "M", "J", "J", "A", "S", "O", "N", "D"], + abbreviated: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"], + wide: ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"] +}; +var dayValues = { + narrow: ["S", "M", "T", "W", "T", "F", "S"], + short: ["Su", "Mo", "Tu", "We", "Th", "Fr", "Sa"], + abbreviated: ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"], + wide: ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"] +}; +var dayPeriodValues = { + narrow: { + am: "a", + pm: "p", + midnight: "mi", + noon: "n", + morning: "morning", + afternoon: "afternoon", + evening: "evening", + night: "night" + }, + abbreviated: { + am: "AM", + pm: "PM", + midnight: "midnight", + noon: "noon", + morning: "morning", + afternoon: "afternoon", + evening: "evening", + night: "night" + }, + wide: { + am: "a.m.", + pm: "p.m.", + midnight: "midnight", + noon: "noon", + morning: "morning", + afternoon: "afternoon", + evening: "evening", + night: "night" } }; -var events = { - move: { - name: "pointermove" +var formattingDayPeriodValues = { + narrow: { + am: "a", + pm: "p", + midnight: "mi", + noon: "n", + morning: "in the morning", + afternoon: "in the afternoon", + evening: "in the evening", + night: "at night" + }, + abbreviated: { + am: "AM", + pm: "PM", + midnight: "midnight", + noon: "noon", + morning: "in the morning", + afternoon: "in the afternoon", + evening: "in the evening", + night: "at night" }, - end: { - name: "pointerup" + wide: { + am: "a.m.", + pm: "p.m.", + midnight: "midnight", + noon: "noon", + morning: "in the morning", + afternoon: "in the afternoon", + evening: "in the evening", + night: "at night" } }; -var PointerSensor = class extends AbstractPointerSensor { - constructor(props2) { - const { - event - } = props2; - const listenerTarget = getOwnerDocument(event.target); - super(props2, events, listenerTarget); +var ordinalNumber = function ordinalNumber2(dirtyNumber, _options) { + var number = Number(dirtyNumber); + var rem100 = number % 100; + if (rem100 > 20 || rem100 < 10) { + switch (rem100 % 10) { + case 1: + return number + "st"; + case 2: + return number + "nd"; + case 3: + return number + "rd"; + } } + return number + "th"; }; -PointerSensor.activators = [{ - eventName: "onPointerDown", - handler: (_ref, _ref2) => { - let { - nativeEvent: event - } = _ref; - let { - onActivation - } = _ref2; - if (!event.isPrimary || event.button !== 0) { - return false; +var localize = { + ordinalNumber, + era: buildLocalizeFn({ + values: eraValues, + defaultWidth: "wide" + }), + quarter: buildLocalizeFn({ + values: quarterValues, + defaultWidth: "wide", + argumentCallback: function argumentCallback(quarter) { + return quarter - 1; } - onActivation == null ? void 0 : onActivation({ - event + }), + month: buildLocalizeFn({ + values: monthValues, + defaultWidth: "wide" + }), + day: buildLocalizeFn({ + values: dayValues, + defaultWidth: "wide" + }), + dayPeriod: buildLocalizeFn({ + values: dayPeriodValues, + defaultWidth: "wide", + formattingValues: formattingDayPeriodValues, + defaultFormattingWidth: "wide" + }) +}; +var localize_default = localize; + +// node_modules/date-fns/esm/locale/_lib/buildMatchFn/index.js +function buildMatchFn(args) { + return function(string) { + var options = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {}; + var width = options.width; + var matchPattern = width && args.matchPatterns[width] || args.matchPatterns[args.defaultMatchWidth]; + var matchResult = string.match(matchPattern); + if (!matchResult) { + return null; + } + var matchedString = matchResult[0]; + var parsePatterns = width && args.parsePatterns[width] || args.parsePatterns[args.defaultParseWidth]; + var key2 = Array.isArray(parsePatterns) ? findIndex(parsePatterns, function(pattern) { + return pattern.test(matchedString); + }) : findKey(parsePatterns, function(pattern) { + return pattern.test(matchedString); }); - return true; + var value; + value = args.valueCallback ? args.valueCallback(key2) : key2; + value = options.valueCallback ? options.valueCallback(value) : value; + var rest = string.slice(matchedString.length); + return { + value, + rest + }; + }; +} +function findKey(object, predicate) { + for (var key2 in object) { + if (object.hasOwnProperty(key2) && predicate(object[key2])) { + return key2; + } } -}]; -var events$1 = { - move: { - name: "mousemove" - }, - end: { - name: "mouseup" + return void 0; +} +function findIndex(array, predicate) { + for (var key2 = 0; key2 < array.length; key2++) { + if (predicate(array[key2])) { + return key2; + } } + return void 0; +} + +// node_modules/date-fns/esm/locale/_lib/buildMatchPatternFn/index.js +function buildMatchPatternFn(args) { + return function(string) { + var options = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {}; + var matchResult = string.match(args.matchPattern); + if (!matchResult) + return null; + var matchedString = matchResult[0]; + var parseResult = string.match(args.parsePattern); + if (!parseResult) + return null; + var value = args.valueCallback ? args.valueCallback(parseResult[0]) : parseResult[0]; + value = options.valueCallback ? options.valueCallback(value) : value; + var rest = string.slice(matchedString.length); + return { + value, + rest + }; + }; +} + +// node_modules/date-fns/esm/locale/en-US/_lib/match/index.js +var matchOrdinalNumberPattern = /^(\d+)(th|st|nd|rd)?/i; +var parseOrdinalNumberPattern = /\d+/i; +var matchEraPatterns = { + narrow: /^(b|a)/i, + abbreviated: /^(b\.?\s?c\.?|b\.?\s?c\.?\s?e\.?|a\.?\s?d\.?|c\.?\s?e\.?)/i, + wide: /^(before christ|before common era|anno domini|common era)/i }; -var MouseButton; -(function(MouseButton2) { - MouseButton2[MouseButton2["RightClick"] = 2] = "RightClick"; -})(MouseButton || (MouseButton = {})); -var MouseSensor = class extends AbstractPointerSensor { - constructor(props2) { - super(props2, events$1, getOwnerDocument(props2.event.target)); +var parseEraPatterns = { + any: [/^b/i, /^(a|c)/i] +}; +var matchQuarterPatterns = { + narrow: /^[1234]/i, + abbreviated: /^q[1234]/i, + wide: /^[1234](th|st|nd|rd)? quarter/i +}; +var parseQuarterPatterns = { + any: [/1/i, /2/i, /3/i, /4/i] +}; +var matchMonthPatterns = { + narrow: /^[jfmasond]/i, + abbreviated: /^(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)/i, + wide: /^(january|february|march|april|may|june|july|august|september|october|november|december)/i +}; +var parseMonthPatterns = { + narrow: [/^j/i, /^f/i, /^m/i, /^a/i, /^m/i, /^j/i, /^j/i, /^a/i, /^s/i, /^o/i, /^n/i, /^d/i], + any: [/^ja/i, /^f/i, /^mar/i, /^ap/i, /^may/i, /^jun/i, /^jul/i, /^au/i, /^s/i, /^o/i, /^n/i, /^d/i] +}; +var matchDayPatterns = { + narrow: /^[smtwf]/i, + short: /^(su|mo|tu|we|th|fr|sa)/i, + abbreviated: /^(sun|mon|tue|wed|thu|fri|sat)/i, + wide: /^(sunday|monday|tuesday|wednesday|thursday|friday|saturday)/i +}; +var parseDayPatterns = { + narrow: [/^s/i, /^m/i, /^t/i, /^w/i, /^t/i, /^f/i, /^s/i], + any: [/^su/i, /^m/i, /^tu/i, /^w/i, /^th/i, /^f/i, /^sa/i] +}; +var matchDayPeriodPatterns = { + narrow: /^(a|p|mi|n|(in the|at) (morning|afternoon|evening|night))/i, + any: /^([ap]\.?\s?m\.?|midnight|noon|(in the|at) (morning|afternoon|evening|night))/i +}; +var parseDayPeriodPatterns = { + any: { + am: /^a/i, + pm: /^p/i, + midnight: /^mi/i, + noon: /^no/i, + morning: /morning/i, + afternoon: /afternoon/i, + evening: /evening/i, + night: /night/i } }; -MouseSensor.activators = [{ - eventName: "onMouseDown", - handler: (_ref, _ref2) => { - let { - nativeEvent: event - } = _ref; - let { - onActivation - } = _ref2; - if (event.button === MouseButton.RightClick) { - return false; +var match = { + ordinalNumber: buildMatchPatternFn({ + matchPattern: matchOrdinalNumberPattern, + parsePattern: parseOrdinalNumberPattern, + valueCallback: function valueCallback(value) { + return parseInt(value, 10); } - onActivation == null ? void 0 : onActivation({ - event - }); - return true; - } -}]; -var events$2 = { - move: { - name: "touchmove" - }, - end: { - name: "touchend" + }), + era: buildMatchFn({ + matchPatterns: matchEraPatterns, + defaultMatchWidth: "wide", + parsePatterns: parseEraPatterns, + defaultParseWidth: "any" + }), + quarter: buildMatchFn({ + matchPatterns: matchQuarterPatterns, + defaultMatchWidth: "wide", + parsePatterns: parseQuarterPatterns, + defaultParseWidth: "any", + valueCallback: function valueCallback2(index) { + return index + 1; + } + }), + month: buildMatchFn({ + matchPatterns: matchMonthPatterns, + defaultMatchWidth: "wide", + parsePatterns: parseMonthPatterns, + defaultParseWidth: "any" + }), + day: buildMatchFn({ + matchPatterns: matchDayPatterns, + defaultMatchWidth: "wide", + parsePatterns: parseDayPatterns, + defaultParseWidth: "any" + }), + dayPeriod: buildMatchFn({ + matchPatterns: matchDayPeriodPatterns, + defaultMatchWidth: "any", + parsePatterns: parseDayPeriodPatterns, + defaultParseWidth: "any" + }) +}; +var match_default = match; + +// node_modules/date-fns/esm/locale/en-US/index.js +var locale = { + code: "en-US", + formatDistance: formatDistance_default, + formatLong: formatLong_default, + formatRelative: formatRelative_default, + localize: localize_default, + match: match_default, + options: { + weekStartsOn: 0, + firstWeekContainsDate: 1 } }; -var TouchSensor = class extends AbstractPointerSensor { - constructor(props2) { - super(props2, events$2); +var en_US_default = locale; + +// node_modules/date-fns/esm/_lib/defaultLocale/index.js +var defaultLocale_default = en_US_default; + +// node_modules/date-fns/esm/format/index.js +var formattingTokensRegExp = /[yYQqMLwIdDecihHKkms]o|(\w)\1*|''|'(''|[^'])+('|$)|./g; +var longFormattingTokensRegExp = /P+p+|P+|p+|''|'(''|[^'])+('|$)|./g; +var escapedStringRegExp = /^'([^]*?)'?$/; +var doubleQuoteRegExp = /''/g; +var unescapedLatinCharacterRegExp = /[a-zA-Z]/; +function format(dirtyDate, dirtyFormatStr, options) { + var _ref, _options$locale, _ref2, _ref3, _ref4, _options$firstWeekCon, _options$locale2, _options$locale2$opti, _defaultOptions$local, _defaultOptions$local2, _ref5, _ref6, _ref7, _options$weekStartsOn, _options$locale3, _options$locale3$opti, _defaultOptions$local3, _defaultOptions$local4; + requiredArgs(2, arguments); + var formatStr = String(dirtyFormatStr); + var defaultOptions4 = getDefaultOptions(); + var locale2 = (_ref = (_options$locale = options === null || options === void 0 ? void 0 : options.locale) !== null && _options$locale !== void 0 ? _options$locale : defaultOptions4.locale) !== null && _ref !== void 0 ? _ref : defaultLocale_default; + var firstWeekContainsDate = toInteger((_ref2 = (_ref3 = (_ref4 = (_options$firstWeekCon = options === null || options === void 0 ? void 0 : options.firstWeekContainsDate) !== null && _options$firstWeekCon !== void 0 ? _options$firstWeekCon : options === null || options === void 0 ? void 0 : (_options$locale2 = options.locale) === null || _options$locale2 === void 0 ? void 0 : (_options$locale2$opti = _options$locale2.options) === null || _options$locale2$opti === void 0 ? void 0 : _options$locale2$opti.firstWeekContainsDate) !== null && _ref4 !== void 0 ? _ref4 : defaultOptions4.firstWeekContainsDate) !== null && _ref3 !== void 0 ? _ref3 : (_defaultOptions$local = defaultOptions4.locale) === null || _defaultOptions$local === void 0 ? void 0 : (_defaultOptions$local2 = _defaultOptions$local.options) === null || _defaultOptions$local2 === void 0 ? void 0 : _defaultOptions$local2.firstWeekContainsDate) !== null && _ref2 !== void 0 ? _ref2 : 1); + if (!(firstWeekContainsDate >= 1 && firstWeekContainsDate <= 7)) { + throw new RangeError("firstWeekContainsDate must be between 1 and 7 inclusively"); } - static setup() { - window.addEventListener(events$2.move.name, noop2, { - capture: false, - passive: false - }); - return function teardown() { - window.removeEventListener(events$2.move.name, noop2); - }; - function noop2() { - } + var weekStartsOn = toInteger((_ref5 = (_ref6 = (_ref7 = (_options$weekStartsOn = options === null || options === void 0 ? void 0 : options.weekStartsOn) !== null && _options$weekStartsOn !== void 0 ? _options$weekStartsOn : options === null || options === void 0 ? void 0 : (_options$locale3 = options.locale) === null || _options$locale3 === void 0 ? void 0 : (_options$locale3$opti = _options$locale3.options) === null || _options$locale3$opti === void 0 ? void 0 : _options$locale3$opti.weekStartsOn) !== null && _ref7 !== void 0 ? _ref7 : defaultOptions4.weekStartsOn) !== null && _ref6 !== void 0 ? _ref6 : (_defaultOptions$local3 = defaultOptions4.locale) === null || _defaultOptions$local3 === void 0 ? void 0 : (_defaultOptions$local4 = _defaultOptions$local3.options) === null || _defaultOptions$local4 === void 0 ? void 0 : _defaultOptions$local4.weekStartsOn) !== null && _ref5 !== void 0 ? _ref5 : 0); + if (!(weekStartsOn >= 0 && weekStartsOn <= 6)) { + throw new RangeError("weekStartsOn must be between 0 and 6 inclusively"); } -}; -TouchSensor.activators = [{ - eventName: "onTouchStart", - handler: (_ref, _ref2) => { - let { - nativeEvent: event - } = _ref; - let { - onActivation - } = _ref2; - const { - touches - } = event; - if (touches.length > 1) { - return false; - } - onActivation == null ? void 0 : onActivation({ - event - }); - return true; + if (!locale2.localize) { + throw new RangeError("locale must contain localize property"); } -}]; -var AutoScrollActivator; -(function(AutoScrollActivator2) { - AutoScrollActivator2[AutoScrollActivator2["Pointer"] = 0] = "Pointer"; - AutoScrollActivator2[AutoScrollActivator2["DraggableRect"] = 1] = "DraggableRect"; -})(AutoScrollActivator || (AutoScrollActivator = {})); -var TraversalOrder; -(function(TraversalOrder2) { - TraversalOrder2[TraversalOrder2["TreeOrder"] = 0] = "TreeOrder"; - TraversalOrder2[TraversalOrder2["ReversedTreeOrder"] = 1] = "ReversedTreeOrder"; -})(TraversalOrder || (TraversalOrder = {})); -function useAutoScroller(_ref) { - let { - acceleration, - activator = AutoScrollActivator.Pointer, - canScroll, - draggingRect, - enabled, - interval = 5, - order = TraversalOrder.TreeOrder, - pointerCoordinates, - scrollableAncestors, - scrollableAncestorRects, - delta, - threshold - } = _ref; - const scrollIntent = useScrollIntent({ - delta, - disabled: !enabled - }); - const [setAutoScrollInterval, clearAutoScrollInterval] = useInterval(); - const scrollSpeed = _2({ - x: 0, - y: 0 - }); - const scrollDirection = _2({ - x: 0, - y: 0 - }); - const rect = F2(() => { - switch (activator) { - case AutoScrollActivator.Pointer: - return pointerCoordinates ? { - top: pointerCoordinates.y, - bottom: pointerCoordinates.y, - left: pointerCoordinates.x, - right: pointerCoordinates.x - } : null; - case AutoScrollActivator.DraggableRect: - return draggingRect; - } - }, [activator, draggingRect, pointerCoordinates]); - const scrollContainerRef = _2(null); - const autoScroll = T2(() => { - const scrollContainer = scrollContainerRef.current; - if (!scrollContainer) { - return; - } - const scrollLeft = scrollSpeed.current.x * scrollDirection.current.x; - const scrollTop = scrollSpeed.current.y * scrollDirection.current.y; - scrollContainer.scrollBy(scrollLeft, scrollTop); - }, []); - const sortedScrollableAncestors = F2(() => order === TraversalOrder.TreeOrder ? [...scrollableAncestors].reverse() : scrollableAncestors, [order, scrollableAncestors]); - p2( - () => { - if (!enabled || !scrollableAncestors.length || !rect) { - clearAutoScrollInterval(); - return; - } - for (const scrollContainer of sortedScrollableAncestors) { - if ((canScroll == null ? void 0 : canScroll(scrollContainer)) === false) { - continue; - } - const index = scrollableAncestors.indexOf(scrollContainer); - const scrollContainerRect = scrollableAncestorRects[index]; - if (!scrollContainerRect) { - continue; - } - const { - direction, - speed - } = getScrollDirectionAndSpeed(scrollContainer, scrollContainerRect, rect, acceleration, threshold); - for (const axis of ["x", "y"]) { - if (!scrollIntent[axis][direction[axis]]) { - speed[axis] = 0; - direction[axis] = 0; - } - } - if (speed.x > 0 || speed.y > 0) { - clearAutoScrollInterval(); - scrollContainerRef.current = scrollContainer; - setAutoScrollInterval(autoScroll, interval); - scrollSpeed.current = speed; - scrollDirection.current = direction; - return; - } - } - scrollSpeed.current = { - x: 0, - y: 0 - }; - scrollDirection.current = { - x: 0, - y: 0 - }; - clearAutoScrollInterval(); - }, - [ - acceleration, - autoScroll, - canScroll, - clearAutoScrollInterval, - enabled, - interval, - JSON.stringify(rect), - JSON.stringify(scrollIntent), - setAutoScrollInterval, - scrollableAncestors, - sortedScrollableAncestors, - scrollableAncestorRects, - JSON.stringify(threshold) - ] - ); -} -var defaultScrollIntent = { - x: { - [Direction2.Backward]: false, - [Direction2.Forward]: false - }, - y: { - [Direction2.Backward]: false, - [Direction2.Forward]: false + if (!locale2.formatLong) { + throw new RangeError("locale must contain formatLong property"); } -}; -function useScrollIntent(_ref2) { - let { - delta, - disabled - } = _ref2; - const previousDelta = usePrevious(delta); - return useLazyMemo((previousIntent) => { - if (disabled || !previousDelta || !previousIntent) { - return defaultScrollIntent; - } - const direction = { - x: Math.sign(delta.x - previousDelta.x), - y: Math.sign(delta.y - previousDelta.y) - }; - return { - x: { - [Direction2.Backward]: previousIntent.x[Direction2.Backward] || direction.x === -1, - [Direction2.Forward]: previousIntent.x[Direction2.Forward] || direction.x === 1 - }, - y: { - [Direction2.Backward]: previousIntent.y[Direction2.Backward] || direction.y === -1, - [Direction2.Forward]: previousIntent.y[Direction2.Forward] || direction.y === 1 - } - }; - }, [disabled, delta, previousDelta]); -} -function useCachedNode(draggableNodes, id2) { - const draggableNode = id2 !== null ? draggableNodes.get(id2) : void 0; - const node = draggableNode ? draggableNode.node.current : null; - return useLazyMemo((cachedNode) => { - var _ref; - if (id2 === null) { - return null; + var originalDate = toDate(dirtyDate); + if (!isValid(originalDate)) { + throw new RangeError("Invalid time value"); + } + var timezoneOffset = getTimezoneOffsetInMilliseconds(originalDate); + var utcDate = subMilliseconds(originalDate, timezoneOffset); + var formatterOptions = { + firstWeekContainsDate, + weekStartsOn, + locale: locale2, + _originalDate: originalDate + }; + var result = formatStr.match(longFormattingTokensRegExp).map(function(substring) { + var firstCharacter = substring[0]; + if (firstCharacter === "p" || firstCharacter === "P") { + var longFormatter = longFormatters_default[firstCharacter]; + return longFormatter(substring, locale2.formatLong); } - return (_ref = node != null ? node : cachedNode) != null ? _ref : null; - }, [node, id2]); -} -function useCombineActivators(sensors, getSyntheticHandler) { - return F2(() => sensors.reduce((accumulator, sensor) => { - const { - sensor: Sensor - } = sensor; - const sensorActivators = Sensor.activators.map((activator) => ({ - eventName: activator.eventName, - handler: getSyntheticHandler(activator.handler, sensor) - })); - return [...accumulator, ...sensorActivators]; - }, []), [sensors, getSyntheticHandler]); -} -var MeasuringStrategy; -(function(MeasuringStrategy2) { - MeasuringStrategy2[MeasuringStrategy2["Always"] = 0] = "Always"; - MeasuringStrategy2[MeasuringStrategy2["BeforeDragging"] = 1] = "BeforeDragging"; - MeasuringStrategy2[MeasuringStrategy2["WhileDragging"] = 2] = "WhileDragging"; -})(MeasuringStrategy || (MeasuringStrategy = {})); -var MeasuringFrequency; -(function(MeasuringFrequency2) { - MeasuringFrequency2["Optimized"] = "optimized"; -})(MeasuringFrequency || (MeasuringFrequency = {})); -var defaultValue = /* @__PURE__ */ new Map(); -function useDroppableMeasuring(containers, _ref) { - let { - dragging, - dependencies, - config - } = _ref; - const [queue, setQueue] = h2(null); - const { - frequency, - measure, - strategy - } = config; - const containersRef = _2(containers); - const disabled = isDisabled(); - const disabledRef = useLatestValue(disabled); - const measureDroppableContainers = T2(function(ids2) { - if (ids2 === void 0) { - ids2 = []; + return substring; + }).join("").match(formattingTokensRegExp).map(function(substring) { + if (substring === "''") { + return "'"; } - if (disabledRef.current) { - return; + var firstCharacter = substring[0]; + if (firstCharacter === "'") { + return cleanEscapedString(substring); } - setQueue((value) => { - if (value === null) { - return ids2; + var formatter = formatters_default[firstCharacter]; + if (formatter) { + if (!(options !== null && options !== void 0 && options.useAdditionalWeekYearTokens) && isProtectedWeekYearToken(substring)) { + throwProtectedError(substring, dirtyFormatStr, String(dirtyDate)); } - return value.concat(ids2.filter((id2) => !value.includes(id2))); - }); - }, [disabledRef]); - const timeoutId = _2(null); - const droppableRects = useLazyMemo((previousValue) => { - if (disabled && !dragging) { - return defaultValue; - } - if (!previousValue || previousValue === defaultValue || containersRef.current !== containers || queue != null) { - const map = /* @__PURE__ */ new Map(); - for (let container of containers) { - if (!container) { - continue; - } - if (queue && queue.length > 0 && !queue.includes(container.id) && container.rect.current) { - map.set(container.id, container.rect.current); - continue; - } - const node = container.node.current; - const rect = node ? new Rect(measure(node), node) : null; - container.rect.current = rect; - if (rect) { - map.set(container.id, rect); - } + if (!(options !== null && options !== void 0 && options.useAdditionalDayOfYearTokens) && isProtectedDayOfYearToken(substring)) { + throwProtectedError(substring, dirtyFormatStr, String(dirtyDate)); } - return map; + return formatter(utcDate, substring, locale2.localize, formatterOptions); } - return previousValue; - }, [containers, queue, dragging, disabled, measure]); - p2(() => { - containersRef.current = containers; - }, [containers]); - p2( - () => { - if (disabled) { - return; - } - measureDroppableContainers(); - }, - [dragging, disabled] - ); - p2( - () => { - if (queue && queue.length > 0) { - setQueue(null); - } - }, - [JSON.stringify(queue)] - ); - p2( - () => { - if (disabled || typeof frequency !== "number" || timeoutId.current !== null) { - return; - } - timeoutId.current = setTimeout(() => { - measureDroppableContainers(); - timeoutId.current = null; - }, frequency); - }, - [frequency, disabled, measureDroppableContainers, ...dependencies] - ); - return { - droppableRects, - measureDroppableContainers, - measuringScheduled: queue != null - }; - function isDisabled() { - switch (strategy) { - case MeasuringStrategy.Always: - return false; - case MeasuringStrategy.BeforeDragging: - return dragging; - default: - return !dragging; + if (firstCharacter.match(unescapedLatinCharacterRegExp)) { + throw new RangeError("Format string contains an unescaped latin alphabet character `" + firstCharacter + "`"); } + return substring; + }).join(""); + return result; +} +function cleanEscapedString(input) { + var matched = input.match(escapedStringRegExp); + if (!matched) { + return input; } + return matched[1].replace(doubleQuoteRegExp, "'"); } -function useInitialValue(value, computeFn) { - return useLazyMemo((previousValue) => { - if (!value) { - return null; - } - if (previousValue) { - return previousValue; + +// node_modules/date-fns/esm/_lib/assign/index.js +function assign(target, object) { + if (target == null) { + throw new TypeError("assign requires that input parameter not be null or undefined"); + } + for (var property in object) { + if (Object.prototype.hasOwnProperty.call(object, property)) { + ; + target[property] = object[property]; } - return typeof computeFn === "function" ? computeFn(value) : value; - }, [computeFn, value]); + } + return target; } -function useInitialRect(node, measure) { - return useInitialValue(node, measure); + +// node_modules/date-fns/esm/_lib/cloneObject/index.js +function cloneObject(object) { + return assign({}, object); } -function useMutationObserver(_ref) { - let { - callback, - disabled - } = _ref; - const handleMutations = useEvent(callback); - const mutationObserver = F2(() => { - if (disabled || typeof window === "undefined" || typeof window.MutationObserver === "undefined") { - return void 0; + +// node_modules/date-fns/esm/formatDistance/index.js +var MINUTES_IN_DAY = 1440; +var MINUTES_IN_ALMOST_TWO_DAYS = 2520; +var MINUTES_IN_MONTH = 43200; +var MINUTES_IN_TWO_MONTHS = 86400; +function formatDistance3(dirtyDate, dirtyBaseDate, options) { + var _ref, _options$locale; + requiredArgs(2, arguments); + var defaultOptions4 = getDefaultOptions(); + var locale2 = (_ref = (_options$locale = options === null || options === void 0 ? void 0 : options.locale) !== null && _options$locale !== void 0 ? _options$locale : defaultOptions4.locale) !== null && _ref !== void 0 ? _ref : defaultLocale_default; + if (!locale2.formatDistance) { + throw new RangeError("locale must contain formatDistance property"); + } + var comparison = compareAsc(dirtyDate, dirtyBaseDate); + if (isNaN(comparison)) { + throw new RangeError("Invalid time value"); + } + var localizeOptions = assign(cloneObject(options), { + addSuffix: Boolean(options === null || options === void 0 ? void 0 : options.addSuffix), + comparison + }); + var dateLeft; + var dateRight; + if (comparison > 0) { + dateLeft = toDate(dirtyBaseDate); + dateRight = toDate(dirtyDate); + } else { + dateLeft = toDate(dirtyDate); + dateRight = toDate(dirtyBaseDate); + } + var seconds = differenceInSeconds(dateRight, dateLeft); + var offsetInSeconds = (getTimezoneOffsetInMilliseconds(dateRight) - getTimezoneOffsetInMilliseconds(dateLeft)) / 1e3; + var minutes = Math.round((seconds - offsetInSeconds) / 60); + var months; + if (minutes < 2) { + if (options !== null && options !== void 0 && options.includeSeconds) { + if (seconds < 5) { + return locale2.formatDistance("lessThanXSeconds", 5, localizeOptions); + } else if (seconds < 10) { + return locale2.formatDistance("lessThanXSeconds", 10, localizeOptions); + } else if (seconds < 20) { + return locale2.formatDistance("lessThanXSeconds", 20, localizeOptions); + } else if (seconds < 40) { + return locale2.formatDistance("halfAMinute", 0, localizeOptions); + } else if (seconds < 60) { + return locale2.formatDistance("lessThanXMinutes", 1, localizeOptions); + } else { + return locale2.formatDistance("xMinutes", 1, localizeOptions); + } + } else { + if (minutes === 0) { + return locale2.formatDistance("lessThanXMinutes", 1, localizeOptions); + } else { + return locale2.formatDistance("xMinutes", minutes, localizeOptions); + } } - const { - MutationObserver - } = window; - return new MutationObserver(handleMutations); - }, [handleMutations, disabled]); - p2(() => { - return () => mutationObserver == null ? void 0 : mutationObserver.disconnect(); - }, [mutationObserver]); - return mutationObserver; + } else if (minutes < 45) { + return locale2.formatDistance("xMinutes", minutes, localizeOptions); + } else if (minutes < 90) { + return locale2.formatDistance("aboutXHours", 1, localizeOptions); + } else if (minutes < MINUTES_IN_DAY) { + var hours = Math.round(minutes / 60); + return locale2.formatDistance("aboutXHours", hours, localizeOptions); + } else if (minutes < MINUTES_IN_ALMOST_TWO_DAYS) { + return locale2.formatDistance("xDays", 1, localizeOptions); + } else if (minutes < MINUTES_IN_MONTH) { + var days = Math.round(minutes / MINUTES_IN_DAY); + return locale2.formatDistance("xDays", days, localizeOptions); + } else if (minutes < MINUTES_IN_TWO_MONTHS) { + months = Math.round(minutes / MINUTES_IN_MONTH); + return locale2.formatDistance("aboutXMonths", months, localizeOptions); + } + months = differenceInMonths(dateRight, dateLeft); + if (months < 12) { + var nearestMonth = Math.round(minutes / MINUTES_IN_MONTH); + return locale2.formatDistance("xMonths", nearestMonth, localizeOptions); + } else { + var monthsSinceStartOfYear = months % 12; + var years = Math.floor(months / 12); + if (monthsSinceStartOfYear < 3) { + return locale2.formatDistance("aboutXYears", years, localizeOptions); + } else if (monthsSinceStartOfYear < 9) { + return locale2.formatDistance("overXYears", years, localizeOptions); + } else { + return locale2.formatDistance("almostXYears", years + 1, localizeOptions); + } + } } -function useResizeObserver(_ref) { - let { - callback, - disabled - } = _ref; - const handleResize = useEvent(callback); - const resizeObserver = F2( - () => { - if (disabled || typeof window === "undefined" || typeof window.ResizeObserver === "undefined") { - return void 0; - } - const { - ResizeObserver - } = window; - return new ResizeObserver(handleResize); - }, - [disabled] - ); - p2(() => { - return () => resizeObserver == null ? void 0 : resizeObserver.disconnect(); - }, [resizeObserver]); - return resizeObserver; + +// node_modules/date-fns/esm/getDaysInMonth/index.js +function getDaysInMonth(dirtyDate) { + requiredArgs(1, arguments); + var date = toDate(dirtyDate); + var year = date.getFullYear(); + var monthIndex = date.getMonth(); + var lastDayOfMonth2 = new Date(0); + lastDayOfMonth2.setFullYear(year, monthIndex + 1, 0); + lastDayOfMonth2.setHours(0, 0, 0, 0); + return lastDayOfMonth2.getDate(); } -function defaultMeasure(element) { - return new Rect(getClientRect(element), element); + +// node_modules/date-fns/esm/getISOWeek/index.js +var MILLISECONDS_IN_WEEK4 = 6048e5; +function getISOWeek(dirtyDate) { + requiredArgs(1, arguments); + var date = toDate(dirtyDate); + var diff = startOfISOWeek(date).getTime() - startOfISOWeekYear(date).getTime(); + return Math.round(diff / MILLISECONDS_IN_WEEK4) + 1; } -function useRect(element, measure, fallbackRect) { - if (measure === void 0) { - measure = defaultMeasure; + +// node_modules/date-fns/esm/getTime/index.js +function getTime(dirtyDate) { + requiredArgs(1, arguments); + var date = toDate(dirtyDate); + var timestamp = date.getTime(); + return timestamp; +} + +// node_modules/date-fns/esm/getUnixTime/index.js +function getUnixTime(dirtyDate) { + requiredArgs(1, arguments); + return Math.floor(getTime(dirtyDate) / 1e3); +} + +// node_modules/date-fns/esm/getWeekYear/index.js +function getWeekYear(dirtyDate, options) { + var _ref, _ref2, _ref3, _options$firstWeekCon, _options$locale, _options$locale$optio, _defaultOptions$local, _defaultOptions$local2; + requiredArgs(1, arguments); + var date = toDate(dirtyDate); + var year = date.getFullYear(); + var defaultOptions4 = getDefaultOptions(); + var firstWeekContainsDate = toInteger((_ref = (_ref2 = (_ref3 = (_options$firstWeekCon = options === null || options === void 0 ? void 0 : options.firstWeekContainsDate) !== null && _options$firstWeekCon !== void 0 ? _options$firstWeekCon : options === null || options === void 0 ? void 0 : (_options$locale = options.locale) === null || _options$locale === void 0 ? void 0 : (_options$locale$optio = _options$locale.options) === null || _options$locale$optio === void 0 ? void 0 : _options$locale$optio.firstWeekContainsDate) !== null && _ref3 !== void 0 ? _ref3 : defaultOptions4.firstWeekContainsDate) !== null && _ref2 !== void 0 ? _ref2 : (_defaultOptions$local = defaultOptions4.locale) === null || _defaultOptions$local === void 0 ? void 0 : (_defaultOptions$local2 = _defaultOptions$local.options) === null || _defaultOptions$local2 === void 0 ? void 0 : _defaultOptions$local2.firstWeekContainsDate) !== null && _ref !== void 0 ? _ref : 1); + if (!(firstWeekContainsDate >= 1 && firstWeekContainsDate <= 7)) { + throw new RangeError("firstWeekContainsDate must be between 1 and 7 inclusively"); } - const [rect, measureRect] = s2(reducer2, null); - const mutationObserver = useMutationObserver({ - callback(records) { - if (!element) { - return; - } - for (const record of records) { - const { - type, - target - } = record; - if (type === "childList" && target instanceof HTMLElement && target.contains(element)) { - measureRect(); - break; - } - } - } - }); - const resizeObserver = useResizeObserver({ - callback: measureRect - }); - useIsomorphicLayoutEffect(() => { - measureRect(); - if (element) { - resizeObserver == null ? void 0 : resizeObserver.observe(element); - mutationObserver == null ? void 0 : mutationObserver.observe(document.body, { - childList: true, - subtree: true + var firstWeekOfNextYear = new Date(0); + firstWeekOfNextYear.setFullYear(year + 1, 0, firstWeekContainsDate); + firstWeekOfNextYear.setHours(0, 0, 0, 0); + var startOfNextYear = startOfWeek(firstWeekOfNextYear, options); + var firstWeekOfThisYear = new Date(0); + firstWeekOfThisYear.setFullYear(year, 0, firstWeekContainsDate); + firstWeekOfThisYear.setHours(0, 0, 0, 0); + var startOfThisYear = startOfWeek(firstWeekOfThisYear, options); + if (date.getTime() >= startOfNextYear.getTime()) { + return year + 1; + } else if (date.getTime() >= startOfThisYear.getTime()) { + return year; + } else { + return year - 1; + } +} + +// node_modules/date-fns/esm/startOfWeekYear/index.js +function startOfWeekYear(dirtyDate, options) { + var _ref, _ref2, _ref3, _options$firstWeekCon, _options$locale, _options$locale$optio, _defaultOptions$local, _defaultOptions$local2; + requiredArgs(1, arguments); + var defaultOptions4 = getDefaultOptions(); + var firstWeekContainsDate = toInteger((_ref = (_ref2 = (_ref3 = (_options$firstWeekCon = options === null || options === void 0 ? void 0 : options.firstWeekContainsDate) !== null && _options$firstWeekCon !== void 0 ? _options$firstWeekCon : options === null || options === void 0 ? void 0 : (_options$locale = options.locale) === null || _options$locale === void 0 ? void 0 : (_options$locale$optio = _options$locale.options) === null || _options$locale$optio === void 0 ? void 0 : _options$locale$optio.firstWeekContainsDate) !== null && _ref3 !== void 0 ? _ref3 : defaultOptions4.firstWeekContainsDate) !== null && _ref2 !== void 0 ? _ref2 : (_defaultOptions$local = defaultOptions4.locale) === null || _defaultOptions$local === void 0 ? void 0 : (_defaultOptions$local2 = _defaultOptions$local.options) === null || _defaultOptions$local2 === void 0 ? void 0 : _defaultOptions$local2.firstWeekContainsDate) !== null && _ref !== void 0 ? _ref : 1); + var year = getWeekYear(dirtyDate, options); + var firstWeek = new Date(0); + firstWeek.setFullYear(year, 0, firstWeekContainsDate); + firstWeek.setHours(0, 0, 0, 0); + var date = startOfWeek(firstWeek, options); + return date; +} + +// node_modules/date-fns/esm/getWeek/index.js +var MILLISECONDS_IN_WEEK5 = 6048e5; +function getWeek(dirtyDate, options) { + requiredArgs(1, arguments); + var date = toDate(dirtyDate); + var diff = startOfWeek(date, options).getTime() - startOfWeekYear(date, options).getTime(); + return Math.round(diff / MILLISECONDS_IN_WEEK5) + 1; +} + +// node_modules/date-fns/esm/lastDayOfMonth/index.js +function lastDayOfMonth(dirtyDate) { + requiredArgs(1, arguments); + var date = toDate(dirtyDate); + var month = date.getMonth(); + date.setFullYear(date.getFullYear(), month + 1, 0); + date.setHours(0, 0, 0, 0); + return date; +} + +// node_modules/date-fns/esm/getWeeksInMonth/index.js +function getWeeksInMonth(date, options) { + requiredArgs(1, arguments); + return differenceInCalendarWeeks(lastDayOfMonth(date), startOfMonth(date), options) + 1; +} + +// node_modules/date-fns/esm/isAfter/index.js +function isAfter2(dirtyDate, dirtyDateToCompare) { + requiredArgs(2, arguments); + var date = toDate(dirtyDate); + var dateToCompare = toDate(dirtyDateToCompare); + return date.getTime() > dateToCompare.getTime(); +} + +// node_modules/date-fns/esm/isBefore/index.js +function isBefore(dirtyDate, dirtyDateToCompare) { + requiredArgs(2, arguments); + var date = toDate(dirtyDate); + var dateToCompare = toDate(dirtyDateToCompare); + return date.getTime() < dateToCompare.getTime(); +} + +// node_modules/date-fns/esm/isSameMonth/index.js +function isSameMonth(dirtyDateLeft, dirtyDateRight) { + requiredArgs(2, arguments); + var dateLeft = toDate(dirtyDateLeft); + var dateRight = toDate(dirtyDateRight); + return dateLeft.getFullYear() === dateRight.getFullYear() && dateLeft.getMonth() === dateRight.getMonth(); +} + +// node_modules/date-fns/esm/isSameYear/index.js +function isSameYear(dirtyDateLeft, dirtyDateRight) { + requiredArgs(2, arguments); + var dateLeft = toDate(dirtyDateLeft); + var dateRight = toDate(dirtyDateRight); + return dateLeft.getFullYear() === dateRight.getFullYear(); +} + +// node_modules/date-fns/esm/subDays/index.js +function subDays(dirtyDate, dirtyAmount) { + requiredArgs(2, arguments); + var amount = toInteger(dirtyAmount); + return addDays(dirtyDate, -amount); +} + +// node_modules/date-fns/esm/setMonth/index.js +function setMonth(dirtyDate, dirtyMonth) { + requiredArgs(2, arguments); + var date = toDate(dirtyDate); + var month = toInteger(dirtyMonth); + var year = date.getFullYear(); + var day = date.getDate(); + var dateWithDesiredMonth = new Date(0); + dateWithDesiredMonth.setFullYear(year, month, 15); + dateWithDesiredMonth.setHours(0, 0, 0, 0); + var daysInMonth = getDaysInMonth(dateWithDesiredMonth); + date.setMonth(month, Math.min(day, daysInMonth)); + return date; +} + +// node_modules/date-fns/esm/setYear/index.js +function setYear(dirtyDate, dirtyYear) { + requiredArgs(2, arguments); + var date = toDate(dirtyDate); + var year = toInteger(dirtyYear); + if (isNaN(date.getTime())) { + return new Date(NaN); + } + date.setFullYear(year); + return date; +} + +// src/utils/metadata/frontmatter/fm.ts +var import_lodash2 = __toESM(require_lodash()); +var import_obsidian12 = require("obsidian"); + +// src/utils/metadata/dv.ts +var import_obsidian11 = require("obsidian"); +var LocationWrapper = { + fullLine: { start: "", end: "" }, + brackets: { start: "[", end: "]" }, + parenthesis: { start: "(", end: ")" } +}; +var fieldComponents = [ + "inQuote", + "inList", + "startStyle", + "attribute", + "endStyle", + "beforeSeparatorSpacer", + "afterSeparatorSpacer", + "values" +]; +var genericFieldRegex = "(?>(\\s+)?)?(?- )?(?[_\\*~`]*)(?[0-9\\w\\p{Letter}\\p{Emoji_Presentation}][-0-9\\w\\p{Letter}\\p{Emoji_Presentation}\\s]*)(?[_\\*~`]*)(?\\s*)"; +var inlineFieldRegex = (attribute) => `(?>(\\s+)?)?(?- )?(?[_\\*~\`]*)(?${attribute})(?[_\\*~\`]*)(?\\s*)::(?\\s*)`; +var fullLineRegex = new RegExp( + `^${genericFieldRegex}::\\s*(?.*)?`, + "u" +); +var inSentenceRegexBrackets = new RegExp( + `\\[${genericFieldRegex}::\\s*(?[^\\]]+)?\\]`, + "gu" +); +var inSentenceRegexPar = new RegExp( + `\\(${genericFieldRegex}::\\s*(?[^\\)]+)?\\)`, + "gu" +); +var encodeLink = (value) => { + return value ? value.replace(/\[\[/g, "\u{1F54C}\u{1F527}").replace(/\]\]/g, "\u{1F413}\u{1F400}") : value; +}; +var decodeLink = (value) => { + return value ? value.replace(/🕌🔧/gu, "[[").replace(/🐓🐀/gu, "]]") : value; +}; +var matchInlineFields = (regex, line, attribute, input, location = "fullLine") => { + const sR = line.matchAll(regex); + let next = sR.next(); + const newFields = []; + while (!next.done) { + const match2 = next.value; + if (match2.groups && Object.keys(match2.groups).every((j4) => fieldComponents.includes(j4))) { + const { + inList, + inQuote, + startStyle, + endStyle, + beforeSeparatorSpacer, + afterSeparatorSpacer, + values + } = match2.groups; + const inputArray = input ? input.replace(/(\,\s+)/g, ",").split(",") : [""]; + const newValue = inputArray.length == 1 ? inputArray[0] : `${serializeMultiDisplayString(inputArray)}`; + const start = LocationWrapper[location].start; + const end = LocationWrapper[location].end; + newFields.push({ + oldField: match2[0], + newField: `${inQuote || ""}${start}${inList || ""}${startStyle}${attribute}${endStyle}${beforeSeparatorSpacer}::${afterSeparatorSpacer}${newValue}${end}` }); - } else { - resizeObserver == null ? void 0 : resizeObserver.disconnect(); - mutationObserver == null ? void 0 : mutationObserver.disconnect(); - } - }, [element]); - return rect; - function reducer2(currentRect) { - if (!element) { - return null; } - if (element.isConnected === false) { - var _ref; - return (_ref = currentRect != null ? currentRect : fallbackRect) != null ? _ref : null; + next = sR.next(); + } + return newFields; +}; +async function replaceValues(plugin, fileOrFilePath, attribute, input, previousItemsCount = 0) { + var _a2, _b2; + let file; + if (fileOrFilePath instanceof import_obsidian11.TFile) { + file = fileOrFilePath; + } else { + const _file = plugin.app.vault.getAbstractFileByPath(fileOrFilePath); + if (_file instanceof import_obsidian11.TFile && _file.extension == "md") { + file = _file; + } else { + throw Error("path doesn't correspond to a proper file"); } - const newRect = measure(element); - if (JSON.stringify(currentRect) === JSON.stringify(newRect)) { - return currentRect; + } + const content = (await plugin.app.vault.read(file)).split("\n"); + const frontmatter = (_a2 = plugin.app.metadataCache.getFileCache(file)) == null ? void 0 : _a2.frontmatter; + const skippedLines = []; + const { + position: { start, end } + } = frontmatter ? frontmatter : { position: { start: void 0, end: void 0 } }; + const newContent = content.map((line, i4) => { + const encodedInput = encodeLink(input); + let encodedLine = encodeLink(line); + const fullLineRegex2 = new RegExp( + `^${inlineFieldRegex(attribute)}(?[^\\]]*)`, + "u" + ); + const fR = encodedLine.match(fullLineRegex2); + if ((fR == null ? void 0 : fR.groups) && Object.keys(fR.groups).every((j4) => fieldComponents.includes(j4))) { + const { + inList, + inQuote, + startStyle, + endStyle, + beforeSeparatorSpacer, + afterSeparatorSpacer, + values + } = fR.groups; + const inputArray = input ? input.replace(/(\,\s+)/g, ",").split(",").sort() : []; + const hiddenValue = ""; + const newValue = inputArray.length == 1 ? inputArray[0] : `${serializeMultiDisplayString(inputArray)}`; + return `${inQuote || ""}${inList || ""}${startStyle}${attribute}${endStyle}${beforeSeparatorSpacer}::${afterSeparatorSpacer}${hiddenValue + newValue}`; + } else { + const newFields = []; + const inSentenceRegexBrackets2 = new RegExp( + `\\[${inlineFieldRegex(attribute)}(?[^\\]]+)?\\]`, + "gu" + ); + const inSentenceRegexPar2 = new RegExp( + `\\(${inlineFieldRegex(attribute)}(?[^\\)]+)?\\)`, + "gu" + ); + newFields.push( + ...matchInlineFields( + inSentenceRegexBrackets2, + encodedLine, + attribute, + encodedInput, + "brackets" /* brackets */ + ) + ); + newFields.push( + ...matchInlineFields( + inSentenceRegexPar2, + encodedLine, + attribute, + encodedInput, + "parenthesis" /* parenthesis */ + ) + ); + newFields.forEach((field) => { + const fieldRegex = new RegExp( + field.oldField.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"), + "u" + ); + encodedLine = encodedLine.replace(fieldRegex, field.newField); + }); + return decodeLink(encodedLine); } - return newRect; + }); + await plugin.app.vault.modify( + file, + newContent.filter((line, i4) => !skippedLines.includes(i4)).join("\n") + ); + const editor = (_b2 = plugin.app.workspace.getActiveViewOfType(import_obsidian11.MarkdownView)) == null ? void 0 : _b2.editor; + if (editor) { + const lineNumber = editor.getCursor().line; + editor.setCursor({ + line: editor.getCursor().line, + ch: editor.getLine(lineNumber).length + }); } } -function useRectDelta(rect) { - const initialRect = useInitialValue(rect); - return getRectDelta(rect, initialRect); -} -var defaultValue$1 = []; -function useScrollableAncestors(node) { - const previousNode = _2(node); - const ancestors = useLazyMemo((previousValue) => { - if (!node) { - return defaultValue$1; + +// src/utils/metadata/frontmatter/detectYAMLType.ts +var detectYAMLType = (value, key2) => { + if (typeof value === "string") { + if (/\/\/(\S+?(?:jpe?g|png|gif|svg))/gi.test(value) || value.includes("unsplash")) { + return "image"; } - if (previousValue && previousValue !== defaultValue$1 && node && previousNode.current && node.parentNode === previousNode.current.parentNode) { - return previousValue; + if (/^\d{4}-\d{2}-\d{2}$/.test(value)) { + return "date"; } - return getScrollableAncestors(node); - }, [node]); - p2(() => { - previousNode.current = node; - }, [node]); - return ancestors; -} -function useScrollOffsets(elements) { - const [scrollCoordinates, setScrollCoordinates] = h2(null); - const prevElements = _2(elements); - const handleScroll = T2((event) => { - const scrollingElement = getScrollableElement(event.target); - if (!scrollingElement) { - return; + if (key2 == "tag" || key2 == "tags") { + return "tag"; } - setScrollCoordinates((scrollCoordinates2) => { - if (!scrollCoordinates2) { - return null; - } - scrollCoordinates2.set(scrollingElement, getScrollCoordinates(scrollingElement)); - return new Map(scrollCoordinates2); - }); - }, []); - p2(() => { - const previousElements = prevElements.current; - if (elements !== previousElements) { - cleanup(previousElements); - const entries = elements.map((element) => { - const scrollableElement = getScrollableElement(element); - if (scrollableElement) { - scrollableElement.addEventListener("scroll", handleScroll, { - passive: true - }); - return [scrollableElement, getScrollCoordinates(scrollableElement)]; - } - return null; - }).filter((entry) => entry != null); - setScrollCoordinates(entries.length ? new Map(entries) : null); - prevElements.current = elements; + if (/\[\[.*?\]\]/.test(value)) { + return "link"; } - return () => { - cleanup(elements); - cleanup(previousElements); - }; - function cleanup(elements2) { - elements2.forEach((element) => { - const scrollableElement = getScrollableElement(element); - scrollableElement == null ? void 0 : scrollableElement.removeEventListener("scroll", handleScroll); - }); + } else if (typeof value === "number") { + return "number"; + } else if (typeof value === "boolean") { + return "boolean"; + } else if (!value) { + return "unknown"; + } else if (Array.isArray(value) || typeof value === "string" && value.indexOf(",") > -1) { + let arrayValue = Array.isArray(value) ? value : []; + if (typeof value === "string" && value.indexOf(",") > -1) { + arrayValue = parseMultiString(value); } - }, [handleScroll, elements]); - return F2(() => { - if (elements.length) { - return scrollCoordinates ? Array.from(scrollCoordinates.values()).reduce((acc, coordinates) => add(acc, coordinates), defaultCoordinates) : getScrollOffsets(elements); + if (key2 == "tag" || key2 == "tags") { + return "tag-multi"; } - return defaultCoordinates; - }, [elements, scrollCoordinates]); -} -function useScrollOffsetsDelta(scrollOffsets, dependencies) { - if (dependencies === void 0) { - dependencies = []; - } - const initialScrollOffsets = _2(null); - p2( - () => { - initialScrollOffsets.current = null; - }, - dependencies - ); - p2(() => { - const hasScrollOffsets = scrollOffsets !== defaultCoordinates; - if (hasScrollOffsets && !initialScrollOffsets.current) { - initialScrollOffsets.current = scrollOffsets; + if (arrayValue.length == 1 && Array.isArray(arrayValue[0]) && arrayValue[0].length == 1 && typeof arrayValue[0][0] === "string") { + return "link"; } - if (!hasScrollOffsets && initialScrollOffsets.current) { - initialScrollOffsets.current = null; + const types2 = uniq(arrayValue.map((f4) => detectYAMLType(f4, key2))); + if (types2.length == 1 && types2[0] == "link") { + return "link-multi"; } - }, [scrollOffsets]); - return initialScrollOffsets.current ? subtract(scrollOffsets, initialScrollOffsets.current) : defaultCoordinates; -} -function useSensorSetup(sensors) { - p2( - () => { - if (!canUseDOM) { - return; - } - const teardownFns = sensors.map((_ref) => { - let { - sensor - } = _ref; - return sensor.setup == null ? void 0 : sensor.setup(); + return "option-multi"; + } else if (value.isLuxonDateTime) { + return "date"; + } else if (value.isLuxonDuration) { + return "duration"; + } else if (value.type == "file") { + return "link"; + } else if (typeof value === "object" && !Array.isArray(value) && value !== null) { + return "object"; + } + return "text"; +}; + +// src/utils/metadata/frontmatter/frontMatterKeys.ts +var frontMatterKeys = (fm) => { + return Object.keys(fm != null ? fm : {}).filter((f4) => f4 != "position").filter((f4) => f4 != "tag" && f4 != "tags"); +}; + +// src/utils/metadata/frontmatter/yamlTypeToMDBType.ts +var yamlTypeToMDBType = (YAMLtype) => { + switch (YAMLtype) { + case "duration": + return "text"; + break; + case "unknown": + return "text"; + break; + } + return YAMLtype; +}; + +// src/utils/metadata/frontmatter/fm.ts +var saveContextToFile = (file, cols, context, plugin) => { + if (plugin.metadata.canProcessFrontmatter()) { + plugin.metadata.processFrontMatter(file.path, (frontmatter) => { + Object.keys(context).filter( + (f4) => cols.find((c4) => c4.name == f4) && cols.find((c4) => c4.name == f4).hidden != "true" && !cols.find((c4) => c4.name == f4).type.contains("file") && context[f4] + ).forEach((f4) => { + const col = cols.find((c4) => c4.name == f4); + frontmatter[f4] = valueForFrontmatter(col.type, context[f4]); + frontmatter[f4] = valueForFrontmatter(col.type, context[f4]); }); - return () => { - for (const teardown of teardownFns) { - teardown == null ? void 0 : teardown(); - } - }; + }); + } +}; +var frontMatterForFile = (plugin, file) => { + let currentCache; + if (file instanceof import_obsidian12.TFile && plugin.app.metadataCache.getFileCache(file) !== null) { + currentCache = plugin.app.metadataCache.getFileCache(file); + } + return currentCache == null ? void 0 : currentCache.frontmatter; +}; +var guestimateTypes = (_files, plugin, dv) => { + const typesArray = _files.map((f4) => getAbstractFileAtPath(plugin, f4)).filter((f4) => f4).map((k5) => { + const fm = dv && plugin.dataViewAPI() ? plugin.dataViewAPI().page(k5.path) : frontMatterForFile(plugin, k5); + const fmKeys = dv ? Object.keys(fm != null ? fm : {}).filter( + (f4, i4, self2) => !self2.find( + (g4, j4) => g4.toLowerCase().replace(/\s/g, "-") == f4.toLowerCase().replace(/\s/g, "-") && i4 > j4 + ) ? true : false + ).filter((f4) => f4 != "file") : frontMatterKeys(fm); + return fmKeys.reduce( + (pk, ck) => ({ ...pk, [ck]: detectYAMLType(fm[ck], ck) }), + {} + ); + }); + const types2 = typesArray.reduce( + (p3, c4) => { + const newSet = Object.keys(c4).reduce( + (pk, ck) => { + var _a2; + return { ...pk, [ck]: [...(_a2 = p3 == null ? void 0 : p3[ck]) != null ? _a2 : [], c4[ck]] }; + }, + { ...p3 } + ); + return newSet; }, - sensors.map((_ref2) => { - let { - sensor - } = _ref2; - return sensor; - }) + {} ); -} -function useSyntheticListeners(listeners, id2) { - return F2(() => { - return listeners.reduce((acc, _ref) => { - let { - eventName, - handler - } = _ref; - acc[eventName] = (event) => { - handler(event, id2); - }; - return acc; - }, {}); - }, [listeners, id2]); -} -function useWindowRect(element) { - return F2(() => element ? getWindowClientRect(element) : null, [element]); -} -var defaultValue$2 = []; -function useRects(elements, measure) { - if (measure === void 0) { - measure = getClientRect; + const guessType = (ts) => { + return import_lodash2.default.head((0, import_lodash2.default)(ts).countBy().entries().maxBy(import_lodash2.default.last)); + }; + const guessedTypes = Object.keys(types2).reduce((p3, c4) => { + return { ...p3, [c4]: guessType(types2[c4]) }; + }, {}); + return guessedTypes; +}; +var valueForFrontmatter = (type, value) => { + if (type == "number") { + return parseFloat(value); + } else if (type == "boolean") { + return value == "true"; + } else if (type.contains("multi")) { + return parseMultiString(value).map( + (f4) => valueForFrontmatter(type.replace("-multi", ""), f4) + ); + } else if (type.contains("link") || type.contains("context")) { + return `[[${value}]]`; } - const [firstElement] = elements; - const windowRect = useWindowRect(firstElement ? getWindow(firstElement) : null); - const [rects, measureRects] = s2(reducer2, defaultValue$2); - const resizeObserver = useResizeObserver({ - callback: measureRects - }); - if (elements.length > 0 && rects === defaultValue$2) { - measureRects(); + return value; +}; +var valueForDataview = (type, value) => { + if (type.contains("link") || type.contains("context")) { + return `[[${value}]]`; } - useIsomorphicLayoutEffect(() => { - if (elements.length) { - elements.forEach((element) => resizeObserver == null ? void 0 : resizeObserver.observe(element)); - } else { - resizeObserver == null ? void 0 : resizeObserver.disconnect(); - measureRects(); - } - }, [elements]); - return rects; - function reducer2() { - if (!elements.length) { - return defaultValue$2; - } - return elements.map((element) => isDocumentScrollingElement(element) ? windowRect : new Rect(measure(element), element)); + return value; +}; +var renameFrontmatterKey = (plugin, path, key2, name) => { + if (plugin.metadata.canProcessFrontmatter()) { + plugin.metadata.processFrontMatter(path, (frontmatter) => { + if (key2 in frontmatter) { + frontmatter[name] = frontmatter[key2]; + delete frontmatter[key2]; + } + }); } -} -function getMeasurableNode(node) { - if (!node) { - return null; +}; +var defaultValueForType = (value, type) => { + if (type == "date") { + return format(Date.now(), "yyyy-MM-dd"); } - if (node.children.length > 1) { - return node; + if (type == "number") { + return 0; } - const firstChild = node.children[0]; - return isHTMLElement(firstChild) ? firstChild : node; -} -function useDragOverlayMeasuring(_ref) { - let { - measure - } = _ref; - const [rect, setRect] = h2(null); - const handleResize = T2((entries) => { - for (const { - target - } of entries) { - if (isHTMLElement(target)) { - setRect((rect2) => { - const newRect = measure(target); - return rect2 ? { - ...rect2, - width: newRect.width, - height: newRect.height - } : newRect; - }); - break; - } - } - }, [measure]); - const resizeObserver = useResizeObserver({ - callback: handleResize - }); - const handleNodeChange = T2((element) => { - const node = getMeasurableNode(element); - resizeObserver == null ? void 0 : resizeObserver.disconnect(); - if (node) { - resizeObserver == null ? void 0 : resizeObserver.observe(node); - } - setRect(node ? measure(node) : null); - }, [measure, resizeObserver]); - const [nodeRef, setRef] = useNodeRef(handleNodeChange); - return F2(() => ({ - nodeRef, - rect, - setRef - }), [rect, nodeRef, setRef]); -} -var defaultSensors = [{ - sensor: PointerSensor, - options: {} -}, { - sensor: KeyboardSensor, - options: {} -}]; -var defaultData = { - current: {} -}; -var defaultMeasuringConfiguration = { - draggable: { - measure: getTransformAgnosticClientRect - }, - droppable: { - measure: getTransformAgnosticClientRect, - strategy: MeasuringStrategy.WhileDragging, - frequency: MeasuringFrequency.Optimized - }, - dragOverlay: { - measure: getClientRect + if (type == "boolean") { + return true; } -}; -var DroppableContainersMap = class extends Map { - get(id2) { - var _super$get; - return id2 != null ? (_super$get = super.get(id2)) != null ? _super$get : void 0 : void 0; + if (type == "link") { + return "[[Select Note]]"; } - toArray() { - return Array.from(this.values()); + if (type == "option") { + return "one, two"; } - getEnabled() { - return this.toArray().filter((_ref) => { - let { - disabled - } = _ref; - return !disabled; - }); + if (type == "text") { + return " "; } - getNodeFor(id2) { - var _this$get$node$curren, _this$get; - return (_this$get$node$curren = (_this$get = this.get(id2)) == null ? void 0 : _this$get.node.current) != null ? _this$get$node$curren : void 0; + if (type == "image") { + return "https://images.unsplash.com/photo-1675789652575-0a5d2425b6c2?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=2070&q=80"; } }; -var defaultPublicContext = { - activatorEvent: null, - active: null, - activeNode: null, - activeNodeRect: null, - collisions: null, - containerNodeRect: null, - draggableNodes: /* @__PURE__ */ new Map(), - droppableRects: /* @__PURE__ */ new Map(), - droppableContainers: /* @__PURE__ */ new DroppableContainersMap(), - over: null, - dragOverlay: { - nodeRef: { - current: null - }, - rect: null, - setRef: noop - }, - scrollableAncestors: [], - scrollableAncestorRects: [], - measuringConfiguration: defaultMeasuringConfiguration, - measureDroppableContainers: noop, - windowRect: null, - measuringScheduled: false -}; -var defaultInternalContext = { - activatorEvent: null, - activators: [], - active: null, - activeNodeRect: null, - ariaDescribedById: { - draggable: "" - }, - dispatch: noop, - draggableNodes: /* @__PURE__ */ new Map(), - over: null, - measureDroppableContainers: noop -}; -var InternalContext = /* @__PURE__ */ F(defaultInternalContext); -var PublicContext = /* @__PURE__ */ F(defaultPublicContext); -function getInitialState() { - return { - draggable: { - active: null, - initialCoordinates: { - x: 0, - y: 0 - }, - nodes: /* @__PURE__ */ new Map(), - translate: { - x: 0, - y: 0 - } - }, - droppable: { - containers: new DroppableContainersMap() - } - }; -} -function reducer(state, action) { - switch (action.type) { - case Action.DragStart: - return { - ...state, - draggable: { - ...state.draggable, - initialCoordinates: action.initialCoordinates, - active: action.active - } - }; - case Action.DragMove: - if (!state.draggable.active) { - return state; +var changeFrontmatterType = (plugin, path, key2, type) => { + if (plugin.metadata.canProcessFrontmatter()) { + plugin.metadata.processFrontMatter(path, (frontmatter) => { + if (key2 in frontmatter) { + frontmatter[key2] = defaultValueForType(frontmatter[key2], type); } - return { - ...state, - draggable: { - ...state.draggable, - translate: { - x: action.coordinates.x - state.draggable.initialCoordinates.x, - y: action.coordinates.y - state.draggable.initialCoordinates.y - } - } - }; - case Action.DragEnd: - case Action.DragCancel: - return { - ...state, - draggable: { - ...state.draggable, - active: null, - initialCoordinates: { - x: 0, - y: 0 - }, - translate: { - x: 0, - y: 0 + }); + } +}; +var deleteFrontmatterValue = (plugin, path, key2) => { + if (plugin.metadata.canProcessFrontmatter()) { + plugin.metadata.processFrontMatter(path, (frontmatter) => { + if (plugin.dataViewAPI()) { + if (plugin.dataViewAPI().page(path)[key2] && !frontmatter[key2]) { + replaceValues(plugin, path, key2, ""); + } else { + if (key2 in frontmatter) { + delete frontmatter[key2]; } } - }; - case Action.RegisterDroppable: { - const { - element - } = action; - const { - id: id2 - } = element; - const containers = new DroppableContainersMap(state.droppable.containers); - containers.set(id2, element); - return { - ...state, - droppable: { - ...state.droppable, - containers - } - }; - } - case Action.SetDroppableDisabled: { - const { - id: id2, - key: key2, - disabled - } = action; - const element = state.droppable.containers.get(id2); - if (!element || key2 !== element.key) { - return state; - } - const containers = new DroppableContainersMap(state.droppable.containers); - containers.set(id2, { - ...element, - disabled - }); - return { - ...state, - droppable: { - ...state.droppable, - containers + } else { + if (key2 in frontmatter) { + delete frontmatter[key2]; } - }; - } - case Action.UnregisterDroppable: { - const { - id: id2, - key: key2 - } = action; - const element = state.droppable.containers.get(id2); - if (!element || key2 !== element.key) { - return state; } - const containers = new DroppableContainersMap(state.droppable.containers); - containers.delete(id2); - return { - ...state, - droppable: { - ...state.droppable, - containers - } - }; - } - default: { - return state; - } + }); } -} -function RestoreFocus(_ref) { - let { - disabled - } = _ref; - const { - active, - activatorEvent, - draggableNodes - } = q2(InternalContext); - const previousActivatorEvent = usePrevious(activatorEvent); - const previousActiveId = usePrevious(active == null ? void 0 : active.id); - p2(() => { - if (disabled) { - return; +}; +var saveFrontmatterValue = (plugin, path, key2, value, type, forceSave) => { + let afile = getAbstractFileAtPath(plugin, path); + const fileCache = plugin.index.filesIndex.get(path); + if (afile) { + if (fileCache && fileCache.isFolder && fileCache.folderNote) { + afile = getAbstractFileAtPath(plugin, fileCache.folderNote.folderNotePath); } - if (!activatorEvent && previousActivatorEvent && previousActiveId != null) { - if (!isKeyboardEvent(previousActivatorEvent)) { - return; - } - if (document.activeElement === previousActivatorEvent.target) { - return; - } - const draggableNode = draggableNodes.get(previousActiveId); - if (!draggableNode) { - return; - } - const { - activatorNode, - node - } = draggableNode; - if (!activatorNode.current && !node.current) { - return; - } - requestAnimationFrame(() => { - for (const element of [activatorNode.current, node.current]) { - if (!element) { - continue; - } - const focusableNode = findFirstFocusableNode(element); - if (focusableNode) { - focusableNode.focus(); - break; + if (afile instanceof import_obsidian12.TFile) { + if (plugin.metadata.canProcessFrontmatter()) { + plugin.metadata.processFrontMatter(afile.path, (frontmatter) => { + var _a2; + if (plugin.dataViewAPI()) { + if (((_a2 = plugin.dataViewAPI().page(afile.path)) == null ? void 0 : _a2[key2]) && !frontmatter[key2]) { + replaceValues(plugin, afile.path, key2, valueForDataview(type, value)); + } else { + if (key2 in frontmatter || forceSave) { + frontmatter[key2] = valueForFrontmatter(type, value); + } + } + } else { + if (key2 in frontmatter || forceSave) { + frontmatter[key2] = valueForFrontmatter(type, value); + } } - } - }); - } - }, [activatorEvent, disabled, draggableNodes, previousActiveId, previousActivatorEvent]); - return null; -} -function applyModifiers(modifiers, _ref) { - let { - transform, - ...args - } = _ref; - return modifiers != null && modifiers.length ? modifiers.reduce((accumulator, modifier) => { - return modifier({ - transform: accumulator, - ...args - }); - }, transform) : transform; -} -function useMeasuringConfiguration(config) { - return F2( - () => ({ - draggable: { - ...defaultMeasuringConfiguration.draggable, - ...config == null ? void 0 : config.draggable - }, - droppable: { - ...defaultMeasuringConfiguration.droppable, - ...config == null ? void 0 : config.droppable - }, - dragOverlay: { - ...defaultMeasuringConfiguration.dragOverlay, - ...config == null ? void 0 : config.dragOverlay - } - }), - [config == null ? void 0 : config.draggable, config == null ? void 0 : config.droppable, config == null ? void 0 : config.dragOverlay] - ); -} -function useLayoutShiftScrollCompensation(_ref) { - let { - activeNode, - measure, - initialRect, - config = true - } = _ref; - const initialized = _2(false); - const { - x: x5, - y: y5 - } = typeof config === "boolean" ? { - x: config, - y: config - } : config; - useIsomorphicLayoutEffect(() => { - const disabled = !x5 && !y5; - if (disabled || !activeNode) { - initialized.current = false; - return; - } - if (initialized.current || !initialRect) { - return; - } - const node = activeNode == null ? void 0 : activeNode.node.current; - if (!node || node.isConnected === false) { - return; - } - const rect = measure(node); - const rectDelta = getRectDelta(rect, initialRect); - if (!x5) { - rectDelta.x = 0; - } - if (!y5) { - rectDelta.y = 0; - } - initialized.current = true; - if (Math.abs(rectDelta.x) > 0 || Math.abs(rectDelta.y) > 0) { - const firstScrollableAncestor = getFirstScrollableAncestor(node); - if (firstScrollableAncestor) { - firstScrollableAncestor.scrollBy({ - top: rectDelta.y, - left: rectDelta.x }); } } - }, [activeNode, x5, y5, initialRect, measure]); -} -var ActiveDraggableContext = /* @__PURE__ */ F({ - ...defaultCoordinates, - scaleX: 1, - scaleY: 1 -}); -var Status; -(function(Status2) { - Status2[Status2["Uninitialized"] = 0] = "Uninitialized"; - Status2[Status2["Initializing"] = 1] = "Initializing"; - Status2[Status2["Initialized"] = 2] = "Initialized"; -})(Status || (Status = {})); -var DndContext = /* @__PURE__ */ x3(function DndContext2(_ref) { - var _sensorContext$curren, _dragOverlay$nodeRef$, _dragOverlay$rect, _over$rect; - let { - id: id2, - accessibility, - autoScroll = true, - children, - sensors = defaultSensors, - collisionDetection = rectIntersection, - measuring, - modifiers, - ...props2 - } = _ref; - const store = s2(reducer, void 0, getInitialState); - const [state, dispatch] = store; - const [dispatchMonitorEvent, registerMonitorListener] = useDndMonitorProvider(); - const [status, setStatus] = h2(Status.Uninitialized); - const isInitialized = status === Status.Initialized; - const { - draggable: { - active: activeId, - nodes: draggableNodes, - translate - }, - droppable: { - containers: droppableContainers - } - } = state; - const node = activeId ? draggableNodes.get(activeId) : null; - const activeRects = _2({ - initial: null, - translated: null - }); - const active = F2(() => { - var _node$data; - return activeId != null ? { - id: activeId, - data: (_node$data = node == null ? void 0 : node.data) != null ? _node$data : defaultData, - rect: activeRects - } : null; - }, [activeId, node]); - const activeRef = _2(null); - const [activeSensor, setActiveSensor] = h2(null); - const [activatorEvent, setActivatorEvent] = h2(null); - const latestProps = useLatestValue(props2, Object.values(props2)); - const draggableDescribedById = useUniqueId("DndDescribedBy", id2); - const enabledDroppableContainers = F2(() => droppableContainers.getEnabled(), [droppableContainers]); - const measuringConfiguration = useMeasuringConfiguration(measuring); - const { - droppableRects, - measureDroppableContainers, - measuringScheduled - } = useDroppableMeasuring(enabledDroppableContainers, { - dragging: isInitialized, - dependencies: [translate.x, translate.y], - config: measuringConfiguration.droppable - }); - const activeNode = useCachedNode(draggableNodes, activeId); - const activationCoordinates = F2(() => activatorEvent ? getEventCoordinates(activatorEvent) : null, [activatorEvent]); - const autoScrollOptions = getAutoScrollerOptions(); - const initialActiveNodeRect = useInitialRect(activeNode, measuringConfiguration.draggable.measure); - useLayoutShiftScrollCompensation({ - activeNode: activeId ? draggableNodes.get(activeId) : null, - config: autoScrollOptions.layoutShiftCompensation, - initialRect: initialActiveNodeRect, - measure: measuringConfiguration.draggable.measure - }); - const activeNodeRect = useRect(activeNode, measuringConfiguration.draggable.measure, initialActiveNodeRect); - const containerNodeRect = useRect(activeNode ? activeNode.parentElement : null); - const sensorContext = _2({ - activatorEvent: null, - active: null, - activeNode, - collisionRect: null, - collisions: null, - droppableRects, - draggableNodes, - draggingNode: null, - draggingNodeRect: null, - droppableContainers, - over: null, - scrollableAncestors: [], - scrollAdjustedTranslate: null - }); - const overNode = droppableContainers.getNodeFor((_sensorContext$curren = sensorContext.current.over) == null ? void 0 : _sensorContext$curren.id); - const dragOverlay = useDragOverlayMeasuring({ - measure: measuringConfiguration.dragOverlay.measure - }); - const draggingNode = (_dragOverlay$nodeRef$ = dragOverlay.nodeRef.current) != null ? _dragOverlay$nodeRef$ : activeNode; - const draggingNodeRect = isInitialized ? (_dragOverlay$rect = dragOverlay.rect) != null ? _dragOverlay$rect : activeNodeRect : null; - const usesDragOverlay = Boolean(dragOverlay.nodeRef.current && dragOverlay.rect); - const nodeRectDelta = useRectDelta(usesDragOverlay ? null : activeNodeRect); - const windowRect = useWindowRect(draggingNode ? getWindow(draggingNode) : null); - const scrollableAncestors = useScrollableAncestors(isInitialized ? overNode != null ? overNode : activeNode : null); - const scrollableAncestorRects = useRects(scrollableAncestors); - const modifiedTranslate = applyModifiers(modifiers, { - transform: { - x: translate.x - nodeRectDelta.x, - y: translate.y - nodeRectDelta.y, - scaleX: 1, - scaleY: 1 - }, - activatorEvent, - active, - activeNodeRect, - containerNodeRect, - draggingNodeRect, - over: sensorContext.current.over, - overlayNodeRect: dragOverlay.rect, - scrollableAncestors, - scrollableAncestorRects, - windowRect - }); - const pointerCoordinates = activationCoordinates ? add(activationCoordinates, translate) : null; - const scrollOffsets = useScrollOffsets(scrollableAncestors); - const scrollAdjustment = useScrollOffsetsDelta(scrollOffsets); - const activeNodeScrollDelta = useScrollOffsetsDelta(scrollOffsets, [activeNodeRect]); - const scrollAdjustedTranslate = add(modifiedTranslate, scrollAdjustment); - const collisionRect = draggingNodeRect ? getAdjustedRect(draggingNodeRect, modifiedTranslate) : null; - const collisions = active && collisionRect ? collisionDetection({ - active, - collisionRect, - droppableRects, - droppableContainers: enabledDroppableContainers, - pointerCoordinates - }) : null; - const overId = getFirstCollision(collisions, "id"); - const [over, setOver] = h2(null); - const appliedTranslate = usesDragOverlay ? modifiedTranslate : add(modifiedTranslate, activeNodeScrollDelta); - const transform = adjustScale(appliedTranslate, (_over$rect = over == null ? void 0 : over.rect) != null ? _over$rect : null, activeNodeRect); - const instantiateSensor = T2( - (event, _ref2) => { - let { - sensor: Sensor, - options - } = _ref2; - if (activeRef.current == null) { - return; - } - const activeNode2 = draggableNodes.get(activeRef.current); - if (!activeNode2) { - return; + } +}; + +// src/utils/metadata/frontmatter/parseFrontMatter.ts +var parseFrontMatter = (field, value) => { + const YAMLtype = detectYAMLType(value, field); + switch (YAMLtype) { + case "object": + return JSON.stringify(value); + break; + case "number": + return value.toString(); + break; + case "boolean": + return value ? "true" : "false"; + break; + case "date": + return value; + break; + case "duration": + return serializeMultiDisplayString(Object.keys(value.values).reduce( + (p3, c4) => [ + ...p3, + ...value.values[c4] > 0 ? [value.values[c4] + " " + c4] : [] + ], + [] + )); + break; + case "option-multi": + case "link-multi": + if (typeof value === "string") { + return parseLinkString(value); } - const activatorEvent2 = event.nativeEvent; - const sensorInstance = new Sensor({ - active: activeRef.current, - activeNode: activeNode2, - event: activatorEvent2, - options, - context: sensorContext, - onStart(initialCoordinates) { - const id3 = activeRef.current; - if (id3 == null) { - return; + return serializeMultiString( + value.map((v3) => { + if (!v3) { + return ""; } - const draggableNode = draggableNodes.get(id3); - if (!draggableNode) { - return; + if (typeof v3 === "string") { + return parseLinkString(v3); } - const { - onDragStart - } = latestProps.current; - const event2 = { - active: { - id: id3, - data: draggableNode.data, - rect: activeRects - } - }; - dn(() => { - onDragStart == null ? void 0 : onDragStart(event2); - setStatus(Status.Initializing); - dispatch({ - type: Action.DragStart, - initialCoordinates, - active: id3 - }); - dispatchMonitorEvent({ - type: "onDragStart", - event: event2 - }); - }); - }, - onMove(coordinates) { - dispatch({ - type: Action.DragMove, - coordinates - }); - }, - onEnd: createHandler(Action.DragEnd), - onCancel: createHandler(Action.DragCancel) - }); - dn(() => { - setActiveSensor(sensorInstance); - setActivatorEvent(event.nativeEvent); - }); - function createHandler(type) { - return async function handler() { - const { - active: active2, - collisions: collisions2, - over: over2, - scrollAdjustedTranslate: scrollAdjustedTranslate2 - } = sensorContext.current; - let event2 = null; - if (active2 && scrollAdjustedTranslate2) { - const { - cancelDrop - } = latestProps.current; - event2 = { - activatorEvent: activatorEvent2, - active: active2, - collisions: collisions2, - delta: scrollAdjustedTranslate2, - over: over2 - }; - if (type === Action.DragEnd && typeof cancelDrop === "function") { - const shouldCancel = await Promise.resolve(cancelDrop(event2)); - if (shouldCancel) { - type = Action.DragCancel; - } - } + if (v3.path) { + return v3.path; } - activeRef.current = null; - dn(() => { - dispatch({ - type - }); - setStatus(Status.Uninitialized); - setOver(null); - setActiveSensor(null); - setActivatorEvent(null); - const eventName = type === Action.DragEnd ? "onDragEnd" : "onDragCancel"; - if (event2) { - const handler2 = latestProps.current[eventName]; - handler2 == null ? void 0 : handler2(event2); - dispatchMonitorEvent({ - type: eventName, - event: event2 - }); - } - }); - }; + if (Array.isArray(value) && v3.length == 1 && Array.isArray(v3[0]) && v3[0].length == 1 && typeof v3[0][0] === "string") { + return v3[0][0]; + } + return JSON.stringify(v3); + }) + ); + break; + case "link": + { + if (Array.isArray(value) && value.length == 1 && Array.isArray(value[0]) && value[0].length == 1 && typeof value[0][0] === "string") { + return value[0][0]; + } else if (typeof value === "string") { + return parseLinkString(value); + } + return value.path; } - }, - [draggableNodes] + break; + case "text": + case "tag": + case "image": + return value; + break; + } + return ""; +}; + +// src/utils/contexts/predicate/predicate.tsx +var defaultPredicateFnForType = (type, types2) => { + const fnType = Object.keys(types2).find( + (f4) => types2[f4].type.find((g4) => g4 == type) ); - const bindActivatorToSensorInstantiator = T2((handler, sensor) => { - return (event, active2) => { - const nativeEvent = event.nativeEvent; - const activeDraggableNode = draggableNodes.get(active2); - if (activeRef.current !== null || !activeDraggableNode || nativeEvent.dndKit || nativeEvent.defaultPrevented) { - return; - } - const activationContext = { - active: activeDraggableNode + return fnType; +}; +var predicateFnsForType = (type, types2) => { + const fnTypes = Object.keys(types2).filter( + (f4) => types2[f4].type.find((g4) => g4 == type) + ); + return fnTypes; +}; +var cleanPredicateType = (type, definedTypes) => { + return type.filter((f4) => Object.keys(definedTypes).find((g4) => g4 == f4.fn)); +}; +var validatePredicate = (prevPredicate) => { + if (!prevPredicate) { + return defaultPredicate; + } + return { + ...defaultPredicate, + view: prevPredicate.view, + frame: prevPredicate.frame, + frameProps: prevPredicate.frameProps, + filters: Array.isArray(prevPredicate.filters) ? cleanPredicateType(prevPredicate.filters, filterFnTypes) : [], + sort: Array.isArray(prevPredicate.sort) ? cleanPredicateType(prevPredicate.sort, sortFnTypes) : [], + groupBy: Array.isArray(prevPredicate.groupBy) ? prevPredicate.groupBy : [], + colsOrder: Array.isArray(prevPredicate.colsOrder) ? prevPredicate.colsOrder : [], + colsHidden: Array.isArray(prevPredicate.colsHidden) ? prevPredicate.colsHidden : [], + colsSize: prevPredicate.colsSize + }; +}; +var defaultPredicate = { + view: "list", + filters: [], + frame: "", + frameProps: {}, + sort: [], + groupBy: [], + colsOrder: [], + colsHidden: [], + colsSize: {} +}; +var defaultTablePredicate = { + view: "table", + filters: [], + frame: "", + frameProps: {}, + sort: [], + groupBy: [], + colsOrder: [], + colsHidden: [], + colsSize: {} +}; + +// src/context/ContextMDBContext.tsx +var import_lodash3 = __toESM(require_lodash()); +var import_obsidian13 = require("obsidian"); +var ContextMDBContext = F({ + dbSchemas: [], + tableData: null, + contextTable: {}, + setContextTable: () => null, + saveDB: () => null, + saveContextDB: () => null, + dbSchema: null, + setDBSchema: () => null, + saveSchema: () => null, + deleteSchema: () => null, + dbFileExists: false +}); +var ContextMDBProvider = (props2) => { + var _a2, _b2; + const [dbFileExists, setDBFileExists] = h2(false); + const [schemaTable, setSchemaTable] = h2(null); + const schemas = (_a2 = schemaTable == null ? void 0 : schemaTable.rows) != null ? _a2 : []; + const [tableData, setTableData] = h2(null); + const [dbSchema, setDBSchema] = h2(null); + const [contextTable, setContextTable] = h2({}); + const [metadataCache, setMetadataCache] = h2(null); + const defaultSchema = defaultFolderSchema; + const { spaceInfo, readMode, spaceCache } = q2(SpaceContext); + const contexts = (_b2 = spaceCache == null ? void 0 : spaceCache.contexts) != null ? _b2 : []; + const deleteSchema = async (table) => { + if (table.primary) + return; + const deleteResult = await deleteMDBTable( + props2.plugin, + spaceInfo, + table.id, + spaceInfo.dbPath + ); + if (deleteResult) { + const newSchemaTable = { + ...schemaTable, + rows: schemaTable.rows.filter( + (f4) => f4.id != table.id && f4.def != table.id + ) }; - const shouldActivate = handler(event, sensor.options, activationContext); - if (shouldActivate === true) { - nativeEvent.dndKit = { - capturedBy: sensor.sensor - }; - activeRef.current = active2; - instantiateSensor(event, sensor); + setSchemaTable(newSchemaTable); + if (dbSchema.id == table.id) { + setDBSchema( + newSchemaTable.rows.find((g4) => g4.type == "db") + ); } + } + }; + const saveSchema = async (table) => { + const newSchema = schemaTable.rows.find((f4) => f4.id == table.id) ? true : false; + const newSchemaTable = newSchema ? { + ...schemaTable, + rows: schemaTable.rows.map((f4) => f4.id == table.id ? table : f4) + } : { + ...schemaTable, + rows: [...schemaTable.rows, table] }; - }, [draggableNodes, instantiateSensor]); - const activators = useCombineActivators(sensors, bindActivatorToSensorInstantiator); - useSensorSetup(sensors); - useIsomorphicLayoutEffect(() => { - if (activeNodeRect && status === Status.Initializing) { - setStatus(Status.Initialized); + if (!spaceInfo.readOnly) { + await saveSpaceDBToPath(props2.plugin, spaceInfo, "context", { + m_schema: newSchemaTable + }); } - }, [activeNodeRect, status]); - p2( - () => { - const { - onDragMove - } = latestProps.current; - const { - active: active2, - activatorEvent: activatorEvent2, - collisions: collisions2, - over: over2 - } = sensorContext.current; - if (!active2 || !activatorEvent2) { - return; + if (table.id == (dbSchema == null ? void 0 : dbSchema.id)) { + setDBSchema(table); + setTableData((f4) => ({ + ...f4, + schema: table + })); + } + setSchemaTable(newSchemaTable); + }; + p2(() => { + var _a3, _b3; + if (schemaTable) { + if (props2.schema) { + const preselectSchema = schemaTable.rows.find( + (g4) => g4.id == props2.schema + ); + if (preselectSchema) { + if (preselectSchema.type == "db") { + setDBSchema(preselectSchema); + return; + } else { + const preselectDBSchema = schemaTable.rows.find( + (g4) => g4.id == preselectSchema.def + ); + if (preselectDBSchema) { + setDBSchema(preselectDBSchema); + return; + } + } + } else { + const newSchema = { + id: uniqueNameFromString( + sanitizeTableName(props2.schema), + schemaTable.rows.map((g4) => g4.id) + ), + name: props2.schema, + type: "db" + }; + setDBSchema(newSchema); + saveSchema(newSchema).then(() => { + saveDB2({ + schema: newSchema, + cols: defaultTableFields.map((g4) => ({ + ...g4, + schemaId: newSchema.id + })), + rows: [] + }); + }); + } + } else { + if (!dbSchema) { + setDBSchema( + (_a3 = schemaTable.rows) == null ? void 0 : _a3.find((g4) => g4.id == "files") + ); + } else { + setDBSchema( + (_b3 = schemaTable.rows) == null ? void 0 : _b3.find((g4) => g4.id == dbSchema.id) + ); + } } - const event = { - active: active2, - activatorEvent: activatorEvent2, - collisions: collisions2, - delta: { - x: scrollAdjustedTranslate.x, - y: scrollAdjustedTranslate.y - }, - over: over2 - }; - dn(() => { - onDragMove == null ? void 0 : onDragMove(event); - dispatchMonitorEvent({ - type: "onDragMove", - event - }); + } + }, [schemaTable]); + const loadTables = async () => { + if (!spaceInfo) + return; + const spaceExists = await props2.plugin.app.vault.adapter.exists( + spaceInfo.dbPath + ); + if (spaceExists || spaceInfo.isRemote) { + setDBFileExists(true); + getMDBTableSchemas(props2.plugin, spaceInfo, "context").then((f4) => { + if (f4) + setSchemaTable(() => ({ + ...defaultSchema, + rows: f4 + })); }); - }, - [scrollAdjustedTranslate.x, scrollAdjustedTranslate.y] - ); - p2( - () => { - const { - active: active2, - activatorEvent: activatorEvent2, - collisions: collisions2, - droppableContainers: droppableContainers2, - scrollAdjustedTranslate: scrollAdjustedTranslate2 - } = sensorContext.current; - if (!active2 || activeRef.current == null || !activatorEvent2 || !scrollAdjustedTranslate2) { + } else { + setDBFileExists(false); + if (props2.schema) { + const tableData2 = defaultTableDataForContext(props2.plugin, spaceInfo); + if (tableData2) { + setSchemaTable(defaultSchema); + } + } else { + setSchemaTable(defaultSchema); + setDBSchema(defaultFileDBSchema); + } + } + }; + const refreshFile = T2(async (file) => { + var _a3; + if (file.path == props2.file && dbSchema) { + const fCache = (_a3 = props2.plugin.app.metadataCache.getCache( + file.path + )) == null ? void 0 : _a3.frontmatter; + if ((0, import_lodash3.isEqual)(fCache, metadataCache)) return; + setMetadataCache(fCache); + if (dbSchema.primary) { + runDef(); + } else { + getMDBData(); } - const { - onDragOver - } = latestProps.current; - const overContainer = droppableContainers2.get(overId); - const over2 = overContainer && overContainer.rect.current ? { - id: overContainer.id, - rect: overContainer.rect.current, - data: overContainer.data, - disabled: overContainer.disabled - } : null; - const event = { - active: active2, - activatorEvent: activatorEvent2, - collisions: collisions2, - delta: { - x: scrollAdjustedTranslate2.x, - y: scrollAdjustedTranslate2.y - }, - over: over2 - }; - dn(() => { - setOver(over2); - onDragOver == null ? void 0 : onDragOver(event); - dispatchMonitorEvent({ - type: "onDragOver", - event - }); - }); - }, - [overId] - ); - useIsomorphicLayoutEffect(() => { - sensorContext.current = { - activatorEvent, - active, - activeNode, - collisionRect, - collisions, - droppableRects, - draggableNodes, - draggingNode, - draggingNodeRect, - droppableContainers, - over, - scrollableAncestors, - scrollAdjustedTranslate - }; - activeRects.current = { - initial: draggingNodeRect, - translated: collisionRect - }; - }, [active, activeNode, collisions, collisionRect, draggableNodes, draggingNode, draggingNodeRect, droppableRects, droppableContainers, over, scrollableAncestors, scrollAdjustedTranslate]); - useAutoScroller({ - ...autoScrollOptions, - delta: translate, - draggingRect: collisionRect, - pointerCoordinates, - scrollableAncestors, - scrollableAncestorRects - }); - const publicContext = F2(() => { - const context = { - active, - activeNode, - activeNodeRect, - activatorEvent, - collisions, - containerNodeRect, - dragOverlay, - draggableNodes, - droppableContainers, - droppableRects, - over, - measureDroppableContainers, - scrollableAncestors, - scrollableAncestorRects, - measuringConfiguration, - measuringScheduled, - windowRect - }; - return context; - }, [active, activeNode, activeNodeRect, activatorEvent, collisions, containerNodeRect, dragOverlay, draggableNodes, droppableContainers, droppableRects, over, measureDroppableContainers, scrollableAncestors, scrollableAncestorRects, measuringConfiguration, measuringScheduled, windowRect]); - const internalContext = F2(() => { - const context = { - activatorEvent, - activators, - active, - activeNodeRect, - ariaDescribedById: { - draggable: draggableDescribedById - }, - dispatch, - draggableNodes, - over, - measureDroppableContainers - }; - return context; - }, [activatorEvent, activators, active, activeNodeRect, dispatch, draggableDescribedById, draggableNodes, over, measureDroppableContainers]); - return Cn.createElement(DndMonitorContext.Provider, { - value: registerMonitorListener - }, Cn.createElement(InternalContext.Provider, { - value: internalContext - }, Cn.createElement(PublicContext.Provider, { - value: publicContext - }, Cn.createElement(ActiveDraggableContext.Provider, { - value: transform - }, children)), Cn.createElement(RestoreFocus, { - disabled: (accessibility == null ? void 0 : accessibility.restoreFocus) === false - })), Cn.createElement(Accessibility, { - ...accessibility, - hiddenTextDescribedById: draggableDescribedById - })); - function getAutoScrollerOptions() { - const activeSensorDisablesAutoscroll = (activeSensor == null ? void 0 : activeSensor.autoScrollEnabled) === false; - const autoScrollGloballyDisabled = typeof autoScroll === "object" ? autoScroll.enabled === false : autoScroll === false; - const enabled = isInitialized && !activeSensorDisablesAutoscroll && !autoScrollGloballyDisabled; - if (typeof autoScroll === "object") { - return { - ...autoScroll, - enabled - }; } - return { - enabled - }; - } -}); -var NullContext = /* @__PURE__ */ F(null); -var defaultRole = "button"; -var ID_PREFIX = "Droppable"; -function useDraggable(_ref) { - let { - id: id2, - data, - disabled = false, - attributes - } = _ref; - const key2 = useUniqueId(ID_PREFIX); - const { - activators, - activatorEvent, - active, - activeNodeRect, - ariaDescribedById, - draggableNodes, - over - } = q2(InternalContext); - const { - role = defaultRole, - roleDescription = "draggable", - tabIndex = 0 - } = attributes != null ? attributes : {}; - const isDragging = (active == null ? void 0 : active.id) === id2; - const transform = q2(isDragging ? ActiveDraggableContext : NullContext); - const [node, setNodeRef] = useNodeRef(); - const [activatorNode, setActivatorNodeRef] = useNodeRef(); - const listeners = useSyntheticListeners(activators, id2); - const dataRef = useLatestValue(data); - useIsomorphicLayoutEffect( - () => { - draggableNodes.set(id2, { - id: id2, - key: key2, - node, - activatorNode, - data: dataRef - }); - return () => { - const node2 = draggableNodes.get(id2); - if (node2 && node2.key === key2) { - draggableNodes.delete(id2); + }, []); + const loadContextFields = T2(async (tag) => { + getMDBTable( + props2.plugin, + spaceFromTag(props2.plugin, tag), + "files", + "context" + ).then((f4) => { + setContextTable((t4) => ({ + ...t4, + [tag]: f4 + })); + }); + }, []); + const refreshTags = async (tags) => { + if (contexts.some((f4) => tags.some((g4) => g4 == f4))) + if (dbSchema.primary) { + runDef(); + } else { + getMDBData(); + } + }; + const refreshMDB = T2( + async (contextPath) => { + if ((dbSchema == null ? void 0 : dbSchema.primary) != "true") { + return; + } + if (contextPath == spaceInfo.path) { + if (dbSchema) { + loadTables(); } - }; + } else { + const tag = Object.keys(contextTable).find( + (t4) => spaceFromTag(props2.plugin, t4).path == contextPath + ); + if (tag) + loadContextFields(tag); + } }, - [draggableNodes, id2] + [ + contextTable, + dbFileExists, + dbSchema, + loadContextFields, + loadTables, + props2.plugin, + spaceInfo + ] ); - const memoizedAttributes = F2(() => ({ - role, - tabIndex, - "aria-disabled": disabled, - "aria-pressed": isDragging && role === defaultRole ? true : void 0, - "aria-roledescription": roleDescription, - "aria-describedby": ariaDescribedById.draggable - }), [disabled, role, tabIndex, isDragging, roleDescription, ariaDescribedById.draggable]); - return { - active, - activatorEvent, - activeNodeRect, - attributes: memoizedAttributes, - isDragging, - listeners: disabled ? void 0 : listeners, - node, - over, - setNodeRef, - setActivatorNodeRef, - transform - }; -} -function useDndContext() { - return q2(PublicContext); -} -var ID_PREFIX$1 = "Droppable"; -var defaultResizeObserverConfig = { - timeout: 25 -}; -function useDroppable(_ref) { - let { - data, - disabled = false, - id: id2, - resizeObserverConfig - } = _ref; - const key2 = useUniqueId(ID_PREFIX$1); - const { - active, - dispatch, - over, - measureDroppableContainers - } = q2(InternalContext); - const previous = _2({ - disabled - }); - const resizeObserverConnected = _2(false); - const rect = _2(null); - const callbackId = _2(null); - const { - disabled: resizeObserverDisabled, - updateMeasurementsFor, - timeout: resizeObserverTimeout - } = { - ...defaultResizeObserverConfig, - ...resizeObserverConfig - }; - const ids2 = useLatestValue(updateMeasurementsFor != null ? updateMeasurementsFor : id2); - const handleResize = T2( - () => { - if (!resizeObserverConnected.current) { - resizeObserverConnected.current = true; + const refreshSpace = T2( + async (evt) => { + if (evt.detail.type == "context") { + refreshMDB(evt.detail.name); return; } - if (callbackId.current != null) { - clearTimeout(callbackId.current); + if (evt.detail.type == "file") { + refreshFile(getAbstractFileAtPath(props2.plugin, evt.detail.name)); + return; + } + if ((evt.detail.type == "space" || evt.detail.type == "vault") && !dbFileExists) { + const defaultTable = defaultTableDataForContext( + props2.plugin, + spaceInfo + ); + if (defaultTable) + setTableData(defaultTable); + } else if (evt.detail.type == "vault") { + refreshMDB(spaceInfo.path); } - callbackId.current = setTimeout(() => { - measureDroppableContainers(Array.isArray(ids2.current) ? ids2.current : [ids2.current]); - callbackId.current = null; - }, resizeObserverTimeout); }, - [resizeObserverTimeout] + [dbFileExists, props2.plugin, refreshFile, refreshMDB, spaceInfo] ); - const resizeObserver = useResizeObserver({ - callback: handleResize, - disabled: resizeObserverDisabled || !active - }); - const handleNodeChange = T2((newElement, previousElement) => { - if (!resizeObserver) { + const getMDBData = () => { + getMDBTable(props2.plugin, spaceInfo, dbSchema.id, "context").then((f4) => { + setTableData(f4); + }); + }; + p2(() => { + window.addEventListener(eventTypes.spacesChange, refreshSpace); + return () => { + window.removeEventListener(eventTypes.spacesChange, refreshSpace); + }; + }, [refreshSpace]); + p2(() => { + loadTables(); + }, [spaceInfo]); + const saveDB2 = async (newTable) => { + var _a3, _b3; + if (spaceInfo.readOnly) return; + if (!dbFileExists) { + const defaultFields = defaultFieldsForContext(spaceInfo); + const defaultTable = defaultTablesForContext(spaceInfo); + const dbField = { + ...defaultTable, + m_fields: { + uniques: defaultFields.uniques, + cols: defaultFields.cols, + rows: [...(_a3 = defaultFields.rows) != null ? _a3 : [], ...(_b3 = newTable == null ? void 0 : newTable.cols) != null ? _b3 : []] + }, + [newTable.schema.id]: { + uniques: newTable.cols.filter((c4) => c4.unique == "true").map((c4) => c4.name), + cols: newTable.cols.map((c4) => c4.name), + rows: newTable.rows + } + }; + await saveSpaceDBToPath(props2.plugin, spaceInfo, "context", dbField).then( + (f4) => { + setDBFileExists(true); + f4 ? setTableData(newTable) : new import_obsidian13.Notice("DB ERROR"); + } + ); + } else { + await saveMDBToPath(props2.plugin, spaceInfo, newTable).then((f4) => { + f4 ? setTableData(newTable) : new import_obsidian13.Notice("DB ERROR"); + }); } - if (previousElement) { - resizeObserver.unobserve(previousElement); - resizeObserverConnected.current = false; - } - if (newElement) { - resizeObserver.observe(newElement); - } - }, [resizeObserver]); - const [nodeRef, setNodeRef] = useNodeRef(handleNodeChange); - const dataRef = useLatestValue(data); + }; p2(() => { - if (!resizeObserver || !nodeRef.current) { + if (!schemaTable || !dbSchema) return; + if (dbFileExists) { + if (dbSchema.primary) { + runDef(); + } else { + getMDBData(); + } + } else { + const defaultTable = defaultTableDataForContext(props2.plugin, spaceInfo); + if (defaultTable) + setTableData(defaultTable); } - resizeObserver.disconnect(); - resizeObserverConnected.current = false; - resizeObserver.observe(nodeRef.current); - }, [nodeRef, resizeObserver]); - useIsomorphicLayoutEffect( - () => { - dispatch({ - type: Action.RegisterDroppable, - element: { - id: id2, - key: key2, - disabled, - node: nodeRef, - rect, - data: dataRef + }, [dbSchema]); + p2(() => { + if (dbFileExists && tableData) + getContextTags(tableData); + }, [tableData]); + const getContextTags = async (_tableData) => { + const contextFields = _tableData.cols.filter((f4) => f4.type.contains("context")).map((f4) => f4.value).filter((f4) => !contexts.some((g4) => g4 == f4)); + for (const c4 of contextFields) { + loadContextFields(c4); + } + }; + const runDef = async () => { + if (spaceInfo.uri.type == "folder") { + getMDBTable(props2.plugin, spaceInfo, "files", "context").then((f4) => { + if (f4) { + for (const c4 of contexts) { + loadTagContext(c4, f4.rows); + } + setTableData(f4); } + return f4; }); - return () => dispatch({ - type: Action.UnregisterDroppable, - key: key2, - id: id2 + } else if (spaceInfo.uri.type == "tag") { + getMDBTable(props2.plugin, spaceInfo, "files", "context").then((f4) => { + if (f4) { + for (const c4 of contexts) { + loadTagContext(c4, f4.rows); + } + setTableData(f4); + } + return f4; }); - }, - [id2] - ); - p2(() => { - if (disabled !== previous.current.disabled) { - dispatch({ - type: Action.SetDroppableDisabled, - id: id2, - key: key2, - disabled + } else if (spaceInfo.uri.type == "space") { + getMDBTable(props2.plugin, spaceInfo, "files", "context").then((f4) => { + if (f4) + setTableData(f4); + return f4; + }); + } else { + getMDBTable(props2.plugin, spaceInfo, dbSchema.id, "context").then((f4) => { + if (f4) + setTableData(f4); }); - previous.current.disabled = disabled; } - }, [id2, key2, disabled, dispatch]); - return { - active, - rect, - isOver: (over == null ? void 0 : over.id) === id2, - node: nodeRef, - over, - setNodeRef }; -} -function AnimationManager(_ref) { - let { - animation, - children - } = _ref; - const [clonedChildren, setClonedChildren] = h2(null); - const [element, setElement] = h2(null); - const previousChildren = usePrevious(children); - if (!children && !clonedChildren && previousChildren) { - setClonedChildren(previousChildren); - } - useIsomorphicLayoutEffect(() => { - if (!element) { - return; + const loadTagContext = async (tag, files) => { + getMDBTable( + props2.plugin, + spaceFromTag(props2.plugin, tag), + "files", + "context" + ).then((f4) => { + if (f4) { + const contextFields = f4.cols.filter((g4) => g4.type.contains("context")).map((g4) => g4.value).filter((g4) => !contexts.some((h5) => h5 == g4)); + for (const c4 of contextFields) { + loadContextFields(c4); + } + setContextTable((t4) => ({ + ...t4, + [tag]: f4 + })); + } + }); + }; + const saveContextDB = async (newTable, tag) => { + const context = spaceFromTag(props2.plugin, tag); + await saveMDBToPath(props2.plugin, context, newTable).then( + (f4) => f4 && setContextTable((t4) => ({ + ...t4, + [tag]: newTable + })) + ); + }; + return /* @__PURE__ */ Cn.createElement(ContextMDBContext.Provider, { + value: { + tableData, + contextTable, + setContextTable, + saveDB: saveDB2, + saveContextDB, + dbSchemas: schemas, + saveSchema, + deleteSchema, + dbFileExists, + dbSchema, + setDBSchema } - const key2 = clonedChildren == null ? void 0 : clonedChildren.key; - const id2 = clonedChildren == null ? void 0 : clonedChildren.props.id; - if (key2 == null || id2 == null) { - setClonedChildren(null); + }, props2.children); +}; + +// src/context/ContextEditorContext.tsx +var ContextEditorContext = F({ + cols: [], + data: [], + schema: null, + views: [], + setSchema: () => null, + sortedColumns: [], + filteredData: [], + contextTable: {}, + selectedRows: [], + selectRows: () => null, + setContextTable: () => null, + predicate: defaultPredicate, + savePredicate: () => null, + saveContextDB: () => null, + hideColumn: () => null, + saveColumn: () => false, + newColumn: () => false, + sortColumn: () => null, + delColumn: () => null, + searchString: "", + setSearchString: () => null, + loadContextFields: () => null, + updateValue: () => null, + updateFieldValue: () => null +}); +var ContextEditorProvider = (props2) => { + var _a2; + const { spaceInfo, spaceCache } = q2(SpaceContext); + const contexts = (_a2 = spaceCache == null ? void 0 : spaceCache.contexts) != null ? _a2 : []; + const { dbFileExists, dbSchema, saveDB: saveDB2, tableData } = q2(ContextMDBContext); + const { frameSchemas, saveSchema } = q2(FramesMDBContext); + const [schema, setSchema] = h2(defaultFileListSchema); + const [searchString, setSearchString] = h2(null); + const [contextTable, setContextTable] = h2({}); + const [predicate, setPredicate] = h2(defaultPredicate); + const [selectedRows, setSelectedRows] = h2([]); + const views = F2(() => { + const _views = frameSchemas.filter( + (f4) => f4.type == "view" && f4.def.db == (dbSchema == null ? void 0 : dbSchema.id) + ); + return _views.length > 0 ? _views : schema ? [schema] : []; + }, [frameSchemas, schema]); + const getSchema = (_schemaTable, _dbSchema, _currentSchema) => { + var _a3, _b2; + let _schema; + if (props2.schema) { + _schema = _schemaTable.find((f4) => f4.id == props2.schema); + } else { + _schema = ((_a3 = _currentSchema == null ? void 0 : _currentSchema.def) == null ? void 0 : _a3.db) == _dbSchema.id ? _schemaTable.find((f4) => f4.id == _currentSchema.id) : (_b2 = _schemaTable.find((f4) => { + var _a4; + return ((_a4 = f4.def) == null ? void 0 : _a4.db) == _dbSchema.id; + })) != null ? _b2 : { + ..._dbSchema, + id: uniqueNameFromString( + _dbSchema.id + "View", + _schemaTable.map((f4) => f4.id) + ), + type: "view", + def: { db: _dbSchema.id }, + predicate: JSON.stringify( + _dbSchema.primary == "true" ? defaultPredicate : defaultTablePredicate + ) + }; + } + return _schema; + }; + p2(() => { + if (!dbSchema) return; + const _schema = getSchema(frameSchemas, dbSchema, schema); + if (_schema) { + setSchema(_schema); } - Promise.resolve(animation(id2, element)).then(() => { - setClonedChildren(null); + }, [dbSchema, frameSchemas, props2.schema]); + const cols = F2( + () => { + var _a3; + return tableData ? [ + ...(_a3 = tableData.cols.map((f4) => ({ ...f4, table: "" }))) != null ? _a3 : [], + ...(dbSchema == null ? void 0 : dbSchema.primary) == "true" ? contexts.reduce( + (p3, c4) => { + var _a4, _b2; + return [ + ...p3, + ...(_b2 = (_a4 = contextTable[c4]) == null ? void 0 : _a4.cols.filter( + (f4) => f4.name != FilePropertyName && f4.type != "fileprop" + ).map((f4) => ({ ...f4, table: c4 }))) != null ? _b2 : [] + ]; + }, + [] + ) : [] + ] : []; + }, + [tableData, contextTable, contexts] + ); + const data2 = F2( + () => { + var _a3; + return (_a3 = tableData == null ? void 0 : tableData.rows.map( + (r3, index) => linkContextRow( + props2.plugin, + { + _index: index.toString(), + ...r3, + ...contexts.reduce((p3, c4) => { + var _a4, _b2, _c2, _d2; + const contextRowIndexByFile = (_b2 = (_a4 = contextTable[c4]) == null ? void 0 : _a4.rows.findIndex((f4) => f4.File == r3.File)) != null ? _b2 : -1; + const contextRowsByFile = (_d2 = (_c2 = contextTable[c4]) == null ? void 0 : _c2.rows[contextRowIndexByFile]) != null ? _d2 : {}; + const contextRowsWithKeysAppended = Object.keys( + contextRowsByFile + ).reduce( + (pa, ca) => ({ ...pa, [ca + c4]: contextRowsByFile[ca] }), + { + ["_index" + c4]: contextRowIndexByFile.toString() + } + ); + return { ...p3, ...contextRowsWithKeysAppended }; + }, {}) + }, + cols + ) + )) != null ? _a3 : []; + }, + [tableData, schema, contextTable] + ); + const sortedColumns = F2(() => { + return cols.filter( + (f4) => f4.hidden != "true" && !predicate.colsHidden.some((c4) => c4 == f4.name + f4.table) + ).sort( + (a5, b4) => predicate.colsOrder.findIndex((x5) => x5 == a5.name + a5.table) - predicate.colsOrder.findIndex((x5) => x5 == b4.name + b4.table) + ); + }, [cols, predicate]); + const filteredData = F2( + () => data2.filter((f4) => { + return predicate.filters.reduce((p3, c4) => { + return p3 ? filterReturnForCol( + cols.find((col) => col.name + col.table == c4.field), + c4, + f4 + ) : p3; + }, true); + }).filter( + (f4) => (searchString == null ? void 0 : searchString.length) > 0 ? matchAny(searchString).test( + Object.keys(f4).filter((g4) => g4.charAt(0) != "_").map((g4) => f4[g4]).join("|") + ) : true + ).sort((a5, b4) => { + return predicate.sort.reduce((p3, c4) => { + return p3 == 0 ? sortReturnForCol( + cols.find((col) => col.name + col.table == c4.field), + c4, + a5, + b4 + ) : p3; + }, 0); + }), + [predicate, data2, cols, searchString] + ); + const updateValue2 = (column, value, table, index, file) => { + var _a3, _b2; + const col = (_a3 = table == "" ? tableData : contextTable[table]) == null ? void 0 : _a3.cols.find( + (f4) => f4.name == column + ); + if (col) + saveFrontmatterValue( + props2.plugin, + file != null ? file : (_b2 = tableData.rows[index]) == null ? void 0 : _b2.File, + column, + value, + col.type, + props2.plugin.settings.saveAllContextToFrontmatter + ); + if (table == "") { + saveDB2({ + ...tableData, + rows: tableData.rows.map( + (r3, i4) => i4 == index ? { + ...r3, + [column]: value + } : r3 + ) + }); + } else if (contextTable[table]) { + saveContextDB( + { + ...contextTable[table], + rows: contextTable[table].rows.map( + (r3, i4) => i4 == index ? { + ...r3, + [column]: value + } : r3 + ) + }, + table + ); + } + }; + const sortColumn = (sort) => { + savePredicate({ + ...predicate, + sort: [sort] }); - }, [animation, clonedChildren, element]); - return Cn.createElement(Cn.Fragment, null, children, clonedChildren ? sn(clonedChildren, { - ref: setElement - }) : null); -} -var defaultTransform = { - x: 0, - y: 0, - scaleX: 1, - scaleY: 1 -}; -function NullifiedContextProvider(_ref) { - let { - children - } = _ref; - return Cn.createElement(InternalContext.Provider, { - value: defaultInternalContext - }, Cn.createElement(ActiveDraggableContext.Provider, { - value: defaultTransform - }, children)); -} -var baseStyles = { - position: "fixed", - touchAction: "none" -}; -var defaultTransition = (activatorEvent) => { - const isKeyboardActivator = isKeyboardEvent(activatorEvent); - return isKeyboardActivator ? "transform 250ms ease" : void 0; -}; -var PositionedOverlay = /* @__PURE__ */ k3((_ref, ref) => { - let { - as, - activatorEvent, - adjustScale: adjustScale2, - children, - className, - rect, - style, - transform, - transition = defaultTransition - } = _ref; - if (!rect) { - return null; - } - const scaleAdjustedTransform = adjustScale2 ? transform : { - ...transform, - scaleX: 1, - scaleY: 1 }; - const styles = { - ...baseStyles, - width: rect.width, - height: rect.height, - top: rect.top, - left: rect.left, - transform: CSS.Transform.toString(scaleAdjustedTransform), - transformOrigin: adjustScale2 && activatorEvent ? getRelativeTransformOrigin(activatorEvent, rect) : void 0, - transition: typeof transition === "function" ? transition(activatorEvent) : transition, - ...style + const hideColumn = (col, hidden) => { + savePredicate({ + ...predicate, + colsHidden: hidden ? [ + ...predicate.colsHidden.filter((s5) => s5 != col.name + col.table), + col.name + col.table + ] : predicate.colsHidden.filter((s5) => s5 != col.name + col.table) + }); }; - return Cn.createElement(as, { - className, - style: styles, - ref - }, children); -}); -var defaultDropAnimationSideEffects = (options) => (_ref) => { - let { - active, - dragOverlay - } = _ref; - const originalStyles = {}; - const { - styles, - className - } = options; - if (styles != null && styles.active) { - for (const [key2, value] of Object.entries(styles.active)) { - if (value === void 0) { - continue; - } - originalStyles[key2] = active.node.style.getPropertyValue(key2); - active.node.style.setProperty(key2, value); + const updateFieldValue = (column, fieldValue, value, table, index, file) => { + var _a3; + const col = tableData.cols.find((f4) => f4.name == column); + saveFrontmatterValue( + props2.plugin, + file != null ? file : (_a3 = tableData.rows[index]) == null ? void 0 : _a3.File, + column, + value, + col.type, + props2.plugin.settings.saveAllContextToFrontmatter + ); + if (table == "") { + const newTable = { + ...tableData, + cols: tableData.cols.map( + (m5) => m5.name == column ? { + ...m5, + value: fieldValue + } : m5 + ), + rows: tableData.rows.map( + (r3, i4) => i4 == index ? { + ...r3, + [column]: value + } : r3 + ) + }; + saveDB2(newTable); + } else if (contextTable[table]) { + saveContextDB( + { + ...contextTable[table], + cols: contextTable[table].cols.map( + (m5) => m5.name == column ? { + ...m5, + value: fieldValue + } : m5 + ), + rows: contextTable[table].rows.map( + (r3, i4) => i4 == index ? { + ...r3, + [column]: value + } : r3 + ) + }, + table + ); } - } - if (styles != null && styles.dragOverlay) { - for (const [key2, value] of Object.entries(styles.dragOverlay)) { - if (value === void 0) { - continue; + }; + const syncAllMetadata = (f4) => { + const files = f4.rows.map((f5) => f5.File); + const importYAML = (files2, fmKeys) => { + return files2.map((f5) => getAbstractFileAtPath(props2.plugin, f5)).filter((f5) => f5).reduce( + (p3, c4) => { + const fm = frontMatterForFile(props2.plugin, c4); + if (!fm) + return p3; + return { + uniques: [], + cols: uniq([...p3.cols, ...fmKeys]), + rows: [ + ...p3.rows, + { + File: c4.path, + ...fmKeys.reduce((p4, c5) => { + const value = parseFrontMatter(c5, fm[c5]); + if ((value == null ? void 0 : value.length) > 0) + return { ...p4, [c5]: value }; + return p4; + }, {}) + } + ] + }; + }, + { uniques: [], cols: [], rows: [] } + ); + }; + const yamlTableData = importYAML( + files, + f4.cols.filter((f5) => !f5.type.contains("file")).map((f5) => f5.name) + ); + const newRows = f4.rows.map((r3) => { + const fmRow = yamlTableData.rows.find((f5) => f5.File == r3.File); + if (fmRow) { + return { + ...r3, + ...fmRow + }; } - dragOverlay.node.style.setProperty(key2, value); - } - } - if (className != null && className.active) { - active.node.classList.add(className.active); - } - if (className != null && className.dragOverlay) { - dragOverlay.node.classList.add(className.dragOverlay); - } - return function cleanup() { - for (const [key2, value] of Object.entries(originalStyles)) { - active.node.style.setProperty(key2, value); - } - if (className != null && className.active) { - active.node.classList.remove(className.active); + return r3; + }); + const rowsChanged = !import_lodash4.default.isEqual(newRows, tableData == null ? void 0 : tableData.rows); + const colsChanged = !import_lodash4.default.isEqual(tableData == null ? void 0 : tableData.cols, f4.cols); + if (rowsChanged || colsChanged) { + saveDB2({ + ...f4, + rows: newRows + }); } }; -}; -var defaultKeyframeResolver = (_ref2) => { - let { - transform: { - initial, - final + const refreshSpace = async (evt) => { + if (evt.detail.type == "context") { + refreshMDB(evt.detail.name); + return; } - } = _ref2; - return [{ - transform: CSS.Transform.toString(initial) - }, { - transform: CSS.Transform.toString(final) - }]; -}; -var defaultDropAnimationConfiguration = { - duration: 250, - easing: "ease", - keyframes: defaultKeyframeResolver, - sideEffects: /* @__PURE__ */ defaultDropAnimationSideEffects({ - styles: { - active: { - opacity: "0" - } + if (evt.detail.type == "vault") { + refreshMDB(spaceInfo.path); } - }) -}; -function useDropAnimation(_ref3) { - let { - config, - draggableNodes, - droppableContainers, - measuringConfiguration - } = _ref3; - return useEvent((id2, node) => { - if (config === null) { + }; + const refreshMDB = async (contextPath) => { + if (!dbFileExists || (dbSchema == null ? void 0 : dbSchema.primary) != "true") { return; } - const activeDraggable = draggableNodes.get(id2); - if (!activeDraggable) { - return; + const tag = Object.keys(contextTable).find( + (t4) => spaceFromTag(props2.plugin, t4).path == contextPath + ); + if (tag) + loadContextFields(tag); + }; + p2(() => { + window.addEventListener(eventTypes.spacesChange, refreshSpace); + return () => { + window.removeEventListener(eventTypes.spacesChange, refreshSpace); + }; + }, [refreshSpace]); + p2(() => { + if (schema) { + parsePredicate(schema.predicate); } - const activeNode = activeDraggable.node.current; - if (!activeNode) { + }, [schema]); + p2(() => { + if (dbFileExists && tableData) + getContextTags(tableData); + }, [tableData]); + const selectRows = (lastSelected, rows) => { + setSelectedRows(rows); + if (!((dbSchema == null ? void 0 : dbSchema.primary) == "true")) return; + if (lastSelected) { + const path = tableData.rows[parseInt(lastSelected)].File; + const evt = new CustomEvent( + eventTypes.activePathChange, + { + detail: { + selection: path, + path: { + ...uriByString(props2.plugin, spaceInfo.path), + ref: schema == null ? void 0 : schema.id + } + } + } + ); + window.dispatchEvent(evt); + } else { + const evt = new CustomEvent( + eventTypes.activePathChange, + { + detail: { + path: { + ...uriByString(props2.plugin, spaceInfo.path), + ref: schema == null ? void 0 : schema.id + }, + selection: null + } + } + ); + window.dispatchEvent(evt); } - const measurableNode = getMeasurableNode(node); - if (!measurableNode) { - return; + }; + const getContextTags = async (_tableData) => { + const contextFields = _tableData.cols.filter((f4) => f4.type.contains("context")).map((f4) => f4.value).filter((f4) => !contexts.some((g4) => g4 == f4)); + for (const c4 of contextFields) { + loadContextFields(c4); } - const { - transform - } = getWindow(node).getComputedStyle(node); - const parsedTransform = parseTransform(transform); - if (!parsedTransform) { - return; + }; + p2(() => { + if (tableData) { + for (const c4 of contexts) { + loadTagContext(c4, tableData.rows); + } } - const animation = typeof config === "function" ? config : createDefaultDropAnimation(config); - scrollIntoViewIfNeeded(activeNode, measuringConfiguration.draggable.measure); - return animation({ - active: { - id: id2, - data: activeDraggable.data, - node: activeNode, - rect: measuringConfiguration.draggable.measure(activeNode) - }, - draggableNodes, - dragOverlay: { - node, - rect: measuringConfiguration.dragOverlay.measure(measurableNode) - }, - droppableContainers, - measuringConfiguration, - transform: parsedTransform + }, [tableData]); + const loadTagContext = async (tag, files) => { + getMDBTable( + props2.plugin, + spaceFromTag(props2.plugin, tag), + "files", + "context" + ).then((f4) => { + if (f4) { + const contextFields = f4.cols.filter((g4) => g4.type.contains("context")).map((g4) => g4.value).filter((g4) => !contexts.some((h5) => h5 == g4)); + for (const c4 of contextFields) { + loadContextFields(c4); + } + setContextTable((t4) => ({ + ...t4, + [tag]: f4 + })); + } }); - }); -} -function createDefaultDropAnimation(options) { - const { - duration, - easing, - sideEffects, - keyframes - } = { - ...defaultDropAnimationConfiguration, - ...options }; - return (_ref4) => { - let { - active, - dragOverlay, - transform, - ...rest - } = _ref4; - if (!duration) { - return; + const loadContextFields = async (tag) => { + getMDBTable( + props2.plugin, + spaceFromTag(props2.plugin, tag), + "files", + "context" + ).then((f4) => { + setContextTable((t4) => ({ + ...t4, + [tag]: f4 + })); + }); + }; + const saveContextDB = async (newTable, tag) => { + const context = spaceFromTag(props2.plugin, tag); + await saveMDBToPath(props2.plugin, context, newTable).then( + (f4) => f4 && setContextTable((t4) => ({ + ...t4, + [tag]: newTable + })) + ); + }; + const savePredicate = (newPredicate) => { + const cleanedPredicate = validatePredicate(newPredicate); + saveSchema({ + ...schema, + predicate: JSON.stringify(cleanedPredicate) + }); + setPredicate(cleanedPredicate); + }; + p2(() => { + setPredicate((p3) => ({ + ...p3, + colsOrder: uniq([ + ...p3.colsOrder, + ...cols.filter((f4) => f4.hidden != "true").map((c4) => c4.name + c4.table) + ]) + })); + }, [cols]); + const parsePredicate = (predicateStr) => { + const newPredicate = safelyParseJSON(predicateStr); + setPredicate(validatePredicate(newPredicate)); + }; + const delColumn = (column) => { + let mdbtable; + const table = column.table; + if (table == "") { + mdbtable = tableData; + } else if (contextTable[table]) { + mdbtable = contextTable[table]; } - const delta = { - x: dragOverlay.rect.left - active.rect.left, - y: dragOverlay.rect.top - active.rect.top + const newFields = mdbtable.cols.filter( + (f4, i4) => f4.name != column.name + ); + const newTable = { + ...mdbtable, + cols: newFields, + rows: mdbtable.rows.map((r3) => { + const { [column.name]: val, ...rest } = r3; + return rest; + }) }; - const scale = { - scaleX: transform.scaleX !== 1 ? active.rect.width * transform.scaleX / dragOverlay.rect.width : 1, - scaleY: transform.scaleY !== 1 ? active.rect.height * transform.scaleY / dragOverlay.rect.height : 1 + if (table == "") { + saveDB2(newTable); + } else if (contextTable[table]) { + saveContextDB(newTable, table); + } + }; + const newColumn = (col) => { + return saveColumn(col); + }; + const saveColumn = (newColumn2, oldColumn) => { + let mdbtable; + const column = { + ...newColumn2, + name: sanitizeColumnName(newColumn2.name) }; - const finalTransform = { - x: transform.x - delta.x, - y: transform.y - delta.y, - ...scale + const table = column.table; + if (table == "") { + mdbtable = tableData; + } else if (contextTable[table]) { + mdbtable = contextTable[table]; + } + if (column.name == "") { + new import_obsidian14.Notice(i18n_default.notice.noPropertyName); + return false; + } + if (!oldColumn && mdbtable.cols.find( + (f4) => f4.name.toLowerCase() == column.name.toLowerCase() + ) || oldColumn && oldColumn.name != column.name && mdbtable.cols.find( + (f4) => f4.name.toLowerCase() == column.name.toLowerCase() + )) { + new import_obsidian14.Notice(i18n_default.notice.duplicatePropertyName); + return false; + } + const oldFieldIndex = oldColumn ? mdbtable.cols.findIndex((f4) => f4.name == oldColumn.name) : -1; + const newFields = oldFieldIndex == -1 ? [...mdbtable.cols, column] : mdbtable.cols.map((f4, i4) => i4 == oldFieldIndex ? column : f4); + const newTable = { + ...mdbtable, + cols: newFields, + rows: mdbtable.rows.map( + (f4) => oldColumn ? { + ...f4, + [column.name]: f4[oldColumn.name], + oldColumn: void 0 + } : f4 + ) }; - const animationKeyframes = keyframes({ - ...rest, - active, - dragOverlay, - transform: { - initial: transform, - final: finalTransform - } - }); - const [firstKeyframe] = animationKeyframes; - const lastKeyframe = animationKeyframes[animationKeyframes.length - 1]; - if (JSON.stringify(firstKeyframe) === JSON.stringify(lastKeyframe)) { - return; + if (oldColumn) + savePredicate({ + view: predicate.view, + frame: predicate.frame, + frameProps: predicate.frameProps, + filters: predicate.filters.map( + (f4) => f4.field == oldColumn.name + oldColumn.table ? { ...f4, field: column.name + column.table } : f4 + ), + sort: predicate.sort.map( + (f4) => f4.field == oldColumn.name + oldColumn.table ? { ...f4, field: column.name + column.table } : f4 + ), + groupBy: predicate.groupBy.map( + (f4) => f4 == oldColumn.name + oldColumn.table ? column.name + column.table : f4 + ), + colsHidden: predicate.colsHidden.map( + (f4) => f4 == oldColumn.name + oldColumn.table ? column.name + column.table : f4 + ), + colsOrder: predicate.colsOrder.map( + (f4) => f4 == oldColumn.name + oldColumn.table ? column.name + column.table : f4 + ), + colsSize: { + ...predicate.colsSize, + [column.name + column.table]: predicate.colsSize[oldColumn.name + oldColumn.table], + [oldColumn.name + oldColumn.table]: void 0 + } + }); + if (table == "") { + syncAllMetadata(newTable); + } else if (contextTable[table]) { + saveContextDB(newTable, table); } - const cleanup = sideEffects == null ? void 0 : sideEffects({ - active, - dragOverlay, - ...rest - }); - const animation = dragOverlay.node.animate(animationKeyframes, { - duration, - easing, - fill: "forwards" - }); - return new Promise((resolve) => { - animation.onfinish = () => { - cleanup == null ? void 0 : cleanup(); - resolve(); - }; - }); + return true; }; -} -var key = 0; -function useKey(id2) { - return F2(() => { - if (id2 == null) { - return; + return /* @__PURE__ */ Cn.createElement(ContextEditorContext.Provider, { + value: { + cols, + data: data2, + views, + schema, + setSchema, + filteredData, + loadContextFields, + selectedRows, + selectRows, + sortedColumns, + contextTable, + setContextTable, + predicate, + savePredicate, + saveContextDB, + saveColumn, + hideColumn, + sortColumn, + delColumn, + newColumn, + searchString, + setSearchString, + updateValue: updateValue2, + updateFieldValue } - key++; - return key; - }, [id2]); + }, props2.children); +}; + +// src/hooks/useCombinedRef.tsx +function useCombinedRefs2(...refs) { + return F2( + () => (node) => { + refs.forEach((ref2) => ref2(node)); + }, + refs + ); } -var DragOverlay = /* @__PURE__ */ Cn.memo((_ref) => { - let { - adjustScale: adjustScale2 = false, - children, - dropAnimation: dropAnimationConfig, - style, - transition, - modifiers, - wrapperElement = "div", - className, - zIndex = 999 - } = _ref; + +// src/components/SpaceView/Contexts/TableView/ColumnHeader.tsx +var filePropTypes = [ + { + name: i18n_default.properties.fileProperty.createdTime, + value: "ctime" + }, + { + name: i18n_default.properties.fileProperty.modifiedTime, + value: "mtime" + }, + { + name: i18n_default.properties.fileProperty.extension, + value: "extension" + }, + { + name: i18n_default.properties.fileProperty.size, + value: "size" + }, + { + name: i18n_default.properties.fileProperty.parentFolder, + value: "folder" + }, + { + name: "Links", + value: "links" + }, + { + name: "Tags", + value: "tags" + }, + { + name: "Spaces", + value: "spaces" + } +]; +var ColumnHeader = (props2) => { + var _a2, _b2; + const [field, setField] = h2(props2.column); + const menuRef = _2(null); + const { spaceInfo, spaceCache } = q2(SpaceContext); + const { tableData, contextTable } = q2(ContextMDBContext); + const { + predicate, + loadContextFields, + cols, + newColumn, + saveColumn, + hideColumn, + sortColumn, + delColumn + } = q2(ContextEditorContext); + p2(() => { + setField(props2.column); + }, [props2.column]); const { - activatorEvent, - active, - activeNodeRect, - containerNodeRect, - draggableNodes, - droppableContainers, - dragOverlay, - over, - measuringConfiguration, - scrollableAncestors, - scrollableAncestorRects, - windowRect - } = useDndContext(); - const transform = q2(ActiveDraggableContext); - const key2 = useKey(active == null ? void 0 : active.id); - const modifiedTransform = applyModifiers(modifiers, { - activatorEvent, - active, - activeNodeRect, - containerNodeRect, - draggingNodeRect: dragOverlay.rect, - over, - overlayNodeRect: dragOverlay.rect, - scrollableAncestors, - scrollableAncestorRects, - transform, - windowRect + attributes, + listeners, + setNodeRef: setDraggableNodeRef, + transform + } = useDraggable({ + id: field.name + field.table, + data: { name: field.name } }); - const initialRect = useInitialValue(activeNodeRect); - const dropAnimation = useDropAnimation({ - config: dropAnimationConfig, - draggableNodes, - droppableContainers, - measuringConfiguration + const { setNodeRef: setDroppableNodeRef } = useDroppable({ + id: field.name + field.table, + data: { name: field.name } }); - const ref = initialRect ? dragOverlay.setRef : void 0; - return Cn.createElement(NullifiedContextProvider, null, Cn.createElement(AnimationManager, { - animation: dropAnimation - }, active && key2 ? Cn.createElement(PositionedOverlay, { - key: key2, - id: active.id, - ref, - as: wrapperElement, - activatorEvent, - adjustScale: adjustScale2, - className, - transition, - rect: initialRect, - style: { - zIndex, - ...style - }, - transform: modifiedTransform - }, children) : null)); -}); + const saveField = (field2) => { + if (field2.name.length > 0) { + if (field2.name != props2.column.name || field2.type != props2.column.type || field2.value != props2.column.value || field2.attrs != props2.column.attrs) { + const saveResult = saveColumn(field2, props2.column); + if (saveResult) { + if (props2.isNew) { + setField(props2.column); + } + } + } + } + }; + const showNewMenu = (e4) => { + var _a3; + const offset2 = ref2.current.getBoundingClientRect(); + showNewPropertyMenu( + props2.plugin, + { x: offset2.left, y: offset2.top + 30 }, + (_a3 = spaceCache == null ? void 0 : spaceCache.contexts) != null ? _a3 : [], + cols, + (source, field2) => newColumn({ ...field2, table: source }), + tableData.schema.id, + spaceInfo.path, + false + ); + }; + const toggleMenu = (e4) => { + if (props2.isNew) { + showNewMenu(e4); + } else { + const offset2 = e4.target.getBoundingClientRect(); + const options = optionValuesForColumn( + field.name, + field.table == "" ? tableData : contextTable[field.table] + ); + showPropertyMenu({ + plugin: props2.plugin, + position: { x: offset2.left, y: offset2.top + 30 }, + editable: props2.editable, + options, + field, + fields: cols, + contextPath: spaceInfo.path, + saveField, + hide: hideColumn, + deleteColumn: delColumn, + sortColumn, + hidden: predicate.colsHidden.includes(field.name + field.table) + }); + } + }; + const ref2 = _2(null); + const setNodeRef = useCombinedRefs2(setDroppableNodeRef, setDraggableNodeRef); + return /* @__PURE__ */ Cn.createElement("div", { + ref: setNodeRef, + ...listeners, + ...attributes, + className: "mk-col-header", + onClick: (e4) => { + toggleMenu(e4); + } + }, /* @__PURE__ */ Cn.createElement("div", { + ref: ref2 + }, props2.column.name.length > 0 ? /* @__PURE__ */ Cn.createElement(Cn.Fragment, null, /* @__PURE__ */ Cn.createElement("div", { + dangerouslySetInnerHTML: { + __html: stickerFromString( + ((_a2 = props2.column.attrs) == null ? void 0 : _a2.length) > 0 ? props2.column.attrs : (_b2 = fieldTypeForType(props2.column.type)) == null ? void 0 : _b2.icon, + props2.plugin + ) + } + }), field.name) : "+", /* @__PURE__ */ Cn.createElement("span", { + className: "mk-col-header-context", + "aria-label": props2.column.table.length > 0 ? props2.column.table : "" + }, props2.column.table.length > 0 ? "#" : ""))); +}; // src/dispatch/mdb.ts -var import_lodash4 = __toESM(require_lodash()); -var import_obsidian13 = require("obsidian"); +var import_lodash5 = __toESM(require_lodash()); +var import_obsidian15 = require("obsidian"); // src/utils/contexts/file.ts var renameRowForFile = (folder, filePath, toFilePath) => { @@ -30102,6 +39248,17 @@ var removeRowsForFile = (folder, filePaths) => { ) }; }; +var reorderRowsForFile = (folder, filePaths, index) => { + const rows = folder.rows.filter( + (f4) => filePaths.includes(f4.File) + ); + return { + ...folder, + rows: insertMulti(folder.rows.filter( + (f4) => !filePaths.includes(f4.File) + ), index, rows) + }; +}; // src/utils/contexts/links.ts var valueContainsLink = (link, value) => { @@ -30227,12 +39384,12 @@ var parseDataview = (field, value) => { }; // src/dispatch/mdb.ts -var processContextFile = async (plugin, context, processor, fallback) => { - const dbFileExists = getAbstractFileAtPath(app, context.dbPath); +var processContextFile = async (plugin, space, processor, fallback) => { + const dbFileExists = await plugin.app.vault.adapter.exists(space.dbPath); if (dbFileExists) { - const contextDB = await getMDBTable(plugin, context, "files"); + const contextDB = await getMDBTable(plugin, space, "files", "context"); if (contextDB) { - await processor(contextDB, context); + await processor(contextDB, space); return; } else if (fallback) { await fallback(); @@ -30244,9 +39401,9 @@ var processContextFile = async (plugin, context, processor, fallback) => { var saveDB = async (plugin, context, newTable) => { return saveMDBToPath(plugin, context, newTable); }; -var insertColumns = (table, column) => { +var insertColumn = (table, column) => { if (table.cols.find((f4) => f4.name == column.name)) { - new import_obsidian13.Notice(i18n_default.notice.duplicatePropertyName); + new import_obsidian15.Notice(i18n_default.notice.duplicatePropertyName); return; } return { @@ -30254,6 +39411,23 @@ var insertColumns = (table, column) => { cols: [...table.cols, column] }; }; +var insertColumns = (table, columns) => { + return { + ...table, + cols: [...table.cols, ...columns.filter((f4) => !table.cols.some((g4) => g4.name == f4.name))] + }; +}; +var deletePropertyMultiValue = (folder, lookupField, lookupValue, field, value) => { + return { + ...folder, + rows: folder.rows.map( + (f4) => f4[lookupField] == lookupValue ? { + ...f4, + [field]: serializeMultiString(parseMultiString(f4[field]).filter((g4) => g4 != value)) + } : f4 + ) + }; +}; var updateValue = (folder, lookupField, lookupValue, field, value) => { return { ...folder, @@ -30265,69 +39439,75 @@ var updateValue = (folder, lookupField, lookupValue, field, value) => { ) }; }; -var insertRowsIfUnique = (folder, rows) => { - return { ...folder, rows: [...folder.rows, ...rows.filter((f4) => !folder.rows.some((g4) => g4.File == f4.File))] }; +var insertRowsIfUnique = (folder, rows, index) => { + return { ...folder, rows: index ? insertMulti(folder.rows, index, rows.filter((f4) => !folder.rows.some((g4) => g4.File == f4.File))) : [...folder.rows, ...rows.filter((f4) => !folder.rows.some((g4) => g4.File == f4.File))] }; }; var saveContextToFrontmatter = (file, cols, context, plugin) => { - const afile = getAbstractFileAtPath(app, file); - if (afile && afile instanceof import_obsidian13.TFile) + const afile = getAbstractFileAtPath(plugin, file); + if (afile && afile instanceof import_obsidian15.TFile) saveContextToFile(afile, cols, context, plugin); }; -var initiateContextIfNotExists = async (plugin, tag) => { - const context = tagContextFromTag(plugin, tag); - const tagFileExists = getAbstractFileAtPath(app, context.dbPath); - if (tagFileExists) - return false; - return createDefaultDB(plugin, context); -}; -var updateContextValue = async (plugin, context, file, field, value) => { - let tagFileExists = abstractFileAtPathExists(app, context.dbPath); +var updateContextValue = async (plugin, space, file, field, value, _updateFunction) => { + let tagFileExists = await plugin.app.vault.adapter.exists(space.dbPath); if (!tagFileExists) { - tagFileExists = await createDefaultDB(plugin, context); + tagFileExists = await createContextMDB(plugin, space); } if (tagFileExists) - await getMDBTable(plugin, context, "files").then( + await getMDBTable(plugin, space, "files", "context").then( (tagDB) => { - const newMDB = updateValue(tagDB, FilePropertyName, file, field, value); - return saveDB(plugin, context, newMDB).then((f4) => newMDB); + const updateFunction = _updateFunction != null ? _updateFunction : updateValue; + const newMDB = updateFunction(tagDB, FilePropertyName, file, field, value); + return saveDB(plugin, space, newMDB).then((f4) => newMDB); } ); }; -var insertContextColumn = async (plugin, context, field) => { - let tagFileExists = abstractFileAtPathExists(app, context.dbPath); +var insertContextColumn = async (plugin, space, field) => { + let tagFileExists = await plugin.app.vault.adapter.exists(space.dbPath); + if (!tagFileExists) { + tagFileExists = await createContextMDB(plugin, space); + } + if (tagFileExists) + await getMDBTable(plugin, space, "files", "context").then((tagDB) => { + const newDB = insertColumn(tagDB, field); + saveDB(plugin, space, newDB).then((f4) => newDB); + return newDB; + }).then((f4) => plugin.index.reloadContext(space)); +}; +var insertContextColumns = async (plugin, space, fields) => { + let tagFileExists = await plugin.app.vault.adapter.exists(space.dbPath); if (!tagFileExists) { - tagFileExists = await createDefaultDB(plugin, context); + tagFileExists = await createContextMDB(plugin, space); } if (tagFileExists) - await getMDBTable(plugin, context, "files").then((tagDB) => { - const newDB = insertColumns(tagDB, field); - saveDB(plugin, context, newDB).then((f4) => newDB); + await getMDBTable(plugin, space, "files", "context").then((tagDB) => { + const newDB = insertColumns(tagDB, fields); + saveDB(plugin, space, newDB).then((f4) => newDB); return newDB; - }).then((f4) => plugin.index.reloadContext(context)); + }).then((f4) => plugin.index.reloadContext(space)); }; var insertContextItems = async (plugin, newPaths, t4) => { - const saveNewContextRows = async (tag, context2) => { + const saveNewContextRows = async (tag, space2) => { const newRow = newPaths.map((newPath) => ({ File: newPath })); - await saveDB(plugin, context2, insertRowsIfUnique(tag, newRow)); + await saveDB(plugin, space2, insertRowsIfUnique(tag, newRow)); }; - const context = tagContextFromTag(plugin, t4); - let tagFileExists = abstractFileAtPathExists(app, context.dbPath); + const space = plugin.index.spacesIndex.get(t4); + let tagFileExists = await plugin.app.vault.adapter.exists(space.space.dbPath); if (!tagFileExists) { - tagFileExists = await createDefaultDB(plugin, context); + tagFileExists = await createContextMDB(plugin, space.space); } if (tagFileExists) - await getMDBTable(plugin, context, "files").then( - (tagDB) => saveNewContextRows(tagDB, context) + await getMDBTable(plugin, space.space, "files", "context").then( + (tagDB) => saveNewContextRows(tagDB, space.space) ); }; var fileToFM = (afile, cols, plugin) => { let file = afile; - if (afile instanceof import_obsidian13.TFolder) { - file = getAbstractFileAtPath(app, folderNotePathFromAFile(plugin.settings, tFileToAFile(afile))); + if (afile instanceof import_obsidian15.TFolder) { + file = getAbstractFileAtPath(plugin, folderNotePathFromAFile(plugin.settings, tFileToAFile(afile))); } if (!file) return []; - const fm = frontMatterForFile(file); + const fm = frontMatterForFile(plugin, file); const fmKeys = frontMatterKeys(fm).filter((f4) => cols.some((g4) => f4 == g4)); const rows = fmKeys.reduce( (p3, c4) => ({ ...p3, [c4]: parseFrontMatter(c4, fm[c4]) }), @@ -30355,570 +39535,339 @@ var fileToDV = (file, cols, plugin) => { {} ); }; -var onMetadataChange = async (plugin, file, contexts) => { - const promises = contexts.map((context) => { - return processContextFile(plugin, context, async (mdb, context2) => { +var onMetadataChange = async (plugin, file, spaces) => { + const updateFile = (mdb) => { + const objectExists = mdb.rows.some((item) => item.File === file.path); + if (objectExists) { + return mdb.rows.map( + (f4) => f4.File == file.path ? { + ...f4, + ...fileToFM( + file, + mdb.cols.map((f5) => f5.name), + plugin + ) + } : f4 + ); + } else { + return [ + ...mdb.rows, + { + File: file.path, + ...fileToFM( + file, + mdb.cols.map((f4) => f4.name), + plugin + ) + } + ]; + } + }; + const promises = spaces.map((space) => { + return processContextFile(plugin, space, async (mdb, space2) => { const newDB = { ...mdb, - rows: mdb.rows.map( - (f4) => f4.File == file.path ? { - ...f4, - ...fileToFM( - file, - mdb.cols.map((f5) => f5.name), - plugin - ) - } : f4 - ) + rows: updateFile(mdb) }; - if (!import_lodash4.default.isEqual(mdb, newDB)) { - await saveDB(plugin, context2, newDB); + if (!import_lodash5.default.isEqual(mdb, newDB)) { + await saveDB(plugin, space2, newDB); } return newDB; }); }); return Promise.all(promises); }; -var renameTagInContexts = async (plugin, oldTag, newTag, contexts) => { +var updateValueInContext = async (plugin, row, field, value, space) => { + const changeTagInContextMDB = (mdb) => { + return { ...mdb, rows: mdb.rows.map((f4) => f4.File == row ? { ...f4, [field]: value } : f4) }; + }; + return processContextFile(plugin, space, async (mdb, space2) => { + const newDB = changeTagInContextMDB(mdb); + if (!import_lodash5.default.isEqual(mdb, newDB)) { + await saveDB(plugin, space2, newDB); + } + return newDB; + }); +}; +var renameTagInContexts = async (plugin, oldTag, newTag, spaces) => { const changeTagInContextMDB = (mdb) => { - const schema = parseContextDefString(mdb.schema.def).some((t4) => t4.type == "tag" && t4.value == oldTag) ? { ...mdb.schema, def: updateTagsForDefString(mdb.schema.def, tagsFromDefString(mdb.schema.def).map((t4) => t4 == oldTag ? newTag : t4)) } : mdb.schema; const cols = mdb.cols.map((f4) => f4.type.startsWith("context") && f4.value == oldTag ? { ...f4, value: newTag } : f4); - return { ...mdb, schema, cols }; + return { ...mdb, cols }; }; - const promises = contexts.map((context) => { - return processContextFile(plugin, context, async (mdb, context2) => { + const promises = spaces.map((space) => { + return processContextFile(plugin, space, async (mdb, space2) => { const newDB = changeTagInContextMDB(mdb); - if (!import_lodash4.default.isEqual(mdb, newDB)) { - await saveDB(plugin, context2, newDB); + if (!import_lodash5.default.isEqual(mdb, newDB)) { + await saveDB(plugin, space2, newDB); } return newDB; }); }); return Promise.all(promises); }; -var removeTagInContexts = async (plugin, tag, contexts) => { +var removeTagInContexts = async (plugin, tag, spaces) => { const deleteTagInContextMDB = (mdb) => { - const schema = parseContextDefString(mdb.schema.def).some((t4) => t4.type == "tag" && t4.value == tag) ? { ...mdb.schema, def: updateTagsForDefString(mdb.schema.def, tagsFromDefString(mdb.schema.def).filter((t4) => t4 != tag)) } : mdb.schema; const cols = mdb.cols.map((f4) => f4.type.startsWith("context") && f4.value == tag ? { ...f4, type: "link-multi" } : f4); - return { ...mdb, schema, cols }; + return { ...mdb, cols }; }; - const promises = contexts.map((context) => { - return processContextFile(plugin, context, async (mdb, context2) => { + const promises = spaces.map((space) => { + return processContextFile(plugin, space, async (mdb, space2) => { const newDB = deleteTagInContextMDB(mdb); - if (!import_lodash4.default.isEqual(mdb, newDB)) { - await saveDB(plugin, context2, newDB); + if (!import_lodash5.default.isEqual(mdb, newDB)) { + await saveDB(plugin, space2, newDB); } return newDB; }); }); return Promise.all(promises); }; -var addFileInContexts = async (plugin, path, contexts) => { - const promises = contexts.map((context) => { - return processContextFile(plugin, context, async (mdb, context2) => { - const newDB = insertRowsIfUnique(mdb, [{ File: path }]); - if (!import_lodash4.default.isEqual(mdb, newDB)) { - await saveDB(plugin, context2, newDB); +var addFileInContexts = async (plugin, path, contexts, index) => { + const promises = contexts.map((space) => { + return processContextFile(plugin, space, async (mdb, space2) => { + const newDB = insertRowsIfUnique(mdb, [{ File: path }], index); + if (!import_lodash5.default.isEqual(mdb, newDB)) { + await saveDB(plugin, space2, newDB); } return newDB; }); }); return Promise.all(promises); }; -var renameLinkInContexts = async (plugin, oldPath, newPath, contexts) => { - const promises = contexts.map((context) => { - return processContextFile(plugin, context, async (mdb, context2) => { +var renameLinkInContexts = async (plugin, oldPath, newPath, spaces) => { + const promises = spaces.map((space) => { + return processContextFile(plugin, space, async (mdb, space2) => { const linkCols = linkColumns(mdb.cols); const newDB = { ...mdb, rows: mdb.rows.map((r3) => renameLinksInRow(plugin, r3, oldPath, newPath, linkCols)) }; - if (!import_lodash4.default.isEqual(mdb, newDB)) { - await saveDB(plugin, context2, newDB); + if (!import_lodash5.default.isEqual(mdb, newDB)) { + await saveDB(plugin, space2, newDB); } return newDB; }); }); return Promise.all(promises); }; -var removeLinkInContexts = async (plugin, path, contexts) => { - const promises = contexts.map((context) => { - return processContextFile(plugin, context, async (mdb, context2) => { +var removeLinkInContexts = async (plugin, path, spaces) => { + const promises = spaces.map((space) => { + return processContextFile(plugin, space, async (mdb, space2) => { const linkCols = linkColumns(mdb.cols); const newDB = { ...mdb, rows: mdb.rows.map((r3) => removeLinksInRow(plugin, r3, path, linkCols)) }; - if (!import_lodash4.default.isEqual(mdb, newDB)) { - await saveDB(plugin, context2, newDB); + if (!import_lodash5.default.isEqual(mdb, newDB)) { + await saveDB(plugin, space2, newDB); } return newDB; }); }); return Promise.all(promises); }; -var renameFileInContexts = async (plugin, oldPath, newPath, contexts) => { - const promises = contexts.map((context) => { - return processContextFile(plugin, context, async (mdb, context2) => { +var renameFileInContexts = async (plugin, oldPath, newPath, spaces) => { + const promises = spaces.map((space) => { + return processContextFile(plugin, space, async (mdb, space2) => { const newDB = renameRowForFile(mdb, oldPath, newPath); - if (!import_lodash4.default.isEqual(mdb, newDB)) { - await saveDB(plugin, context2, newDB); + if (!import_lodash5.default.isEqual(mdb, newDB)) { + await saveDB(plugin, space2, newDB); } return newDB; }); }); return Promise.all(promises); }; -var removeFileInContexts = async (plugin, path, contexts) => { - const promises = contexts.map((context) => { - return processContextFile(plugin, context, async (mdb, context2) => { +var removeFileInContexts = async (plugin, path, spaces) => { + const promises = spaces.map((space) => { + return processContextFile(plugin, space, async (mdb, space2) => { const removeRow = mdb.rows.find((f4) => f4.File == path); if (removeRow) { saveContextToFrontmatter(path, mdb.cols, removeRow, plugin); } const newDB = removeRowForFile(mdb, path); - if (!import_lodash4.default.isEqual(mdb, newDB)) { - await saveDB(plugin, context2, newDB); + if (!import_lodash5.default.isEqual(mdb, newDB)) { + await saveDB(plugin, space2, newDB); } return newDB; }); }); return Promise.all(promises); }; -var removeFilesInContext = async (plugin, paths, context) => { - return processContextFile(plugin, context, async (mdb, context2) => { +var reorderFilesInContext = async (plugin, paths, index, space) => { + return processContextFile(plugin, space, async (mdb, context) => { + const newDB = reorderRowsForFile(mdb, paths, index); + if (!import_lodash5.default.isEqual(mdb, newDB)) { + await saveDB(plugin, context, newDB); + } + return newDB; + }); +}; +var removeFilesInContext = async (plugin, paths, space) => { + return processContextFile(plugin, space, async (mdb, context) => { mdb.rows.forEach((row) => { if (paths.includes(row.File)) saveContextToFrontmatter(row.File, mdb.cols, row, plugin); }); const newDB = removeRowsForFile(mdb, paths); - if (!import_lodash4.default.isEqual(mdb, newDB)) { - await saveDB(plugin, context2, newDB); + if (!import_lodash5.default.isEqual(mdb, newDB)) { + await saveDB(plugin, context, newDB); } return newDB; }); }; -// src/hooks/useCombinedRef.tsx -function useCombinedRefs2(...refs) { - return F2( - () => (node) => { - refs.forEach((ref) => ref(node)); - }, - refs - ); -} - -// src/components/ContextView/TableView/ColumnHeader.tsx -var filePropTypes = [ - { - name: i18n_default.properties.fileProperty.createdTime, - value: "ctime" - }, - { - name: i18n_default.properties.fileProperty.modifiedTime, - value: "mtime" - }, - { - name: i18n_default.properties.fileProperty.extension, - value: "extension" - }, - { - name: i18n_default.properties.fileProperty.size, - value: "size" - }, - { - name: i18n_default.properties.fileProperty.parentFolder, - value: "folder" - }, - { - name: "Links", - value: "links" - }, - { - name: "Tags", - value: "tags" - }, - { - name: "Spaces", - value: "spaces" - } -]; -var ColumnHeader = (props2) => { - const [field, setField] = h2(props2.column); - const menuRef = _2(null); - const { - loadContextFields, - contextInfo, - predicate, - tableData, - tagContexts, - contextTable, - cols, - newColumn, - saveColumn, - hideColumn, - sortColumn, - delColumn - } = q2(MDBContext); - p2(() => { - setField(props2.column); - }, [props2.column]); - const { - attributes, - listeners, - setNodeRef: setDraggableNodeRef, - transform - } = useDraggable({ - id: field.name + field.table, - data: { name: field.name } - }); - const { setNodeRef: setDroppableNodeRef } = useDroppable({ - id: field.name + field.table, - data: { name: field.name } - }); - const saveField = (field2) => { - if (field2.name.length > 0) { - if (field2.name != props2.column.name || field2.type != props2.column.type || field2.value != props2.column.value || field2.attrs != props2.column.attrs) { - const saveResult = saveColumn(field2, props2.column); - if (saveResult) { - if (props2.isNew) { - setField(props2.column); - } - } - } - } - }; - const saveContext = (field2, value) => { - const newContext = value[0]; - connectContext(props2.plugin, value[0], contextInfo.dbPath); - initiateContextIfNotExists(props2.plugin, newContext).then((f4) => { - if (f4) { - return insertContextItems( - props2.plugin, - optionValuesForColumn( - field2.name, - field2.table == "" ? tableData : contextTable[field2.table] - ), - newContext - ); - } - }).then((f4) => loadContextFields(newContext)); - const newField = { - ...field2, - value: newContext != null ? newContext : "" - }; - setField(newField); - saveColumn(newField, props2.column); - }; - const showNewMenu = (e4) => { - const offset = ref.current.getBoundingClientRect(); - showNewPropertyMenu( - props2.plugin, - { x: offset.left, y: offset.top + 30 }, - tagContexts, - cols, - (source, field2) => newColumn({ ...field2, table: source }), - tableData.schema.id, - contextInfo.contextPath, - false - ); - }; - const toggleMenu = (e4) => { - if (props2.isNew) { - showNewMenu(e4); - } else { - const offset = e4.target.getBoundingClientRect(); - const options = optionValuesForColumn( - field.name, - field.table == "" ? tableData : contextTable[field.table] - ); - showPropertyMenu( - props2.plugin, - { x: offset.left, y: offset.top + 30 }, - props2.editable, - options, - field, - cols, - contextInfo.contextPath, - saveField, - saveContext, - hideColumn, - delColumn, - sortColumn, - predicate.colsHidden.includes(field.name + field.table) - ); - } - }; - const ref = _2(null); - const setNodeRef = useCombinedRefs2(setDroppableNodeRef, setDraggableNodeRef); - return /* @__PURE__ */ Cn.createElement("div", { - ref: setNodeRef, - ...listeners, - ...attributes, - className: "mk-col-header", - onClick: (e4) => { - toggleMenu(e4); - } - }, /* @__PURE__ */ Cn.createElement("div", { - ref - }, props2.column.name.length > 0 ? field.name : "+", /* @__PURE__ */ Cn.createElement("span", { - className: "mk-col-header-context", - "aria-label": props2.column.table.length > 0 ? props2.column.table : "" - }, props2.column.table.length > 0 ? "#" : ""))); -}; - -// src/components/ui/menus/propertyMenu.tsx -var import_obsidian14 = require("obsidian"); +// src/components/UI/menus/propertyMenu/PropertyValue.tsx var PropertyValueComponent = (props2) => { - const selectContext = (e4) => { - var _a2; + var _a2; + const showOptions = (e4, value, options, field, saveProperty) => { showSelectMenu(e4.target.getBoundingClientRect(), { + plugin: props2.plugin, multi: false, editable: true, searchable: true, - saveOptions: (_9, v3) => props2.saveContext(v3[0]), - placeholder: i18n_default.labels.propertyContext, - value: [(_a2 = props2.value) != null ? _a2 : ""], - options: loadTags(props2.plugin).map((m5) => ({ name: m5, value: m5 })) - }); - }; - const selectFileProp = (e4) => { - var _a2; - const properties2 = (_a2 = props2.plugin.index.contextsIndex.get(props2.contextPath)) == null ? void 0 : _a2.cols.filter( - (f4) => f4.type == "file" || f4.type == "link" || f4.type == "context" - ).reduce((p3, c4) => { - var _a3, _b2; - return [ - ...p3, - ...c4.type == "file" || c4.type == "link" ? filePropTypes.map((f4) => ({ - name: c4.name + "." + f4.name, - value: c4.name + "." + f4.value - })) : (_b2 = (_a3 = props2.plugin.index.contextsIndex.get(c4.value)) == null ? void 0 : _a3.cols.filter((f4) => f4.hidden != "true").map((f4) => ({ - name: c4.name + "." + f4.name, - value: c4.name + "." + f4.name - }))) != null ? _b2 : [] - ]; - }, []); - showSelectMenu(e4.target.getBoundingClientRect(), { - multi: false, - editable: false, - searchable: false, - saveOptions: (_9, v3) => props2.saveValue(v3[0]), - value: [], - options: properties2, - showAll: true - }); - }; - const selectDateFormat = (e4) => { - const formats = [ - { - name: "2020-04-21", - value: "yyyy-MM-dd" - }, - { - name: "Apr 21, 2020", - value: "MMM d, yyyy" + saveOptions: (_12, v3) => { + if (saveProperty) { + saveProperty(v3[0]); + } else { + saveParsedValue(field, v3[0]); + } }, - { - name: "Tue Apr 21, 2020", - value: "EEE MMM d, yyyy" - } - ]; - showSelectMenu(e4.target.getBoundingClientRect(), { - multi: false, - editable: true, - searchable: false, - saveOptions: (_9, v3) => props2.saveValue(v3[0]), - value: [], - options: formats, - showAll: true, - placeholder: i18n_default.labels.selectDateFormat + placeholder: i18n_default.labels.propertyValueSpace, + value: [value != null ? value : ""], + options }); }; - return props2.fieldType.startsWith("date") ? /* @__PURE__ */ Cn.createElement("div", { - className: "menu-item", - onClick: (e4) => selectDateFormat(e4) - }, /* @__PURE__ */ Cn.createElement("span", null, i18n_default.labels.dateFormat), /* @__PURE__ */ Cn.createElement("span", null, props2.value)) : props2.fieldType.startsWith("context") ? /* @__PURE__ */ Cn.createElement("div", { - className: "menu-item", - onClick: (e4) => selectContext(e4) - }, /* @__PURE__ */ Cn.createElement("span", null, i18n_default.labels.propertyContext), /* @__PURE__ */ Cn.createElement("span", null, props2.value)) : props2.fieldType == "fileprop" ? /* @__PURE__ */ Cn.createElement("div", { - className: "menu-item", - onClick: (e4) => selectFileProp(e4) - }, /* @__PURE__ */ Cn.createElement("span", null, i18n_default.labels.propertyFileProp), /* @__PURE__ */ Cn.createElement("span", null, props2.value)) : /* @__PURE__ */ Cn.createElement(Cn.Fragment, null); -}; -var PropertyMenuComponent = (props2) => { - var _a2; - const [field, setField] = h2(props2.field); - const selectedType = (_9, value) => { - const newField = { - ...field, - type: value[0], - value: getNewValueForType(field, value) - }; - setField(newField); - props2.saveField(newField); - }; - const selectedValue = (value) => { - const newField = { ...field, value }; - setField(newField); - props2.saveField(newField); - }; - const selectedContext = (context) => { - const newField = { ...field, value: context }; - setField(newField); - props2.saveContext(newField, [context]); - }; - const toggleMulti = () => { - const newField = { - ...field, - type: field.type == fieldType.multiType ? fieldType.type : fieldType.multiType - }; - setField(newField); - props2.saveField(newField); - }; - const fieldType = (_a2 = fieldTypeForType(field.type)) != null ? _a2 : fieldTypes[0]; - const getNewValueForType = (f4, value) => { - if (value[0].startsWith("option")) { - return serializeMultiString(props2.options); - } - return value[0] == fieldType.type || value[0] == fieldType.multiType ? f4.value : null; - }; - const selectType = (e4) => { - showSelectMenu(e4.target.getBoundingClientRect(), { - multi: false, - editable: false, - searchable: false, - saveOptions: selectedType, - value: [], - showAll: true, - options: fieldTypes.filter((f4) => !f4.restricted).map((f4, i4) => ({ - id: i4 + 1, - name: f4.label, - value: f4.type, - icon: "" - })) - }); + const parsedValue = F2( + () => parseFieldValue(props2.value, props2.fieldType), + [props2.value, props2.fieldType] + ); + const saveParsedValue = (field, value) => { + props2.saveValue(JSON.stringify({ ...parsedValue, [field]: value })); }; - return /* @__PURE__ */ Cn.createElement(Cn.Fragment, null, /* @__PURE__ */ Cn.createElement("div", { - className: "menu-item", - onClick: (e4) => selectType(e4) - }, /* @__PURE__ */ Cn.createElement("span", null, i18n_default.labels.propertyType), /* @__PURE__ */ Cn.createElement("span", null, fieldType.label)), fieldType.multi ? /* @__PURE__ */ Cn.createElement("div", { - className: "menu-item" - }, /* @__PURE__ */ Cn.createElement("span", null, i18n_default.labels.multiple), /* @__PURE__ */ Cn.createElement("input", { - type: "checkbox", - checked: field.type == fieldType.multiType, - onChange: () => toggleMulti() - })) : /* @__PURE__ */ Cn.createElement(Cn.Fragment, null), /* @__PURE__ */ Cn.createElement("div", { - className: "menu-separator" - }), /* @__PURE__ */ Cn.createElement(PropertyValueComponent, { - plugin: props2.plugin, - table: field.table, - fields: props2.fields, - fieldType: fieldType.type, - value: field.value, - contextPath: props2.contextPath, - saveValue: selectedValue, - saveContext: selectedContext - })); -}; -var showPropertyMenu = (plugin, position, editable, options, field, fields, contextPath, saveField, saveContext, hide, deleteColumn, sortColumn, hidden) => { - const menu = new import_obsidian14.Menu(); - menu.setUseNativeMenu(false); - if (editable) { - menu.addItem((menuItem) => { - var _a2; - inputMenuItem( - menuItem, - (_a2 = field == null ? void 0 : field.name) != null ? _a2 : "", - (value) => saveField({ ...field, name: value }) - ); - menuItem.setIcon("type"); - }); - menu.addSeparator(); - const frag = document.createDocumentFragment(); - const div = frag.createDiv(); - div.addEventListener("click", (e4) => { - e4.stopImmediatePropagation(); - }); - div.addEventListener("keydown", (e4) => { - }); - const root = createRoot(div); - root.render( - /* @__PURE__ */ Cn.createElement(Cn.Fragment, null, /* @__PURE__ */ Cn.createElement(PropertyMenuComponent, { - plugin, - field, - fields, - contextPath, - options, - saveField, - saveContext - })) - ); - menu.addItem((menuItem) => { - menuItem.setTitle(frag); - menuItem.dom.toggleClass("mk-properties", true); - }); - menu.addSeparator(); - if (!hidden) { - menu.addItem((menuItem) => { - menuItem.setTitle(i18n_default.menu.hideProperty); - menuItem.onClick(() => { - hide(field, true); - }); - menuItem.setIcon("eye-off"); - }); - } else { - menu.addItem((menuItem) => { - menuItem.setTitle(i18n_default.menu.unhideProperty); - menuItem.onClick(() => { - hide(field, false); - }); - menuItem.setIcon("eye"); - }); - } - menu.addItem((menuItem) => { - menuItem.setTitle(i18n_default.menu.deleteProperty); - menuItem.onClick(() => { - deleteColumn(field); - }); - menuItem.setIcon("trash-2"); - }); - menu.addSeparator(); - } - const sortableString = normalizedSortForType(field.type, false); - if (sortableString) { - menu.addItem((menuItem) => { - menuItem.setTitle(i18n_default.menu.sortAscending); - menuItem.setIcon("sort-asc"); - menuItem.onClick(() => { - sortColumn({ - field: field.name + field.table, - fn: normalizedSortForType(field.type, false) - }); - }); - }); - menu.addItem((menuItem) => { - menuItem.setTitle(i18n_default.menu.sortDescending); - menuItem.setIcon("sort-desc"); - menuItem.onClick(() => { - sortColumn({ - field: field.name + field.table, - fn: normalizedSortForType(field.type, true) - }); - }); - }); - } - menu.showAtPosition(position); - return menu; + const saveSpaceProperty = (field) => { + var _a3, _b2; + const colExists = (_b2 = (_a3 = props2.plugin.index.contextsIndex.get(parsedValue.space)) == null ? void 0 : _a3.cols) == null ? void 0 : _b2.some((f4) => f4.name == field); + if (!colExists) { + insertContextColumn( + props2.plugin, + props2.plugin.index.spacesIndex.get(parsedValue.space).space, + { + name: field, + schemaId: "files", + type: "context", + value: props2.name + } + ); + } + saveParsedValue("field", field); + }; + const selectContext = (e4) => { + showOptions( + e4, + parsedValue.space, + props2.plugin.index.allSpaces().filter((f4) => f4.type != "default").map((m5) => ({ name: m5.name, value: m5.path })), + "space" + ); + }; + const selectSpaceProperty = (e4) => { + var _a3, _b2; + showOptions( + e4, + parsedValue.property, + (_b2 = (_a3 = props2.plugin.index.contextsIndex.get(parsedValue.space)) == null ? void 0 : _a3.cols.filter((f4) => { + return f4.type.startsWith("context") && parseFieldValue(f4.value, f4.type)["space"] == props2.contextPath ? true : false; + }).map((m5) => ({ name: m5.name, value: m5.name }))) != null ? _b2 : [], + "field", + saveSpaceProperty + ); + }; + const selectProperty = (e4) => { + var _a3, _b2; + const properties2 = (_b2 = (_a3 = props2.plugin.index.contextsIndex.get(props2.contextPath)) == null ? void 0 : _a3.cols.filter( + (f4) => f4.type == "file" || f4.type == "link" || f4.type == "context" + ).map((f4) => ({ + name: f4.name, + value: f4.name + }))) != null ? _b2 : []; + showOptions(e4, null, properties2, "field"); + }; + const selectFileProp = (e4) => { + var _a3, _b2, _c2; + const property = (_a3 = props2.plugin.index.contextsIndex.get(props2.contextPath)) == null ? void 0 : _a3.cols.find((f4) => f4.name == parsedValue.field); + const fileProps2 = property ? property.type == "file" || property.type == "link" ? filePropTypes.map((f4) => ({ + name: f4.name, + value: f4.value + })) : (_c2 = (_b2 = props2.plugin.index.contextsIndex.get(parseFieldValue(property.value, "context").space)) == null ? void 0 : _b2.cols.filter((f4) => f4.hidden != "true").map((f4) => ({ + name: f4.name, + value: f4.name + }))) != null ? _c2 : [] : []; + showOptions(e4, null, fileProps2, "value"); + }; + const selectDateFormat = (e4) => { + const formats = [ + { + name: "2020-04-21", + value: "yyyy-MM-dd" + }, + { + name: "Apr 21, 2020", + value: "MMM d, yyyy" + }, + { + name: "Tue Apr 21, 2020", + value: "EEE MMM d, yyyy" + } + ]; + showOptions(e4, null, formats, "format"); + }; + return props2.fieldType.startsWith("date") ? /* @__PURE__ */ Cn.createElement("div", { + className: "menu-item", + onClick: (e4) => selectDateFormat(e4) + }, /* @__PURE__ */ Cn.createElement("span", null, i18n_default.labels.dateFormat), /* @__PURE__ */ Cn.createElement("span", null, parsedValue.format)) : props2.fieldType.startsWith("context") ? /* @__PURE__ */ Cn.createElement(Cn.Fragment, null, /* @__PURE__ */ Cn.createElement("div", { + className: "menu-item", + onClick: (e4) => selectContext(e4) + }, /* @__PURE__ */ Cn.createElement("span", null, i18n_default.labels.propertyValueSpace), /* @__PURE__ */ Cn.createElement("span", null, spaceNameFromSpacePath(parsedValue.space, props2.plugin))), ((_a2 = parsedValue.space) == null ? void 0 : _a2.length) > 0 && /* @__PURE__ */ Cn.createElement("div", { + className: "menu-item", + onClick: (e4) => selectSpaceProperty(e4) + }, /* @__PURE__ */ Cn.createElement("span", null, i18n_default.labels.propertyValueProperty), /* @__PURE__ */ Cn.createElement("span", null, parsedValue.field))) : props2.fieldType == "fileprop" ? /* @__PURE__ */ Cn.createElement(Cn.Fragment, null, /* @__PURE__ */ Cn.createElement("div", { + className: "menu-item", + onClick: (e4) => selectProperty(e4) + }, /* @__PURE__ */ Cn.createElement("span", null, i18n_default.labels.propertyFileProp), /* @__PURE__ */ Cn.createElement("span", null, parsedValue.field)), parsedValue.field && /* @__PURE__ */ Cn.createElement("div", { + className: "menu-item", + onClick: (e4) => selectFileProp(e4) + }, /* @__PURE__ */ Cn.createElement("span", null, i18n_default.labels.propertyValueProperty), /* @__PURE__ */ Cn.createElement("span", null, parsedValue.value))) : props2.fieldType == "super" ? /* @__PURE__ */ Cn.createElement(Cn.Fragment, null, /* @__PURE__ */ Cn.createElement("div", { + className: "menu-item" + }, /* @__PURE__ */ Cn.createElement("span", null, "Dynamic"), /* @__PURE__ */ Cn.createElement("input", { + type: "checkbox", + checked: parsedValue.dynamic == true, + onChange: () => saveParsedValue("dynamic", !parsedValue.dynamic) + })), !parsedValue.dynamic ? /* @__PURE__ */ Cn.createElement("div", { + className: "menu-item", + onClick: (e4) => showOptions( + e4, + parsedValue.field, + [...props2.plugin.index.superProperties.keys()].map((f4) => ({ + value: f4, + name: props2.plugin.index.superProperties.get(f4).name + })), + "field" + ) + }, /* @__PURE__ */ Cn.createElement("span", null, "Field"), /* @__PURE__ */ Cn.createElement("span", null, parsedValue.field)) : /* @__PURE__ */ Cn.createElement("div", { + className: "menu-item", + onClick: (e4) => selectProperty(e4) + }, /* @__PURE__ */ Cn.createElement("span", null, i18n_default.labels.propertyFileProp), /* @__PURE__ */ Cn.createElement("span", null, parsedValue.field))) : /* @__PURE__ */ Cn.createElement(Cn.Fragment, null); }; -// src/components/ui/menus/newPropertyMenu.tsx +// src/components/UI/menus/propertyMenu/newPropertyMenu.tsx var NewPropertyMenuComponent = (props2) => { const [fieldName, setFieldName] = h2(""); const [fieldSource, setFieldSource] = h2( props2.fileMetadata ? "fm" : "" ); + const spaceCaches = F2( + () => props2.spaces.map((f4) => props2.plugin.index.spacesIndex.get(f4)).filter((f4) => f4), + [props2.spaces] + ); const [fieldValue, setFieldValue] = h2(""); const [fieldType, setFieldType] = h2("text"); const options = F2(() => { @@ -30926,33 +39875,30 @@ var NewPropertyMenuComponent = (props2) => { if (props2.fileMetadata) { options2.push({ name: i18n_default.menu.fileMetadata, - value: "fm", - description: i18n_default.menu.fileMetadataDescription + value: "fm" }); } if (props2.contextPath) { options2.push({ name: folderPathToString(props2.contextPath), - value: "", - description: `All notes in ${folderPathToString(props2.contextPath)}` + value: "" }); } options2.push( - ...props2.tags.map((f4) => ({ - name: f4, - value: f4, - description: `All notes tagged ${f4}` + ...(spaceCaches != null ? spaceCaches : []).map((f4) => ({ + name: f4.name, + value: f4.path })) ); return options2; - }, []); - const selectedType = (_9, value) => { + }, [spaceCaches]); + const selectedType = (_12, value) => { setFieldType(value[0]); }; const selectedValue = (value) => { setFieldValue(value); }; - const selectedSource = (_9, value) => { + const selectedSource = (_12, value) => { setFieldSource(value[0]); }; const toggleMulti = () => { @@ -30963,6 +39909,7 @@ var NewPropertyMenuComponent = (props2) => { }; const selectType = (e4) => { showSelectMenu(e4.target.getBoundingClientRect(), { + plugin: props2.plugin, multi: false, editable: false, searchable: false, @@ -30989,6 +39936,7 @@ var NewPropertyMenuComponent = (props2) => { ); const selectSource = (e4) => { showSelectMenu(e4.target.getBoundingClientRect(), { + plugin: props2.plugin, multi: false, editable: false, searchable: false, @@ -31000,7 +39948,7 @@ var NewPropertyMenuComponent = (props2) => { }; const saveField = () => { if (fieldName.length == 0) { - new import_obsidian15.Notice(i18n_default.notice.noPropertyName); + new import_obsidian16.Notice(i18n_default.notice.noPropertyName); return; } props2.saveField(fieldSource, { @@ -31036,7 +39984,7 @@ var NewPropertyMenuComponent = (props2) => { }), options.length > 1 && /* @__PURE__ */ Cn.createElement("div", { className: "menu-item", onClick: (e4) => selectSource(e4) - }, /* @__PURE__ */ Cn.createElement("span", null, "Context"), /* @__PURE__ */ Cn.createElement("span", null, fieldSource == "fm" ? "File Metadata" : fieldSource == "" ? props2.contextPath : fieldSource)), /* @__PURE__ */ Cn.createElement("div", { + }, /* @__PURE__ */ Cn.createElement("span", null, "Space"), /* @__PURE__ */ Cn.createElement("span", null, fieldSource == "fm" ? "None" : fieldSource == "" ? props2.contextPath : fieldSource)), /* @__PURE__ */ Cn.createElement("div", { className: "menu-item", onClick: (e4) => selectType(e4) }, /* @__PURE__ */ Cn.createElement("span", null, "Type"), /* @__PURE__ */ Cn.createElement("span", null, type.label)), type.multi ? /* @__PURE__ */ Cn.createElement("div", { @@ -31054,8 +40002,7 @@ var NewPropertyMenuComponent = (props2) => { fieldType, value: fieldValue, contextPath: props2.contextPath, - saveValue: selectedValue, - saveContext: selectedContext + saveValue: selectedValue }) : /* @__PURE__ */ Cn.createElement(Cn.Fragment, null), /* @__PURE__ */ Cn.createElement("div", { className: "menu-separator" }), /* @__PURE__ */ Cn.createElement("div", { @@ -31066,8 +40013,8 @@ var NewPropertyMenuComponent = (props2) => { onClick: (e4) => props2.hide() }, /* @__PURE__ */ Cn.createElement("span", null, "Cancel"))); }; -var showNewPropertyMenu = (plugin, position, tags, fields, saveField, schemaId, contextPath, fileMetadata) => { - const menu = new import_obsidian15.Menu(); +var showNewPropertyMenu = (plugin, position, spaces, fields, saveField, schemaId, contextPath, fileMetadata) => { + const menu = new import_obsidian16.Menu(); menu.setUseNativeMenu(false); const frag = document.createDocumentFragment(); const div = frag.createDiv(); @@ -31080,7 +40027,7 @@ var showNewPropertyMenu = (plugin, position, tags, fields, saveField, schemaId, root.render( /* @__PURE__ */ Cn.createElement(Cn.Fragment, null, /* @__PURE__ */ Cn.createElement(NewPropertyMenuComponent, { plugin, - tags, + spaces, schemaId, contextPath, fields, @@ -31099,7674 +40046,10839 @@ var showNewPropertyMenu = (plugin, position, tags, fields, saveField, schemaId, menu.scope.unregister(keys[i4]); } } - menu.showAtPosition(position); - return menu; + menu.showAtPosition(position); + return menu; +}; + +// src/components/UI/menus/spaceMenu.tsx +var showSpacesMenu = (e4, plugin, saveLink, includeDefaults, canAdd) => { + const offset2 = e4.target.getBoundingClientRect(); + const options = plugin.index.allSpaces(true).filter((f4) => includeDefaults || f4.type != "default").map((f4) => ({ + name: f4.name, + value: f4.path, + icon: f4.sticker, + section: f4.type == "tag" ? "Tag" : "Folder", + description: f4.type == "tag" ? f4.name : f4.path + })); + showSelectMenu( + { x: offset2.left, y: offset2.top + 30 }, + { + plugin, + multi: false, + editable: canAdd, + value: [], + options, + sections: ["Tag", "Folder"], + saveOptions: (_12, value) => { + saveLink(value[0], !options.some((f4) => f4.value == value[0])); + }, + placeholder: i18n_default.labels.spaceSelectPlaceholder, + detail: true, + searchable: true, + showSections: true, + showAll: true + } + ); +}; + +// src/components/SpaceView/Contexts/TagsView/NoteSpacesBar.tsx +var import_obsidian17 = require("obsidian"); +var NoteSpacesBar = (props2) => { + const showContextMenu = (e4, space) => { + e4.stopPropagation(); + e4.preventDefault(); + const menu = new import_obsidian17.Menu(); + menu.addItem((menuItem) => { + menuItem.setIcon("layout-grid"); + menuItem.setTitle(i18n_default.menu.openSpace); + menuItem.onClick(() => { + openSpace(space.path, props2.plugin, e4.metaKey); + }); + }); + menu.addItem((menuItem) => { + menuItem.setIcon("add"); + menuItem.setTitle(i18n_default.labels.newProperty); + menuItem.onClick(() => { + newProperty(e4, space.path); + }); + }); + if (space.type == "folder") { + } + if (props2.removeSpace && space.type == "tag") + menu.addItem((menuItem) => { + menuItem.setIcon("trash"); + menuItem.setTitle(i18n_default.menu.removeFromSpace); + menuItem.onClick(() => { + props2.removeSpace(space.path); + }); + }); + const offset2 = e4.target.getBoundingClientRect(); + menu.showAtPosition({ x: offset2.left, y: offset2.top + 30 }); + }; + const showAddMenu = (e4) => { + showSpacesMenu( + e4, + props2.plugin, + (link) => { + props2.addSpace(link); + }, + false, + true + ); + }; + const spacesFromPath = (path) => { + return [...props2.plugin.index.spacesMap.get(path)].map((f4) => props2.plugin.index.spacesIndex.get(f4)).filter((f4) => f4 && f4.type != "default" && f4.path != "/").sort( + (f4, k5) => path.startsWith(f4.path) ? -1 : path.startsWith(k5.path) ? 1 : 0 + ); + }; + const [spaces, setSpaces] = h2( + spacesFromPath(props2.path) + ); + const saveField = (source, field) => { + var _a2; + insertContextColumn( + props2.plugin, + (_a2 = spaces.find((f4) => f4.path == source)) == null ? void 0 : _a2.space, + field + ); + }; + const newProperty = (e4, space) => { + const offset2 = e4.target.getBoundingClientRect(); + showNewPropertyMenu( + props2.plugin, + { x: offset2.left, y: offset2.top + 30 }, + [], + [], + saveField, + "files", + space + ); + }; + const refreshSpaces = (evt) => { + if (evt.detail.type == "file" && evt.detail.name == props2.path || evt.detail.type == "space" && evt.detail.name == props2.path) { + setSpaces(spacesFromPath(props2.path)); + } + }; + p2(() => { + setSpaces(spacesFromPath(props2.path)); + window.addEventListener(eventTypes.spacesChange, refreshSpaces); + return () => { + window.removeEventListener(eventTypes.spacesChange, refreshSpaces); + }; + }, [props2.path]); + return spaces.length > 0 ? /* @__PURE__ */ Cn.createElement("div", { + className: "mk-tag-selector" + }, spaces.map((f4, i4) => { + var _a2; + return /* @__PURE__ */ Cn.createElement("div", { + key: i4, + onContextMenu: (e4) => showContextMenu(e4, f4), + onClick: (e4) => openSpace( + f4.path, + props2.plugin, + e4.ctrlKey || e4.metaKey ? e4.altKey ? "split" : "tab" : false + ), + style: ((_a2 = f4.color) == null ? void 0 : _a2.length) > 0 ? { + "--tag-background": f4.color, + "--tag-color": "var(--color-white)" + } : {} + }, /* @__PURE__ */ Cn.createElement("span", { + className: "cm-hashtag cm-hashtag-begin mk-space-icon" + }, /* @__PURE__ */ Cn.createElement("div", { + className: `mk-icon-xsmall`, + dangerouslySetInnerHTML: { + __html: stickerFromString(f4.sticker, props2.plugin) + } + })), /* @__PURE__ */ Cn.createElement("span", { + className: "cm-hashtag cm-hashtag-end" + }, f4.name)); + })) : /* @__PURE__ */ Cn.createElement(Cn.Fragment, null); +}; + +// src/hooks/useLongPress.tsx +function isMouseEvent(e4) { + return e4 && "screenX" in e4; +} + +// src/components/UI/FileSticker/FileSticker.tsx +var import_obsidian22 = require("obsidian"); + +// src/components/UI/modals/vaultChangeModals.ts +var import_obsidian18 = require("obsidian"); +var VaultChangeModal = class extends import_obsidian18.Modal { + constructor(plugin, file, action, space) { + super(plugin.app); + this.file = file; + this.action = action; + this.plugin = plugin; + this.space = space; + } + onOpen() { + const { contentEl } = this; + let headerText; + if (this.action === "rename") { + headerText = i18n_default.labels.rename; + } else if (this.action === "create folder") { + headerText = i18n_default.labels.createFolder; + } else if (this.action === "create note") { + headerText = i18n_default.labels.createNote; + } + const headerEl = contentEl.createEl("div", { text: headerText }); + headerEl.addClass("modal-title"); + const inputEl = contentEl.createEl("input"); + inputEl.style.cssText = "width: 100%; height: 2.5em; margin-bottom: 15px;"; + if (this.action === "rename") { + if (this.file instanceof import_obsidian18.TFolder) { + inputEl.value = this.file.name; + } else { + inputEl.value = this.file.name.substring( + 0, + indexOfCharElseEOS(".", this.file.name) + ); + } + } + inputEl.focus(); + let changeButtonText; + if (this.action === "rename") { + changeButtonText = i18n_default.buttons.rename; + } else if (this.action === "create folder") { + changeButtonText = i18n_default.buttons.createFolder; + } else if (this.action === "create note") { + changeButtonText = i18n_default.buttons.createNote; + } + const changeButton = contentEl.createEl("button", { + text: changeButtonText + }); + const cancelButton = contentEl.createEl("button", { + text: i18n_default.buttons.cancel + }); + cancelButton.style.cssText = "float: right;"; + cancelButton.addEventListener("click", () => { + this.close(); + }); + const onClickAction = async () => { + const newName = inputEl.value; + if (this.action === "rename") { + renameFile(this.plugin, this.file, newName); + } else if (this.action === "create folder") { + const path = !this.file || this.file.path == "/" ? newName : this.file.path + "/" + newName; + if (getAbstractFileAtPath(this.plugin, path)) { + new import_obsidian18.Notice(i18n_default.notice.folderExists); + return; + } + this.app.vault.createFolder(path); + if (this.space) + insertSpaceItemAtIndex(this.plugin, this.space, path, 0); + } + this.close(); + }; + changeButton.addEventListener("click", onClickAction); + inputEl.addEventListener("keydown", (e4) => { + if (e4.key === "Enter") + onClickAction(); + }); + } + onClose() { + const { contentEl } = this; + contentEl.empty(); + } +}; +var MoveSuggestionModal = class extends import_obsidian18.FuzzySuggestModal { + constructor(plugin, files) { + super(plugin.app); + this.files = files; + this.plugin = plugin; + } + getItemText(item) { + return item.path; + } + getItems() { + return getAllFoldersInVault(this.plugin); + } + onChooseItem(item, evt) { + this.files.forEach((f4) => { + const file = getAbstractFileAtPath(this.plugin, f4); + if (file) { + this.app.vault.rename(file, item.path + "/" + file.name); + } + }); + } +}; + +// src/superstate/spacesStore/spaces.ts +var import_lodash7 = __toESM(require_lodash()); +var import_obsidian21 = require("obsidian"); + +// src/schemas/spaces.ts +var vaultSchema = { + uniques: ["path"], + cols: ["path", "parent", "created", "sticker", "color", "folder", "rank"], + rows: [] +}; + +// src/superstate/cacheParsers.ts +var import_lodash6 = __toESM(require_lodash()); + +// src/utils/defaultIconForExtension.ts +var defaultIconForExtension = (type, solid) => { + if (!type) + return solid ? "ui//mk-ui-folder-solid" : "ui//mk-ui-folder"; + switch (type) { + case "png": + case "jpg": + case "jpeg": + case "svg": + return "ui//mk-make-image"; + break; + case "mov": + case "webm": + return "ui//mk-ui-video"; + break; + case "canvas": + return "ui//mk-ui-canvas"; + default: + return solid ? "ui//mk-ui-file-solid" : "ui//mk-ui-file"; + } +}; + +// src/utils/spaces/query.ts +var filterFilesForAny = (files, filters) => { + const newArray = filters.reduce((p3, c4) => { + const [result, remaining] = p3; + const filteredFiles = c4.type == "fileprop" ? filterFileprop(remaining, c4) : c4.type == "filemeta" ? filterFilemeta(remaining, c4) : c4.type == "frontmatter" ? filterFM(remaining, c4) : []; + const diffArray = remaining.filter((x5) => !filteredFiles.includes(x5)); + return [[...result, ...filteredFiles], diffArray]; + }, [[], files]); + return newArray[0]; +}; +var filterFilesForAll = (files, filters) => { + return filters.reduce((p3, c4) => { + return c4.type == "fileprop" ? filterFileprop(p3, c4) : c4.type == "filemeta" ? filterFilemeta(p3, c4) : c4.type == "frontmatter" ? filterFM(p3, c4) : []; + }, files); +}; +var filterFM = (files, def) => { + return files.filter((f4) => { + const fm = f4.frontmatter; + if (!fm || !fm[def.field]) { + return false; + } + const filterFn = filterFnTypes[def.fn]; + let result = true; + if (filterFn) { + result = filterFn.fn(parseFrontMatter(def.field, fm[def.field]), def.value); + } + return result; + }); +}; +var filterFilemeta = (files, def) => { + return files.filter((f4) => { + let value = ""; + if (def.field == "outlinks") { + value = serializeMultiString(f4.outlinks); + } else if (def.field == "inlinks") { + value = serializeMultiString(f4.inlinks); + } else if (def.field == "tags") { + value = serializeMultiString(f4.tags); + } + const filterFn = filterFnTypes[def.fn]; + let result = true; + if (filterFn) { + result = filterFn.fn(value, def.value); + } + return result; + }); +}; +var filterFileprop = (files, def) => { + return files.filter((f4) => { + const vaultItemFields = ["name", "path", "sticker", "color", "isFolder", "extension", "ctime", "mtime", "size", "parent"]; + if (vaultItemFields.includes(def.field)) { + const filterFn = filterFnTypes[def.fn]; + let result = true; + if (filterFn) { + result = filterFn.fn(f4[def.field], def.value); + } + return result; + } + return true; + }); +}; +var fileByDef = (filters, file) => { + const fileInFilter = filters.reduce((p3, c4) => { + if (!p3 || c4.filters.length == 0) + return p3; + const result = c4.type == "any" ? filterFilesForAny([file], c4.filters).length > 0 : filterFilesForAll([file], c4.filters).length > 0; + return result; + }, true); + return fileInFilter; +}; + +// src/superstate/cacheParsers.ts +var fileMetadataToVaultItem = (cache) => { + var _a2, _b2; + return { + path: cache.path, + parent: cache.parent, + color: cache.color, + created: (_b2 = (_a2 = cache.ctime) == null ? void 0 : _a2.toString()) != null ? _b2 : "", + sticker: cache.sticker, + folder: cache.isFolder ? "true" : "false" + }; +}; + +// src/utils/metadata/tags.ts +var import_obsidian19 = require("obsidian"); +var tagKeys = ["tag", "tags", "Tag", "Tags"]; +var tagToTagPath = (tag) => { + if (!tag) + return null; + let string = tag; + if (string.charAt(0) != "#") + string = "#" + string; + return encodeSpaceName(string); +}; +var tagPathToTag = (string) => { + return filePathToString(string).replace(/\+/g, "/"); +}; +var loadTags = (plugin) => { + var _a2; + const folder = plugin.settings.spacesFolder == "" ? plugin.app.vault.getRoot() : getAbstractFileAtPath( + plugin, + getFolderPathFromString(plugin, plugin.settings.spacesFolder) + ); + return uniq([ + ...Object.keys(plugin.app.metadataCache.getTags()), + ...(_a2 = folder == null ? void 0 : folder.children.filter( + (f4) => f4 instanceof import_obsidian19.TFile && f4.extension == "mdb" && f4.name.charAt(0) == "#" + ).map((f4) => tagPathToTag(f4.name))) != null ? _a2 : [] + ]); +}; +var tagExists = (currentCache, findTag) => { + let currentTags = []; + if ((0, import_obsidian19.getAllTags)(currentCache)) { + currentTags = (0, import_obsidian19.getAllTags)(currentCache); + } + return currentTags.find((tag) => tag.toLowerCase() == findTag.toLowerCase()) ? true : false; +}; +var getAllFilesForTag = (plugin, tag) => { + const tagsCache = []; + (() => { + plugin.app.vault.getMarkdownFiles().forEach((tfile) => { + let currentCache; + if (plugin.app.metadataCache.getFileCache(tfile) !== null) { + currentCache = plugin.app.metadataCache.getFileCache(tfile); + } + const relativePath = tfile.path; + const hasTag = tagExists(currentCache, tag); + if (hasTag) { + tagsCache.push(relativePath); + } + }); + })(); + return tagsCache; +}; +var addTagToNote = (plugin, tag, tFile) => { + const newTag = validateName(tag); + editTagInFrontmatter(plugin, "", newTag, tFile); +}; +var positionsForTag = (plugin, tag, file) => { + const currentCache = plugin.app.metadataCache.getFileCache(file); + if (currentCache.tags) { + const positions = currentCache.tags.filter((f4) => f4.tag == tag).map((f4) => f4.position).sort((a5, b4) => { + if (a5.start.offset < b4.start.offset) { + return -1; + } + if (a5.start.offset > b4.start.offset) { + return 1; + } + return 0; + }); + return positions; + } + return []; +}; +var removeTagFromFile = (plugin, tag, file) => { + const pos = positionsForTag(plugin, tag, file); + removeTagInFrontmatter(plugin, tag, file); + editTagInFileBody(plugin, tag, "", pos, file); +}; +var validateName = (tag) => { + return tag.trim(); +}; +var renameTag = async (plugin, tag, toTag) => { + const tags = getAllSubtags(plugin, tag); + const newTag = validateName(toTag); + const files = getAllFilesForTag(plugin, tag); + for (const file of files) { + const tFile = getAbstractFileAtPath(plugin, file); + if (tFile instanceof import_obsidian19.TFile) { + const positions = positionsForTag(plugin, tag, tFile); + if (positions.length > 0) { + await editTagInFileBody(plugin, tag, newTag, positions, tFile); + } else { + await editTagInFrontmatter(plugin, tag, newTag, tFile); + } + } + } + await renameSpaceFolder(plugin, tag, toTag); + plugin.index.renameTag(tag, toTag); + for (const subtag of tags) { + await renameTag(plugin, subtag, subtag.replace(tag, newTag)); + } +}; +var getAllSubtags = (plugin, tag) => { + const tags = loadTags(plugin); + return tags.filter((f4) => f4.startsWith(tag) && f4 != tag); +}; +var getAllParentTags = (str) => { + if (str.startsWith("#")) { + str = str.slice(1); + } + const parts = str.split("/"); + const result = []; + for (let i4 = 0; i4 < parts.length - 1; i4++) { + if (i4 === 0) { + result.push(parts[i4]); + } else { + result.push(result[i4 - 1] + "/" + parts[i4]); + } + } + return result; +}; +var removeTagInFrontmatter = async (plugin, oldTag, file) => { + var _a2; + let fm; + if (plugin.app.metadataCache.getFileCache(file) !== null) { + fm = (_a2 = plugin.app.metadataCache.getFileCache(file)) == null ? void 0 : _a2.frontmatter; + } + if (fm && plugin.metadata.canProcessFrontmatter()) { + const processKey = (value) => { + if (Array.isArray(value)) { + return value.filter((f4) => stringFromTag(oldTag) != f4); + } else if (typeof value === "string") { + return serializeMultiDisplayString( + value.replace(/\s/g, "").split(",").filter((f4) => stringFromTag(oldTag) != f4) + ); + } + return value; + }; + const editKeys = tagKeys.filter((f4) => { + let tags = []; + if (Array.isArray(fm[f4])) { + tags = fm[f4]; + } else if (typeof fm[f4] === "string") { + tags = fm[f4].replace(/\s/g, "").split(","); + } + if (tags.find((g4) => g4 == stringFromTag(oldTag))) + return true; + return false; + }); + editKeys.forEach((tag) => { + plugin.metadata.processFrontMatter(file.path, (frontmatter) => { + frontmatter[tag] = processKey(fm[tag]); + }); + }); + } +}; +var editTagInFrontmatter = async (plugin, oldTag, newTag, file) => { + var _a2; + let fm; + if (plugin.app.metadataCache.getFileCache(file) !== null) { + fm = (_a2 = plugin.app.metadataCache.getFileCache(file)) == null ? void 0 : _a2.frontmatter; + } + const addTag = (plugin2, value) => { + if (Array.isArray(value)) { + return uniq([...value, stringFromTag(newTag)]).filter((f4) => (f4 == null ? void 0 : f4.length) > 0); + } else if (typeof value === "string") { + return serializeMultiDisplayString(uniq([ + ...value.replace(/\s/g, "").split(","), + stringFromTag(newTag) + ]).filter((f4) => (f4 == null ? void 0 : f4.length) > 0)); + } + return stringFromTag(newTag); + }; + if (plugin.metadata.canProcessFrontmatter()) { + if (fm) { + const processKey = (value) => { + if (Array.isArray(value)) { + return uniq( + value.map( + (f4) => stringFromTag(oldTag) == f4 ? stringFromTag(newTag) : f4 + ) + ); + } else if (typeof value === "string") { + return serializeMultiDisplayString(uniq( + value.replace(/\s/g, "").split(",").map( + (f4) => stringFromTag(oldTag) == f4 ? stringFromTag(newTag) : f4 + ) + )); + } + return value; + }; + const editKeys = tagKeys.filter((f4) => { + let tags = []; + if (Array.isArray(fm[f4])) { + tags = fm[f4]; + } else if (typeof fm[f4] === "string") { + tags = fm[f4].replace(/\s/g, "").split(","); + } + if (tags.find((g4) => g4 == stringFromTag(oldTag))) + return true; + return false; + }); + if (editKeys.length > 0) { + editKeys.forEach((key2) => { + plugin.metadata.processFrontMatter(file.path, (frontmatter) => { + frontmatter[key2] = processKey(fm[key2]); + }); + }); + } else { + plugin.metadata.processFrontMatter(file.path, (frontmatter) => { + frontmatter["tags"] = addTag(plugin, fm["tags"]); + }); + } + } else { + plugin.metadata.processFrontMatter(file.path, (frontmatter) => { + frontmatter["tags"] = stringFromTag(newTag); + }); + } + } +}; +var editTagInFileBody = async (plugin, oldTag, newTag, positions, file) => { + const offsetOffset = newTag.length - oldTag.length; + if (positions.length == 0) + return false; + const original = await plugin.app.vault.read(file); + let text2 = original; + let offset2 = 0; + for (const { start, end } of positions) { + const startOff = start.offset + offset2; + const endOff = end.offset + offset2; + if (text2.slice(startOff, endOff) !== oldTag) { + return false; + } + text2 = text2.slice(0, startOff) + newTag + text2.slice(startOff + oldTag.length); + offset2 += offsetOffset; + } + if (text2 !== original) { + await plugin.app.vault.modify(file, text2); + return true; + } +}; + +// src/utils/tree.ts +var import_obsidian20 = require("obsidian"); +var nodeIsAncestorOfTarget = (path, target) => { + if (target.type == "folder" && path.type == "folder") + return target.path.startsWith(path.path); + return false; +}; +var excludeVaultItemPredicate = (settings) => (f4, index, folder) => !(f4.folder != "true" && settings.hiddenExtensions.find( + (e4) => f4.path.endsWith(e4) +)) && !settings.hiddenFiles.find((e4) => e4 == f4.path) && (!settings.enableFolderNote || !settings.folderNoteInsideFolder && !folder.some((g4) => g4.path + ".md" == f4.path) || settings.folderNoteInsideFolder && !(f4.parent + "/" + folderPathToString(f4.parent) + ".md" == f4.path)); +var excludeFilePredicate = (plugin) => (f4) => f4 && !(f4 instanceof import_obsidian20.TFile && plugin.settings.hiddenExtensions.some((e4) => f4.extension == e4)) && !f4.path.startsWith(plugin.settings.spacesFolder + "/#") && !plugin.settings.hiddenFiles.some((e4) => e4 == f4.path) && (!f4.parent || !plugin.settings.enableFolderNote || !plugin.settings.folderNoteInsideFolder && !f4.parent.children.some((g4) => g4.path + ".md" == f4.path) || plugin.settings.folderNoteInsideFolder && !((f4.parent.path == "/" ? plugin.systemName() + ".md" : f4.parent.path + "/" + f4.parent.name + ".md") == f4.path)); +var folderChildren = (plugin, f4, exclusionList) => { + var _a2, _b2; + return (_b2 = (_a2 = f4 == null ? void 0 : f4.children) == null ? void 0 : _a2.filter(excludeFilePredicate(plugin))) != null ? _b2 : []; +}; +var compareByField = (field, dir) => (_a2, _b2) => { + const a5 = dir ? _a2 : _b2; + const b4 = dir ? _b2 : _a2; + if (a5[field] < b4[field]) { + return -1; + } + if (a5[field] > b4[field]) { + return 1; + } + return 0; +}; +var compareByFieldCaseInsensitive = (field, dir) => (_a2, _b2) => { + var _a3, _b3, _c2, _d2; + const a5 = dir ? _a2 : _b2; + const b4 = dir ? _b2 : _a2; + if (((_a3 = a5[field]) == null ? void 0 : _a3.toLowerCase()) < ((_b3 = b4[field]) == null ? void 0 : _b3.toLowerCase())) { + return -1; + } + if (((_c2 = a5[field]) == null ? void 0 : _c2.toLowerCase()) > ((_d2 = b4[field]) == null ? void 0 : _d2.toLowerCase())) { + return 1; + } + return 0; +}; +var internalPluginLoaded = (pluginName, app2) => { + var _a2; + return (_a2 = app2.internalPlugins.plugins[pluginName]) == null ? void 0 : _a2._loaded; }; +function selectElementContents(el) { + if (!el) + return; + const range = document.createRange(); + range.selectNodeContents(el); + const sel = window.getSelection(); + sel.removeAllRanges(); + sel.addRange(range); +} -// src/components/ui/modals/imageModal.tsx -var import_obsidian16 = require("obsidian"); -var imageModal = class extends import_obsidian16.FuzzySuggestModal { - constructor(plugin, app2, selectImage) { - super(app2); - this.plugin = plugin; - this.selectImage = selectImage; - this.resultContainerEl.toggleClass("mk-image-modal", true); - this.inputEl.focus(); - this.inputEl.placeholder = "Select an image or paste a URL"; - this.emptyStateText = "No Images Found"; - this.limit = 30; +// src/superstate/spacesStore/spaces.ts +var spaceContextsKey = (plugin) => plugin.settings.fmKeyContexts; +var spaceFilterKey = (plugin) => plugin.settings.fmKeyFilter; +var spaceLinksKey = (plugin) => plugin.settings.fmKeyLinks; +var spaceSortKey = (plugin) => plugin.settings.fmKeySort; +var FMSpaceKeys = (plugin) => [spaceContextsKey(plugin), spaceFilterKey(plugin), spaceLinksKey(plugin), spaceSortKey(plugin)]; +var parseSpaceSort = (value) => { + var _a2; + return { + field: ensureString((_a2 = value == null ? void 0 : value["field"]) != null ? _a2 : "rank"), + asc: ensureBoolean(value == null ? void 0 : value["asc"]), + group: ensureBoolean(value == null ? void 0 : value["group"]) + }; +}; +var parseSpaceFilterGroupFilter = (value) => { + return { + type: ensureStringValueFromSet(value["type"], ["frontmatter", "fileprop", "filemeta"], "frontmatter"), + fType: ensureString(value["fType"]), + field: ensureString(value["field"]), + fn: ensureString(value["fn"]), + value: ensureString(value["value"]) + }; +}; +var parseSpaceFilterGroup = (value) => { + return { + type: ensureStringValueFromSet(value["type"], ["any", "all"], "any"), + trueFalse: value["truefalse"] ? true : false, + filters: ensureArray(value["filters"]).map((f4) => parseSpaceFilterGroupFilter(f4)) + }; +}; +var parseSpaceMetadata = (metadata, spaceInfo, plugin) => { + return { ...metadata, sort: parseSpaceSort(metadata[spaceSortKey(plugin)]), contexts: ensureArray(metadata[spaceContextsKey(plugin)]), links: ensureArray(metadata[spaceLinksKey(plugin)]), filters: ensureArray(metadata[spaceFilterKey(plugin)]).map((f4) => parseSpaceFilterGroup(f4)) }; +}; +var rebuildIndex = async (plugin, save) => { + var _a2; + console.time("Make.md Vault Index"); + const newTables = indexCurrentFileTree(plugin, (_a2 = plugin.index.vaultDBCache) != null ? _a2 : []); + if (save && !import_lodash7.default.isEqual(newTables.vault.rows, plugin.index.vaultDBCache)) { + await plugin.index.saveSpacesDatabaseToDisk(newTables, save); } - renderSuggestion(item, el) { - var oImg = el.createEl("img"); - const file = getAbstractFileAtPath(app, item.item); - oImg.setAttribute( - "src", - file ? app.vault.getResourcePath(file) : item.item - ); - oImg.setAttribute("height", "100px"); - oImg.setAttribute("width", "100px"); - el.appendChild(oImg); + plugin.index.initialize(); + console.timeEnd("Make.md Vault Index"); +}; +var spaceToTreeNode = (space, collapsed, sortable, depth, parentId, parentPath, childrenCount, hasChildren) => { + var _a2; + return { + id: parentId ? parentId + "/" + space.path : space.path, + parentId, + depth, + index: 0, + space: parentPath, + path: space.path, + item: space, + uri: (_a2 = space.space) == null ? void 0 : _a2.uri, + collapsed, + sortable, + childrenCount, + type: "space", + leaf: false + }; +}; +var vaulItemToTreeNode = (plugin, item, space, path, depth, i4, collapsed, sortable, childrenCount, parentId) => ({ + item, + file: getAbstractFileAtPath(plugin, item.path), + space, + id: parentId + "/" + item.filename, + parentId, + depth, + path, + index: i4, + uri: uriByString(plugin, item.path), + collapsed, + sortable, + childrenCount, + type: "file", + leaf: true +}); +var spaceRowHeight = (plugin) => { + return platformIsMobile() ? 40 : plugin.settings.spaceRowHeight; +}; +var spaceSortFn = (sortStrategy) => (a5, b4) => { + if (sortStrategy.field == "rank") { + return a5.rank - b4.rank; } - getItemText(item) { - return item; + const sortFns = []; + if (sortStrategy.group) { + sortFns.push(compareByField("cacheType", false)); } - getSuggestions(query) { - let allImages = []; - if (query.match(urlRegex)) - allImages.push(query); - allImages.push( - ...getAllAbstractFilesInVault(this.plugin, app).filter( - (f4) => f4 instanceof import_obsidian16.TFile && ["png", "jpg", "jpeg"].contains(f4.extension) - ).map((f4) => f4.path) - ); - return allImages.filter((f4) => f4.contains(query)).map((f4, i4) => ({ - item: f4, - match: { - score: i4, - matches: [] - } - })); + if (sortStrategy.field == "name") { + sortFns.push(compareByFieldCaseInsensitive(sortStrategy.field, sortStrategy.asc)); + } else { + sortFns.push(compareByField(sortStrategy.field, sortStrategy.asc)); } - getItems() { - let allImages = []; - allImages.push( - ...getAllAbstractFilesInVault(this.plugin, app).filter( - (f4) => f4 instanceof import_obsidian16.TFile && ["png", "jpg", "jpeg"].contains(f4.extension) - ).map((f4) => f4.path) + return sortFns.reduce((p3, c4) => { + return p3 == 0 ? c4(a5, b4) : p3; + }, 0); +}; +var flattenedTreeFromVaultItems = (plugin, root, openNodes, depth, sortStrategy) => { + const _caches = plugin.index.getSpaceItems(root); + if (!_caches) { + return []; + } + const flattenNavigatorTree = (path, openNodes2, depth2, index, folderSort, caches) => { + const items = []; + let i4 = index; + const sortStrat = folderSort.length > 0 ? parseSortStrat(folderSort) : sortStrategy; + caches.sort(spaceSortFn(sortStrat)).forEach( + (item) => { + if (item.cacheType == "file") { + item = item; + const id2 = path + "/" + item.filename; + const collapsed = !openNodes2.includes(id2); + i4 = i4 + 1; + const newItems = []; + const newCaches = plugin.index.getSpaceItems(item.path); + if (newCaches && !collapsed) { + newItems.push( + ...flattenNavigatorTree(item.path, openNodes2, depth2 + 1, i4, item.sortBy, newCaches) + ); + } + const node = vaulItemToTreeNode( + plugin, + item, + item.path, + path, + depth2, + i4, + collapsed, + sortStrategy.field == "rank", + newItems.length, + path + ); + if (node.file) + newItems.splice(0, 0, node); + items.push(...newItems); + } else { + const collapsed = !openNodes2.includes(item.path); + items.push(spaceToTreeNode(item, collapsed, sortStrategy.field == "rank", depth2, path, item.path, 0, false)); + } + } ); - return allImages; + return items; + }; + return flattenNavigatorTree(root, openNodes, depth, 0, "", _caches); +}; +var vaultItemForPath = (plugin, path) => { + if (!path) + return null; + return plugin.index.vaultDBCache.find((f4) => f4.path == path); +}; +var saveFileSticker = async (plugin, path, sticker) => { + if (plugin.settings.spacesEnabled) { + const newVaultDB = plugin.index.vaultDBCache.map((f4) => f4.path == path ? { ...f4, sticker } : f4); + await plugin.index.saveSpacesDatabaseToDisk({ vault: { ...vaultSchema, rows: newVaultDB } }); } - onChooseItem(item, evt) { - this.selectImage(item); + saveFrontmatterValue( + plugin, + path, + plugin.settings.fmKeySticker, + sticker, + "text", + true + ); + plugin.index.reloadFile(getAbstractFileAtPath(plugin, path)).then((f4) => plugin.index.broadcast("space")); +}; +var saveFileColor = async (plugin, path, color) => { + if (plugin.settings.spacesEnabled) { + const newVaultDB = plugin.index.vaultDBCache.map((f4) => f4.path == path ? { ...f4, color } : f4); + await plugin.index.saveSpacesDatabaseToDisk({ vault: { ...vaultSchema, rows: newVaultDB } }); } + saveFrontmatterValue( + plugin, + path, + plugin.settings.fmKeyColor, + color, + "text", + true + ); + plugin.index.reloadFile(getAbstractFileAtPath(plugin, path)).then((f4) => plugin.index.broadcast("space")); }; - -// src/components/FileContextView/InlineFileContextView.tsx -var import_he = __toESM(require_he()); -var import_obsidian35 = require("obsidian"); - -// src/types/space.ts -var FMMetadataKeys = (plugin) => [plugin.settings.fmKeyBanner, plugin.settings.fmKeySticker, plugin.settings.fmKeyColor]; - -// src/utils/obsidian/obsidian.ts -var corePluginEnabled = (app2, plugin) => app2.internalPlugins.getPluginById(plugin) ? true : false; - -// node_modules/@dnd-kit/sortable/dist/sortable.esm.js -function arrayMove(array, from, to) { - const newArray = array.slice(); - newArray.splice(to < 0 ? newArray.length + to : to, 0, newArray.splice(from, 1)[0]); - return newArray; -} -function getSortedRects(items, rects) { - return items.reduce((accumulator, id2, index) => { - const rect = rects.get(id2); - if (rect) { - accumulator[index] = rect; - } - return accumulator; - }, Array(items.length)); -} -function isValidIndex(index) { - return index !== null && index >= 0; -} -function itemsEqual(a5, b4) { - if (a5 === b4) { - return true; +var saveSpaceColor = async (plugin, path, color) => { + await saveSpaceMetadataValue(plugin, path, "color", color); + plugin.index.broadcast("space"); +}; +var saveSpaceSticker = async (plugin, path, sticker) => { + await saveSpaceMetadataValue(plugin, path, "sticker", sticker); + plugin.index.broadcast("space"); +}; +var updateFileRank = async (plugin, path, rank, space) => { + const fixedRank = rank; + if (!await plugin.app.vault.adapter.exists(space.space.dbPath)) { + await createContextMDB(plugin, space.space); } - if (a5.length !== b4.length) { - return false; + plugin.index.addToContextStoreQueue(() => reorderFilesInContext(plugin, [path], fixedRank, space.space).then((f4) => { + return plugin.index.reloadContext(space.space); + }).then((f4) => { + const promises = [...plugin.index.spacesMap.getInverse(space.path)].map((f5) => plugin.index.reloadFile(getAbstractFileAtPath(plugin, f5))); + return Promise.all(promises); + }).then((f4) => plugin.index.broadcast("space"))); +}; +var moveAFileToNewParentAtIndex = async (plugin, item, newParent, index, copy) => { + if (!item) + return; + const currFile = getAbstractFileAtPath(plugin, item.path); + const newPath = newParent == "/" ? currFile.name : newParent + "/" + currFile.name; + const newItem = { + ...fileMetadataToVaultItem(item), + path: newPath, + parent: newParent + }; + if (getAbstractFileAtPath(plugin, newPath)) { + new import_obsidian21.Notice(i18n_default.notice.fileExists); + return; } - for (let i4 = 0; i4 < a5.length; i4++) { - if (a5[i4] !== b4[i4]) { - return false; + const allRows = plugin.index.vaultDBCache.filter((f4) => f4.parent == newParent); + const rows = insert( + allRows, + index, + newItem + ); + const newVaultTable = [...plugin.index.vaultDBCache, newItem].filter((f4) => copy || f4.path != item.path).map((f4) => { + const newItem2 = rows.find((g4) => g4.path == f4.path); + if (newItem2) { + return { ...f4, ...newItem2 }; } + return f4; + }); + await plugin.index.saveSpacesDatabaseToDisk({ vault: { ...vaultSchema, rows: newVaultTable } }); + const afile = getAbstractFileAtPath(plugin, item.path); + if (copy) { + await copyFile(plugin, getAbstractFileAtPath(plugin, newParent), afile); + } else { + await moveFile(plugin, getAbstractFileAtPath(plugin, newParent), afile); } - return true; -} -function normalizeDisabled(disabled) { - if (typeof disabled === "boolean") { - return { - draggable: disabled, - droppable: disabled - }; - } - return disabled; -} -var defaultScale = { - scaleX: 1, - scaleY: 1 + updateFileRank(plugin, newPath, index, plugin.index.spacesIndex.get(newParent)); }; -var horizontalListSortingStrategy = (_ref) => { - var _rects$activeIndex; - let { - rects, - activeNodeRect: fallbackActiveRect, - activeIndex, - overIndex, - index - } = _ref; - const activeNodeRect = (_rects$activeIndex = rects[activeIndex]) != null ? _rects$activeIndex : fallbackActiveRect; - if (!activeNodeRect) { - return null; +var movePathsToSpace = async (plugin, paths, newSpaceCache, index, modifier) => { + if (newSpaceCache.type == "folder" || newSpaceCache.type == "vault") { + paths.forEach((path) => { + if (modifier == "link" || nodeIsAncestorOfTarget(uriByString(plugin, path), newSpaceCache.space.uri)) { + insertSpaceItemAtIndex(plugin, newSpaceCache, path, index); + } else { + moveAFileToNewParentAtIndex(plugin, plugin.index.filesIndex.get(path), newSpaceCache.path, index, modifier == "copy"); + } + }); } - const itemGap = getItemGap(rects, index, activeIndex); - if (index === activeIndex) { - const newIndexRect = rects[overIndex]; - if (!newIndexRect) { - return null; - } - return { - x: activeIndex < overIndex ? newIndexRect.left + newIndexRect.width - (activeNodeRect.left + activeNodeRect.width) : newIndexRect.left - activeNodeRect.left, - y: 0, - ...defaultScale - }; + if (newSpaceCache.type == "tag") { + paths.map((f4) => { + var _a2, _b2, _c2; + return (_c2 = (_a2 = plugin.index.spacesIndex.get(f4)) == null ? void 0 : _a2.space.defPath) != null ? _c2 : (_b2 = plugin.index.filesIndex.get(f4)) == null ? void 0 : _b2.path; + }).filter((f4) => f4).forEach((path) => addTagToNote(plugin, newSpaceCache.name, getAbstractFileAtPath(plugin, path))); } - if (index > activeIndex && index <= overIndex) { - return { - x: -activeNodeRect.width - itemGap, - y: 0, - ...defaultScale - }; +}; +var movePathToSpace = async (plugin, path, oldSpaceCache, newSpaceCache, index, modifier) => { + let cache = plugin.index.spacesIndex.get(path); + if (!cache) { + cache = plugin.index.filesIndex.get(path); } - if (index < activeIndex && index >= overIndex) { - return { - x: activeNodeRect.width + itemGap, - y: 0, - ...defaultScale - }; + if (!cache || !newSpaceCache) + return false; + if ((oldSpaceCache == null ? void 0 : oldSpaceCache.path) == newSpaceCache.path) { + updateFileRank(plugin, path, index, oldSpaceCache); + return; } - return { - x: 0, - y: 0, - ...defaultScale - }; -}; -function getItemGap(rects, index, activeIndex) { - const currentRect = rects[index]; - const previousRect = rects[index - 1]; - const nextRect = rects[index + 1]; - if (!currentRect || !previousRect && !nextRect) { - return 0; + if (newSpaceCache.type == "folder" || newSpaceCache.type == "vault") { + if (modifier == "link" || nodeIsAncestorOfTarget(uriByString(plugin, path), newSpaceCache.space.uri)) { + insertSpaceItemAtIndex(plugin, newSpaceCache, path, index); + } else { + moveAFileToNewParentAtIndex(plugin, plugin.index.filesIndex.get(path), newSpaceCache.path, index, modifier == "copy"); + } } - if (activeIndex < index) { - return previousRect ? currentRect.left - (previousRect.left + previousRect.width) : nextRect.left - (currentRect.left + currentRect.width); + if (newSpaceCache.type == "tag") { + addTagToNote(plugin, newSpaceCache.name, getAbstractFileAtPath(plugin, path)); } - return nextRect ? nextRect.left - (currentRect.left + currentRect.width) : currentRect.left - (previousRect.left + previousRect.width); -} -var rectSortingStrategy = (_ref) => { - let { - rects, - activeIndex, - overIndex, - index - } = _ref; - const newRects = arrayMove(rects, overIndex, activeIndex); - const oldRect = rects[index]; - const newRect = newRects[index]; - if (!newRect || !oldRect) { - return null; + if (oldSpaceCache && (oldSpaceCache == null ? void 0 : oldSpaceCache.path) != newSpaceCache.path) { + removePathsFromSpace(plugin, oldSpaceCache, [path]); } - return { - x: newRect.left - oldRect.left, - y: newRect.top - oldRect.top, - scaleX: newRect.width / oldRect.width, - scaleY: newRect.height / oldRect.height - }; }; -var defaultScale$1 = { - scaleX: 1, - scaleY: 1 +var insertSpaceAtIndex = async (plugin, path, newSpace) => { + const spaces = plugin.index.allSpaces(); + const spaceInfo = spaceFromFolder(plugin, path); + let newSpaceCache; + if (spaces.find((f4) => f4.path == spaceInfo.path)) { + if (newSpace) { + newSpaceCache = await saveSpaceCache(plugin, spaceInfo, newSpace); + } else { + return; + } + } else { + if (!await abstractFileAtPathExists(plugin, spaceInfo.folderPath)) { + await plugin.app.vault.createFolder(spaceInfo.folderPath); + } + if (newSpace) { + await createNewMarkdownFile(plugin, getAbstractFileAtPath(plugin, spaceInfo.folderPath), spaceInfo.name, null, true); + await saveSpaceCache(plugin, spaceInfo, newSpace); + newSpaceCache = await plugin.index.reloadSpace(spaceInfo, newSpace); + } else { + newSpaceCache = await plugin.index.reloadSpace(spaceInfo); + } + } + plugin.index.initalizeFiles(); + plugin.settings.rootSpaces = [...plugin.settings.rootSpaces, spaceInfo.path]; + plugin.saveSettings(); + return newSpaceCache; }; -var verticalListSortingStrategy = (_ref) => { - var _rects$activeIndex; - let { - activeIndex, - activeNodeRect: fallbackActiveRect, - index, - rects, - overIndex - } = _ref; - const activeNodeRect = (_rects$activeIndex = rects[activeIndex]) != null ? _rects$activeIndex : fallbackActiveRect; - if (!activeNodeRect) { - return null; +var saveSpaceMetadataValue = async (plugin, space, key2, value) => { + const spaceCache = plugin.index.spacesIndex.get(space); + let file = getAbstractFileAtPath(plugin, spaceCache.space.defPath); + if (!file) { + file = await createNewMarkdownFile(plugin, getAbstractFileAtPath(plugin, spaceCache.space.folderPath), filePathToString(spaceCache.space.defPath), "", true); } - if (index === activeIndex) { - const overIndexRect = rects[overIndex]; - if (!overIndexRect) { - return null; - } - return { - x: 0, - y: activeIndex < overIndex ? overIndexRect.top + overIndexRect.height - (activeNodeRect.top + activeNodeRect.height) : overIndexRect.top - activeNodeRect.top, - ...defaultScale$1 - }; + if (plugin.metadata.canProcessFrontmatter()) { + await plugin.metadata.processFrontMatter(file.path, (frontmatter) => { + frontmatter[key2] = value; + }); } - const itemGap = getItemGap$1(rects, index, activeIndex); - if (index > activeIndex && index <= overIndex) { - return { - x: 0, - y: -activeNodeRect.height - itemGap, - ...defaultScale$1 - }; + plugin.index.updateSpaceMetadata(space, { ...spaceCache.metadata, [key2]: value }); +}; +var saveSpaceCache = async (plugin, spaceInfo, metadata) => { + let file = getAbstractFileAtPath(plugin, spaceInfo.defPath); + if (!file) { + file = await createNewMarkdownFile(plugin, getAbstractFileAtPath(plugin, spaceInfo.folderPath), filePathToString(spaceInfo.defPath), "", true); + } + if (plugin.metadata.canProcessFrontmatter()) { + await plugin.metadata.processFrontMatter(file.path, (frontmatter) => { + frontmatter[plugin.settings.fmKeySticker] = metadata.sticker; + frontmatter[spaceFilterKey(plugin)] = metadata.filters; + frontmatter[plugin.settings.fmKeyBanner] = metadata.banner; + frontmatter[spaceContextsKey(plugin)] = metadata.contexts; + frontmatter[spaceLinksKey(plugin)] = metadata.links; + frontmatter[spaceSortKey(plugin)] = metadata.sort; + frontmatter["tags"] = metadata.tags; + }); } - if (index < activeIndex && index >= overIndex) { - return { - x: 0, - y: activeNodeRect.height + itemGap, - ...defaultScale$1 - }; + return plugin.index.updateSpaceMetadata(spaceInfo.path, metadata); +}; +var insertSpaceItemAtIndex = async (plugin, space, path, rank) => { + var _a2; + const spaceExists = (_a2 = ensureArray(space.metadata.links)) != null ? _a2 : []; + const pathExists = spaceExists.find((f4) => f4 == path); + if (!pathExists) { + spaceExists.push(path); } - return { - x: 0, - y: 0, - ...defaultScale$1 - }; + await saveSpaceCache(plugin, space.space, { ...space.metadata, links: spaceExists }); + await plugin.index.reloadFile(getAbstractFileAtPath(plugin, path)); + await plugin.index.reloadSpace(space.space); + updateFileRank(plugin, path, rank, space); + plugin.index.broadcast("vault"); }; -function getItemGap$1(clientRects, index, activeIndex) { - const currentRect = clientRects[index]; - const previousRect = clientRects[index - 1]; - const nextRect = clientRects[index + 1]; - if (!currentRect) { - return 0; +var removeSpace = async (plugin, space) => { + const spaceCache = plugin.index.spacesIndex.get(space); + if (spaceCache.type == "tag") { + plugin.index.deleteTag(spaceCache.name); + } else if (spaceCache.type == "folder") { + deleteFile(plugin, getAbstractFileAtPath(plugin, space)); + } else { + deleteSpaceFolder(plugin, spaceCache.name); + plugin.index.deleteSpace(space); } - if (activeIndex < index) { - return previousRect ? currentRect.top - (previousRect.top + previousRect.height) : nextRect ? nextRect.top - (currentRect.top + currentRect.height) : 0; +}; +var updateSpaceSort = (plugin, spaceName, sort) => { + const space = plugin.index.spacesIndex.get(spaceName); + if (space) + saveSpaceCache(plugin, space.space, { + ...space.metadata, + sort + }); +}; +var toggleSpacePin = (plugin, spacePath, type, remove, rank) => { + if (type == "home") { + if (remove) { + plugin.settings.rootSpaces = plugin.settings.rootSpaces.filter((f4) => f4 != spacePath); + } else if (plugin.settings.rootSpaces.some((f4) => f4 == spacePath)) { + const currIndex = plugin.settings.rootSpaces.findIndex((f4) => f4 == spacePath); + plugin.settings.rootSpaces = arrayMove(plugin.settings.rootSpaces, currIndex, rank); + } else { + plugin.settings.rootSpaces = insert(plugin.settings.rootSpaces, rank, spacePath); + } + } else if (type == "pinned") { + if (remove) { + plugin.settings.waypoints = plugin.settings.waypoints.filter((f4) => f4 != spacePath); + } else if (plugin.settings.waypoints.some((f4) => f4 == spacePath)) { + const currIndex = plugin.settings.waypoints.findIndex((f4) => f4 == spacePath); + plugin.settings.waypoints = arrayMove(plugin.settings.waypoints, currIndex, rank); + } else { + plugin.settings.waypoints = insert(plugin.settings.waypoints, rank, spacePath); + } } - return nextRect ? nextRect.top - (currentRect.top + currentRect.height) : previousRect ? currentRect.top - (previousRect.top + previousRect.height) : 0; -} -var ID_PREFIX2 = "Sortable"; -var Context = /* @__PURE__ */ Cn.createContext({ - activeIndex: -1, - containerId: ID_PREFIX2, - disableTransforms: false, - items: [], - overIndex: -1, - useDragOverlay: false, - sortedRects: [], - strategy: rectSortingStrategy, - disabled: { - draggable: false, - droppable: false + plugin.saveSettings(); +}; +var removePathsFromSpace = async (plugin, space, paths) => { + if (space.type == "tag") { + paths.map((f4) => { + var _a2, _b2, _c2; + return (_c2 = (_a2 = plugin.index.spacesIndex.get(f4)) == null ? void 0 : _a2.space.defPath) != null ? _c2 : (_b2 = plugin.index.filesIndex.get(f4)) == null ? void 0 : _b2.path; + }).filter((f4) => f4).forEach((path) => removeTagFromFile(plugin, space.name, getAbstractFileAtPath(plugin, path))); + } else if (space.type == "folder" || space.type == "vault") { + paths.forEach((f4) => { + if (pathIsSpace(plugin, f4)) { + plugin.index.spacesMap.set(f4, new Set([...plugin.index.spacesMap.get(f4)].filter((g4) => g4 != space.path))); + } + }); + await saveSpaceMetadataValue(plugin, space.path, spaceLinksKey(plugin), space.metadata.links.filter((f4) => !paths.some((g4) => g4 == f4))); + await plugin.index.reloadSpace(space.space); + const promises = paths.map((f4) => pathIsSpace(plugin, f4) ? plugin.index.reloadSpaceByPath(f4) : plugin.index.reloadFile(getAbstractFileAtPath(plugin, f4))); + await Promise.all(promises); + plugin.index.broadcast("vault"); } -}); -function SortableContext(_ref) { - let { - children, - id: id2, - items: userDefinedItems, - strategy = rectSortingStrategy, - disabled: disabledProp = false - } = _ref; - const { - active, - dragOverlay, - droppableRects, - over, - measureDroppableContainers - } = useDndContext(); - const containerId = useUniqueId(ID_PREFIX2, id2); - const useDragOverlay = Boolean(dragOverlay.rect !== null); - const items = F2(() => userDefinedItems.map((item) => typeof item === "object" && "id" in item ? item.id : item), [userDefinedItems]); - const isDragging = active != null; - const activeIndex = active ? items.indexOf(active.id) : -1; - const overIndex = over ? items.indexOf(over.id) : -1; - const previousItemsRef = _2(items); - const itemsHaveChanged = !itemsEqual(items, previousItemsRef.current); - const disableTransforms = overIndex !== -1 && activeIndex === -1 || itemsHaveChanged; - const disabled = normalizeDisabled(disabledProp); - useIsomorphicLayoutEffect(() => { - if (itemsHaveChanged && isDragging) { - measureDroppableContainers(items); - } - }, [itemsHaveChanged, items, isDragging, measureDroppableContainers]); - p2(() => { - previousItemsRef.current = items; - }, [items]); - const contextValue = F2( - () => ({ - activeIndex, - containerId, - disabled, - disableTransforms, - items, - overIndex, - useDragOverlay, - sortedRects: getSortedRects(items, droppableRects), - strategy - }), - [activeIndex, containerId, disabled.draggable, disabled.droppable, disableTransforms, items, overIndex, droppableRects, useDragOverlay, strategy] +}; +var retrieveAllRecursiveChildren = (vaultDB, settings, folder) => { + return vaultDB.filter((f4) => f4["parent"].startsWith(folder)).filter( + excludeVaultItemPredicate(settings) ); - return Cn.createElement(Context.Provider, { - value: contextValue - }, children); -} -var defaultNewIndexGetter = (_ref) => { - let { - id: id2, - items, - activeIndex, - overIndex - } = _ref; - return arrayMove(items, activeIndex, overIndex).indexOf(id2); }; -var defaultAnimateLayoutChanges = (_ref2) => { - let { - containerId, - isSorting, - wasDragging, - index, - items, - newIndex, - previousItems, - previousContainerId, - transition - } = _ref2; - if (!transition || !wasDragging) { - return false; - } - if (previousItems !== items && index === newIndex) { - return false; - } - if (isSorting) { - return true; +var retrieveAllFiles = (vaultDB, settings) => { + return vaultDB.filter( + excludeVaultItemPredicate(settings) + ); +}; +var initiateDB = (db) => { + replaceDB(db, { + vault: vaultSchema + }); +}; +var indexCurrentFileTree = (plugin, vaultDB) => { + const treeItems = getAllAbstractFilesInVault(plugin).map((file) => { + var _a2; + return { + path: file.path, + parent: (_a2 = file.parent) == null ? void 0 : _a2.path, + created: file instanceof import_obsidian21.TFile ? file.stat.ctime.toString() : void 0, + folder: file instanceof import_obsidian21.TFolder ? "true" : "false" + }; + }); + const currentPaths = vaultDB; + const deleteRows = currentPaths.filter( + (item) => !treeItems.some((i4) => i4.path == item.path) + ); + const fixRows = currentPaths.filter( + (item) => treeItems.some((i4) => i4.path == item.path && i4.parent != item.parent) + ).map((item) => ({ + ...item, + ...treeItems.find((i4) => i4.path == item.path) + })); + const newRows = treeItems.filter( + (item) => !currentPaths.some((i4) => i4.path == item.path) + ); + const newVaultRows = [...vaultDB.map((f4) => { + const newItem = fixRows.find((g4) => g4.path == f4.path); + if (newItem) { + return { ...f4, ...newItem }; + } + return f4; + }).filter((f4) => !deleteRows.some((g4) => g4.path == f4.path)), ...newRows]; + return { + vault: { + ...vaultSchema, + rows: newVaultRows + } + }; +}; +var newFileInSpace = async (plugin, space, activeFile, canvas, dontOpen) => { + var _a2, _b2; + let newFile; + const folder = space.type == "tag" ? defaultNoteFolder(plugin, activeFile) : ((_b2 = (_a2 = space.space) == null ? void 0 : _a2.folderPath) == null ? void 0 : _b2.length) > 0 ? getFolderFromPath(plugin, space.space.folderPath) : defaultNoteFolder(plugin, activeFile); + if (canvas) { + newFile = await createNewCanvasFile( + plugin, + folder, + "Canvas", + dontOpen + ); + } else { + newFile = await createNewMarkdownFile( + plugin, + folder, + "", + space.type == "tag" ? `--- +tags: + - ${space.name.replace("#", "")} +---` : "", + dontOpen + ); } - return newIndex !== index && containerId === previousContainerId; + return newFile; }; -var defaultTransition2 = { - duration: 200, - easing: "ease" + +// src/utils/emoji.ts +var saveIconsForPaths = (plugin, files, icon) => { + files.forEach((file) => { + const cache = plugin.index.cacheForURI(uriByString(plugin, file)); + if ((cache == null ? void 0 : cache.cacheType) == "file") { + saveFileSticker(plugin, file, icon); + } else if ((cache == null ? void 0 : cache.cacheType) == "space") { + saveSpaceSticker(plugin, file, icon); + } + }); }; -var transitionProperty = "transform"; -var disabledTransition = /* @__PURE__ */ CSS.Transition.toString({ - property: transitionProperty, - duration: 0, - easing: "linear" -}); -var defaultAttributes = { - roleDescription: "sortable" +var saveColorForPaths = (plugin, files, icon) => { + files.forEach((file) => { + const cache = plugin.index.cacheForURI(uriByString(plugin, file)); + if ((cache == null ? void 0 : cache.cacheType) == "file") { + saveFileColor(plugin, file, icon); + } else if ((cache == null ? void 0 : cache.cacheType) == "space") { + saveSpaceColor(plugin, file, icon); + } + }); }; -function useDerivedTransform(_ref) { - let { - disabled, - index, - node, - rect - } = _ref; - const [derivedTransform, setDerivedtransform] = h2(null); - const previousIndex = _2(index); - useIsomorphicLayoutEffect(() => { - if (!disabled && index !== previousIndex.current && node.current) { - const initial = rect.current; - if (initial) { - const current = getClientRect(node.current, { - ignoreTransform: true - }); - const delta = { - x: initial.left - current.left, - y: initial.top - current.top, - scaleX: initial.width / current.width, - scaleY: initial.height / current.height - }; - if (delta.x || delta.y) { - setDerivedtransform(delta); - } - } +var removeSpaceIcon = (plugin, space) => { + saveSpaceSticker(plugin, space, ""); +}; +var saveFileIcon = (plugin, data2, icon) => { + saveFileSticker(plugin, data2.path, icon); +}; +var removeIconsForPaths = (plugin, files) => { + files.forEach((file) => { + const cache = plugin.index.cacheForURI(uriByString(plugin, file)); + if ((cache == null ? void 0 : cache.cacheType) == "file") { + saveFileSticker(plugin, file, ""); + } else if ((cache == null ? void 0 : cache.cacheType) == "space") { + saveSpaceSticker(plugin, file, ""); } - if (index !== previousIndex.current) { - previousIndex.current = index; + }); +}; +var removeFileIcon = (plugin, data2) => { + saveFileSticker(plugin, data2.path, ""); +}; + +// src/components/UI/FileSticker/FileSticker.tsx +var FileSticker = (props2) => { + const { fileCache } = props2; + const sticker = fileCache == null ? void 0 : fileCache.sticker; + const color = fileCache == null ? void 0 : fileCache.color; + const extension = (fileCache == null ? void 0 : fileCache.cacheType) == "file" && (fileCache == null ? void 0 : fileCache.extension); + const triggerStickerContextMenu = (e4) => { + if (!fileCache) + return; + e4.preventDefault(); + const fileMenu = new import_obsidian22.Menu(); + fileMenu.addSeparator(); + fileMenu.addItem((menuItem) => { + menuItem.setTitle(i18n_default.buttons.changeIcon); + menuItem.setIcon("lucide-sticker"); + menuItem.onClick((ev) => { + const vaultChangeModal = new stickerModal( + props2.plugin.app, + props2.plugin, + (emoji) => (fileCache == null ? void 0 : fileCache.cacheType) == "space" ? saveSpaceSticker(props2.plugin, fileCache == null ? void 0 : fileCache.path, emoji) : saveFileSticker(props2.plugin, fileCache == null ? void 0 : fileCache.path, emoji) + ); + vaultChangeModal.open(); + }); + }); + fileMenu.addItem((menuItem) => { + menuItem.setTitle(i18n_default.buttons.removeIcon); + menuItem.setIcon("lucide-file-minus"); + menuItem.onClick((ev) => { + removeIconsForPaths(props2.plugin, [fileCache.path]); + }); + }); + if (isMouseEvent(e4)) { + fileMenu.showAtPosition({ x: e4.pageX, y: e4.pageY }); + } else { + fileMenu.showAtPosition({ + x: e4.nativeEvent.locationX, + y: e4.nativeEvent.locationY + }); } - }, [disabled, index, node, rect]); - p2(() => { - if (derivedTransform) { - setDerivedtransform(null); + return false; + }; + const triggerStickerMenu = (e4) => { + e4.stopPropagation(); + if ((fileCache == null ? void 0 : fileCache.cacheType) == "space") { + const vaultChangeModal2 = new stickerModal( + props2.plugin.app, + props2.plugin, + (emoji) => saveSpaceSticker( + props2.plugin, + fileCache.space.path, + emoji + ) + ); + vaultChangeModal2.open(); + return; } - }, [derivedTransform]); - return derivedTransform; -} -function useSortable(_ref) { - let { - animateLayoutChanges: animateLayoutChanges3 = defaultAnimateLayoutChanges, - attributes: userDefinedAttributes, - disabled: localDisabled, - data: customData, - getNewIndex = defaultNewIndexGetter, - id: id2, - strategy: localStrategy, - resizeObserverConfig, - transition = defaultTransition2 - } = _ref; - const { - items, - containerId, - activeIndex, - disabled: globalDisabled, - disableTransforms, - sortedRects, - overIndex, - useDragOverlay, - strategy: globalStrategy - } = q2(Context); - const disabled = normalizeLocalDisabled(localDisabled, globalDisabled); - const index = items.indexOf(id2); - const data = F2(() => ({ - sortable: { - containerId, - index, - items + const vaultChangeModal = new stickerModal( + props2.plugin.app, + props2.plugin, + (emoji) => saveFileSticker(props2.plugin, fileCache.path, emoji) + ); + vaultChangeModal.open(); + }; + return /* @__PURE__ */ Cn.createElement("div", { + className: `mk-file-icon ${sticker ? "" : "mk-file-icon-placeholder"}` + }, /* @__PURE__ */ Cn.createElement("button", { + "aria-label": i18n_default.buttons.changeIcon, + onContextMenu: triggerStickerContextMenu, + style: (color == null ? void 0 : color.length) > 0 ? { + "--label-color": `${color}`, + "--icon-color": `#ffffff` + } : { + "--icon-color": `var(--text-muted)` }, - ...customData - }), [containerId, customData, index, items]); - const itemsAfterCurrentSortable = F2(() => items.slice(items.indexOf(id2)), [items, id2]); - const { - rect, - node, - isOver, - setNodeRef: setDroppableNodeRef - } = useDroppable({ - id: id2, - data, - disabled: disabled.droppable, - resizeObserverConfig: { - updateMeasurementsFor: itemsAfterCurrentSortable, - ...resizeObserverConfig + dangerouslySetInnerHTML: sticker ? { __html: stickerFromString(sticker, props2.plugin) } : fileCache.cacheType == "file" ? { + __html: stickerFromString( + defaultIconForExtension(extension, color ? true : false), + props2.plugin + ) + } : { + __html: stickerFromString( + iconForSpaceType( + fileCache.type, + fileCache.path, + true + ), + props2.plugin + ) + }, + onClick: (e4) => triggerStickerMenu(e4) + })); +}; +var FileStickerContainer = (props2) => { + const [cache, setCache] = h2(null); + const reloadCache = () => { + setCache(props2.plugin.index.cacheForURI(props2.path)); + }; + const reloadIcon = (e4) => { + if (e4.detail.type == "file" && e4.detail.name == props2.path.path || e4.detail.type == "space" && e4.detail.name == props2.path.fullPath) { + reloadCache(); } - }); - const { - active, - activatorEvent, - activeNodeRect, - attributes, - setNodeRef: setDraggableNodeRef, - listeners, - isDragging, - over, - setActivatorNodeRef, - transform - } = useDraggable({ - id: id2, - data, - attributes: { - ...defaultAttributes, - ...userDefinedAttributes + }; + p2(() => { + reloadCache(); + }, []); + p2(() => { + window.addEventListener(eventTypes.spacesChange, reloadIcon); + return () => { + window.removeEventListener(eventTypes.spacesChange, reloadIcon); + }; + }, [props2.path]); + return cache ? /* @__PURE__ */ Cn.createElement(FileSticker, { + plugin: props2.plugin, + fileCache: cache + }) : /* @__PURE__ */ Cn.createElement(Cn.Fragment, null); +}; + +// src/components/SpaceView/Contexts/ContextBuilder/SpacePropertyEditor.tsx +var SpacePropertyEditor = (props2) => { + const [activeId, setActiveId] = h2(""); + const items = props2.columns.map((f4) => ({ ...f4, table: "", id: f4.name })); + const [openNodes, setOpenNodes] = h2([]); + const [overId, setOverId] = h2(""); + const contextProperties = F2(() => { + return props2.contexts.reduce((p3, c4) => { + var _a2, _b2; + return { + ...p3, + [c4]: { + space: props2.plugin.index.spacesIndex.get(tagSpacePathFromTag(c4)), + cols: (_b2 = (_a2 = props2.plugin.index.contextsIndex.get(tagSpacePathFromTag(c4))) == null ? void 0 : _a2.cols) != null ? _b2 : [].map((f4) => ({ ...f4, table: c4 })) + } + }; + }, {}); + }, [props2.contexts]); + const sensors = useSensors( + useSensor(MouseSensor, { + activationConstraint: { + distance: 10 + } + }), + useSensor(TouchSensor, { + activationConstraint: { + delay: 250, + tolerance: 5 + } + }), + useSensor(KeyboardSensor, { + coordinateGetter: sortableKeyboardCoordinates + }) + ); + const resetState = () => { + setActiveId(null); + setOverId(null); + }; + const saveNewField = (source, field) => { + props2.saveColumn({ ...field, table: "" }); + }; + const newProperty = (e4) => { + var _a2; + const offset2 = e4.target.getBoundingClientRect(); + showNewPropertyMenu( + props2.plugin, + { x: offset2.left, y: offset2.top + 30 }, + (_a2 = props2.contexts) != null ? _a2 : [], + [], + saveNewField, + "files", + null, + false + ); + }; + const newContexts = (e4) => { + const offset2 = e4.target.getBoundingClientRect(); + const f4 = loadTags(props2.plugin); + const addTag = async (tag) => { + const newTag = tagToTagPath(tag); + props2.saveContexts([ + ...props2.contexts.filter((f5) => f5 != newTag), + newTag + ]); + }; + showSelectMenu( + { x: offset2.left, y: offset2.top + 30 }, + { + plugin: props2.plugin, + multi: false, + editable: true, + value: [], + options: f4.map((m5) => ({ name: m5, value: m5 })), + saveOptions: (_12, value) => addTag(value[0]), + placeholder: i18n_default.labels.contextItemSelectPlaceholder, + searchable: true, + showAll: true + } + ); + }; + return /* @__PURE__ */ Cn.createElement(DndContext, { + sensors, + collisionDetection: closestCenter, + measuring: { + droppable: { + strategy: MeasuringStrategy.Always + } }, - disabled: disabled.draggable - }); - const setNodeRef = useCombinedRefs(setDroppableNodeRef, setDraggableNodeRef); - const isSorting = Boolean(active); - const displaceItem = isSorting && !disableTransforms && isValidIndex(activeIndex) && isValidIndex(overIndex); - const shouldDisplaceDragSource = !useDragOverlay && isDragging; - const dragSourceDisplacement = shouldDisplaceDragSource && displaceItem ? transform : null; - const strategy = localStrategy != null ? localStrategy : globalStrategy; - const finalTransform = displaceItem ? dragSourceDisplacement != null ? dragSourceDisplacement : strategy({ - rects: sortedRects, - activeNodeRect, - activeIndex, - overIndex, - index - }) : null; - const newIndex = isValidIndex(activeIndex) && isValidIndex(overIndex) ? getNewIndex({ - id: id2, - items, - activeIndex, - overIndex - }) : index; - const activeId = active == null ? void 0 : active.id; - const previous = _2({ - activeId, - items, - newIndex, - containerId - }); - const itemsHaveChanged = items !== previous.current.items; - const shouldAnimateLayoutChanges = animateLayoutChanges3({ - active, - containerId, - isDragging, - isSorting, - id: id2, - index, + onDragStart: ({ active }) => { + setActiveId(active.id); + }, + onDragOver: ({ active, over }) => { + const overId2 = over == null ? void 0 : over.id; + if (overId2) + setOverId(overId2); + }, + onDragEnd: ({ active, over }) => { + const overId2 = over == null ? void 0 : over.id; + if (!overId2) { + resetState(); + return; + } + props2.setColumnOrder( + arrayMove( + props2.colsOrder, + props2.colsOrder.findIndex((f4) => f4 == activeId), + props2.colsOrder.findIndex((f4) => f4 == overId2) + ) + ); + resetState(); + }, + onDragCancel: resetState + }, /* @__PURE__ */ Cn.createElement("div", { + className: "mk-property-editor" + }, /* @__PURE__ */ Cn.createElement("div", { + className: "mk-property-editor-context" + }, /* @__PURE__ */ Cn.createElement("div", { + className: "mk-property-editor-context-title" + }, /* @__PURE__ */ Cn.createElement("span", null, "Define Properties for your Space Items"), /* @__PURE__ */ Cn.createElement("button", { + onClick: (e4) => newProperty(e4) + }, "Add Property")), /* @__PURE__ */ Cn.createElement("div", { + className: "mk-property-editor-context-list" + }, /* @__PURE__ */ Cn.createElement("div", { + className: "mk-property-editor-list" + }, /* @__PURE__ */ Cn.createElement(SortableContext, { items, - newIndex: previous.current.newIndex, - previousItems: previous.current.items, - previousContainerId: previous.current.containerId, - transition, - wasDragging: previous.current.activeId != null - }); - const derivedTransform = useDerivedTransform({ - disabled: !shouldAnimateLayoutChanges, - index, - node, - rect - }); - p2(() => { - if (isSorting && previous.current.newIndex !== newIndex) { - previous.current.newIndex = newIndex; + strategy: verticalListSortingStrategy + }, items.map((value, index) => { + return /* @__PURE__ */ Cn.createElement(SortableItem, { + key: index, + id: value.id, + field: value, + plugin: props2.plugin, + saveColumn: (field) => props2.saveColumn(field, value), + cols: items, + colsHidden: props2.colsHidden, + hideColumn: props2.hideColumn, + delColumn: props2.delColumn + }); + }))))), props2.contexts.map((f4, i4) => { + var _a2; + return /* @__PURE__ */ Cn.createElement("div", { + key: i4, + className: "mk-property-editor-context" + }, /* @__PURE__ */ Cn.createElement("div", { + className: "mk-property-editor-context-title" + }, f4, /* @__PURE__ */ Cn.createElement("button", { + className: `mk-collapse mk-inline-button mk-icon-xsmall ${!openNodes.some((g4) => g4 == f4) ? "mk-collapsed" : ""}`, + dangerouslySetInnerHTML: { + __html: stickerFromString("ui//mk-ui-collapse", props2.plugin) + }, + onClick: () => setOpenNodes( + (p3) => p3.some((g4) => g4 == f4) ? p3.filter((o3) => o3 != f4) : [...p3, f4] + ) + }), /* @__PURE__ */ Cn.createElement("span", null), /* @__PURE__ */ Cn.createElement("div", null, /* @__PURE__ */ Cn.createElement("div", { + className: "mk-icon-small", + dangerouslySetInnerHTML: { + __html: uiIconSet["mk-ui-close"] + }, + onClick: (e4) => { + props2.saveContexts(props2.contexts.filter((g4) => g4 != f4)); + } + }))), openNodes.some((g4) => g4 == f4) ? /* @__PURE__ */ Cn.createElement("div", { + className: "mk-property-editor-list" + }, (_a2 = contextProperties[f4]) == null ? void 0 : _a2.cols.filter((f5) => f5.primary != "true").map((g4, h5) => /* @__PURE__ */ Cn.createElement(SortableItem, { + key: h5, + id: g4.name + "#" + f4, + field: g4, + plugin: props2.plugin, + saveColumn: (field) => props2.saveColumn(field, g4), + cols: contextProperties[f4].cols, + colsHidden: props2.colsHidden, + hideColumn: props2.hideColumn, + delColumn: props2.delColumn + }))) : /* @__PURE__ */ Cn.createElement(Cn.Fragment, null)); + }), /* @__PURE__ */ Cn.createElement("div", { + onClick: (e4) => newContexts(e4), + className: "mk-property-editor-new" + }, "+ Add Context", /* @__PURE__ */ Cn.createElement("span", null, "Contexts lets you connect properties from your tags"))), z3( + /* @__PURE__ */ Cn.createElement(DragOverlay, { + adjustScale: false + }, activeId ? /* @__PURE__ */ Cn.createElement(SortableItem, { + id: items.find((f4) => f4.id == activeId).id, + field: items.find((f4) => f4.id == activeId), + plugin: props2.plugin, + cols: items, + colsHidden: props2.colsHidden + }) : null), + document.body + )); +}; +function SortableItem(props2) { + var _a2, _b2; + const { spaceInfo } = q2(SpaceContext); + const { field } = props2; + const saveField = (field2, oldField) => { + if (field2.name.length > 0) { + if (field2.name != oldField.name || field2.type != oldField.type || field2.value != oldField.value || field2.attrs != oldField.attrs) { + const saveResult = props2.saveColumn(field2, oldField); + } } - if (containerId !== previous.current.containerId) { - previous.current.containerId = containerId; + }; + const { attributes, listeners, setNodeRef, transform, transition } = useSortable({ id: props2.id }); + const style = { + transform: CSS.Transform.toString(transform), + transition + }; + const icon = ((_a2 = props2.field.attrs) == null ? void 0 : _a2.length) > 0 ? props2.field.attrs : (_b2 = fieldTypeForType(props2.field.type)) == null ? void 0 : _b2.icon; + const selectedType = (_12, value) => { + const newField = { + ...props2.field, + type: value[0] + }; + props2.saveColumn(newField); + }; + return /* @__PURE__ */ Cn.createElement("div", { + className: "mk-property-editor-property", + ref: setNodeRef, + style, + ...attributes, + ...listeners + }, /* @__PURE__ */ Cn.createElement("div", { + className: "mk-file-context-field-icon", + dangerouslySetInnerHTML: { + __html: stickerFromString(icon, props2.plugin) + }, + onClick: (e4) => { + selectPropertyTypeMenu(e4, props2.plugin, selectedType); } - if (items !== previous.current.items) { - previous.current.items = items; + }), props2.field.name, /* @__PURE__ */ Cn.createElement("span", null), /* @__PURE__ */ Cn.createElement("div", { + className: "mk-icon-small", + dangerouslySetInnerHTML: { + __html: uiIconSet["mk-ui-options"] + }, + onClick: (e4) => { + const offset2 = e4.target.getBoundingClientRect(); + showPropertyMenu({ + plugin: props2.plugin, + position: { x: offset2.left, y: offset2.top + 30 }, + editable: true, + options: [], + field, + fields: props2.cols, + contextPath: spaceInfo == null ? void 0 : spaceInfo.path, + saveField: (newField) => saveField(newField, field), + hide: props2.hideColumn, + deleteColumn: props2.delColumn, + hidden: props2.colsHidden.includes(field.name + field.table) + }); } - }, [isSorting, newIndex, containerId, items]); - p2(() => { - if (activeId === previous.current.activeId) { - return; + })); +} + +// src/components/UI/menus/linkMenu.tsx +var showLinkMenu = (e4, plugin, saveLink) => { + const offset2 = e4.target.getBoundingClientRect(); + const options = getAllAbstractFilesInVault(plugin).map((f4) => ({ + name: fileNameToString(f4.name), + value: f4.path, + description: f4.path + })); + showSelectMenu( + { x: offset2.left, y: offset2.top + 30 }, + { + plugin, + multi: false, + editable: true, + value: [], + options, + saveOptions: (_12, value) => { + saveLink(value[0]); + }, + placeholder: i18n_default.labels.linkItemSelectPlaceholder, + detail: true, + searchable: true, + showAll: true } - if (activeId && !previous.current.activeId) { - previous.current.activeId = activeId; - return; + ); +}; + +// src/components/Navigator/SpaceEditor.tsx +var import_obsidian41 = require("obsidian"); + +// src/components/SpaceView/Contexts/ContextBuilder/BuilderMetadataFields.tsx +var import_obsidian23 = require("obsidian"); +var allMetadataForFiles = (plugin, files) => { + return files.reduce((p3, c4) => { + const fm = frontMatterForFile(plugin, c4); + const fmKeys = uniqCaseInsensitive(frontMatterKeys(fm)); + if (plugin.dataViewAPI()) { + const dvValues = plugin.dataViewAPI().page(c4.path); + const dvKeys = uniqCaseInsensitive( + Object.keys(dvValues != null ? dvValues : {}).filter( + (f4, i4, self2) => !self2.find( + (g4, j4) => g4.toLowerCase().replace(/\s/g, "-") == f4.toLowerCase().replace(/\s/g, "-") && i4 > j4 + ) ? true : false + ).filter((f4) => f4 != "file" && !fmKeys.some((g4) => f4 == g4)) + ); + return [ + ...p3, + ...fmKeys.map((f4) => ({ name: f4, type: "fm" })), + ...dvKeys.map((f4) => ({ name: f4, type: "dv" })) + ].filter(metadatTypeFilterPredicate); } - const timeoutId = setTimeout(() => { - previous.current.activeId = activeId; - }, 50); - return () => clearTimeout(timeoutId); - }, [activeId]); - return { - active, - activeIndex, - attributes, - data, - rect, - index, - newIndex, - items, - isOver, - isSorting, - isDragging, - listeners, - node, - overIndex, - over, - setNodeRef, - setActivatorNodeRef, - setDroppableNodeRef, - setDraggableNodeRef, - transform: derivedTransform != null ? derivedTransform : finalTransform, - transition: getTransition() - }; - function getTransition() { - if (derivedTransform || itemsHaveChanged && previous.current.newIndex === index) { - return disabledTransition; + return [ + ...p3, + ...fmKeys.map((f4) => ({ name: f4, type: "fm" })) + ].filter(metadatTypeFilterPredicate); + }, []); +}; +var metadatTypeFilterPredicate = (value, index, self2) => { + return self2.findIndex( + (v3) => value["type"] == v3["type"] && value["name"] == v3["name"] + ) === index; +}; + +// src/components/UI/menus/datePickerMenu.tsx +var import_obsidian24 = require("obsidian"); + +// node_modules/react-day-picker/dist/index.esm.js +var __assign = function() { + __assign = Object.assign || function __assign5(t4) { + for (var s5, i4 = 1, n2 = arguments.length; i4 < n2; i4++) { + s5 = arguments[i4]; + for (var p3 in s5) + if (Object.prototype.hasOwnProperty.call(s5, p3)) + t4[p3] = s5[p3]; } - if (shouldDisplaceDragSource && !isKeyboardEvent(activatorEvent) || !transition) { - return void 0; + return t4; + }; + return __assign.apply(this, arguments); +}; +function __rest(s5, e4) { + var t4 = {}; + for (var p3 in s5) + if (Object.prototype.hasOwnProperty.call(s5, p3) && e4.indexOf(p3) < 0) + t4[p3] = s5[p3]; + if (s5 != null && typeof Object.getOwnPropertySymbols === "function") + for (var i4 = 0, p3 = Object.getOwnPropertySymbols(s5); i4 < p3.length; i4++) { + if (e4.indexOf(p3[i4]) < 0 && Object.prototype.propertyIsEnumerable.call(s5, p3[i4])) + t4[p3[i4]] = s5[p3[i4]]; } - if (isSorting || shouldAnimateLayoutChanges) { - return CSS.Transition.toString({ - ...transition, - property: transitionProperty - }); + return t4; +} +function __spreadArray(to, from, pack) { + if (pack || arguments.length === 2) + for (var i4 = 0, l3 = from.length, ar; i4 < l3; i4++) { + if (ar || !(i4 in from)) { + if (!ar) + ar = Array.prototype.slice.call(from, 0, i4); + ar[i4] = from[i4]; + } } - return void 0; - } + return to.concat(ar || Array.prototype.slice.call(from)); } -function normalizeLocalDisabled(localDisabled, globalDisabled) { - var _localDisabled$dragga, _localDisabled$droppa; - if (typeof localDisabled === "boolean") { - return { - draggable: localDisabled, - droppable: false - }; +function isDayPickerMultiple(props2) { + return props2.mode === "multiple"; +} +function isDayPickerRange(props2) { + return props2.mode === "range"; +} +function isDayPickerSingle(props2) { + return props2.mode === "single"; +} +var defaultClassNames = { + root: "rdp", + multiple_months: "rdp-multiple_months", + with_weeknumber: "rdp-with_weeknumber", + vhidden: "rdp-vhidden", + button_reset: "rdp-button_reset", + button: "rdp-button", + caption: "rdp-caption", + caption_start: "rdp-caption_start", + caption_end: "rdp-caption_end", + caption_between: "rdp-caption_between", + caption_label: "rdp-caption_label", + caption_dropdowns: "rdp-caption_dropdowns", + dropdown: "rdp-dropdown", + dropdown_month: "rdp-dropdown_month", + dropdown_year: "rdp-dropdown_year", + dropdown_icon: "rdp-dropdown_icon", + months: "rdp-months", + month: "rdp-month", + table: "rdp-table", + tbody: "rdp-tbody", + tfoot: "rdp-tfoot", + head: "rdp-head", + head_row: "rdp-head_row", + head_cell: "rdp-head_cell", + nav: "rdp-nav", + nav_button: "rdp-nav_button", + nav_button_previous: "rdp-nav_button_previous", + nav_button_next: "rdp-nav_button_next", + nav_icon: "rdp-nav_icon", + row: "rdp-row", + weeknumber: "rdp-weeknumber", + cell: "rdp-cell", + day: "rdp-day", + day_today: "rdp-day_today", + day_outside: "rdp-day_outside", + day_selected: "rdp-day_selected", + day_disabled: "rdp-day_disabled", + day_hidden: "rdp-day_hidden", + day_range_start: "rdp-day_range_start", + day_range_end: "rdp-day_range_end", + day_range_middle: "rdp-day_range_middle" +}; +function formatCaption(month, options) { + return format(month, "LLLL y", options); +} +function formatDay(day, options) { + return format(day, "d", options); +} +function formatMonthCaption(month, options) { + return format(month, "LLLL", options); +} +function formatWeekNumber(weekNumber) { + return "".concat(weekNumber); +} +function formatWeekdayName(weekday, options) { + return format(weekday, "cccccc", options).toUpperCase(); +} +function formatYearCaption(year, options) { + return format(year, "yyyy", options); +} +var formatters3 = /* @__PURE__ */ Object.freeze({ + __proto__: null, + formatCaption, + formatDay, + formatMonthCaption, + formatWeekNumber, + formatWeekdayName, + formatYearCaption +}); +var labelDay = function(day, activeModifiers, options) { + return format(day, "do MMMM (EEEE)", options); +}; +var labelMonthDropdown = function() { + return "Month: "; +}; +var labelNext = function() { + return "Go to next month"; +}; +var labelPrevious = function() { + return "Go to previous month"; +}; +var labelWeekday = function(day, options) { + return format(day, "cccc", options); +}; +var labelWeekNumber = function(n2) { + return "Week n. ".concat(n2); +}; +var labelYearDropdown = function() { + return "Year: "; +}; +var labels = /* @__PURE__ */ Object.freeze({ + __proto__: null, + labelDay, + labelMonthDropdown, + labelNext, + labelPrevious, + labelWeekNumber, + labelWeekday, + labelYearDropdown +}); +function getDefaultContextValues() { + var captionLayout = "buttons"; + var classNames9 = defaultClassNames; + var locale2 = en_US_default; + var modifiersClassNames = {}; + var modifiers = {}; + var numberOfMonths = 1; + var styles2 = {}; + var today = new Date(); + return { + captionLayout, + classNames: classNames9, + formatters: formatters3, + labels, + locale: locale2, + modifiersClassNames, + modifiers, + numberOfMonths, + styles: styles2, + today, + mode: "default" + }; +} +function parseFromToProps(props2) { + var fromYear = props2.fromYear, toYear = props2.toYear, fromMonth = props2.fromMonth, toMonth = props2.toMonth; + var fromDate = props2.fromDate, toDate2 = props2.toDate; + if (fromMonth) { + fromDate = startOfMonth(fromMonth); + } else if (fromYear) { + fromDate = new Date(fromYear, 0, 1); + } + if (toMonth) { + toDate2 = endOfMonth(toMonth); + } else if (toYear) { + toDate2 = new Date(toYear, 11, 31); } return { - draggable: (_localDisabled$dragga = localDisabled == null ? void 0 : localDisabled.draggable) != null ? _localDisabled$dragga : globalDisabled.draggable, - droppable: (_localDisabled$droppa = localDisabled == null ? void 0 : localDisabled.droppable) != null ? _localDisabled$droppa : globalDisabled.droppable + fromDate: fromDate ? startOfDay(fromDate) : void 0, + toDate: toDate2 ? startOfDay(toDate2) : void 0 }; } -function hasSortableData(entry) { - if (!entry) { - return false; +var DayPickerContext = F(void 0); +function DayPickerProvider(props2) { + var _a2; + var initialProps = props2.initialProps; + var defaultContextValues = getDefaultContextValues(); + var _b2 = parseFromToProps(initialProps), fromDate = _b2.fromDate, toDate2 = _b2.toDate; + var captionLayout = (_a2 = initialProps.captionLayout) !== null && _a2 !== void 0 ? _a2 : defaultContextValues.captionLayout; + if (captionLayout !== "buttons" && (!fromDate || !toDate2)) { + captionLayout = "buttons"; } - const data = entry.data.current; - if (data && "sortable" in data && typeof data.sortable === "object" && "containerId" in data.sortable && "items" in data.sortable && "index" in data.sortable) { - return true; + var onSelect; + if (isDayPickerSingle(initialProps) || isDayPickerMultiple(initialProps) || isDayPickerRange(initialProps)) { + onSelect = initialProps.onSelect; } - return false; + var value = __assign(__assign(__assign({}, defaultContextValues), initialProps), { captionLayout, classNames: __assign(__assign({}, defaultContextValues.classNames), initialProps.classNames), components: __assign({}, initialProps.components), formatters: __assign(__assign({}, defaultContextValues.formatters), initialProps.formatters), fromDate, labels: __assign(__assign({}, defaultContextValues.labels), initialProps.labels), mode: initialProps.mode || defaultContextValues.mode, modifiers: __assign(__assign({}, defaultContextValues.modifiers), initialProps.modifiers), modifiersClassNames: __assign(__assign({}, defaultContextValues.modifiersClassNames), initialProps.modifiersClassNames), onSelect, styles: __assign(__assign({}, defaultContextValues.styles), initialProps.styles), toDate: toDate2 }); + return Cn.createElement(DayPickerContext.Provider, { value }, props2.children); } -var directions = [KeyboardCode.Down, KeyboardCode.Right, KeyboardCode.Up, KeyboardCode.Left]; -var sortableKeyboardCoordinates = (event, _ref) => { - let { - context: { - active, - collisionRect, - droppableRects, - droppableContainers, - over, - scrollableAncestors - } - } = _ref; - if (directions.includes(event.code)) { - event.preventDefault(); - if (!active || !collisionRect) { - return; - } - const filteredContainers = []; - droppableContainers.getEnabled().forEach((entry) => { - if (!entry || entry != null && entry.disabled) { - return; - } - const rect = droppableRects.get(entry.id); - if (!rect) { - return; - } - switch (event.code) { - case KeyboardCode.Down: - if (collisionRect.top < rect.top) { - filteredContainers.push(entry); - } - break; - case KeyboardCode.Up: - if (collisionRect.top > rect.top) { - filteredContainers.push(entry); - } - break; - case KeyboardCode.Left: - if (collisionRect.left > rect.left) { - filteredContainers.push(entry); - } - break; - case KeyboardCode.Right: - if (collisionRect.left < rect.left) { - filteredContainers.push(entry); - } - break; - } - }); - const collisions = closestCorners({ - active, - collisionRect, - droppableRects, - droppableContainers: filteredContainers, - pointerCoordinates: null - }); - let closestId = getFirstCollision(collisions, "id"); - if (closestId === (over == null ? void 0 : over.id) && collisions.length > 1) { - closestId = collisions[1].id; +function useDayPicker() { + var context = q2(DayPickerContext); + if (!context) { + throw new Error("useDayPicker must be used within a DayPickerProvider."); + } + return context; +} +function CaptionLabel(props2) { + var _a2 = useDayPicker(), locale2 = _a2.locale, classNames9 = _a2.classNames, styles2 = _a2.styles, formatCaption2 = _a2.formatters.formatCaption; + return Cn.createElement("div", { className: classNames9.caption_label, style: styles2.caption_label, "aria-live": "polite", role: "presentation", id: props2.id }, formatCaption2(props2.displayMonth, { locale: locale2 })); +} +function IconDropdown(props2) { + return Cn.createElement( + "svg", + __assign({ width: "8px", height: "8px", viewBox: "0 0 120 120", "data-testid": "iconDropdown" }, props2), + Cn.createElement("path", { d: "M4.22182541,48.2218254 C8.44222828,44.0014225 15.2388494,43.9273804 19.5496459,47.9996989 L19.7781746,48.2218254 L60,88.443 L100.221825,48.2218254 C104.442228,44.0014225 111.238849,43.9273804 115.549646,47.9996989 L115.778175,48.2218254 C119.998577,52.4422283 120.07262,59.2388494 116.000301,63.5496459 L115.778175,63.7781746 L67.7781746,111.778175 C63.5577717,115.998577 56.7611506,116.07262 52.4503541,112.000301 L52.2218254,111.778175 L4.22182541,63.7781746 C-0.0739418023,59.4824074 -0.0739418023,52.5175926 4.22182541,48.2218254 Z", fill: "currentColor", fillRule: "nonzero" }) + ); +} +function Dropdown(props2) { + var _a2, _b2; + var onChange = props2.onChange, value = props2.value, children = props2.children, caption = props2.caption, className = props2.className, style = props2.style; + var dayPicker = useDayPicker(); + var IconDropdownComponent = (_b2 = (_a2 = dayPicker.components) === null || _a2 === void 0 ? void 0 : _a2.IconDropdown) !== null && _b2 !== void 0 ? _b2 : IconDropdown; + return Cn.createElement( + "div", + { className, style }, + Cn.createElement("span", { className: dayPicker.classNames.vhidden }, props2["aria-label"]), + Cn.createElement("select", { name: props2.name, "aria-label": props2["aria-label"], className: dayPicker.classNames.dropdown, style: dayPicker.styles.dropdown, value, onChange }, children), + Cn.createElement( + "div", + { className: dayPicker.classNames.caption_label, style: dayPicker.styles.caption_label, "aria-hidden": "true" }, + caption, + Cn.createElement(IconDropdownComponent, { className: dayPicker.classNames.dropdown_icon, style: dayPicker.styles.dropdown_icon }) + ) + ); +} +function MonthsDropdown(props2) { + var _a2; + var _b2 = useDayPicker(), fromDate = _b2.fromDate, toDate2 = _b2.toDate, styles2 = _b2.styles, locale2 = _b2.locale, formatMonthCaption2 = _b2.formatters.formatMonthCaption, classNames9 = _b2.classNames, components = _b2.components, labelMonthDropdown2 = _b2.labels.labelMonthDropdown; + if (!fromDate) + return Cn.createElement(Cn.Fragment, null); + if (!toDate2) + return Cn.createElement(Cn.Fragment, null); + var dropdownMonths = []; + if (isSameYear(fromDate, toDate2)) { + var date = startOfMonth(fromDate); + for (var month = fromDate.getMonth(); month <= toDate2.getMonth(); month++) { + dropdownMonths.push(setMonth(date, month)); } - if (closestId != null) { - const activeDroppable = droppableContainers.get(active.id); - const newDroppable = droppableContainers.get(closestId); - const newRect = newDroppable ? droppableRects.get(newDroppable.id) : null; - const newNode = newDroppable == null ? void 0 : newDroppable.node.current; - if (newNode && newRect && activeDroppable && newDroppable) { - const newScrollAncestors = getScrollableAncestors(newNode); - const hasDifferentScrollAncestors = newScrollAncestors.some((element, index) => scrollableAncestors[index] !== element); - const hasSameContainer = isSameContainer(activeDroppable, newDroppable); - const isAfterActive = isAfter2(activeDroppable, newDroppable); - const offset = hasDifferentScrollAncestors || !hasSameContainer ? { - x: 0, - y: 0 - } : { - x: isAfterActive ? collisionRect.width - newRect.width : 0, - y: isAfterActive ? collisionRect.height - newRect.height : 0 - }; - const rectCoordinates = { - x: newRect.left, - y: newRect.top - }; - const newCoordinates = offset.x && offset.y ? rectCoordinates : subtract(rectCoordinates, offset); - return newCoordinates; - } + } else { + var date = startOfMonth(new Date()); + for (var month = 0; month <= 11; month++) { + dropdownMonths.push(setMonth(date, month)); } } - return void 0; -}; -function isSameContainer(a5, b4) { - if (!hasSortableData(a5) || !hasSortableData(b4)) { - return false; + var handleChange = function(e4) { + var selectedMonth = Number(e4.target.value); + var newMonth = setMonth(startOfMonth(props2.displayMonth), selectedMonth); + props2.onChange(newMonth); + }; + var DropdownComponent2 = (_a2 = components === null || components === void 0 ? void 0 : components.Dropdown) !== null && _a2 !== void 0 ? _a2 : Dropdown; + return Cn.createElement(DropdownComponent2, { name: "months", "aria-label": labelMonthDropdown2(), className: classNames9.dropdown_month, style: styles2.dropdown_month, onChange: handleChange, value: props2.displayMonth.getMonth(), caption: formatMonthCaption2(props2.displayMonth, { locale: locale2 }) }, dropdownMonths.map(function(m5) { + return Cn.createElement("option", { key: m5.getMonth(), value: m5.getMonth() }, formatMonthCaption2(m5, { locale: locale2 })); + })); +} +function YearsDropdown(props2) { + var _a2; + var displayMonth = props2.displayMonth; + var _b2 = useDayPicker(), fromDate = _b2.fromDate, toDate2 = _b2.toDate, locale2 = _b2.locale, styles2 = _b2.styles, classNames9 = _b2.classNames, components = _b2.components, formatYearCaption2 = _b2.formatters.formatYearCaption, labelYearDropdown2 = _b2.labels.labelYearDropdown; + var years = []; + if (!fromDate) + return Cn.createElement(Cn.Fragment, null); + if (!toDate2) + return Cn.createElement(Cn.Fragment, null); + var fromYear = fromDate.getFullYear(); + var toYear = toDate2.getFullYear(); + for (var year = fromYear; year <= toYear; year++) { + years.push(setYear(startOfYear(new Date()), year)); } - return a5.data.current.sortable.containerId === b4.data.current.sortable.containerId; + var handleChange = function(e4) { + var newMonth = setYear(startOfMonth(displayMonth), Number(e4.target.value)); + props2.onChange(newMonth); + }; + var DropdownComponent2 = (_a2 = components === null || components === void 0 ? void 0 : components.Dropdown) !== null && _a2 !== void 0 ? _a2 : Dropdown; + return Cn.createElement(DropdownComponent2, { name: "years", "aria-label": labelYearDropdown2(), className: classNames9.dropdown_year, style: styles2.dropdown_year, onChange: handleChange, value: displayMonth.getFullYear(), caption: formatYearCaption2(displayMonth, { locale: locale2 }) }, years.map(function(year2) { + return Cn.createElement("option", { key: year2.getFullYear(), value: year2.getFullYear() }, formatYearCaption2(year2, { locale: locale2 })); + })); } -function isAfter2(a5, b4) { - if (!hasSortableData(a5) || !hasSortableData(b4)) { - return false; +function useControlledValue(defaultValue2, controlledValue) { + var _a2 = h2(defaultValue2), uncontrolledValue = _a2[0], setValue = _a2[1]; + var value = controlledValue === void 0 ? uncontrolledValue : controlledValue; + return [value, setValue]; +} +function getInitialMonth(context) { + var month = context.month, defaultMonth = context.defaultMonth, today = context.today; + var initialMonth = month || defaultMonth || today || new Date(); + var toDate2 = context.toDate, fromDate = context.fromDate, _a2 = context.numberOfMonths, numberOfMonths = _a2 === void 0 ? 1 : _a2; + if (toDate2 && differenceInCalendarMonths(toDate2, initialMonth) < 0) { + var offset2 = -1 * (numberOfMonths - 1); + initialMonth = addMonths(toDate2, offset2); } - if (!isSameContainer(a5, b4)) { - return false; + if (fromDate && differenceInCalendarMonths(initialMonth, fromDate) < 0) { + initialMonth = fromDate; } - return a5.data.current.sortable.index < b4.data.current.sortable.index; -} - -// node_modules/@tanstack/table-core/build/lib/index.mjs -function functionalUpdate(updater, input) { - return typeof updater === "function" ? updater(input) : updater; + return startOfMonth(initialMonth); } -function makeStateUpdater(key2, instance) { - return (updater) => { - instance.setState((old) => { - return { - ...old, - [key2]: functionalUpdate(updater, old[key2]) - }; - }); +function useNavigationState() { + var context = useDayPicker(); + var initialMonth = getInitialMonth(context); + var _a2 = useControlledValue(initialMonth, context.month), month = _a2[0], setMonth2 = _a2[1]; + var goToMonth = function(date) { + var _a3; + if (context.disableNavigation) + return; + var month2 = startOfMonth(date); + setMonth2(month2); + (_a3 = context.onMonthChange) === null || _a3 === void 0 ? void 0 : _a3.call(context, month2); }; + return [month, goToMonth]; } -function isFunction(d5) { - return d5 instanceof Function; +function getDisplayMonths(month, _a2) { + var reverseMonths = _a2.reverseMonths, numberOfMonths = _a2.numberOfMonths; + var start = startOfMonth(month); + var end = startOfMonth(addMonths(start, numberOfMonths)); + var monthsDiff = differenceInCalendarMonths(end, start); + var months = []; + for (var i4 = 0; i4 < monthsDiff; i4++) { + var nextMonth = addMonths(start, i4); + months.push(nextMonth); + } + if (reverseMonths) + months = months.reverse(); + return months; } -function flattenBy(arr, getChildren) { - const flat = []; - const recurse = (subArr) => { - subArr.forEach((item) => { - flat.push(item); - const children = getChildren(item); - if (children != null && children.length) { - recurse(children); - } +function getNextMonth(startingMonth, options) { + if (options.disableNavigation) { + return void 0; + } + var toDate2 = options.toDate, pagedNavigation = options.pagedNavigation, _a2 = options.numberOfMonths, numberOfMonths = _a2 === void 0 ? 1 : _a2; + var offset2 = pagedNavigation ? numberOfMonths : 1; + var month = startOfMonth(startingMonth); + if (!toDate2) { + return addMonths(month, offset2); + } + var monthsDiff = differenceInCalendarMonths(toDate2, startingMonth); + if (monthsDiff < numberOfMonths) { + return void 0; + } + return addMonths(month, offset2); +} +function getPreviousMonth(startingMonth, options) { + if (options.disableNavigation) { + return void 0; + } + var fromDate = options.fromDate, pagedNavigation = options.pagedNavigation, _a2 = options.numberOfMonths, numberOfMonths = _a2 === void 0 ? 1 : _a2; + var offset2 = pagedNavigation ? numberOfMonths : 1; + var month = startOfMonth(startingMonth); + if (!fromDate) { + return addMonths(month, -offset2); + } + var monthsDiff = differenceInCalendarMonths(month, fromDate); + if (monthsDiff <= 0) { + return void 0; + } + return addMonths(month, -offset2); +} +var NavigationContext = F(void 0); +function NavigationProvider(props2) { + var dayPicker = useDayPicker(); + var _a2 = useNavigationState(), currentMonth = _a2[0], goToMonth = _a2[1]; + var displayMonths = getDisplayMonths(currentMonth, dayPicker); + var nextMonth = getNextMonth(currentMonth, dayPicker); + var previousMonth = getPreviousMonth(currentMonth, dayPicker); + var isDateDisplayed = function(date) { + return displayMonths.some(function(displayMonth) { + return isSameMonth(date, displayMonth); }); }; - recurse(arr); - return flat; -} -function memo(getDeps, fn2, opts) { - let deps = []; - let result; - return () => { - let depTime; - if (opts.key && opts.debug) - depTime = Date.now(); - const newDeps = getDeps(); - const depsChanged = newDeps.length !== deps.length || newDeps.some((dep, index) => deps[index] !== dep); - if (!depsChanged) { - return result; - } - deps = newDeps; - let resultTime; - if (opts.key && opts.debug) - resultTime = Date.now(); - result = fn2(...newDeps); - opts == null ? void 0 : opts.onChange == null ? void 0 : opts.onChange(result); - if (opts.key && opts.debug) { - if (opts != null && opts.debug()) { - const depEndTime = Math.round((Date.now() - depTime) * 100) / 100; - const resultEndTime = Math.round((Date.now() - resultTime) * 100) / 100; - const resultFpsPercentage = resultEndTime / 16; - const pad = (str, num) => { - str = String(str); - while (str.length < num) { - str = " " + str; - } - return str; - }; - console.info(`%c\u23F1 ${pad(resultEndTime, 5)} /${pad(depEndTime, 5)} ms`, ` - font-size: .6rem; - font-weight: bold; - color: hsl(${Math.max(0, Math.min(120 - 120 * resultFpsPercentage, 120))}deg 100% 31%);`, opts == null ? void 0 : opts.key); - } + var goToDate = function(date, refDate) { + if (isDateDisplayed(date)) { + return; } - return result; + if (refDate && isBefore(date, refDate)) { + goToMonth(addMonths(date, 1 + dayPicker.numberOfMonths * -1)); + } else { + goToMonth(date); + } + }; + var value = { + currentMonth, + displayMonths, + goToMonth, + goToDate, + previousMonth, + nextMonth, + isDateDisplayed }; + return Cn.createElement(NavigationContext.Provider, { value }, props2.children); } -function createColumn(table, columnDef, depth, parent) { - var _ref, _resolvedColumnDef$id; - const defaultColumn = table._getDefaultColumnDef(); - const resolvedColumnDef = { - ...defaultColumn, - ...columnDef +function useNavigation() { + var context = q2(NavigationContext); + if (!context) { + throw new Error("useNavigation must be used within a NavigationProvider"); + } + return context; +} +function CaptionDropdowns(props2) { + var _a2; + var _b2 = useDayPicker(), classNames9 = _b2.classNames, styles2 = _b2.styles, components = _b2.components; + var goToMonth = useNavigation().goToMonth; + var handleMonthChange = function(newMonth) { + goToMonth(newMonth); }; - const accessorKey = resolvedColumnDef.accessorKey; - let id2 = (_ref = (_resolvedColumnDef$id = resolvedColumnDef.id) != null ? _resolvedColumnDef$id : accessorKey ? accessorKey.replace(".", "_") : void 0) != null ? _ref : typeof resolvedColumnDef.header === "string" ? resolvedColumnDef.header : void 0; - let accessorFn; - if (resolvedColumnDef.accessorFn) { - accessorFn = resolvedColumnDef.accessorFn; - } else if (accessorKey) { - if (accessorKey.includes(".")) { - accessorFn = (originalRow) => { - let result = originalRow; - for (const key2 of accessorKey.split(".")) { - var _result; - result = (_result = result) == null ? void 0 : _result[key2]; - if (result === void 0) { - console.warn(`"${key2}" in deeply nested key "${accessorKey}" returned undefined.`); - } - } - return result; - }; - } else { - accessorFn = (originalRow) => originalRow[resolvedColumnDef.accessorKey]; - } + var CaptionLabelComponent = (_a2 = components === null || components === void 0 ? void 0 : components.CaptionLabel) !== null && _a2 !== void 0 ? _a2 : CaptionLabel; + var captionLabel = Cn.createElement(CaptionLabelComponent, { id: props2.id, displayMonth: props2.displayMonth }); + return Cn.createElement( + "div", + { className: classNames9.caption_dropdowns, style: styles2.caption_dropdowns }, + Cn.createElement("div", { className: classNames9.vhidden }, captionLabel), + Cn.createElement(MonthsDropdown, { onChange: handleMonthChange, displayMonth: props2.displayMonth }), + Cn.createElement(YearsDropdown, { onChange: handleMonthChange, displayMonth: props2.displayMonth }) + ); +} +function IconLeft(props2) { + return Cn.createElement( + "svg", + __assign({ width: "16px", height: "16px", viewBox: "0 0 120 120" }, props2), + Cn.createElement("path", { d: "M69.490332,3.34314575 C72.6145263,0.218951416 77.6798462,0.218951416 80.8040405,3.34314575 C83.8617626,6.40086786 83.9268205,11.3179931 80.9992143,14.4548388 L80.8040405,14.6568542 L35.461,60 L80.8040405,105.343146 C83.8617626,108.400868 83.9268205,113.317993 80.9992143,116.454839 L80.8040405,116.656854 C77.7463184,119.714576 72.8291931,119.779634 69.6923475,116.852028 L69.490332,116.656854 L18.490332,65.6568542 C15.4326099,62.5991321 15.367552,57.6820069 18.2951583,54.5451612 L18.490332,54.3431458 L69.490332,3.34314575 Z", fill: "currentColor", fillRule: "nonzero" }) + ); +} +function IconRight(props2) { + return Cn.createElement( + "svg", + __assign({ width: "16px", height: "16px", viewBox: "0 0 120 120" }, props2), + Cn.createElement("path", { d: "M49.8040405,3.34314575 C46.6798462,0.218951416 41.6145263,0.218951416 38.490332,3.34314575 C35.4326099,6.40086786 35.367552,11.3179931 38.2951583,14.4548388 L38.490332,14.6568542 L83.8333725,60 L38.490332,105.343146 C35.4326099,108.400868 35.367552,113.317993 38.2951583,116.454839 L38.490332,116.656854 C41.5480541,119.714576 46.4651794,119.779634 49.602025,116.852028 L49.8040405,116.656854 L100.804041,65.6568542 C103.861763,62.5991321 103.926821,57.6820069 100.999214,54.5451612 L100.804041,54.3431458 L49.8040405,3.34314575 Z", fill: "currentColor" }) + ); +} +var Button = k3(function(props2, ref2) { + var _a2 = useDayPicker(), classNames9 = _a2.classNames, styles2 = _a2.styles; + var classNamesArr = [classNames9.button_reset, classNames9.button]; + if (props2.className) { + classNamesArr.push(props2.className); } - if (!id2) { - if (true) { - throw new Error(resolvedColumnDef.accessorFn ? `Columns require an id when using an accessorFn` : `Columns require an id when using a non-string header`); - } - throw new Error(); + var className = classNamesArr.join(" "); + var style = __assign(__assign({}, styles2.button_reset), styles2.button); + if (props2.style) { + Object.assign(style, props2.style); } - let column = { - id: `${String(id2)}`, - accessorFn, - parent, - depth, - columnDef: resolvedColumnDef, - columns: [], - getFlatColumns: memo(() => [true], () => { - var _column$columns; - return [column, ...(_column$columns = column.columns) == null ? void 0 : _column$columns.flatMap((d5) => d5.getFlatColumns())]; - }, { - key: false, - debug: () => { - var _table$options$debugA; - return (_table$options$debugA = table.options.debugAll) != null ? _table$options$debugA : table.options.debugColumns; - } - }), - getLeafColumns: memo(() => [table._getOrderColumnsFn()], (orderColumns2) => { - var _column$columns2; - if ((_column$columns2 = column.columns) != null && _column$columns2.length) { - let leafColumns = column.columns.flatMap((column2) => column2.getLeafColumns()); - return orderColumns2(leafColumns); - } - return [column]; - }, { - key: false, - debug: () => { - var _table$options$debugA2; - return (_table$options$debugA2 = table.options.debugAll) != null ? _table$options$debugA2 : table.options.debugColumns; - } - }) - }; - column = table._features.reduce((obj, feature) => { - return Object.assign(obj, feature.createColumn == null ? void 0 : feature.createColumn(column, table)); - }, column); - return column; + return Cn.createElement("button", __assign({}, props2, { ref: ref2, type: "button", className, style })); +}); +function Navigation(props2) { + var _a2, _b2; + var _c2 = useDayPicker(), dir = _c2.dir, locale2 = _c2.locale, classNames9 = _c2.classNames, styles2 = _c2.styles, _d2 = _c2.labels, labelPrevious2 = _d2.labelPrevious, labelNext2 = _d2.labelNext, components = _c2.components; + if (!props2.nextMonth && !props2.previousMonth) { + return Cn.createElement(Cn.Fragment, null); + } + var previousLabel = labelPrevious2(props2.previousMonth, { locale: locale2 }); + var previousClassName = [ + classNames9.nav_button, + classNames9.nav_button_previous + ].join(" "); + var nextLabel = labelNext2(props2.nextMonth, { locale: locale2 }); + var nextClassName = [ + classNames9.nav_button, + classNames9.nav_button_next + ].join(" "); + var IconRightComponent = (_a2 = components === null || components === void 0 ? void 0 : components.IconRight) !== null && _a2 !== void 0 ? _a2 : IconRight; + var IconLeftComponent = (_b2 = components === null || components === void 0 ? void 0 : components.IconLeft) !== null && _b2 !== void 0 ? _b2 : IconLeft; + return Cn.createElement( + "div", + { className: classNames9.nav, style: styles2.nav }, + !props2.hidePrevious && Cn.createElement(Button, { name: "previous-month", "aria-label": previousLabel, className: previousClassName, style: styles2.nav_button_previous, disabled: !props2.previousMonth, onClick: props2.onPreviousClick }, dir === "rtl" ? Cn.createElement(IconRightComponent, { className: classNames9.nav_icon, style: styles2.nav_icon }) : Cn.createElement(IconLeftComponent, { className: classNames9.nav_icon, style: styles2.nav_icon })), + !props2.hideNext && Cn.createElement(Button, { name: "next-month", "aria-label": nextLabel, className: nextClassName, style: styles2.nav_button_next, disabled: !props2.nextMonth, onClick: props2.onNextClick }, dir === "rtl" ? Cn.createElement(IconLeftComponent, { className: classNames9.nav_icon, style: styles2.nav_icon }) : Cn.createElement(IconRightComponent, { className: classNames9.nav_icon, style: styles2.nav_icon })) + ); } -function createHeader(table, column, options) { - var _options$id; - const id2 = (_options$id = options.id) != null ? _options$id : column.id; - let header = { - id: id2, - column, - index: options.index, - isPlaceholder: !!options.isPlaceholder, - placeholderId: options.placeholderId, - depth: options.depth, - subHeaders: [], - colSpan: 0, - rowSpan: 0, - headerGroup: null, - getLeafHeaders: () => { - const leafHeaders = []; - const recurseHeader = (h5) => { - if (h5.subHeaders && h5.subHeaders.length) { - h5.subHeaders.map(recurseHeader); - } - leafHeaders.push(h5); - }; - recurseHeader(header); - return leafHeaders; - }, - getContext: () => ({ - table, - header, - column - }) - }; - table._features.forEach((feature) => { - Object.assign(header, feature.createHeader == null ? void 0 : feature.createHeader(header, table)); +function CaptionNavigation(props2) { + var _a2; + var _b2 = useDayPicker(), numberOfMonths = _b2.numberOfMonths, dir = _b2.dir; + var _c2 = useNavigation(), previousMonth = _c2.previousMonth, nextMonth = _c2.nextMonth, goToMonth = _c2.goToMonth, displayMonths = _c2.displayMonths; + var displayIndex = displayMonths.findIndex(function(month) { + return isSameMonth(props2.displayMonth, month); }); - return header; + var isFirst = displayIndex === 0; + var isLast = displayIndex === displayMonths.length - 1; + if (dir === "rtl") { + _a2 = [isFirst, isLast], isLast = _a2[0], isFirst = _a2[1]; + } + var hideNext = numberOfMonths > 1 && (isFirst || !isLast); + var hidePrevious = numberOfMonths > 1 && (isLast || !isFirst); + var handlePreviousClick = function() { + if (!previousMonth) + return; + goToMonth(previousMonth); + }; + var handleNextClick = function() { + if (!nextMonth) + return; + goToMonth(nextMonth); + }; + return Cn.createElement(Navigation, { displayMonth: props2.displayMonth, hideNext, hidePrevious, nextMonth, previousMonth, onPreviousClick: handlePreviousClick, onNextClick: handleNextClick }); } -var Headers = { - createTable: (table) => { - return { - getHeaderGroups: memo(() => [table.getAllColumns(), table.getVisibleLeafColumns(), table.getState().columnPinning.left, table.getState().columnPinning.right], (allColumns, leafColumns, left, right) => { - var _left$map$filter, _right$map$filter; - const leftColumns = (_left$map$filter = left == null ? void 0 : left.map((columnId) => leafColumns.find((d5) => d5.id === columnId)).filter(Boolean)) != null ? _left$map$filter : []; - const rightColumns = (_right$map$filter = right == null ? void 0 : right.map((columnId) => leafColumns.find((d5) => d5.id === columnId)).filter(Boolean)) != null ? _right$map$filter : []; - const centerColumns = leafColumns.filter((column) => !(left != null && left.includes(column.id)) && !(right != null && right.includes(column.id))); - const headerGroups = buildHeaderGroups(allColumns, [...leftColumns, ...centerColumns, ...rightColumns], table); - return headerGroups; - }, { - key: "getHeaderGroups", - debug: () => { - var _table$options$debugA; - return (_table$options$debugA = table.options.debugAll) != null ? _table$options$debugA : table.options.debugHeaders; - } - }), - getCenterHeaderGroups: memo(() => [table.getAllColumns(), table.getVisibleLeafColumns(), table.getState().columnPinning.left, table.getState().columnPinning.right], (allColumns, leafColumns, left, right) => { - leafColumns = leafColumns.filter((column) => !(left != null && left.includes(column.id)) && !(right != null && right.includes(column.id))); - return buildHeaderGroups(allColumns, leafColumns, table, "center"); - }, { - key: "getCenterHeaderGroups", - debug: () => { - var _table$options$debugA2; - return (_table$options$debugA2 = table.options.debugAll) != null ? _table$options$debugA2 : table.options.debugHeaders; - } - }), - getLeftHeaderGroups: memo(() => [table.getAllColumns(), table.getVisibleLeafColumns(), table.getState().columnPinning.left], (allColumns, leafColumns, left) => { - var _left$map$filter2; - const orderedLeafColumns = (_left$map$filter2 = left == null ? void 0 : left.map((columnId) => leafColumns.find((d5) => d5.id === columnId)).filter(Boolean)) != null ? _left$map$filter2 : []; - return buildHeaderGroups(allColumns, orderedLeafColumns, table, "left"); - }, { - key: "getLeftHeaderGroups", - debug: () => { - var _table$options$debugA3; - return (_table$options$debugA3 = table.options.debugAll) != null ? _table$options$debugA3 : table.options.debugHeaders; - } - }), - getRightHeaderGroups: memo(() => [table.getAllColumns(), table.getVisibleLeafColumns(), table.getState().columnPinning.right], (allColumns, leafColumns, right) => { - var _right$map$filter2; - const orderedLeafColumns = (_right$map$filter2 = right == null ? void 0 : right.map((columnId) => leafColumns.find((d5) => d5.id === columnId)).filter(Boolean)) != null ? _right$map$filter2 : []; - return buildHeaderGroups(allColumns, orderedLeafColumns, table, "right"); - }, { - key: "getRightHeaderGroups", - debug: () => { - var _table$options$debugA4; - return (_table$options$debugA4 = table.options.debugAll) != null ? _table$options$debugA4 : table.options.debugHeaders; - } - }), - getFooterGroups: memo(() => [table.getHeaderGroups()], (headerGroups) => { - return [...headerGroups].reverse(); - }, { - key: "getFooterGroups", - debug: () => { - var _table$options$debugA5; - return (_table$options$debugA5 = table.options.debugAll) != null ? _table$options$debugA5 : table.options.debugHeaders; - } - }), - getLeftFooterGroups: memo(() => [table.getLeftHeaderGroups()], (headerGroups) => { - return [...headerGroups].reverse(); - }, { - key: "getLeftFooterGroups", - debug: () => { - var _table$options$debugA6; - return (_table$options$debugA6 = table.options.debugAll) != null ? _table$options$debugA6 : table.options.debugHeaders; - } - }), - getCenterFooterGroups: memo(() => [table.getCenterHeaderGroups()], (headerGroups) => { - return [...headerGroups].reverse(); - }, { - key: "getCenterFooterGroups", - debug: () => { - var _table$options$debugA7; - return (_table$options$debugA7 = table.options.debugAll) != null ? _table$options$debugA7 : table.options.debugHeaders; - } - }), - getRightFooterGroups: memo(() => [table.getRightHeaderGroups()], (headerGroups) => { - return [...headerGroups].reverse(); - }, { - key: "getRightFooterGroups", - debug: () => { - var _table$options$debugA8; - return (_table$options$debugA8 = table.options.debugAll) != null ? _table$options$debugA8 : table.options.debugHeaders; - } - }), - getFlatHeaders: memo(() => [table.getHeaderGroups()], (headerGroups) => { - return headerGroups.map((headerGroup) => { - return headerGroup.headers; - }).flat(); - }, { - key: "getFlatHeaders", - debug: () => { - var _table$options$debugA9; - return (_table$options$debugA9 = table.options.debugAll) != null ? _table$options$debugA9 : table.options.debugHeaders; - } - }), - getLeftFlatHeaders: memo(() => [table.getLeftHeaderGroups()], (left) => { - return left.map((headerGroup) => { - return headerGroup.headers; - }).flat(); - }, { - key: "getLeftFlatHeaders", - debug: () => { - var _table$options$debugA10; - return (_table$options$debugA10 = table.options.debugAll) != null ? _table$options$debugA10 : table.options.debugHeaders; - } - }), - getCenterFlatHeaders: memo(() => [table.getCenterHeaderGroups()], (left) => { - return left.map((headerGroup) => { - return headerGroup.headers; - }).flat(); - }, { - key: "getCenterFlatHeaders", - debug: () => { - var _table$options$debugA11; - return (_table$options$debugA11 = table.options.debugAll) != null ? _table$options$debugA11 : table.options.debugHeaders; - } - }), - getRightFlatHeaders: memo(() => [table.getRightHeaderGroups()], (left) => { - return left.map((headerGroup) => { - return headerGroup.headers; - }).flat(); - }, { - key: "getRightFlatHeaders", - debug: () => { - var _table$options$debugA12; - return (_table$options$debugA12 = table.options.debugAll) != null ? _table$options$debugA12 : table.options.debugHeaders; - } - }), - getCenterLeafHeaders: memo(() => [table.getCenterFlatHeaders()], (flatHeaders) => { - return flatHeaders.filter((header) => { - var _header$subHeaders; - return !((_header$subHeaders = header.subHeaders) != null && _header$subHeaders.length); - }); - }, { - key: "getCenterLeafHeaders", - debug: () => { - var _table$options$debugA13; - return (_table$options$debugA13 = table.options.debugAll) != null ? _table$options$debugA13 : table.options.debugHeaders; - } - }), - getLeftLeafHeaders: memo(() => [table.getLeftFlatHeaders()], (flatHeaders) => { - return flatHeaders.filter((header) => { - var _header$subHeaders2; - return !((_header$subHeaders2 = header.subHeaders) != null && _header$subHeaders2.length); - }); - }, { - key: "getLeftLeafHeaders", - debug: () => { - var _table$options$debugA14; - return (_table$options$debugA14 = table.options.debugAll) != null ? _table$options$debugA14 : table.options.debugHeaders; - } - }), - getRightLeafHeaders: memo(() => [table.getRightFlatHeaders()], (flatHeaders) => { - return flatHeaders.filter((header) => { - var _header$subHeaders3; - return !((_header$subHeaders3 = header.subHeaders) != null && _header$subHeaders3.length); - }); - }, { - key: "getRightLeafHeaders", - debug: () => { - var _table$options$debugA15; - return (_table$options$debugA15 = table.options.debugAll) != null ? _table$options$debugA15 : table.options.debugHeaders; - } - }), - getLeafHeaders: memo(() => [table.getLeftHeaderGroups(), table.getCenterHeaderGroups(), table.getRightHeaderGroups()], (left, center, right) => { - var _left$0$headers, _left$, _center$0$headers, _center$, _right$0$headers, _right$; - return [...(_left$0$headers = (_left$ = left[0]) == null ? void 0 : _left$.headers) != null ? _left$0$headers : [], ...(_center$0$headers = (_center$ = center[0]) == null ? void 0 : _center$.headers) != null ? _center$0$headers : [], ...(_right$0$headers = (_right$ = right[0]) == null ? void 0 : _right$.headers) != null ? _right$0$headers : []].map((header) => { - return header.getLeafHeaders(); - }).flat(); - }, { - key: "getLeafHeaders", - debug: () => { - var _table$options$debugA16; - return (_table$options$debugA16 = table.options.debugAll) != null ? _table$options$debugA16 : table.options.debugHeaders; - } - }) - }; +function Caption(props2) { + var _a2; + var _b2 = useDayPicker(), classNames9 = _b2.classNames, disableNavigation = _b2.disableNavigation, styles2 = _b2.styles, captionLayout = _b2.captionLayout, components = _b2.components; + var CaptionLabelComponent = (_a2 = components === null || components === void 0 ? void 0 : components.CaptionLabel) !== null && _a2 !== void 0 ? _a2 : CaptionLabel; + var caption; + if (disableNavigation) { + caption = Cn.createElement(CaptionLabelComponent, { id: props2.id, displayMonth: props2.displayMonth }); + } else if (captionLayout === "dropdown") { + caption = Cn.createElement(CaptionDropdowns, { displayMonth: props2.displayMonth, id: props2.id }); + } else if (captionLayout === "dropdown-buttons") { + caption = Cn.createElement( + Cn.Fragment, + null, + Cn.createElement(CaptionDropdowns, { displayMonth: props2.displayMonth, id: props2.id }), + Cn.createElement(CaptionNavigation, { displayMonth: props2.displayMonth, id: props2.id }) + ); + } else { + caption = Cn.createElement( + Cn.Fragment, + null, + Cn.createElement(CaptionLabelComponent, { id: props2.id, displayMonth: props2.displayMonth }), + Cn.createElement(CaptionNavigation, { displayMonth: props2.displayMonth, id: props2.id }) + ); } -}; -function buildHeaderGroups(allColumns, columnsToGroup, table, headerFamily) { - var _headerGroups$0$heade, _headerGroups$; - let maxDepth = 0; - const findMaxDepth = function(columns, depth) { - if (depth === void 0) { - depth = 1; - } - maxDepth = Math.max(maxDepth, depth); - columns.filter((column) => column.getIsVisible()).forEach((column) => { - var _column$columns; - if ((_column$columns = column.columns) != null && _column$columns.length) { - findMaxDepth(column.columns, depth + 1); + return Cn.createElement("div", { className: classNames9.caption, style: styles2.caption }, caption); +} +function Footer(props2) { + var _a2 = useDayPicker(), footer = _a2.footer, styles2 = _a2.styles, tfoot = _a2.classNames.tfoot; + if (!footer) + return Cn.createElement(Cn.Fragment, null); + return Cn.createElement( + "tfoot", + { className: tfoot, style: styles2.tfoot }, + Cn.createElement( + "tr", + null, + Cn.createElement("td", { colSpan: 8 }, footer) + ) + ); +} +function getWeekdays(locale2, weekStartsOn, ISOWeek) { + var start = ISOWeek ? startOfISOWeek(new Date()) : startOfWeek(new Date(), { locale: locale2, weekStartsOn }); + var days = []; + for (var i4 = 0; i4 < 7; i4++) { + var day = addDays(start, i4); + days.push(day); + } + return days; +} +function HeadRow() { + var _a2 = useDayPicker(), classNames9 = _a2.classNames, styles2 = _a2.styles, showWeekNumber = _a2.showWeekNumber, locale2 = _a2.locale, weekStartsOn = _a2.weekStartsOn, ISOWeek = _a2.ISOWeek, formatWeekdayName2 = _a2.formatters.formatWeekdayName, labelWeekday2 = _a2.labels.labelWeekday; + var weekdays = getWeekdays(locale2, weekStartsOn, ISOWeek); + return Cn.createElement( + "tr", + { style: styles2.head_row, className: classNames9.head_row }, + showWeekNumber && Cn.createElement("th", { scope: "col", style: styles2.head_cell, className: classNames9.head_cell }), + weekdays.map(function(weekday, i4) { + return Cn.createElement("th", { key: i4, scope: "col", className: classNames9.head_cell, style: styles2.head_cell, "aria-label": labelWeekday2(weekday, { locale: locale2 }) }, formatWeekdayName2(weekday, { locale: locale2 })); + }) + ); +} +function Head() { + var _a2; + var _b2 = useDayPicker(), classNames9 = _b2.classNames, styles2 = _b2.styles, components = _b2.components; + var HeadRowComponent = (_a2 = components === null || components === void 0 ? void 0 : components.HeadRow) !== null && _a2 !== void 0 ? _a2 : HeadRow; + return Cn.createElement( + "thead", + { style: styles2.head, className: classNames9.head }, + Cn.createElement(HeadRowComponent, null) + ); +} +function DayContent(props2) { + var _a2 = useDayPicker(), locale2 = _a2.locale, formatDay2 = _a2.formatters.formatDay; + return Cn.createElement(Cn.Fragment, null, formatDay2(props2.date, { locale: locale2 })); +} +var SelectMultipleContext = F(void 0); +function SelectMultipleProvider(props2) { + if (!isDayPickerMultiple(props2.initialProps)) { + var emptyContextValue = { + selected: void 0, + modifiers: { + disabled: [] } - }, 0); - }; - findMaxDepth(allColumns); - let headerGroups = []; - const createHeaderGroup = (headersToGroup, depth) => { - const headerGroup = { - depth, - id: [headerFamily, `${depth}`].filter(Boolean).join("_"), - headers: [] }; - const pendingParentHeaders = []; - headersToGroup.forEach((headerToGroup) => { - const latestPendingParentHeader = [...pendingParentHeaders].reverse()[0]; - const isLeafHeader = headerToGroup.column.depth === headerGroup.depth; - let column; - let isPlaceholder = false; - if (isLeafHeader && headerToGroup.column.parent) { - column = headerToGroup.column.parent; - } else { - column = headerToGroup.column; - isPlaceholder = true; - } - if (latestPendingParentHeader && (latestPendingParentHeader == null ? void 0 : latestPendingParentHeader.column) === column) { - latestPendingParentHeader.subHeaders.push(headerToGroup); - } else { - const header = createHeader(table, column, { - id: [headerFamily, depth, column.id, headerToGroup == null ? void 0 : headerToGroup.id].filter(Boolean).join("_"), - isPlaceholder, - placeholderId: isPlaceholder ? `${pendingParentHeaders.filter((d5) => d5.column === column).length}` : void 0, - depth, - index: pendingParentHeaders.length - }); - header.subHeaders.push(headerToGroup); - pendingParentHeaders.push(header); - } - headerGroup.headers.push(headerToGroup); - headerToGroup.headerGroup = headerGroup; - }); - headerGroups.push(headerGroup); - if (depth > 0) { - createHeaderGroup(pendingParentHeaders, depth - 1); + return Cn.createElement(SelectMultipleContext.Provider, { value: emptyContextValue }, props2.children); + } + return Cn.createElement(SelectMultipleProviderInternal, { initialProps: props2.initialProps, children: props2.children }); +} +function SelectMultipleProviderInternal(_a2) { + var initialProps = _a2.initialProps, children = _a2.children; + var selected = initialProps.selected, min3 = initialProps.min, max3 = initialProps.max; + var onDayClick = function(day, activeModifiers, e4) { + var _a3, _b2; + (_a3 = initialProps.onDayClick) === null || _a3 === void 0 ? void 0 : _a3.call(initialProps, day, activeModifiers, e4); + var isMinSelected = Boolean(activeModifiers.selected && min3 && (selected === null || selected === void 0 ? void 0 : selected.length) === min3); + if (isMinSelected) { + return; + } + var isMaxSelected = Boolean(!activeModifiers.selected && max3 && (selected === null || selected === void 0 ? void 0 : selected.length) === max3); + if (isMaxSelected) { + return; + } + var selectedDays = selected ? __spreadArray([], selected, true) : []; + if (activeModifiers.selected) { + var index = selectedDays.findIndex(function(selectedDay) { + return isSameDay(day, selectedDay); + }); + selectedDays.splice(index, 1); + } else { + selectedDays.push(day); } + (_b2 = initialProps.onSelect) === null || _b2 === void 0 ? void 0 : _b2.call(initialProps, selectedDays, day, activeModifiers, e4); }; - const bottomHeaders = columnsToGroup.map((column, index) => createHeader(table, column, { - depth: maxDepth, - index - })); - createHeaderGroup(bottomHeaders, maxDepth - 1); - headerGroups.reverse(); - const recurseHeadersForSpans = (headers) => { - const filteredHeaders = headers.filter((header) => header.column.getIsVisible()); - return filteredHeaders.map((header) => { - let colSpan = 0; - let rowSpan = 0; - let childRowSpans = [0]; - if (header.subHeaders && header.subHeaders.length) { - childRowSpans = []; - recurseHeadersForSpans(header.subHeaders).forEach((_ref) => { - let { - colSpan: childColSpan, - rowSpan: childRowSpan - } = _ref; - colSpan += childColSpan; - childRowSpans.push(childRowSpan); - }); - } else { - colSpan = 1; - } - const minChildRowSpan = Math.min(...childRowSpans); - rowSpan = rowSpan + minChildRowSpan; - header.colSpan = colSpan; - header.rowSpan = rowSpan; - return { - colSpan, - rowSpan - }; + var modifiers = { + disabled: [] + }; + if (selected) { + modifiers.disabled.push(function(day) { + var isMaxSelected = max3 && selected.length > max3 - 1; + var isSelected = selected.some(function(selectedDay) { + return isSameDay(selectedDay, day); + }); + return Boolean(isMaxSelected && !isSelected); }); + } + var contextValue = { + selected, + onDayClick, + modifiers }; - recurseHeadersForSpans((_headerGroups$0$heade = (_headerGroups$ = headerGroups[0]) == null ? void 0 : _headerGroups$.headers) != null ? _headerGroups$0$heade : []); - return headerGroups; + return Cn.createElement(SelectMultipleContext.Provider, { value: contextValue }, children); } -var defaultColumnSizing = { - size: 150, - minSize: 20, - maxSize: Number.MAX_SAFE_INTEGER -}; -var getDefaultColumnSizingInfoState = () => ({ - startOffset: null, - startSize: null, - deltaOffset: null, - deltaPercentage: null, - isResizingColumn: false, - columnSizingStart: [] -}); -var ColumnSizing = { - getDefaultColumnDef: () => { - return defaultColumnSizing; - }, - getInitialState: (state) => { - return { - columnSizing: {}, - columnSizingInfo: getDefaultColumnSizingInfoState(), - ...state - }; - }, - getDefaultOptions: (table) => { - return { - columnResizeMode: "onEnd", - onColumnSizingChange: makeStateUpdater("columnSizing", table), - onColumnSizingInfoChange: makeStateUpdater("columnSizingInfo", table) - }; - }, - createColumn: (column, table) => { - return { - getSize: () => { - var _column$columnDef$min, _ref, _column$columnDef$max; - const columnSize = table.getState().columnSizing[column.id]; - return Math.min(Math.max((_column$columnDef$min = column.columnDef.minSize) != null ? _column$columnDef$min : defaultColumnSizing.minSize, (_ref = columnSize != null ? columnSize : column.columnDef.size) != null ? _ref : defaultColumnSizing.size), (_column$columnDef$max = column.columnDef.maxSize) != null ? _column$columnDef$max : defaultColumnSizing.maxSize); - }, - getStart: (position) => { - const columns = !position ? table.getVisibleLeafColumns() : position === "left" ? table.getLeftVisibleLeafColumns() : table.getRightVisibleLeafColumns(); - const index = columns.findIndex((d5) => d5.id === column.id); - if (index > 0) { - const prevSiblingColumn = columns[index - 1]; - return prevSiblingColumn.getStart(position) + prevSiblingColumn.getSize(); - } - return 0; - }, - resetSize: () => { - table.setColumnSizing((_ref2) => { - let { - [column.id]: _9, - ...rest - } = _ref2; - return rest; - }); - }, - getCanResize: () => { - var _column$columnDef$ena, _table$options$enable; - return ((_column$columnDef$ena = column.columnDef.enableResizing) != null ? _column$columnDef$ena : true) && ((_table$options$enable = table.options.enableColumnResizing) != null ? _table$options$enable : true); - }, - getIsResizing: () => { - return table.getState().columnSizingInfo.isResizingColumn === column.id; +function useSelectMultiple() { + var context = q2(SelectMultipleContext); + if (!context) { + throw new Error("useSelectMultiple must be used within a SelectMultipleProvider"); + } + return context; +} +function addToRange(day, range) { + var _a2 = range || {}, from = _a2.from, to = _a2.to; + if (!from) { + return { from: day, to: void 0 }; + } + if (!to && isSameDay(from, day)) { + return { from, to: day }; + } + if (!to && isBefore(day, from)) { + return { from: day, to: from }; + } + if (!to) { + return { from, to: day }; + } + if (isSameDay(to, day) && isSameDay(from, day)) { + return void 0; + } + if (isSameDay(to, day)) { + return { from: to, to: void 0 }; + } + if (isSameDay(from, day)) { + return void 0; + } + if (isAfter2(from, day)) { + return { from: day, to }; + } + return { from, to: day }; +} +var SelectRangeContext = F(void 0); +function SelectRangeProvider(props2) { + if (!isDayPickerRange(props2.initialProps)) { + var emptyContextValue = { + selected: void 0, + modifiers: { + range_start: [], + range_end: [], + range_middle: [], + disabled: [] } }; - }, - createHeader: (header, table) => { - return { - getSize: () => { - let sum2 = 0; - const recurse = (header2) => { - if (header2.subHeaders.length) { - header2.subHeaders.forEach(recurse); - } else { - var _header$column$getSiz; - sum2 += (_header$column$getSiz = header2.column.getSize()) != null ? _header$column$getSiz : 0; - } - }; - recurse(header); - return sum2; - }, - getStart: () => { - if (header.index > 0) { - const prevSiblingHeader = header.headerGroup.headers[header.index - 1]; - return prevSiblingHeader.getStart() + prevSiblingHeader.getSize(); - } - return 0; - }, - getResizeHandler: () => { - const column = table.getColumn(header.column.id); - const canResize = column == null ? void 0 : column.getCanResize(); - return (e4) => { - if (!column || !canResize) { - return; - } - e4.persist == null ? void 0 : e4.persist(); - if (isTouchStartEvent(e4)) { - if (e4.touches && e4.touches.length > 1) { - return; - } - } - const startSize = header.getSize(); - const columnSizingStart = header ? header.getLeafHeaders().map((d5) => [d5.column.id, d5.column.getSize()]) : [[column.id, column.getSize()]]; - const clientX = isTouchStartEvent(e4) ? Math.round(e4.touches[0].clientX) : e4.clientX; - const newColumnSizing = {}; - const updateOffset = (eventType, clientXPos) => { - if (typeof clientXPos !== "number") { - return; - } - table.setColumnSizingInfo((old) => { - var _old$startOffset, _old$startSize; - const deltaOffset = clientXPos - ((_old$startOffset = old == null ? void 0 : old.startOffset) != null ? _old$startOffset : 0); - const deltaPercentage = Math.max(deltaOffset / ((_old$startSize = old == null ? void 0 : old.startSize) != null ? _old$startSize : 0), -0.999999); - old.columnSizingStart.forEach((_ref3) => { - let [columnId, headerSize] = _ref3; - newColumnSizing[columnId] = Math.round(Math.max(headerSize + headerSize * deltaPercentage, 0) * 100) / 100; - }); - return { - ...old, - deltaOffset, - deltaPercentage - }; - }); - if (table.options.columnResizeMode === "onChange" || eventType === "end") { - table.setColumnSizing((old) => ({ - ...old, - ...newColumnSizing - })); - } - }; - const onMove = (clientXPos) => updateOffset("move", clientXPos); - const onEnd = (clientXPos) => { - updateOffset("end", clientXPos); - table.setColumnSizingInfo((old) => ({ - ...old, - isResizingColumn: false, - startOffset: null, - startSize: null, - deltaOffset: null, - deltaPercentage: null, - columnSizingStart: [] - })); - }; - const mouseEvents = { - moveHandler: (e5) => onMove(e5.clientX), - upHandler: (e5) => { - document.removeEventListener("mousemove", mouseEvents.moveHandler); - document.removeEventListener("mouseup", mouseEvents.upHandler); - onEnd(e5.clientX); - } - }; - const touchEvents = { - moveHandler: (e5) => { - if (e5.cancelable) { - e5.preventDefault(); - e5.stopPropagation(); - } - onMove(e5.touches[0].clientX); - return false; - }, - upHandler: (e5) => { - var _e$touches$; - document.removeEventListener("touchmove", touchEvents.moveHandler); - document.removeEventListener("touchend", touchEvents.upHandler); - if (e5.cancelable) { - e5.preventDefault(); - e5.stopPropagation(); - } - onEnd((_e$touches$ = e5.touches[0]) == null ? void 0 : _e$touches$.clientX); - } - }; - const passiveIfSupported = passiveEventSupported() ? { - passive: false - } : false; - if (isTouchStartEvent(e4)) { - document.addEventListener("touchmove", touchEvents.moveHandler, passiveIfSupported); - document.addEventListener("touchend", touchEvents.upHandler, passiveIfSupported); - } else { - document.addEventListener("mousemove", mouseEvents.moveHandler, passiveIfSupported); - document.addEventListener("mouseup", mouseEvents.upHandler, passiveIfSupported); + return Cn.createElement(SelectRangeContext.Provider, { value: emptyContextValue }, props2.children); + } + return Cn.createElement(SelectRangeProviderInternal, { initialProps: props2.initialProps, children: props2.children }); +} +function SelectRangeProviderInternal(_a2) { + var initialProps = _a2.initialProps, children = _a2.children; + var selected = initialProps.selected; + var _b2 = selected || {}, selectedFrom = _b2.from, selectedTo = _b2.to; + var min3 = initialProps.min; + var max3 = initialProps.max; + var onDayClick = function(day, activeModifiers, e4) { + var _a3, _b3; + (_a3 = initialProps.onDayClick) === null || _a3 === void 0 ? void 0 : _a3.call(initialProps, day, activeModifiers, e4); + var newRange = addToRange(day, selected); + (_b3 = initialProps.onSelect) === null || _b3 === void 0 ? void 0 : _b3.call(initialProps, newRange, day, activeModifiers, e4); + }; + var modifiers = { + range_start: [], + range_end: [], + range_middle: [], + disabled: [] + }; + if (selectedFrom) { + modifiers.range_start = [selectedFrom]; + if (!selectedTo) { + modifiers.range_end = [selectedFrom]; + } else { + modifiers.range_end = [selectedTo]; + if (!isSameDay(selectedFrom, selectedTo)) { + modifiers.range_middle = [ + { + after: selectedFrom, + before: selectedTo } - table.setColumnSizingInfo((old) => ({ - ...old, - startOffset: clientX, - startSize, - deltaOffset: 0, - deltaPercentage: 0, - columnSizingStart, - isResizingColumn: column.id - })); - }; - } - }; - }, - createTable: (table) => { - return { - setColumnSizing: (updater) => table.options.onColumnSizingChange == null ? void 0 : table.options.onColumnSizingChange(updater), - setColumnSizingInfo: (updater) => table.options.onColumnSizingInfoChange == null ? void 0 : table.options.onColumnSizingInfoChange(updater), - resetColumnSizing: (defaultState) => { - var _table$initialState$c; - table.setColumnSizing(defaultState ? {} : (_table$initialState$c = table.initialState.columnSizing) != null ? _table$initialState$c : {}); - }, - resetHeaderSizeInfo: (defaultState) => { - var _table$initialState$c2; - table.setColumnSizingInfo(defaultState ? getDefaultColumnSizingInfoState() : (_table$initialState$c2 = table.initialState.columnSizingInfo) != null ? _table$initialState$c2 : getDefaultColumnSizingInfoState()); - }, - getTotalSize: () => { - var _table$getHeaderGroup, _table$getHeaderGroup2; - return (_table$getHeaderGroup = (_table$getHeaderGroup2 = table.getHeaderGroups()[0]) == null ? void 0 : _table$getHeaderGroup2.headers.reduce((sum2, header) => { - return sum2 + header.getSize(); - }, 0)) != null ? _table$getHeaderGroup : 0; - }, - getLeftTotalSize: () => { - var _table$getLeftHeaderG, _table$getLeftHeaderG2; - return (_table$getLeftHeaderG = (_table$getLeftHeaderG2 = table.getLeftHeaderGroups()[0]) == null ? void 0 : _table$getLeftHeaderG2.headers.reduce((sum2, header) => { - return sum2 + header.getSize(); - }, 0)) != null ? _table$getLeftHeaderG : 0; - }, - getCenterTotalSize: () => { - var _table$getCenterHeade, _table$getCenterHeade2; - return (_table$getCenterHeade = (_table$getCenterHeade2 = table.getCenterHeaderGroups()[0]) == null ? void 0 : _table$getCenterHeade2.headers.reduce((sum2, header) => { - return sum2 + header.getSize(); - }, 0)) != null ? _table$getCenterHeade : 0; - }, - getRightTotalSize: () => { - var _table$getRightHeader, _table$getRightHeader2; - return (_table$getRightHeader = (_table$getRightHeader2 = table.getRightHeaderGroups()[0]) == null ? void 0 : _table$getRightHeader2.headers.reduce((sum2, header) => { - return sum2 + header.getSize(); - }, 0)) != null ? _table$getRightHeader : 0; + ]; } - }; + } + } + if (min3) { + if (selectedFrom && !selectedTo) { + modifiers.disabled.push({ + after: subDays(selectedFrom, min3 - 1), + before: addDays(selectedFrom, min3 - 1) + }); + } + if (selectedFrom && selectedTo) { + modifiers.disabled.push({ + after: selectedFrom, + before: addDays(selectedFrom, min3 - 1) + }); + } + } + if (max3) { + if (selectedFrom && !selectedTo) { + modifiers.disabled.push({ + before: addDays(selectedFrom, -max3 + 1) + }); + modifiers.disabled.push({ + after: addDays(selectedFrom, max3 - 1) + }); + } + if (selectedFrom && selectedTo) { + var selectedCount = differenceInCalendarDays(selectedTo, selectedFrom) + 1; + var offset2 = max3 - selectedCount; + modifiers.disabled.push({ + before: subDays(selectedFrom, offset2) + }); + modifiers.disabled.push({ + after: addDays(selectedTo, offset2) + }); + } + } + return Cn.createElement(SelectRangeContext.Provider, { value: { selected, onDayClick, modifiers } }, children); +} +function useSelectRange() { + var context = q2(SelectRangeContext); + if (!context) { + throw new Error("useSelectRange must be used within a SelectRangeProvider"); + } + return context; +} +function matcherToArray(matcher) { + if (Array.isArray(matcher)) { + return __spreadArray([], matcher, true); + } else if (matcher !== void 0) { + return [matcher]; + } else { + return []; + } +} +function getCustomModifiers(dayModifiers) { + var customModifiers = {}; + Object.entries(dayModifiers).forEach(function(_a2) { + var modifier = _a2[0], matcher = _a2[1]; + customModifiers[modifier] = matcherToArray(matcher); + }); + return customModifiers; +} +var InternalModifier; +(function(InternalModifier2) { + InternalModifier2["Outside"] = "outside"; + InternalModifier2["Disabled"] = "disabled"; + InternalModifier2["Selected"] = "selected"; + InternalModifier2["Hidden"] = "hidden"; + InternalModifier2["Today"] = "today"; + InternalModifier2["RangeStart"] = "range_start"; + InternalModifier2["RangeEnd"] = "range_end"; + InternalModifier2["RangeMiddle"] = "range_middle"; +})(InternalModifier || (InternalModifier = {})); +var Selected = InternalModifier.Selected; +var Disabled = InternalModifier.Disabled; +var Hidden = InternalModifier.Hidden; +var Today = InternalModifier.Today; +var RangeEnd = InternalModifier.RangeEnd; +var RangeMiddle = InternalModifier.RangeMiddle; +var RangeStart = InternalModifier.RangeStart; +var Outside2 = InternalModifier.Outside; +function getInternalModifiers(dayPicker, selectMultiple, selectRange2) { + var _a2; + var internalModifiers = (_a2 = {}, _a2[Selected] = matcherToArray(dayPicker.selected), _a2[Disabled] = matcherToArray(dayPicker.disabled), _a2[Hidden] = matcherToArray(dayPicker.hidden), _a2[Today] = [dayPicker.today], _a2[RangeEnd] = [], _a2[RangeMiddle] = [], _a2[RangeStart] = [], _a2[Outside2] = [], _a2); + if (dayPicker.fromDate) { + internalModifiers[Disabled].push({ before: dayPicker.fromDate }); + } + if (dayPicker.toDate) { + internalModifiers[Disabled].push({ after: dayPicker.toDate }); + } + if (isDayPickerMultiple(dayPicker)) { + internalModifiers[Disabled] = internalModifiers[Disabled].concat(selectMultiple.modifiers[Disabled]); + } else if (isDayPickerRange(dayPicker)) { + internalModifiers[Disabled] = internalModifiers[Disabled].concat(selectRange2.modifiers[Disabled]); + internalModifiers[RangeStart] = selectRange2.modifiers[RangeStart]; + internalModifiers[RangeMiddle] = selectRange2.modifiers[RangeMiddle]; + internalModifiers[RangeEnd] = selectRange2.modifiers[RangeEnd]; + } + return internalModifiers; +} +var ModifiersContext = F(void 0); +function ModifiersProvider(props2) { + var dayPicker = useDayPicker(); + var selectMultiple = useSelectMultiple(); + var selectRange2 = useSelectRange(); + var internalModifiers = getInternalModifiers(dayPicker, selectMultiple, selectRange2); + var customModifiers = getCustomModifiers(dayPicker.modifiers); + var modifiers = __assign(__assign({}, internalModifiers), customModifiers); + return Cn.createElement(ModifiersContext.Provider, { value: modifiers }, props2.children); +} +function useModifiers() { + var context = q2(ModifiersContext); + if (!context) { + throw new Error("useModifiers must be used within a ModifiersProvider"); + } + return context; +} +function isDateInterval(matcher) { + return Boolean(matcher && typeof matcher === "object" && "before" in matcher && "after" in matcher); +} +function isDateRange(value) { + return Boolean(value && typeof value === "object" && "from" in value); +} +function isDateAfterType(value) { + return Boolean(value && typeof value === "object" && "after" in value); +} +function isDateBeforeType(value) { + return Boolean(value && typeof value === "object" && "before" in value); +} +function isDayOfWeekType(value) { + return Boolean(value && typeof value === "object" && "dayOfWeek" in value); +} +function isDateInRange(date, range) { + var _a2; + var from = range.from, to = range.to; + if (!from) { + return false; + } + if (!to && isSameDay(from, date)) { + return true; } -}; -var passiveSupported = null; -function passiveEventSupported() { - if (typeof passiveSupported === "boolean") - return passiveSupported; - let supported = false; - try { - const options = { - get passive() { - supported = true; - return false; - } - }; - const noop2 = () => { - }; - window.addEventListener("test", noop2, options); - window.removeEventListener("test", noop2); - } catch (err) { - supported = false; + if (!to) { + return false; } - passiveSupported = supported; - return passiveSupported; + var isRangeInverted = differenceInCalendarDays(to, from) < 0; + if (isRangeInverted) { + _a2 = [to, from], from = _a2[0], to = _a2[1]; + } + var isInRange = differenceInCalendarDays(date, from) >= 0 && differenceInCalendarDays(to, date) >= 0; + return isInRange; } -function isTouchStartEvent(e4) { - return e4.type === "touchstart"; +function isDateType(value) { + return isDate(value); } -var Expanding = { - getInitialState: (state) => { - return { - expanded: {}, - ...state - }; - }, - getDefaultOptions: (table) => { - return { - onExpandedChange: makeStateUpdater("expanded", table), - paginateExpandedRows: true - }; - }, - createTable: (table) => { - let registered = false; - let queued = false; - return { - _autoResetExpanded: () => { - var _ref, _table$options$autoRe; - if (!registered) { - table._queue(() => { - registered = true; - }); - return; - } - if ((_ref = (_table$options$autoRe = table.options.autoResetAll) != null ? _table$options$autoRe : table.options.autoResetExpanded) != null ? _ref : !table.options.manualExpanding) { - if (queued) - return; - queued = true; - table._queue(() => { - table.resetExpanded(); - queued = false; - }); - } - }, - setExpanded: (updater) => table.options.onExpandedChange == null ? void 0 : table.options.onExpandedChange(updater), - toggleAllRowsExpanded: (expanded) => { - if (expanded != null ? expanded : !table.getIsAllRowsExpanded()) { - table.setExpanded(true); - } else { - table.setExpanded({}); - } - }, - resetExpanded: (defaultState) => { - var _table$initialState$e, _table$initialState; - table.setExpanded(defaultState ? {} : (_table$initialState$e = (_table$initialState = table.initialState) == null ? void 0 : _table$initialState.expanded) != null ? _table$initialState$e : {}); - }, - getCanSomeRowsExpand: () => { - return table.getRowModel().flatRows.some((row) => row.getCanExpand()); - }, - getToggleAllRowsExpandedHandler: () => { - return (e4) => { - e4.persist == null ? void 0 : e4.persist(); - table.toggleAllRowsExpanded(); - }; - }, - getIsSomeRowsExpanded: () => { - const expanded = table.getState().expanded; - return expanded === true || Object.values(expanded).some(Boolean); - }, - getIsAllRowsExpanded: () => { - const expanded = table.getState().expanded; - if (typeof expanded === "boolean") { - return expanded === true; - } - if (!Object.keys(expanded).length) { - return false; - } - if (table.getRowModel().flatRows.some((row) => !row.getIsExpanded())) { - return false; - } - return true; - }, - getExpandedDepth: () => { - let maxDepth = 0; - const rowIds = table.getState().expanded === true ? Object.keys(table.getRowModel().rowsById) : Object.keys(table.getState().expanded); - rowIds.forEach((id2) => { - const splitId = id2.split("."); - maxDepth = Math.max(maxDepth, splitId.length); - }); - return maxDepth; - }, - getPreExpandedRowModel: () => table.getSortedRowModel(), - getExpandedRowModel: () => { - if (!table._getExpandedRowModel && table.options.getExpandedRowModel) { - table._getExpandedRowModel = table.options.getExpandedRowModel(table); - } - if (table.options.manualExpanding || !table._getExpandedRowModel) { - return table.getPreExpandedRowModel(); - } - return table._getExpandedRowModel(); +function isArrayOfDates(value) { + return Array.isArray(value) && value.every(isDate); +} +function isMatch(day, matchers) { + return matchers.some(function(matcher) { + if (typeof matcher === "boolean") { + return matcher; + } + if (isDateType(matcher)) { + return isSameDay(day, matcher); + } + if (isArrayOfDates(matcher)) { + return matcher.includes(day); + } + if (isDateRange(matcher)) { + return isDateInRange(day, matcher); + } + if (isDayOfWeekType(matcher)) { + return matcher.dayOfWeek.includes(day.getDay()); + } + if (isDateInterval(matcher)) { + var diffBefore = differenceInCalendarDays(matcher.before, day); + var diffAfter = differenceInCalendarDays(matcher.after, day); + var isDayBefore = diffBefore > 0; + var isDayAfter = diffAfter < 0; + var isClosedInterval = isAfter2(matcher.before, matcher.after); + if (isClosedInterval) { + return isDayAfter && isDayBefore; + } else { + return isDayBefore || isDayAfter; } + } + if (isDateAfterType(matcher)) { + return differenceInCalendarDays(day, matcher.after) > 0; + } + if (isDateBeforeType(matcher)) { + return differenceInCalendarDays(matcher.before, day) > 0; + } + if (typeof matcher === "function") { + return matcher(day); + } + return false; + }); +} +function getActiveModifiers(day, modifiers, displayMonth) { + var matchedModifiers = Object.keys(modifiers).reduce(function(result, key2) { + var modifier = modifiers[key2]; + if (isMatch(day, modifier)) { + result.push(key2); + } + return result; + }, []); + var activeModifiers = {}; + matchedModifiers.forEach(function(modifier) { + return activeModifiers[modifier] = true; + }); + if (displayMonth && !isSameMonth(day, displayMonth)) { + activeModifiers.outside = true; + } + return activeModifiers; +} +function getInitialFocusTarget(displayMonths, modifiers) { + var firstDayInMonth = startOfMonth(displayMonths[0]); + var lastDayInMonth = endOfMonth(displayMonths[displayMonths.length - 1]); + var firstFocusableDay; + var today; + var date = firstDayInMonth; + while (date <= lastDayInMonth) { + var activeModifiers = getActiveModifiers(date, modifiers); + var isFocusable = !activeModifiers.disabled && !activeModifiers.hidden; + if (!isFocusable) { + date = addDays(date, 1); + continue; + } + if (activeModifiers.selected) { + return date; + } + if (activeModifiers.today && !today) { + today = date; + } + if (!firstFocusableDay) { + firstFocusableDay = date; + } + date = addDays(date, 1); + } + if (today) { + return today; + } else { + return firstFocusableDay; + } +} +var MAX_RETRY = 365; +function getNextFocus(focusedDay, options) { + var moveBy = options.moveBy, direction = options.direction, context = options.context, modifiers = options.modifiers, _a2 = options.retry, retry = _a2 === void 0 ? { count: 0, lastFocused: focusedDay } : _a2; + var weekStartsOn = context.weekStartsOn, fromDate = context.fromDate, toDate2 = context.toDate, locale2 = context.locale; + var moveFns = { + day: addDays, + week: addWeeks, + month: addMonths, + year: addYears, + startOfWeek: function(date) { + return context.ISOWeek ? startOfISOWeek(date) : startOfWeek(date, { locale: locale2, weekStartsOn }); + }, + endOfWeek: function(date) { + return context.ISOWeek ? endOfISOWeek(date) : endOfWeek(date, { locale: locale2, weekStartsOn }); + } + }; + var newFocusedDay = moveFns[moveBy](focusedDay, direction === "after" ? 1 : -1); + if (direction === "before" && fromDate) { + newFocusedDay = max([fromDate, newFocusedDay]); + } else if (direction === "after" && toDate2) { + newFocusedDay = min([toDate2, newFocusedDay]); + } + var isFocusable = true; + if (modifiers) { + var activeModifiers = getActiveModifiers(newFocusedDay, modifiers); + isFocusable = !activeModifiers.disabled && !activeModifiers.hidden; + } + if (isFocusable) { + return newFocusedDay; + } else { + if (retry.count > MAX_RETRY) { + return retry.lastFocused; + } + return getNextFocus(newFocusedDay, { + moveBy, + direction, + context, + modifiers, + retry: __assign(__assign({}, retry), { count: retry.count + 1 }) + }); + } +} +var FocusContext = F(void 0); +function FocusProvider(props2) { + var navigation = useNavigation(); + var modifiers = useModifiers(); + var _a2 = h2(), focusedDay = _a2[0], setFocusedDay = _a2[1]; + var _b2 = h2(), lastFocused = _b2[0], setLastFocused = _b2[1]; + var initialFocusTarget = getInitialFocusTarget(navigation.displayMonths, modifiers); + var focusTarget = (focusedDay !== null && focusedDay !== void 0 ? focusedDay : lastFocused && navigation.isDateDisplayed(lastFocused)) ? lastFocused : initialFocusTarget; + var blur = function() { + setLastFocused(focusedDay); + setFocusedDay(void 0); + }; + var focus = function(date) { + setFocusedDay(date); + }; + var context = useDayPicker(); + var moveFocus = function(moveBy, direction) { + if (!focusedDay) + return; + var nextFocused = getNextFocus(focusedDay, { + moveBy, + direction, + context, + modifiers + }); + if (isSameDay(focusedDay, nextFocused)) + return void 0; + navigation.goToDate(nextFocused, focusedDay); + focus(nextFocused); + }; + var value = { + focusedDay, + focusTarget, + blur, + focus, + focusDayAfter: function() { + return moveFocus("day", "after"); + }, + focusDayBefore: function() { + return moveFocus("day", "before"); + }, + focusWeekAfter: function() { + return moveFocus("week", "after"); + }, + focusWeekBefore: function() { + return moveFocus("week", "before"); + }, + focusMonthBefore: function() { + return moveFocus("month", "before"); + }, + focusMonthAfter: function() { + return moveFocus("month", "after"); + }, + focusYearBefore: function() { + return moveFocus("year", "before"); + }, + focusYearAfter: function() { + return moveFocus("year", "after"); + }, + focusStartOfWeek: function() { + return moveFocus("startOfWeek", "before"); + }, + focusEndOfWeek: function() { + return moveFocus("endOfWeek", "after"); + } + }; + return Cn.createElement(FocusContext.Provider, { value }, props2.children); +} +function useFocusContext() { + var context = q2(FocusContext); + if (!context) { + throw new Error("useFocusContext must be used within a FocusProvider"); + } + return context; +} +function useActiveModifiers(day, displayMonth) { + var modifiers = useModifiers(); + var activeModifiers = getActiveModifiers(day, modifiers, displayMonth); + return activeModifiers; +} +var SelectSingleContext = F(void 0); +function SelectSingleProvider(props2) { + if (!isDayPickerSingle(props2.initialProps)) { + var emptyContextValue = { + selected: void 0 }; - }, - createRow: (row, table) => { - return { - toggleExpanded: (expanded) => { - table.setExpanded((old) => { - var _expanded; - const exists = old === true ? true : !!(old != null && old[row.id]); - let oldExpanded = {}; - if (old === true) { - Object.keys(table.getRowModel().rowsById).forEach((rowId) => { - oldExpanded[rowId] = true; - }); - } else { - oldExpanded = old; - } - expanded = (_expanded = expanded) != null ? _expanded : !exists; - if (!exists && expanded) { - return { - ...oldExpanded, - [row.id]: true - }; - } - if (exists && !expanded) { - const { - [row.id]: _9, - ...rest - } = oldExpanded; - return rest; - } - return old; - }); - }, - getIsExpanded: () => { - var _table$options$getIsR; - const expanded = table.getState().expanded; - return !!((_table$options$getIsR = table.options.getIsRowExpanded == null ? void 0 : table.options.getIsRowExpanded(row)) != null ? _table$options$getIsR : expanded === true || (expanded == null ? void 0 : expanded[row.id])); - }, - getCanExpand: () => { - var _table$options$getRow, _table$options$enable, _row$subRows; - return (_table$options$getRow = table.options.getRowCanExpand == null ? void 0 : table.options.getRowCanExpand(row)) != null ? _table$options$getRow : ((_table$options$enable = table.options.enableExpanding) != null ? _table$options$enable : true) && !!((_row$subRows = row.subRows) != null && _row$subRows.length); - }, - getToggleExpandedHandler: () => { - const canExpand = row.getCanExpand(); - return () => { - if (!canExpand) - return; - row.toggleExpanded(); - }; + return Cn.createElement(SelectSingleContext.Provider, { value: emptyContextValue }, props2.children); + } + return Cn.createElement(SelectSingleProviderInternal, { initialProps: props2.initialProps, children: props2.children }); +} +function SelectSingleProviderInternal(_a2) { + var initialProps = _a2.initialProps, children = _a2.children; + var onDayClick = function(day, activeModifiers, e4) { + var _a3, _b2, _c2; + (_a3 = initialProps.onDayClick) === null || _a3 === void 0 ? void 0 : _a3.call(initialProps, day, activeModifiers, e4); + if (activeModifiers.selected && !initialProps.required) { + (_b2 = initialProps.onSelect) === null || _b2 === void 0 ? void 0 : _b2.call(initialProps, void 0, day, activeModifiers, e4); + return; + } + (_c2 = initialProps.onSelect) === null || _c2 === void 0 ? void 0 : _c2.call(initialProps, day, day, activeModifiers, e4); + }; + var contextValue = { + selected: initialProps.selected, + onDayClick + }; + return Cn.createElement(SelectSingleContext.Provider, { value: contextValue }, children); +} +function useSelectSingle() { + var context = q2(SelectSingleContext); + if (!context) { + throw new Error("useSelectSingle must be used within a SelectSingleProvider"); + } + return context; +} +function useDayEventHandlers(date, activeModifiers) { + var dayPicker = useDayPicker(); + var single = useSelectSingle(); + var multiple = useSelectMultiple(); + var range = useSelectRange(); + var _a2 = useFocusContext(), focusDayAfter = _a2.focusDayAfter, focusDayBefore = _a2.focusDayBefore, focusWeekAfter = _a2.focusWeekAfter, focusWeekBefore = _a2.focusWeekBefore, blur = _a2.blur, focus = _a2.focus, focusMonthBefore = _a2.focusMonthBefore, focusMonthAfter = _a2.focusMonthAfter, focusYearBefore = _a2.focusYearBefore, focusYearAfter = _a2.focusYearAfter, focusStartOfWeek = _a2.focusStartOfWeek, focusEndOfWeek = _a2.focusEndOfWeek; + var onClick = function(e4) { + var _a3, _b2, _c2, _d2; + if (isDayPickerSingle(dayPicker)) { + (_a3 = single.onDayClick) === null || _a3 === void 0 ? void 0 : _a3.call(single, date, activeModifiers, e4); + } else if (isDayPickerMultiple(dayPicker)) { + (_b2 = multiple.onDayClick) === null || _b2 === void 0 ? void 0 : _b2.call(multiple, date, activeModifiers, e4); + } else if (isDayPickerRange(dayPicker)) { + (_c2 = range.onDayClick) === null || _c2 === void 0 ? void 0 : _c2.call(range, date, activeModifiers, e4); + } else { + (_d2 = dayPicker.onDayClick) === null || _d2 === void 0 ? void 0 : _d2.call(dayPicker, date, activeModifiers, e4); + } + }; + var onFocus = function(e4) { + var _a3; + focus(date); + (_a3 = dayPicker.onDayFocus) === null || _a3 === void 0 ? void 0 : _a3.call(dayPicker, date, activeModifiers, e4); + }; + var onBlur = function(e4) { + var _a3; + blur(); + (_a3 = dayPicker.onDayBlur) === null || _a3 === void 0 ? void 0 : _a3.call(dayPicker, date, activeModifiers, e4); + }; + var onMouseEnter = function(e4) { + var _a3; + (_a3 = dayPicker.onDayMouseEnter) === null || _a3 === void 0 ? void 0 : _a3.call(dayPicker, date, activeModifiers, e4); + }; + var onMouseLeave = function(e4) { + var _a3; + (_a3 = dayPicker.onDayMouseLeave) === null || _a3 === void 0 ? void 0 : _a3.call(dayPicker, date, activeModifiers, e4); + }; + var onPointerEnter = function(e4) { + var _a3; + (_a3 = dayPicker.onDayPointerEnter) === null || _a3 === void 0 ? void 0 : _a3.call(dayPicker, date, activeModifiers, e4); + }; + var onPointerLeave = function(e4) { + var _a3; + (_a3 = dayPicker.onDayPointerLeave) === null || _a3 === void 0 ? void 0 : _a3.call(dayPicker, date, activeModifiers, e4); + }; + var onTouchCancel = function(e4) { + var _a3; + (_a3 = dayPicker.onDayTouchCancel) === null || _a3 === void 0 ? void 0 : _a3.call(dayPicker, date, activeModifiers, e4); + }; + var onTouchEnd = function(e4) { + var _a3; + (_a3 = dayPicker.onDayTouchEnd) === null || _a3 === void 0 ? void 0 : _a3.call(dayPicker, date, activeModifiers, e4); + }; + var onTouchMove = function(e4) { + var _a3; + (_a3 = dayPicker.onDayTouchMove) === null || _a3 === void 0 ? void 0 : _a3.call(dayPicker, date, activeModifiers, e4); + }; + var onTouchStart = function(e4) { + var _a3; + (_a3 = dayPicker.onDayTouchStart) === null || _a3 === void 0 ? void 0 : _a3.call(dayPicker, date, activeModifiers, e4); + }; + var onKeyUp = function(e4) { + var _a3; + (_a3 = dayPicker.onDayKeyUp) === null || _a3 === void 0 ? void 0 : _a3.call(dayPicker, date, activeModifiers, e4); + }; + var onKeyDown = function(e4) { + var _a3; + switch (e4.key) { + case "ArrowLeft": + e4.preventDefault(); + e4.stopPropagation(); + dayPicker.dir === "rtl" ? focusDayAfter() : focusDayBefore(); + break; + case "ArrowRight": + e4.preventDefault(); + e4.stopPropagation(); + dayPicker.dir === "rtl" ? focusDayBefore() : focusDayAfter(); + break; + case "ArrowDown": + e4.preventDefault(); + e4.stopPropagation(); + focusWeekAfter(); + break; + case "ArrowUp": + e4.preventDefault(); + e4.stopPropagation(); + focusWeekBefore(); + break; + case "PageUp": + e4.preventDefault(); + e4.stopPropagation(); + e4.shiftKey ? focusYearBefore() : focusMonthBefore(); + break; + case "PageDown": + e4.preventDefault(); + e4.stopPropagation(); + e4.shiftKey ? focusYearAfter() : focusMonthAfter(); + break; + case "Home": + e4.preventDefault(); + e4.stopPropagation(); + focusStartOfWeek(); + break; + case "End": + e4.preventDefault(); + e4.stopPropagation(); + focusEndOfWeek(); + break; + } + (_a3 = dayPicker.onDayKeyDown) === null || _a3 === void 0 ? void 0 : _a3.call(dayPicker, date, activeModifiers, e4); + }; + var eventHandlers = { + onClick, + onFocus, + onBlur, + onKeyDown, + onKeyUp, + onMouseEnter, + onMouseLeave, + onPointerEnter, + onPointerLeave, + onTouchCancel, + onTouchEnd, + onTouchMove, + onTouchStart + }; + return eventHandlers; +} +function useSelectedDays() { + var dayPicker = useDayPicker(); + var single = useSelectSingle(); + var multiple = useSelectMultiple(); + var range = useSelectRange(); + var selectedDays = isDayPickerSingle(dayPicker) ? single.selected : isDayPickerMultiple(dayPicker) ? multiple.selected : isDayPickerRange(dayPicker) ? range.selected : void 0; + return selectedDays; +} +function isInternalModifier(modifier) { + return Object.values(InternalModifier).includes(modifier); +} +function getDayClassNames(dayPicker, activeModifiers) { + var classNames9 = [dayPicker.classNames.day]; + Object.keys(activeModifiers).forEach(function(modifier) { + var customClassName = dayPicker.modifiersClassNames[modifier]; + if (customClassName) { + classNames9.push(customClassName); + } else if (isInternalModifier(modifier)) { + var internalClassName = dayPicker.classNames["day_".concat(modifier)]; + if (internalClassName) { + classNames9.push(internalClassName); } - }; - } -}; -var includesString = (row, columnId, filterValue) => { - var _row$getValue; - const search = filterValue.toLowerCase(); - return Boolean((_row$getValue = row.getValue(columnId)) == null ? void 0 : _row$getValue.toLowerCase().includes(search)); -}; -includesString.autoRemove = (val) => testFalsey(val); -var includesStringSensitive = (row, columnId, filterValue) => { - var _row$getValue2; - return Boolean((_row$getValue2 = row.getValue(columnId)) == null ? void 0 : _row$getValue2.includes(filterValue)); -}; -includesStringSensitive.autoRemove = (val) => testFalsey(val); -var equalsString = (row, columnId, filterValue) => { - var _row$getValue3; - return ((_row$getValue3 = row.getValue(columnId)) == null ? void 0 : _row$getValue3.toLowerCase()) === filterValue.toLowerCase(); -}; -equalsString.autoRemove = (val) => testFalsey(val); -var arrIncludes = (row, columnId, filterValue) => { - var _row$getValue4; - return (_row$getValue4 = row.getValue(columnId)) == null ? void 0 : _row$getValue4.includes(filterValue); -}; -arrIncludes.autoRemove = (val) => testFalsey(val) || !(val != null && val.length); -var arrIncludesAll = (row, columnId, filterValue) => { - return !filterValue.some((val) => { - var _row$getValue5; - return !((_row$getValue5 = row.getValue(columnId)) != null && _row$getValue5.includes(val)); + } }); -}; -arrIncludesAll.autoRemove = (val) => testFalsey(val) || !(val != null && val.length); -var arrIncludesSome = (row, columnId, filterValue) => { - return filterValue.some((val) => { - var _row$getValue6; - return (_row$getValue6 = row.getValue(columnId)) == null ? void 0 : _row$getValue6.includes(val); + return classNames9; +} +function getDayStyle(dayPicker, activeModifiers) { + var style = __assign({}, dayPicker.styles.day); + Object.keys(activeModifiers).forEach(function(modifier) { + var _a2; + style = __assign(__assign({}, style), (_a2 = dayPicker.modifiersStyles) === null || _a2 === void 0 ? void 0 : _a2[modifier]); }); -}; -arrIncludesSome.autoRemove = (val) => testFalsey(val) || !(val != null && val.length); -var equals = (row, columnId, filterValue) => { - return row.getValue(columnId) === filterValue; -}; -equals.autoRemove = (val) => testFalsey(val); -var weakEquals = (row, columnId, filterValue) => { - return row.getValue(columnId) == filterValue; -}; -weakEquals.autoRemove = (val) => testFalsey(val); -var inNumberRange = (row, columnId, filterValue) => { - let [min3, max3] = filterValue; - const rowValue = row.getValue(columnId); - return rowValue >= min3 && rowValue <= max3; -}; -inNumberRange.resolveFilterValue = (val) => { - let [unsafeMin, unsafeMax] = val; - let parsedMin = typeof unsafeMin !== "number" ? parseFloat(unsafeMin) : unsafeMin; - let parsedMax = typeof unsafeMax !== "number" ? parseFloat(unsafeMax) : unsafeMax; - let min3 = unsafeMin === null || Number.isNaN(parsedMin) ? -Infinity : parsedMin; - let max3 = unsafeMax === null || Number.isNaN(parsedMax) ? Infinity : parsedMax; - if (min3 > max3) { - const temp = min3; - min3 = max3; - max3 = temp; + return style; +} +function useDayRender(day, displayMonth, buttonRef) { + var _a2; + var _b2, _c2; + var dayPicker = useDayPicker(); + var focusContext = useFocusContext(); + var activeModifiers = useActiveModifiers(day, displayMonth); + var eventHandlers = useDayEventHandlers(day, activeModifiers); + var selectedDays = useSelectedDays(); + var isButton = Boolean(dayPicker.onDayClick || dayPicker.mode !== "default"); + p2(function() { + var _a3; + if (activeModifiers.outside) + return; + if (!focusContext.focusedDay) + return; + if (!isButton) + return; + if (isSameDay(focusContext.focusedDay, day)) { + (_a3 = buttonRef.current) === null || _a3 === void 0 ? void 0 : _a3.focus(); + } + }, [ + focusContext.focusedDay, + day, + buttonRef, + isButton, + activeModifiers.outside + ]); + var className = getDayClassNames(dayPicker, activeModifiers).join(" "); + var style = getDayStyle(dayPicker, activeModifiers); + var isHidden = Boolean(activeModifiers.outside && !dayPicker.showOutsideDays || activeModifiers.hidden); + var DayContentComponent = (_c2 = (_b2 = dayPicker.components) === null || _b2 === void 0 ? void 0 : _b2.DayContent) !== null && _c2 !== void 0 ? _c2 : DayContent; + var children = Cn.createElement(DayContentComponent, { date: day, displayMonth, activeModifiers }); + var divProps = { + style, + className, + children, + role: "gridcell" + }; + var isFocusTarget = focusContext.focusTarget && isSameDay(focusContext.focusTarget, day) && !activeModifiers.outside; + var isFocused = focusContext.focusedDay && isSameDay(focusContext.focusedDay, day); + var buttonProps = __assign(__assign(__assign({}, divProps), (_a2 = { disabled: activeModifiers.disabled, role: "gridcell" }, _a2["aria-selected"] = activeModifiers.selected, _a2.tabIndex = isFocused || isFocusTarget ? 0 : -1, _a2)), eventHandlers); + var dayRender = { + isButton, + isHidden, + activeModifiers, + selectedDays, + buttonProps, + divProps + }; + return dayRender; +} +function Day(props2) { + var buttonRef = _2(null); + var dayRender = useDayRender(props2.date, props2.displayMonth, buttonRef); + if (dayRender.isHidden) { + return Cn.createElement("div", { role: "gridcell" }); } - return [min3, max3]; -}; -inNumberRange.autoRemove = (val) => testFalsey(val) || testFalsey(val[0]) && testFalsey(val[1]); -var filterFns = { - includesString, - includesStringSensitive, - equalsString, - arrIncludes, - arrIncludesAll, - arrIncludesSome, - equals, - weakEquals, - inNumberRange -}; -function testFalsey(val) { - return val === void 0 || val === null || val === ""; + if (!dayRender.isButton) { + return Cn.createElement("div", __assign({}, dayRender.divProps)); + } + return Cn.createElement(Button, __assign({ name: "day", ref: buttonRef }, dayRender.buttonProps)); } -var Filters = { - getDefaultColumnDef: () => { - return { - filterFn: "auto" - }; - }, - getInitialState: (state) => { - return { - columnFilters: [], - globalFilter: void 0, - ...state - }; - }, - getDefaultOptions: (table) => { - return { - onColumnFiltersChange: makeStateUpdater("columnFilters", table), - onGlobalFilterChange: makeStateUpdater("globalFilter", table), - filterFromLeafRows: false, - maxLeafRowFilterDepth: 100, - globalFilterFn: "auto", - getColumnCanGlobalFilter: (column) => { - var _table$getCoreRowMode, _table$getCoreRowMode2; - const value = (_table$getCoreRowMode = table.getCoreRowModel().flatRows[0]) == null ? void 0 : (_table$getCoreRowMode2 = _table$getCoreRowMode._getAllCellsByColumnId()[column.id]) == null ? void 0 : _table$getCoreRowMode2.getValue(); - return typeof value === "string" || typeof value === "number"; - } - }; - }, - createColumn: (column, table) => { - return { - getAutoFilterFn: () => { - const firstRow = table.getCoreRowModel().flatRows[0]; - const value = firstRow == null ? void 0 : firstRow.getValue(column.id); - if (typeof value === "string") { - return filterFns.includesString; - } - if (typeof value === "number") { - return filterFns.inNumberRange; - } - if (typeof value === "boolean") { - return filterFns.equals; - } - if (value !== null && typeof value === "object") { - return filterFns.equals; - } - if (Array.isArray(value)) { - return filterFns.arrIncludes; - } - return filterFns.weakEquals; - }, - getFilterFn: () => { - var _table$options$filter, _table$options$filter2; - return isFunction(column.columnDef.filterFn) ? column.columnDef.filterFn : column.columnDef.filterFn === "auto" ? column.getAutoFilterFn() : (_table$options$filter = (_table$options$filter2 = table.options.filterFns) == null ? void 0 : _table$options$filter2[column.columnDef.filterFn]) != null ? _table$options$filter : filterFns[column.columnDef.filterFn]; - }, - getCanFilter: () => { - var _column$columnDef$ena, _table$options$enable, _table$options$enable2; - return ((_column$columnDef$ena = column.columnDef.enableColumnFilter) != null ? _column$columnDef$ena : true) && ((_table$options$enable = table.options.enableColumnFilters) != null ? _table$options$enable : true) && ((_table$options$enable2 = table.options.enableFilters) != null ? _table$options$enable2 : true) && !!column.accessorFn; - }, - getCanGlobalFilter: () => { - var _column$columnDef$ena2, _table$options$enable3, _table$options$enable4, _table$options$getCol; - return ((_column$columnDef$ena2 = column.columnDef.enableGlobalFilter) != null ? _column$columnDef$ena2 : true) && ((_table$options$enable3 = table.options.enableGlobalFilter) != null ? _table$options$enable3 : true) && ((_table$options$enable4 = table.options.enableFilters) != null ? _table$options$enable4 : true) && ((_table$options$getCol = table.options.getColumnCanGlobalFilter == null ? void 0 : table.options.getColumnCanGlobalFilter(column)) != null ? _table$options$getCol : true) && !!column.accessorFn; - }, - getIsFiltered: () => column.getFilterIndex() > -1, - getFilterValue: () => { - var _table$getState$colum, _table$getState$colum2; - return (_table$getState$colum = table.getState().columnFilters) == null ? void 0 : (_table$getState$colum2 = _table$getState$colum.find((d5) => d5.id === column.id)) == null ? void 0 : _table$getState$colum2.value; - }, - getFilterIndex: () => { - var _table$getState$colum3, _table$getState$colum4; - return (_table$getState$colum3 = (_table$getState$colum4 = table.getState().columnFilters) == null ? void 0 : _table$getState$colum4.findIndex((d5) => d5.id === column.id)) != null ? _table$getState$colum3 : -1; - }, - setFilterValue: (value) => { - table.setColumnFilters((old) => { - const filterFn = column.getFilterFn(); - const previousfilter = old == null ? void 0 : old.find((d5) => d5.id === column.id); - const newFilter = functionalUpdate(value, previousfilter ? previousfilter.value : void 0); - if (shouldAutoRemoveFilter(filterFn, newFilter, column)) { - var _old$filter; - return (_old$filter = old == null ? void 0 : old.filter((d5) => d5.id !== column.id)) != null ? _old$filter : []; - } - const newFilterObj = { - id: column.id, - value: newFilter - }; - if (previousfilter) { - var _old$map; - return (_old$map = old == null ? void 0 : old.map((d5) => { - if (d5.id === column.id) { - return newFilterObj; - } - return d5; - })) != null ? _old$map : []; - } - if (old != null && old.length) { - return [...old, newFilterObj]; - } - return [newFilterObj]; - }); - }, - _getFacetedRowModel: table.options.getFacetedRowModel && table.options.getFacetedRowModel(table, column.id), - getFacetedRowModel: () => { - if (!column._getFacetedRowModel) { - return table.getPreFilteredRowModel(); - } - return column._getFacetedRowModel(); - }, - _getFacetedUniqueValues: table.options.getFacetedUniqueValues && table.options.getFacetedUniqueValues(table, column.id), - getFacetedUniqueValues: () => { - if (!column._getFacetedUniqueValues) { - return /* @__PURE__ */ new Map(); - } - return column._getFacetedUniqueValues(); - }, - _getFacetedMinMaxValues: table.options.getFacetedMinMaxValues && table.options.getFacetedMinMaxValues(table, column.id), - getFacetedMinMaxValues: () => { - if (!column._getFacetedMinMaxValues) { - return void 0; - } - return column._getFacetedMinMaxValues(); - } - }; - }, - createRow: (row, table) => { - return { - columnFilters: {}, - columnFiltersMeta: {} - }; - }, - createTable: (table) => { - return { - getGlobalAutoFilterFn: () => { - return filterFns.includesString; - }, - getGlobalFilterFn: () => { - var _table$options$filter3, _table$options$filter4; - const { - globalFilterFn - } = table.options; - return isFunction(globalFilterFn) ? globalFilterFn : globalFilterFn === "auto" ? table.getGlobalAutoFilterFn() : (_table$options$filter3 = (_table$options$filter4 = table.options.filterFns) == null ? void 0 : _table$options$filter4[globalFilterFn]) != null ? _table$options$filter3 : filterFns[globalFilterFn]; - }, - setColumnFilters: (updater) => { - const leafColumns = table.getAllLeafColumns(); - const updateFn = (old) => { - var _functionalUpdate; - return (_functionalUpdate = functionalUpdate(updater, old)) == null ? void 0 : _functionalUpdate.filter((filter) => { - const column = leafColumns.find((d5) => d5.id === filter.id); - if (column) { - const filterFn = column.getFilterFn(); - if (shouldAutoRemoveFilter(filterFn, filter.value, column)) { - return false; - } - } - return true; - }); - }; - table.options.onColumnFiltersChange == null ? void 0 : table.options.onColumnFiltersChange(updateFn); - }, - setGlobalFilter: (updater) => { - table.options.onGlobalFilterChange == null ? void 0 : table.options.onGlobalFilterChange(updater); - }, - resetGlobalFilter: (defaultState) => { - table.setGlobalFilter(defaultState ? void 0 : table.initialState.globalFilter); - }, - resetColumnFilters: (defaultState) => { - var _table$initialState$c, _table$initialState; - table.setColumnFilters(defaultState ? [] : (_table$initialState$c = (_table$initialState = table.initialState) == null ? void 0 : _table$initialState.columnFilters) != null ? _table$initialState$c : []); - }, - getPreFilteredRowModel: () => table.getCoreRowModel(), - getFilteredRowModel: () => { - if (!table._getFilteredRowModel && table.options.getFilteredRowModel) { - table._getFilteredRowModel = table.options.getFilteredRowModel(table); - } - if (table.options.manualFiltering || !table._getFilteredRowModel) { - return table.getPreFilteredRowModel(); - } - return table._getFilteredRowModel(); - }, - _getGlobalFacetedRowModel: table.options.getFacetedRowModel && table.options.getFacetedRowModel(table, "__global__"), - getGlobalFacetedRowModel: () => { - if (table.options.manualFiltering || !table._getGlobalFacetedRowModel) { - return table.getPreFilteredRowModel(); - } - return table._getGlobalFacetedRowModel(); - }, - _getGlobalFacetedUniqueValues: table.options.getFacetedUniqueValues && table.options.getFacetedUniqueValues(table, "__global__"), - getGlobalFacetedUniqueValues: () => { - if (!table._getGlobalFacetedUniqueValues) { - return /* @__PURE__ */ new Map(); - } - return table._getGlobalFacetedUniqueValues(); - }, - _getGlobalFacetedMinMaxValues: table.options.getFacetedMinMaxValues && table.options.getFacetedMinMaxValues(table, "__global__"), - getGlobalFacetedMinMaxValues: () => { - if (!table._getGlobalFacetedMinMaxValues) { - return; - } - return table._getGlobalFacetedMinMaxValues(); - } - }; +function WeekNumber(props2) { + var weekNumber = props2.number, dates = props2.dates; + var _a2 = useDayPicker(), onWeekNumberClick = _a2.onWeekNumberClick, styles2 = _a2.styles, classNames9 = _a2.classNames, locale2 = _a2.locale, labelWeekNumber2 = _a2.labels.labelWeekNumber, formatWeekNumber2 = _a2.formatters.formatWeekNumber; + var content = formatWeekNumber2(Number(weekNumber), { locale: locale2 }); + if (!onWeekNumberClick) { + return Cn.createElement("span", { className: classNames9.weeknumber, style: styles2.weeknumber }, content); } -}; -function shouldAutoRemoveFilter(filterFn, value, column) { - return (filterFn && filterFn.autoRemove ? filterFn.autoRemove(value, column) : false) || typeof value === "undefined" || typeof value === "string" && !value; + var label = labelWeekNumber2(Number(weekNumber), { locale: locale2 }); + var handleClick = function(e4) { + onWeekNumberClick(weekNumber, dates, e4); + }; + return Cn.createElement(Button, { name: "week-number", "aria-label": label, className: classNames9.weeknumber, style: styles2.weeknumber, onClick: handleClick }, content); } -var sum = (columnId, _leafRows, childRows) => { - return childRows.reduce((sum2, next) => { - const nextValue = next.getValue(columnId); - return sum2 + (typeof nextValue === "number" ? nextValue : 0); - }, 0); -}; -var min2 = (columnId, _leafRows, childRows) => { - let min3; - childRows.forEach((row) => { - const value = row.getValue(columnId); - if (value != null && (min3 > value || min3 === void 0 && value >= value)) { - min3 = value; +function Row(props2) { + var _a2, _b2; + var _c2 = useDayPicker(), styles2 = _c2.styles, classNames9 = _c2.classNames, showWeekNumber = _c2.showWeekNumber, components = _c2.components; + var DayComponent = (_a2 = components === null || components === void 0 ? void 0 : components.Day) !== null && _a2 !== void 0 ? _a2 : Day; + var WeeknumberComponent = (_b2 = components === null || components === void 0 ? void 0 : components.WeekNumber) !== null && _b2 !== void 0 ? _b2 : WeekNumber; + var weekNumberCell; + if (showWeekNumber) { + weekNumberCell = Cn.createElement( + "td", + { className: classNames9.cell, style: styles2.cell }, + Cn.createElement(WeeknumberComponent, { number: props2.weekNumber, dates: props2.dates }) + ); + } + return Cn.createElement( + "tr", + { className: classNames9.row, style: styles2.row }, + weekNumberCell, + props2.dates.map(function(date) { + return Cn.createElement( + "td", + { className: classNames9.cell, style: styles2.cell, key: getUnixTime(date), role: "presentation" }, + Cn.createElement(DayComponent, { displayMonth: props2.displayMonth, date }) + ); + }) + ); +} +function daysToMonthWeeks(fromDate, toDate2, options) { + var toWeek = (options === null || options === void 0 ? void 0 : options.ISOWeek) ? endOfISOWeek(toDate2) : endOfWeek(toDate2, options); + var fromWeek = (options === null || options === void 0 ? void 0 : options.ISOWeek) ? startOfISOWeek(fromDate) : startOfWeek(fromDate, options); + var nOfDays = differenceInCalendarDays(toWeek, fromWeek); + var days = []; + for (var i4 = 0; i4 <= nOfDays; i4++) { + days.push(addDays(fromWeek, i4)); + } + var weeksInMonth = days.reduce(function(result, date) { + var weekNumber = (options === null || options === void 0 ? void 0 : options.ISOWeek) ? getISOWeek(date) : getWeek(date, options); + var existingWeek = result.find(function(value) { + return value.weekNumber === weekNumber; + }); + if (existingWeek) { + existingWeek.dates.push(date); + return result; } - }); - return min3; -}; -var max2 = (columnId, _leafRows, childRows) => { - let max3; - childRows.forEach((row) => { - const value = row.getValue(columnId); - if (value != null && (max3 < value || max3 === void 0 && value >= value)) { - max3 = value; + result.push({ + weekNumber, + dates: [date] + }); + return result; + }, []); + return weeksInMonth; +} +function getMonthWeeks(month, options) { + var weeksInMonth = daysToMonthWeeks(startOfMonth(month), endOfMonth(month), options); + if (options === null || options === void 0 ? void 0 : options.useFixedWeeks) { + var nrOfMonthWeeks = getWeeksInMonth(month, options); + if (nrOfMonthWeeks < 6) { + var lastWeek = weeksInMonth[weeksInMonth.length - 1]; + var lastDate = lastWeek.dates[lastWeek.dates.length - 1]; + var toDate2 = addWeeks(lastDate, 6 - nrOfMonthWeeks); + var extraWeeks = daysToMonthWeeks(addWeeks(lastDate, 1), toDate2, options); + weeksInMonth.push.apply(weeksInMonth, extraWeeks); } + } + return weeksInMonth; +} +function Table(props2) { + var _a2, _b2, _c2; + var _d2 = useDayPicker(), locale2 = _d2.locale, classNames9 = _d2.classNames, styles2 = _d2.styles, hideHead = _d2.hideHead, fixedWeeks = _d2.fixedWeeks, components = _d2.components, weekStartsOn = _d2.weekStartsOn, firstWeekContainsDate = _d2.firstWeekContainsDate, ISOWeek = _d2.ISOWeek; + var weeks = getMonthWeeks(props2.displayMonth, { + useFixedWeeks: Boolean(fixedWeeks), + ISOWeek, + locale: locale2, + weekStartsOn, + firstWeekContainsDate }); - return max3; -}; -var extent = (columnId, _leafRows, childRows) => { - let min3; - let max3; - childRows.forEach((row) => { - const value = row.getValue(columnId); - if (value != null) { - if (min3 === void 0) { - if (value >= value) - min3 = max3 = value; - } else { - if (min3 > value) - min3 = value; - if (max3 < value) - max3 = value; - } + var HeadComponent = (_a2 = components === null || components === void 0 ? void 0 : components.Head) !== null && _a2 !== void 0 ? _a2 : Head; + var RowComponent = (_b2 = components === null || components === void 0 ? void 0 : components.Row) !== null && _b2 !== void 0 ? _b2 : Row; + var FooterComponent = (_c2 = components === null || components === void 0 ? void 0 : components.Footer) !== null && _c2 !== void 0 ? _c2 : Footer; + return Cn.createElement( + "table", + { className: classNames9.table, style: styles2.table, role: "grid", "aria-labelledby": props2["aria-labelledby"] }, + !hideHead && Cn.createElement(HeadComponent, null), + Cn.createElement("tbody", { className: classNames9.tbody, style: styles2.tbody, role: "rowgroup" }, weeks.map(function(week) { + return Cn.createElement(RowComponent, { displayMonth: props2.displayMonth, key: week.weekNumber, dates: week.dates, weekNumber: week.weekNumber }); + })), + Cn.createElement(FooterComponent, { displayMonth: props2.displayMonth }) + ); +} +function canUseDOM2() { + return !!(typeof window !== "undefined" && window.document && window.document.createElement); +} +var useIsomorphicLayoutEffect2 = canUseDOM2() ? y2 : p2; +var serverHandoffComplete = false; +var id = 0; +function genId2() { + return "react-day-picker-".concat(++id); +} +function useId(providedId) { + var _a2; + var initialId = providedId !== null && providedId !== void 0 ? providedId : serverHandoffComplete ? genId2() : null; + var _b2 = h2(initialId), id2 = _b2[0], setId = _b2[1]; + useIsomorphicLayoutEffect2(function() { + if (id2 === null) { + setId(genId2()); } - }); - return [min3, max3]; -}; -var mean = (columnId, leafRows) => { - let count2 = 0; - let sum2 = 0; - leafRows.forEach((row) => { - let value = row.getValue(columnId); - if (value != null && (value = +value) >= value) { - ++count2, sum2 += value; + }, []); + p2(function() { + if (serverHandoffComplete === false) { + serverHandoffComplete = true; } - }); - if (count2) - return sum2 / count2; - return; -}; -var median = (columnId, leafRows) => { - if (!leafRows.length) { - return; + }, []); + return (_a2 = providedId !== null && providedId !== void 0 ? providedId : id2) !== null && _a2 !== void 0 ? _a2 : void 0; +} +function Month(props2) { + var _a2; + var _b2; + var dayPicker = useDayPicker(); + var dir = dayPicker.dir, classNames9 = dayPicker.classNames, styles2 = dayPicker.styles, components = dayPicker.components; + var displayMonths = useNavigation().displayMonths; + var captionId = useId(dayPicker.id ? "".concat(dayPicker.id, "-").concat(props2.displayIndex) : void 0); + var className = [classNames9.month]; + var style = styles2.month; + var isStart = props2.displayIndex === 0; + var isEnd = props2.displayIndex === displayMonths.length - 1; + var isCenter = !isStart && !isEnd; + if (dir === "rtl") { + _a2 = [isStart, isEnd], isEnd = _a2[0], isStart = _a2[1]; } - let min3 = 0; - let max3 = 0; - leafRows.forEach((row) => { - let value = row.getValue(columnId); - if (typeof value === "number") { - min3 = Math.min(min3, value); - max3 = Math.max(max3, value); - } - }); - return (min3 + max3) / 2; -}; -var unique = (columnId, leafRows) => { - return Array.from(new Set(leafRows.map((d5) => d5.getValue(columnId))).values()); -}; -var uniqueCount = (columnId, leafRows) => { - return new Set(leafRows.map((d5) => d5.getValue(columnId))).size; -}; -var count = (_columnId, leafRows) => { - return leafRows.length; -}; -var aggregationFns = { - sum, - min: min2, - max: max2, - extent, - mean, - median, - unique, - uniqueCount, - count -}; -var Grouping = { - getDefaultColumnDef: () => { - return { - aggregatedCell: (props2) => { - var _toString, _props$getValue; - return (_toString = (_props$getValue = props2.getValue()) == null ? void 0 : _props$getValue.toString == null ? void 0 : _props$getValue.toString()) != null ? _toString : null; - }, - aggregationFn: "auto" - }; - }, - getInitialState: (state) => { - return { - grouping: [], - ...state - }; - }, - getDefaultOptions: (table) => { - return { - onGroupingChange: makeStateUpdater("grouping", table), - groupedColumnMode: "reorder" - }; - }, - createColumn: (column, table) => { - return { - toggleGrouping: () => { - table.setGrouping((old) => { - if (old != null && old.includes(column.id)) { - return old.filter((d5) => d5 !== column.id); - } - return [...old != null ? old : [], column.id]; - }); - }, - getCanGroup: () => { - var _ref, _ref2, _ref3, _column$columnDef$ena; - return (_ref = (_ref2 = (_ref3 = (_column$columnDef$ena = column.columnDef.enableGrouping) != null ? _column$columnDef$ena : true) != null ? _ref3 : table.options.enableGrouping) != null ? _ref2 : true) != null ? _ref : !!column.accessorFn; - }, - getIsGrouped: () => { - var _table$getState$group; - return (_table$getState$group = table.getState().grouping) == null ? void 0 : _table$getState$group.includes(column.id); - }, - getGroupedIndex: () => { - var _table$getState$group2; - return (_table$getState$group2 = table.getState().grouping) == null ? void 0 : _table$getState$group2.indexOf(column.id); - }, - getToggleGroupingHandler: () => { - const canGroup = column.getCanGroup(); - return () => { - if (!canGroup) - return; - column.toggleGrouping(); - }; - }, - getAutoAggregationFn: () => { - const firstRow = table.getCoreRowModel().flatRows[0]; - const value = firstRow == null ? void 0 : firstRow.getValue(column.id); - if (typeof value === "number") { - return aggregationFns.sum; - } - if (Object.prototype.toString.call(value) === "[object Date]") { - return aggregationFns.extent; - } - }, - getAggregationFn: () => { - var _table$options$aggreg, _table$options$aggreg2; - if (!column) { - throw new Error(); - } - return isFunction(column.columnDef.aggregationFn) ? column.columnDef.aggregationFn : column.columnDef.aggregationFn === "auto" ? column.getAutoAggregationFn() : (_table$options$aggreg = (_table$options$aggreg2 = table.options.aggregationFns) == null ? void 0 : _table$options$aggreg2[column.columnDef.aggregationFn]) != null ? _table$options$aggreg : aggregationFns[column.columnDef.aggregationFn]; - } - }; - }, - createTable: (table) => { - return { - setGrouping: (updater) => table.options.onGroupingChange == null ? void 0 : table.options.onGroupingChange(updater), - resetGrouping: (defaultState) => { - var _table$initialState$g, _table$initialState; - table.setGrouping(defaultState ? [] : (_table$initialState$g = (_table$initialState = table.initialState) == null ? void 0 : _table$initialState.grouping) != null ? _table$initialState$g : []); - }, - getPreGroupedRowModel: () => table.getFilteredRowModel(), - getGroupedRowModel: () => { - if (!table._getGroupedRowModel && table.options.getGroupedRowModel) { - table._getGroupedRowModel = table.options.getGroupedRowModel(table); - } - if (table.options.manualGrouping || !table._getGroupedRowModel) { - return table.getPreGroupedRowModel(); - } - return table._getGroupedRowModel(); - } - }; - }, - createRow: (row) => { - return { - getIsGrouped: () => !!row.groupingColumnId, - _groupingValuesCache: {} - }; - }, - createCell: (cell, column, row, table) => { - return { - getIsGrouped: () => column.getIsGrouped() && column.id === row.groupingColumnId, - getIsPlaceholder: () => !cell.getIsGrouped() && column.getIsGrouped(), - getIsAggregated: () => { - var _row$subRows; - return !cell.getIsGrouped() && !cell.getIsPlaceholder() && !!((_row$subRows = row.subRows) != null && _row$subRows.length); - } - }; + if (isStart) { + className.push(classNames9.caption_start); + style = __assign(__assign({}, style), styles2.caption_start); } -}; -function orderColumns(leafColumns, grouping, groupedColumnMode) { - if (!(grouping != null && grouping.length) || !groupedColumnMode) { - return leafColumns; + if (isEnd) { + className.push(classNames9.caption_end); + style = __assign(__assign({}, style), styles2.caption_end); } - const nonGroupingColumns = leafColumns.filter((col) => !grouping.includes(col.id)); - if (groupedColumnMode === "remove") { - return nonGroupingColumns; + if (isCenter) { + className.push(classNames9.caption_between); + style = __assign(__assign({}, style), styles2.caption_between); } - const groupingColumns = grouping.map((g4) => leafColumns.find((col) => col.id === g4)).filter(Boolean); - return [...groupingColumns, ...nonGroupingColumns]; + var CaptionComponent = (_b2 = components === null || components === void 0 ? void 0 : components.Caption) !== null && _b2 !== void 0 ? _b2 : Caption; + return Cn.createElement( + "div", + { key: props2.displayIndex, className: className.join(" "), style }, + Cn.createElement(CaptionComponent, { id: captionId, displayMonth: props2.displayMonth }), + Cn.createElement(Table, { "aria-labelledby": captionId, displayMonth: props2.displayMonth }) + ); } -var Ordering = { - getInitialState: (state) => { - return { - columnOrder: [], - ...state - }; - }, - getDefaultOptions: (table) => { - return { - onColumnOrderChange: makeStateUpdater("columnOrder", table) - }; - }, - createTable: (table) => { - return { - setColumnOrder: (updater) => table.options.onColumnOrderChange == null ? void 0 : table.options.onColumnOrderChange(updater), - resetColumnOrder: (defaultState) => { - var _table$initialState$c; - table.setColumnOrder(defaultState ? [] : (_table$initialState$c = table.initialState.columnOrder) != null ? _table$initialState$c : []); - }, - _getOrderColumnsFn: memo(() => [table.getState().columnOrder, table.getState().grouping, table.options.groupedColumnMode], (columnOrder, grouping, groupedColumnMode) => (columns) => { - let orderedColumns = []; - if (!(columnOrder != null && columnOrder.length)) { - orderedColumns = columns; - } else { - const columnOrderCopy = [...columnOrder]; - const columnsCopy = [...columns]; - while (columnsCopy.length && columnOrderCopy.length) { - const targetColumnId = columnOrderCopy.shift(); - const foundIndex = columnsCopy.findIndex((d5) => d5.id === targetColumnId); - if (foundIndex > -1) { - orderedColumns.push(columnsCopy.splice(foundIndex, 1)[0]); - } - } - orderedColumns = [...orderedColumns, ...columnsCopy]; - } - return orderColumns(orderedColumns, grouping, groupedColumnMode); - }, { - key: "getOrderColumnsFn" - }) - }; +function Root2() { + var dayPicker = useDayPicker(); + var focusContext = useFocusContext(); + var navigation = useNavigation(); + var _a2 = h2(false), hasInitialFocus = _a2[0], setHasInitialFocus = _a2[1]; + p2(function() { + if (!dayPicker.initialFocus) + return; + if (!focusContext.focusTarget) + return; + if (hasInitialFocus) + return; + focusContext.focus(focusContext.focusTarget); + setHasInitialFocus(true); + }, [ + dayPicker.initialFocus, + hasInitialFocus, + focusContext.focus, + focusContext.focusTarget, + focusContext + ]); + var classNames9 = [dayPicker.classNames.root, dayPicker.className]; + if (dayPicker.numberOfMonths > 1) { + classNames9.push(dayPicker.classNames.multiple_months); } -}; -var defaultPageIndex = 0; -var defaultPageSize = 10; -var getDefaultPaginationState = () => ({ - pageIndex: defaultPageIndex, - pageSize: defaultPageSize -}); -var Pagination = { - getInitialState: (state) => { - return { - ...state, - pagination: { - ...getDefaultPaginationState(), - ...state == null ? void 0 : state.pagination - } - }; - }, - getDefaultOptions: (table) => { - return { - onPaginationChange: makeStateUpdater("pagination", table) - }; - }, - createTable: (table) => { - let registered = false; - let queued = false; - return { - _autoResetPageIndex: () => { - var _ref, _table$options$autoRe; - if (!registered) { - table._queue(() => { - registered = true; - }); - return; - } - if ((_ref = (_table$options$autoRe = table.options.autoResetAll) != null ? _table$options$autoRe : table.options.autoResetPageIndex) != null ? _ref : !table.options.manualPagination) { - if (queued) - return; - queued = true; - table._queue(() => { - table.resetPageIndex(); - queued = false; - }); - } - }, - setPagination: (updater) => { - const safeUpdater = (old) => { - let newState = functionalUpdate(updater, old); - return newState; - }; - return table.options.onPaginationChange == null ? void 0 : table.options.onPaginationChange(safeUpdater); - }, - resetPagination: (defaultState) => { - var _table$initialState$p; - table.setPagination(defaultState ? getDefaultPaginationState() : (_table$initialState$p = table.initialState.pagination) != null ? _table$initialState$p : getDefaultPaginationState()); - }, - setPageIndex: (updater) => { - table.setPagination((old) => { - let pageIndex = functionalUpdate(updater, old.pageIndex); - const maxPageIndex = typeof table.options.pageCount === "undefined" || table.options.pageCount === -1 ? Number.MAX_SAFE_INTEGER : table.options.pageCount - 1; - pageIndex = Math.max(0, Math.min(pageIndex, maxPageIndex)); - return { - ...old, - pageIndex - }; - }); - }, - resetPageIndex: (defaultState) => { - var _table$initialState$p2, _table$initialState, _table$initialState$p3; - table.setPageIndex(defaultState ? defaultPageIndex : (_table$initialState$p2 = (_table$initialState = table.initialState) == null ? void 0 : (_table$initialState$p3 = _table$initialState.pagination) == null ? void 0 : _table$initialState$p3.pageIndex) != null ? _table$initialState$p2 : defaultPageIndex); - }, - resetPageSize: (defaultState) => { - var _table$initialState$p4, _table$initialState2, _table$initialState2$; - table.setPageSize(defaultState ? defaultPageSize : (_table$initialState$p4 = (_table$initialState2 = table.initialState) == null ? void 0 : (_table$initialState2$ = _table$initialState2.pagination) == null ? void 0 : _table$initialState2$.pageSize) != null ? _table$initialState$p4 : defaultPageSize); - }, - setPageSize: (updater) => { - table.setPagination((old) => { - const pageSize = Math.max(1, functionalUpdate(updater, old.pageSize)); - const topRowIndex = old.pageSize * old.pageIndex; - const pageIndex = Math.floor(topRowIndex / pageSize); - return { - ...old, - pageIndex, - pageSize - }; - }); - }, - setPageCount: (updater) => table.setPagination((old) => { - var _table$options$pageCo; - let newPageCount = functionalUpdate(updater, (_table$options$pageCo = table.options.pageCount) != null ? _table$options$pageCo : -1); - if (typeof newPageCount === "number") { - newPageCount = Math.max(-1, newPageCount); - } - return { - ...old, - pageCount: newPageCount - }; - }), - getPageOptions: memo(() => [table.getPageCount()], (pageCount) => { - let pageOptions = []; - if (pageCount && pageCount > 0) { - pageOptions = [...new Array(pageCount)].fill(null).map((_9, i4) => i4); - } - return pageOptions; - }, { - key: "getPageOptions", - debug: () => { - var _table$options$debugA; - return (_table$options$debugA = table.options.debugAll) != null ? _table$options$debugA : table.options.debugTable; - } - }), - getCanPreviousPage: () => table.getState().pagination.pageIndex > 0, - getCanNextPage: () => { - const { - pageIndex - } = table.getState().pagination; - const pageCount = table.getPageCount(); - if (pageCount === -1) { - return true; - } - if (pageCount === 0) { - return false; - } - return pageIndex < pageCount - 1; - }, - previousPage: () => { - return table.setPageIndex((old) => old - 1); - }, - nextPage: () => { - return table.setPageIndex((old) => { - return old + 1; - }); - }, - getPrePaginationRowModel: () => table.getExpandedRowModel(), - getPaginationRowModel: () => { - if (!table._getPaginationRowModel && table.options.getPaginationRowModel) { - table._getPaginationRowModel = table.options.getPaginationRowModel(table); - } - if (table.options.manualPagination || !table._getPaginationRowModel) { - return table.getPrePaginationRowModel(); - } - return table._getPaginationRowModel(); + if (dayPicker.showWeekNumber) { + classNames9.push(dayPicker.classNames.with_weeknumber); + } + var style = __assign(__assign({}, dayPicker.styles.root), dayPicker.style); + return Cn.createElement( + "div", + { className: classNames9.join(" "), style, dir: dayPicker.dir }, + Cn.createElement("div", { className: dayPicker.classNames.months, style: dayPicker.styles.months }, navigation.displayMonths.map(function(month, i4) { + return Cn.createElement(Month, { key: i4, displayIndex: i4, displayMonth: month }); + })) + ); +} +function RootProvider(props2) { + var children = props2.children, initialProps = __rest(props2, ["children"]); + return Cn.createElement( + DayPickerProvider, + { initialProps }, + Cn.createElement( + NavigationProvider, + null, + Cn.createElement( + SelectSingleProvider, + { initialProps }, + Cn.createElement( + SelectMultipleProvider, + { initialProps }, + Cn.createElement( + SelectRangeProvider, + { initialProps }, + Cn.createElement( + ModifiersProvider, + null, + Cn.createElement(FocusProvider, null, children) + ) + ) + ) + ) + ) + ); +} +function DayPicker(props2) { + return Cn.createElement( + RootProvider, + __assign({}, props2), + Cn.createElement(Root2, null) + ); +} + +// src/components/UI/menus/datePickerMenu.tsx +var showDatePickerMenu = (point, value, setValue, format2) => { + const menu = new import_obsidian24.Menu(); + menu.dom.toggleClass("mk-menu", true); + menu.setUseNativeMenu(false); + const frag = document.createDocumentFragment(); + const div = frag.createEl("div"); + div.addEventListener("click", (e4) => { + e4.stopImmediatePropagation(); + }); + div.addEventListener("mousedown", (e4) => { + e4.stopImmediatePropagation(); + }); + div.addEventListener("mouseup", (e4) => { + e4.stopImmediatePropagation(); + }); + div.addEventListener("keydown", (e4) => { + }); + const setDate = (date) => { + setValue(date); + menu.hide(); + }; + const root = createRoot(div); + root.render( + /* @__PURE__ */ Cn.createElement(Cn.Fragment, null, /* @__PURE__ */ Cn.createElement(DayPicker, { + defaultMonth: value, + mode: "single", + selected: value, + labels: { + labelMonthDropdown: () => void 0, + labelYearDropdown: () => void 0, + labelNext: () => void 0, + labelPrevious: () => void 0, + labelDay: () => void 0, + labelWeekday: () => void 0, + labelWeekNumber: () => void 0 }, - getPageCount: () => { - var _table$options$pageCo2; - return (_table$options$pageCo2 = table.options.pageCount) != null ? _table$options$pageCo2 : Math.ceil(table.getPrePaginationRowModel().rows.length / table.getState().pagination.pageSize); - } - }; + onSelect: setDate + })) + ); + menu.addItem((item) => { + item.setTitle(frag); + }); + const keys = [...menu.scope.keys]; + for (let i4 = 0; i4 < keys.length; i4++) { + if (keys[i4].key != "Escape") { + menu.scope.unregister(keys[i4]); + } } + menu.showAtPosition(point); + return menu; }; -var getDefaultPinningState = () => ({ - left: [], - right: [] -}); -var Pinning = { - getInitialState: (state) => { - return { - columnPinning: getDefaultPinningState(), - ...state - }; + +// src/components/Navigator/SpaceQuery.tsx +var import_obsidian40 = require("obsidian"); + +// src/types/metadata.ts +var fileProps = { + "name": { + label: "File Name", + field: "name", + vType: "text", + type: "fileprop" }, - getDefaultOptions: (table) => { - return { - onColumnPinningChange: makeStateUpdater("columnPinning", table) - }; + "path": { + label: "Path", + field: "path", + vType: "text", + type: "fileprop" }, - createColumn: (column, table) => { - return { - pin: (position) => { - const columnIds = column.getLeafColumns().map((d5) => d5.id).filter(Boolean); - table.setColumnPinning((old) => { - var _old$left3, _old$right3; - if (position === "right") { - var _old$left, _old$right; - return { - left: ((_old$left = old == null ? void 0 : old.left) != null ? _old$left : []).filter((d5) => !(columnIds != null && columnIds.includes(d5))), - right: [...((_old$right = old == null ? void 0 : old.right) != null ? _old$right : []).filter((d5) => !(columnIds != null && columnIds.includes(d5))), ...columnIds] - }; - } - if (position === "left") { - var _old$left2, _old$right2; - return { - left: [...((_old$left2 = old == null ? void 0 : old.left) != null ? _old$left2 : []).filter((d5) => !(columnIds != null && columnIds.includes(d5))), ...columnIds], - right: ((_old$right2 = old == null ? void 0 : old.right) != null ? _old$right2 : []).filter((d5) => !(columnIds != null && columnIds.includes(d5))) - }; - } - return { - left: ((_old$left3 = old == null ? void 0 : old.left) != null ? _old$left3 : []).filter((d5) => !(columnIds != null && columnIds.includes(d5))), - right: ((_old$right3 = old == null ? void 0 : old.right) != null ? _old$right3 : []).filter((d5) => !(columnIds != null && columnIds.includes(d5))) - }; - }); - }, - getCanPin: () => { - const leafColumns = column.getLeafColumns(); - return leafColumns.some((d5) => { - var _d$columnDef$enablePi, _table$options$enable; - return ((_d$columnDef$enablePi = d5.columnDef.enablePinning) != null ? _d$columnDef$enablePi : true) && ((_table$options$enable = table.options.enablePinning) != null ? _table$options$enable : true); - }); - }, - getIsPinned: () => { - const leafColumnIds = column.getLeafColumns().map((d5) => d5.id); - const { - left, - right - } = table.getState().columnPinning; - const isLeft = leafColumnIds.some((d5) => left == null ? void 0 : left.includes(d5)); - const isRight = leafColumnIds.some((d5) => right == null ? void 0 : right.includes(d5)); - return isLeft ? "left" : isRight ? "right" : false; - }, - getPinnedIndex: () => { - var _table$getState$colum, _table$getState$colum2, _table$getState$colum3; - const position = column.getIsPinned(); - return position ? (_table$getState$colum = (_table$getState$colum2 = table.getState().columnPinning) == null ? void 0 : (_table$getState$colum3 = _table$getState$colum2[position]) == null ? void 0 : _table$getState$colum3.indexOf(column.id)) != null ? _table$getState$colum : -1 : 0; - } - }; + "parent": { + label: "Folder", + field: "parent", + vType: "text", + type: "fileprop" }, - createRow: (row, table) => { - return { - getCenterVisibleCells: memo(() => [row._getAllVisibleCells(), table.getState().columnPinning.left, table.getState().columnPinning.right], (allCells, left, right) => { - const leftAndRight = [...left != null ? left : [], ...right != null ? right : []]; - return allCells.filter((d5) => !leftAndRight.includes(d5.column.id)); - }, { - key: false, - debug: () => { - var _table$options$debugA; - return (_table$options$debugA = table.options.debugAll) != null ? _table$options$debugA : table.options.debugRows; - } - }), - getLeftVisibleCells: memo(() => [row._getAllVisibleCells(), table.getState().columnPinning.left, ,], (allCells, left) => { - const cells = (left != null ? left : []).map((columnId) => allCells.find((cell) => cell.column.id === columnId)).filter(Boolean).map((d5) => ({ - ...d5, - position: "left" - })); - return cells; - }, { - key: false, - debug: () => { - var _table$options$debugA2; - return (_table$options$debugA2 = table.options.debugAll) != null ? _table$options$debugA2 : table.options.debugRows; - } - }), - getRightVisibleCells: memo(() => [row._getAllVisibleCells(), table.getState().columnPinning.right], (allCells, right) => { - const cells = (right != null ? right : []).map((columnId) => allCells.find((cell) => cell.column.id === columnId)).filter(Boolean).map((d5) => ({ - ...d5, - position: "right" - })); - return cells; - }, { - key: false, - debug: () => { - var _table$options$debugA3; - return (_table$options$debugA3 = table.options.debugAll) != null ? _table$options$debugA3 : table.options.debugRows; - } - }) - }; + "sticker": { + label: "Sticker", + field: "sticker", + vType: "text", + type: "fileprop" }, - createTable: (table) => { - return { - setColumnPinning: (updater) => table.options.onColumnPinningChange == null ? void 0 : table.options.onColumnPinningChange(updater), - resetColumnPinning: (defaultState) => { - var _table$initialState$c, _table$initialState; - return table.setColumnPinning(defaultState ? getDefaultPinningState() : (_table$initialState$c = (_table$initialState = table.initialState) == null ? void 0 : _table$initialState.columnPinning) != null ? _table$initialState$c : getDefaultPinningState()); - }, - getIsSomeColumnsPinned: (position) => { - var _pinningState$positio; - const pinningState = table.getState().columnPinning; - if (!position) { - var _pinningState$left, _pinningState$right; - return Boolean(((_pinningState$left = pinningState.left) == null ? void 0 : _pinningState$left.length) || ((_pinningState$right = pinningState.right) == null ? void 0 : _pinningState$right.length)); - } - return Boolean((_pinningState$positio = pinningState[position]) == null ? void 0 : _pinningState$positio.length); - }, - getLeftLeafColumns: memo(() => [table.getAllLeafColumns(), table.getState().columnPinning.left], (allColumns, left) => { - return (left != null ? left : []).map((columnId) => allColumns.find((column) => column.id === columnId)).filter(Boolean); - }, { - key: "getLeftLeafColumns", - debug: () => { - var _table$options$debugA4; - return (_table$options$debugA4 = table.options.debugAll) != null ? _table$options$debugA4 : table.options.debugColumns; - } - }), - getRightLeafColumns: memo(() => [table.getAllLeafColumns(), table.getState().columnPinning.right], (allColumns, right) => { - return (right != null ? right : []).map((columnId) => allColumns.find((column) => column.id === columnId)).filter(Boolean); - }, { - key: "getRightLeafColumns", - debug: () => { - var _table$options$debugA5; - return (_table$options$debugA5 = table.options.debugAll) != null ? _table$options$debugA5 : table.options.debugColumns; - } - }), - getCenterLeafColumns: memo(() => [table.getAllLeafColumns(), table.getState().columnPinning.left, table.getState().columnPinning.right], (allColumns, left, right) => { - const leftAndRight = [...left != null ? left : [], ...right != null ? right : []]; - return allColumns.filter((d5) => !leftAndRight.includes(d5.id)); - }, { - key: "getCenterLeafColumns", - debug: () => { - var _table$options$debugA6; - return (_table$options$debugA6 = table.options.debugAll) != null ? _table$options$debugA6 : table.options.debugColumns; - } - }) - }; + "color": { + label: "Color", + field: "color", + vType: "text", + type: "fileprop" + }, + "ctime": { + label: "Created", + field: "ctime", + vType: "date", + type: "fileprop" + }, + "mtime": { + label: "Last Modified", + field: "mtime", + vType: "date", + type: "fileprop" + }, + "extension": { + label: "Extension", + field: "extension", + vType: "text", + type: "fileprop" + }, + "size": { + label: "Size", + field: "size", + vType: "number", + type: "fileprop" } }; -var RowSelection = { - getInitialState: (state) => { - return { - rowSelection: {}, - ...state - }; +var fileMeta = { + "tags": { + label: "Tags", + field: "tags", + vType: "tags-multi", + type: "filemeta" }, - getDefaultOptions: (table) => { - return { - onRowSelectionChange: makeStateUpdater("rowSelection", table), - enableRowSelection: true, - enableMultiRowSelection: true, - enableSubRowSelection: true - }; + "inlinks": { + label: "Linked Mentions", + field: "inlinks", + vType: "link-multi", + type: "filemeta" }, - createTable: (table) => { - return { - setRowSelection: (updater) => table.options.onRowSelectionChange == null ? void 0 : table.options.onRowSelectionChange(updater), - resetRowSelection: (defaultState) => { - var _table$initialState$r; - return table.setRowSelection(defaultState ? {} : (_table$initialState$r = table.initialState.rowSelection) != null ? _table$initialState$r : {}); - }, - toggleAllRowsSelected: (value) => { - table.setRowSelection((old) => { - value = typeof value !== "undefined" ? value : !table.getIsAllRowsSelected(); - const rowSelection = { - ...old - }; - const preGroupedFlatRows = table.getPreGroupedRowModel().flatRows; - if (value) { - preGroupedFlatRows.forEach((row) => { - if (!row.getCanSelect()) { - return; - } - rowSelection[row.id] = true; - }); - } else { - preGroupedFlatRows.forEach((row) => { - delete rowSelection[row.id]; - }); - } - return rowSelection; - }); - }, - toggleAllPageRowsSelected: (value) => table.setRowSelection((old) => { - const resolvedValue = typeof value !== "undefined" ? value : !table.getIsAllPageRowsSelected(); - const rowSelection = { - ...old - }; - table.getRowModel().rows.forEach((row) => { - mutateRowIsSelected(rowSelection, row.id, resolvedValue, table); - }); - return rowSelection; - }), - getPreSelectedRowModel: () => table.getCoreRowModel(), - getSelectedRowModel: memo(() => [table.getState().rowSelection, table.getCoreRowModel()], (rowSelection, rowModel) => { - if (!Object.keys(rowSelection).length) { - return { - rows: [], - flatRows: [], - rowsById: {} - }; - } - return selectRowsFn(table, rowModel); - }, { - key: "getSelectedRowModel", - debug: () => { - var _table$options$debugA; - return (_table$options$debugA = table.options.debugAll) != null ? _table$options$debugA : table.options.debugTable; - } - }), - getFilteredSelectedRowModel: memo(() => [table.getState().rowSelection, table.getFilteredRowModel()], (rowSelection, rowModel) => { - if (!Object.keys(rowSelection).length) { - return { - rows: [], - flatRows: [], - rowsById: {} - }; - } - return selectRowsFn(table, rowModel); - }, { - key: false, - debug: () => { - var _table$options$debugA2; - return (_table$options$debugA2 = table.options.debugAll) != null ? _table$options$debugA2 : table.options.debugTable; - } - }), - getGroupedSelectedRowModel: memo(() => [table.getState().rowSelection, table.getSortedRowModel()], (rowSelection, rowModel) => { - if (!Object.keys(rowSelection).length) { - return { - rows: [], - flatRows: [], - rowsById: {} - }; - } - return selectRowsFn(table, rowModel); - }, { - key: false, - debug: () => { - var _table$options$debugA3; - return (_table$options$debugA3 = table.options.debugAll) != null ? _table$options$debugA3 : table.options.debugTable; - } - }), - getIsAllRowsSelected: () => { - const preGroupedFlatRows = table.getFilteredRowModel().flatRows; - const { - rowSelection - } = table.getState(); - let isAllRowsSelected = Boolean(preGroupedFlatRows.length && Object.keys(rowSelection).length); - if (isAllRowsSelected) { - if (preGroupedFlatRows.some((row) => row.getCanSelect() && !rowSelection[row.id])) { - isAllRowsSelected = false; - } - } - return isAllRowsSelected; - }, - getIsAllPageRowsSelected: () => { - const paginationFlatRows = table.getPaginationRowModel().flatRows; - const { - rowSelection - } = table.getState(); - let isAllPageRowsSelected = !!paginationFlatRows.length; - if (isAllPageRowsSelected && paginationFlatRows.some((row) => row.getCanSelect() && !rowSelection[row.id])) { - isAllPageRowsSelected = false; + "outlinks": { + label: "Links", + field: "outlinks", + vType: "link-multi", + type: "filemeta" + } +}; + +// src/utils/contexts/predicate/filterFns/filterFnLabels.ts +var filterFnLabels = { + isEmpty: i18n_default.filterTypes.isEmpty, + isNotEmpty: i18n_default.filterTypes.isNotEmpty, + include: i18n_default.filterTypes.contains, + notInclude: i18n_default.filterTypes.notContains, + is: i18n_default.filterTypes.is, + isNot: i18n_default.filterTypes.isNot, + equal: "=", + isGreatThan: ">", + isLessThan: "<", + isLessThanOrEqual: "\u2264", + isGreatThanOrEqual: "\u2265", + dateBefore: i18n_default.filterTypes.before, + dateAfter: i18n_default.filterTypes.after, + isSameDateAsToday: "today", + isAnyInList: i18n_default.filterTypes.anyOf, + isNoneInList: i18n_default.filterTypes.noneOf, + isTrue: i18n_default.filterTypes.checked, + isFalse: i18n_default.filterTypes.unchecked +}; + +// src/components/SpaceView/Frames/EditorNodes/FrameNodeView.tsx +var import_classnames4 = __toESM(require_classnames()); + +// src/context/FrameEditorContext.tsx +var import_lodash8 = __toESM(require_lodash()); +var import_obsidian25 = require("obsidian"); + +// src/utils/frames/frames.ts +var propFieldFromString = (str, schemaProps) => { + return schemaProps.find((f4) => str == `${f4.schemaId}.props.${f4.name}`); +}; +var nameForField = (field) => { + var _a2; + if (!field) + return null; + const parsedValue = parseFieldValue(field.value, field.type); + return (_a2 = parsedValue.alias) != null ? _a2 : field.name; +}; +var stringIsConst = (str) => { + const hasQuotesAtStartEndOnly = /^["'][^"']*["'](?:;)?$/.test(str); + const isNumber = !isNaN(parseFloat(str)) && isFinite(str); + return hasQuotesAtStartEndOnly || isNumber || str == null || str == ""; +}; +var newUniqueNode = (node, parent, otherNodes, schemaId) => { + const id2 = uniqueNameFromString( + node.node.id, + otherNodes.map((f4) => f4.id) + ); + return { + ...node.node, + id: id2, + schemaId, + parentId: parent + }; +}; + +// src/utils/frames/runner.ts +function extractDependencies(code) { + const dependencies = []; + function visit(node, parts = []) { + if (node.type === "Identifier") { + parts.push(node.name); + return parts; + } else if (node.type === "MemberExpression") { + const objectParts = visit(node.object, parts); + if (objectParts && node.computed) { + if (node.property.type === "Literal") { + objectParts.push(String(node.property.value)); + return objectParts; + } else { + return null; } - return isAllPageRowsSelected; - }, - getIsSomeRowsSelected: () => { - var _table$getState$rowSe; - const totalSelected = Object.keys((_table$getState$rowSe = table.getState().rowSelection) != null ? _table$getState$rowSe : {}).length; - return totalSelected > 0 && totalSelected < table.getFilteredRowModel().flatRows.length; - }, - getIsSomePageRowsSelected: () => { - const paginationFlatRows = table.getPaginationRowModel().flatRows; - return table.getIsAllPageRowsSelected() ? false : paginationFlatRows.some((d5) => d5.getIsSelected() || d5.getIsSomeSelected()); - }, - getToggleAllRowsSelectedHandler: () => { - return (e4) => { - table.toggleAllRowsSelected(e4.target.checked); - }; - }, - getToggleAllPageRowsSelectedHandler: () => { - return (e4) => { - table.toggleAllPageRowsSelected(e4.target.checked); - }; + } else if (objectParts) { + return visit(node.property, objectParts); } - }; - }, - createRow: (row, table) => { - return { - toggleSelected: (value) => { - const isSelected = row.getIsSelected(); - table.setRowSelection((old) => { - value = typeof value !== "undefined" ? value : !isSelected; - if (isSelected === value) { - return old; - } - const selectedRowIds = { - ...old - }; - mutateRowIsSelected(selectedRowIds, row.id, value, table); - return selectedRowIds; - }); - }, - getIsSelected: () => { - const { - rowSelection - } = table.getState(); - return isRowSelected(row, rowSelection); - }, - getIsSomeSelected: () => { - const { - rowSelection - } = table.getState(); - return isSubRowSelected(row, rowSelection) === "some"; - }, - getIsAllSubRowsSelected: () => { - const { - rowSelection - } = table.getState(); - return isSubRowSelected(row, rowSelection) === "all"; - }, - getCanSelect: () => { - var _table$options$enable; - if (typeof table.options.enableRowSelection === "function") { - return table.options.enableRowSelection(row); - } - return (_table$options$enable = table.options.enableRowSelection) != null ? _table$options$enable : true; - }, - getCanSelectSubRows: () => { - var _table$options$enable2; - if (typeof table.options.enableSubRowSelection === "function") { - return table.options.enableSubRowSelection(row); - } - return (_table$options$enable2 = table.options.enableSubRowSelection) != null ? _table$options$enable2 : true; - }, - getCanMultiSelect: () => { - var _table$options$enable3; - if (typeof table.options.enableMultiRowSelection === "function") { - return table.options.enableMultiRowSelection(row); - } - return (_table$options$enable3 = table.options.enableMultiRowSelection) != null ? _table$options$enable3 : true; + } else if (node.type === "Literal") { + parts.push(String(node.value)); + return parts; + } + return null; + } + function explore(node) { + if (node.type === "MemberExpression") { + const parts = visit(node); + if (parts) { + dependencies.push(parts); + } + return; + } + for (const key2 in node) { + if (typeof node[key2] === "object" && node[key2] !== null) { + explore(node[key2]); + } + } + } + try { + const ast = parse3(code.replace("return ", ""), { ecmaVersion: 2020 }); + explore(ast); + } catch (e4) { + return []; + } + return dependencies; +} +function sortKeysByDependencies(codeBlockStore, identifier) { + const graph = /* @__PURE__ */ new Map(); + const dependencies = /* @__PURE__ */ new Map(); + const allDependencies = /* @__PURE__ */ new Map(); + for (const key2 in codeBlockStore) { + const code = codeBlockStore[key2]; + const extractedDependencies = extractDependencies(code); + const localDependencies = extractedDependencies.filter((dep) => { + return dep.slice(0, -1).join(".") === identifier; + }); + dependencies.set(key2, localDependencies); + allDependencies.set(key2, extractedDependencies); + if (!graph.has(key2)) { + graph.set(key2, /* @__PURE__ */ new Set()); + } + for (const dep of localDependencies) { + const depStr = dep[dep.length - 1]; + if (depStr === key2) + continue; + graph.get(key2).add(depStr); + } + } + const visited = /* @__PURE__ */ new Set(); + const result = []; + const temp = /* @__PURE__ */ new Set(); + const visit = (key2) => { + if (temp.has(key2)) + throw new Error("Circular dependency detected"); + if (!visited.has(key2)) { + temp.add(key2); + const edges = graph.get(key2) || /* @__PURE__ */ new Set(); + for (const dep of edges) { + visit(dep); + } + visited.add(key2); + temp.delete(key2); + result.push(key2); + } + }; + for (const key2 in codeBlockStore) { + if (!visited.has(key2)) { + visit(key2); + } + } + return { sortedKeys: result, dependencies: allDependencies }; +} +var executeTreeNode = async (_treeNode, state, api, saveState, root, runID, newState) => { + var _a2, _b2, _c2; + const treeNode = _treeNode; + let execState = await executeNode(treeNode.node, { state, newState }, api); + if (treeNode.node.type == "list") { + let uid = 0; + treeNode.children = parseMultiString(execState.state[treeNode.id].props.value).flatMap((f4, i4) => treeNode.children.map((n2) => { + const [tree, m5] = linkTreeNodes({ ...n2, node: { ...n2.node, props: { ...n2.node.props, value: wrapQuotes(f4) } } }, uid); + uid = m5; + return tree; + })); + } + if (typeof ((_b2 = (_a2 = execState.state[treeNode.id]) == null ? void 0 : _a2.actions) == null ? void 0 : _b2.onRun) == "function") { + (_c2 = execState.state[treeNode.id].actions) == null ? void 0 : _c2.onRun( + execState, + (s5) => { + saveState(s5, { state: execState.state, root, id: runID }); }, - getToggleSelectedHandler: () => { - const canSelect = row.getCanSelect(); - return (e4) => { - var _target; - if (!canSelect) - return; - row.toggleSelected((_target = e4.target) == null ? void 0 : _target.checked); - }; + api + ); + } + for (let i4 = 0; i4 < treeNode.children.length; i4++) { + const [newState2, newNode] = await executeTreeNode(treeNode.children[i4], execState.state, api, saveState, root, runID, execState.newState).then((f4) => [{ state: f4.state, newState: f4.newState }, f4.root]); + execState = newState2; + treeNode.children[i4] = newNode; + } + return { id: runID, root: treeNode, state: execState.state, newState: execState.newState }; +}; +var executeNode = async (node, results, api) => { + const propResults = await executePropsCodeBlocks(node, results, api); + const stylesResults = executeCodeBlocks(node, "styles", propResults); + const actions = executeCodeBlocks(node, "actions", stylesResults); + return actions; +}; +var executePropsCodeBlocks = async (node, results, api) => { + var _a2, _b2, _c2, _d2, _e2, _f, _g, _h, _i, _j, _k; + const { type, props: props2, id: id2 } = node; + const codeBlockStore = props2 != null ? props2 : {}; + const { sortedKeys, dependencies } = sortKeysByDependencies(codeBlockStore, `${node.id}.props`); + const runKeys = results.newState ? sortedKeys.filter((f4) => { + var _a3, _b3, _c3, _d3, _e3, _f2; + const deps = dependencies.get(f4); + if (f4 in ((_c3 = (_b3 = (_a3 = results.newState) == null ? void 0 : _a3[node.id]) == null ? void 0 : _b3["props"]) != null ? _c3 : {})) { + return true; + } + for (const dep of deps) { + if (dep[0] == "api") + return true; + if ((_f2 = (_e3 = (_d3 = results.newState) == null ? void 0 : _d3[dep[0]]) == null ? void 0 : _e3[dep[1]]) == null ? void 0 : _f2[dep[2]]) { + return true; + } + } + return false; + }) : sortedKeys.filter((f4) => { + var _a3; + return ((_a3 = codeBlockStore[f4]) == null ? void 0 : _a3.length) > 0; + }); + const environment = results.state; + environment[id2] = { + props: (_b2 = (_a2 = results.state[id2]) == null ? void 0 : _a2.props) != null ? _b2 : {}, + actions: (_d2 = (_c2 = results.state[id2]) == null ? void 0 : _c2.actions) != null ? _d2 : {}, + styles: (_f = (_e2 = results.state[id2]) == null ? void 0 : _e2.styles) != null ? _f : {}, + contexts: (_h = (_g = results.state[id2]) == null ? void 0 : _g.contexts) != null ? _h : {} + }; + environment.api = api; + for (const key2 of runKeys) { + try { + let result; + if (key2 in (((_j = (_i = results.newState) == null ? void 0 : _i[node.id]) == null ? void 0 : _j["props"]) || {})) { + result = results.newState[node.id]["props"][key2]; + } else { + const isMultiLine = codeBlockStore[key2].includes("\n"); + const func = isMultiLine ? new Function(`with(this) { ${codeBlockStore[key2]} }`) : new Function(`with(this) { return ${codeBlockStore[key2]}; }`); + result = func.call(environment); + if (result instanceof Promise) { + result = await result; + } } - }; + environment[id2]["props"][key2] = result; + results.state[id2]["props"][key2] = result; + if (results.newState) { + results.newState[id2] = (_k = results.newState[id2]) != null ? _k : { props: {}, styles: {}, actions: {}, contexts: {} }; + results.newState[id2]["props"][key2] = result; + } + } catch (error) { + console.log(error); + } } + return results; }; -var mutateRowIsSelected = (selectedRowIds, id2, value, table) => { - var _row$subRows; - const row = table.getRow(id2); - if (value) { - if (!row.getCanMultiSelect()) { - Object.keys(selectedRowIds).forEach((key2) => delete selectedRowIds[key2]); - } - if (row.getCanSelect()) { - selectedRowIds[id2] = true; +function executeCodeBlocks(node, type, results) { + var _a2; + const codeBlockStore = (_a2 = node[type]) != null ? _a2 : {}; + for (const key2 of Object.keys(codeBlockStore)) { + try { + const isMultiLine = typeof codeBlockStore[key2] === "string" || codeBlockStore[key2] instanceof String ? codeBlockStore[key2].includes("\n") : false; + const func = isMultiLine && !(type == "actions") ? new Function(`with(this) { ${codeBlockStore[key2]} }`) : new Function(`with(this) { return ${codeBlockStore[key2]}; }`); + const result = func.call(results.state); + parseKeyResult(results.state[node.id][type], key2, result); + } catch (error) { + console.log(error); } - } else { - delete selectedRowIds[id2]; } - if ((_row$subRows = row.subRows) != null && _row$subRows.length && row.getCanSelectSubRows()) { - row.subRows.forEach((row2) => mutateRowIsSelected(selectedRowIds, row2.id, value, table)); + return results; +} +var parseKeyResult = (resultStore, key2, result) => { + if (key2 == "layout") { + if (result == "row" || result == "column") { + resultStore["display"] = "flex"; + resultStore["flexDirection"] = result; + return; + } + resultStore["display"] = result; + return; } + resultStore[key2] = result; }; -function selectRowsFn(table, rowModel) { - const rowSelection = table.getState().rowSelection; - const newSelectedFlatRows = []; - const newSelectedRowsById = {}; - const recurseRows = function(rows, depth) { - return rows.map((row) => { - var _row$subRows2; - const isSelected = isRowSelected(row, rowSelection); - if (isSelected) { - newSelectedFlatRows.push(row); - newSelectedRowsById[row.id] = row; - } - if ((_row$subRows2 = row.subRows) != null && _row$subRows2.length) { - row = { - ...row, - subRows: recurseRows(row.subRows) - }; - } - if (isSelected) { - return row; - } - }).filter(Boolean); + +// src/context/FrameEditorContext.tsx +var FramesEditorContext = F({ + root: null, + runRoot: () => null, + instance: { state: {}, id: null, root: null }, + saveState: () => null, + fastSaveState: () => null, + nodes: [], + properties: [], + dragNode: null, + setDragNode: () => null, + hoverNode: null, + selectableNodeBounds: null, + setHoverNode: () => null, + selectedNodes: [], + selectNodes: () => null, + saveProperty: () => false, + newProperty: () => false, + delProperty: () => null, + groupNodes: () => null, + ungroupNode: () => null, + renameNode: () => null, + addNode: () => null, + deleteNode: () => null, + saveNodes: () => null, + moveUp: () => null, + moveDown: () => null, + moveToRank: () => null, + moveNodeFromSchema: () => null +}); +var FramesEditorProvider = (props2) => { + var _a2; + const { spaceInfo } = q2(SpaceContext); + const editorProps = { editMode: props2.editMode }; + const { + frameSchema, + setFrameSchema: setDBSchema, + saveFrame, + frameSchemas: schemas, + tableData, + getMDBData + } = q2(FramesMDBContext); + const [hoverNode, setHoverNode] = h2(null); + const [dragNode, setDragNode] = h2(null); + const [selectedNodes, setSelectedNodes] = h2([]); + const nodes = F2(() => { + var _a3; + if (!frameSchema) + return []; + const frames2 = (_a3 = tableData == null ? void 0 : tableData.rows.map( + (f4) => f4.id == frameSchema.id ? { + ...frameToNode(f4), + types: tableData.cols.reduce( + (p3, c4) => ({ ...p3, [c4.name]: c4.type }), + {} + ), + propsValue: tableData.cols.reduce( + (p3, c4) => ({ ...p3, [c4.name]: c4.value }), + {} + ) + } : frameToNode(f4) + )) != null ? _a3 : []; + const _root = schemaToRoot(frameSchema); + if (frames2.some((f4) => f4.id == _root.id)) { + return frames2; + } + return [...frames2, _root]; + }, [tableData, frameSchema]); + const [root, setRoot] = h2(null); + const [instance, setInstance] = h2({ + state: {}, + id: null, + root: null + }); + const activeRunID = _2(null); + const saveState = (newState, instance2) => { + const { root: _root, id: runID, state } = instance2; + if (activeRunID.current != runID) + return; + executeTreeNode( + applyPropsToRoot(_root, props2.props), + state, + props2.plugin.index.api, + saveState, + _root, + runID, + newState + ).then( + (s5) => setInstance((p3) => { + return s5; + }) + ); }; - return { - rows: recurseRows(rowModel.rows), - flatRows: newSelectedFlatRows, - rowsById: newSelectedRowsById + const selectableNodeBounds = _2({}); + const fastSaveState = (newState) => { + setInstance((p3) => { + return { ...p3, state: newState }; + }); }; -} -function isRowSelected(row, selection) { - var _selection$row$id; - return (_selection$row$id = selection[row.id]) != null ? _selection$row$id : false; -} -function isSubRowSelected(row, selection, table) { - if (row.subRows && row.subRows.length) { - let allChildrenSelected = true; - let someSelected = false; - row.subRows.forEach((subRow) => { - if (someSelected && !allChildrenSelected) { - return; - } - if (isRowSelected(subRow, selection)) { - someSelected = true; - } else { - allChildrenSelected = false; + p2( + () => () => { + activeRunID.current = null; + }, + [] + ); + const runRoot = () => { + var _a3; + if ((frameSchema == null ? void 0 : frameSchema.type) == "frame" || (frameSchema == null ? void 0 : frameSchema.type) == "listitem") { + const _newRoot = buildRoot( + frameSchema, + (_a3 = tableData == null ? void 0 : tableData.cols) != null ? _a3 : [], + nodes, + props2.plugin, + editorProps + ); + setRoot(_newRoot); + if (_newRoot) { + const newRoot = import_lodash8.default.cloneDeep(_newRoot); + const runID = (0, import_lodash8.uniqueId)(); + activeRunID.current = runID; + executeTreeNode( + applyPropsToRoot(newRoot, props2.props), + {}, + props2.plugin.index.api, + saveState, + newRoot, + runID + ).then((s5) => { + setInstance((p3) => { + return s5; + }); + activeRunID.current = s5.id; + }); + if (selectedNodes.length == 0) { + } else { + setSelectedNodes( + nodes.filter((f4) => selectedNodes.find((g4) => g4.id == f4.id)) + ); + } } + } + }; + const refreshFrame = (e4) => { + if (e4.detail.type == "frames" && e4.detail.name == spaceInfo.path) { + runRoot(); + } + }; + p2(() => { + window.addEventListener(eventTypes.spacesChange, refreshFrame); + return () => { + window.removeEventListener(eventTypes.spacesChange, refreshFrame); + }; + }, [spaceInfo]); + p2(() => { + runRoot(); + }, [frameSchema, nodes, tableData, props2.props]); + const moveUp = (node) => { + const items = nodes.filter((f4) => f4.parentId == node.parentId).sort((a5, b4) => a5.rank - b4.rank).map((f4, i4) => ({ ...f4, rank: i4 })); + const itemIndex = items.findIndex((item2) => item2.id === node.id); + if (itemIndex <= 0) { + saveNodes(items); + return; + } + const item = items[itemIndex]; + const swappedItem = items[itemIndex - 1]; + [item.rank, swappedItem.rank] = [swappedItem.rank, item.rank]; + saveNodes(items); + }; + const moveDown = (node) => { + const items = nodes.filter((f4) => f4.parentId == node.parentId).sort((a5, b4) => a5.rank - b4.rank).map((f4, i4) => ({ ...f4, rank: i4 })); + const itemIndex = items.findIndex((item2) => item2.id === node.id); + if (itemIndex < 0 || itemIndex >= items.length - 1) { + saveNodes(items); + return; + } + const item = items[itemIndex]; + const swappedItem = items[itemIndex + 1]; + [item.rank, swappedItem.rank] = [swappedItem.rank, item.rank]; + saveNodes(items.sort((a5, b4) => a5.rank - b4.rank)); + }; + const ungroupNode = (node) => { + const children = nodes.filter((f4) => f4.parentId == node.id); + const newRank = node.rank; + const items = nodes.filter((f4) => f4.parentId == node.parentId).sort((a5, b4) => a5.rank - b4.rank); + const newItems = insertMulti( + items, + newRank, + children.map((f4) => ({ ...f4, parentId: node.parentId })) + ).filter((f4) => f4.id != node.id).map((f4, i4) => ({ ...f4, rank: i4 })); + return saveNodes(newItems, [node]); + }; + const moveToRank = (node, newRank) => { + const items = nodes.filter((f4) => f4.parentId == node.parentId).sort((a5, b4) => a5.rank - b4.rank).map((f4, i4) => ({ ...f4, rank: i4 })); + const itemIndex = items.findIndex((item2) => item2.id === node.id); + if (itemIndex < 0 || newRank < 0 || newRank >= items.length) { + saveNodes(items); + return; + } + const item = items[itemIndex]; + item.rank = newRank; + const newItems = arrayMove(items, itemIndex, newRank).map((f4, i4) => ({ + ...f4, + rank: i4 + })); + saveNodes(newItems); + }; + const groupNodes = (treeNodes, style) => { + const parentId = treeNodes[0].id == frameSchema.id ? "" : treeNodes[0].parentId; + const group = { + ...newUniqueNode(groupNode, parentId, nodes, frameSchema.id) + }; + const newNodes = treeNodes.map((f4) => { + const node = import_lodash8.default.cloneDeep(f4); + node.parentId = group.id; + return node; }); - return allChildrenSelected ? "all" : someSelected ? "some" : false; + saveNodes([ + { ...group, styles: { ...group.styles, ...style } }, + ...newNodes + ]); + }; + const addNode = (treeNode, target) => { + const id2 = uniqueNameFromString( + treeNode.id, + nodes.map((f4) => f4.id) + ); + let parent = target ? target : selectedNodes.length > 0 ? selectedNodes[0] : root.node; + let rank = target ? target.rank + 1 : parent.rank; + if (!groupableTypes.some((f4) => parent.type == f4)) { + parent = findParent(root, parent.id).node; + } else { + rank = nodes.filter((f4) => f4.parentId == parent.id).length; + } + const newTreeNode = { + ...treeNode, + id: id2, + schemaId: frameSchema.id, + parentId: parent.id + }; + const newNodes = insert( + nodes.filter((f4) => f4.parentId == parent.id).sort((a5, b4) => a5.rank - b4.rank), + rank, + newTreeNode + ).map((f4, i4) => ({ ...f4, rank: i4 })); + saveNodes(newNodes).then((f4) => selectNodes([newTreeNode])); + }; + const saveNodes = async (treeNodes, deleteNodes) => { + var _a3, _b2, _c2; + if (!tableData) { + return; + } + const newRows = ((_a3 = tableData == null ? void 0 : tableData.rows) == null ? void 0 : _a3.some((f4) => f4.id == root.id)) ? tableData.rows : [...(_b2 = tableData == null ? void 0 : tableData.rows) != null ? _b2 : [], nodeToFrame(root.node)]; + const insertRows = treeNodes.filter((f4) => !newRows.some((g4) => g4.id == f4.id)).map((f4) => nodeToFrame(f4)); + const modRows = treeNodes.filter((f4) => newRows.some((g4) => g4.id == f4.id)).map((f4) => nodeToFrame(f4)); + const newTable = { + ...tableData, + cols: (_c2 = tableData.cols) != null ? _c2 : [], + rows: [ + ...newRows.map((f4) => { + var _a4; + return (_a4 = modRows.find((g4) => g4.id == f4.id)) != null ? _a4 : f4; + }), + ...insertRows + ].filter( + (f4) => deleteNodes ? !deleteNodes.some((g4) => g4.id == f4.id) : f4 + ) + }; + await saveFrame(newTable); + }; + const moveNodeFromSchema = async (nodeId, schemaId, newParentId, styles2) => { + const oldTable = await getMDBData(); + if (!oldTable[schemaId]) + return; + const tableNodes = oldTable[schemaId].rows.map( + (g4) => frameToNode(g4) + ); + const oldSchema = schemas.find((f4) => f4.id == schemaId); + const treeNode = tableNodes.find((f4) => f4.id == nodeId); + if (!oldSchema || !treeNode) + return; + const tree = buildFrameTree( + treeNode, + tableNodes, + props2.plugin, + 0, + false, + editorProps + )[0]; + const deleteNodes = flattenToFrameNodes(tree); + const newTreeNodes = deleteNodes.map((f4) => ({ + ...f4, + schemaId: frameSchema.id, + styles: f4.id == nodeId && styles2 ? { + ...f4.styles, + ...styles2 + } : f4.styles, + parentId: f4.id == nodeId ? newParentId : f4.parentId + })); + await saveFrame({ + ...oldTable[frameSchema.id], + rows: oldTable[frameSchema.id].rows.filter( + (f4) => !deleteNodes.some((g4) => f4.schemaId == g4.schemaId && f4.id == g4.id) + ) + }); + await saveFrame({ + ...tableData, + rows: [ + ...tableData.rows, + ...newTreeNodes.map((f4) => nodeToFrame(f4)) + ] + }); + }; + const deleteNode = (treeNode) => { + const tree = buildFrameTree( + treeNode, + nodes, + props2.plugin, + 0, + false, + editorProps + )[0]; + const parent = findParent(root, treeNode.id); + const deleteNodes = flattenToFrameNodes(tree); + if (parent) { + if (parent.children.length == 1 && parent.node.type == "column") + deleteNodes.push(parent.node); + const grandParent = findParent(root, parent.id); + if ((grandParent == null ? void 0 : grandParent.children.length) == 1 && grandParent.node.type == "container") { + deleteNodes.push(grandParent.node); + } + } + saveFrame({ + ...tableData, + rows: tableData.rows.filter( + (f4) => !deleteNodes.some((g4) => f4.schemaId == g4.schemaId && f4.id == g4.id) + ) + }); + }; + const properties2 = (_a2 = tableData == null ? void 0 : tableData.cols) != null ? _a2 : []; + const selectNodes = (frames2) => { + setSelectedNodes(frames2); + }; + const delProperty = (column) => { + const mdbtable = tableData; + const newFields = mdbtable.cols.filter( + (f4, i4) => f4.name != column.name + ); + const newTable = { + ...mdbtable, + cols: newFields != null ? newFields : [] + }; + saveFrame(newTable); + }; + const newProperty = (col) => { + return saveProperty(col); + }; + const renameNode = (node, newName) => { + }; + const saveProperty = (newColumn, oldColumn) => { + const column = { + ...newColumn, + name: sanitizeColumnName(newColumn.name) + }; + const mdbtable = tableData; + if (column.name == "") { + new import_obsidian25.Notice(i18n_default.notice.noPropertyName); + return false; + } + if (!oldColumn && mdbtable.cols.find( + (f4) => f4.name.toLowerCase() == column.name.toLowerCase() + ) || oldColumn && oldColumn.name != column.name && mdbtable.cols.find( + (f4) => f4.name.toLowerCase() == column.name.toLowerCase() + )) { + new import_obsidian25.Notice(i18n_default.notice.duplicatePropertyName); + return false; + } + const oldFieldIndex = oldColumn ? mdbtable.cols.findIndex((f4) => f4.name == oldColumn.name) : -1; + const newFields = oldFieldIndex == -1 ? [...mdbtable.cols, column] : mdbtable.cols.map((f4, i4) => i4 == oldFieldIndex ? column : f4); + const newTable = { + ...mdbtable, + cols: newFields != null ? newFields : [] + }; + saveFrame(newTable); + return true; + }; + return /* @__PURE__ */ Cn.createElement(FramesEditorContext.Provider, { + value: { + root, + runRoot, + instance, + dragNode, + fastSaveState, + setDragNode, + hoverNode, + setHoverNode, + saveState, + nodes, + properties: properties2, + addNode, + deleteNode, + selectedNodes, + selectNodes, + saveProperty, + newProperty, + selectableNodeBounds, + renameNode, + delProperty, + saveNodes, + ungroupNode, + moveUp, + moveDown, + moveToRank, + moveNodeFromSchema, + groupNodes + } + }, props2.children); +}; + +// node_modules/re-resizable/lib/resizer.js +var __extends = function() { + var extendStatics = function(d5, b4) { + extendStatics = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(d6, b5) { + d6.__proto__ = b5; + } || function(d6, b5) { + for (var p3 in b5) + if (Object.prototype.hasOwnProperty.call(b5, p3)) + d6[p3] = b5[p3]; + }; + return extendStatics(d5, b4); + }; + return function(d5, b4) { + extendStatics(d5, b4); + function __() { + this.constructor = d5; + } + d5.prototype = b4 === null ? Object.create(b4) : (__.prototype = b4.prototype, new __()); + }; +}(); +var __assign2 = function() { + __assign2 = Object.assign || function(t4) { + for (var s5, i4 = 1, n2 = arguments.length; i4 < n2; i4++) { + s5 = arguments[i4]; + for (var p3 in s5) + if (Object.prototype.hasOwnProperty.call(s5, p3)) + t4[p3] = s5[p3]; + } + return t4; + }; + return __assign2.apply(this, arguments); +}; +var rowSizeBase = { + width: "100%", + height: "10px", + top: "0px", + left: "0px", + cursor: "row-resize" +}; +var colSizeBase = { + width: "10px", + height: "100%", + top: "0px", + left: "0px", + cursor: "col-resize" +}; +var edgeBase = { + width: "20px", + height: "20px", + position: "absolute" +}; +var styles = { + top: __assign2(__assign2({}, rowSizeBase), { top: "-5px" }), + right: __assign2(__assign2({}, colSizeBase), { left: void 0, right: "-5px" }), + bottom: __assign2(__assign2({}, rowSizeBase), { top: void 0, bottom: "-5px" }), + left: __assign2(__assign2({}, colSizeBase), { left: "-5px" }), + topRight: __assign2(__assign2({}, edgeBase), { right: "-10px", top: "-10px", cursor: "ne-resize" }), + bottomRight: __assign2(__assign2({}, edgeBase), { right: "-10px", bottom: "-10px", cursor: "se-resize" }), + bottomLeft: __assign2(__assign2({}, edgeBase), { left: "-10px", bottom: "-10px", cursor: "sw-resize" }), + topLeft: __assign2(__assign2({}, edgeBase), { left: "-10px", top: "-10px", cursor: "nw-resize" }) +}; +var Resizer = function(_super) { + __extends(Resizer2, _super); + function Resizer2() { + var _this = _super !== null && _super.apply(this, arguments) || this; + _this.onMouseDown = function(e4) { + _this.props.onResizeStart(e4, _this.props.direction); + }; + _this.onTouchStart = function(e4) { + _this.props.onResizeStart(e4, _this.props.direction); + }; + return _this; } - return false; -} -var reSplitAlphaNumeric = /([0-9]+)/gm; -var alphanumeric = (rowA, rowB, columnId) => { - return compareAlphanumeric(toString(rowA.getValue(columnId)).toLowerCase(), toString(rowB.getValue(columnId)).toLowerCase()); + Resizer2.prototype.render = function() { + return y("div", { className: this.props.className || "", style: __assign2(__assign2({ position: "absolute", userSelect: "none" }, styles[this.props.direction]), this.props.replaceStyles || {}), onMouseDown: this.onMouseDown, onTouchStart: this.onTouchStart }, this.props.children); + }; + return Resizer2; +}(w3); + +// node_modules/re-resizable/lib/index.js +var __extends2 = function() { + var extendStatics = function(d5, b4) { + extendStatics = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(d6, b5) { + d6.__proto__ = b5; + } || function(d6, b5) { + for (var p3 in b5) + if (Object.prototype.hasOwnProperty.call(b5, p3)) + d6[p3] = b5[p3]; + }; + return extendStatics(d5, b4); + }; + return function(d5, b4) { + extendStatics(d5, b4); + function __() { + this.constructor = d5; + } + d5.prototype = b4 === null ? Object.create(b4) : (__.prototype = b4.prototype, new __()); + }; +}(); +var __assign3 = function() { + __assign3 = Object.assign || function(t4) { + for (var s5, i4 = 1, n2 = arguments.length; i4 < n2; i4++) { + s5 = arguments[i4]; + for (var p3 in s5) + if (Object.prototype.hasOwnProperty.call(s5, p3)) + t4[p3] = s5[p3]; + } + return t4; + }; + return __assign3.apply(this, arguments); }; -var alphanumericCaseSensitive = (rowA, rowB, columnId) => { - return compareAlphanumeric(toString(rowA.getValue(columnId)), toString(rowB.getValue(columnId))); +var DEFAULT_SIZE = { + width: "auto", + height: "auto" }; -var text = (rowA, rowB, columnId) => { - return compareBasic(toString(rowA.getValue(columnId)).toLowerCase(), toString(rowB.getValue(columnId)).toLowerCase()); +var clamp = function(n2, min3, max3) { + return Math.max(Math.min(n2, max3), min3); }; -var textCaseSensitive = (rowA, rowB, columnId) => { - return compareBasic(toString(rowA.getValue(columnId)), toString(rowB.getValue(columnId))); +var snap = function(n2, size) { + return Math.round(n2 / size) * size; }; -var datetime = (rowA, rowB, columnId) => { - const a5 = rowA.getValue(columnId); - const b4 = rowB.getValue(columnId); - return a5 > b4 ? 1 : a5 < b4 ? -1 : 0; +var hasDirection = function(dir, target) { + return new RegExp(dir, "i").test(target); }; -var basic = (rowA, rowB, columnId) => { - return compareBasic(rowA.getValue(columnId), rowB.getValue(columnId)); +var isTouchEvent2 = function(event) { + return Boolean(event.touches && event.touches.length); }; -function compareBasic(a5, b4) { - return a5 === b4 ? 0 : a5 > b4 ? 1 : -1; -} -function toString(a5) { - if (typeof a5 === "number") { - if (isNaN(a5) || a5 === Infinity || a5 === -Infinity) { - return ""; - } - return String(a5); +var isMouseEvent2 = function(event) { + return Boolean((event.clientX || event.clientX === 0) && (event.clientY || event.clientY === 0)); +}; +var findClosestSnap = function(n2, snapArray, snapGap) { + if (snapGap === void 0) { + snapGap = 0; } - if (typeof a5 === "string") { - return a5; + var closestGapIndex = snapArray.reduce(function(prev, curr, index) { + return Math.abs(curr - n2) < Math.abs(snapArray[prev] - n2) ? index : prev; + }, 0); + var gap = Math.abs(snapArray[closestGapIndex] - n2); + return snapGap === 0 || gap < snapGap ? snapArray[closestGapIndex] : n2; +}; +var getStringSize = function(n2) { + n2 = n2.toString(); + if (n2 === "auto") { + return n2; } - return ""; -} -function compareAlphanumeric(aStr, bStr) { - const a5 = aStr.split(reSplitAlphaNumeric).filter(Boolean); - const b4 = bStr.split(reSplitAlphaNumeric).filter(Boolean); - while (a5.length && b4.length) { - const aa = a5.shift(); - const bb = b4.shift(); - const an2 = parseInt(aa, 10); - const bn2 = parseInt(bb, 10); - const combo = [an2, bn2].sort(); - if (isNaN(combo[0])) { - if (aa > bb) { - return 1; - } - if (bb > aa) { - return -1; - } - continue; + if (n2.endsWith("px")) { + return n2; + } + if (n2.endsWith("%")) { + return n2; + } + if (n2.endsWith("vh")) { + return n2; + } + if (n2.endsWith("vw")) { + return n2; + } + if (n2.endsWith("vmax")) { + return n2; + } + if (n2.endsWith("vmin")) { + return n2; + } + return n2 + "px"; +}; +var getPixelSize = function(size, parentSize, innerWidth2, innerHeight2) { + if (size && typeof size === "string") { + if (size.endsWith("px")) { + return Number(size.replace("px", "")); } - if (isNaN(combo[1])) { - return isNaN(an2) ? -1 : 1; + if (size.endsWith("%")) { + var ratio = Number(size.replace("%", "")) / 100; + return parentSize * ratio; } - if (an2 > bn2) { - return 1; + if (size.endsWith("vw")) { + var ratio = Number(size.replace("vw", "")) / 100; + return innerWidth2 * ratio; } - if (bn2 > an2) { - return -1; + if (size.endsWith("vh")) { + var ratio = Number(size.replace("vh", "")) / 100; + return innerHeight2 * ratio; } } - return a5.length - b4.length; -} -var sortingFns = { - alphanumeric, - alphanumericCaseSensitive, - text, - textCaseSensitive, - datetime, - basic + return size; }; -var Sorting = { - getInitialState: (state) => { - return { - sorting: [], - ...state - }; - }, - getDefaultColumnDef: () => { - return { - sortingFn: "auto" - }; - }, - getDefaultOptions: (table) => { - return { - onSortingChange: makeStateUpdater("sorting", table), - isMultiSortEvent: (e4) => { - return e4.shiftKey; - } - }; - }, - createColumn: (column, table) => { - return { - getAutoSortingFn: () => { - const firstRows = table.getFilteredRowModel().flatRows.slice(10); - let isString = false; - for (const row of firstRows) { - const value = row == null ? void 0 : row.getValue(column.id); - if (Object.prototype.toString.call(value) === "[object Date]") { - return sortingFns.datetime; - } - if (typeof value === "string") { - isString = true; - if (value.split(reSplitAlphaNumeric).length > 1) { - return sortingFns.alphanumeric; - } - } - } - if (isString) { - return sortingFns.text; - } - return sortingFns.basic; - }, - getAutoSortDir: () => { - const firstRow = table.getFilteredRowModel().flatRows[0]; - const value = firstRow == null ? void 0 : firstRow.getValue(column.id); - if (typeof value === "string") { - return "asc"; - } - return "desc"; - }, - getSortingFn: () => { - var _table$options$sortin, _table$options$sortin2; - if (!column) { - throw new Error(); - } - return isFunction(column.columnDef.sortingFn) ? column.columnDef.sortingFn : column.columnDef.sortingFn === "auto" ? column.getAutoSortingFn() : (_table$options$sortin = (_table$options$sortin2 = table.options.sortingFns) == null ? void 0 : _table$options$sortin2[column.columnDef.sortingFn]) != null ? _table$options$sortin : sortingFns[column.columnDef.sortingFn]; - }, - toggleSorting: (desc, multi) => { - const nextSortingOrder = column.getNextSortingOrder(); - const hasManualValue = typeof desc !== "undefined" && desc !== null; - table.setSorting((old) => { - const existingSorting = old == null ? void 0 : old.find((d5) => d5.id === column.id); - const existingIndex = old == null ? void 0 : old.findIndex((d5) => d5.id === column.id); - let newSorting = []; - let sortAction; - let nextDesc = hasManualValue ? desc : nextSortingOrder === "desc"; - if (old != null && old.length && column.getCanMultiSort() && multi) { - if (existingSorting) { - sortAction = "toggle"; - } else { - sortAction = "add"; - } - } else { - if (old != null && old.length && existingIndex !== old.length - 1) { - sortAction = "replace"; - } else if (existingSorting) { - sortAction = "toggle"; - } else { - sortAction = "replace"; - } - } - if (sortAction === "toggle") { - if (!hasManualValue) { - if (!nextSortingOrder) { - sortAction = "remove"; - } - } - } - if (sortAction === "add") { - var _table$options$maxMul; - newSorting = [...old, { - id: column.id, - desc: nextDesc - }]; - newSorting.splice(0, newSorting.length - ((_table$options$maxMul = table.options.maxMultiSortColCount) != null ? _table$options$maxMul : Number.MAX_SAFE_INTEGER)); - } else if (sortAction === "toggle") { - newSorting = old.map((d5) => { - if (d5.id === column.id) { - return { - ...d5, - desc: nextDesc - }; - } - return d5; - }); - } else if (sortAction === "remove") { - newSorting = old.filter((d5) => d5.id !== column.id); - } else { - newSorting = [{ - id: column.id, - desc: nextDesc - }]; - } - return newSorting; - }); - }, - getFirstSortDir: () => { - var _ref, _column$columnDef$sor; - const sortDescFirst = (_ref = (_column$columnDef$sor = column.columnDef.sortDescFirst) != null ? _column$columnDef$sor : table.options.sortDescFirst) != null ? _ref : column.getAutoSortDir() === "desc"; - return sortDescFirst ? "desc" : "asc"; - }, - getNextSortingOrder: (multi) => { - var _table$options$enable, _table$options$enable2; - const firstSortDirection = column.getFirstSortDir(); - const isSorted = column.getIsSorted(); - if (!isSorted) { - return firstSortDirection; - } - if (isSorted !== firstSortDirection && ((_table$options$enable = table.options.enableSortingRemoval) != null ? _table$options$enable : true) && (multi ? (_table$options$enable2 = table.options.enableMultiRemove) != null ? _table$options$enable2 : true : true)) { - return false; - } - return isSorted === "desc" ? "asc" : "desc"; - }, - getCanSort: () => { - var _column$columnDef$ena, _table$options$enable3; - return ((_column$columnDef$ena = column.columnDef.enableSorting) != null ? _column$columnDef$ena : true) && ((_table$options$enable3 = table.options.enableSorting) != null ? _table$options$enable3 : true) && !!column.accessorFn; - }, - getCanMultiSort: () => { - var _ref2, _column$columnDef$ena2; - return (_ref2 = (_column$columnDef$ena2 = column.columnDef.enableMultiSort) != null ? _column$columnDef$ena2 : table.options.enableMultiSort) != null ? _ref2 : !!column.accessorFn; - }, - getIsSorted: () => { - var _table$getState$sorti; - const columnSort = (_table$getState$sorti = table.getState().sorting) == null ? void 0 : _table$getState$sorti.find((d5) => d5.id === column.id); - return !columnSort ? false : columnSort.desc ? "desc" : "asc"; - }, - getSortIndex: () => { - var _table$getState$sorti2, _table$getState$sorti3; - return (_table$getState$sorti2 = (_table$getState$sorti3 = table.getState().sorting) == null ? void 0 : _table$getState$sorti3.findIndex((d5) => d5.id === column.id)) != null ? _table$getState$sorti2 : -1; - }, - clearSorting: () => { - table.setSorting((old) => old != null && old.length ? old.filter((d5) => d5.id !== column.id) : []); - }, - getToggleSortingHandler: () => { - const canSort = column.getCanSort(); - return (e4) => { - if (!canSort) - return; - e4.persist == null ? void 0 : e4.persist(); - column.toggleSorting == null ? void 0 : column.toggleSorting(void 0, column.getCanMultiSort() ? table.options.isMultiSortEvent == null ? void 0 : table.options.isMultiSortEvent(e4) : false); - }; - } - }; - }, - createTable: (table) => { - return { - setSorting: (updater) => table.options.onSortingChange == null ? void 0 : table.options.onSortingChange(updater), - resetSorting: (defaultState) => { - var _table$initialState$s, _table$initialState; - table.setSorting(defaultState ? [] : (_table$initialState$s = (_table$initialState = table.initialState) == null ? void 0 : _table$initialState.sorting) != null ? _table$initialState$s : []); - }, - getPreSortedRowModel: () => table.getGroupedRowModel(), - getSortedRowModel: () => { - if (!table._getSortedRowModel && table.options.getSortedRowModel) { - table._getSortedRowModel = table.options.getSortedRowModel(table); - } - if (table.options.manualSorting || !table._getSortedRowModel) { - return table.getPreSortedRowModel(); - } - return table._getSortedRowModel(); - } - }; - } +var calculateNewMax = function(parentSize, innerWidth2, innerHeight2, maxWidth, maxHeight, minWidth, minHeight) { + maxWidth = getPixelSize(maxWidth, parentSize.width, innerWidth2, innerHeight2); + maxHeight = getPixelSize(maxHeight, parentSize.height, innerWidth2, innerHeight2); + minWidth = getPixelSize(minWidth, parentSize.width, innerWidth2, innerHeight2); + minHeight = getPixelSize(minHeight, parentSize.height, innerWidth2, innerHeight2); + return { + maxWidth: typeof maxWidth === "undefined" ? void 0 : Number(maxWidth), + maxHeight: typeof maxHeight === "undefined" ? void 0 : Number(maxHeight), + minWidth: typeof minWidth === "undefined" ? void 0 : Number(minWidth), + minHeight: typeof minHeight === "undefined" ? void 0 : Number(minHeight) + }; }; -var Visibility = { - getInitialState: (state) => { - return { - columnVisibility: {}, - ...state - }; - }, - getDefaultOptions: (table) => { - return { - onColumnVisibilityChange: makeStateUpdater("columnVisibility", table) - }; - }, - createColumn: (column, table) => { - return { - toggleVisibility: (value) => { - if (column.getCanHide()) { - table.setColumnVisibility((old) => ({ - ...old, - [column.id]: value != null ? value : !column.getIsVisible() - })); - } - }, - getIsVisible: () => { - var _table$getState$colum, _table$getState$colum2; - return (_table$getState$colum = (_table$getState$colum2 = table.getState().columnVisibility) == null ? void 0 : _table$getState$colum2[column.id]) != null ? _table$getState$colum : true; - }, - getCanHide: () => { - var _column$columnDef$ena, _table$options$enable; - return ((_column$columnDef$ena = column.columnDef.enableHiding) != null ? _column$columnDef$ena : true) && ((_table$options$enable = table.options.enableHiding) != null ? _table$options$enable : true); - }, - getToggleVisibilityHandler: () => { - return (e4) => { - column.toggleVisibility == null ? void 0 : column.toggleVisibility(e4.target.checked); - }; +var definedProps = [ + "as", + "style", + "className", + "grid", + "snap", + "bounds", + "boundsByDirection", + "size", + "defaultSize", + "minWidth", + "minHeight", + "maxWidth", + "maxHeight", + "lockAspectRatio", + "lockAspectRatioExtraWidth", + "lockAspectRatioExtraHeight", + "enable", + "handleStyles", + "handleClasses", + "handleWrapperStyle", + "handleWrapperClass", + "children", + "onResizeStart", + "onResize", + "onResizeStop", + "handleComponent", + "scale", + "resizeRatio", + "snapGap" +]; +var baseClassName = "__resizable_base__"; +var Resizable = function(_super) { + __extends2(Resizable2, _super); + function Resizable2(props2) { + var _this = _super.call(this, props2) || this; + _this.ratio = 1; + _this.resizable = null; + _this.parentLeft = 0; + _this.parentTop = 0; + _this.resizableLeft = 0; + _this.resizableRight = 0; + _this.resizableTop = 0; + _this.resizableBottom = 0; + _this.targetLeft = 0; + _this.targetTop = 0; + _this.appendBase = function() { + if (!_this.resizable || !_this.window) { + return null; + } + var parent = _this.parentNode; + if (!parent) { + return null; } + var element = _this.window.document.createElement("div"); + element.style.width = "100%"; + element.style.height = "100%"; + element.style.position = "absolute"; + element.style.transform = "scale(0, 0)"; + element.style.left = "0"; + element.style.flex = "0 0 100%"; + if (element.classList) { + element.classList.add(baseClassName); + } else { + element.className += baseClassName; + } + parent.appendChild(element); + return element; }; - }, - createRow: (row, table) => { - return { - _getAllVisibleCells: memo(() => [row.getAllCells(), table.getState().columnVisibility], (cells) => { - return cells.filter((cell) => cell.column.getIsVisible()); - }, { - key: false, - debug: () => { - var _table$options$debugA; - return (_table$options$debugA = table.options.debugAll) != null ? _table$options$debugA : table.options.debugRows; - } - }), - getVisibleCells: memo(() => [row.getLeftVisibleCells(), row.getCenterVisibleCells(), row.getRightVisibleCells()], (left, center, right) => [...left, ...center, ...right], { - key: "row.getVisibleCells", - debug: () => { - var _table$options$debugA2; - return (_table$options$debugA2 = table.options.debugAll) != null ? _table$options$debugA2 : table.options.debugRows; - } - }) + _this.removeBase = function(base2) { + var parent = _this.parentNode; + if (!parent) { + return; + } + parent.removeChild(base2); }; - }, - createTable: (table) => { - const makeVisibleColumnsMethod = (key2, getColumns) => { - return memo(() => [getColumns(), getColumns().filter((d5) => d5.getIsVisible()).map((d5) => d5.id).join("_")], (columns) => { - return columns.filter((d5) => d5.getIsVisible == null ? void 0 : d5.getIsVisible()); - }, { - key: key2, - debug: () => { - var _table$options$debugA3; - return (_table$options$debugA3 = table.options.debugAll) != null ? _table$options$debugA3 : table.options.debugColumns; - } - }); + _this.ref = function(c4) { + if (c4) { + _this.resizable = c4; + } }; - return { - getVisibleFlatColumns: makeVisibleColumnsMethod("getVisibleFlatColumns", () => table.getAllFlatColumns()), - getVisibleLeafColumns: makeVisibleColumnsMethod("getVisibleLeafColumns", () => table.getAllLeafColumns()), - getLeftVisibleLeafColumns: makeVisibleColumnsMethod("getLeftVisibleLeafColumns", () => table.getLeftLeafColumns()), - getRightVisibleLeafColumns: makeVisibleColumnsMethod("getRightVisibleLeafColumns", () => table.getRightLeafColumns()), - getCenterVisibleLeafColumns: makeVisibleColumnsMethod("getCenterVisibleLeafColumns", () => table.getCenterLeafColumns()), - setColumnVisibility: (updater) => table.options.onColumnVisibilityChange == null ? void 0 : table.options.onColumnVisibilityChange(updater), - resetColumnVisibility: (defaultState) => { - var _table$initialState$c; - table.setColumnVisibility(defaultState ? {} : (_table$initialState$c = table.initialState.columnVisibility) != null ? _table$initialState$c : {}); + _this.state = { + isResizing: false, + width: typeof (_this.propsSize && _this.propsSize.width) === "undefined" ? "auto" : _this.propsSize && _this.propsSize.width, + height: typeof (_this.propsSize && _this.propsSize.height) === "undefined" ? "auto" : _this.propsSize && _this.propsSize.height, + direction: "right", + original: { + x: 0, + y: 0, + width: 0, + height: 0 }, - toggleAllColumnsVisible: (value) => { - var _value; - value = (_value = value) != null ? _value : !table.getIsAllColumnsVisible(); - table.setColumnVisibility(table.getAllLeafColumns().reduce((obj, column) => ({ - ...obj, - [column.id]: !value ? !(column.getCanHide != null && column.getCanHide()) : value - }), {})); + backgroundStyle: { + height: "100%", + width: "100%", + backgroundColor: "rgba(0,0,0,0)", + cursor: "auto", + opacity: 0, + position: "fixed", + zIndex: 9999, + top: "0", + left: "0", + bottom: "0", + right: "0" }, - getIsAllColumnsVisible: () => !table.getAllLeafColumns().some((column) => !(column.getIsVisible != null && column.getIsVisible())), - getIsSomeColumnsVisible: () => table.getAllLeafColumns().some((column) => column.getIsVisible == null ? void 0 : column.getIsVisible()), - getToggleAllColumnsVisibilityHandler: () => { - return (e4) => { - var _target; - table.toggleAllColumnsVisible((_target = e4.target) == null ? void 0 : _target.checked); - }; - } - }; - } -}; -var features = [Headers, Visibility, Ordering, Pinning, Filters, Sorting, Grouping, Expanding, Pagination, RowSelection, ColumnSizing]; -function createTable(options) { - var _options$initialState; - if (options.debugAll || options.debugTable) { - console.info("Creating Table Instance..."); - } - let table = { - _features: features - }; - const defaultOptions3 = table._features.reduce((obj, feature) => { - return Object.assign(obj, feature.getDefaultOptions == null ? void 0 : feature.getDefaultOptions(table)); - }, {}); - const mergeOptions = (options2) => { - if (table.options.mergeOptions) { - return table.options.mergeOptions(defaultOptions3, options2); - } - return { - ...defaultOptions3, - ...options2 + flexBasis: void 0 }; - }; - const coreInitialState = {}; - let initialState = { - ...coreInitialState, - ...(_options$initialState = options.initialState) != null ? _options$initialState : {} - }; - table._features.forEach((feature) => { - var _feature$getInitialSt; - initialState = (_feature$getInitialSt = feature.getInitialState == null ? void 0 : feature.getInitialState(initialState)) != null ? _feature$getInitialSt : initialState; - }); - const queued = []; - let queuedTimeout = false; - const coreInstance = { - _features: features, - options: { - ...defaultOptions3, - ...options - }, - initialState, - _queue: (cb) => { - queued.push(cb); - if (!queuedTimeout) { - queuedTimeout = true; - Promise.resolve().then(() => { - while (queued.length) { - queued.shift()(); - } - queuedTimeout = false; - }).catch((error) => setTimeout(() => { - throw error; - })); + _this.onResizeStart = _this.onResizeStart.bind(_this); + _this.onMouseMove = _this.onMouseMove.bind(_this); + _this.onMouseUp = _this.onMouseUp.bind(_this); + return _this; + } + Object.defineProperty(Resizable2.prototype, "parentNode", { + get: function() { + if (!this.resizable) { + return null; } + return this.resizable.parentNode; }, - reset: () => { - table.setState(table.initialState); - }, - setOptions: (updater) => { - const newOptions = functionalUpdate(updater, table.options); - table.options = mergeOptions(newOptions); - }, - getState: () => { - return table.options.state; - }, - setState: (updater) => { - table.options.onStateChange == null ? void 0 : table.options.onStateChange(updater); - }, - _getRowId: (row, index, parent) => { - var _table$options$getRow; - return (_table$options$getRow = table.options.getRowId == null ? void 0 : table.options.getRowId(row, index, parent)) != null ? _table$options$getRow : `${parent ? [parent.id, index].join(".") : index}`; - }, - getCoreRowModel: () => { - if (!table._getCoreRowModel) { - table._getCoreRowModel = table.options.getCoreRowModel(table); + enumerable: false, + configurable: true + }); + Object.defineProperty(Resizable2.prototype, "window", { + get: function() { + if (!this.resizable) { + return null; } - return table._getCoreRowModel(); + if (!this.resizable.ownerDocument) { + return null; + } + return this.resizable.ownerDocument.defaultView; }, - getRowModel: () => { - return table.getPaginationRowModel(); + enumerable: false, + configurable: true + }); + Object.defineProperty(Resizable2.prototype, "propsSize", { + get: function() { + return this.props.size || this.props.defaultSize || DEFAULT_SIZE; }, - getRow: (id2) => { - const row = table.getRowModel().rowsById[id2]; - if (!row) { - if (true) { - throw new Error(`getRow expected an ID, but got ${id2}`); - } - throw new Error(); - } - return row; + enumerable: false, + configurable: true + }); + Object.defineProperty(Resizable2.prototype, "size", { + get: function() { + var width = 0; + var height = 0; + if (this.resizable && this.window) { + var orgWidth = this.resizable.offsetWidth; + var orgHeight = this.resizable.offsetHeight; + var orgPosition = this.resizable.style.position; + if (orgPosition !== "relative") { + this.resizable.style.position = "relative"; + } + width = this.resizable.style.width !== "auto" ? this.resizable.offsetWidth : orgWidth; + height = this.resizable.style.height !== "auto" ? this.resizable.offsetHeight : orgHeight; + this.resizable.style.position = orgPosition; + } + return { width, height }; }, - _getDefaultColumnDef: memo(() => [table.options.defaultColumn], (defaultColumn) => { - var _defaultColumn; - defaultColumn = (_defaultColumn = defaultColumn) != null ? _defaultColumn : {}; - return { - header: (props2) => { - const resolvedColumnDef = props2.header.column.columnDef; - if (resolvedColumnDef.accessorKey) { - return resolvedColumnDef.accessorKey; - } - if (resolvedColumnDef.accessorFn) { - return resolvedColumnDef.id; - } - return null; - }, - cell: (props2) => { - var _props$renderValue$to, _props$renderValue; - return (_props$renderValue$to = (_props$renderValue = props2.renderValue()) == null ? void 0 : _props$renderValue.toString == null ? void 0 : _props$renderValue.toString()) != null ? _props$renderValue$to : null; - }, - ...table._features.reduce((obj, feature) => { - return Object.assign(obj, feature.getDefaultColumnDef == null ? void 0 : feature.getDefaultColumnDef()); - }, {}), - ...defaultColumn - }; - }, { - debug: () => { - var _table$options$debugA; - return (_table$options$debugA = table.options.debugAll) != null ? _table$options$debugA : table.options.debugColumns; - }, - key: "getDefaultColumnDef" - }), - _getColumnDefs: () => table.options.columns, - getAllColumns: memo(() => [table._getColumnDefs()], (columnDefs) => { - const recurseColumns = function(columnDefs2, parent, depth) { - if (depth === void 0) { - depth = 0; - } - return columnDefs2.map((columnDef) => { - const column = createColumn(table, columnDef, depth, parent); - const groupingColumnDef = columnDef; - column.columns = groupingColumnDef.columns ? recurseColumns(groupingColumnDef.columns, column, depth + 1) : []; - return column; - }); + enumerable: false, + configurable: true + }); + Object.defineProperty(Resizable2.prototype, "sizeStyle", { + get: function() { + var _this = this; + var size = this.props.size; + var getSize = function(key2) { + if (typeof _this.state[key2] === "undefined" || _this.state[key2] === "auto") { + return "auto"; + } + if (_this.propsSize && _this.propsSize[key2] && _this.propsSize[key2].toString().endsWith("%")) { + if (_this.state[key2].toString().endsWith("%")) { + return _this.state[key2].toString(); + } + var parentSize = _this.getParentSize(); + var value = Number(_this.state[key2].toString().replace("px", "")); + var percent = value / parentSize[key2] * 100; + return percent + "%"; + } + return getStringSize(_this.state[key2]); }; - return recurseColumns(columnDefs); - }, { - key: "getAllColumns", - debug: () => { - var _table$options$debugA2; - return (_table$options$debugA2 = table.options.debugAll) != null ? _table$options$debugA2 : table.options.debugColumns; - } - }), - getAllFlatColumns: memo(() => [table.getAllColumns()], (allColumns) => { - return allColumns.flatMap((column) => { - return column.getFlatColumns(); + var width = size && typeof size.width !== "undefined" && !this.state.isResizing ? getStringSize(size.width) : getSize("width"); + var height = size && typeof size.height !== "undefined" && !this.state.isResizing ? getStringSize(size.height) : getSize("height"); + return { width, height }; + }, + enumerable: false, + configurable: true + }); + Resizable2.prototype.getParentSize = function() { + if (!this.parentNode) { + if (!this.window) { + return { width: 0, height: 0 }; + } + return { width: this.window.innerWidth, height: this.window.innerHeight }; + } + var base2 = this.appendBase(); + if (!base2) { + return { width: 0, height: 0 }; + } + var wrapChanged = false; + var wrap = this.parentNode.style.flexWrap; + if (wrap !== "wrap") { + wrapChanged = true; + this.parentNode.style.flexWrap = "wrap"; + } + base2.style.position = "relative"; + base2.style.minWidth = "100%"; + base2.style.minHeight = "100%"; + var size = { + width: base2.offsetWidth, + height: base2.offsetHeight + }; + if (wrapChanged) { + this.parentNode.style.flexWrap = wrap; + } + this.removeBase(base2); + return size; + }; + Resizable2.prototype.bindEvents = function() { + if (this.window) { + this.window.addEventListener("mouseup", this.onMouseUp); + this.window.addEventListener("mousemove", this.onMouseMove); + this.window.addEventListener("mouseleave", this.onMouseUp); + this.window.addEventListener("touchmove", this.onMouseMove, { + capture: true, + passive: false }); - }, { - key: "getAllFlatColumns", - debug: () => { - var _table$options$debugA3; - return (_table$options$debugA3 = table.options.debugAll) != null ? _table$options$debugA3 : table.options.debugColumns; - } - }), - _getAllFlatColumnsById: memo(() => [table.getAllFlatColumns()], (flatColumns) => { - return flatColumns.reduce((acc, column) => { - acc[column.id] = column; - return acc; - }, {}); - }, { - key: "getAllFlatColumnsById", - debug: () => { - var _table$options$debugA4; - return (_table$options$debugA4 = table.options.debugAll) != null ? _table$options$debugA4 : table.options.debugColumns; - } - }), - getAllLeafColumns: memo(() => [table.getAllColumns(), table._getOrderColumnsFn()], (allColumns, orderColumns2) => { - let leafColumns = allColumns.flatMap((column) => column.getLeafColumns()); - return orderColumns2(leafColumns); - }, { - key: "getAllLeafColumns", - debug: () => { - var _table$options$debugA5; - return (_table$options$debugA5 = table.options.debugAll) != null ? _table$options$debugA5 : table.options.debugColumns; - } - }), - getColumn: (columnId) => { - const column = table._getAllFlatColumnsById()[columnId]; - if (!column) { - console.error(`[Table] Column with id '${columnId}' does not exist.`); - } - return column; + this.window.addEventListener("touchend", this.onMouseUp); } }; - Object.assign(table, coreInstance); - table._features.forEach((feature) => { - return Object.assign(table, feature.createTable == null ? void 0 : feature.createTable(table)); - }); - return table; -} -function createCell(table, row, column, columnId) { - const getRenderValue = () => { - var _cell$getValue; - return (_cell$getValue = cell.getValue()) != null ? _cell$getValue : table.options.renderFallbackValue; + Resizable2.prototype.unbindEvents = function() { + if (this.window) { + this.window.removeEventListener("mouseup", this.onMouseUp); + this.window.removeEventListener("mousemove", this.onMouseMove); + this.window.removeEventListener("mouseleave", this.onMouseUp); + this.window.removeEventListener("touchmove", this.onMouseMove, true); + this.window.removeEventListener("touchend", this.onMouseUp); + } }; - const cell = { - id: `${row.id}_${column.id}`, - row, - column, - getValue: () => row.getValue(columnId), - renderValue: getRenderValue, - getContext: memo(() => [table, column, row, cell], (table2, column2, row2, cell2) => ({ - table: table2, - column: column2, - row: row2, - cell: cell2, - getValue: cell2.getValue, - renderValue: cell2.renderValue - }), { - key: "cell.getContext", - debug: () => table.options.debugAll - }) + Resizable2.prototype.componentDidMount = function() { + if (!this.resizable || !this.window) { + return; + } + var computedStyle = this.window.getComputedStyle(this.resizable); + this.setState({ + width: this.state.width || this.size.width, + height: this.state.height || this.size.height, + flexBasis: computedStyle.flexBasis !== "auto" ? computedStyle.flexBasis : void 0 + }); }; - table._features.forEach((feature) => { - Object.assign(cell, feature.createCell == null ? void 0 : feature.createCell(cell, column, row, table)); - }, {}); - return cell; -} -var createRow = (table, id2, original, rowIndex, depth, subRows) => { - let row = { - id: id2, - index: rowIndex, - original, - depth, - _valuesCache: {}, - _uniqueValuesCache: {}, - getValue: (columnId) => { - if (row._valuesCache.hasOwnProperty(columnId)) { - return row._valuesCache[columnId]; - } - const column = table.getColumn(columnId); - if (!(column != null && column.accessorFn)) { - return void 0; - } - row._valuesCache[columnId] = column.accessorFn(row.original, rowIndex); - return row._valuesCache[columnId]; - }, - getUniqueValues: (columnId) => { - if (row._uniqueValuesCache.hasOwnProperty(columnId)) { - return row._uniqueValuesCache[columnId]; - } - const column = table.getColumn(columnId); - if (!(column != null && column.accessorFn)) { - return void 0; + Resizable2.prototype.componentWillUnmount = function() { + if (this.window) { + this.unbindEvents(); + } + }; + Resizable2.prototype.createSizeForCssProperty = function(newSize, kind) { + var propsSize = this.propsSize && this.propsSize[kind]; + return this.state[kind] === "auto" && this.state.original[kind] === newSize && (typeof propsSize === "undefined" || propsSize === "auto") ? "auto" : newSize; + }; + Resizable2.prototype.calculateNewMaxFromBoundary = function(maxWidth, maxHeight) { + var boundsByDirection = this.props.boundsByDirection; + var direction = this.state.direction; + var widthByDirection = boundsByDirection && hasDirection("left", direction); + var heightByDirection = boundsByDirection && hasDirection("top", direction); + var boundWidth; + var boundHeight; + if (this.props.bounds === "parent") { + var parent_1 = this.parentNode; + if (parent_1) { + boundWidth = widthByDirection ? this.resizableRight - this.parentLeft : parent_1.offsetWidth + (this.parentLeft - this.resizableLeft); + boundHeight = heightByDirection ? this.resizableBottom - this.parentTop : parent_1.offsetHeight + (this.parentTop - this.resizableTop); + } + } else if (this.props.bounds === "window") { + if (this.window) { + boundWidth = widthByDirection ? this.resizableRight : this.window.innerWidth - this.resizableLeft; + boundHeight = heightByDirection ? this.resizableBottom : this.window.innerHeight - this.resizableTop; + } + } else if (this.props.bounds) { + boundWidth = widthByDirection ? this.resizableRight - this.targetLeft : this.props.bounds.offsetWidth + (this.targetLeft - this.resizableLeft); + boundHeight = heightByDirection ? this.resizableBottom - this.targetTop : this.props.bounds.offsetHeight + (this.targetTop - this.resizableTop); + } + if (boundWidth && Number.isFinite(boundWidth)) { + maxWidth = maxWidth && maxWidth < boundWidth ? maxWidth : boundWidth; + } + if (boundHeight && Number.isFinite(boundHeight)) { + maxHeight = maxHeight && maxHeight < boundHeight ? maxHeight : boundHeight; + } + return { maxWidth, maxHeight }; + }; + Resizable2.prototype.calculateNewSizeFromDirection = function(clientX, clientY) { + var scale = this.props.scale || 1; + var resizeRatio = this.props.resizeRatio || 1; + var _a2 = this.state, direction = _a2.direction, original = _a2.original; + var _b2 = this.props, lockAspectRatio = _b2.lockAspectRatio, lockAspectRatioExtraHeight = _b2.lockAspectRatioExtraHeight, lockAspectRatioExtraWidth = _b2.lockAspectRatioExtraWidth; + var newWidth = original.width; + var newHeight = original.height; + var extraHeight = lockAspectRatioExtraHeight || 0; + var extraWidth = lockAspectRatioExtraWidth || 0; + if (hasDirection("right", direction)) { + newWidth = original.width + (clientX - original.x) * resizeRatio / scale; + if (lockAspectRatio) { + newHeight = (newWidth - extraWidth) / this.ratio + extraHeight; } - if (!column.columnDef.getUniqueValues) { - row._uniqueValuesCache[columnId] = [row.getValue(columnId)]; - return row._uniqueValuesCache[columnId]; + } + if (hasDirection("left", direction)) { + newWidth = original.width - (clientX - original.x) * resizeRatio / scale; + if (lockAspectRatio) { + newHeight = (newWidth - extraWidth) / this.ratio + extraHeight; } - row._uniqueValuesCache[columnId] = column.columnDef.getUniqueValues(row.original, rowIndex); - return row._uniqueValuesCache[columnId]; - }, - renderValue: (columnId) => { - var _row$getValue; - return (_row$getValue = row.getValue(columnId)) != null ? _row$getValue : table.options.renderFallbackValue; - }, - subRows: subRows != null ? subRows : [], - getLeafRows: () => flattenBy(row.subRows, (d5) => d5.subRows), - getAllCells: memo(() => [table.getAllLeafColumns()], (leafColumns) => { - return leafColumns.map((column) => { - return createCell(table, row, column, column.id); - }); - }, { - key: "row.getAllCells", - debug: () => { - var _table$options$debugA; - return (_table$options$debugA = table.options.debugAll) != null ? _table$options$debugA : table.options.debugRows; + } + if (hasDirection("bottom", direction)) { + newHeight = original.height + (clientY - original.y) * resizeRatio / scale; + if (lockAspectRatio) { + newWidth = (newHeight - extraHeight) * this.ratio + extraWidth; } - }), - _getAllCellsByColumnId: memo(() => [row.getAllCells()], (allCells) => { - return allCells.reduce((acc, cell) => { - acc[cell.column.id] = cell; - return acc; - }, {}); - }, { - key: false, - debug: () => { - var _table$options$debugA2; - return (_table$options$debugA2 = table.options.debugAll) != null ? _table$options$debugA2 : table.options.debugRows; + } + if (hasDirection("top", direction)) { + newHeight = original.height - (clientY - original.y) * resizeRatio / scale; + if (lockAspectRatio) { + newWidth = (newHeight - extraHeight) * this.ratio + extraWidth; } - }) + } + return { newWidth, newHeight }; }; - for (let i4 = 0; i4 < table._features.length; i4++) { - const feature = table._features[i4]; - Object.assign(row, feature == null ? void 0 : feature.createRow == null ? void 0 : feature.createRow(row, table)); - } - return row; -}; -function getCoreRowModel() { - return (table) => memo(() => [table.options.data], (data) => { - const rowModel = { - rows: [], - flatRows: [], - rowsById: {} - }; - const accessRows = function(originalRows, depth, parent) { - if (depth === void 0) { - depth = 0; - } - const rows = []; - for (let i4 = 0; i4 < originalRows.length; i4++) { - const row = createRow(table, table._getRowId(originalRows[i4], i4, parent), originalRows[i4], i4, depth); - rowModel.flatRows.push(row); - rowModel.rowsById[row.id] = row; - rows.push(row); - if (table.options.getSubRows) { - var _row$originalSubRows; - row.originalSubRows = table.options.getSubRows(originalRows[i4], i4); - if ((_row$originalSubRows = row.originalSubRows) != null && _row$originalSubRows.length) { - row.subRows = accessRows(row.originalSubRows, depth + 1, row); - } + Resizable2.prototype.calculateNewSizeFromAspectRatio = function(newWidth, newHeight, max3, min3) { + var _a2 = this.props, lockAspectRatio = _a2.lockAspectRatio, lockAspectRatioExtraHeight = _a2.lockAspectRatioExtraHeight, lockAspectRatioExtraWidth = _a2.lockAspectRatioExtraWidth; + var computedMinWidth = typeof min3.width === "undefined" ? 10 : min3.width; + var computedMaxWidth = typeof max3.width === "undefined" || max3.width < 0 ? newWidth : max3.width; + var computedMinHeight = typeof min3.height === "undefined" ? 10 : min3.height; + var computedMaxHeight = typeof max3.height === "undefined" || max3.height < 0 ? newHeight : max3.height; + var extraHeight = lockAspectRatioExtraHeight || 0; + var extraWidth = lockAspectRatioExtraWidth || 0; + if (lockAspectRatio) { + var extraMinWidth = (computedMinHeight - extraHeight) * this.ratio + extraWidth; + var extraMaxWidth = (computedMaxHeight - extraHeight) * this.ratio + extraWidth; + var extraMinHeight = (computedMinWidth - extraWidth) / this.ratio + extraHeight; + var extraMaxHeight = (computedMaxWidth - extraWidth) / this.ratio + extraHeight; + var lockedMinWidth = Math.max(computedMinWidth, extraMinWidth); + var lockedMaxWidth = Math.min(computedMaxWidth, extraMaxWidth); + var lockedMinHeight = Math.max(computedMinHeight, extraMinHeight); + var lockedMaxHeight = Math.min(computedMaxHeight, extraMaxHeight); + newWidth = clamp(newWidth, lockedMinWidth, lockedMaxWidth); + newHeight = clamp(newHeight, lockedMinHeight, lockedMaxHeight); + } else { + newWidth = clamp(newWidth, computedMinWidth, computedMaxWidth); + newHeight = clamp(newHeight, computedMinHeight, computedMaxHeight); + } + return { newWidth, newHeight }; + }; + Resizable2.prototype.setBoundingClientRect = function() { + if (this.props.bounds === "parent") { + var parent_2 = this.parentNode; + if (parent_2) { + var parentRect = parent_2.getBoundingClientRect(); + this.parentLeft = parentRect.left; + this.parentTop = parentRect.top; + } + } + if (this.props.bounds && typeof this.props.bounds !== "string") { + var targetRect = this.props.bounds.getBoundingClientRect(); + this.targetLeft = targetRect.left; + this.targetTop = targetRect.top; + } + if (this.resizable) { + var _a2 = this.resizable.getBoundingClientRect(), left = _a2.left, top_1 = _a2.top, right = _a2.right, bottom = _a2.bottom; + this.resizableLeft = left; + this.resizableRight = right; + this.resizableTop = top_1; + this.resizableBottom = bottom; + } + }; + Resizable2.prototype.onResizeStart = function(event, direction) { + if (!this.resizable || !this.window) { + return; + } + var clientX = 0; + var clientY = 0; + if (event.nativeEvent && isMouseEvent2(event.nativeEvent)) { + clientX = event.nativeEvent.clientX; + clientY = event.nativeEvent.clientY; + } else if (event.nativeEvent && isTouchEvent2(event.nativeEvent)) { + clientX = event.nativeEvent.touches[0].clientX; + clientY = event.nativeEvent.touches[0].clientY; + } + if (this.props.onResizeStart) { + if (this.resizable) { + var startResize = this.props.onResizeStart(event, direction, this.resizable); + if (startResize === false) { + return; } } - return rows; - }; - rowModel.rows = accessRows(data); - return rowModel; - }, { - key: "getRowModel", - debug: () => { - var _table$options$debugA; - return (_table$options$debugA = table.options.debugAll) != null ? _table$options$debugA : table.options.debugTable; - }, - onChange: () => { - table._autoResetPageIndex(); } - }); -} -function getGroupedRowModel() { - return (table) => memo(() => [table.getState().grouping, table.getPreGroupedRowModel()], (grouping, rowModel) => { - if (!rowModel.rows.length || !grouping.length) { - return rowModel; + if (this.props.size) { + if (typeof this.props.size.height !== "undefined" && this.props.size.height !== this.state.height) { + this.setState({ height: this.props.size.height }); + } + if (typeof this.props.size.width !== "undefined" && this.props.size.width !== this.state.width) { + this.setState({ width: this.props.size.width }); + } } - const existingGrouping = grouping.filter((columnId) => table.getColumn(columnId)); - const groupedFlatRows = []; - const groupedRowsById = {}; - const groupUpRecursively = function(rows, depth, parentId) { - if (depth === void 0) { - depth = 0; + this.ratio = typeof this.props.lockAspectRatio === "number" ? this.props.lockAspectRatio : this.size.width / this.size.height; + var flexBasis; + var computedStyle = this.window.getComputedStyle(this.resizable); + if (computedStyle.flexBasis !== "auto") { + var parent_3 = this.parentNode; + if (parent_3) { + var dir = this.window.getComputedStyle(parent_3).flexDirection; + this.flexDir = dir.startsWith("row") ? "row" : "column"; + flexBasis = computedStyle.flexBasis; } - if (depth >= existingGrouping.length) { - return rows.map((row) => { - row.depth = depth; - groupedFlatRows.push(row); - groupedRowsById[row.id] = row; - if (row.subRows) { - row.subRows = groupUpRecursively(row.subRows, depth + 1); - } - return row; - }); + } + this.setBoundingClientRect(); + this.bindEvents(); + var state = { + original: { + x: clientX, + y: clientY, + width: this.size.width, + height: this.size.height + }, + isResizing: true, + backgroundStyle: __assign3(__assign3({}, this.state.backgroundStyle), { cursor: this.window.getComputedStyle(event.target).cursor || "auto" }), + direction, + flexBasis + }; + this.setState(state); + }; + Resizable2.prototype.onMouseMove = function(event) { + var _this = this; + if (!this.state.isResizing || !this.resizable || !this.window) { + return; + } + if (this.window.TouchEvent && isTouchEvent2(event)) { + try { + event.preventDefault(); + event.stopPropagation(); + } catch (e4) { } - const columnId = existingGrouping[depth]; - const rowGroupsMap = groupBy(rows, columnId); - const aggregatedGroupedRows = Array.from(rowGroupsMap.entries()).map((_ref, index) => { - let [groupingValue, groupedRows2] = _ref; - let id2 = `${columnId}:${groupingValue}`; - id2 = parentId ? `${parentId}>${id2}` : id2; - const subRows = groupUpRecursively(groupedRows2, depth + 1, id2); - const leafRows = depth ? flattenBy(groupedRows2, (row2) => row2.subRows) : groupedRows2; - const row = createRow(table, id2, leafRows[0].original, index, depth); - Object.assign(row, { - groupingColumnId: columnId, - groupingValue, - subRows, - leafRows, - getValue: (columnId2) => { - if (existingGrouping.includes(columnId2)) { - if (row._valuesCache.hasOwnProperty(columnId2)) { - return row._valuesCache[columnId2]; - } - if (groupedRows2[0]) { - var _groupedRows$0$getVal; - row._valuesCache[columnId2] = (_groupedRows$0$getVal = groupedRows2[0].getValue(columnId2)) != null ? _groupedRows$0$getVal : void 0; - } - return row._valuesCache[columnId2]; - } - if (row._groupingValuesCache.hasOwnProperty(columnId2)) { - return row._groupingValuesCache[columnId2]; - } - const column = table.getColumn(columnId2); - const aggregateFn = column == null ? void 0 : column.getAggregationFn(); - if (aggregateFn) { - row._groupingValuesCache[columnId2] = aggregateFn(columnId2, leafRows, groupedRows2); - return row._groupingValuesCache[columnId2]; - } - } - }); - subRows.forEach((subRow) => { - groupedFlatRows.push(subRow); - groupedRowsById[subRow.id] = subRow; - }); - return row; - }); - return aggregatedGroupedRows; + } + var _a2 = this.props, maxWidth = _a2.maxWidth, maxHeight = _a2.maxHeight, minWidth = _a2.minWidth, minHeight = _a2.minHeight; + var clientX = isTouchEvent2(event) ? event.touches[0].clientX : event.clientX; + var clientY = isTouchEvent2(event) ? event.touches[0].clientY : event.clientY; + var _b2 = this.state, direction = _b2.direction, original = _b2.original, width = _b2.width, height = _b2.height; + var parentSize = this.getParentSize(); + var max3 = calculateNewMax(parentSize, this.window.innerWidth, this.window.innerHeight, maxWidth, maxHeight, minWidth, minHeight); + maxWidth = max3.maxWidth; + maxHeight = max3.maxHeight; + minWidth = max3.minWidth; + minHeight = max3.minHeight; + var _c2 = this.calculateNewSizeFromDirection(clientX, clientY), newHeight = _c2.newHeight, newWidth = _c2.newWidth; + var boundaryMax = this.calculateNewMaxFromBoundary(maxWidth, maxHeight); + if (this.props.snap && this.props.snap.x) { + newWidth = findClosestSnap(newWidth, this.props.snap.x, this.props.snapGap); + } + if (this.props.snap && this.props.snap.y) { + newHeight = findClosestSnap(newHeight, this.props.snap.y, this.props.snapGap); + } + var newSize = this.calculateNewSizeFromAspectRatio(newWidth, newHeight, { width: boundaryMax.maxWidth, height: boundaryMax.maxHeight }, { width: minWidth, height: minHeight }); + newWidth = newSize.newWidth; + newHeight = newSize.newHeight; + if (this.props.grid) { + var newGridWidth = snap(newWidth, this.props.grid[0]); + var newGridHeight = snap(newHeight, this.props.grid[1]); + var gap = this.props.snapGap || 0; + newWidth = gap === 0 || Math.abs(newGridWidth - newWidth) <= gap ? newGridWidth : newWidth; + newHeight = gap === 0 || Math.abs(newGridHeight - newHeight) <= gap ? newGridHeight : newHeight; + } + var delta = { + width: newWidth - original.width, + height: newHeight - original.height }; - const groupedRows = groupUpRecursively(rowModel.rows, 0, ""); - groupedRows.forEach((subRow) => { - groupedFlatRows.push(subRow); - groupedRowsById[subRow.id] = subRow; - }); - return { - rows: groupedRows, - flatRows: groupedFlatRows, - rowsById: groupedRowsById + if (width && typeof width === "string") { + if (width.endsWith("%")) { + var percent = newWidth / parentSize.width * 100; + newWidth = percent + "%"; + } else if (width.endsWith("vw")) { + var vw = newWidth / this.window.innerWidth * 100; + newWidth = vw + "vw"; + } else if (width.endsWith("vh")) { + var vh = newWidth / this.window.innerHeight * 100; + newWidth = vh + "vh"; + } + } + if (height && typeof height === "string") { + if (height.endsWith("%")) { + var percent = newHeight / parentSize.height * 100; + newHeight = percent + "%"; + } else if (height.endsWith("vw")) { + var vw = newHeight / this.window.innerWidth * 100; + newHeight = vw + "vw"; + } else if (height.endsWith("vh")) { + var vh = newHeight / this.window.innerHeight * 100; + newHeight = vh + "vh"; + } + } + var newState = { + width: this.createSizeForCssProperty(newWidth, "width"), + height: this.createSizeForCssProperty(newHeight, "height") }; - }, { - key: "getGroupedRowModel", - debug: () => { - var _table$options$debugA; - return (_table$options$debugA = table.options.debugAll) != null ? _table$options$debugA : table.options.debugTable; - }, - onChange: () => { - table._queue(() => { - table._autoResetExpanded(); - table._autoResetPageIndex(); - }); + if (this.flexDir === "row") { + newState.flexBasis = newState.width; + } else if (this.flexDir === "column") { + newState.flexBasis = newState.height; } - }); -} -function groupBy(rows, columnId) { - const groupMap = /* @__PURE__ */ new Map(); - return rows.reduce((map, row) => { - const resKey = `${row.getValue(columnId)}`; - const previous = map.get(resKey); - if (!previous) { - map.set(resKey, [row]); - } else { - previous.push(row); + pn(function() { + _this.setState(newState); + }); + if (this.props.onResize) { + this.props.onResize(event, direction, this.resizable, delta); } - return map; - }, groupMap); -} -function getExpandedRowModel() { - return (table) => memo(() => [table.getState().expanded, table.getPreExpandedRowModel(), table.options.paginateExpandedRows], (expanded, rowModel, paginateExpandedRows) => { - if (!rowModel.rows.length || expanded !== true && !Object.keys(expanded != null ? expanded : {}).length) { - return rowModel; + }; + Resizable2.prototype.onMouseUp = function(event) { + var _a2 = this.state, isResizing = _a2.isResizing, direction = _a2.direction, original = _a2.original; + if (!isResizing || !this.resizable) { + return; } - if (!paginateExpandedRows) { - return rowModel; + var delta = { + width: this.size.width - original.width, + height: this.size.height - original.height + }; + if (this.props.onResizeStop) { + this.props.onResizeStop(event, direction, this.resizable, delta); } - return expandRows(rowModel); - }, { - key: "getExpandedRowModel", - debug: () => { - var _table$options$debugA; - return (_table$options$debugA = table.options.debugAll) != null ? _table$options$debugA : table.options.debugTable; + if (this.props.size) { + this.setState(this.props.size); } - }); -} -function expandRows(rowModel) { - const expandedRows = []; - const handleRow = (row) => { - var _row$subRows; - expandedRows.push(row); - if ((_row$subRows = row.subRows) != null && _row$subRows.length && row.getIsExpanded()) { - row.subRows.forEach(handleRow); + this.unbindEvents(); + this.setState({ + isResizing: false, + backgroundStyle: __assign3(__assign3({}, this.state.backgroundStyle), { cursor: "auto" }) + }); + }; + Resizable2.prototype.updateSize = function(size) { + this.setState({ width: size.width, height: size.height }); + }; + Resizable2.prototype.renderResizer = function() { + var _this = this; + var _a2 = this.props, enable = _a2.enable, handleStyles = _a2.handleStyles, handleClasses = _a2.handleClasses, handleWrapperStyle = _a2.handleWrapperStyle, handleWrapperClass = _a2.handleWrapperClass, handleComponent = _a2.handleComponent; + if (!enable) { + return null; } + var resizers = Object.keys(enable).map(function(dir) { + if (enable[dir] !== false) { + return y(Resizer, { key: dir, direction: dir, onResizeStart: _this.onResizeStart, replaceStyles: handleStyles && handleStyles[dir], className: handleClasses && handleClasses[dir] }, handleComponent && handleComponent[dir] ? handleComponent[dir] : null); + } + return null; + }); + return y("div", { className: handleWrapperClass, style: handleWrapperStyle }, resizers); }; - rowModel.rows.forEach(handleRow); - return { - rows: expandedRows, - flatRows: rowModel.flatRows, - rowsById: rowModel.rowsById + Resizable2.prototype.render = function() { + var _this = this; + var extendsProps = Object.keys(this.props).reduce(function(acc, key2) { + if (definedProps.indexOf(key2) !== -1) { + return acc; + } + acc[key2] = _this.props[key2]; + return acc; + }, {}); + var style = __assign3(__assign3(__assign3({ position: "relative", userSelect: this.state.isResizing ? "none" : "auto" }, this.props.style), this.sizeStyle), { maxWidth: this.props.maxWidth, maxHeight: this.props.maxHeight, minWidth: this.props.minWidth, minHeight: this.props.minHeight, boxSizing: "border-box", flexShrink: 0 }); + if (this.state.flexBasis) { + style.flexBasis = this.state.flexBasis; + } + var Wrapper = this.props.as || "div"; + return y( + Wrapper, + __assign3({ ref: this.ref, style, className: this.props.className }, extendsProps), + this.state.isResizing && y("div", { style: this.state.backgroundStyle }), + this.props.children, + this.renderResizer() + ); }; -} + Resizable2.defaultProps = { + as: "div", + onResizeStart: function() { + }, + onResize: function() { + }, + onResizeStop: function() { + }, + enable: { + top: true, + right: true, + bottom: true, + left: true, + topRight: true, + bottomRight: true, + bottomLeft: true, + topLeft: true + }, + style: {}, + grid: [1, 1], + lockAspectRatio: false, + lockAspectRatioExtraWidth: 0, + lockAspectRatioExtraHeight: 0, + scale: 1, + resizeRatio: 1, + snapGap: 0 + }; + return Resizable2; +}(w3); -// node_modules/@tanstack/react-table/build/lib/index.mjs -function flexRender(Comp, props2) { - return !Comp ? null : isReactComponent(Comp) ? /* @__PURE__ */ y(Comp, props2) : Comp; -} -function isReactComponent(component) { - return isClassComponent(component) || typeof component === "function" || isExoticComponent(component); -} -function isClassComponent(component) { - return typeof component === "function" && (() => { - const proto = Object.getPrototypeOf(component); - return proto.prototype && proto.prototype.isReactComponent; - })(); -} -function isExoticComponent(component) { - return typeof component === "object" && typeof component.$$typeof === "symbol" && ["react.memo", "react.forward_ref"].includes(component.$$typeof.description); -} -function useReactTable(options) { - const resolvedOptions = { - state: {}, - onStateChange: () => { +// src/utils/contexts/mdtable.ts +var createTable = (object, columns) => { + const columnNames = columns.map((f4) => f4.name); + const base2 = "|"; + let outputString = base2 + columnNames.join(base2) + "|\n"; + columns.forEach((f4) => { + outputString += base2 + "----"; + }); + outputString += base2 + "\n"; + object.forEach((row) => { + outputString += columnNames.map((c4) => base2 + row[c4]).join("") + "|\n"; + }); + return outputString; +}; +var createInlineTable = async (plugin, path) => { + const context = spaceInfoByPath(plugin, path); + const schemas = await getMDBTableSchemas(plugin, context, "context"); + if (schemas) + return uniqueNameFromString( + "Table", + schemas.map((f4) => f4.id) + ); + return "Table"; +}; + +// src/components/UI/menus/newFrameMenu.tsx +var showNewFrameMenu = (e4, plugin, space, addNode) => { + const offset2 = e4.target.getBoundingClientRect(); + const kits = plugin.settings.quickFrames.flatMap((s5) => { + var _a2, _b2; + const frameSchemas = (_b2 = (_a2 = plugin.index.framesIndex.get(s5)) == null ? void 0 : _a2.schemas) != null ? _b2 : []; + return frameSchemas.map((f4) => mdbSchemaToFrameSchema(f4)).map((f4) => ({ + id: `${s5}#*${f4.id}`, + def: f4.def, + node: { + ...schemaToFrame(f4), + ref: `${s5}#*${f4.id}` + } + })); + }); + const presets = [ + { + name: "New Note", + value: { type: "preset", value: "note" }, + section: "default", + icon: "ui//mk-make-flow" }, - renderFallbackValue: null, - ...options + { + name: "Table", + value: { type: "preset", value: "table" }, + section: "default", + icon: "ui//mk-make-table" + } + ]; + const defaultElements = [ + flowNode, + spaceNode, + textNode, + imageNode, + dividerNode, + iconNode + ]; + const defaultFrames = [ + buttonNode, + linkNode, + cardNode, + progressNode + ]; + const options = [ + ...presets, + ...defaultElements.map((f4) => { + var _a2; + return { + name: f4.node.name, + value: { type: "element", value: f4 }, + section: "element", + icon: (_a2 = f4.def) == null ? void 0 : _a2.icon + }; + }), + ...defaultFrames.map((f4) => { + var _a2; + return { + name: f4.node.name, + value: { type: "default", value: f4 }, + section: "element", + icon: (_a2 = f4.def) == null ? void 0 : _a2.icon + }; + }), + ...kits.map((f4) => { + var _a2; + return { + name: f4.node.name, + value: { type: "kit", value: f4.node }, + section: "kit", + icon: (_a2 = f4.def) == null ? void 0 : _a2.icon + }; + }) + ]; + const insertNode = async (item) => { + if (item.type == "preset") { + if (item.value == "note") { + if (space.uri.type == "folder") { + const newFile = await createNewMarkdownFile( + plugin, + getAbstractFileAtPath(plugin, space.path), + "", + null, + true + ); + addNode({ + ...flowNode.node, + props: { value: `'${newFile.path}'` } + }); + } else { + const _space = plugin.index.spacesIndex.get(space.path); + if (_space) { + const newFile = await newFileInSpace( + plugin, + _space, + uriByString(plugin, space.path), + false, + true + ); + addNode({ + ...flowNode.node, + props: { value: `'${newFile.path}'` } + }); + } + } + } else if (item.value == "table") { + const table = await createInlineTable(plugin, space.uri.fullPath); + addNode({ + ...spaceNode.node, + props: { value: `'${space.uri.fullPath}/#^${table}'` } + }); + } else if (item.value == "link") { + } + } else if (item.type == "default") { + addNode({ + ...item.value.node, + type: "frame", + ref: "spaces://$kit/#*" + item.value.node.id + }); + } else if (item.type == "element") { + addNode({ + ...item.value.node + }); + } }; - const [tableRef] = h2(() => ({ - current: createTable(resolvedOptions) - })); - const [state, setState] = h2(() => tableRef.current.initialState); - tableRef.current.setOptions((prev) => ({ - ...prev, - ...options, - state: { - ...state, - ...options.state + showSelectMenu( + { x: offset2.left, y: offset2.top + 30 }, + { + plugin, + multi: false, + editable: false, + value: [], + options, + saveOptions: (_12, value) => insertNode(value[0]), + searchable: true, + showAll: true + } + ); +}; + +// src/components/SpaceView/Frames/FrameHoverMenu/FrameHoverMenu.tsx +var FrameHoverMenu = (props2) => { + var _a2, _b2; + const { spaceInfo } = q2(SpaceContext); + const { addNode, selectNodes, selectedNodes } = q2(FramesEditorContext); + return /* @__PURE__ */ Cn.createElement(Cn.Fragment, null, /* @__PURE__ */ Cn.createElement("div", { + className: "mk-frame-hover-menu-container" + }, /* @__PURE__ */ Cn.createElement("div", { + className: "mk-frame-hover-menu" + }, props2.dragRef && /* @__PURE__ */ Cn.createElement("div", { + className: "mk-icon-small mk-hover-button", + dangerouslySetInnerHTML: { __html: uiIconSet["mk-ui-handle"] }, + ref: props2.dragRef, + onClick: (e4) => { + e4.stopPropagation(); + if (e4.shiftKey) { + selectNodes( + [...selectedNodes, props2.node].sort( + (a5, b4) => a5.rank - b4.rank + ) + ); + } else { + selectNodes([props2.node]); + } }, - onStateChange: (updater) => { - setState(updater); - options.onStateChange == null ? void 0 : options.onStateChange(updater); + ...(_a2 = props2.listeners) != null ? _a2 : {}, + ...(_b2 = props2.attributes) != null ? _b2 : {} + }), /* @__PURE__ */ Cn.createElement("div", { + onClick: (e4) => showNewFrameMenu( + e4, + props2.plugin, + spaceInfo, + (newNode) => addNode(newNode, props2.node) + ), + className: "mk-icon-small mk-hover-button", + dangerouslySetInnerHTML: { __html: uiIconSet["mk-ui-plus"] } + })))); +}; + +// src/components/SpaceView/Frames/FrameHoverMenu/HoverMultiMenu.tsx +var HoverMultiMenu = (props2) => { + const { selectedNodes, groupNodes, selectNodes, saveNodes } = q2(FramesEditorContext); + const showSelectNodeMenu = (e4) => { + const offset2 = e4.target.getBoundingClientRect(); + const options = selectedNodes.map((f4) => ({ + name: f4.name, + value: f4.id + })); + showSelectMenu( + { x: offset2.left, y: offset2.top + 30 }, + { + plugin: props2.plugin, + multi: false, + editable: false, + value: [], + options, + saveOptions: (_12, value) => { + selectNodes(selectedNodes.filter((f4) => f4.id == value[0])); + }, + placeholder: i18n_default.labels.linkItemSelectPlaceholder, + detail: true, + searchable: false, + showAll: true + } + ); + }; + return /* @__PURE__ */ Cn.createElement("div", { + className: "mk-frame-props-editor menu", + onClick: (e4) => e4.stopPropagation() + }, /* @__PURE__ */ Cn.createElement("div", { + className: "mk-mark", + onClick: (e4) => showSelectNodeMenu(e4) + }, /* @__PURE__ */ Cn.createElement("div", { + dangerouslySetInnerHTML: { + __html: stickerFromString("lucide//copy-check", props2.plugin) + } + }), selectedNodes.length.toString(), " Selected"), /* @__PURE__ */ Cn.createElement("div", { + className: "mk-divider" + }), /* @__PURE__ */ Cn.createElement("div", { + className: "mk-mark", + "aria-label": "Delete", + onClick: () => saveNodes([], selectedNodes), + dangerouslySetInnerHTML: { + __html: stickerFromString("lucide//trash", props2.plugin) } })); - return tableRef.current; -} +}; -// src/components/ContextView/DataTypeView/OptionCell.tsx -var import_lodash5 = __toESM(require_lodash()); -var OptionCell = (props2) => { - var _a2, _b2; - const initialValue = (props2.multi ? (_a2 = parseMultiString(props2.initialValue)) != null ? _a2 : [] : [props2.initialValue]).filter((f4) => f4); - const initialOptions = [ - ...(_b2 = parseMultiString(props2.options).filter((f4) => f4).map((t4) => ({ name: t4, value: t4, removeable: true }))) != null ? _b2 : [], - ...initialValue.map((f4) => ({ name: f4, value: f4, removeable: true })) - ].filter(onlyUniqueProp("value")).filter((f4) => f4.value.length > 0); - const [options, setOptions] = h2(initialOptions); - const [value, setValue] = h2(initialValue); - p2(() => { - var _a3; - setValue( - (props2.multi ? (_a3 = parseMultiString(props2.initialValue)) != null ? _a3 : [] : [props2.initialValue]).filter((f4) => f4) +// src/components/UI/modals/imageModal.tsx +var import_obsidian26 = require("obsidian"); +var imageModal = class extends import_obsidian26.FuzzySuggestModal { + constructor(plugin, app2, selectImage) { + super(app2); + this.plugin = plugin; + this.selectImage = selectImage; + this.resultContainerEl.toggleClass("mk-image-modal", true); + this.inputEl.focus(); + this.inputEl.placeholder = "Select an image or paste a URL"; + this.emptyStateText = "No Images Found"; + this.limit = 30; + } + renderSuggestion(item, el) { + const oImg = el.createEl("img"); + const file = getAbstractFileAtPath(this.plugin, item.item); + oImg.setAttribute( + "src", + file ? this.plugin.app.vault.getResourcePath(file) : item.item ); - }, [props2.initialValue]); - const removeValue = (v3) => { - const newValues = value.filter((f4) => f4 != v3); - setValue(newValues); - props2.saveOptions( - serializeMultiString(options.map((f4) => f4.value)), - serializeMultiString(newValues) + oImg.setAttribute("height", "100px"); + oImg.setAttribute("width", "100px"); + el.appendChild(oImg); + } + getItemText(item) { + return item; + } + getSuggestions(query) { + const allImages = []; + if (query.match(urlRegex)) + allImages.push(query); + allImages.push( + ...getAllAbstractFilesInVault(this.plugin).filter( + (f4) => f4 instanceof import_obsidian26.TFile && ["png", "jpg", "jpeg"].contains(f4.extension) + ).map((f4) => f4.path) ); - }; - const removeOption = (option) => { - const newOptions = options.filter((f4) => f4.value != option); - const newValues = value.filter((f4) => f4 != option); - setOptions(newOptions); - setValue(newValues); - props2.saveOptions( - serializeMultiString(newOptions.map((f4) => f4.value)), - serializeMultiString(newValues) + return allImages.filter((f4) => f4.contains(query)).map((f4, i4) => ({ + item: f4, + match: { + score: i4, + matches: [] + } + })); + } + getItems() { + const allImages = []; + allImages.push( + ...getAllAbstractFilesInVault(this.plugin).filter( + (f4) => f4 instanceof import_obsidian26.TFile && ["png", "jpg", "jpeg"].contains(f4.extension) + ).map((f4) => f4.path) ); - }; - const saveOptions = (_options, _value) => { - if (!props2.multi) { - setOptions( - _options.filter((f4) => f4.length > 0).map((t4) => ({ name: t4, value: t4, removeable: true })) - ); - setValue(_value); - props2.saveOptions( - serializeMultiString(_options.filter((f4) => f4.length > 0)), - serializeMultiString(_value) - ); + return allImages; + } + onChooseItem(item, evt) { + this.selectImage(item); + } +}; + +// src/components/SpaceView/Frames/FrameHoverMenu/HoverPropsMenu.tsx +var import_obsidian27 = require("obsidian"); + +// src/utils/fonts.ts +function listFonts() { + const { fonts } = document; + const it = fonts.entries(); + const arr = []; + let done = false; + while (!done) { + const font = it.next(); + if (!font.done) { + arr.push(font.value[0].family); } else { - const newValues = (0, import_lodash5.uniq)([...value, _value[0]]); - setOptions( - _options.map((t4) => ({ name: t4, value: t4, removeable: true })) + done = font.done; + } + } + return Array.from(new Set(arr)); +} + +// src/components/SpaceView/Frames/FrameHoverMenu/HoverPropsMenu.tsx +var HoverPropsMenu = (props2) => { + var _a2; + const { deleteFrame, duplicateFrame, fields, saveStyleValue } = props2; + const { ungroupNode } = q2(FramesEditorContext); + const [editMode, setEditMode] = h2(0 /* EditModeDefault */); + const [frameProps, setFrameProps] = h2(props2.node.props); + p2(() => { + setFrameProps(props2.node.props); + }, [props2.node]); + const savePropValue = (prop, value) => { + setFrameProps((p3) => ({ ...p3, [prop]: value })); + props2.savePropValue(prop, value); + }; + const showValueMenu = (e4, field) => { + var _a3, _b2; + e4.stopPropagation(); + e4.preventDefault(); + const currentValue = removeQuotes(frameProps[field.name]); + switch (field.type) { + case "space": + { + const menu = new import_obsidian27.Menu(); + menu.setUseNativeMenu(false); + menu.addItem((menuItem) => { + menuItem.setIcon("type"); + menuItem.setTitle("Select Space"); + menuItem.onClick( + (e5) => showSpacesMenu( + e5, + props2.plugin, + (link) => savePropValue(field.name, wrapQuotes(link + "#^files")) + ) + ); + }); + menu.addSeparator(); + props2.schemaProps.filter((f4) => f4.type == field.type).forEach((f4) => { + menu.addItem((menuItem) => { + menuItem.setTitle(nameForField(f4)); + menuItem.setIcon("type"); + menuItem.onClick((e5) => { + savePropValue(field.name, `${f4.schemaId}.props.${f4.name}`); + }); + }); + }); + const offset2 = e4.target.getBoundingClientRect(); + menu.showAtPosition({ x: offset2.left, y: offset2.top + 30 }); + } + break; + case "option": + { + const parsedValue = parseFieldValue(field.value, field.type); + const options = (_a3 = parsedValue.options) != null ? _a3 : []; + showSelectMenu(e4.target.getBoundingClientRect(), { + plugin: props2.plugin, + multi: false, + editable: false, + searchable: true, + saveOptions: (_12, v3) => { + savePropValue(field.name, `'${v3[0]}'`); + }, + value: [currentValue != null ? currentValue : ""], + options + }); + } + break; + case "link": + { + const menu = new import_obsidian27.Menu(); + menu.setUseNativeMenu(false); + menu.addItem((menuItem) => { + menuItem.setIcon("type"); + menuItem.setTitle("Select Note"); + menuItem.onClick( + (e5) => showLinkMenu( + e5, + props2.plugin, + (link) => savePropValue(field.name, wrapQuotes(link)) + ) + ); + }); + menu.addSeparator(); + props2.schemaProps.filter((f4) => f4.type == field.type).forEach((f4) => { + menu.addItem((menuItem) => { + menuItem.setTitle(nameForField(f4)); + menuItem.setIcon("type"); + menuItem.onClick((e5) => { + savePropValue(field.name, `${f4.schemaId}.props.${f4.name}`); + }); + }); + }); + const offset2 = e4.target.getBoundingClientRect(); + menu.showAtPosition({ x: offset2.left, y: offset2.top + 30 }); + } + break; + case "icon": + { + const vaultChangeModal = new stickerModal( + props2.plugin.app, + props2.plugin, + (emoji) => savePropValue(field.name, wrapQuotes(emoji)) + ); + vaultChangeModal.open(); + } + break; + case "image": + { + const menu = new import_obsidian27.Menu(); + menu.setUseNativeMenu(false); + menu.addItem((menuItem) => { + menuItem.setTitle("Select Image"); + menuItem.onClick((e5) => { + const vaultChangeModal = new imageModal( + props2.plugin, + props2.plugin.app, + (image) => savePropValue(field.name, wrapQuotes(image)) + ); + vaultChangeModal.open(); + }); + menuItem.setIcon("type"); + }); + props2.schemaProps.forEach((f4) => { + menu.addItem((menuItem) => { + menuItem.setTitle(f4.name); + menuItem.setIcon("type"); + menuItem.onClick((e5) => { + savePropValue(field.name, `${f4.schemaId}.props.${f4.name}`); + }); + }); + }); + const offset2 = e4.target.getBoundingClientRect(); + menu.showAtPosition({ x: offset2.left, y: offset2.top + 30 }); + } + break; + case "text": + case "number": + { + const menu = new import_obsidian27.Menu(); + menu.setUseNativeMenu(false); + menu.addItem((menuItem) => { + inputMenuItem( + menuItem, + currentValue, + (value) => savePropValue(field.name, wrapQuotes(value)) + ); + menuItem.setIcon("type"); + }); + props2.schemaProps.forEach((f4) => { + menu.addItem((menuItem) => { + menuItem.setTitle(nameForField(f4)); + menuItem.setIcon("type"); + menuItem.onClick((e5) => { + savePropValue(field.name, `${f4.schemaId}.props.${f4.name}`); + }); + }); + }); + const offset2 = e4.target.getBoundingClientRect(); + menu.showAtPosition({ x: offset2.left, y: offset2.top + 30 }); + } + break; + case "date": { + const offset2 = e4.target.getBoundingClientRect(); + const date = new Date(currentValue); + showDatePickerMenu( + { x: offset2.left, y: offset2.top + 30 }, + date.getTime() ? date : null, + (date2) => savePropValue(field.name, date2.valueOf().toString()) + ); + break; + } + case "super": + { + const parsedValue = parseFieldValue(field.value, field.type); + const superPropertyName = parsedValue.dynamic ? removeQuotes(frameProps[(_b2 = parsedValue.field) != null ? _b2 : ""]) : parsedValue.field; + if (superPropertyName) { + const property = props2.plugin.index.superProperties.get(superPropertyName); + const superProperty = property ? { + ...property, + name: field.name, + value: JSON.stringify( + props2.plugin.index.valueForSuperproperty( + superPropertyName, + property + ) + ) + } : null; + if (superProperty) + showValueMenu(e4, superProperty); + } + break; + } + break; + } + }; + const showImageSizeMenu = (e4) => { + const menu = new import_obsidian27.Menu(); + menu.setUseNativeMenu(false); + menu.addItem((menuItem) => { + menuItem.setTitle("H1"); + menuItem.setIcon("type"); + menuItem.onClick((e5) => { + saveStyleValue("maxWidth", `'50px'`); + }); + }); + menu.addItem((menuItem) => { + menuItem.setTitle("H2"); + menuItem.setIcon("type"); + menuItem.onClick((e5) => { + saveStyleValue("maxWidth", `'100px'`); + }); + }); + menu.addItem((menuItem) => { + menuItem.setTitle("H3"); + menuItem.setIcon("type"); + menuItem.onClick((e5) => { + saveStyleValue("maxWidth", `'200px'`); + }); + }); + const offset2 = e4.target.getBoundingClientRect(); + menu.showAtPosition({ x: offset2.left, y: offset2.top + 30 }); + }; + const showTypographyMenu = (e4) => { + const menu = new import_obsidian27.Menu(); + menu.setUseNativeMenu(false); + menu.addItem((menuItem) => { + menuItem.setTitle("H1"); + menuItem.setIcon("type"); + menuItem.onClick((e5) => { + saveStyleValue("class", `'mk-t-h1'`); + }); + }); + menu.addItem((menuItem) => { + menuItem.setTitle("H2"); + menuItem.setIcon("type"); + menuItem.onClick((e5) => { + saveStyleValue("class", `'mk-t-h2'`); + }); + }); + menu.addItem((menuItem) => { + menuItem.setTitle("H3"); + menuItem.setIcon("type"); + menuItem.onClick((e5) => { + saveStyleValue("class", `'mk-t-h3'`); + }); + }); + menu.addItem((menuItem) => { + menuItem.setTitle("H4"); + menuItem.setIcon("type"); + menuItem.onClick((e5) => { + saveStyleValue("class", `'mk-t-h4'`); + }); + }); + menu.addItem((menuItem) => { + menuItem.setTitle("H5"); + menuItem.setIcon("type"); + menuItem.onClick((e5) => { + saveStyleValue("class", `'mk-t-h5'`); + }); + }); + menu.addItem((menuItem) => { + menuItem.setTitle("H6"); + menuItem.setIcon("type"); + menuItem.onClick((e5) => { + saveStyleValue("class", `'mk-t-h6'`); + }); + }); + menu.addItem((menuItem) => { + menuItem.setTitle("Text"); + menuItem.setIcon("type"); + menuItem.onClick((e5) => { + saveStyleValue("class", `'mk-t-p'`); + }); + }); + const offset2 = e4.target.getBoundingClientRect(); + menu.showAtPosition({ x: offset2.left, y: offset2.top + 30 }); + }; + const showFontMenu = (e4) => { + var _a3, _b2; + const options = listFonts().map((f4) => ({ name: f4, value: f4 })); + showSelectMenu(e4.target.getBoundingClientRect(), { + plugin: props2.plugin, + multi: false, + editable: false, + searchable: true, + saveOptions: (_12, v3) => { + saveStyleValue("--font-text", `'${v3[0]}'`); + }, + value: [(_b2 = (_a3 = props2.node.styles) == null ? void 0 : _a3["--font-text"]) != null ? _b2 : ""], + options + }); + }; + const setAlign = (e4, value) => { + e4.stopPropagation(); + e4.preventDefault(); + saveStyleValue("textAlign", `'${value}'`); + }; + return /* @__PURE__ */ Cn.createElement("div", { + className: "mk-frame-props-editor menu" + }, editMode == 0 /* EditModeDefault */ ? /* @__PURE__ */ Cn.createElement(Cn.Fragment, null, fields.map((f4, i4) => { + var _a3, _b2; + return /* @__PURE__ */ Cn.createElement(Cn.Fragment, null, /* @__PURE__ */ Cn.createElement("div", { + className: "mk-mark", + key: i4, + onClick: (e4) => showValueMenu(e4, f4) + }, /* @__PURE__ */ Cn.createElement("div", { + "aria-label": (_b2 = (_a3 = safelyParseJSON(f4.attrs)) == null ? void 0 : _a3.name) != null ? _b2 : f4.name, + dangerouslySetInnerHTML: { + __html: stickerFromString(stickerForField(f4), props2.plugin) + } + }), !stringIsConst(frameProps == null ? void 0 : frameProps[f4.name]) ? /* @__PURE__ */ Cn.createElement("div", { + className: "mk-mark-prop" + }, nameForField( + propFieldFromString( + frameProps == null ? void 0 : frameProps[f4.name], + props2.schemaProps + ) + )) : /* @__PURE__ */ Cn.createElement(Cn.Fragment, null), f4.type == "text" && stringIsConst(frameProps == null ? void 0 : frameProps[f4.name]) && /* @__PURE__ */ Cn.createElement("div", { + className: "mk-menu-input" + }, /* @__PURE__ */ Cn.createElement("input", { + value: removeQuotes(frameProps == null ? void 0 : frameProps[f4.name]), + onClick: (e4) => e4.stopPropagation(), + onKeyDown: (e4) => { + if (e4.key == "Enter") + e4.target.blur(); + }, + onBlur: (e4) => { + savePropValue(f4.name, wrapQuotes(e4.target.value)); + } + }))), props2.node.type == "flow" && /* @__PURE__ */ Cn.createElement("div", { + className: "mk-mark", + onClick: (e4) => { + e4.preventDefault(); + e4.stopPropagation(); + props2.triggerMenu && props2.triggerMenu(e4); + }, + dangerouslySetInnerHTML: { + __html: stickerFromString( + "ui//mk-ui-options", + props2.plugin + ) + } + })); + }), /* @__PURE__ */ Cn.createElement("div", { + className: "mk-divider" + }), props2.node.type == "space" ? /* @__PURE__ */ Cn.createElement(Cn.Fragment, null, /* @__PURE__ */ Cn.createElement("div", { + className: "mk-mark", + onClick: (e4) => { + e4.preventDefault(); + e4.stopPropagation(); + savePropValue( + "minMode", + `${props2.node.props.minMode == "true" ? "false" : "true"}` ); - setValue(newValues); - props2.saveOptions( - serializeMultiString(_options.filter((f4) => f4.length > 0)), - serializeMultiString(newValues) + }, + dangerouslySetInnerHTML: { + __html: stickerFromString("lucide//minimize-2", props2.plugin) + } + })) : /* @__PURE__ */ Cn.createElement(Cn.Fragment, null), props2.node.type == "text" || props2.node.type == "flow" ? /* @__PURE__ */ Cn.createElement("div", { + className: "mk-mark", + onClick: (e4) => { + e4.preventDefault(); + e4.stopPropagation(); + setEditMode(1); + }, + dangerouslySetInnerHTML: { + __html: stickerFromString("lucide//type", props2.plugin) + } + }) : /* @__PURE__ */ Cn.createElement(Cn.Fragment, null), props2.node.type == "image" ? /* @__PURE__ */ Cn.createElement("div", { + className: "mk-mark", + onClick: (e4) => { + e4.preventDefault(); + e4.stopPropagation(); + showImageSizeMenu(e4); + }, + dangerouslySetInnerHTML: { + __html: stickerFromString("lucide//type", props2.plugin) + } + }) : /* @__PURE__ */ Cn.createElement(Cn.Fragment, null), /* @__PURE__ */ Cn.createElement("div", { + className: "mk-mark", + onClick: (e4) => { + e4.preventDefault(); + e4.stopPropagation(); + saveStyleValue( + "maxWidth", + `${removeQuotes(props2.node.styles.maxWidth) == "100%" ? "" : `"100%"`}` ); + }, + dangerouslySetInnerHTML: { + __html: stickerFromString("ui//mk-ui-full-width", props2.plugin) } - }; - const menuProps = () => ({ - multi: false, - editable: true, - value, - options: !props2.multi ? [{ name: i18n_default.menu.none, value: "" }, ...options] : options, - saveOptions, - removeOption, - placeholder: i18n_default.labels.optionItemSelectPlaceholder, - searchable: true, - showAll: true, - onHide: () => props2.setEditMode(null) - }); - return /* @__PURE__ */ Cn.createElement(OptionCellBase, { - baseClass: "mk-cell-option", - value, - menuProps, - multi: props2.multi, - editMode: props2.editMode, - removeValue - }); -}; -var OptionCellBase = (props2) => { - const { - value, - menuProps, - removeValue, - getLabelString, - openItem, - valueClass - } = props2; - const menuRef = _2(null); - p2(() => { - if (props2.editMode == 2) { - if (!menuRef.current) - showMenu(); + }), /* @__PURE__ */ Cn.createElement("div", { + className: "mk-divider" + }), props2.node.type == "group" || props2.node.type == "container" ? /* @__PURE__ */ Cn.createElement("div", { + "aria-label": "Ungroup", + className: "mk-mark", + onClick: () => ungroupNode(props2.node), + dangerouslySetInnerHTML: { + __html: stickerFromString("lucide//copy-x", props2.plugin) + } + }) : /* @__PURE__ */ Cn.createElement("div", { + className: "mk-mark", + "aria-label": "Duplicate", + onClick: () => duplicateFrame(), + dangerouslySetInnerHTML: { + __html: stickerFromString("lucide//copy", props2.plugin) } - }, [props2.editMode]); - const ref = _2(null); - const showMenu = () => { - const offset = ref.current.getBoundingClientRect(); - menuRef.current = showSelectMenu( - { x: offset.left - 4, y: offset.bottom - 4 }, - menuProps() - ); - }; - const editable = props2.editMode > 0; - return /* @__PURE__ */ Cn.createElement("div", { - className: props2.baseClass, - ref - }, value.length > 0 ? value.map((o3) => /* @__PURE__ */ Cn.createElement("div", { - className: "mk-cell-option-item" - }, (getLabelString ? getLabelString(o3).length > 0 : o3.length > 0) ? /* @__PURE__ */ Cn.createElement(Cn.Fragment, null, /* @__PURE__ */ Cn.createElement("div", { - className: valueClass && valueClass(o3), - onClick: () => openItem && openItem(o3) - }, getLabelString ? getLabelString(o3) : o3), editable && props2.multi ? /* @__PURE__ */ Cn.createElement("div", { - className: "mk-icon-xsmall", - onClick: () => removeValue(o3), + }), /* @__PURE__ */ Cn.createElement("div", { + className: "mk-mark", + "aria-label": "Delete", + onClick: () => deleteFrame(), dangerouslySetInnerHTML: { - __html: uiIconSet["mk-ui-close"] + __html: stickerFromString("lucide//trash", props2.plugin) } - }) : /* @__PURE__ */ Cn.createElement(Cn.Fragment, null)) : /* @__PURE__ */ Cn.createElement("div", null, i18n_default.labels.select), editable && !props2.multi && value.length > 0 ? /* @__PURE__ */ Cn.createElement(Cn.Fragment, null, /* @__PURE__ */ Cn.createElement("span", null), /* @__PURE__ */ Cn.createElement("div", { - onClick: (e4) => editable && !props2.multi && showMenu(), - className: "mk-cell-option-select mk-icon-xxsmall mk-icon-rotated", + })) : editMode == 1 /* EditModeText */ ? /* @__PURE__ */ Cn.createElement(Cn.Fragment, null, /* @__PURE__ */ Cn.createElement("div", { + className: "mk-mark", + onMouseDown: () => { + setEditMode(0); + }, + dangerouslySetInnerHTML: { __html: uiIconSet["mk-ui-close"] } + }), /* @__PURE__ */ Cn.createElement("div", { + className: "mk-divider" + }), /* @__PURE__ */ Cn.createElement("div", { + className: "mk-mark", + onClick: (e4) => showTypographyMenu(e4) + }, /* @__PURE__ */ Cn.createElement("div", { dangerouslySetInnerHTML: { - __html: uiIconSet["mk-ui-collapse-sm"] + __html: stickerFromString( + "lucide//case-sensitive", + props2.plugin + ) } - })) : /* @__PURE__ */ Cn.createElement(Cn.Fragment, null))) : editable && !props2.multi ? /* @__PURE__ */ Cn.createElement("div", { - className: "mk-cell-option-item" + }), "Type"), /* @__PURE__ */ Cn.createElement("div", { + className: "mk-mark", + onClick: (e4) => showFontMenu(e4) }, /* @__PURE__ */ Cn.createElement("div", { - onClick: (e4) => !props2.multi && showMenu() - }, i18n_default.labels.select)) : props2.editMode == -1 ? /* @__PURE__ */ Cn.createElement("div", { - className: "mk-cell-option-item mk-cell-empty" - }, /* @__PURE__ */ Cn.createElement("div", null, i18n_default.menu.none)) : /* @__PURE__ */ Cn.createElement(Cn.Fragment, null), editable && props2.multi ? /* @__PURE__ */ Cn.createElement("div", { - onClick: (e4) => editable && showMenu(), - className: "mk-cell-option-new mk-icon-small", - dangerouslySetInnerHTML: { __html: uiIconSet["mk-ui-plus"] } - }) : /* @__PURE__ */ Cn.createElement(Cn.Fragment, null)); + dangerouslySetInnerHTML: { + __html: stickerFromString("lucide//type", props2.plugin) + } + }), "Font"), /* @__PURE__ */ Cn.createElement("div", { + className: "mk-divider" + }), /* @__PURE__ */ Cn.createElement("div", { + className: "mk-mark", + onClick: (e4) => setAlign(e4, "left"), + dangerouslySetInnerHTML: { + __html: stickerFromString("lucide//align-left", props2.plugin) + } + }), /* @__PURE__ */ Cn.createElement("div", { + className: "mk-mark", + onClick: (e4) => setAlign(e4, "center"), + dangerouslySetInnerHTML: { + __html: stickerFromString("lucide//align-center", props2.plugin) + } + }), /* @__PURE__ */ Cn.createElement("div", { + className: "mk-mark", + onClick: (e4) => setAlign(e4, "right"), + dangerouslySetInnerHTML: { + __html: stickerFromString("lucide//align-right", props2.plugin) + } + }), /* @__PURE__ */ Cn.createElement("div", { + className: "mk-divider" + }), /* @__PURE__ */ Cn.createElement("div", { + className: "mk-color", + style: { background: removeQuotes((_a2 = props2.node.styles) == null ? void 0 : _a2["color"]) } + })) : /* @__PURE__ */ Cn.createElement(Cn.Fragment, null)); }; -// src/components/ContextView/DataTypeView/ContextCell.tsx -var ContextCell = (props2) => { - var _a2, _b2, _c2; - const stringValueToLink = (strings) => strings.map((f4) => { - return { - label: parseLinkDisplayString(f4), - path: parseLinkString(f4) - }; +// src/components/SpaceView/Frames/Placeholders/ColumnPlaceholder.tsx +var FrameEditorDropZone = (props2) => { + const { frameSchema } = q2(FramesMDBContext); + const { setNodeRef } = useDroppable({ + id: props2.id, + data: { + id: props2.id, + type: "item", + parent: props2.parentId, + frame: frameSchema.id + } }); - const initialValue = stringValueToLink( - props2.multi ? (_a2 = parseMultiString(props2.initialValue)) != null ? _a2 : [] : [props2.initialValue] - ); - const ref = _2(null); - const options = stringValueToLink( - (_c2 = (_b2 = props2.contextTable) == null ? void 0 : _b2.rows.map((f4) => f4[FilePropertyName])) != null ? _c2 : [] - ).map((f4) => ({ - name: f4.label, - value: f4.path + return /* @__PURE__ */ Cn.createElement("div", { + className: `mk-frame-drop-placeholder`, + style: { width: props2.width, height: props2.height } + }, /* @__PURE__ */ Cn.createElement("div", { + className: `${props2.insertRow ? "mk-indicator-bottom" : ""}`, + style: { width: props2.width, height: props2.height }, + ref: props2.mode != 3 /* DropModeColumnOnly */ && props2.dropRef + }), props2.mode != 2 /* DropModeRowOnly */ && /* @__PURE__ */ Cn.createElement("div", { + className: `mk-frame-column-placeholder ${props2.columnInsert && "mk-indicator-right"}`, + style: { height: props2.height }, + ref: setNodeRef })); - const [value, setValue] = h2(initialValue); - const removeValue = (v3) => { - const newValues = value.filter((f4) => f4.path != v3.path); - setValue(newValues); - props2.saveValue(serializeMultiString(newValues.map((f4) => f4.path))); - }; - p2(() => { - var _a3; - setValue( - stringValueToLink( - props2.multi ? (_a3 = parseMultiString(props2.initialValue)) != null ? _a3 : [] : [props2.initialValue] - ) - ); - }, [props2.initialValue]); - const saveOptions = (_options, _value) => { - insertContextItems(props2.plugin, _options, props2.contextTag); - if (!props2.multi) { - setValue( - _value.map((f4) => ({ - path: f4, - label: fileNameToString(folderPathToString(f4)) - })) - ); - props2.saveValue(serializeMultiString(_value)); - } else { - const newValue = _value[0]; - if (newValue) { - const newValues = uniq([...value.map((f4) => f4.path), newValue]); - setValue( - newValues.map((f4) => ({ - label: fileNameToString(folderPathToString(f4)), - path: f4 - })) - ); - props2.saveValue(serializeMultiString(newValues)); - } +}; + +// src/components/SpaceView/Frames/Placeholders/RowPlaceholder.tsx +var RowPlaceholder = (props2) => { + const { hoverNode, root, deleteNode, nodes } = q2(FramesEditorContext); + const { setNodeRef } = useDroppable({ + id: props2.id, + data: { + id: props2.id, + type: "item", + parent: props2.parentId } - }; - const openLink = async (o3) => { - const file = getAbstractFileAtPath(app, o3.path); - if (file) { - openAFile(file, props2.plugin, false); + }); + const presets = [ + { + name: "New Note", + value: { type: "preset", value: "note" }, + section: "default", + icon: "ui//mk-make-flow" + }, + { + name: "Table", + value: { type: "preset", value: "table" }, + section: "default", + icon: "ui//mk-make-table" + } + ]; + const defaultElements = [ + flowNode, + spaceNode, + textNode, + imageNode, + iconNode + ]; + const defaultFrames = [ + buttonNode, + linkNode, + cardNode, + progressNode + ]; + const [queryStr, setQueryStr] = h2(""); + const allOptions = [ + ...presets, + ...defaultElements.map((f4) => { + var _a2; + return { + name: f4.node.name, + value: { type: "element", value: f4 }, + section: "element", + icon: (_a2 = f4.def) == null ? void 0 : _a2.icon + }; + }), + ...defaultFrames.map((f4) => { + var _a2; + return { + name: f4.node.name, + value: { type: "default", value: f4 }, + section: "element", + icon: (_a2 = f4.def) == null ? void 0 : _a2.icon + }; + }) + ]; + const { spaceInfo } = q2(SpaceContext); + const { addNode, selectNodes, selectedNodes } = q2(FramesEditorContext); + const options = F2(() => { + return queryStr.length == 0 ? allOptions : allOptions.filter((f4) => matchAny(queryStr).test(f4.name)); + }, [queryStr]); + const onKeyDown = (e4) => { + e4.stopPropagation(); + if (e4.key == "Backspace" && e4.target.textContent.length == 0) { + if (props2.id) + deleteNode(nodes.find((f4) => f4.id == props2.id)); } }; - const menuProps = () => { - const _options = !props2.multi ? [{ name: i18n_default.menu.none, value: "" }, ...options] : options; - return { - multi: false, - editable: true, - value: value.map((f4) => f4.path), - options: _options, - saveOptions, - placeholder: i18n_default.labels.contextItemSelectPlaceholder, - searchable: true, - showAll: true, - onHide: () => props2.setEditMode(null) - }; - }; - return /* @__PURE__ */ Cn.createElement(OptionCellBase, { - baseClass: "mk-cell-context", - menuProps, - openItem: openLink, - getLabelString: (o3) => o3.label, - value, - multi: props2.multi, - editMode: props2.editMode, - removeValue - }); + return /* @__PURE__ */ Cn.createElement("div", { + className: "mk-f" + }, /* @__PURE__ */ Cn.createElement("div", { + className: `mk-frame-row-placeholder ${hoverNode == props2.id && "mk-indicator-bottom"}`, + ref: setNodeRef + }, /* @__PURE__ */ Cn.createElement("div", { + onClick: (e4) => showNewFrameMenu(e4, props2.plugin, spaceInfo, addNode) + })), /* @__PURE__ */ Cn.createElement(FrameHoverMenu, { + plugin: props2.plugin, + node: root.node, + listeners: null, + dragRef: null + })); }; -// src/components/ui/menus/datePickerMenu.tsx -var import_obsidian17 = require("obsidian"); +// src/components/SpaceView/Editor/FlowView.tsx +var import_obsidian35 = require("obsidian"); -// node_modules/react-day-picker/dist/index.esm.js -var __assign = function() { - __assign = Object.assign || function __assign3(t4) { - for (var s5, i4 = 1, n2 = arguments.length; i4 < n2; i4++) { - s5 = arguments[i4]; - for (var p3 in s5) - if (Object.prototype.hasOwnProperty.call(s5, p3)) - t4[p3] = s5[p3]; - } - return t4; - }; - return __assign.apply(this, arguments); +// src/utils/flow/flowEditor.ts +var import_state5 = require("@codemirror/state"); + +// src/cm-extensions/flowEditor/atomic.ts +var import_state4 = require("@codemirror/state"); + +// src/cm-extensions/flowEditor/selectiveEditor.ts +var import_state3 = require("@codemirror/state"); +var import_view3 = require("@codemirror/view"); + +// node_modules/tslib/modules/index.js +var import_tslib = __toESM(require_tslib(), 1); +var { + __extends: __extends3, + __assign: __assign4, + __rest: __rest2, + __decorate, + __param, + __esDecorate, + __runInitializers, + __propKey, + __setFunctionName, + __metadata, + __awaiter, + __generator, + __exportStar, + __createBinding, + __values, + __read, + __spread, + __spreadArrays, + __spreadArray: __spreadArray2, + __await, + __asyncGenerator, + __asyncDelegator, + __asyncValues, + __makeTemplateObject, + __importStar, + __importDefault, + __classPrivateFieldGet, + __classPrivateFieldSet, + __classPrivateFieldIn +} = import_tslib.default; + +// src/cm-extensions/flowEditor/selectiveEditor.ts +var combinedRangeFacets = (rangeA, rangeB) => { + const startRange = !(rangeA == null ? void 0 : rangeA[0]) ? rangeB[0] : !(rangeB == null ? void 0 : rangeB[0]) ? rangeA[0] : Math.max(rangeA == null ? void 0 : rangeA[0], rangeB == null ? void 0 : rangeB[0]); + const endRange = !(rangeA == null ? void 0 : rangeA[1]) ? rangeB[1] : !(rangeB == null ? void 0 : rangeB[1]) ? rangeA[1] : Math.min(rangeA == null ? void 0 : rangeA[1], rangeB == null ? void 0 : rangeB[1]); + return [isNaN(startRange) ? null : startRange, isNaN(endRange) ? null : endRange]; }; -function __rest(s5, e4) { - var t4 = {}; - for (var p3 in s5) - if (Object.prototype.hasOwnProperty.call(s5, p3) && e4.indexOf(p3) < 0) - t4[p3] = s5[p3]; - if (s5 != null && typeof Object.getOwnPropertySymbols === "function") - for (var i4 = 0, p3 = Object.getOwnPropertySymbols(s5); i4 < p3.length; i4++) { - if (e4.indexOf(p3[i4]) < 0 && Object.prototype.propertyIsEnumerable.call(s5, p3[i4])) - t4[p3[i4]] = s5[p3[i4]]; +var editableRange = import_state3.Annotation.define(); +var contentRange = import_state3.Annotation.define(); +var hiddenLine = import_view3.Decoration.replace({ inclusive: true, block: true }); +var hideLine = import_state3.StateField.define({ + create() { + return import_view3.Decoration.none; + }, + update(value, tr) { + const builder = new import_state3.RangeSetBuilder(); + const betterFacet = combinedRangeFacets(tr.state.field(selectiveLinesFacet, false), tr.state.field(frontmatterFacet, false)); + if ((betterFacet == null ? void 0 : betterFacet[0]) != null) { + const starterLine = Math.min( + tr.state.doc.lines, + betterFacet[0] + ); + builder.add( + tr.state.doc.line(1).from, + tr.state.doc.line(starterLine).from - 1, + hiddenLine + ); + if (tr.newDoc.lines != betterFacet[1]) + builder.add( + tr.state.doc.line( + Math.min(tr.newDoc.lines, betterFacet[1]) + ).to, + tr.state.doc.line(tr.newDoc.lines).to, + hiddenLine + ); } - return t4; -} -function __spreadArray(to, from, pack) { - if (pack || arguments.length === 2) - for (var i4 = 0, l3 = from.length, ar; i4 < l3; i4++) { - if (ar || !(i4 in from)) { - if (!ar) - ar = Array.prototype.slice.call(from, 0, i4); - ar[i4] = from[i4]; + const dec = builder.finish(); + return dec; + }, + provide: (f4) => import_view3.EditorView.decorations.from(f4) +}); +var frontmatterFacet = import_state3.StateField.define({ + create: () => [void 0, void 0], + update(value, tr) { + if (tr.annotation(contentRange)) { + if (tr.annotation(contentRange)[0]) { + return [ + tr.annotation(contentRange)[0], + Math.min(tr.state.doc.lines, tr.annotation(contentRange)[1]) + ]; } + return tr.annotation(contentRange); } - return to.concat(ar || Array.prototype.slice.call(from)); -} -function isDayPickerMultiple(props2) { - return props2.mode === "multiple"; -} -function isDayPickerRange(props2) { - return props2.mode === "range"; -} -function isDayPickerSingle(props2) { - return props2.mode === "single"; -} -var defaultClassNames = { - root: "rdp", - multiple_months: "rdp-multiple_months", - with_weeknumber: "rdp-with_weeknumber", - vhidden: "rdp-vhidden", - button_reset: "rdp-button_reset", - button: "rdp-button", - caption: "rdp-caption", - caption_start: "rdp-caption_start", - caption_end: "rdp-caption_end", - caption_between: "rdp-caption_between", - caption_label: "rdp-caption_label", - caption_dropdowns: "rdp-caption_dropdowns", - dropdown: "rdp-dropdown", - dropdown_month: "rdp-dropdown_month", - dropdown_year: "rdp-dropdown_year", - dropdown_icon: "rdp-dropdown_icon", - months: "rdp-months", - month: "rdp-month", - table: "rdp-table", - tbody: "rdp-tbody", - tfoot: "rdp-tfoot", - head: "rdp-head", - head_row: "rdp-head_row", - head_cell: "rdp-head_cell", - nav: "rdp-nav", - nav_button: "rdp-nav_button", - nav_button_previous: "rdp-nav_button_previous", - nav_button_next: "rdp-nav_button_next", - nav_icon: "rdp-nav_icon", - row: "rdp-row", - weeknumber: "rdp-weeknumber", - cell: "rdp-cell", - day: "rdp-day", - day_today: "rdp-day_today", - day_outside: "rdp-day_outside", - day_selected: "rdp-day_selected", - day_disabled: "rdp-day_disabled", - day_hidden: "rdp-day_hidden", - day_range_start: "rdp-day_range_start", - day_range_end: "rdp-day_range_end", - day_range_middle: "rdp-day_range_middle" -}; -function formatCaption(month, options) { - return format(month, "LLLL y", options); -} -function formatDay(day, options) { - return format(day, "d", options); -} -function formatMonthCaption(month, options) { - return format(month, "LLLL", options); -} -function formatWeekNumber(weekNumber) { - return "".concat(weekNumber); -} -function formatWeekdayName(weekday, options) { - return format(weekday, "cccccc", options).toUpperCase(); -} -function formatYearCaption(year, options) { - return format(year, "yyyy", options); -} -var formatters3 = /* @__PURE__ */ Object.freeze({ - __proto__: null, - formatCaption, - formatDay, - formatMonthCaption, - formatWeekNumber, - formatWeekdayName, - formatYearCaption -}); -var labelDay = function(day, activeModifiers, options) { - return format(day, "do MMMM (EEEE)", options); -}; -var labelMonthDropdown = function() { - return "Month: "; -}; -var labelNext = function() { - return "Go to next month"; -}; -var labelPrevious = function() { - return "Go to previous month"; -}; -var labelWeekday = function(day, options) { - return format(day, "cccc", options); -}; -var labelWeekNumber = function(n2) { - return "Week n. ".concat(n2); -}; -var labelYearDropdown = function() { - return "Year: "; -}; -var labels = /* @__PURE__ */ Object.freeze({ - __proto__: null, - labelDay, - labelMonthDropdown, - labelNext, - labelPrevious, - labelWeekNumber, - labelWeekday, - labelYearDropdown -}); -function getDefaultContextValues() { - var captionLayout = "buttons"; - var classNames9 = defaultClassNames; - var locale2 = en_US_default; - var modifiersClassNames = {}; - var modifiers = {}; - var numberOfMonths = 1; - var styles = {}; - var today = new Date(); - return { - captionLayout, - classNames: classNames9, - formatters: formatters3, - labels, - locale: locale2, - modifiersClassNames, - modifiers, - numberOfMonths, - styles, - today, - mode: "default" - }; -} -function parseFromToProps(props2) { - var fromYear = props2.fromYear, toYear = props2.toYear, fromMonth = props2.fromMonth, toMonth = props2.toMonth; - var fromDate = props2.fromDate, toDate2 = props2.toDate; - if (fromMonth) { - fromDate = startOfMonth(fromMonth); - } else if (fromYear) { - fromDate = new Date(fromYear, 0, 1); + return value; } - if (toMonth) { - toDate2 = endOfMonth(toMonth); - } else if (toYear) { - toDate2 = new Date(toYear, 11, 31); +}); +var selectiveLinesFacet = import_state3.StateField.define({ + create: () => [void 0, void 0], + update(value, tr) { + if (tr.annotation(editableRange)) { + if (tr.annotation(editableRange)[0]) { + return [ + tr.annotation(editableRange)[0], + Math.min(tr.state.doc.lines, tr.annotation(editableRange)[1]) + ]; + } + return tr.annotation(editableRange); + } + return value; } +}); +var lineRangeToPosRange = (state, range) => { return { - fromDate: fromDate ? startOfDay(fromDate) : void 0, - toDate: toDate2 ? startOfDay(toDate2) : void 0 + from: state.doc.line(range[0]).from, + to: state.doc.line(Math.min(state.doc.lines, range[1])).to }; -} -var DayPickerContext = F(void 0); -function DayPickerProvider(props2) { - var _a2; - var initialProps = props2.initialProps; - var defaultContextValues = getDefaultContextValues(); - var _b2 = parseFromToProps(initialProps), fromDate = _b2.fromDate, toDate2 = _b2.toDate; - var captionLayout = (_a2 = initialProps.captionLayout) !== null && _a2 !== void 0 ? _a2 : defaultContextValues.captionLayout; - if (captionLayout !== "buttons" && (!fromDate || !toDate2)) { - captionLayout = "buttons"; - } - var onSelect; - if (isDayPickerSingle(initialProps) || isDayPickerMultiple(initialProps) || isDayPickerRange(initialProps)) { - onSelect = initialProps.onSelect; +}; +var smartDelete = import_state3.EditorState.transactionFilter.of( + (tr) => { + if (tr.isUserEvent("delete") && !tr.annotation(import_state3.Transaction.userEvent).endsWith(".smart")) { + const initialSelections = tr.startState.selection.ranges.map((range) => ({ + from: range.from, + to: range.to + })); + const betterFacet = combinedRangeFacets(tr.startState.field(selectiveLinesFacet, false), tr.startState.field(frontmatterFacet, false)); + if (initialSelections.length > 0 && (betterFacet == null ? void 0 : betterFacet[0])) { + const posRange = lineRangeToPosRange( + tr.startState, + betterFacet + ); + if (tr.changes.touchesRange(0, posRange.from - 1)) { + const minFrom = Math.max(posRange.from, initialSelections[0].from); + const minTo = Math.min(posRange.to, initialSelections[0].to); + return [{ + changes: { + from: Math.min(minFrom, minTo), + to: Math.max(minFrom, minTo) + }, + annotations: import_state3.Transaction.userEvent.of( + `${tr.annotation(import_state3.Transaction.userEvent)}.smart` + ) + }]; + } + } + } + return tr; } - var value = __assign(__assign(__assign({}, defaultContextValues), initialProps), { captionLayout, classNames: __assign(__assign({}, defaultContextValues.classNames), initialProps.classNames), components: __assign({}, initialProps.components), formatters: __assign(__assign({}, defaultContextValues.formatters), initialProps.formatters), fromDate, labels: __assign(__assign({}, defaultContextValues.labels), initialProps.labels), mode: initialProps.mode || defaultContextValues.mode, modifiers: __assign(__assign({}, defaultContextValues.modifiers), initialProps.modifiers), modifiersClassNames: __assign(__assign({}, defaultContextValues.modifiersClassNames), initialProps.modifiersClassNames), onSelect, styles: __assign(__assign({}, defaultContextValues.styles), initialProps.styles), toDate: toDate2 }); - return Cn.createElement(DayPickerContext.Provider, { value }, props2.children); -} -function useDayPicker() { - var context = q2(DayPickerContext); - if (!context) { - throw new Error("useDayPicker must be used within a DayPickerProvider."); +); +var preventModifyTargetRanges = import_state3.EditorState.transactionFilter.of( + (tr) => { + const newTrans = []; + try { + const editableLines = tr.startState.field(selectiveLinesFacet, false); + const contentLines = tr.startState.field(frontmatterFacet, false); + const selectiveLines = combinedRangeFacets(editableLines, contentLines); + if (tr.isUserEvent("input") || tr.isUserEvent("delete") || tr.isUserEvent("move")) { + if (selectiveLines == null ? void 0 : selectiveLines[0]) { + const posRange = lineRangeToPosRange( + tr.startState, + selectiveLines + ); + if (!tr.changes.touchesRange(posRange.from, posRange.to)) { + return []; + } + } + } + if (tr.state.doc.lines != tr.startState.doc.lines) { + const numberNewLines = tr.state.doc.lines - tr.startState.doc.lines; + if (selectiveLines == null ? void 0 : selectiveLines[0]) { + const posRange = lineRangeToPosRange( + tr.startState, + selectiveLines + ); + if (tr.changes.touchesRange(0, posRange.from - 1)) { + const newAnnotations = []; + if (editableLines[0]) { + newAnnotations.push(editableRange.of([ + editableLines[0] + numberNewLines, + editableLines[1] + numberNewLines + ])); + } + if (contentLines[0]) { + newAnnotations.push(contentRange.of([ + contentLines[0] + numberNewLines, + contentLines[1] + numberNewLines + ])); + } + newTrans.push({ + annotations: newAnnotations + }); + } else if (tr.changes.touchesRange(posRange.from - 1, posRange.to)) { + const newAnnotations = []; + if (editableLines[0]) { + newAnnotations.push(editableRange.of([ + editableLines[0], + editableLines[1] + numberNewLines + ])); + } + if (contentLines[0]) { + newAnnotations.push(contentRange.of([ + contentLines[0], + contentLines[1] + numberNewLines + ])); + } + newTrans.push({ + annotations: newAnnotations + }); + } + } + } + } catch (e4) { + return []; + } + return [tr, ...newTrans]; } - return context; -} -function CaptionLabel(props2) { - var _a2 = useDayPicker(), locale2 = _a2.locale, classNames9 = _a2.classNames, styles = _a2.styles, formatCaption2 = _a2.formatters.formatCaption; - return Cn.createElement("div", { className: classNames9.caption_label, style: styles.caption_label, "aria-live": "polite", role: "presentation", id: props2.id }, formatCaption2(props2.displayMonth, { locale: locale2 })); -} -function IconDropdown(props2) { - return Cn.createElement( - "svg", - __assign({ width: "8px", height: "8px", viewBox: "0 0 120 120", "data-testid": "iconDropdown" }, props2), - Cn.createElement("path", { d: "M4.22182541,48.2218254 C8.44222828,44.0014225 15.2388494,43.9273804 19.5496459,47.9996989 L19.7781746,48.2218254 L60,88.443 L100.221825,48.2218254 C104.442228,44.0014225 111.238849,43.9273804 115.549646,47.9996989 L115.778175,48.2218254 C119.998577,52.4422283 120.07262,59.2388494 116.000301,63.5496459 L115.778175,63.7781746 L67.7781746,111.778175 C63.5577717,115.998577 56.7611506,116.07262 52.4503541,112.000301 L52.2218254,111.778175 L4.22182541,63.7781746 C-0.0739418023,59.4824074 -0.0739418023,52.5175926 4.22182541,48.2218254 Z", fill: "currentColor", fillRule: "nonzero" }) - ); -} -function Dropdown(props2) { - var _a2, _b2; - var onChange = props2.onChange, value = props2.value, children = props2.children, caption = props2.caption, className = props2.className, style = props2.style; - var dayPicker = useDayPicker(); - var IconDropdownComponent = (_b2 = (_a2 = dayPicker.components) === null || _a2 === void 0 ? void 0 : _a2.IconDropdown) !== null && _b2 !== void 0 ? _b2 : IconDropdown; - return Cn.createElement( - "div", - { className, style }, - Cn.createElement("span", { className: dayPicker.classNames.vhidden }, props2["aria-label"]), - Cn.createElement("select", { name: props2.name, "aria-label": props2["aria-label"], className: dayPicker.classNames.dropdown, style: dayPicker.styles.dropdown, value, onChange }, children), - Cn.createElement( - "div", - { className: dayPicker.classNames.caption_label, style: dayPicker.styles.caption_label, "aria-hidden": "true" }, - caption, - Cn.createElement(IconDropdownComponent, { className: dayPicker.classNames.dropdown_icon, style: dayPicker.styles.dropdown_icon }) - ) - ); -} -function MonthsDropdown(props2) { - var _a2; - var _b2 = useDayPicker(), fromDate = _b2.fromDate, toDate2 = _b2.toDate, styles = _b2.styles, locale2 = _b2.locale, formatMonthCaption2 = _b2.formatters.formatMonthCaption, classNames9 = _b2.classNames, components = _b2.components, labelMonthDropdown2 = _b2.labels.labelMonthDropdown; - if (!fromDate) - return Cn.createElement(Cn.Fragment, null); - if (!toDate2) - return Cn.createElement(Cn.Fragment, null); - var dropdownMonths = []; - if (isSameYear(fromDate, toDate2)) { - var date = startOfMonth(fromDate); - for (var month = fromDate.getMonth(); month <= toDate2.getMonth(); month++) { - dropdownMonths.push(setMonth(date, month)); +); +var readOnlyRangesExtension = [smartDelete, preventModifyTargetRanges]; +var editBlockExtensions = () => [ + readOnlyRangesExtension, + hideLine, + selectiveLinesFacet, + frontmatterFacet +]; + +// src/cm-extensions/flowEditor/atomic.ts +var arrowKeyAnnotation = import_state4.Annotation.define(); +var atomicSelect = import_state4.EditorState.transactionFilter.of( + (tr) => { + if (tr.isUserEvent("delete") || tr.isUserEvent("input")) { + return tr; } - } else { - var date = startOfMonth(new Date()); - for (var month = 0; month <= 11; month++) { - dropdownMonths.push(setMonth(date, month)); + const flowID = tr.startState.field(flowIDStateField, false); + if (tr.annotation(arrowKeyAnnotation) && flowID) { + const oldSel = tr.startState.selection.main; + const lineRange = tr.state.field(selectiveLinesFacet, false); + const posRange = lineRange && lineRange[0] != void 0 ? lineRangeToPosRange(tr.startState, lineRange) : { from: 0, to: tr.startState.doc.length }; + if (oldSel.from <= posRange.from && tr.annotation(arrowKeyAnnotation) == 3) { + focusFlowEditorParent(flowID, true); + } + if (oldSel.to >= posRange.to && tr.annotation(arrowKeyAnnotation) == 4) { + focusFlowEditorParent(flowID, false); + } + return tr; + } + const selection = tr.newSelection.main; + if (selection.from == 0 && selection.to == 0 || selection.from != selection.to) + return tr; + const flowEditors = tr.state.field(flowEditorInfo, false); + if (flowEditors) { + for (const info of flowEditors) { + if (info.embed == 1) { + if (info.from - 3 <= selection.from && info.to + 2 >= selection.to && info.expandedState == 2) { + const top = tr.annotation(arrowKeyAnnotation) == 1 || tr.startState.selection.main.from > selection.from ? false : true; + focusFlowEditor(info.id, top); + return { + selection: import_state4.EditorSelection.single(info.from - 4) + }; + break; + } + } + } } + return tr; } - var handleChange = function(e4) { - var selectedMonth = Number(e4.target.value); - var newMonth = setMonth(startOfMonth(props2.displayMonth), selectedMonth); - props2.onChange(newMonth); +); + +// src/components/SpaceView/Editor/EmbedView/EmbedContextView.tsx +var import_obsidian32 = require("obsidian"); + +// src/components/SpaceView/Frames/ViewNodes/FrameRoot.tsx +var import_lodash9 = __toESM(require_lodash()); + +// src/components/SpaceView/Frames/EditorNodes/IconNodeView.tsx +var IconNodeView = (props2) => { + var _a2, _b2, _c2; + const { saveNodes } = q2(FramesEditorContext); + const selectIcon = () => { + const vaultChangeModal = new stickerModal( + props2.plugin.app, + props2.plugin, + (emoji) => saveNodes([ + { + ...props2.treeNode.node, + props: { ...props2.treeNode.node.props, value: wrapQuotes(emoji) } + } + ]) + ); + vaultChangeModal.open(); }; - var DropdownComponent2 = (_a2 = components === null || components === void 0 ? void 0 : components.Dropdown) !== null && _a2 !== void 0 ? _a2 : Dropdown; - return Cn.createElement(DropdownComponent2, { name: "months", "aria-label": labelMonthDropdown2(), className: classNames9.dropdown_month, style: styles.dropdown_month, onChange: handleChange, value: props2.displayMonth.getMonth(), caption: formatMonthCaption2(props2.displayMonth, { locale: locale2 }) }, dropdownMonths.map(function(m5) { - return Cn.createElement("option", { key: m5.getMonth(), value: m5.getMonth() }, formatMonthCaption2(m5, { locale: locale2 })); - })); -} -function YearsDropdown(props2) { - var _a2; - var displayMonth = props2.displayMonth; - var _b2 = useDayPicker(), fromDate = _b2.fromDate, toDate2 = _b2.toDate, locale2 = _b2.locale, styles = _b2.styles, classNames9 = _b2.classNames, components = _b2.components, formatYearCaption2 = _b2.formatters.formatYearCaption, labelYearDropdown2 = _b2.labels.labelYearDropdown; - var years = []; - if (!fromDate) - return Cn.createElement(Cn.Fragment, null); - if (!toDate2) - return Cn.createElement(Cn.Fragment, null); - var fromYear = fromDate.getFullYear(); - var toYear = toDate2.getFullYear(); - for (var year = fromYear; year <= toYear; year++) { - years.push(setYear(startOfYear(new Date()), year)); - } - var handleChange = function(e4) { - var newMonth = setYear(startOfMonth(displayMonth), Number(e4.target.value)); - props2.onChange(newMonth); + return props2.instance.state[props2.treeNode.id] && (((_b2 = (_a2 = props2.instance.state[props2.treeNode.id].props) == null ? void 0 : _a2.value) == null ? void 0 : _b2.length) > 0 ? /* @__PURE__ */ Cn.createElement(Sticker, { + sticker: (_c2 = props2.instance.state[props2.treeNode.id].props) == null ? void 0 : _c2.value, + plugin: props2.plugin + }) : props2.editable ? /* @__PURE__ */ Cn.createElement("div", { + onClick: () => selectIcon(), + className: "mk-frame-placeholder" + }, "Select Icon") : /* @__PURE__ */ Cn.createElement(Cn.Fragment, null)); +}; + +// src/components/SpaceView/Frames/EditorNodes/ImageNodeView.tsx +var ImageNodeView = (props2) => { + var _a2, _b2; + const value = props2.instance.state[props2.treeNode.id].props.value; + const file = F2(() => { + const f4 = getAbstractFileAtPath(props2.plugin, value); + return f4 ? props2.plugin.app.vault.getResourcePath(f4) : value; + }, [value]); + return props2.instance.state[props2.treeNode.id] && /* @__PURE__ */ Cn.createElement("img", { + className: "mk-image-node", + style: { + width: (_a2 = props2.instance.state[props2.treeNode.id]) == null ? void 0 : _a2.styles.width, + height: (_b2 = props2.instance.state[props2.treeNode.id]) == null ? void 0 : _b2.styles.height + }, + src: file + }); +}; + +// src/components/SpaceView/Frames/EditorNodes/SpaceNodeView.tsx +function parseContent(input) { + const regex1 = /!\[!\[(.*?)\]\]/; + const regex2 = /!!\[\[(.*?)\]\]/; + const match1 = input.match(regex1); + const match2 = input.match(regex2); + return match1 ? match1[1] : match2 ? match2[1] : input; +} +var SpaceNodeView = (props2) => { + var _a2, _b2, _c2, _d2; + const fullPath = (_b2 = (_a2 = props2.instance.state[props2.treeNode.id]) == null ? void 0 : _a2.props) == null ? void 0 : _b2.value; + const path = fullPath ? uriByString(props2.plugin, parseContent(fullPath)) : null; + const { saveNodes } = q2(FramesEditorContext); + const selectLink = (e4) => { + showSpacesMenu( + e4, + props2.plugin, + (link) => saveNodes([ + { + ...props2.treeNode.node, + props: { + ...props2.treeNode.node.props, + value: wrapQuotes(link + "#^files") + } + } + ]) + ); }; - var DropdownComponent2 = (_a2 = components === null || components === void 0 ? void 0 : components.Dropdown) !== null && _a2 !== void 0 ? _a2 : Dropdown; - return Cn.createElement(DropdownComponent2, { name: "years", "aria-label": labelYearDropdown2(), className: classNames9.dropdown_year, style: styles.dropdown_year, onChange: handleChange, value: displayMonth.getFullYear(), caption: formatYearCaption2(displayMonth, { locale: locale2 }) }, years.map(function(year2) { - return Cn.createElement("option", { key: year2.getFullYear(), value: year2.getFullYear() }, formatYearCaption2(year2, { locale: locale2 })); - })); -} -function useControlledValue(defaultValue2, controlledValue) { - var _a2 = h2(defaultValue2), uncontrolledValue = _a2[0], setValue = _a2[1]; - var value = controlledValue === void 0 ? uncontrolledValue : controlledValue; - return [value, setValue]; -} -function getInitialMonth(context) { - var month = context.month, defaultMonth = context.defaultMonth, today = context.today; - var initialMonth = month || defaultMonth || today || new Date(); - var toDate2 = context.toDate, fromDate = context.fromDate, _a2 = context.numberOfMonths, numberOfMonths = _a2 === void 0 ? 1 : _a2; - if (toDate2 && differenceInCalendarMonths(toDate2, initialMonth) < 0) { - var offset = -1 * (numberOfMonths - 1); - initialMonth = addMonths(toDate2, offset); - } - if (fromDate && differenceInCalendarMonths(initialMonth, fromDate) < 0) { - initialMonth = fromDate; - } - return startOfMonth(initialMonth); -} -function useNavigationState() { - var context = useDayPicker(); - var initialMonth = getInitialMonth(context); - var _a2 = useControlledValue(initialMonth, context.month), month = _a2[0], setMonth2 = _a2[1]; - var goToMonth = function(date) { + return props2.instance.state[props2.treeNode.id] && path ? /* @__PURE__ */ Cn.createElement(Cn.Fragment, null, /* @__PURE__ */ Cn.createElement(EmbedContextView, { + plugin: props2.plugin, + path, + minMode: (_d2 = (_c2 = props2.instance.state[props2.treeNode.id]) == null ? void 0 : _c2.props) == null ? void 0 : _d2.minMode + })) : /* @__PURE__ */ Cn.createElement("div", { + className: "mk-frame-placeholder", + onClick: (e4) => selectLink(e4) + }, "Select Space"); +}; + +// src/components/SpaceView/Frames/EditorNodes/TextNodeView.tsx +var TextNodeView = (props2) => { + var _a2, _b2; + const fileNameRef = _2(null); + const { saveNodes } = q2(FramesEditorContext); + const onBlur = (e4) => { var _a3; - if (context.disableNavigation) - return; - var month2 = startOfMonth(date); - setMonth2(month2); - (_a3 = context.onMonthChange) === null || _a3 === void 0 ? void 0 : _a3.call(context, month2); + const newValue = e4.target.innerHTML; + if (newValue != ((_a3 = props2.instance.state[props2.treeNode.id].props) == null ? void 0 : _a3.value)) { + saveNodes([ + { + ...props2.treeNode.node, + props: { ...props2.treeNode.node.props, value: wrapQuotes(newValue) } + } + ]); + } }; - return [month, goToMonth]; -} -function getDisplayMonths(month, _a2) { - var reverseMonths = _a2.reverseMonths, numberOfMonths = _a2.numberOfMonths; - var start = startOfMonth(month); - var end = startOfMonth(addMonths(start, numberOfMonths)); - var monthsDiff = differenceInCalendarMonths(end, start); - var months = []; - for (var i4 = 0; i4 < monthsDiff; i4++) { - var nextMonth = addMonths(start, i4); - months.push(nextMonth); - } - if (reverseMonths) - months = months.reverse(); - return months; -} -function getNextMonth(startingMonth, options) { - if (options.disableNavigation) { - return void 0; - } - var toDate2 = options.toDate, pagedNavigation = options.pagedNavigation, _a2 = options.numberOfMonths, numberOfMonths = _a2 === void 0 ? 1 : _a2; - var offset = pagedNavigation ? numberOfMonths : 1; - var month = startOfMonth(startingMonth); - if (!toDate2) { - return addMonths(month, offset); - } - var monthsDiff = differenceInCalendarMonths(toDate2, startingMonth); - if (monthsDiff < numberOfMonths) { - return void 0; - } - return addMonths(month, offset); -} -function getPreviousMonth(startingMonth, options) { - if (options.disableNavigation) { - return void 0; - } - var fromDate = options.fromDate, pagedNavigation = options.pagedNavigation, _a2 = options.numberOfMonths, numberOfMonths = _a2 === void 0 ? 1 : _a2; - var offset = pagedNavigation ? numberOfMonths : 1; - var month = startOfMonth(startingMonth); - if (!fromDate) { - return addMonths(month, -offset); - } - var monthsDiff = differenceInCalendarMonths(month, fromDate); - if (monthsDiff <= 0) { - return void 0; - } - return addMonths(month, -offset); -} -var NavigationContext = F(void 0); -function NavigationProvider(props2) { - var dayPicker = useDayPicker(); - var _a2 = useNavigationState(), currentMonth = _a2[0], goToMonth = _a2[1]; - var displayMonths = getDisplayMonths(currentMonth, dayPicker); - var nextMonth = getNextMonth(currentMonth, dayPicker); - var previousMonth = getPreviousMonth(currentMonth, dayPicker); - var isDateDisplayed = function(date) { - return displayMonths.some(function(displayMonth) { - return isSameMonth(date, displayMonth); - }); + const onKeyPress = (e4) => { + e4.stopPropagation(); }; - var goToDate = function(date, refDate) { - if (isDateDisplayed(date)) { - return; + const onKeyUp = (e4) => { + e4.stopPropagation(); + }; + const onKeyDown = (e4) => { + e4.stopPropagation(); + if (e4.key == "a" && e4.metaKey) { + e4.preventDefault(); + const selection = window.getSelection(); + const range = document.createRange(); + range.selectNodeContents(e4.target); + selection.removeAllRanges(); + selection.addRange(range); } - if (refDate && isBefore(date, refDate)) { - goToMonth(addMonths(date, 1 + dayPicker.numberOfMonths * -1)); - } else { - goToMonth(date); + if (e4.key == "Enter") { + e4.target.blur(); + e4.preventDefault(); + } + if (e4.key == "Escape") { + e4.target.blur(); + e4.preventDefault(); } }; - var value = { - currentMonth, - displayMonths, - goToMonth, - goToDate, - previousMonth, - nextMonth, - isDateDisplayed + return props2.instance.state[props2.treeNode.id] && /* @__PURE__ */ Cn.createElement("div", { + className: `mk-frame-text`, + placeholder: "Enter Text", + dangerouslySetInnerHTML: { + __html: (_a2 = props2.instance.state[props2.treeNode.id].props) == null ? void 0 : _a2.value + }, + onBlur, + onDrop: (e4) => e4.preventDefault(), + onKeyDown, + onKeyPress, + onKeyUp, + ref: fileNameRef, + contentEditable: props2.editable, + style: { + ...(_b2 = props2.instance.state[props2.treeNode.id]) == null ? void 0 : _b2.styles + } + }); +}; + +// src/components/SpaceView/Frames/ViewNodes/FrameView.tsx +var FrameView = (props2) => { + var _a2, _b2, _c2, _d2, _e2, _f, _g, _h, _i; + const innerComponents = props2.treeNode.node.type == "text" ? /* @__PURE__ */ Cn.createElement(TextNodeView, { + treeNode: props2.treeNode, + instance: props2.instance, + editable: false + }) : props2.treeNode.node.type == "icon" ? /* @__PURE__ */ Cn.createElement(IconNodeView, { + plugin: props2.plugin, + treeNode: props2.treeNode, + instance: props2.instance, + editable: false + }) : props2.treeNode.node.type == "image" ? /* @__PURE__ */ Cn.createElement(ImageNodeView, { + plugin: props2.plugin, + treeNode: props2.treeNode, + instance: props2.instance, + editable: false + }) : props2.treeNode.node.type == "space" ? /* @__PURE__ */ Cn.createElement(SpaceNodeView, { + treeNode: props2.treeNode, + instance: props2.instance, + plugin: props2.plugin, + editable: false + }) : props2.treeNode.node.type == "flow" ? /* @__PURE__ */ Cn.createElement(FlowNodeView, { + treeNode: props2.treeNode, + instance: props2.instance, + plugin: props2.plugin, + source: props2.source, + editable: false + }) : props2.treeNode.children.map((c4, i4) => /* @__PURE__ */ Cn.createElement(FrameView, { + plugin: props2.plugin, + key: i4, + treeNode: c4, + instance: props2.instance, + saveState: props2.saveState, + source: props2.source + })); + const parseAs = (role) => role == "checkbox" || role == "text" || role == "range" || role == "number" ? "input" : role; + const tag = (_c2 = parseAs((_b2 = (_a2 = props2.instance.state[props2.treeNode.id]) == null ? void 0 : _a2.styles) == null ? void 0 : _b2.as)) != null ? _c2 : "div"; + const type = tag == "input" ? (_e2 = (_d2 = props2.instance.state[props2.treeNode.id]) == null ? void 0 : _d2.styles) == null ? void 0 : _e2.as : null; + return props2.instance.state[props2.treeNode.id] && Cn.createElement( + tag, + { + className: `mk-frame-view ${(_h = (_g = (_f = props2.instance.state[props2.treeNode.id]) == null ? void 0 : _f.styles) == null ? void 0 : _g.class) != null ? _h : ""}`, + type, + onClick: (e4) => { + var _a3, _b3; + if (typeof ((_a3 = props2.instance.state[props2.treeNode.id].actions) == null ? void 0 : _a3.onClick) == "function") { + (_b3 = props2.instance.state[props2.treeNode.id].actions) == null ? void 0 : _b3.onClick( + e4, + props2.instance.state, + (s5) => props2.saveState(s5, props2.instance), + props2.plugin.index.api + ); + e4.stopPropagation(); + } + }, + style: { + ...defaultFrameStyles, + ...(_i = props2.instance.state[props2.treeNode.id]) == null ? void 0 : _i.styles + } + }, + [innerComponents] + ); +}; + +// src/components/SpaceView/Frames/ViewNodes/FrameRoot.tsx +var FrameRootView = (props2) => { + const [instance, setInstance] = h2({ + state: {}, + id: null, + root: null + }); + const activeRunID = _2(null); + const runRoot = () => { + if (props2.root) { + const root = import_lodash9.default.cloneDeep(props2.root); + const runID = (0, import_lodash9.uniqueId)(); + activeRunID.current = runID; + executeTreeNode( + applyPropsToRoot(root, props2.props), + {}, + props2.plugin.index.api, + saveState, + root, + runID + ).then((s5) => { + setInstance((p3) => s5); + activeRunID.current = s5.id; + }); + } }; - return Cn.createElement(NavigationContext.Provider, { value }, props2.children); -} -function useNavigation() { - var context = q2(NavigationContext); - if (!context) { - throw new Error("useNavigation must be used within a NavigationProvider"); - } - return context; -} -function CaptionDropdowns(props2) { - var _a2; - var _b2 = useDayPicker(), classNames9 = _b2.classNames, styles = _b2.styles, components = _b2.components; - var goToMonth = useNavigation().goToMonth; - var handleMonthChange = function(newMonth) { - goToMonth(newMonth); + p2(() => { + runRoot(); + }, [props2.root]); + p2(() => runRoot(), []); + const saveState = (state, instance2) => { + const { root, state: prevState, id: runID } = instance2; + if (runID != activeRunID.current) + return; + executeTreeNode( + applyPropsToRoot(root, props2.props), + prevState, + props2.plugin.index.api, + saveState, + root, + runID, + state + ).then( + (s5) => setInstance((p3) => ({ + ...s5, + root: replaceSubtree(p3.root, s5.root) + })) + ); }; - var CaptionLabelComponent = (_a2 = components === null || components === void 0 ? void 0 : components.CaptionLabel) !== null && _a2 !== void 0 ? _a2 : CaptionLabel; - var captionLabel = Cn.createElement(CaptionLabelComponent, { id: props2.id, displayMonth: props2.displayMonth }); - return Cn.createElement( - "div", - { className: classNames9.caption_dropdowns, style: styles.caption_dropdowns }, - Cn.createElement("div", { className: classNames9.vhidden }, captionLabel), - Cn.createElement(MonthsDropdown, { onChange: handleMonthChange, displayMonth: props2.displayMonth }), - Cn.createElement(YearsDropdown, { onChange: handleMonthChange, displayMonth: props2.displayMonth }) - ); -} -function IconLeft(props2) { - return Cn.createElement( - "svg", - __assign({ width: "16px", height: "16px", viewBox: "0 0 120 120" }, props2), - Cn.createElement("path", { d: "M69.490332,3.34314575 C72.6145263,0.218951416 77.6798462,0.218951416 80.8040405,3.34314575 C83.8617626,6.40086786 83.9268205,11.3179931 80.9992143,14.4548388 L80.8040405,14.6568542 L35.461,60 L80.8040405,105.343146 C83.8617626,108.400868 83.9268205,113.317993 80.9992143,116.454839 L80.8040405,116.656854 C77.7463184,119.714576 72.8291931,119.779634 69.6923475,116.852028 L69.490332,116.656854 L18.490332,65.6568542 C15.4326099,62.5991321 15.367552,57.6820069 18.2951583,54.5451612 L18.490332,54.3431458 L69.490332,3.34314575 Z", fill: "currentColor", fillRule: "nonzero" }) - ); -} -function IconRight(props2) { - return Cn.createElement( - "svg", - __assign({ width: "16px", height: "16px", viewBox: "0 0 120 120" }, props2), - Cn.createElement("path", { d: "M49.8040405,3.34314575 C46.6798462,0.218951416 41.6145263,0.218951416 38.490332,3.34314575 C35.4326099,6.40086786 35.367552,11.3179931 38.2951583,14.4548388 L38.490332,14.6568542 L83.8333725,60 L38.490332,105.343146 C35.4326099,108.400868 35.367552,113.317993 38.2951583,116.454839 L38.490332,116.656854 C41.5480541,119.714576 46.4651794,119.779634 49.602025,116.852028 L49.8040405,116.656854 L100.804041,65.6568542 C103.861763,62.5991321 103.926821,57.6820069 100.999214,54.5451612 L100.804041,54.3431458 L49.8040405,3.34314575 Z", fill: "currentColor" }) - ); -} -var Button = k3(function(props2, ref) { - var _a2 = useDayPicker(), classNames9 = _a2.classNames, styles = _a2.styles; - var classNamesArr = [classNames9.button_reset, classNames9.button]; - if (props2.className) { - classNamesArr.push(props2.className); - } - var className = classNamesArr.join(" "); - var style = __assign(__assign({}, styles.button_reset), styles.button); - if (props2.style) { - Object.assign(style, props2.style); - } - return Cn.createElement("button", __assign({}, props2, { ref, type: "button", className, style })); -}); -function Navigation(props2) { - var _a2, _b2; - var _c2 = useDayPicker(), dir = _c2.dir, locale2 = _c2.locale, classNames9 = _c2.classNames, styles = _c2.styles, _d2 = _c2.labels, labelPrevious2 = _d2.labelPrevious, labelNext2 = _d2.labelNext, components = _c2.components; - if (!props2.nextMonth && !props2.previousMonth) { - return Cn.createElement(Cn.Fragment, null); - } - var previousLabel = labelPrevious2(props2.previousMonth, { locale: locale2 }); - var previousClassName = [ - classNames9.nav_button, - classNames9.nav_button_previous - ].join(" "); - var nextLabel = labelNext2(props2.nextMonth, { locale: locale2 }); - var nextClassName = [ - classNames9.nav_button, - classNames9.nav_button_next - ].join(" "); - var IconRightComponent = (_a2 = components === null || components === void 0 ? void 0 : components.IconRight) !== null && _a2 !== void 0 ? _a2 : IconRight; - var IconLeftComponent = (_b2 = components === null || components === void 0 ? void 0 : components.IconLeft) !== null && _b2 !== void 0 ? _b2 : IconLeft; - return Cn.createElement( - "div", - { className: classNames9.nav, style: styles.nav }, - !props2.hidePrevious && Cn.createElement(Button, { name: "previous-month", "aria-label": previousLabel, className: previousClassName, style: styles.nav_button_previous, disabled: !props2.previousMonth, onClick: props2.onPreviousClick }, dir === "rtl" ? Cn.createElement(IconRightComponent, { className: classNames9.nav_icon, style: styles.nav_icon }) : Cn.createElement(IconLeftComponent, { className: classNames9.nav_icon, style: styles.nav_icon })), - !props2.hideNext && Cn.createElement(Button, { name: "next-month", "aria-label": nextLabel, className: nextClassName, style: styles.nav_button_next, disabled: !props2.nextMonth, onClick: props2.onNextClick }, dir === "rtl" ? Cn.createElement(IconLeftComponent, { className: classNames9.nav_icon, style: styles.nav_icon }) : Cn.createElement(IconRightComponent, { className: classNames9.nav_icon, style: styles.nav_icon })) + p2( + () => () => { + activeRunID.current = null; + }, + [] ); -} -function CaptionNavigation(props2) { - var _a2; - var _b2 = useDayPicker(), numberOfMonths = _b2.numberOfMonths, dir = _b2.dir; - var _c2 = useNavigation(), previousMonth = _c2.previousMonth, nextMonth = _c2.nextMonth, goToMonth = _c2.goToMonth, displayMonths = _c2.displayMonths; - var displayIndex = displayMonths.findIndex(function(month) { - return isSameMonth(props2.displayMonth, month); + return instance.root && /* @__PURE__ */ Cn.createElement(FrameView, { + plugin: props2.plugin, + treeNode: instance.root, + instance, + saveState, + source: props2.source }); - var isFirst = displayIndex === 0; - var isLast = displayIndex === displayMonths.length - 1; - if (dir === "rtl") { - _a2 = [isFirst, isLast], isLast = _a2[0], isFirst = _a2[1]; +}; + +// src/components/SpaceView/Contexts/CardsView/CardsView.tsx +var import_classnames3 = __toESM(require_classnames()); + +// src/utils/ui/selection.ts +var selectNextIndex = (currIndex, array) => { + if (!currIndex && array.length > 0) + return array[0]; + const pos = array.indexOf(currIndex); + if (pos < array.length - 1) + return array[pos + 1]; + return currIndex; +}; +var selectPrevIndex = (currIndex, array) => { + const pos = array.indexOf(currIndex); + if (pos > 0) + return array[pos - 1]; + return array[0]; +}; +var selectRange = (currSel, newSel, array) => { + const lastIndex = array.findIndex((f4) => f4 == currSel); + const newIndex = array.findIndex((f4) => f4 == newSel); + if (lastIndex < newIndex) { + return array.filter((f4, i4) => i4 > lastIndex && i4 <= newIndex); } - var hideNext = numberOfMonths > 1 && (isFirst || !isLast); - var hidePrevious = numberOfMonths > 1 && (isLast || !isFirst); - var handlePreviousClick = function() { - if (!previousMonth) - return; - goToMonth(previousMonth); - }; - var handleNextClick = function() { - if (!nextMonth) - return; - goToMonth(nextMonth); + return array.filter((f4, i4) => i4 < lastIndex && i4 >= newIndex); +}; + +// src/components/SpaceView/Contexts/CardsView/CardColumnView.tsx +var import_classnames = __toESM(require_classnames()); + +// node_modules/@tanstack/table-core/build/lib/index.mjs +function functionalUpdate(updater, input) { + return typeof updater === "function" ? updater(input) : updater; +} +function makeStateUpdater(key2, instance) { + return (updater) => { + instance.setState((old) => { + return { + ...old, + [key2]: functionalUpdate(updater, old[key2]) + }; + }); }; - return Cn.createElement(Navigation, { displayMonth: props2.displayMonth, hideNext, hidePrevious, nextMonth, previousMonth, onPreviousClick: handlePreviousClick, onNextClick: handleNextClick }); } -function Caption(props2) { - var _a2; - var _b2 = useDayPicker(), classNames9 = _b2.classNames, disableNavigation = _b2.disableNavigation, styles = _b2.styles, captionLayout = _b2.captionLayout, components = _b2.components; - var CaptionLabelComponent = (_a2 = components === null || components === void 0 ? void 0 : components.CaptionLabel) !== null && _a2 !== void 0 ? _a2 : CaptionLabel; - var caption; - if (disableNavigation) { - caption = Cn.createElement(CaptionLabelComponent, { id: props2.id, displayMonth: props2.displayMonth }); - } else if (captionLayout === "dropdown") { - caption = Cn.createElement(CaptionDropdowns, { displayMonth: props2.displayMonth, id: props2.id }); - } else if (captionLayout === "dropdown-buttons") { - caption = Cn.createElement( - Cn.Fragment, - null, - Cn.createElement(CaptionDropdowns, { displayMonth: props2.displayMonth, id: props2.id }), - Cn.createElement(CaptionNavigation, { displayMonth: props2.displayMonth, id: props2.id }) - ); - } else { - caption = Cn.createElement( - Cn.Fragment, - null, - Cn.createElement(CaptionLabelComponent, { id: props2.id, displayMonth: props2.displayMonth }), - Cn.createElement(CaptionNavigation, { displayMonth: props2.displayMonth, id: props2.id }) - ); - } - return Cn.createElement("div", { className: classNames9.caption, style: styles.caption }, caption); +function isFunction(d5) { + return d5 instanceof Function; } -function Footer(props2) { - var _a2 = useDayPicker(), footer = _a2.footer, styles = _a2.styles, tfoot = _a2.classNames.tfoot; - if (!footer) - return Cn.createElement(Cn.Fragment, null); - return Cn.createElement( - "tfoot", - { className: tfoot, style: styles.tfoot }, - Cn.createElement( - "tr", - null, - Cn.createElement("td", { colSpan: 8 }, footer) - ) - ); +function flattenBy(arr, getChildren) { + const flat = []; + const recurse = (subArr) => { + subArr.forEach((item) => { + flat.push(item); + const children = getChildren(item); + if (children != null && children.length) { + recurse(children); + } + }); + }; + recurse(arr); + return flat; } -function getWeekdays(locale2, weekStartsOn, ISOWeek) { - var start = ISOWeek ? startOfISOWeek(new Date()) : startOfWeek(new Date(), { locale: locale2, weekStartsOn }); - var days = []; - for (var i4 = 0; i4 < 7; i4++) { - var day = addDays(start, i4); - days.push(day); - } - return days; +function memo(getDeps, fn2, opts) { + let deps = []; + let result; + return () => { + let depTime; + if (opts.key && opts.debug) + depTime = Date.now(); + const newDeps = getDeps(); + const depsChanged = newDeps.length !== deps.length || newDeps.some((dep, index) => deps[index] !== dep); + if (!depsChanged) { + return result; + } + deps = newDeps; + let resultTime; + if (opts.key && opts.debug) + resultTime = Date.now(); + result = fn2(...newDeps); + opts == null ? void 0 : opts.onChange == null ? void 0 : opts.onChange(result); + if (opts.key && opts.debug) { + if (opts != null && opts.debug()) { + const depEndTime = Math.round((Date.now() - depTime) * 100) / 100; + const resultEndTime = Math.round((Date.now() - resultTime) * 100) / 100; + const resultFpsPercentage = resultEndTime / 16; + const pad = (str, num) => { + str = String(str); + while (str.length < num) { + str = " " + str; + } + return str; + }; + console.info(`%c\u23F1 ${pad(resultEndTime, 5)} /${pad(depEndTime, 5)} ms`, ` + font-size: .6rem; + font-weight: bold; + color: hsl(${Math.max(0, Math.min(120 - 120 * resultFpsPercentage, 120))}deg 100% 31%);`, opts == null ? void 0 : opts.key); + } + } + return result; + }; } -function HeadRow() { - var _a2 = useDayPicker(), classNames9 = _a2.classNames, styles = _a2.styles, showWeekNumber = _a2.showWeekNumber, locale2 = _a2.locale, weekStartsOn = _a2.weekStartsOn, ISOWeek = _a2.ISOWeek, formatWeekdayName2 = _a2.formatters.formatWeekdayName, labelWeekday2 = _a2.labels.labelWeekday; - var weekdays = getWeekdays(locale2, weekStartsOn, ISOWeek); - return Cn.createElement( - "tr", - { style: styles.head_row, className: classNames9.head_row }, - showWeekNumber && Cn.createElement("th", { scope: "col", style: styles.head_cell, className: classNames9.head_cell }), - weekdays.map(function(weekday, i4) { - return Cn.createElement("th", { key: i4, scope: "col", className: classNames9.head_cell, style: styles.head_cell, "aria-label": labelWeekday2(weekday, { locale: locale2 }) }, formatWeekdayName2(weekday, { locale: locale2 })); +function createColumn(table, columnDef, depth, parent) { + var _ref, _resolvedColumnDef$id; + const defaultColumn = table._getDefaultColumnDef(); + const resolvedColumnDef = { + ...defaultColumn, + ...columnDef + }; + const accessorKey = resolvedColumnDef.accessorKey; + let id2 = (_ref = (_resolvedColumnDef$id = resolvedColumnDef.id) != null ? _resolvedColumnDef$id : accessorKey ? accessorKey.replace(".", "_") : void 0) != null ? _ref : typeof resolvedColumnDef.header === "string" ? resolvedColumnDef.header : void 0; + let accessorFn; + if (resolvedColumnDef.accessorFn) { + accessorFn = resolvedColumnDef.accessorFn; + } else if (accessorKey) { + if (accessorKey.includes(".")) { + accessorFn = (originalRow) => { + let result = originalRow; + for (const key2 of accessorKey.split(".")) { + var _result; + result = (_result = result) == null ? void 0 : _result[key2]; + if (result === void 0) { + console.warn(`"${key2}" in deeply nested key "${accessorKey}" returned undefined.`); + } + } + return result; + }; + } else { + accessorFn = (originalRow) => originalRow[resolvedColumnDef.accessorKey]; + } + } + if (!id2) { + if (true) { + throw new Error(resolvedColumnDef.accessorFn ? `Columns require an id when using an accessorFn` : `Columns require an id when using a non-string header`); + } + throw new Error(); + } + let column = { + id: `${String(id2)}`, + accessorFn, + parent, + depth, + columnDef: resolvedColumnDef, + columns: [], + getFlatColumns: memo(() => [true], () => { + var _column$columns; + return [column, ...(_column$columns = column.columns) == null ? void 0 : _column$columns.flatMap((d5) => d5.getFlatColumns())]; + }, { + key: false, + debug: () => { + var _table$options$debugA; + return (_table$options$debugA = table.options.debugAll) != null ? _table$options$debugA : table.options.debugColumns; + } + }), + getLeafColumns: memo(() => [table._getOrderColumnsFn()], (orderColumns2) => { + var _column$columns2; + if ((_column$columns2 = column.columns) != null && _column$columns2.length) { + let leafColumns = column.columns.flatMap((column2) => column2.getLeafColumns()); + return orderColumns2(leafColumns); + } + return [column]; + }, { + key: false, + debug: () => { + var _table$options$debugA2; + return (_table$options$debugA2 = table.options.debugAll) != null ? _table$options$debugA2 : table.options.debugColumns; + } }) - ); + }; + column = table._features.reduce((obj, feature) => { + return Object.assign(obj, feature.createColumn == null ? void 0 : feature.createColumn(column, table)); + }, column); + return column; } -function Head() { - var _a2; - var _b2 = useDayPicker(), classNames9 = _b2.classNames, styles = _b2.styles, components = _b2.components; - var HeadRowComponent = (_a2 = components === null || components === void 0 ? void 0 : components.HeadRow) !== null && _a2 !== void 0 ? _a2 : HeadRow; - return Cn.createElement( - "thead", - { style: styles.head, className: classNames9.head }, - Cn.createElement(HeadRowComponent, null) - ); +function createHeader(table, column, options) { + var _options$id; + const id2 = (_options$id = options.id) != null ? _options$id : column.id; + let header = { + id: id2, + column, + index: options.index, + isPlaceholder: !!options.isPlaceholder, + placeholderId: options.placeholderId, + depth: options.depth, + subHeaders: [], + colSpan: 0, + rowSpan: 0, + headerGroup: null, + getLeafHeaders: () => { + const leafHeaders = []; + const recurseHeader = (h5) => { + if (h5.subHeaders && h5.subHeaders.length) { + h5.subHeaders.map(recurseHeader); + } + leafHeaders.push(h5); + }; + recurseHeader(header); + return leafHeaders; + }, + getContext: () => ({ + table, + header, + column + }) + }; + table._features.forEach((feature) => { + Object.assign(header, feature.createHeader == null ? void 0 : feature.createHeader(header, table)); + }); + return header; } -function DayContent(props2) { - var _a2 = useDayPicker(), locale2 = _a2.locale, formatDay2 = _a2.formatters.formatDay; - return Cn.createElement(Cn.Fragment, null, formatDay2(props2.date, { locale: locale2 })); +var Headers = { + createTable: (table) => { + return { + getHeaderGroups: memo(() => [table.getAllColumns(), table.getVisibleLeafColumns(), table.getState().columnPinning.left, table.getState().columnPinning.right], (allColumns, leafColumns, left, right) => { + var _left$map$filter, _right$map$filter; + const leftColumns = (_left$map$filter = left == null ? void 0 : left.map((columnId) => leafColumns.find((d5) => d5.id === columnId)).filter(Boolean)) != null ? _left$map$filter : []; + const rightColumns = (_right$map$filter = right == null ? void 0 : right.map((columnId) => leafColumns.find((d5) => d5.id === columnId)).filter(Boolean)) != null ? _right$map$filter : []; + const centerColumns = leafColumns.filter((column) => !(left != null && left.includes(column.id)) && !(right != null && right.includes(column.id))); + const headerGroups = buildHeaderGroups(allColumns, [...leftColumns, ...centerColumns, ...rightColumns], table); + return headerGroups; + }, { + key: "getHeaderGroups", + debug: () => { + var _table$options$debugA; + return (_table$options$debugA = table.options.debugAll) != null ? _table$options$debugA : table.options.debugHeaders; + } + }), + getCenterHeaderGroups: memo(() => [table.getAllColumns(), table.getVisibleLeafColumns(), table.getState().columnPinning.left, table.getState().columnPinning.right], (allColumns, leafColumns, left, right) => { + leafColumns = leafColumns.filter((column) => !(left != null && left.includes(column.id)) && !(right != null && right.includes(column.id))); + return buildHeaderGroups(allColumns, leafColumns, table, "center"); + }, { + key: "getCenterHeaderGroups", + debug: () => { + var _table$options$debugA2; + return (_table$options$debugA2 = table.options.debugAll) != null ? _table$options$debugA2 : table.options.debugHeaders; + } + }), + getLeftHeaderGroups: memo(() => [table.getAllColumns(), table.getVisibleLeafColumns(), table.getState().columnPinning.left], (allColumns, leafColumns, left) => { + var _left$map$filter2; + const orderedLeafColumns = (_left$map$filter2 = left == null ? void 0 : left.map((columnId) => leafColumns.find((d5) => d5.id === columnId)).filter(Boolean)) != null ? _left$map$filter2 : []; + return buildHeaderGroups(allColumns, orderedLeafColumns, table, "left"); + }, { + key: "getLeftHeaderGroups", + debug: () => { + var _table$options$debugA3; + return (_table$options$debugA3 = table.options.debugAll) != null ? _table$options$debugA3 : table.options.debugHeaders; + } + }), + getRightHeaderGroups: memo(() => [table.getAllColumns(), table.getVisibleLeafColumns(), table.getState().columnPinning.right], (allColumns, leafColumns, right) => { + var _right$map$filter2; + const orderedLeafColumns = (_right$map$filter2 = right == null ? void 0 : right.map((columnId) => leafColumns.find((d5) => d5.id === columnId)).filter(Boolean)) != null ? _right$map$filter2 : []; + return buildHeaderGroups(allColumns, orderedLeafColumns, table, "right"); + }, { + key: "getRightHeaderGroups", + debug: () => { + var _table$options$debugA4; + return (_table$options$debugA4 = table.options.debugAll) != null ? _table$options$debugA4 : table.options.debugHeaders; + } + }), + getFooterGroups: memo(() => [table.getHeaderGroups()], (headerGroups) => { + return [...headerGroups].reverse(); + }, { + key: "getFooterGroups", + debug: () => { + var _table$options$debugA5; + return (_table$options$debugA5 = table.options.debugAll) != null ? _table$options$debugA5 : table.options.debugHeaders; + } + }), + getLeftFooterGroups: memo(() => [table.getLeftHeaderGroups()], (headerGroups) => { + return [...headerGroups].reverse(); + }, { + key: "getLeftFooterGroups", + debug: () => { + var _table$options$debugA6; + return (_table$options$debugA6 = table.options.debugAll) != null ? _table$options$debugA6 : table.options.debugHeaders; + } + }), + getCenterFooterGroups: memo(() => [table.getCenterHeaderGroups()], (headerGroups) => { + return [...headerGroups].reverse(); + }, { + key: "getCenterFooterGroups", + debug: () => { + var _table$options$debugA7; + return (_table$options$debugA7 = table.options.debugAll) != null ? _table$options$debugA7 : table.options.debugHeaders; + } + }), + getRightFooterGroups: memo(() => [table.getRightHeaderGroups()], (headerGroups) => { + return [...headerGroups].reverse(); + }, { + key: "getRightFooterGroups", + debug: () => { + var _table$options$debugA8; + return (_table$options$debugA8 = table.options.debugAll) != null ? _table$options$debugA8 : table.options.debugHeaders; + } + }), + getFlatHeaders: memo(() => [table.getHeaderGroups()], (headerGroups) => { + return headerGroups.map((headerGroup) => { + return headerGroup.headers; + }).flat(); + }, { + key: "getFlatHeaders", + debug: () => { + var _table$options$debugA9; + return (_table$options$debugA9 = table.options.debugAll) != null ? _table$options$debugA9 : table.options.debugHeaders; + } + }), + getLeftFlatHeaders: memo(() => [table.getLeftHeaderGroups()], (left) => { + return left.map((headerGroup) => { + return headerGroup.headers; + }).flat(); + }, { + key: "getLeftFlatHeaders", + debug: () => { + var _table$options$debugA10; + return (_table$options$debugA10 = table.options.debugAll) != null ? _table$options$debugA10 : table.options.debugHeaders; + } + }), + getCenterFlatHeaders: memo(() => [table.getCenterHeaderGroups()], (left) => { + return left.map((headerGroup) => { + return headerGroup.headers; + }).flat(); + }, { + key: "getCenterFlatHeaders", + debug: () => { + var _table$options$debugA11; + return (_table$options$debugA11 = table.options.debugAll) != null ? _table$options$debugA11 : table.options.debugHeaders; + } + }), + getRightFlatHeaders: memo(() => [table.getRightHeaderGroups()], (left) => { + return left.map((headerGroup) => { + return headerGroup.headers; + }).flat(); + }, { + key: "getRightFlatHeaders", + debug: () => { + var _table$options$debugA12; + return (_table$options$debugA12 = table.options.debugAll) != null ? _table$options$debugA12 : table.options.debugHeaders; + } + }), + getCenterLeafHeaders: memo(() => [table.getCenterFlatHeaders()], (flatHeaders) => { + return flatHeaders.filter((header) => { + var _header$subHeaders; + return !((_header$subHeaders = header.subHeaders) != null && _header$subHeaders.length); + }); + }, { + key: "getCenterLeafHeaders", + debug: () => { + var _table$options$debugA13; + return (_table$options$debugA13 = table.options.debugAll) != null ? _table$options$debugA13 : table.options.debugHeaders; + } + }), + getLeftLeafHeaders: memo(() => [table.getLeftFlatHeaders()], (flatHeaders) => { + return flatHeaders.filter((header) => { + var _header$subHeaders2; + return !((_header$subHeaders2 = header.subHeaders) != null && _header$subHeaders2.length); + }); + }, { + key: "getLeftLeafHeaders", + debug: () => { + var _table$options$debugA14; + return (_table$options$debugA14 = table.options.debugAll) != null ? _table$options$debugA14 : table.options.debugHeaders; + } + }), + getRightLeafHeaders: memo(() => [table.getRightFlatHeaders()], (flatHeaders) => { + return flatHeaders.filter((header) => { + var _header$subHeaders3; + return !((_header$subHeaders3 = header.subHeaders) != null && _header$subHeaders3.length); + }); + }, { + key: "getRightLeafHeaders", + debug: () => { + var _table$options$debugA15; + return (_table$options$debugA15 = table.options.debugAll) != null ? _table$options$debugA15 : table.options.debugHeaders; + } + }), + getLeafHeaders: memo(() => [table.getLeftHeaderGroups(), table.getCenterHeaderGroups(), table.getRightHeaderGroups()], (left, center, right) => { + var _left$0$headers, _left$, _center$0$headers, _center$, _right$0$headers, _right$; + return [...(_left$0$headers = (_left$ = left[0]) == null ? void 0 : _left$.headers) != null ? _left$0$headers : [], ...(_center$0$headers = (_center$ = center[0]) == null ? void 0 : _center$.headers) != null ? _center$0$headers : [], ...(_right$0$headers = (_right$ = right[0]) == null ? void 0 : _right$.headers) != null ? _right$0$headers : []].map((header) => { + return header.getLeafHeaders(); + }).flat(); + }, { + key: "getLeafHeaders", + debug: () => { + var _table$options$debugA16; + return (_table$options$debugA16 = table.options.debugAll) != null ? _table$options$debugA16 : table.options.debugHeaders; + } + }) + }; + } +}; +function buildHeaderGroups(allColumns, columnsToGroup, table, headerFamily) { + var _headerGroups$0$heade, _headerGroups$; + let maxDepth = 0; + const findMaxDepth = function(columns, depth) { + if (depth === void 0) { + depth = 1; + } + maxDepth = Math.max(maxDepth, depth); + columns.filter((column) => column.getIsVisible()).forEach((column) => { + var _column$columns; + if ((_column$columns = column.columns) != null && _column$columns.length) { + findMaxDepth(column.columns, depth + 1); + } + }, 0); + }; + findMaxDepth(allColumns); + let headerGroups = []; + const createHeaderGroup = (headersToGroup, depth) => { + const headerGroup = { + depth, + id: [headerFamily, `${depth}`].filter(Boolean).join("_"), + headers: [] + }; + const pendingParentHeaders = []; + headersToGroup.forEach((headerToGroup) => { + const latestPendingParentHeader = [...pendingParentHeaders].reverse()[0]; + const isLeafHeader = headerToGroup.column.depth === headerGroup.depth; + let column; + let isPlaceholder = false; + if (isLeafHeader && headerToGroup.column.parent) { + column = headerToGroup.column.parent; + } else { + column = headerToGroup.column; + isPlaceholder = true; + } + if (latestPendingParentHeader && (latestPendingParentHeader == null ? void 0 : latestPendingParentHeader.column) === column) { + latestPendingParentHeader.subHeaders.push(headerToGroup); + } else { + const header = createHeader(table, column, { + id: [headerFamily, depth, column.id, headerToGroup == null ? void 0 : headerToGroup.id].filter(Boolean).join("_"), + isPlaceholder, + placeholderId: isPlaceholder ? `${pendingParentHeaders.filter((d5) => d5.column === column).length}` : void 0, + depth, + index: pendingParentHeaders.length + }); + header.subHeaders.push(headerToGroup); + pendingParentHeaders.push(header); + } + headerGroup.headers.push(headerToGroup); + headerToGroup.headerGroup = headerGroup; + }); + headerGroups.push(headerGroup); + if (depth > 0) { + createHeaderGroup(pendingParentHeaders, depth - 1); + } + }; + const bottomHeaders = columnsToGroup.map((column, index) => createHeader(table, column, { + depth: maxDepth, + index + })); + createHeaderGroup(bottomHeaders, maxDepth - 1); + headerGroups.reverse(); + const recurseHeadersForSpans = (headers) => { + const filteredHeaders = headers.filter((header) => header.column.getIsVisible()); + return filteredHeaders.map((header) => { + let colSpan = 0; + let rowSpan = 0; + let childRowSpans = [0]; + if (header.subHeaders && header.subHeaders.length) { + childRowSpans = []; + recurseHeadersForSpans(header.subHeaders).forEach((_ref) => { + let { + colSpan: childColSpan, + rowSpan: childRowSpan + } = _ref; + colSpan += childColSpan; + childRowSpans.push(childRowSpan); + }); + } else { + colSpan = 1; + } + const minChildRowSpan = Math.min(...childRowSpans); + rowSpan = rowSpan + minChildRowSpan; + header.colSpan = colSpan; + header.rowSpan = rowSpan; + return { + colSpan, + rowSpan + }; + }); + }; + recurseHeadersForSpans((_headerGroups$0$heade = (_headerGroups$ = headerGroups[0]) == null ? void 0 : _headerGroups$.headers) != null ? _headerGroups$0$heade : []); + return headerGroups; } -var SelectMultipleContext = F(void 0); -function SelectMultipleProvider(props2) { - if (!isDayPickerMultiple(props2.initialProps)) { - var emptyContextValue = { - selected: void 0, - modifiers: { - disabled: [] +var defaultColumnSizing = { + size: 150, + minSize: 20, + maxSize: Number.MAX_SAFE_INTEGER +}; +var getDefaultColumnSizingInfoState = () => ({ + startOffset: null, + startSize: null, + deltaOffset: null, + deltaPercentage: null, + isResizingColumn: false, + columnSizingStart: [] +}); +var ColumnSizing = { + getDefaultColumnDef: () => { + return defaultColumnSizing; + }, + getInitialState: (state) => { + return { + columnSizing: {}, + columnSizingInfo: getDefaultColumnSizingInfoState(), + ...state + }; + }, + getDefaultOptions: (table) => { + return { + columnResizeMode: "onEnd", + onColumnSizingChange: makeStateUpdater("columnSizing", table), + onColumnSizingInfoChange: makeStateUpdater("columnSizingInfo", table) + }; + }, + createColumn: (column, table) => { + return { + getSize: () => { + var _column$columnDef$min, _ref, _column$columnDef$max; + const columnSize = table.getState().columnSizing[column.id]; + return Math.min(Math.max((_column$columnDef$min = column.columnDef.minSize) != null ? _column$columnDef$min : defaultColumnSizing.minSize, (_ref = columnSize != null ? columnSize : column.columnDef.size) != null ? _ref : defaultColumnSizing.size), (_column$columnDef$max = column.columnDef.maxSize) != null ? _column$columnDef$max : defaultColumnSizing.maxSize); + }, + getStart: (position) => { + const columns = !position ? table.getVisibleLeafColumns() : position === "left" ? table.getLeftVisibleLeafColumns() : table.getRightVisibleLeafColumns(); + const index = columns.findIndex((d5) => d5.id === column.id); + if (index > 0) { + const prevSiblingColumn = columns[index - 1]; + return prevSiblingColumn.getStart(position) + prevSiblingColumn.getSize(); + } + return 0; + }, + resetSize: () => { + table.setColumnSizing((_ref2) => { + let { + [column.id]: _12, + ...rest + } = _ref2; + return rest; + }); + }, + getCanResize: () => { + var _column$columnDef$ena, _table$options$enable; + return ((_column$columnDef$ena = column.columnDef.enableResizing) != null ? _column$columnDef$ena : true) && ((_table$options$enable = table.options.enableColumnResizing) != null ? _table$options$enable : true); + }, + getIsResizing: () => { + return table.getState().columnSizingInfo.isResizingColumn === column.id; + } + }; + }, + createHeader: (header, table) => { + return { + getSize: () => { + let sum2 = 0; + const recurse = (header2) => { + if (header2.subHeaders.length) { + header2.subHeaders.forEach(recurse); + } else { + var _header$column$getSiz; + sum2 += (_header$column$getSiz = header2.column.getSize()) != null ? _header$column$getSiz : 0; + } + }; + recurse(header); + return sum2; + }, + getStart: () => { + if (header.index > 0) { + const prevSiblingHeader = header.headerGroup.headers[header.index - 1]; + return prevSiblingHeader.getStart() + prevSiblingHeader.getSize(); + } + return 0; + }, + getResizeHandler: () => { + const column = table.getColumn(header.column.id); + const canResize = column == null ? void 0 : column.getCanResize(); + return (e4) => { + if (!column || !canResize) { + return; + } + e4.persist == null ? void 0 : e4.persist(); + if (isTouchStartEvent(e4)) { + if (e4.touches && e4.touches.length > 1) { + return; + } + } + const startSize = header.getSize(); + const columnSizingStart = header ? header.getLeafHeaders().map((d5) => [d5.column.id, d5.column.getSize()]) : [[column.id, column.getSize()]]; + const clientX = isTouchStartEvent(e4) ? Math.round(e4.touches[0].clientX) : e4.clientX; + const newColumnSizing = {}; + const updateOffset = (eventType, clientXPos) => { + if (typeof clientXPos !== "number") { + return; + } + table.setColumnSizingInfo((old) => { + var _old$startOffset, _old$startSize; + const deltaOffset = clientXPos - ((_old$startOffset = old == null ? void 0 : old.startOffset) != null ? _old$startOffset : 0); + const deltaPercentage = Math.max(deltaOffset / ((_old$startSize = old == null ? void 0 : old.startSize) != null ? _old$startSize : 0), -0.999999); + old.columnSizingStart.forEach((_ref3) => { + let [columnId, headerSize] = _ref3; + newColumnSizing[columnId] = Math.round(Math.max(headerSize + headerSize * deltaPercentage, 0) * 100) / 100; + }); + return { + ...old, + deltaOffset, + deltaPercentage + }; + }); + if (table.options.columnResizeMode === "onChange" || eventType === "end") { + table.setColumnSizing((old) => ({ + ...old, + ...newColumnSizing + })); + } + }; + const onMove = (clientXPos) => updateOffset("move", clientXPos); + const onEnd = (clientXPos) => { + updateOffset("end", clientXPos); + table.setColumnSizingInfo((old) => ({ + ...old, + isResizingColumn: false, + startOffset: null, + startSize: null, + deltaOffset: null, + deltaPercentage: null, + columnSizingStart: [] + })); + }; + const mouseEvents = { + moveHandler: (e5) => onMove(e5.clientX), + upHandler: (e5) => { + document.removeEventListener("mousemove", mouseEvents.moveHandler); + document.removeEventListener("mouseup", mouseEvents.upHandler); + onEnd(e5.clientX); + } + }; + const touchEvents = { + moveHandler: (e5) => { + if (e5.cancelable) { + e5.preventDefault(); + e5.stopPropagation(); + } + onMove(e5.touches[0].clientX); + return false; + }, + upHandler: (e5) => { + var _e$touches$; + document.removeEventListener("touchmove", touchEvents.moveHandler); + document.removeEventListener("touchend", touchEvents.upHandler); + if (e5.cancelable) { + e5.preventDefault(); + e5.stopPropagation(); + } + onEnd((_e$touches$ = e5.touches[0]) == null ? void 0 : _e$touches$.clientX); + } + }; + const passiveIfSupported = passiveEventSupported() ? { + passive: false + } : false; + if (isTouchStartEvent(e4)) { + document.addEventListener("touchmove", touchEvents.moveHandler, passiveIfSupported); + document.addEventListener("touchend", touchEvents.upHandler, passiveIfSupported); + } else { + document.addEventListener("mousemove", mouseEvents.moveHandler, passiveIfSupported); + document.addEventListener("mouseup", mouseEvents.upHandler, passiveIfSupported); + } + table.setColumnSizingInfo((old) => ({ + ...old, + startOffset: clientX, + startSize, + deltaOffset: 0, + deltaPercentage: 0, + columnSizingStart, + isResizingColumn: column.id + })); + }; + } + }; + }, + createTable: (table) => { + return { + setColumnSizing: (updater) => table.options.onColumnSizingChange == null ? void 0 : table.options.onColumnSizingChange(updater), + setColumnSizingInfo: (updater) => table.options.onColumnSizingInfoChange == null ? void 0 : table.options.onColumnSizingInfoChange(updater), + resetColumnSizing: (defaultState) => { + var _table$initialState$c; + table.setColumnSizing(defaultState ? {} : (_table$initialState$c = table.initialState.columnSizing) != null ? _table$initialState$c : {}); + }, + resetHeaderSizeInfo: (defaultState) => { + var _table$initialState$c2; + table.setColumnSizingInfo(defaultState ? getDefaultColumnSizingInfoState() : (_table$initialState$c2 = table.initialState.columnSizingInfo) != null ? _table$initialState$c2 : getDefaultColumnSizingInfoState()); + }, + getTotalSize: () => { + var _table$getHeaderGroup, _table$getHeaderGroup2; + return (_table$getHeaderGroup = (_table$getHeaderGroup2 = table.getHeaderGroups()[0]) == null ? void 0 : _table$getHeaderGroup2.headers.reduce((sum2, header) => { + return sum2 + header.getSize(); + }, 0)) != null ? _table$getHeaderGroup : 0; + }, + getLeftTotalSize: () => { + var _table$getLeftHeaderG, _table$getLeftHeaderG2; + return (_table$getLeftHeaderG = (_table$getLeftHeaderG2 = table.getLeftHeaderGroups()[0]) == null ? void 0 : _table$getLeftHeaderG2.headers.reduce((sum2, header) => { + return sum2 + header.getSize(); + }, 0)) != null ? _table$getLeftHeaderG : 0; + }, + getCenterTotalSize: () => { + var _table$getCenterHeade, _table$getCenterHeade2; + return (_table$getCenterHeade = (_table$getCenterHeade2 = table.getCenterHeaderGroups()[0]) == null ? void 0 : _table$getCenterHeade2.headers.reduce((sum2, header) => { + return sum2 + header.getSize(); + }, 0)) != null ? _table$getCenterHeade : 0; + }, + getRightTotalSize: () => { + var _table$getRightHeader, _table$getRightHeader2; + return (_table$getRightHeader = (_table$getRightHeader2 = table.getRightHeaderGroups()[0]) == null ? void 0 : _table$getRightHeader2.headers.reduce((sum2, header) => { + return sum2 + header.getSize(); + }, 0)) != null ? _table$getRightHeader : 0; } }; - return Cn.createElement(SelectMultipleContext.Provider, { value: emptyContextValue }, props2.children); } - return Cn.createElement(SelectMultipleProviderInternal, { initialProps: props2.initialProps, children: props2.children }); -} -function SelectMultipleProviderInternal(_a2) { - var initialProps = _a2.initialProps, children = _a2.children; - var selected = initialProps.selected, min3 = initialProps.min, max3 = initialProps.max; - var onDayClick = function(day, activeModifiers, e4) { - var _a3, _b2; - (_a3 = initialProps.onDayClick) === null || _a3 === void 0 ? void 0 : _a3.call(initialProps, day, activeModifiers, e4); - var isMinSelected = Boolean(activeModifiers.selected && min3 && (selected === null || selected === void 0 ? void 0 : selected.length) === min3); - if (isMinSelected) { - return; - } - var isMaxSelected = Boolean(!activeModifiers.selected && max3 && (selected === null || selected === void 0 ? void 0 : selected.length) === max3); - if (isMaxSelected) { - return; - } - var selectedDays = selected ? __spreadArray([], selected, true) : []; - if (activeModifiers.selected) { - var index = selectedDays.findIndex(function(selectedDay) { - return isSameDay(day, selectedDay); - }); - selectedDays.splice(index, 1); - } else { - selectedDays.push(day); - } - (_b2 = initialProps.onSelect) === null || _b2 === void 0 ? void 0 : _b2.call(initialProps, selectedDays, day, activeModifiers, e4); - }; - var modifiers = { - disabled: [] - }; - if (selected) { - modifiers.disabled.push(function(day) { - var isMaxSelected = max3 && selected.length > max3 - 1; - var isSelected = selected.some(function(selectedDay) { - return isSameDay(selectedDay, day); - }); - return Boolean(isMaxSelected && !isSelected); - }); +}; +var passiveSupported = null; +function passiveEventSupported() { + if (typeof passiveSupported === "boolean") + return passiveSupported; + let supported = false; + try { + const options = { + get passive() { + supported = true; + return false; + } + }; + const noop3 = () => { + }; + window.addEventListener("test", noop3, options); + window.removeEventListener("test", noop3); + } catch (err) { + supported = false; } - var contextValue = { - selected, - onDayClick, - modifiers - }; - return Cn.createElement(SelectMultipleContext.Provider, { value: contextValue }, children); + passiveSupported = supported; + return passiveSupported; } -function useSelectMultiple() { - var context = q2(SelectMultipleContext); - if (!context) { - throw new Error("useSelectMultiple must be used within a SelectMultipleProvider"); - } - return context; +function isTouchStartEvent(e4) { + return e4.type === "touchstart"; } -function addToRange(day, range) { - var _a2 = range || {}, from = _a2.from, to = _a2.to; - if (!from) { - return { from: day, to: void 0 }; - } - if (!to && isSameDay(from, day)) { - return { from, to: day }; - } - if (!to && isBefore(day, from)) { - return { from: day, to: from }; - } - if (!to) { - return { from, to: day }; - } - if (isSameDay(to, day) && isSameDay(from, day)) { - return void 0; - } - if (isSameDay(to, day)) { - return { from: to, to: void 0 }; - } - if (isSameDay(from, day)) { - return void 0; +var Expanding = { + getInitialState: (state) => { + return { + expanded: {}, + ...state + }; + }, + getDefaultOptions: (table) => { + return { + onExpandedChange: makeStateUpdater("expanded", table), + paginateExpandedRows: true + }; + }, + createTable: (table) => { + let registered = false; + let queued = false; + return { + _autoResetExpanded: () => { + var _ref, _table$options$autoRe; + if (!registered) { + table._queue(() => { + registered = true; + }); + return; + } + if ((_ref = (_table$options$autoRe = table.options.autoResetAll) != null ? _table$options$autoRe : table.options.autoResetExpanded) != null ? _ref : !table.options.manualExpanding) { + if (queued) + return; + queued = true; + table._queue(() => { + table.resetExpanded(); + queued = false; + }); + } + }, + setExpanded: (updater) => table.options.onExpandedChange == null ? void 0 : table.options.onExpandedChange(updater), + toggleAllRowsExpanded: (expanded) => { + if (expanded != null ? expanded : !table.getIsAllRowsExpanded()) { + table.setExpanded(true); + } else { + table.setExpanded({}); + } + }, + resetExpanded: (defaultState) => { + var _table$initialState$e, _table$initialState; + table.setExpanded(defaultState ? {} : (_table$initialState$e = (_table$initialState = table.initialState) == null ? void 0 : _table$initialState.expanded) != null ? _table$initialState$e : {}); + }, + getCanSomeRowsExpand: () => { + return table.getRowModel().flatRows.some((row) => row.getCanExpand()); + }, + getToggleAllRowsExpandedHandler: () => { + return (e4) => { + e4.persist == null ? void 0 : e4.persist(); + table.toggleAllRowsExpanded(); + }; + }, + getIsSomeRowsExpanded: () => { + const expanded = table.getState().expanded; + return expanded === true || Object.values(expanded).some(Boolean); + }, + getIsAllRowsExpanded: () => { + const expanded = table.getState().expanded; + if (typeof expanded === "boolean") { + return expanded === true; + } + if (!Object.keys(expanded).length) { + return false; + } + if (table.getRowModel().flatRows.some((row) => !row.getIsExpanded())) { + return false; + } + return true; + }, + getExpandedDepth: () => { + let maxDepth = 0; + const rowIds = table.getState().expanded === true ? Object.keys(table.getRowModel().rowsById) : Object.keys(table.getState().expanded); + rowIds.forEach((id2) => { + const splitId = id2.split("."); + maxDepth = Math.max(maxDepth, splitId.length); + }); + return maxDepth; + }, + getPreExpandedRowModel: () => table.getSortedRowModel(), + getExpandedRowModel: () => { + if (!table._getExpandedRowModel && table.options.getExpandedRowModel) { + table._getExpandedRowModel = table.options.getExpandedRowModel(table); + } + if (table.options.manualExpanding || !table._getExpandedRowModel) { + return table.getPreExpandedRowModel(); + } + return table._getExpandedRowModel(); + } + }; + }, + createRow: (row, table) => { + return { + toggleExpanded: (expanded) => { + table.setExpanded((old) => { + var _expanded; + const exists = old === true ? true : !!(old != null && old[row.id]); + let oldExpanded = {}; + if (old === true) { + Object.keys(table.getRowModel().rowsById).forEach((rowId) => { + oldExpanded[rowId] = true; + }); + } else { + oldExpanded = old; + } + expanded = (_expanded = expanded) != null ? _expanded : !exists; + if (!exists && expanded) { + return { + ...oldExpanded, + [row.id]: true + }; + } + if (exists && !expanded) { + const { + [row.id]: _12, + ...rest + } = oldExpanded; + return rest; + } + return old; + }); + }, + getIsExpanded: () => { + var _table$options$getIsR; + const expanded = table.getState().expanded; + return !!((_table$options$getIsR = table.options.getIsRowExpanded == null ? void 0 : table.options.getIsRowExpanded(row)) != null ? _table$options$getIsR : expanded === true || (expanded == null ? void 0 : expanded[row.id])); + }, + getCanExpand: () => { + var _table$options$getRow, _table$options$enable, _row$subRows; + return (_table$options$getRow = table.options.getRowCanExpand == null ? void 0 : table.options.getRowCanExpand(row)) != null ? _table$options$getRow : ((_table$options$enable = table.options.enableExpanding) != null ? _table$options$enable : true) && !!((_row$subRows = row.subRows) != null && _row$subRows.length); + }, + getToggleExpandedHandler: () => { + const canExpand = row.getCanExpand(); + return () => { + if (!canExpand) + return; + row.toggleExpanded(); + }; + } + }; } - if (isAfter(from, day)) { - return { from: day, to }; +}; +var includesString = (row, columnId, filterValue) => { + var _row$getValue; + const search = filterValue.toLowerCase(); + return Boolean((_row$getValue = row.getValue(columnId)) == null ? void 0 : _row$getValue.toLowerCase().includes(search)); +}; +includesString.autoRemove = (val) => testFalsey(val); +var includesStringSensitive = (row, columnId, filterValue) => { + var _row$getValue2; + return Boolean((_row$getValue2 = row.getValue(columnId)) == null ? void 0 : _row$getValue2.includes(filterValue)); +}; +includesStringSensitive.autoRemove = (val) => testFalsey(val); +var equalsString = (row, columnId, filterValue) => { + var _row$getValue3; + return ((_row$getValue3 = row.getValue(columnId)) == null ? void 0 : _row$getValue3.toLowerCase()) === filterValue.toLowerCase(); +}; +equalsString.autoRemove = (val) => testFalsey(val); +var arrIncludes = (row, columnId, filterValue) => { + var _row$getValue4; + return (_row$getValue4 = row.getValue(columnId)) == null ? void 0 : _row$getValue4.includes(filterValue); +}; +arrIncludes.autoRemove = (val) => testFalsey(val) || !(val != null && val.length); +var arrIncludesAll = (row, columnId, filterValue) => { + return !filterValue.some((val) => { + var _row$getValue5; + return !((_row$getValue5 = row.getValue(columnId)) != null && _row$getValue5.includes(val)); + }); +}; +arrIncludesAll.autoRemove = (val) => testFalsey(val) || !(val != null && val.length); +var arrIncludesSome = (row, columnId, filterValue) => { + return filterValue.some((val) => { + var _row$getValue6; + return (_row$getValue6 = row.getValue(columnId)) == null ? void 0 : _row$getValue6.includes(val); + }); +}; +arrIncludesSome.autoRemove = (val) => testFalsey(val) || !(val != null && val.length); +var equals = (row, columnId, filterValue) => { + return row.getValue(columnId) === filterValue; +}; +equals.autoRemove = (val) => testFalsey(val); +var weakEquals = (row, columnId, filterValue) => { + return row.getValue(columnId) == filterValue; +}; +weakEquals.autoRemove = (val) => testFalsey(val); +var inNumberRange = (row, columnId, filterValue) => { + let [min3, max3] = filterValue; + const rowValue = row.getValue(columnId); + return rowValue >= min3 && rowValue <= max3; +}; +inNumberRange.resolveFilterValue = (val) => { + let [unsafeMin, unsafeMax] = val; + let parsedMin = typeof unsafeMin !== "number" ? parseFloat(unsafeMin) : unsafeMin; + let parsedMax = typeof unsafeMax !== "number" ? parseFloat(unsafeMax) : unsafeMax; + let min3 = unsafeMin === null || Number.isNaN(parsedMin) ? -Infinity : parsedMin; + let max3 = unsafeMax === null || Number.isNaN(parsedMax) ? Infinity : parsedMax; + if (min3 > max3) { + const temp = min3; + min3 = max3; + max3 = temp; } - return { from, to: day }; + return [min3, max3]; +}; +inNumberRange.autoRemove = (val) => testFalsey(val) || testFalsey(val[0]) && testFalsey(val[1]); +var filterFns = { + includesString, + includesStringSensitive, + equalsString, + arrIncludes, + arrIncludesAll, + arrIncludesSome, + equals, + weakEquals, + inNumberRange +}; +function testFalsey(val) { + return val === void 0 || val === null || val === ""; } -var SelectRangeContext = F(void 0); -function SelectRangeProvider(props2) { - if (!isDayPickerRange(props2.initialProps)) { - var emptyContextValue = { - selected: void 0, - modifiers: { - range_start: [], - range_end: [], - range_middle: [], - disabled: [] +var Filters = { + getDefaultColumnDef: () => { + return { + filterFn: "auto" + }; + }, + getInitialState: (state) => { + return { + columnFilters: [], + globalFilter: void 0, + ...state + }; + }, + getDefaultOptions: (table) => { + return { + onColumnFiltersChange: makeStateUpdater("columnFilters", table), + onGlobalFilterChange: makeStateUpdater("globalFilter", table), + filterFromLeafRows: false, + maxLeafRowFilterDepth: 100, + globalFilterFn: "auto", + getColumnCanGlobalFilter: (column) => { + var _table$getCoreRowMode, _table$getCoreRowMode2; + const value = (_table$getCoreRowMode = table.getCoreRowModel().flatRows[0]) == null ? void 0 : (_table$getCoreRowMode2 = _table$getCoreRowMode._getAllCellsByColumnId()[column.id]) == null ? void 0 : _table$getCoreRowMode2.getValue(); + return typeof value === "string" || typeof value === "number"; } }; - return Cn.createElement(SelectRangeContext.Provider, { value: emptyContextValue }, props2.children); - } - return Cn.createElement(SelectRangeProviderInternal, { initialProps: props2.initialProps, children: props2.children }); -} -function SelectRangeProviderInternal(_a2) { - var initialProps = _a2.initialProps, children = _a2.children; - var selected = initialProps.selected; - var _b2 = selected || {}, selectedFrom = _b2.from, selectedTo = _b2.to; - var min3 = initialProps.min; - var max3 = initialProps.max; - var onDayClick = function(day, activeModifiers, e4) { - var _a3, _b3; - (_a3 = initialProps.onDayClick) === null || _a3 === void 0 ? void 0 : _a3.call(initialProps, day, activeModifiers, e4); - var newRange = addToRange(day, selected); - (_b3 = initialProps.onSelect) === null || _b3 === void 0 ? void 0 : _b3.call(initialProps, newRange, day, activeModifiers, e4); - }; - var modifiers = { - range_start: [], - range_end: [], - range_middle: [], - disabled: [] - }; - if (selectedFrom) { - modifiers.range_start = [selectedFrom]; - if (!selectedTo) { - modifiers.range_end = [selectedFrom]; - } else { - modifiers.range_end = [selectedTo]; - if (!isSameDay(selectedFrom, selectedTo)) { - modifiers.range_middle = [ - { - after: selectedFrom, - before: selectedTo + }, + createColumn: (column, table) => { + return { + getAutoFilterFn: () => { + const firstRow = table.getCoreRowModel().flatRows[0]; + const value = firstRow == null ? void 0 : firstRow.getValue(column.id); + if (typeof value === "string") { + return filterFns.includesString; + } + if (typeof value === "number") { + return filterFns.inNumberRange; + } + if (typeof value === "boolean") { + return filterFns.equals; + } + if (value !== null && typeof value === "object") { + return filterFns.equals; + } + if (Array.isArray(value)) { + return filterFns.arrIncludes; + } + return filterFns.weakEquals; + }, + getFilterFn: () => { + var _table$options$filter, _table$options$filter2; + return isFunction(column.columnDef.filterFn) ? column.columnDef.filterFn : column.columnDef.filterFn === "auto" ? column.getAutoFilterFn() : (_table$options$filter = (_table$options$filter2 = table.options.filterFns) == null ? void 0 : _table$options$filter2[column.columnDef.filterFn]) != null ? _table$options$filter : filterFns[column.columnDef.filterFn]; + }, + getCanFilter: () => { + var _column$columnDef$ena, _table$options$enable, _table$options$enable2; + return ((_column$columnDef$ena = column.columnDef.enableColumnFilter) != null ? _column$columnDef$ena : true) && ((_table$options$enable = table.options.enableColumnFilters) != null ? _table$options$enable : true) && ((_table$options$enable2 = table.options.enableFilters) != null ? _table$options$enable2 : true) && !!column.accessorFn; + }, + getCanGlobalFilter: () => { + var _column$columnDef$ena2, _table$options$enable3, _table$options$enable4, _table$options$getCol; + return ((_column$columnDef$ena2 = column.columnDef.enableGlobalFilter) != null ? _column$columnDef$ena2 : true) && ((_table$options$enable3 = table.options.enableGlobalFilter) != null ? _table$options$enable3 : true) && ((_table$options$enable4 = table.options.enableFilters) != null ? _table$options$enable4 : true) && ((_table$options$getCol = table.options.getColumnCanGlobalFilter == null ? void 0 : table.options.getColumnCanGlobalFilter(column)) != null ? _table$options$getCol : true) && !!column.accessorFn; + }, + getIsFiltered: () => column.getFilterIndex() > -1, + getFilterValue: () => { + var _table$getState$colum, _table$getState$colum2; + return (_table$getState$colum = table.getState().columnFilters) == null ? void 0 : (_table$getState$colum2 = _table$getState$colum.find((d5) => d5.id === column.id)) == null ? void 0 : _table$getState$colum2.value; + }, + getFilterIndex: () => { + var _table$getState$colum3, _table$getState$colum4; + return (_table$getState$colum3 = (_table$getState$colum4 = table.getState().columnFilters) == null ? void 0 : _table$getState$colum4.findIndex((d5) => d5.id === column.id)) != null ? _table$getState$colum3 : -1; + }, + setFilterValue: (value) => { + table.setColumnFilters((old) => { + const filterFn = column.getFilterFn(); + const previousfilter = old == null ? void 0 : old.find((d5) => d5.id === column.id); + const newFilter = functionalUpdate(value, previousfilter ? previousfilter.value : void 0); + if (shouldAutoRemoveFilter(filterFn, newFilter, column)) { + var _old$filter; + return (_old$filter = old == null ? void 0 : old.filter((d5) => d5.id !== column.id)) != null ? _old$filter : []; } - ]; + const newFilterObj = { + id: column.id, + value: newFilter + }; + if (previousfilter) { + var _old$map; + return (_old$map = old == null ? void 0 : old.map((d5) => { + if (d5.id === column.id) { + return newFilterObj; + } + return d5; + })) != null ? _old$map : []; + } + if (old != null && old.length) { + return [...old, newFilterObj]; + } + return [newFilterObj]; + }); + }, + _getFacetedRowModel: table.options.getFacetedRowModel && table.options.getFacetedRowModel(table, column.id), + getFacetedRowModel: () => { + if (!column._getFacetedRowModel) { + return table.getPreFilteredRowModel(); + } + return column._getFacetedRowModel(); + }, + _getFacetedUniqueValues: table.options.getFacetedUniqueValues && table.options.getFacetedUniqueValues(table, column.id), + getFacetedUniqueValues: () => { + if (!column._getFacetedUniqueValues) { + return /* @__PURE__ */ new Map(); + } + return column._getFacetedUniqueValues(); + }, + _getFacetedMinMaxValues: table.options.getFacetedMinMaxValues && table.options.getFacetedMinMaxValues(table, column.id), + getFacetedMinMaxValues: () => { + if (!column._getFacetedMinMaxValues) { + return void 0; + } + return column._getFacetedMinMaxValues(); } - } - } - if (min3) { - if (selectedFrom && !selectedTo) { - modifiers.disabled.push({ - after: subDays(selectedFrom, min3 - 1), - before: addDays(selectedFrom, min3 - 1) - }); - } - if (selectedFrom && selectedTo) { - modifiers.disabled.push({ - after: selectedFrom, - before: addDays(selectedFrom, min3 - 1) - }); - } - } - if (max3) { - if (selectedFrom && !selectedTo) { - modifiers.disabled.push({ - before: addDays(selectedFrom, -max3 + 1) - }); - modifiers.disabled.push({ - after: addDays(selectedFrom, max3 - 1) - }); - } - if (selectedFrom && selectedTo) { - var selectedCount = differenceInCalendarDays(selectedTo, selectedFrom) + 1; - var offset = max3 - selectedCount; - modifiers.disabled.push({ - before: subDays(selectedFrom, offset) - }); - modifiers.disabled.push({ - after: addDays(selectedTo, offset) - }); - } - } - return Cn.createElement(SelectRangeContext.Provider, { value: { selected, onDayClick, modifiers } }, children); -} -function useSelectRange() { - var context = q2(SelectRangeContext); - if (!context) { - throw new Error("useSelectRange must be used within a SelectRangeProvider"); - } - return context; -} -function matcherToArray(matcher) { - if (Array.isArray(matcher)) { - return __spreadArray([], matcher, true); - } else if (matcher !== void 0) { - return [matcher]; - } else { - return []; - } -} -function getCustomModifiers(dayModifiers) { - var customModifiers = {}; - Object.entries(dayModifiers).forEach(function(_a2) { - var modifier = _a2[0], matcher = _a2[1]; - customModifiers[modifier] = matcherToArray(matcher); - }); - return customModifiers; -} -var InternalModifier; -(function(InternalModifier2) { - InternalModifier2["Outside"] = "outside"; - InternalModifier2["Disabled"] = "disabled"; - InternalModifier2["Selected"] = "selected"; - InternalModifier2["Hidden"] = "hidden"; - InternalModifier2["Today"] = "today"; - InternalModifier2["RangeStart"] = "range_start"; - InternalModifier2["RangeEnd"] = "range_end"; - InternalModifier2["RangeMiddle"] = "range_middle"; -})(InternalModifier || (InternalModifier = {})); -var Selected = InternalModifier.Selected; -var Disabled = InternalModifier.Disabled; -var Hidden = InternalModifier.Hidden; -var Today = InternalModifier.Today; -var RangeEnd = InternalModifier.RangeEnd; -var RangeMiddle = InternalModifier.RangeMiddle; -var RangeStart = InternalModifier.RangeStart; -var Outside2 = InternalModifier.Outside; -function getInternalModifiers(dayPicker, selectMultiple, selectRange2) { - var _a2; - var internalModifiers = (_a2 = {}, _a2[Selected] = matcherToArray(dayPicker.selected), _a2[Disabled] = matcherToArray(dayPicker.disabled), _a2[Hidden] = matcherToArray(dayPicker.hidden), _a2[Today] = [dayPicker.today], _a2[RangeEnd] = [], _a2[RangeMiddle] = [], _a2[RangeStart] = [], _a2[Outside2] = [], _a2); - if (dayPicker.fromDate) { - internalModifiers[Disabled].push({ before: dayPicker.fromDate }); - } - if (dayPicker.toDate) { - internalModifiers[Disabled].push({ after: dayPicker.toDate }); - } - if (isDayPickerMultiple(dayPicker)) { - internalModifiers[Disabled] = internalModifiers[Disabled].concat(selectMultiple.modifiers[Disabled]); - } else if (isDayPickerRange(dayPicker)) { - internalModifiers[Disabled] = internalModifiers[Disabled].concat(selectRange2.modifiers[Disabled]); - internalModifiers[RangeStart] = selectRange2.modifiers[RangeStart]; - internalModifiers[RangeMiddle] = selectRange2.modifiers[RangeMiddle]; - internalModifiers[RangeEnd] = selectRange2.modifiers[RangeEnd]; - } - return internalModifiers; -} -var ModifiersContext = F(void 0); -function ModifiersProvider(props2) { - var dayPicker = useDayPicker(); - var selectMultiple = useSelectMultiple(); - var selectRange2 = useSelectRange(); - var internalModifiers = getInternalModifiers(dayPicker, selectMultiple, selectRange2); - var customModifiers = getCustomModifiers(dayPicker.modifiers); - var modifiers = __assign(__assign({}, internalModifiers), customModifiers); - return Cn.createElement(ModifiersContext.Provider, { value: modifiers }, props2.children); -} -function useModifiers() { - var context = q2(ModifiersContext); - if (!context) { - throw new Error("useModifiers must be used within a ModifiersProvider"); - } - return context; -} -function isDateInterval(matcher) { - return Boolean(matcher && typeof matcher === "object" && "before" in matcher && "after" in matcher); -} -function isDateRange(value) { - return Boolean(value && typeof value === "object" && "from" in value); -} -function isDateAfterType(value) { - return Boolean(value && typeof value === "object" && "after" in value); -} -function isDateBeforeType(value) { - return Boolean(value && typeof value === "object" && "before" in value); -} -function isDayOfWeekType(value) { - return Boolean(value && typeof value === "object" && "dayOfWeek" in value); -} -function isDateInRange(date, range) { - var _a2; - var from = range.from, to = range.to; - if (!from) { - return false; - } - if (!to && isSameDay(from, date)) { - return true; - } - if (!to) { - return false; - } - var isRangeInverted = differenceInCalendarDays(to, from) < 0; - if (isRangeInverted) { - _a2 = [to, from], from = _a2[0], to = _a2[1]; + }; + }, + createRow: (row, table) => { + return { + columnFilters: {}, + columnFiltersMeta: {} + }; + }, + createTable: (table) => { + return { + getGlobalAutoFilterFn: () => { + return filterFns.includesString; + }, + getGlobalFilterFn: () => { + var _table$options$filter3, _table$options$filter4; + const { + globalFilterFn + } = table.options; + return isFunction(globalFilterFn) ? globalFilterFn : globalFilterFn === "auto" ? table.getGlobalAutoFilterFn() : (_table$options$filter3 = (_table$options$filter4 = table.options.filterFns) == null ? void 0 : _table$options$filter4[globalFilterFn]) != null ? _table$options$filter3 : filterFns[globalFilterFn]; + }, + setColumnFilters: (updater) => { + const leafColumns = table.getAllLeafColumns(); + const updateFn = (old) => { + var _functionalUpdate; + return (_functionalUpdate = functionalUpdate(updater, old)) == null ? void 0 : _functionalUpdate.filter((filter) => { + const column = leafColumns.find((d5) => d5.id === filter.id); + if (column) { + const filterFn = column.getFilterFn(); + if (shouldAutoRemoveFilter(filterFn, filter.value, column)) { + return false; + } + } + return true; + }); + }; + table.options.onColumnFiltersChange == null ? void 0 : table.options.onColumnFiltersChange(updateFn); + }, + setGlobalFilter: (updater) => { + table.options.onGlobalFilterChange == null ? void 0 : table.options.onGlobalFilterChange(updater); + }, + resetGlobalFilter: (defaultState) => { + table.setGlobalFilter(defaultState ? void 0 : table.initialState.globalFilter); + }, + resetColumnFilters: (defaultState) => { + var _table$initialState$c, _table$initialState; + table.setColumnFilters(defaultState ? [] : (_table$initialState$c = (_table$initialState = table.initialState) == null ? void 0 : _table$initialState.columnFilters) != null ? _table$initialState$c : []); + }, + getPreFilteredRowModel: () => table.getCoreRowModel(), + getFilteredRowModel: () => { + if (!table._getFilteredRowModel && table.options.getFilteredRowModel) { + table._getFilteredRowModel = table.options.getFilteredRowModel(table); + } + if (table.options.manualFiltering || !table._getFilteredRowModel) { + return table.getPreFilteredRowModel(); + } + return table._getFilteredRowModel(); + }, + _getGlobalFacetedRowModel: table.options.getFacetedRowModel && table.options.getFacetedRowModel(table, "__global__"), + getGlobalFacetedRowModel: () => { + if (table.options.manualFiltering || !table._getGlobalFacetedRowModel) { + return table.getPreFilteredRowModel(); + } + return table._getGlobalFacetedRowModel(); + }, + _getGlobalFacetedUniqueValues: table.options.getFacetedUniqueValues && table.options.getFacetedUniqueValues(table, "__global__"), + getGlobalFacetedUniqueValues: () => { + if (!table._getGlobalFacetedUniqueValues) { + return /* @__PURE__ */ new Map(); + } + return table._getGlobalFacetedUniqueValues(); + }, + _getGlobalFacetedMinMaxValues: table.options.getFacetedMinMaxValues && table.options.getFacetedMinMaxValues(table, "__global__"), + getGlobalFacetedMinMaxValues: () => { + if (!table._getGlobalFacetedMinMaxValues) { + return; + } + return table._getGlobalFacetedMinMaxValues(); + } + }; } - var isInRange = differenceInCalendarDays(date, from) >= 0 && differenceInCalendarDays(to, date) >= 0; - return isInRange; -} -function isDateType(value) { - return isDate(value); -} -function isArrayOfDates(value) { - return Array.isArray(value) && value.every(isDate); +}; +function shouldAutoRemoveFilter(filterFn, value, column) { + return (filterFn && filterFn.autoRemove ? filterFn.autoRemove(value, column) : false) || typeof value === "undefined" || typeof value === "string" && !value; } -function isMatch(day, matchers) { - return matchers.some(function(matcher) { - if (typeof matcher === "boolean") { - return matcher; - } - if (isDateType(matcher)) { - return isSameDay(day, matcher); - } - if (isArrayOfDates(matcher)) { - return matcher.includes(day); - } - if (isDateRange(matcher)) { - return isDateInRange(day, matcher); - } - if (isDayOfWeekType(matcher)) { - return matcher.dayOfWeek.includes(day.getDay()); - } - if (isDateInterval(matcher)) { - var diffBefore = differenceInCalendarDays(matcher.before, day); - var diffAfter = differenceInCalendarDays(matcher.after, day); - var isDayBefore = diffBefore > 0; - var isDayAfter = diffAfter < 0; - var isClosedInterval = isAfter(matcher.before, matcher.after); - if (isClosedInterval) { - return isDayAfter && isDayBefore; - } else { - return isDayBefore || isDayAfter; - } - } - if (isDateAfterType(matcher)) { - return differenceInCalendarDays(day, matcher.after) > 0; - } - if (isDateBeforeType(matcher)) { - return differenceInCalendarDays(matcher.before, day) > 0; - } - if (typeof matcher === "function") { - return matcher(day); +var sum = (columnId, _leafRows, childRows) => { + return childRows.reduce((sum2, next) => { + const nextValue = next.getValue(columnId); + return sum2 + (typeof nextValue === "number" ? nextValue : 0); + }, 0); +}; +var min2 = (columnId, _leafRows, childRows) => { + let min3; + childRows.forEach((row) => { + const value = row.getValue(columnId); + if (value != null && (min3 > value || min3 === void 0 && value >= value)) { + min3 = value; } - return false; }); -} -function getActiveModifiers(day, modifiers, displayMonth) { - var matchedModifiers = Object.keys(modifiers).reduce(function(result, key2) { - var modifier = modifiers[key2]; - if (isMatch(day, modifier)) { - result.push(key2); + return min3; +}; +var max2 = (columnId, _leafRows, childRows) => { + let max3; + childRows.forEach((row) => { + const value = row.getValue(columnId); + if (value != null && (max3 < value || max3 === void 0 && value >= value)) { + max3 = value; } - return result; - }, []); - var activeModifiers = {}; - matchedModifiers.forEach(function(modifier) { - return activeModifiers[modifier] = true; }); - if (displayMonth && !isSameMonth(day, displayMonth)) { - activeModifiers.outside = true; - } - return activeModifiers; -} -function getInitialFocusTarget(displayMonths, modifiers) { - var firstDayInMonth = startOfMonth(displayMonths[0]); - var lastDayInMonth = endOfMonth(displayMonths[displayMonths.length - 1]); - var firstFocusableDay; - var today; - var date = firstDayInMonth; - while (date <= lastDayInMonth) { - var activeModifiers = getActiveModifiers(date, modifiers); - var isFocusable = !activeModifiers.disabled && !activeModifiers.hidden; - if (!isFocusable) { - date = addDays(date, 1); - continue; - } - if (activeModifiers.selected) { - return date; - } - if (activeModifiers.today && !today) { - today = date; + return max3; +}; +var extent = (columnId, _leafRows, childRows) => { + let min3; + let max3; + childRows.forEach((row) => { + const value = row.getValue(columnId); + if (value != null) { + if (min3 === void 0) { + if (value >= value) + min3 = max3 = value; + } else { + if (min3 > value) + min3 = value; + if (max3 < value) + max3 = value; + } } - if (!firstFocusableDay) { - firstFocusableDay = date; + }); + return [min3, max3]; +}; +var mean = (columnId, leafRows) => { + let count2 = 0; + let sum2 = 0; + leafRows.forEach((row) => { + let value = row.getValue(columnId); + if (value != null && (value = +value) >= value) { + ++count2, sum2 += value; } - date = addDays(date, 1); - } - if (today) { - return today; - } else { - return firstFocusableDay; + }); + if (count2) + return sum2 / count2; + return; +}; +var median = (columnId, leafRows) => { + if (!leafRows.length) { + return; } -} -var MAX_RETRY = 365; -function getNextFocus(focusedDay, options) { - var moveBy = options.moveBy, direction = options.direction, context = options.context, modifiers = options.modifiers, _a2 = options.retry, retry = _a2 === void 0 ? { count: 0, lastFocused: focusedDay } : _a2; - var weekStartsOn = context.weekStartsOn, fromDate = context.fromDate, toDate2 = context.toDate, locale2 = context.locale; - var moveFns = { - day: addDays, - week: addWeeks, - month: addMonths, - year: addYears, - startOfWeek: function(date) { - return context.ISOWeek ? startOfISOWeek(date) : startOfWeek(date, { locale: locale2, weekStartsOn }); - }, - endOfWeek: function(date) { - return context.ISOWeek ? endOfISOWeek(date) : endOfWeek(date, { locale: locale2, weekStartsOn }); + let min3 = 0; + let max3 = 0; + leafRows.forEach((row) => { + let value = row.getValue(columnId); + if (typeof value === "number") { + min3 = Math.min(min3, value); + max3 = Math.max(max3, value); } - }; - var newFocusedDay = moveFns[moveBy](focusedDay, direction === "after" ? 1 : -1); - if (direction === "before" && fromDate) { - newFocusedDay = max([fromDate, newFocusedDay]); - } else if (direction === "after" && toDate2) { - newFocusedDay = min([toDate2, newFocusedDay]); + }); + return (min3 + max3) / 2; +}; +var unique = (columnId, leafRows) => { + return Array.from(new Set(leafRows.map((d5) => d5.getValue(columnId))).values()); +}; +var uniqueCount = (columnId, leafRows) => { + return new Set(leafRows.map((d5) => d5.getValue(columnId))).size; +}; +var count = (_columnId, leafRows) => { + return leafRows.length; +}; +var aggregationFns = { + sum, + min: min2, + max: max2, + extent, + mean, + median, + unique, + uniqueCount, + count +}; +var Grouping = { + getDefaultColumnDef: () => { + return { + aggregatedCell: (props2) => { + var _toString, _props$getValue; + return (_toString = (_props$getValue = props2.getValue()) == null ? void 0 : _props$getValue.toString == null ? void 0 : _props$getValue.toString()) != null ? _toString : null; + }, + aggregationFn: "auto" + }; + }, + getInitialState: (state) => { + return { + grouping: [], + ...state + }; + }, + getDefaultOptions: (table) => { + return { + onGroupingChange: makeStateUpdater("grouping", table), + groupedColumnMode: "reorder" + }; + }, + createColumn: (column, table) => { + return { + toggleGrouping: () => { + table.setGrouping((old) => { + if (old != null && old.includes(column.id)) { + return old.filter((d5) => d5 !== column.id); + } + return [...old != null ? old : [], column.id]; + }); + }, + getCanGroup: () => { + var _ref, _ref2, _ref3, _column$columnDef$ena; + return (_ref = (_ref2 = (_ref3 = (_column$columnDef$ena = column.columnDef.enableGrouping) != null ? _column$columnDef$ena : true) != null ? _ref3 : table.options.enableGrouping) != null ? _ref2 : true) != null ? _ref : !!column.accessorFn; + }, + getIsGrouped: () => { + var _table$getState$group; + return (_table$getState$group = table.getState().grouping) == null ? void 0 : _table$getState$group.includes(column.id); + }, + getGroupedIndex: () => { + var _table$getState$group2; + return (_table$getState$group2 = table.getState().grouping) == null ? void 0 : _table$getState$group2.indexOf(column.id); + }, + getToggleGroupingHandler: () => { + const canGroup = column.getCanGroup(); + return () => { + if (!canGroup) + return; + column.toggleGrouping(); + }; + }, + getAutoAggregationFn: () => { + const firstRow = table.getCoreRowModel().flatRows[0]; + const value = firstRow == null ? void 0 : firstRow.getValue(column.id); + if (typeof value === "number") { + return aggregationFns.sum; + } + if (Object.prototype.toString.call(value) === "[object Date]") { + return aggregationFns.extent; + } + }, + getAggregationFn: () => { + var _table$options$aggreg, _table$options$aggreg2; + if (!column) { + throw new Error(); + } + return isFunction(column.columnDef.aggregationFn) ? column.columnDef.aggregationFn : column.columnDef.aggregationFn === "auto" ? column.getAutoAggregationFn() : (_table$options$aggreg = (_table$options$aggreg2 = table.options.aggregationFns) == null ? void 0 : _table$options$aggreg2[column.columnDef.aggregationFn]) != null ? _table$options$aggreg : aggregationFns[column.columnDef.aggregationFn]; + } + }; + }, + createTable: (table) => { + return { + setGrouping: (updater) => table.options.onGroupingChange == null ? void 0 : table.options.onGroupingChange(updater), + resetGrouping: (defaultState) => { + var _table$initialState$g, _table$initialState; + table.setGrouping(defaultState ? [] : (_table$initialState$g = (_table$initialState = table.initialState) == null ? void 0 : _table$initialState.grouping) != null ? _table$initialState$g : []); + }, + getPreGroupedRowModel: () => table.getFilteredRowModel(), + getGroupedRowModel: () => { + if (!table._getGroupedRowModel && table.options.getGroupedRowModel) { + table._getGroupedRowModel = table.options.getGroupedRowModel(table); + } + if (table.options.manualGrouping || !table._getGroupedRowModel) { + return table.getPreGroupedRowModel(); + } + return table._getGroupedRowModel(); + } + }; + }, + createRow: (row) => { + return { + getIsGrouped: () => !!row.groupingColumnId, + _groupingValuesCache: {} + }; + }, + createCell: (cell, column, row, table) => { + return { + getIsGrouped: () => column.getIsGrouped() && column.id === row.groupingColumnId, + getIsPlaceholder: () => !cell.getIsGrouped() && column.getIsGrouped(), + getIsAggregated: () => { + var _row$subRows; + return !cell.getIsGrouped() && !cell.getIsPlaceholder() && !!((_row$subRows = row.subRows) != null && _row$subRows.length); + } + }; } - var isFocusable = true; - if (modifiers) { - var activeModifiers = getActiveModifiers(newFocusedDay, modifiers); - isFocusable = !activeModifiers.disabled && !activeModifiers.hidden; +}; +function orderColumns(leafColumns, grouping, groupedColumnMode) { + if (!(grouping != null && grouping.length) || !groupedColumnMode) { + return leafColumns; } - if (isFocusable) { - return newFocusedDay; - } else { - if (retry.count > MAX_RETRY) { - return retry.lastFocused; - } - return getNextFocus(newFocusedDay, { - moveBy, - direction, - context, - modifiers, - retry: __assign(__assign({}, retry), { count: retry.count + 1 }) - }); + const nonGroupingColumns = leafColumns.filter((col) => !grouping.includes(col.id)); + if (groupedColumnMode === "remove") { + return nonGroupingColumns; } + const groupingColumns = grouping.map((g4) => leafColumns.find((col) => col.id === g4)).filter(Boolean); + return [...groupingColumns, ...nonGroupingColumns]; } -var FocusContext = F(void 0); -function FocusProvider(props2) { - var navigation = useNavigation(); - var modifiers = useModifiers(); - var _a2 = h2(), focusedDay = _a2[0], setFocusedDay = _a2[1]; - var _b2 = h2(), lastFocused = _b2[0], setLastFocused = _b2[1]; - var initialFocusTarget = getInitialFocusTarget(navigation.displayMonths, modifiers); - var focusTarget = (focusedDay !== null && focusedDay !== void 0 ? focusedDay : lastFocused && navigation.isDateDisplayed(lastFocused)) ? lastFocused : initialFocusTarget; - var blur = function() { - setLastFocused(focusedDay); - setFocusedDay(void 0); - }; - var focus = function(date) { - setFocusedDay(date); - }; - var context = useDayPicker(); - var moveFocus = function(moveBy, direction) { - if (!focusedDay) - return; - var nextFocused = getNextFocus(focusedDay, { - moveBy, - direction, - context, - modifiers - }); - if (isSameDay(focusedDay, nextFocused)) - return void 0; - navigation.goToDate(nextFocused, focusedDay); - focus(nextFocused); - }; - var value = { - focusedDay, - focusTarget, - blur, - focus, - focusDayAfter: function() { - return moveFocus("day", "after"); - }, - focusDayBefore: function() { - return moveFocus("day", "before"); - }, - focusWeekAfter: function() { - return moveFocus("week", "after"); - }, - focusWeekBefore: function() { - return moveFocus("week", "before"); - }, - focusMonthBefore: function() { - return moveFocus("month", "before"); - }, - focusMonthAfter: function() { - return moveFocus("month", "after"); - }, - focusYearBefore: function() { - return moveFocus("year", "before"); - }, - focusYearAfter: function() { - return moveFocus("year", "after"); - }, - focusStartOfWeek: function() { - return moveFocus("startOfWeek", "before"); - }, - focusEndOfWeek: function() { - return moveFocus("endOfWeek", "after"); - } - }; - return Cn.createElement(FocusContext.Provider, { value }, props2.children); -} -function useFocusContext() { - var context = q2(FocusContext); - if (!context) { - throw new Error("useFocusContext must be used within a FocusProvider"); +var Ordering = { + getInitialState: (state) => { + return { + columnOrder: [], + ...state + }; + }, + getDefaultOptions: (table) => { + return { + onColumnOrderChange: makeStateUpdater("columnOrder", table) + }; + }, + createTable: (table) => { + return { + setColumnOrder: (updater) => table.options.onColumnOrderChange == null ? void 0 : table.options.onColumnOrderChange(updater), + resetColumnOrder: (defaultState) => { + var _table$initialState$c; + table.setColumnOrder(defaultState ? [] : (_table$initialState$c = table.initialState.columnOrder) != null ? _table$initialState$c : []); + }, + _getOrderColumnsFn: memo(() => [table.getState().columnOrder, table.getState().grouping, table.options.groupedColumnMode], (columnOrder, grouping, groupedColumnMode) => (columns) => { + let orderedColumns = []; + if (!(columnOrder != null && columnOrder.length)) { + orderedColumns = columns; + } else { + const columnOrderCopy = [...columnOrder]; + const columnsCopy = [...columns]; + while (columnsCopy.length && columnOrderCopy.length) { + const targetColumnId = columnOrderCopy.shift(); + const foundIndex = columnsCopy.findIndex((d5) => d5.id === targetColumnId); + if (foundIndex > -1) { + orderedColumns.push(columnsCopy.splice(foundIndex, 1)[0]); + } + } + orderedColumns = [...orderedColumns, ...columnsCopy]; + } + return orderColumns(orderedColumns, grouping, groupedColumnMode); + }, { + key: "getOrderColumnsFn" + }) + }; } - return context; -} -function useActiveModifiers(day, displayMonth) { - var modifiers = useModifiers(); - var activeModifiers = getActiveModifiers(day, modifiers, displayMonth); - return activeModifiers; -} -var SelectSingleContext = F(void 0); -function SelectSingleProvider(props2) { - if (!isDayPickerSingle(props2.initialProps)) { - var emptyContextValue = { - selected: void 0 +}; +var defaultPageIndex = 0; +var defaultPageSize = 10; +var getDefaultPaginationState = () => ({ + pageIndex: defaultPageIndex, + pageSize: defaultPageSize +}); +var Pagination = { + getInitialState: (state) => { + return { + ...state, + pagination: { + ...getDefaultPaginationState(), + ...state == null ? void 0 : state.pagination + } + }; + }, + getDefaultOptions: (table) => { + return { + onPaginationChange: makeStateUpdater("pagination", table) + }; + }, + createTable: (table) => { + let registered = false; + let queued = false; + return { + _autoResetPageIndex: () => { + var _ref, _table$options$autoRe; + if (!registered) { + table._queue(() => { + registered = true; + }); + return; + } + if ((_ref = (_table$options$autoRe = table.options.autoResetAll) != null ? _table$options$autoRe : table.options.autoResetPageIndex) != null ? _ref : !table.options.manualPagination) { + if (queued) + return; + queued = true; + table._queue(() => { + table.resetPageIndex(); + queued = false; + }); + } + }, + setPagination: (updater) => { + const safeUpdater = (old) => { + let newState = functionalUpdate(updater, old); + return newState; + }; + return table.options.onPaginationChange == null ? void 0 : table.options.onPaginationChange(safeUpdater); + }, + resetPagination: (defaultState) => { + var _table$initialState$p; + table.setPagination(defaultState ? getDefaultPaginationState() : (_table$initialState$p = table.initialState.pagination) != null ? _table$initialState$p : getDefaultPaginationState()); + }, + setPageIndex: (updater) => { + table.setPagination((old) => { + let pageIndex = functionalUpdate(updater, old.pageIndex); + const maxPageIndex = typeof table.options.pageCount === "undefined" || table.options.pageCount === -1 ? Number.MAX_SAFE_INTEGER : table.options.pageCount - 1; + pageIndex = Math.max(0, Math.min(pageIndex, maxPageIndex)); + return { + ...old, + pageIndex + }; + }); + }, + resetPageIndex: (defaultState) => { + var _table$initialState$p2, _table$initialState, _table$initialState$p3; + table.setPageIndex(defaultState ? defaultPageIndex : (_table$initialState$p2 = (_table$initialState = table.initialState) == null ? void 0 : (_table$initialState$p3 = _table$initialState.pagination) == null ? void 0 : _table$initialState$p3.pageIndex) != null ? _table$initialState$p2 : defaultPageIndex); + }, + resetPageSize: (defaultState) => { + var _table$initialState$p4, _table$initialState2, _table$initialState2$; + table.setPageSize(defaultState ? defaultPageSize : (_table$initialState$p4 = (_table$initialState2 = table.initialState) == null ? void 0 : (_table$initialState2$ = _table$initialState2.pagination) == null ? void 0 : _table$initialState2$.pageSize) != null ? _table$initialState$p4 : defaultPageSize); + }, + setPageSize: (updater) => { + table.setPagination((old) => { + const pageSize = Math.max(1, functionalUpdate(updater, old.pageSize)); + const topRowIndex = old.pageSize * old.pageIndex; + const pageIndex = Math.floor(topRowIndex / pageSize); + return { + ...old, + pageIndex, + pageSize + }; + }); + }, + setPageCount: (updater) => table.setPagination((old) => { + var _table$options$pageCo; + let newPageCount = functionalUpdate(updater, (_table$options$pageCo = table.options.pageCount) != null ? _table$options$pageCo : -1); + if (typeof newPageCount === "number") { + newPageCount = Math.max(-1, newPageCount); + } + return { + ...old, + pageCount: newPageCount + }; + }), + getPageOptions: memo(() => [table.getPageCount()], (pageCount) => { + let pageOptions = []; + if (pageCount && pageCount > 0) { + pageOptions = [...new Array(pageCount)].fill(null).map((_12, i4) => i4); + } + return pageOptions; + }, { + key: "getPageOptions", + debug: () => { + var _table$options$debugA; + return (_table$options$debugA = table.options.debugAll) != null ? _table$options$debugA : table.options.debugTable; + } + }), + getCanPreviousPage: () => table.getState().pagination.pageIndex > 0, + getCanNextPage: () => { + const { + pageIndex + } = table.getState().pagination; + const pageCount = table.getPageCount(); + if (pageCount === -1) { + return true; + } + if (pageCount === 0) { + return false; + } + return pageIndex < pageCount - 1; + }, + previousPage: () => { + return table.setPageIndex((old) => old - 1); + }, + nextPage: () => { + return table.setPageIndex((old) => { + return old + 1; + }); + }, + getPrePaginationRowModel: () => table.getExpandedRowModel(), + getPaginationRowModel: () => { + if (!table._getPaginationRowModel && table.options.getPaginationRowModel) { + table._getPaginationRowModel = table.options.getPaginationRowModel(table); + } + if (table.options.manualPagination || !table._getPaginationRowModel) { + return table.getPrePaginationRowModel(); + } + return table._getPaginationRowModel(); + }, + getPageCount: () => { + var _table$options$pageCo2; + return (_table$options$pageCo2 = table.options.pageCount) != null ? _table$options$pageCo2 : Math.ceil(table.getPrePaginationRowModel().rows.length / table.getState().pagination.pageSize); + } + }; + } +}; +var getDefaultPinningState = () => ({ + left: [], + right: [] +}); +var Pinning = { + getInitialState: (state) => { + return { + columnPinning: getDefaultPinningState(), + ...state + }; + }, + getDefaultOptions: (table) => { + return { + onColumnPinningChange: makeStateUpdater("columnPinning", table) + }; + }, + createColumn: (column, table) => { + return { + pin: (position) => { + const columnIds = column.getLeafColumns().map((d5) => d5.id).filter(Boolean); + table.setColumnPinning((old) => { + var _old$left3, _old$right3; + if (position === "right") { + var _old$left, _old$right; + return { + left: ((_old$left = old == null ? void 0 : old.left) != null ? _old$left : []).filter((d5) => !(columnIds != null && columnIds.includes(d5))), + right: [...((_old$right = old == null ? void 0 : old.right) != null ? _old$right : []).filter((d5) => !(columnIds != null && columnIds.includes(d5))), ...columnIds] + }; + } + if (position === "left") { + var _old$left2, _old$right2; + return { + left: [...((_old$left2 = old == null ? void 0 : old.left) != null ? _old$left2 : []).filter((d5) => !(columnIds != null && columnIds.includes(d5))), ...columnIds], + right: ((_old$right2 = old == null ? void 0 : old.right) != null ? _old$right2 : []).filter((d5) => !(columnIds != null && columnIds.includes(d5))) + }; + } + return { + left: ((_old$left3 = old == null ? void 0 : old.left) != null ? _old$left3 : []).filter((d5) => !(columnIds != null && columnIds.includes(d5))), + right: ((_old$right3 = old == null ? void 0 : old.right) != null ? _old$right3 : []).filter((d5) => !(columnIds != null && columnIds.includes(d5))) + }; + }); + }, + getCanPin: () => { + const leafColumns = column.getLeafColumns(); + return leafColumns.some((d5) => { + var _d$columnDef$enablePi, _table$options$enable; + return ((_d$columnDef$enablePi = d5.columnDef.enablePinning) != null ? _d$columnDef$enablePi : true) && ((_table$options$enable = table.options.enablePinning) != null ? _table$options$enable : true); + }); + }, + getIsPinned: () => { + const leafColumnIds = column.getLeafColumns().map((d5) => d5.id); + const { + left, + right + } = table.getState().columnPinning; + const isLeft = leafColumnIds.some((d5) => left == null ? void 0 : left.includes(d5)); + const isRight = leafColumnIds.some((d5) => right == null ? void 0 : right.includes(d5)); + return isLeft ? "left" : isRight ? "right" : false; + }, + getPinnedIndex: () => { + var _table$getState$colum, _table$getState$colum2, _table$getState$colum3; + const position = column.getIsPinned(); + return position ? (_table$getState$colum = (_table$getState$colum2 = table.getState().columnPinning) == null ? void 0 : (_table$getState$colum3 = _table$getState$colum2[position]) == null ? void 0 : _table$getState$colum3.indexOf(column.id)) != null ? _table$getState$colum : -1 : 0; + } + }; + }, + createRow: (row, table) => { + return { + getCenterVisibleCells: memo(() => [row._getAllVisibleCells(), table.getState().columnPinning.left, table.getState().columnPinning.right], (allCells, left, right) => { + const leftAndRight = [...left != null ? left : [], ...right != null ? right : []]; + return allCells.filter((d5) => !leftAndRight.includes(d5.column.id)); + }, { + key: false, + debug: () => { + var _table$options$debugA; + return (_table$options$debugA = table.options.debugAll) != null ? _table$options$debugA : table.options.debugRows; + } + }), + getLeftVisibleCells: memo(() => [row._getAllVisibleCells(), table.getState().columnPinning.left, ,], (allCells, left) => { + const cells = (left != null ? left : []).map((columnId) => allCells.find((cell) => cell.column.id === columnId)).filter(Boolean).map((d5) => ({ + ...d5, + position: "left" + })); + return cells; + }, { + key: false, + debug: () => { + var _table$options$debugA2; + return (_table$options$debugA2 = table.options.debugAll) != null ? _table$options$debugA2 : table.options.debugRows; + } + }), + getRightVisibleCells: memo(() => [row._getAllVisibleCells(), table.getState().columnPinning.right], (allCells, right) => { + const cells = (right != null ? right : []).map((columnId) => allCells.find((cell) => cell.column.id === columnId)).filter(Boolean).map((d5) => ({ + ...d5, + position: "right" + })); + return cells; + }, { + key: false, + debug: () => { + var _table$options$debugA3; + return (_table$options$debugA3 = table.options.debugAll) != null ? _table$options$debugA3 : table.options.debugRows; + } + }) + }; + }, + createTable: (table) => { + return { + setColumnPinning: (updater) => table.options.onColumnPinningChange == null ? void 0 : table.options.onColumnPinningChange(updater), + resetColumnPinning: (defaultState) => { + var _table$initialState$c, _table$initialState; + return table.setColumnPinning(defaultState ? getDefaultPinningState() : (_table$initialState$c = (_table$initialState = table.initialState) == null ? void 0 : _table$initialState.columnPinning) != null ? _table$initialState$c : getDefaultPinningState()); + }, + getIsSomeColumnsPinned: (position) => { + var _pinningState$positio; + const pinningState = table.getState().columnPinning; + if (!position) { + var _pinningState$left, _pinningState$right; + return Boolean(((_pinningState$left = pinningState.left) == null ? void 0 : _pinningState$left.length) || ((_pinningState$right = pinningState.right) == null ? void 0 : _pinningState$right.length)); + } + return Boolean((_pinningState$positio = pinningState[position]) == null ? void 0 : _pinningState$positio.length); + }, + getLeftLeafColumns: memo(() => [table.getAllLeafColumns(), table.getState().columnPinning.left], (allColumns, left) => { + return (left != null ? left : []).map((columnId) => allColumns.find((column) => column.id === columnId)).filter(Boolean); + }, { + key: "getLeftLeafColumns", + debug: () => { + var _table$options$debugA4; + return (_table$options$debugA4 = table.options.debugAll) != null ? _table$options$debugA4 : table.options.debugColumns; + } + }), + getRightLeafColumns: memo(() => [table.getAllLeafColumns(), table.getState().columnPinning.right], (allColumns, right) => { + return (right != null ? right : []).map((columnId) => allColumns.find((column) => column.id === columnId)).filter(Boolean); + }, { + key: "getRightLeafColumns", + debug: () => { + var _table$options$debugA5; + return (_table$options$debugA5 = table.options.debugAll) != null ? _table$options$debugA5 : table.options.debugColumns; + } + }), + getCenterLeafColumns: memo(() => [table.getAllLeafColumns(), table.getState().columnPinning.left, table.getState().columnPinning.right], (allColumns, left, right) => { + const leftAndRight = [...left != null ? left : [], ...right != null ? right : []]; + return allColumns.filter((d5) => !leftAndRight.includes(d5.id)); + }, { + key: "getCenterLeafColumns", + debug: () => { + var _table$options$debugA6; + return (_table$options$debugA6 = table.options.debugAll) != null ? _table$options$debugA6 : table.options.debugColumns; + } + }) }; - return Cn.createElement(SelectSingleContext.Provider, { value: emptyContextValue }, props2.children); - } - return Cn.createElement(SelectSingleProviderInternal, { initialProps: props2.initialProps, children: props2.children }); -} -function SelectSingleProviderInternal(_a2) { - var initialProps = _a2.initialProps, children = _a2.children; - var onDayClick = function(day, activeModifiers, e4) { - var _a3, _b2, _c2; - (_a3 = initialProps.onDayClick) === null || _a3 === void 0 ? void 0 : _a3.call(initialProps, day, activeModifiers, e4); - if (activeModifiers.selected && !initialProps.required) { - (_b2 = initialProps.onSelect) === null || _b2 === void 0 ? void 0 : _b2.call(initialProps, void 0, day, activeModifiers, e4); - return; - } - (_c2 = initialProps.onSelect) === null || _c2 === void 0 ? void 0 : _c2.call(initialProps, day, day, activeModifiers, e4); - }; - var contextValue = { - selected: initialProps.selected, - onDayClick - }; - return Cn.createElement(SelectSingleContext.Provider, { value: contextValue }, children); -} -function useSelectSingle() { - var context = q2(SelectSingleContext); - if (!context) { - throw new Error("useSelectSingle must be used within a SelectSingleProvider"); } - return context; -} -function useDayEventHandlers(date, activeModifiers) { - var dayPicker = useDayPicker(); - var single = useSelectSingle(); - var multiple = useSelectMultiple(); - var range = useSelectRange(); - var _a2 = useFocusContext(), focusDayAfter = _a2.focusDayAfter, focusDayBefore = _a2.focusDayBefore, focusWeekAfter = _a2.focusWeekAfter, focusWeekBefore = _a2.focusWeekBefore, blur = _a2.blur, focus = _a2.focus, focusMonthBefore = _a2.focusMonthBefore, focusMonthAfter = _a2.focusMonthAfter, focusYearBefore = _a2.focusYearBefore, focusYearAfter = _a2.focusYearAfter, focusStartOfWeek = _a2.focusStartOfWeek, focusEndOfWeek = _a2.focusEndOfWeek; - var onClick = function(e4) { - var _a3, _b2, _c2, _d2; - if (isDayPickerSingle(dayPicker)) { - (_a3 = single.onDayClick) === null || _a3 === void 0 ? void 0 : _a3.call(single, date, activeModifiers, e4); - } else if (isDayPickerMultiple(dayPicker)) { - (_b2 = multiple.onDayClick) === null || _b2 === void 0 ? void 0 : _b2.call(multiple, date, activeModifiers, e4); - } else if (isDayPickerRange(dayPicker)) { - (_c2 = range.onDayClick) === null || _c2 === void 0 ? void 0 : _c2.call(range, date, activeModifiers, e4); - } else { - (_d2 = dayPicker.onDayClick) === null || _d2 === void 0 ? void 0 : _d2.call(dayPicker, date, activeModifiers, e4); - } - }; - var onFocus = function(e4) { - var _a3; - focus(date); - (_a3 = dayPicker.onDayFocus) === null || _a3 === void 0 ? void 0 : _a3.call(dayPicker, date, activeModifiers, e4); - }; - var onBlur = function(e4) { - var _a3; - blur(); - (_a3 = dayPicker.onDayBlur) === null || _a3 === void 0 ? void 0 : _a3.call(dayPicker, date, activeModifiers, e4); - }; - var onMouseEnter = function(e4) { - var _a3; - (_a3 = dayPicker.onDayMouseEnter) === null || _a3 === void 0 ? void 0 : _a3.call(dayPicker, date, activeModifiers, e4); - }; - var onMouseLeave = function(e4) { - var _a3; - (_a3 = dayPicker.onDayMouseLeave) === null || _a3 === void 0 ? void 0 : _a3.call(dayPicker, date, activeModifiers, e4); - }; - var onPointerEnter = function(e4) { - var _a3; - (_a3 = dayPicker.onDayPointerEnter) === null || _a3 === void 0 ? void 0 : _a3.call(dayPicker, date, activeModifiers, e4); - }; - var onPointerLeave = function(e4) { - var _a3; - (_a3 = dayPicker.onDayPointerLeave) === null || _a3 === void 0 ? void 0 : _a3.call(dayPicker, date, activeModifiers, e4); - }; - var onTouchCancel = function(e4) { - var _a3; - (_a3 = dayPicker.onDayTouchCancel) === null || _a3 === void 0 ? void 0 : _a3.call(dayPicker, date, activeModifiers, e4); - }; - var onTouchEnd = function(e4) { - var _a3; - (_a3 = dayPicker.onDayTouchEnd) === null || _a3 === void 0 ? void 0 : _a3.call(dayPicker, date, activeModifiers, e4); - }; - var onTouchMove = function(e4) { - var _a3; - (_a3 = dayPicker.onDayTouchMove) === null || _a3 === void 0 ? void 0 : _a3.call(dayPicker, date, activeModifiers, e4); - }; - var onTouchStart = function(e4) { - var _a3; - (_a3 = dayPicker.onDayTouchStart) === null || _a3 === void 0 ? void 0 : _a3.call(dayPicker, date, activeModifiers, e4); - }; - var onKeyUp = function(e4) { - var _a3; - (_a3 = dayPicker.onDayKeyUp) === null || _a3 === void 0 ? void 0 : _a3.call(dayPicker, date, activeModifiers, e4); - }; - var onKeyDown = function(e4) { - var _a3; - switch (e4.key) { - case "ArrowLeft": - e4.preventDefault(); - e4.stopPropagation(); - dayPicker.dir === "rtl" ? focusDayAfter() : focusDayBefore(); - break; - case "ArrowRight": - e4.preventDefault(); - e4.stopPropagation(); - dayPicker.dir === "rtl" ? focusDayBefore() : focusDayAfter(); - break; - case "ArrowDown": - e4.preventDefault(); - e4.stopPropagation(); - focusWeekAfter(); - break; - case "ArrowUp": - e4.preventDefault(); - e4.stopPropagation(); - focusWeekBefore(); - break; - case "PageUp": - e4.preventDefault(); - e4.stopPropagation(); - e4.shiftKey ? focusYearBefore() : focusMonthBefore(); - break; - case "PageDown": - e4.preventDefault(); - e4.stopPropagation(); - e4.shiftKey ? focusYearAfter() : focusMonthAfter(); - break; - case "Home": - e4.preventDefault(); - e4.stopPropagation(); - focusStartOfWeek(); - break; - case "End": - e4.preventDefault(); - e4.stopPropagation(); - focusEndOfWeek(); - break; - } - (_a3 = dayPicker.onDayKeyDown) === null || _a3 === void 0 ? void 0 : _a3.call(dayPicker, date, activeModifiers, e4); - }; - var eventHandlers = { - onClick, - onFocus, - onBlur, - onKeyDown, - onKeyUp, - onMouseEnter, - onMouseLeave, - onPointerEnter, - onPointerLeave, - onTouchCancel, - onTouchEnd, - onTouchMove, - onTouchStart - }; - return eventHandlers; -} -function useSelectedDays() { - var dayPicker = useDayPicker(); - var single = useSelectSingle(); - var multiple = useSelectMultiple(); - var range = useSelectRange(); - var selectedDays = isDayPickerSingle(dayPicker) ? single.selected : isDayPickerMultiple(dayPicker) ? multiple.selected : isDayPickerRange(dayPicker) ? range.selected : void 0; - return selectedDays; -} -function isInternalModifier(modifier) { - return Object.values(InternalModifier).includes(modifier); -} -function getDayClassNames(dayPicker, activeModifiers) { - var classNames9 = [dayPicker.classNames.day]; - Object.keys(activeModifiers).forEach(function(modifier) { - var customClassName = dayPicker.modifiersClassNames[modifier]; - if (customClassName) { - classNames9.push(customClassName); - } else if (isInternalModifier(modifier)) { - var internalClassName = dayPicker.classNames["day_".concat(modifier)]; - if (internalClassName) { - classNames9.push(internalClassName); +}; +var RowSelection = { + getInitialState: (state) => { + return { + rowSelection: {}, + ...state + }; + }, + getDefaultOptions: (table) => { + return { + onRowSelectionChange: makeStateUpdater("rowSelection", table), + enableRowSelection: true, + enableMultiRowSelection: true, + enableSubRowSelection: true + }; + }, + createTable: (table) => { + return { + setRowSelection: (updater) => table.options.onRowSelectionChange == null ? void 0 : table.options.onRowSelectionChange(updater), + resetRowSelection: (defaultState) => { + var _table$initialState$r; + return table.setRowSelection(defaultState ? {} : (_table$initialState$r = table.initialState.rowSelection) != null ? _table$initialState$r : {}); + }, + toggleAllRowsSelected: (value) => { + table.setRowSelection((old) => { + value = typeof value !== "undefined" ? value : !table.getIsAllRowsSelected(); + const rowSelection = { + ...old + }; + const preGroupedFlatRows = table.getPreGroupedRowModel().flatRows; + if (value) { + preGroupedFlatRows.forEach((row) => { + if (!row.getCanSelect()) { + return; + } + rowSelection[row.id] = true; + }); + } else { + preGroupedFlatRows.forEach((row) => { + delete rowSelection[row.id]; + }); + } + return rowSelection; + }); + }, + toggleAllPageRowsSelected: (value) => table.setRowSelection((old) => { + const resolvedValue = typeof value !== "undefined" ? value : !table.getIsAllPageRowsSelected(); + const rowSelection = { + ...old + }; + table.getRowModel().rows.forEach((row) => { + mutateRowIsSelected(rowSelection, row.id, resolvedValue, table); + }); + return rowSelection; + }), + getPreSelectedRowModel: () => table.getCoreRowModel(), + getSelectedRowModel: memo(() => [table.getState().rowSelection, table.getCoreRowModel()], (rowSelection, rowModel) => { + if (!Object.keys(rowSelection).length) { + return { + rows: [], + flatRows: [], + rowsById: {} + }; + } + return selectRowsFn(table, rowModel); + }, { + key: "getSelectedRowModel", + debug: () => { + var _table$options$debugA; + return (_table$options$debugA = table.options.debugAll) != null ? _table$options$debugA : table.options.debugTable; + } + }), + getFilteredSelectedRowModel: memo(() => [table.getState().rowSelection, table.getFilteredRowModel()], (rowSelection, rowModel) => { + if (!Object.keys(rowSelection).length) { + return { + rows: [], + flatRows: [], + rowsById: {} + }; + } + return selectRowsFn(table, rowModel); + }, { + key: false, + debug: () => { + var _table$options$debugA2; + return (_table$options$debugA2 = table.options.debugAll) != null ? _table$options$debugA2 : table.options.debugTable; + } + }), + getGroupedSelectedRowModel: memo(() => [table.getState().rowSelection, table.getSortedRowModel()], (rowSelection, rowModel) => { + if (!Object.keys(rowSelection).length) { + return { + rows: [], + flatRows: [], + rowsById: {} + }; + } + return selectRowsFn(table, rowModel); + }, { + key: false, + debug: () => { + var _table$options$debugA3; + return (_table$options$debugA3 = table.options.debugAll) != null ? _table$options$debugA3 : table.options.debugTable; + } + }), + getIsAllRowsSelected: () => { + const preGroupedFlatRows = table.getFilteredRowModel().flatRows; + const { + rowSelection + } = table.getState(); + let isAllRowsSelected = Boolean(preGroupedFlatRows.length && Object.keys(rowSelection).length); + if (isAllRowsSelected) { + if (preGroupedFlatRows.some((row) => row.getCanSelect() && !rowSelection[row.id])) { + isAllRowsSelected = false; + } + } + return isAllRowsSelected; + }, + getIsAllPageRowsSelected: () => { + const paginationFlatRows = table.getPaginationRowModel().flatRows; + const { + rowSelection + } = table.getState(); + let isAllPageRowsSelected = !!paginationFlatRows.length; + if (isAllPageRowsSelected && paginationFlatRows.some((row) => row.getCanSelect() && !rowSelection[row.id])) { + isAllPageRowsSelected = false; + } + return isAllPageRowsSelected; + }, + getIsSomeRowsSelected: () => { + var _table$getState$rowSe; + const totalSelected = Object.keys((_table$getState$rowSe = table.getState().rowSelection) != null ? _table$getState$rowSe : {}).length; + return totalSelected > 0 && totalSelected < table.getFilteredRowModel().flatRows.length; + }, + getIsSomePageRowsSelected: () => { + const paginationFlatRows = table.getPaginationRowModel().flatRows; + return table.getIsAllPageRowsSelected() ? false : paginationFlatRows.some((d5) => d5.getIsSelected() || d5.getIsSomeSelected()); + }, + getToggleAllRowsSelectedHandler: () => { + return (e4) => { + table.toggleAllRowsSelected(e4.target.checked); + }; + }, + getToggleAllPageRowsSelectedHandler: () => { + return (e4) => { + table.toggleAllPageRowsSelected(e4.target.checked); + }; + } + }; + }, + createRow: (row, table) => { + return { + toggleSelected: (value) => { + const isSelected = row.getIsSelected(); + table.setRowSelection((old) => { + value = typeof value !== "undefined" ? value : !isSelected; + if (isSelected === value) { + return old; + } + const selectedRowIds = { + ...old + }; + mutateRowIsSelected(selectedRowIds, row.id, value, table); + return selectedRowIds; + }); + }, + getIsSelected: () => { + const { + rowSelection + } = table.getState(); + return isRowSelected(row, rowSelection); + }, + getIsSomeSelected: () => { + const { + rowSelection + } = table.getState(); + return isSubRowSelected(row, rowSelection) === "some"; + }, + getIsAllSubRowsSelected: () => { + const { + rowSelection + } = table.getState(); + return isSubRowSelected(row, rowSelection) === "all"; + }, + getCanSelect: () => { + var _table$options$enable; + if (typeof table.options.enableRowSelection === "function") { + return table.options.enableRowSelection(row); + } + return (_table$options$enable = table.options.enableRowSelection) != null ? _table$options$enable : true; + }, + getCanSelectSubRows: () => { + var _table$options$enable2; + if (typeof table.options.enableSubRowSelection === "function") { + return table.options.enableSubRowSelection(row); + } + return (_table$options$enable2 = table.options.enableSubRowSelection) != null ? _table$options$enable2 : true; + }, + getCanMultiSelect: () => { + var _table$options$enable3; + if (typeof table.options.enableMultiRowSelection === "function") { + return table.options.enableMultiRowSelection(row); + } + return (_table$options$enable3 = table.options.enableMultiRowSelection) != null ? _table$options$enable3 : true; + }, + getToggleSelectedHandler: () => { + const canSelect = row.getCanSelect(); + return (e4) => { + var _target; + if (!canSelect) + return; + row.toggleSelected((_target = e4.target) == null ? void 0 : _target.checked); + }; } + }; + } +}; +var mutateRowIsSelected = (selectedRowIds, id2, value, table) => { + var _row$subRows; + const row = table.getRow(id2); + if (value) { + if (!row.getCanMultiSelect()) { + Object.keys(selectedRowIds).forEach((key2) => delete selectedRowIds[key2]); } - }); - return classNames9; -} -function getDayStyle(dayPicker, activeModifiers) { - var style = __assign({}, dayPicker.styles.day); - Object.keys(activeModifiers).forEach(function(modifier) { - var _a2; - style = __assign(__assign({}, style), (_a2 = dayPicker.modifiersStyles) === null || _a2 === void 0 ? void 0 : _a2[modifier]); - }); - return style; -} -function useDayRender(day, displayMonth, buttonRef) { - var _a2; - var _b2, _c2; - var dayPicker = useDayPicker(); - var focusContext = useFocusContext(); - var activeModifiers = useActiveModifiers(day, displayMonth); - var eventHandlers = useDayEventHandlers(day, activeModifiers); - var selectedDays = useSelectedDays(); - var isButton = Boolean(dayPicker.onDayClick || dayPicker.mode !== "default"); - p2(function() { - var _a3; - if (activeModifiers.outside) - return; - if (!focusContext.focusedDay) - return; - if (!isButton) - return; - if (isSameDay(focusContext.focusedDay, day)) { - (_a3 = buttonRef.current) === null || _a3 === void 0 ? void 0 : _a3.focus(); + if (row.getCanSelect()) { + selectedRowIds[id2] = true; } - }, [ - focusContext.focusedDay, - day, - buttonRef, - isButton, - activeModifiers.outside - ]); - var className = getDayClassNames(dayPicker, activeModifiers).join(" "); - var style = getDayStyle(dayPicker, activeModifiers); - var isHidden = Boolean(activeModifiers.outside && !dayPicker.showOutsideDays || activeModifiers.hidden); - var DayContentComponent = (_c2 = (_b2 = dayPicker.components) === null || _b2 === void 0 ? void 0 : _b2.DayContent) !== null && _c2 !== void 0 ? _c2 : DayContent; - var children = Cn.createElement(DayContentComponent, { date: day, displayMonth, activeModifiers }); - var divProps = { - style, - className, - children, - role: "gridcell" - }; - var isFocusTarget = focusContext.focusTarget && isSameDay(focusContext.focusTarget, day) && !activeModifiers.outside; - var isFocused = focusContext.focusedDay && isSameDay(focusContext.focusedDay, day); - var buttonProps = __assign(__assign(__assign({}, divProps), (_a2 = { disabled: activeModifiers.disabled, role: "gridcell" }, _a2["aria-selected"] = activeModifiers.selected, _a2.tabIndex = isFocused || isFocusTarget ? 0 : -1, _a2)), eventHandlers); - var dayRender = { - isButton, - isHidden, - activeModifiers, - selectedDays, - buttonProps, - divProps - }; - return dayRender; -} -function Day(props2) { - var buttonRef = _2(null); - var dayRender = useDayRender(props2.date, props2.displayMonth, buttonRef); - if (dayRender.isHidden) { - return Cn.createElement("div", { role: "gridcell" }); - } - if (!dayRender.isButton) { - return Cn.createElement("div", __assign({}, dayRender.divProps)); + } else { + delete selectedRowIds[id2]; } - return Cn.createElement(Button, __assign({ name: "day", ref: buttonRef }, dayRender.buttonProps)); -} -function WeekNumber(props2) { - var weekNumber = props2.number, dates = props2.dates; - var _a2 = useDayPicker(), onWeekNumberClick = _a2.onWeekNumberClick, styles = _a2.styles, classNames9 = _a2.classNames, locale2 = _a2.locale, labelWeekNumber2 = _a2.labels.labelWeekNumber, formatWeekNumber2 = _a2.formatters.formatWeekNumber; - var content = formatWeekNumber2(Number(weekNumber), { locale: locale2 }); - if (!onWeekNumberClick) { - return Cn.createElement("span", { className: classNames9.weeknumber, style: styles.weeknumber }, content); + if ((_row$subRows = row.subRows) != null && _row$subRows.length && row.getCanSelectSubRows()) { + row.subRows.forEach((row2) => mutateRowIsSelected(selectedRowIds, row2.id, value, table)); } - var label = labelWeekNumber2(Number(weekNumber), { locale: locale2 }); - var handleClick = function(e4) { - onWeekNumberClick(weekNumber, dates, e4); +}; +function selectRowsFn(table, rowModel) { + const rowSelection = table.getState().rowSelection; + const newSelectedFlatRows = []; + const newSelectedRowsById = {}; + const recurseRows = function(rows, depth) { + return rows.map((row) => { + var _row$subRows2; + const isSelected = isRowSelected(row, rowSelection); + if (isSelected) { + newSelectedFlatRows.push(row); + newSelectedRowsById[row.id] = row; + } + if ((_row$subRows2 = row.subRows) != null && _row$subRows2.length) { + row = { + ...row, + subRows: recurseRows(row.subRows) + }; + } + if (isSelected) { + return row; + } + }).filter(Boolean); + }; + return { + rows: recurseRows(rowModel.rows), + flatRows: newSelectedFlatRows, + rowsById: newSelectedRowsById }; - return Cn.createElement(Button, { name: "week-number", "aria-label": label, className: classNames9.weeknumber, style: styles.weeknumber, onClick: handleClick }, content); } -function Row(props2) { - var _a2, _b2; - var _c2 = useDayPicker(), styles = _c2.styles, classNames9 = _c2.classNames, showWeekNumber = _c2.showWeekNumber, components = _c2.components; - var DayComponent = (_a2 = components === null || components === void 0 ? void 0 : components.Day) !== null && _a2 !== void 0 ? _a2 : Day; - var WeeknumberComponent = (_b2 = components === null || components === void 0 ? void 0 : components.WeekNumber) !== null && _b2 !== void 0 ? _b2 : WeekNumber; - var weekNumberCell; - if (showWeekNumber) { - weekNumberCell = Cn.createElement( - "td", - { className: classNames9.cell, style: styles.cell }, - Cn.createElement(WeeknumberComponent, { number: props2.weekNumber, dates: props2.dates }) - ); - } - return Cn.createElement( - "tr", - { className: classNames9.row, style: styles.row }, - weekNumberCell, - props2.dates.map(function(date) { - return Cn.createElement( - "td", - { className: classNames9.cell, style: styles.cell, key: getUnixTime(date), role: "presentation" }, - Cn.createElement(DayComponent, { displayMonth: props2.displayMonth, date }) - ); - }) - ); +function isRowSelected(row, selection) { + var _selection$row$id; + return (_selection$row$id = selection[row.id]) != null ? _selection$row$id : false; } -function daysToMonthWeeks(fromDate, toDate2, options) { - var toWeek = (options === null || options === void 0 ? void 0 : options.ISOWeek) ? endOfISOWeek(toDate2) : endOfWeek(toDate2, options); - var fromWeek = (options === null || options === void 0 ? void 0 : options.ISOWeek) ? startOfISOWeek(fromDate) : startOfWeek(fromDate, options); - var nOfDays = differenceInCalendarDays(toWeek, fromWeek); - var days = []; - for (var i4 = 0; i4 <= nOfDays; i4++) { - days.push(addDays(fromWeek, i4)); - } - var weeksInMonth = days.reduce(function(result, date) { - var weekNumber = (options === null || options === void 0 ? void 0 : options.ISOWeek) ? getISOWeek(date) : getWeek(date, options); - var existingWeek = result.find(function(value) { - return value.weekNumber === weekNumber; - }); - if (existingWeek) { - existingWeek.dates.push(date); - return result; - } - result.push({ - weekNumber, - dates: [date] +function isSubRowSelected(row, selection, table) { + if (row.subRows && row.subRows.length) { + let allChildrenSelected = true; + let someSelected = false; + row.subRows.forEach((subRow) => { + if (someSelected && !allChildrenSelected) { + return; + } + if (isRowSelected(subRow, selection)) { + someSelected = true; + } else { + allChildrenSelected = false; + } }); - return result; - }, []); - return weeksInMonth; -} -function getMonthWeeks(month, options) { - var weeksInMonth = daysToMonthWeeks(startOfMonth(month), endOfMonth(month), options); - if (options === null || options === void 0 ? void 0 : options.useFixedWeeks) { - var nrOfMonthWeeks = getWeeksInMonth(month, options); - if (nrOfMonthWeeks < 6) { - var lastWeek = weeksInMonth[weeksInMonth.length - 1]; - var lastDate = lastWeek.dates[lastWeek.dates.length - 1]; - var toDate2 = addWeeks(lastDate, 6 - nrOfMonthWeeks); - var extraWeeks = daysToMonthWeeks(addWeeks(lastDate, 1), toDate2, options); - weeksInMonth.push.apply(weeksInMonth, extraWeeks); - } + return allChildrenSelected ? "all" : someSelected ? "some" : false; } - return weeksInMonth; -} -function Table(props2) { - var _a2, _b2, _c2; - var _d2 = useDayPicker(), locale2 = _d2.locale, classNames9 = _d2.classNames, styles = _d2.styles, hideHead = _d2.hideHead, fixedWeeks = _d2.fixedWeeks, components = _d2.components, weekStartsOn = _d2.weekStartsOn, firstWeekContainsDate = _d2.firstWeekContainsDate, ISOWeek = _d2.ISOWeek; - var weeks = getMonthWeeks(props2.displayMonth, { - useFixedWeeks: Boolean(fixedWeeks), - ISOWeek, - locale: locale2, - weekStartsOn, - firstWeekContainsDate - }); - var HeadComponent = (_a2 = components === null || components === void 0 ? void 0 : components.Head) !== null && _a2 !== void 0 ? _a2 : Head; - var RowComponent = (_b2 = components === null || components === void 0 ? void 0 : components.Row) !== null && _b2 !== void 0 ? _b2 : Row; - var FooterComponent = (_c2 = components === null || components === void 0 ? void 0 : components.Footer) !== null && _c2 !== void 0 ? _c2 : Footer; - return Cn.createElement( - "table", - { className: classNames9.table, style: styles.table, role: "grid", "aria-labelledby": props2["aria-labelledby"] }, - !hideHead && Cn.createElement(HeadComponent, null), - Cn.createElement("tbody", { className: classNames9.tbody, style: styles.tbody, role: "rowgroup" }, weeks.map(function(week) { - return Cn.createElement(RowComponent, { displayMonth: props2.displayMonth, key: week.weekNumber, dates: week.dates, weekNumber: week.weekNumber }); - })), - Cn.createElement(FooterComponent, { displayMonth: props2.displayMonth }) - ); -} -function canUseDOM2() { - return !!(typeof window !== "undefined" && window.document && window.document.createElement); + return false; } -var useIsomorphicLayoutEffect2 = canUseDOM2() ? y2 : p2; -var serverHandoffComplete = false; -var id = 0; -function genId2() { - return "react-day-picker-".concat(++id); +var reSplitAlphaNumeric = /([0-9]+)/gm; +var alphanumeric = (rowA, rowB, columnId) => { + return compareAlphanumeric(toString2(rowA.getValue(columnId)).toLowerCase(), toString2(rowB.getValue(columnId)).toLowerCase()); +}; +var alphanumericCaseSensitive = (rowA, rowB, columnId) => { + return compareAlphanumeric(toString2(rowA.getValue(columnId)), toString2(rowB.getValue(columnId))); +}; +var text = (rowA, rowB, columnId) => { + return compareBasic(toString2(rowA.getValue(columnId)).toLowerCase(), toString2(rowB.getValue(columnId)).toLowerCase()); +}; +var textCaseSensitive = (rowA, rowB, columnId) => { + return compareBasic(toString2(rowA.getValue(columnId)), toString2(rowB.getValue(columnId))); +}; +var datetime = (rowA, rowB, columnId) => { + const a5 = rowA.getValue(columnId); + const b4 = rowB.getValue(columnId); + return a5 > b4 ? 1 : a5 < b4 ? -1 : 0; +}; +var basic = (rowA, rowB, columnId) => { + return compareBasic(rowA.getValue(columnId), rowB.getValue(columnId)); +}; +function compareBasic(a5, b4) { + return a5 === b4 ? 0 : a5 > b4 ? 1 : -1; } -function useId(providedId) { - var _a2; - var initialId = providedId !== null && providedId !== void 0 ? providedId : serverHandoffComplete ? genId2() : null; - var _b2 = h2(initialId), id2 = _b2[0], setId = _b2[1]; - useIsomorphicLayoutEffect2(function() { - if (id2 === null) { - setId(genId2()); - } - }, []); - p2(function() { - if (serverHandoffComplete === false) { - serverHandoffComplete = true; +function toString2(a5) { + if (typeof a5 === "number") { + if (isNaN(a5) || a5 === Infinity || a5 === -Infinity) { + return ""; } - }, []); - return (_a2 = providedId !== null && providedId !== void 0 ? providedId : id2) !== null && _a2 !== void 0 ? _a2 : void 0; -} -function Month(props2) { - var _a2; - var _b2; - var dayPicker = useDayPicker(); - var dir = dayPicker.dir, classNames9 = dayPicker.classNames, styles = dayPicker.styles, components = dayPicker.components; - var displayMonths = useNavigation().displayMonths; - var captionId = useId(dayPicker.id ? "".concat(dayPicker.id, "-").concat(props2.displayIndex) : void 0); - var className = [classNames9.month]; - var style = styles.month; - var isStart = props2.displayIndex === 0; - var isEnd = props2.displayIndex === displayMonths.length - 1; - var isCenter = !isStart && !isEnd; - if (dir === "rtl") { - _a2 = [isStart, isEnd], isEnd = _a2[0], isStart = _a2[1]; - } - if (isStart) { - className.push(classNames9.caption_start); - style = __assign(__assign({}, style), styles.caption_start); - } - if (isEnd) { - className.push(classNames9.caption_end); - style = __assign(__assign({}, style), styles.caption_end); - } - if (isCenter) { - className.push(classNames9.caption_between); - style = __assign(__assign({}, style), styles.caption_between); - } - var CaptionComponent = (_b2 = components === null || components === void 0 ? void 0 : components.Caption) !== null && _b2 !== void 0 ? _b2 : Caption; - return Cn.createElement( - "div", - { key: props2.displayIndex, className: className.join(" "), style }, - Cn.createElement(CaptionComponent, { id: captionId, displayMonth: props2.displayMonth }), - Cn.createElement(Table, { "aria-labelledby": captionId, displayMonth: props2.displayMonth }) - ); -} -function Root() { - var dayPicker = useDayPicker(); - var focusContext = useFocusContext(); - var navigation = useNavigation(); - var _a2 = h2(false), hasInitialFocus = _a2[0], setHasInitialFocus = _a2[1]; - p2(function() { - if (!dayPicker.initialFocus) - return; - if (!focusContext.focusTarget) - return; - if (hasInitialFocus) - return; - focusContext.focus(focusContext.focusTarget); - setHasInitialFocus(true); - }, [ - dayPicker.initialFocus, - hasInitialFocus, - focusContext.focus, - focusContext.focusTarget, - focusContext - ]); - var classNames9 = [dayPicker.classNames.root, dayPicker.className]; - if (dayPicker.numberOfMonths > 1) { - classNames9.push(dayPicker.classNames.multiple_months); + return String(a5); } - if (dayPicker.showWeekNumber) { - classNames9.push(dayPicker.classNames.with_weeknumber); + if (typeof a5 === "string") { + return a5; } - var style = __assign(__assign({}, dayPicker.styles.root), dayPicker.style); - return Cn.createElement( - "div", - { className: classNames9.join(" "), style, dir: dayPicker.dir }, - Cn.createElement("div", { className: dayPicker.classNames.months, style: dayPicker.styles.months }, navigation.displayMonths.map(function(month, i4) { - return Cn.createElement(Month, { key: i4, displayIndex: i4, displayMonth: month }); - })) - ); -} -function RootProvider(props2) { - var children = props2.children, initialProps = __rest(props2, ["children"]); - return Cn.createElement( - DayPickerProvider, - { initialProps }, - Cn.createElement( - NavigationProvider, - null, - Cn.createElement( - SelectSingleProvider, - { initialProps }, - Cn.createElement( - SelectMultipleProvider, - { initialProps }, - Cn.createElement( - SelectRangeProvider, - { initialProps }, - Cn.createElement( - ModifiersProvider, - null, - Cn.createElement(FocusProvider, null, children) - ) - ) - ) - ) - ) - ); -} -function DayPicker(props2) { - return Cn.createElement( - RootProvider, - __assign({}, props2), - Cn.createElement(Root, null) - ); + return ""; } - -// src/components/ui/menus/datePickerMenu.tsx -var showDatePickerMenu = (point, value, setValue, format2) => { - const menu = new import_obsidian17.Menu(); - menu.dom.toggleClass("mk-menu", true); - menu.setUseNativeMenu(false); - const frag = document.createDocumentFragment(); - const div = frag.createEl("div"); - div.addEventListener("click", (e4) => { - e4.stopImmediatePropagation(); - }); - div.addEventListener("mousedown", (e4) => { - e4.stopImmediatePropagation(); - }); - div.addEventListener("mouseup", (e4) => { - e4.stopImmediatePropagation(); - }); - div.addEventListener("keydown", (e4) => { - }); - const setDate = (date) => { - setValue(date); - menu.hide(); - }; - const root = createRoot(div); - root.render( - /* @__PURE__ */ Cn.createElement(Cn.Fragment, null, /* @__PURE__ */ Cn.createElement(DayPicker, { - defaultMonth: value, - mode: "single", - selected: value, - labels: { - labelMonthDropdown: () => void 0, - labelYearDropdown: () => void 0, - labelNext: () => void 0, - labelPrevious: () => void 0, - labelDay: () => void 0, - labelWeekday: () => void 0, - labelWeekNumber: () => void 0 - }, - onSelect: setDate - })) - ); - menu.addItem((item) => { - item.setTitle(frag); - }); - const keys = [...menu.scope.keys]; - for (let i4 = 0; i4 < keys.length; i4++) { - if (keys[i4].key != "Escape") { - menu.scope.unregister(keys[i4]); - } - } - menu.showAtPosition(point); - return menu; -}; - -// src/utils/date.ts -var formatDate = (plugin, date, dateFormat) => { - let dateString; - try { - dateString = format( - date, - (dateFormat == null ? void 0 : dateFormat.length) > 0 ? dateFormat : plugin.settings.defaultDateFormat - ); - } catch (e4) { - dateString = "Date Format Invalid"; - } - return dateString; -}; - -// src/components/ContextView/DataTypeView/DateCell.tsx -var DateCell = (props2) => { - const [value, setValue] = h2(props2.initialValue); - p2(() => { - setValue(props2.initialValue); - }, [props2.initialValue]); - const date = F2(() => { - const dateTime = Date.parse(value); - return dateTime > 0 ? new Date(dateTime + new Date().getTimezoneOffset() * 60 * 1e3) : null; - }, [value]); - const saveValue = (date2) => { - const newValue = format(date2, "yyyy-MM-dd"); - props2.saveValue(newValue); - setValue(newValue); - props2.setEditMode(null); - }; - const menuRef = _2(null); - const ref = _2(null); - p2(() => { - if (props2.editMode == 2 /* EditModeActive */) { - if (ref.current) { - showPicker(); - ref.current.focus(); +function compareAlphanumeric(aStr, bStr) { + const a5 = aStr.split(reSplitAlphaNumeric).filter(Boolean); + const b4 = bStr.split(reSplitAlphaNumeric).filter(Boolean); + while (a5.length && b4.length) { + const aa = a5.shift(); + const bb = b4.shift(); + const an2 = parseInt(aa, 10); + const bn2 = parseInt(bb, 10); + const combo = [an2, bn2].sort(); + if (isNaN(combo[0])) { + if (aa > bb) { + return 1; } - } - }, [props2.editMode]); - const showPicker = T2( - (e4) => { - if (props2.editMode <= 0) { - return; + if (bb > aa) { + return -1; } - const offset = e4 ? e4.target.getBoundingClientRect() : ref.current.getBoundingClientRect(); - menuRef.current = showDatePickerMenu( - { x: offset.left - 4, y: offset.bottom - 4 }, - date, - saveValue - ); - }, - [date] - ); - const onKeyDown = (e4) => { - e4.stopPropagation(); - if (e4.key == "Enter" || e4.key == "Escape") { - e4.target.blur(); - saveValue(date); - menuRef.current.hide(); + continue; } - }; - return /* @__PURE__ */ Cn.createElement("div", { - className: "mk-cell-date", - onClick: (e4) => !value && showPicker(e4) - }, props2.editMode == 2 ? /* @__PURE__ */ Cn.createElement("input", { - onClick: (e4) => e4.stopPropagation(), - className: "mk-cell-text", - ref, - type: "text", - value, - onChange: (e4) => setValue(e4.target.value), - onMouseDown: () => showPicker(), - onKeyDown - }) : /* @__PURE__ */ Cn.createElement("div", { - className: "mk-cell-date-value", - onClick: (e4) => showPicker(e4) - }, date ? formatDate(props2.plugin, date, props2.propertyValue) : value)); -}; - -// src/components/ContextView/ContextBuilder/BuilderMetadataFields.tsx -var import_obsidian18 = require("obsidian"); -var allMetadataForFiles = (plugin, files) => { - return files.reduce((p3, c4) => { - const fm = frontMatterForFile(c4); - const fmKeys = uniqCaseInsensitive(frontMatterKeys(fm)); - if (plugin.dataViewAPI()) { - const dvValues = plugin.dataViewAPI().page(c4.path); - const dvKeys = uniqCaseInsensitive( - Object.keys(dvValues != null ? dvValues : {}).filter( - (f4, i4, self2) => !self2.find( - (g4, j4) => g4.toLowerCase().replace(/\s/g, "-") == f4.toLowerCase().replace(/\s/g, "-") && i4 > j4 - ) ? true : false - ).filter((f4) => f4 != "file" && !fmKeys.some((g4) => f4 == g4)) - ); - return [ - ...p3, - ...fmKeys.map((f4) => ({ name: f4, type: "fm" })), - ...dvKeys.map((f4) => ({ name: f4, type: "dv" })) - ].filter(metadatTypeFilterPredicate); + if (isNaN(combo[1])) { + return isNaN(an2) ? -1 : 1; } - return [ - ...p3, - ...fmKeys.map((f4) => ({ name: f4, type: "fm" })) - ].filter(metadatTypeFilterPredicate); - }, []); -}; -var metadatTypeFilterPredicate = (value, index, self2) => { - return self2.findIndex( - (v3) => value["type"] == v3["type"] && value["name"] == v3["name"] - ) === index; -}; -var SyncMetadataComponent = (props2) => { - const cols = allMetadataForFiles( - props2.plugin, - props2.files.filter((f4) => f4 instanceof import_obsidian18.TFile) - ).filter( - (f4) => props2.columns ? !props2.columns.some((g4) => g4.name == f4.name) : true - ); - return /* @__PURE__ */ Cn.createElement("div", { - className: "mk-cell-option" - }, cols.map((f4, index) => /* @__PURE__ */ Cn.createElement("div", { - className: "mk-cell-option-item", - onClick: () => props2.syncColumn(f4, "") - }, /* @__PURE__ */ Cn.createElement("div", null, f4.name), /* @__PURE__ */ Cn.createElement("div", { - className: `mk-icon-xsmall`, - dangerouslySetInnerHTML: { - __html: uiIconSet["mk-ui-plus"] + if (an2 > bn2) { + return 1; } - })))); + if (bn2 > an2) { + return -1; + } + } + return a5.length - b4.length; +} +var sortingFns = { + alphanumeric, + alphanumericCaseSensitive, + text, + textCaseSensitive, + datetime, + basic }; - -// src/components/Spaces/SpaceEditor.tsx -var import_obsidian23 = require("obsidian"); - -// src/types/metadata.ts -var fileProps = { - "name": { - label: "File Name", - field: "name", - vType: "text", - type: "fileprop" +var Sorting = { + getInitialState: (state) => { + return { + sorting: [], + ...state + }; }, - "path": { - label: "Path", - field: "path", - vType: "text", - type: "fileprop" + getDefaultColumnDef: () => { + return { + sortingFn: "auto" + }; }, - "parent": { - label: "Folder", - field: "parent", - vType: "text", - type: "fileprop" + getDefaultOptions: (table) => { + return { + onSortingChange: makeStateUpdater("sorting", table), + isMultiSortEvent: (e4) => { + return e4.shiftKey; + } + }; }, - "sticker": { - label: "Sticker", - field: "sticker", - vType: "text", - type: "fileprop" + createColumn: (column, table) => { + return { + getAutoSortingFn: () => { + const firstRows = table.getFilteredRowModel().flatRows.slice(10); + let isString = false; + for (const row of firstRows) { + const value = row == null ? void 0 : row.getValue(column.id); + if (Object.prototype.toString.call(value) === "[object Date]") { + return sortingFns.datetime; + } + if (typeof value === "string") { + isString = true; + if (value.split(reSplitAlphaNumeric).length > 1) { + return sortingFns.alphanumeric; + } + } + } + if (isString) { + return sortingFns.text; + } + return sortingFns.basic; + }, + getAutoSortDir: () => { + const firstRow = table.getFilteredRowModel().flatRows[0]; + const value = firstRow == null ? void 0 : firstRow.getValue(column.id); + if (typeof value === "string") { + return "asc"; + } + return "desc"; + }, + getSortingFn: () => { + var _table$options$sortin, _table$options$sortin2; + if (!column) { + throw new Error(); + } + return isFunction(column.columnDef.sortingFn) ? column.columnDef.sortingFn : column.columnDef.sortingFn === "auto" ? column.getAutoSortingFn() : (_table$options$sortin = (_table$options$sortin2 = table.options.sortingFns) == null ? void 0 : _table$options$sortin2[column.columnDef.sortingFn]) != null ? _table$options$sortin : sortingFns[column.columnDef.sortingFn]; + }, + toggleSorting: (desc, multi) => { + const nextSortingOrder = column.getNextSortingOrder(); + const hasManualValue = typeof desc !== "undefined" && desc !== null; + table.setSorting((old) => { + const existingSorting = old == null ? void 0 : old.find((d5) => d5.id === column.id); + const existingIndex = old == null ? void 0 : old.findIndex((d5) => d5.id === column.id); + let newSorting = []; + let sortAction; + let nextDesc = hasManualValue ? desc : nextSortingOrder === "desc"; + if (old != null && old.length && column.getCanMultiSort() && multi) { + if (existingSorting) { + sortAction = "toggle"; + } else { + sortAction = "add"; + } + } else { + if (old != null && old.length && existingIndex !== old.length - 1) { + sortAction = "replace"; + } else if (existingSorting) { + sortAction = "toggle"; + } else { + sortAction = "replace"; + } + } + if (sortAction === "toggle") { + if (!hasManualValue) { + if (!nextSortingOrder) { + sortAction = "remove"; + } + } + } + if (sortAction === "add") { + var _table$options$maxMul; + newSorting = [...old, { + id: column.id, + desc: nextDesc + }]; + newSorting.splice(0, newSorting.length - ((_table$options$maxMul = table.options.maxMultiSortColCount) != null ? _table$options$maxMul : Number.MAX_SAFE_INTEGER)); + } else if (sortAction === "toggle") { + newSorting = old.map((d5) => { + if (d5.id === column.id) { + return { + ...d5, + desc: nextDesc + }; + } + return d5; + }); + } else if (sortAction === "remove") { + newSorting = old.filter((d5) => d5.id !== column.id); + } else { + newSorting = [{ + id: column.id, + desc: nextDesc + }]; + } + return newSorting; + }); + }, + getFirstSortDir: () => { + var _ref, _column$columnDef$sor; + const sortDescFirst = (_ref = (_column$columnDef$sor = column.columnDef.sortDescFirst) != null ? _column$columnDef$sor : table.options.sortDescFirst) != null ? _ref : column.getAutoSortDir() === "desc"; + return sortDescFirst ? "desc" : "asc"; + }, + getNextSortingOrder: (multi) => { + var _table$options$enable, _table$options$enable2; + const firstSortDirection = column.getFirstSortDir(); + const isSorted = column.getIsSorted(); + if (!isSorted) { + return firstSortDirection; + } + if (isSorted !== firstSortDirection && ((_table$options$enable = table.options.enableSortingRemoval) != null ? _table$options$enable : true) && (multi ? (_table$options$enable2 = table.options.enableMultiRemove) != null ? _table$options$enable2 : true : true)) { + return false; + } + return isSorted === "desc" ? "asc" : "desc"; + }, + getCanSort: () => { + var _column$columnDef$ena, _table$options$enable3; + return ((_column$columnDef$ena = column.columnDef.enableSorting) != null ? _column$columnDef$ena : true) && ((_table$options$enable3 = table.options.enableSorting) != null ? _table$options$enable3 : true) && !!column.accessorFn; + }, + getCanMultiSort: () => { + var _ref2, _column$columnDef$ena2; + return (_ref2 = (_column$columnDef$ena2 = column.columnDef.enableMultiSort) != null ? _column$columnDef$ena2 : table.options.enableMultiSort) != null ? _ref2 : !!column.accessorFn; + }, + getIsSorted: () => { + var _table$getState$sorti; + const columnSort = (_table$getState$sorti = table.getState().sorting) == null ? void 0 : _table$getState$sorti.find((d5) => d5.id === column.id); + return !columnSort ? false : columnSort.desc ? "desc" : "asc"; + }, + getSortIndex: () => { + var _table$getState$sorti2, _table$getState$sorti3; + return (_table$getState$sorti2 = (_table$getState$sorti3 = table.getState().sorting) == null ? void 0 : _table$getState$sorti3.findIndex((d5) => d5.id === column.id)) != null ? _table$getState$sorti2 : -1; + }, + clearSorting: () => { + table.setSorting((old) => old != null && old.length ? old.filter((d5) => d5.id !== column.id) : []); + }, + getToggleSortingHandler: () => { + const canSort = column.getCanSort(); + return (e4) => { + if (!canSort) + return; + e4.persist == null ? void 0 : e4.persist(); + column.toggleSorting == null ? void 0 : column.toggleSorting(void 0, column.getCanMultiSort() ? table.options.isMultiSortEvent == null ? void 0 : table.options.isMultiSortEvent(e4) : false); + }; + } + }; }, - "color": { - label: "Color", - field: "color", - vType: "text", - type: "fileprop" + createTable: (table) => { + return { + setSorting: (updater) => table.options.onSortingChange == null ? void 0 : table.options.onSortingChange(updater), + resetSorting: (defaultState) => { + var _table$initialState$s, _table$initialState; + table.setSorting(defaultState ? [] : (_table$initialState$s = (_table$initialState = table.initialState) == null ? void 0 : _table$initialState.sorting) != null ? _table$initialState$s : []); + }, + getPreSortedRowModel: () => table.getGroupedRowModel(), + getSortedRowModel: () => { + if (!table._getSortedRowModel && table.options.getSortedRowModel) { + table._getSortedRowModel = table.options.getSortedRowModel(table); + } + if (table.options.manualSorting || !table._getSortedRowModel) { + return table.getPreSortedRowModel(); + } + return table._getSortedRowModel(); + } + }; + } +}; +var Visibility = { + getInitialState: (state) => { + return { + columnVisibility: {}, + ...state + }; }, - "ctime": { - label: "Created", - field: "ctime", - vType: "date", - type: "fileprop" + getDefaultOptions: (table) => { + return { + onColumnVisibilityChange: makeStateUpdater("columnVisibility", table) + }; }, - "mtime": { - label: "Last Modified", - field: "mtime", - vType: "date", - type: "fileprop" + createColumn: (column, table) => { + return { + toggleVisibility: (value) => { + if (column.getCanHide()) { + table.setColumnVisibility((old) => ({ + ...old, + [column.id]: value != null ? value : !column.getIsVisible() + })); + } + }, + getIsVisible: () => { + var _table$getState$colum, _table$getState$colum2; + return (_table$getState$colum = (_table$getState$colum2 = table.getState().columnVisibility) == null ? void 0 : _table$getState$colum2[column.id]) != null ? _table$getState$colum : true; + }, + getCanHide: () => { + var _column$columnDef$ena, _table$options$enable; + return ((_column$columnDef$ena = column.columnDef.enableHiding) != null ? _column$columnDef$ena : true) && ((_table$options$enable = table.options.enableHiding) != null ? _table$options$enable : true); + }, + getToggleVisibilityHandler: () => { + return (e4) => { + column.toggleVisibility == null ? void 0 : column.toggleVisibility(e4.target.checked); + }; + } + }; }, - "extension": { - label: "Extension", - field: "extension", - vType: "text", - type: "fileprop" + createRow: (row, table) => { + return { + _getAllVisibleCells: memo(() => [row.getAllCells(), table.getState().columnVisibility], (cells) => { + return cells.filter((cell) => cell.column.getIsVisible()); + }, { + key: false, + debug: () => { + var _table$options$debugA; + return (_table$options$debugA = table.options.debugAll) != null ? _table$options$debugA : table.options.debugRows; + } + }), + getVisibleCells: memo(() => [row.getLeftVisibleCells(), row.getCenterVisibleCells(), row.getRightVisibleCells()], (left, center, right) => [...left, ...center, ...right], { + key: "row.getVisibleCells", + debug: () => { + var _table$options$debugA2; + return (_table$options$debugA2 = table.options.debugAll) != null ? _table$options$debugA2 : table.options.debugRows; + } + }) + }; }, - "size": { - label: "Size", - field: "size", - vType: "number", - type: "fileprop" + createTable: (table) => { + const makeVisibleColumnsMethod = (key2, getColumns) => { + return memo(() => [getColumns(), getColumns().filter((d5) => d5.getIsVisible()).map((d5) => d5.id).join("_")], (columns) => { + return columns.filter((d5) => d5.getIsVisible == null ? void 0 : d5.getIsVisible()); + }, { + key: key2, + debug: () => { + var _table$options$debugA3; + return (_table$options$debugA3 = table.options.debugAll) != null ? _table$options$debugA3 : table.options.debugColumns; + } + }); + }; + return { + getVisibleFlatColumns: makeVisibleColumnsMethod("getVisibleFlatColumns", () => table.getAllFlatColumns()), + getVisibleLeafColumns: makeVisibleColumnsMethod("getVisibleLeafColumns", () => table.getAllLeafColumns()), + getLeftVisibleLeafColumns: makeVisibleColumnsMethod("getLeftVisibleLeafColumns", () => table.getLeftLeafColumns()), + getRightVisibleLeafColumns: makeVisibleColumnsMethod("getRightVisibleLeafColumns", () => table.getRightLeafColumns()), + getCenterVisibleLeafColumns: makeVisibleColumnsMethod("getCenterVisibleLeafColumns", () => table.getCenterLeafColumns()), + setColumnVisibility: (updater) => table.options.onColumnVisibilityChange == null ? void 0 : table.options.onColumnVisibilityChange(updater), + resetColumnVisibility: (defaultState) => { + var _table$initialState$c; + table.setColumnVisibility(defaultState ? {} : (_table$initialState$c = table.initialState.columnVisibility) != null ? _table$initialState$c : {}); + }, + toggleAllColumnsVisible: (value) => { + var _value; + value = (_value = value) != null ? _value : !table.getIsAllColumnsVisible(); + table.setColumnVisibility(table.getAllLeafColumns().reduce((obj, column) => ({ + ...obj, + [column.id]: !value ? !(column.getCanHide != null && column.getCanHide()) : value + }), {})); + }, + getIsAllColumnsVisible: () => !table.getAllLeafColumns().some((column) => !(column.getIsVisible != null && column.getIsVisible())), + getIsSomeColumnsVisible: () => table.getAllLeafColumns().some((column) => column.getIsVisible == null ? void 0 : column.getIsVisible()), + getToggleAllColumnsVisibilityHandler: () => { + return (e4) => { + var _target; + table.toggleAllColumnsVisible((_target = e4.target) == null ? void 0 : _target.checked); + }; + } + }; } }; -var fileMeta = { - "tags": { - label: "Tags", - field: "tags", - vType: "tags-multi", - type: "filemeta" - }, - "inlinks": { - label: "Linked Mentions", - field: "inlinks", - vType: "link-multi", - type: "filemeta" - }, - "outlinks": { - label: "Links", - field: "outlinks", - vType: "link-multi", - type: "filemeta" +var features = [Headers, Visibility, Ordering, Pinning, Filters, Sorting, Grouping, Expanding, Pagination, RowSelection, ColumnSizing]; +function createTable2(options) { + var _options$initialState; + if (options.debugAll || options.debugTable) { + console.info("Creating Table Instance..."); } -}; - -// src/utils/contexts/predicate/filterFns/filterFnLabels.ts -var filterFnLabels = { - isEmpty: i18n_default.filterTypes.isEmpty, - isNotEmpty: i18n_default.filterTypes.isNotEmpty, - include: i18n_default.filterTypes.contains, - notInclude: i18n_default.filterTypes.notContains, - is: i18n_default.filterTypes.is, - isNot: i18n_default.filterTypes.isNot, - equal: "=", - isGreatThan: ">", - isLessThan: "<", - isLessThanOrEqual: "\u2264", - isGreatThanOrEqual: "\u2265", - dateBefore: i18n_default.filterTypes.before, - dateAfter: i18n_default.filterTypes.after, - isAnyInList: i18n_default.filterTypes.anyOf, - isNoneInList: i18n_default.filterTypes.noneOf, - isTrue: i18n_default.filterTypes.checked, - isFalse: i18n_default.filterTypes.unchecked -}; - -// src/components/ContextView/ContextBuilder/ContextBuilderView.tsx -var import_classnames = __toESM(require_classnames()); - -// src/components/ContextView/ContextBuilder/TagSelector.tsx -var TagSelector = (props2) => { - const { - data, - tagContexts, - dbFileExists, - setContextTable, - saveDB: saveDB2, - tableData, - cols, - contextTable, - dbSchema, - contextInfo, - saveContextDB, - saveSchema, - loadContextFields - } = q2(MDBContext); - const removeContext = (value) => { - const tags = tagContexts.filter((f4) => value != f4); - saveSchema({ - ...dbSchema, - def: updateTagsForDefString(dbSchema.def, tags) - }); + let table = { + _features: features }; - const addTag2 = async (tag) => { - const tags = uniq([...tagContexts, tag]); - tags.forEach((tag2) => { - initiateContextIfNotExists(props2.plugin, tag2).then( - (f4) => loadContextFields(tag2) - ); - }); - saveSchema({ - ...dbSchema, - def: updateTagsForDefString(dbSchema.def, tags) - }); - connectContext(props2.plugin, tag, contextInfo.dbPath); + const defaultOptions4 = table._features.reduce((obj, feature) => { + return Object.assign(obj, feature.getDefaultOptions == null ? void 0 : feature.getDefaultOptions(table)); + }, {}); + const mergeOptions = (options2) => { + if (table.options.mergeOptions) { + return table.options.mergeOptions(defaultOptions4, options2); + } + return { + ...defaultOptions4, + ...options2 + }; }; - return /* @__PURE__ */ Cn.createElement(TagsView, { - plugin: props2.plugin, - tags: tagContexts, - canOpen: false, - addTag: props2.canAdd && addTag2, - removeTag: removeContext + const coreInitialState = {}; + let initialState2 = { + ...coreInitialState, + ...(_options$initialState = options.initialState) != null ? _options$initialState : {} + }; + table._features.forEach((feature) => { + var _feature$getInitialSt; + initialState2 = (_feature$getInitialSt = feature.getInitialState == null ? void 0 : feature.getInitialState(initialState2)) != null ? _feature$getInitialSt : initialState2; }); -}; - -// src/components/ContextView/ContextBuilder/ContextDesigner.tsx -var ContextDesigner = (props2) => { - const { sortedColumns, predicate, savePredicate } = q2(MDBContext); - const [activeId, setActiveId] = h2(""); - const [overId, setOverId] = h2(""); - const items = sortedColumns.map((f4) => ({ ...f4, id: f4.name + f4.table })); - const sensors = useSensors( - useSensor(MouseSensor, { - activationConstraint: { - distance: 10 + const queued = []; + let queuedTimeout = false; + const coreInstance = { + _features: features, + options: { + ...defaultOptions4, + ...options + }, + initialState: initialState2, + _queue: (cb) => { + queued.push(cb); + if (!queuedTimeout) { + queuedTimeout = true; + Promise.resolve().then(() => { + while (queued.length) { + queued.shift()(); + } + queuedTimeout = false; + }).catch((error) => setTimeout(() => { + throw error; + })); + } + }, + reset: () => { + table.setState(table.initialState); + }, + setOptions: (updater) => { + const newOptions = functionalUpdate(updater, table.options); + table.options = mergeOptions(newOptions); + }, + getState: () => { + return table.options.state; + }, + setState: (updater) => { + table.options.onStateChange == null ? void 0 : table.options.onStateChange(updater); + }, + _getRowId: (row, index, parent) => { + var _table$options$getRow; + return (_table$options$getRow = table.options.getRowId == null ? void 0 : table.options.getRowId(row, index, parent)) != null ? _table$options$getRow : `${parent ? [parent.id, index].join(".") : index}`; + }, + getCoreRowModel: () => { + if (!table._getCoreRowModel) { + table._getCoreRowModel = table.options.getCoreRowModel(table); + } + return table._getCoreRowModel(); + }, + getRowModel: () => { + return table.getPaginationRowModel(); + }, + getRow: (id2) => { + const row = table.getRowModel().rowsById[id2]; + if (!row) { + if (true) { + throw new Error(`getRow expected an ID, but got ${id2}`); + } + throw new Error(); + } + return row; + }, + _getDefaultColumnDef: memo(() => [table.options.defaultColumn], (defaultColumn) => { + var _defaultColumn; + defaultColumn = (_defaultColumn = defaultColumn) != null ? _defaultColumn : {}; + return { + header: (props2) => { + const resolvedColumnDef = props2.header.column.columnDef; + if (resolvedColumnDef.accessorKey) { + return resolvedColumnDef.accessorKey; + } + if (resolvedColumnDef.accessorFn) { + return resolvedColumnDef.id; + } + return null; + }, + cell: (props2) => { + var _props$renderValue$to, _props$renderValue; + return (_props$renderValue$to = (_props$renderValue = props2.renderValue()) == null ? void 0 : _props$renderValue.toString == null ? void 0 : _props$renderValue.toString()) != null ? _props$renderValue$to : null; + }, + ...table._features.reduce((obj, feature) => { + return Object.assign(obj, feature.getDefaultColumnDef == null ? void 0 : feature.getDefaultColumnDef()); + }, {}), + ...defaultColumn + }; + }, { + debug: () => { + var _table$options$debugA; + return (_table$options$debugA = table.options.debugAll) != null ? _table$options$debugA : table.options.debugColumns; + }, + key: "getDefaultColumnDef" + }), + _getColumnDefs: () => table.options.columns, + getAllColumns: memo(() => [table._getColumnDefs()], (columnDefs) => { + const recurseColumns = function(columnDefs2, parent, depth) { + if (depth === void 0) { + depth = 0; + } + return columnDefs2.map((columnDef) => { + const column = createColumn(table, columnDef, depth, parent); + const groupingColumnDef = columnDef; + column.columns = groupingColumnDef.columns ? recurseColumns(groupingColumnDef.columns, column, depth + 1) : []; + return column; + }); + }; + return recurseColumns(columnDefs); + }, { + key: "getAllColumns", + debug: () => { + var _table$options$debugA2; + return (_table$options$debugA2 = table.options.debugAll) != null ? _table$options$debugA2 : table.options.debugColumns; } }), - useSensor(TouchSensor, { - activationConstraint: { - delay: 250, - tolerance: 5 + getAllFlatColumns: memo(() => [table.getAllColumns()], (allColumns) => { + return allColumns.flatMap((column) => { + return column.getFlatColumns(); + }); + }, { + key: "getAllFlatColumns", + debug: () => { + var _table$options$debugA3; + return (_table$options$debugA3 = table.options.debugAll) != null ? _table$options$debugA3 : table.options.debugColumns; } }), - useSensor(KeyboardSensor, { - coordinateGetter: sortableKeyboardCoordinates + _getAllFlatColumnsById: memo(() => [table.getAllFlatColumns()], (flatColumns) => { + return flatColumns.reduce((acc, column) => { + acc[column.id] = column; + return acc; + }, {}); + }, { + key: "getAllFlatColumnsById", + debug: () => { + var _table$options$debugA4; + return (_table$options$debugA4 = table.options.debugAll) != null ? _table$options$debugA4 : table.options.debugColumns; + } + }), + getAllLeafColumns: memo(() => [table.getAllColumns(), table._getOrderColumnsFn()], (allColumns, orderColumns2) => { + let leafColumns = allColumns.flatMap((column) => column.getLeafColumns()); + return orderColumns2(leafColumns); + }, { + key: "getAllLeafColumns", + debug: () => { + var _table$options$debugA5; + return (_table$options$debugA5 = table.options.debugAll) != null ? _table$options$debugA5 : table.options.debugColumns; + } + }), + getColumn: (columnId) => { + const column = table._getAllFlatColumnsById()[columnId]; + if (!column) { + console.error(`[Table] Column with id '${columnId}' does not exist.`); + } + return column; + } + }; + Object.assign(table, coreInstance); + table._features.forEach((feature) => { + return Object.assign(table, feature.createTable == null ? void 0 : feature.createTable(table)); + }); + return table; +} +function createCell(table, row, column, columnId) { + const getRenderValue = () => { + var _cell$getValue; + return (_cell$getValue = cell.getValue()) != null ? _cell$getValue : table.options.renderFallbackValue; + }; + const cell = { + id: `${row.id}_${column.id}`, + row, + column, + getValue: () => row.getValue(columnId), + renderValue: getRenderValue, + getContext: memo(() => [table, column, row, cell], (table2, column2, row2, cell2) => ({ + table: table2, + column: column2, + row: row2, + cell: cell2, + getValue: cell2.getValue, + renderValue: cell2.renderValue + }), { + key: "cell.getContext", + debug: () => table.options.debugAll }) - ); - const resetState = () => { - setActiveId(null); - setOverId(null); }; - return /* @__PURE__ */ Cn.createElement(DndContext, { - sensors, - collisionDetection: closestCenter, - measuring: { - droppable: { - strategy: MeasuringStrategy.Always + table._features.forEach((feature) => { + Object.assign(cell, feature.createCell == null ? void 0 : feature.createCell(cell, column, row, table)); + }, {}); + return cell; +} +var createRow = (table, id2, original, rowIndex, depth, subRows) => { + let row = { + id: id2, + index: rowIndex, + original, + depth, + _valuesCache: {}, + _uniqueValuesCache: {}, + getValue: (columnId) => { + if (row._valuesCache.hasOwnProperty(columnId)) { + return row._valuesCache[columnId]; + } + const column = table.getColumn(columnId); + if (!(column != null && column.accessorFn)) { + return void 0; } + row._valuesCache[columnId] = column.accessorFn(row.original, rowIndex); + return row._valuesCache[columnId]; }, - onDragStart: ({ active }) => { - setActiveId(active.id); + getUniqueValues: (columnId) => { + if (row._uniqueValuesCache.hasOwnProperty(columnId)) { + return row._uniqueValuesCache[columnId]; + } + const column = table.getColumn(columnId); + if (!(column != null && column.accessorFn)) { + return void 0; + } + if (!column.columnDef.getUniqueValues) { + row._uniqueValuesCache[columnId] = [row.getValue(columnId)]; + return row._uniqueValuesCache[columnId]; + } + row._uniqueValuesCache[columnId] = column.columnDef.getUniqueValues(row.original, rowIndex); + return row._uniqueValuesCache[columnId]; }, - onDragOver: ({ active, over }) => { - const overId2 = over == null ? void 0 : over.id; - if (overId2) - setOverId(overId2); + renderValue: (columnId) => { + var _row$getValue; + return (_row$getValue = row.getValue(columnId)) != null ? _row$getValue : table.options.renderFallbackValue; }, - onDragEnd: ({ active, over }) => { - const overId2 = over == null ? void 0 : over.id; - if (!overId2) { - resetState(); - return; - } - savePredicate({ - ...predicate, - colsOrder: arrayMove( - predicate.colsOrder, - predicate.colsOrder.findIndex((f4) => f4 == activeId), - predicate.colsOrder.findIndex((f4) => f4 == overId2) - ) + subRows: subRows != null ? subRows : [], + getLeafRows: () => flattenBy(row.subRows, (d5) => d5.subRows), + getAllCells: memo(() => [table.getAllLeafColumns()], (leafColumns) => { + return leafColumns.map((column) => { + return createCell(table, row, column, column.id); }); - resetState(); - }, - onDragCancel: resetState - }, /* @__PURE__ */ Cn.createElement("div", { - className: "mk-context-maker-layout" - }, /* @__PURE__ */ Cn.createElement("div", null, /* @__PURE__ */ Cn.createElement(SortableContext, { - items, - strategy: verticalListSortingStrategy - }, items.map((value, index) => { - return /* @__PURE__ */ Cn.createElement(SortableItem, { - id: value.id, - value: value.name - }); - })))), z3( - /* @__PURE__ */ Cn.createElement(DragOverlay, { - adjustScale: false - }, activeId ? /* @__PURE__ */ Cn.createElement(SortableItem, { - id: items.find((f4) => f4.id == activeId).id, - value: items.find((f4) => f4.id == activeId).name - }) : null), - document.body - )); -}; -function SortableItem(props2) { - const { attributes, listeners, setNodeRef, transform, transition } = useSortable({ id: props2.id }); - const style = { - transform: CSS.Transform.toString(transform), - transition + }, { + key: "row.getAllCells", + debug: () => { + var _table$options$debugA; + return (_table$options$debugA = table.options.debugAll) != null ? _table$options$debugA : table.options.debugRows; + } + }), + _getAllCellsByColumnId: memo(() => [row.getAllCells()], (allCells) => { + return allCells.reduce((acc, cell) => { + acc[cell.column.id] = cell; + return acc; + }, {}); + }, { + key: false, + debug: () => { + var _table$options$debugA2; + return (_table$options$debugA2 = table.options.debugAll) != null ? _table$options$debugA2 : table.options.debugRows; + } + }) }; - return /* @__PURE__ */ Cn.createElement("div", { - ref: setNodeRef, - style, - ...attributes, - ...listeners - }, props2.value); -} - -// src/components/ContextView/ContextBuilder/ContextBuilderView.tsx -var ContextBuilderView = (props2) => { - const { - data, - cols, - sortedColumns, - dbSchema, - schema, - contextInfo, - tableData, - contextTable, - saveColumn, - loadContextFields, - tagContexts, - hideColumn, - sortColumn, - delColumn, - saveDB: saveDB2, - saveContextDB, - dbFileExists, - predicate, - saveSchema - } = q2(MDBContext); - const [section, setSection] = h2(0); - const saveField = (field, oldField) => { - if (field.name.length > 0) { - if (field.name != oldField.name || field.type != oldField.type || field.value != oldField.value || field.attrs != oldField.attrs) { - const saveResult = saveColumn(field, oldField); + for (let i4 = 0; i4 < table._features.length; i4++) { + const feature = table._features[i4]; + Object.assign(row, feature == null ? void 0 : feature.createRow == null ? void 0 : feature.createRow(row, table)); + } + return row; +}; +function getCoreRowModel() { + return (table) => memo(() => [table.options.data], (data2) => { + const rowModel = { + rows: [], + flatRows: [], + rowsById: {} + }; + const accessRows = function(originalRows, depth, parent) { + if (depth === void 0) { + depth = 0; + } + const rows = []; + for (let i4 = 0; i4 < originalRows.length; i4++) { + const row = createRow(table, table._getRowId(originalRows[i4], i4, parent), originalRows[i4], i4, depth); + rowModel.flatRows.push(row); + rowModel.rowsById[row.id] = row; + rows.push(row); + if (table.options.getSubRows) { + var _row$originalSubRows; + row.originalSubRows = table.options.getSubRows(originalRows[i4], i4); + if ((_row$originalSubRows = row.originalSubRows) != null && _row$originalSubRows.length) { + row.subRows = accessRows(row.originalSubRows, depth + 1, row); + } + } } + return rows; + }; + rowModel.rows = accessRows(data2); + return rowModel; + }, { + key: "getRowModel", + debug: () => { + var _table$options$debugA; + return (_table$options$debugA = table.options.debugAll) != null ? _table$options$debugA : table.options.debugTable; + }, + onChange: () => { + table._autoResetPageIndex(); } - }; - const saveContext = (field, oldField, value) => { - const newContext = value[0]; - initiateContextIfNotExists(props2.plugin, newContext).then((f4) => { - if (f4) { - return insertContextItems( - props2.plugin, - optionValuesForColumn( - field.name, - field.table == "" ? tableData : contextTable[field.table] - ), - newContext - ); + }); +} +function getGroupedRowModel() { + return (table) => memo(() => [table.getState().grouping, table.getPreGroupedRowModel()], (grouping, rowModel) => { + if (!rowModel.rows.length || !grouping.length) { + return rowModel; + } + const existingGrouping = grouping.filter((columnId) => table.getColumn(columnId)); + const groupedFlatRows = []; + const groupedRowsById = {}; + const groupUpRecursively = function(rows, depth, parentId) { + if (depth === void 0) { + depth = 0; } - }).then((f4) => loadContextFields(newContext)); - const newField = { - ...field, - value: newContext != null ? newContext : "" + if (depth >= existingGrouping.length) { + return rows.map((row) => { + row.depth = depth; + groupedFlatRows.push(row); + groupedRowsById[row.id] = row; + if (row.subRows) { + row.subRows = groupUpRecursively(row.subRows, depth + 1); + } + return row; + }); + } + const columnId = existingGrouping[depth]; + const rowGroupsMap = groupBy(rows, columnId); + const aggregatedGroupedRows = Array.from(rowGroupsMap.entries()).map((_ref, index) => { + let [groupingValue, groupedRows2] = _ref; + let id2 = `${columnId}:${groupingValue}`; + id2 = parentId ? `${parentId}>${id2}` : id2; + const subRows = groupUpRecursively(groupedRows2, depth + 1, id2); + const leafRows = depth ? flattenBy(groupedRows2, (row2) => row2.subRows) : groupedRows2; + const row = createRow(table, id2, leafRows[0].original, index, depth); + Object.assign(row, { + groupingColumnId: columnId, + groupingValue, + subRows, + leafRows, + getValue: (columnId2) => { + if (existingGrouping.includes(columnId2)) { + if (row._valuesCache.hasOwnProperty(columnId2)) { + return row._valuesCache[columnId2]; + } + if (groupedRows2[0]) { + var _groupedRows$0$getVal; + row._valuesCache[columnId2] = (_groupedRows$0$getVal = groupedRows2[0].getValue(columnId2)) != null ? _groupedRows$0$getVal : void 0; + } + return row._valuesCache[columnId2]; + } + if (row._groupingValuesCache.hasOwnProperty(columnId2)) { + return row._groupingValuesCache[columnId2]; + } + const column = table.getColumn(columnId2); + const aggregateFn = column == null ? void 0 : column.getAggregationFn(); + if (aggregateFn) { + row._groupingValuesCache[columnId2] = aggregateFn(columnId2, leafRows, groupedRows2); + return row._groupingValuesCache[columnId2]; + } + } + }); + subRows.forEach((subRow) => { + groupedFlatRows.push(subRow); + groupedRowsById[subRow.id] = subRow; + }); + return row; + }); + return aggregatedGroupedRows; + }; + const groupedRows = groupUpRecursively(rowModel.rows, 0, ""); + groupedRows.forEach((subRow) => { + groupedFlatRows.push(subRow); + groupedRowsById[subRow.id] = subRow; + }); + return { + rows: groupedRows, + flatRows: groupedFlatRows, + rowsById: groupedRowsById }; - saveColumn(newField, oldField); + }, { + key: "getGroupedRowModel", + debug: () => { + var _table$options$debugA; + return (_table$options$debugA = table.options.debugAll) != null ? _table$options$debugA : table.options.debugTable; + }, + onChange: () => { + table._queue(() => { + table._autoResetExpanded(); + table._autoResetPageIndex(); + }); + } + }); +} +function groupBy(rows, columnId) { + const groupMap = /* @__PURE__ */ new Map(); + return rows.reduce((map, row) => { + const resKey = `${row.getValue(columnId)}`; + const previous = map.get(resKey); + if (!previous) { + map.set(resKey, [row]); + } else { + previous.push(row); + } + return map; + }, groupMap); +} +function getExpandedRowModel() { + return (table) => memo(() => [table.getState().expanded, table.getPreExpandedRowModel(), table.options.paginateExpandedRows], (expanded, rowModel, paginateExpandedRows) => { + if (!rowModel.rows.length || expanded !== true && !Object.keys(expanded != null ? expanded : {}).length) { + return rowModel; + } + if (!paginateExpandedRows) { + return rowModel; + } + return expandRows(rowModel); + }, { + key: "getExpandedRowModel", + debug: () => { + var _table$options$debugA; + return (_table$options$debugA = table.options.debugAll) != null ? _table$options$debugA : table.options.debugTable; + } + }); +} +function expandRows(rowModel) { + const expandedRows = []; + const handleRow = (row) => { + var _row$subRows; + expandedRows.push(row); + if ((_row$subRows = row.subRows) != null && _row$subRows.length && row.getIsExpanded()) { + row.subRows.forEach(handleRow); + } }; - const showMenu = (e4, field) => { - const offset = e4.target.getBoundingClientRect(); - const options = optionValuesForColumn( - field.name, - field.table == "" ? tableData : contextTable[field.table] - ); - showPropertyMenu( - props2.plugin, - { x: offset.left, y: offset.top + 30 }, - true, - options, - field, - cols, - contextInfo.contextPath, - (newField) => saveField(newField, field), - (newField, val) => saveContext(newField, field, val), - hideColumn, - delColumn, - sortColumn, - predicate.colsHidden.includes(field.name + field.table) - ); + rowModel.rows.forEach(handleRow); + return { + rows: expandedRows, + flatRows: rowModel.flatRows, + rowsById: rowModel.rowsById }; - const saveNewField = (source, field) => { - saveColumn({ ...field, table: "" }); +} + +// node_modules/@tanstack/react-table/build/lib/index.mjs +function flexRender(Comp, props2) { + return !Comp ? null : isReactComponent(Comp) ? /* @__PURE__ */ y(Comp, props2) : Comp; +} +function isReactComponent(component) { + return isClassComponent(component) || typeof component === "function" || isExoticComponent(component); +} +function isClassComponent(component) { + return typeof component === "function" && (() => { + const proto = Object.getPrototypeOf(component); + return proto.prototype && proto.prototype.isReactComponent; + })(); +} +function isExoticComponent(component) { + return typeof component === "object" && typeof component.$$typeof === "symbol" && ["react.memo", "react.forward_ref"].includes(component.$$typeof.description); +} +function useReactTable(options) { + const resolvedOptions = { + state: {}, + onStateChange: () => { + }, + renderFallbackValue: null, + ...options }; - const newProperty = (e4) => { - const offset = e4.target.getBoundingClientRect(); - showNewPropertyMenu( - props2.plugin, - { x: offset.left, y: offset.top + 30 }, - tagContexts, - [], - saveNewField, - "files", - contextInfo.contextPath, - false + const [tableRef] = h2(() => ({ + current: createTable2(resolvedOptions) + })); + const [state, setState] = h2(() => tableRef.current.initialState); + tableRef.current.setOptions((prev) => ({ + ...prev, + ...options, + state: { + ...state, + ...options.state + }, + onStateChange: (updater) => { + setState(updater); + options.onStateChange == null ? void 0 : options.onStateChange(updater); + } + })); + return tableRef.current; +} + +// src/components/SpaceView/Contexts/DataTypeView/OptionCell.tsx +var import_lodash10 = __toESM(require_lodash()); +var OptionCell = (props2) => { + var _a2, _b2, _c2; + const parsedValue = F2( + () => parseFieldValue(props2.options, "option"), + [props2.options] + ); + const serializeValue = (newOptions, value2) => JSON.stringify({ + ...value2, + options: newOptions.map((f4) => ({ name: f4.name, value: f4.value })) + }); + const initialValue = (props2.multi ? (_a2 = parseMultiString(props2.initialValue)) != null ? _a2 : [] : [props2.initialValue]).filter((f4) => f4); + const initialOptions = [ + ...(_c2 = ((_b2 = parsedValue.options) != null ? _b2 : []).filter((f4) => f4.value).map((t4) => ({ name: t4.name, value: t4.value, removeable: true }))) != null ? _c2 : [], + ...initialValue.map((f4) => ({ name: f4, value: f4, removeable: true })) + ].filter(onlyUniqueProp("value")).filter((f4) => f4.value.length > 0); + const [options, setOptions] = h2(initialOptions); + const [value, setValue] = h2(initialValue); + p2(() => { + var _a3; + setValue( + (props2.multi ? (_a3 = parseMultiString(props2.initialValue)) != null ? _a3 : [] : [props2.initialValue]).filter((f4) => f4) + ); + }, [props2.initialValue]); + const removeValue = (v3) => { + const newValues = value.filter((f4) => f4 != v3); + setValue(newValues); + props2.saveOptions( + serializeValue(options, parsedValue), + serializeMultiString(newValues) ); }; - const saveMetadata = (keys, table) => { - const files = data.map((f4) => f4.File); - const importDV = (files2, dvKeys) => { - return files2.reduce( - (p3, c4) => { - const dvValues = props2.plugin.dataViewAPI().page(c4); - if (!dvValues) { - return p3; - } - return { - uniques: [], - cols: uniqCaseInsensitive([...p3.cols, ...dvKeys]), - rows: [ - ...p3.rows, - { - File: c4, - ...dvKeys.reduce( - (p4, c5) => ({ - ...p4, - [c5]: parseDataview(c5, dvValues[c5]) - }), - {} - ) - } - ] - }; - }, - { uniques: [], cols: [], rows: [] } - ); - }; - const importYAML = (files2, fmKeys) => { - return files2.map((f4) => getAbstractFileAtPath(app, f4)).filter((f4) => f4).reduce( - (p3, c4) => { - const fm = frontMatterForFile(c4); - if (!fm) { - return p3; - } - return { - uniques: [], - cols: uniq([...p3.cols, ...fmKeys]), - rows: [ - ...p3.rows, - { - File: c4.path, - ...fmKeys.reduce( - (p4, c5) => ({ - ...p4, - [c5]: parseFrontMatter(c5, fm[c5]) - }), - {} - ) - } - ] - }; - }, - { uniques: [], cols: [], rows: [] } - ); - }; - let yamlTableData = importYAML( - files, - keys.filter((f4) => f4.type == "fm").map((f4) => f4.name) + const removeOption = (option) => { + const newOptions = options.filter((f4) => f4.value != option); + const newValues = value.filter((f4) => f4 != option); + setOptions(newOptions); + setValue(newValues); + props2.saveOptions( + serializeValue( + newOptions.map((f4) => f4.value), + parsedValue + ), + serializeMultiString(newValues) ); - let yamlTypes = guestimateTypes(files, props2.plugin, false); - if (props2.plugin.dataViewAPI()) { - const dvTableData = importDV( - files, - keys.filter((f4) => f4.type == "dv").map((f4) => f4.name) - ); - const dvTypes = guestimateTypes(files, props2.plugin, true); - yamlTableData = { - uniques: uniq([...yamlTableData.uniques, ...dvTableData.uniques]), - cols: uniqCaseInsensitive([...yamlTableData.cols, ...dvTableData.cols]), - rows: files.map((file) => { - var _a2, _b2; - return { - ...(_a2 = yamlTableData.rows.find((r3) => r3.File == file)) != null ? _a2 : {}, - ...(_b2 = dvTableData.rows.find((r3) => r3.File == file)) != null ? _b2 : {} - }; - }) - }; - yamlTypes = { ...yamlTypes, ...dvTypes }; - } - if (table == "") { - const newTable = mergeTableData(tableData, yamlTableData, yamlTypes); - saveDB2(newTable); - } else { - if (!dbFileExists) { - saveDB2(tableData).then( - () => syncMetadataContext(yamlTableData, yamlTypes, table) - ); - } else { - syncMetadataContext(yamlTableData, yamlTypes, table); - } - } }; - const syncMetadataContext = (yamlTableData, yamlTypes, table) => { - if (contextTable[table]) { - const newTable = mergeTableData( - contextTable[table], - yamlTableData, - yamlTypes + const saveOptions = (_options, _value) => { + if (!props2.multi) { + setOptions( + _options.filter((f4) => f4.length > 0).map((t4) => ({ name: t4, value: t4, removeable: true })) + ); + setValue(_value); + props2.saveOptions( + serializeValue( + _options.filter((f4) => f4.length > 0).map((t4) => ({ name: t4, value: t4 })), + parsedValue + ), + serializeMultiString(_value) ); - saveContextDB(newTable, table); - saveSchema({ - ...dbSchema, - def: updateTagsForDefString( - dbSchema.def, - uniq([...tagContexts, table]) - ) - }); } else { - getMDBTable(props2.plugin, tagContextFromTag(props2.plugin, table), "files").then((f4) => { - if (f4) { - const newTable = mergeTableData(f4, yamlTableData, yamlTypes); - return saveContextDB(newTable, table); - } - }).then(() => { - saveSchema({ - ...dbSchema, - def: updateTagsForDefString( - dbSchema.def, - uniq([...tagContexts, table]) - ) - }); - }); + const newValues = (0, import_lodash10.uniq)([...value, _value[0]]); + setOptions( + _options.map((t4) => ({ name: t4, value: t4, removeable: true })) + ); + setValue(newValues); + props2.saveOptions( + serializeValue( + _options.filter((f4) => f4.length > 0).map((t4) => ({ name: t4, value: t4 })), + parsedValue + ), + serializeMultiString(newValues) + ); } }; - return /* @__PURE__ */ Cn.createElement(Cn.Fragment, null, /* @__PURE__ */ Cn.createElement("div", { - className: "mk-context-maker-preview" - }, /* @__PURE__ */ Cn.createElement("div", { - className: (schema == null ? void 0 : schema.type) == "card" ? "mk-cards-container mk-cards-grid" : "mk-list-container" - }, /* @__PURE__ */ Cn.createElement("div", { - className: "mk-list-item" - }, sortedColumns.filter((f4) => f4.type == "preview" && f4.table == "").map((f4) => /* @__PURE__ */ Cn.createElement(DataTypeView, { - plugin: props2.plugin, - initialValue: defaultValueForPropertyType( - f4.name, - f4.value, - f4.type - ), - column: f4, - index: 0, - file: "", - editable: false - })), /* @__PURE__ */ Cn.createElement("div", { - className: "mk-list-fields" - }, sortedColumns.filter((f4) => f4.type != "preview").map((f4, i4) => /* @__PURE__ */ Cn.createElement(DataTypeView, { + const menuProps = () => ({ + multi: false, + editable: true, plugin: props2.plugin, - initialValue: defaultValueForPropertyType( - f4.name, - f4.value, - f4.type - ), - index: 0, - file: "", - column: { ...f4, table: "" }, - editable: false, - updateValue: (v3) => { - }, - updateFieldValue: (fv, v3) => { - }, - contextTable: {} - })))))), /* @__PURE__ */ Cn.createElement("div", { - className: "mk-context-maker-selector" - }, section == 0 ? /* @__PURE__ */ Cn.createElement("div", null, /* @__PURE__ */ Cn.createElement("div", { - className: (0, import_classnames.default)("mk-section-title") - }, (dbSchema == null ? void 0 : dbSchema.primary) == "true" ? contextDisplayName(contextInfo) : "Properties"), /* @__PURE__ */ Cn.createElement("div", { - className: "mk-cell-option" - }, cols.filter( - (f4) => !(f4.type == "preview" && f4.table != "") && f4.table == "" - ).map((f4, i4) => /* @__PURE__ */ Cn.createElement("div", { - key: i4 - }, /* @__PURE__ */ Cn.createElement("div", { - className: (0, import_classnames.default)( - "mk-cell-option-item", - !predicate.colsHidden.includes(f4.name + f4.table) && "mk-is-active" - ), - onClick: (e4) => hideColumn( - f4, - !predicate.colsHidden.includes(f4.name + f4.table) - ), - onContextMenu: (e4) => showMenu(e4, f4) - }, /* @__PURE__ */ Cn.createElement("div", null, f4.name, " ")))), /* @__PURE__ */ Cn.createElement("div", { - className: "mk-cell-option-item" - }, /* @__PURE__ */ Cn.createElement("div", { - className: (0, import_classnames.default)(`mk-icon-xsmall`), - onClick: (e4) => newProperty(e4), - dangerouslySetInnerHTML: { - __html: uiIconSet["mk-ui-plus"] + value, + options: !props2.multi ? [{ name: i18n_default.menu.none, value: "" }, ...options] : options, + saveOptions, + removeOption, + placeholder: i18n_default.labels.optionItemSelectPlaceholder, + searchable: true, + showAll: true, + onHide: () => props2.setEditMode(null) + }); + return /* @__PURE__ */ Cn.createElement(OptionCellBase, { + baseClass: "mk-cell-option", + value, + menuProps, + multi: props2.multi, + editMode: props2.editMode, + removeValue + }); +}; +var OptionCellBase = (props2) => { + const { + value, + menuProps, + removeValue, + getLabelString, + openItem, + valueClass + } = props2; + const menuRef = _2(null); + p2(() => { + if (props2.editMode == 2) { + if (!menuRef.current) + showMenu(); } - }))), (dbSchema == null ? void 0 : dbSchema.primary) == "true" && contextInfo.type != "tag" && /* @__PURE__ */ Cn.createElement(Cn.Fragment, null, /* @__PURE__ */ Cn.createElement("div", { - className: (0, import_classnames.default)("mk-section-title") - }, "Contexts"), /* @__PURE__ */ Cn.createElement(TagSelector, { - plugin: props2.plugin, - canAdd: true - }), tagContexts.map((t4) => /* @__PURE__ */ Cn.createElement(Cn.Fragment, null, /* @__PURE__ */ Cn.createElement("div", { - className: (0, import_classnames.default)("mk-section-title") - }, t4 == "" ? contextDisplayName(contextInfo) : t4), /* @__PURE__ */ Cn.createElement("div", { - className: "mk-cell-option" - }, cols.filter( - (f4) => !(f4.type == "preview" && f4.table != "") && f4.table == t4 - ).map((f4, i4) => /* @__PURE__ */ Cn.createElement("div", { - key: i4 - }, /* @__PURE__ */ Cn.createElement("div", { - className: (0, import_classnames.default)( - "mk-cell-option-item", - !predicate.colsHidden.includes( - f4.name + f4.table - ) && "mk-is-active" - ), - onClick: (e4) => hideColumn( - f4, - !predicate.colsHidden.includes( - f4.name + f4.table - ) - ), - onContextMenu: (e4) => showMenu(e4, f4) - }, /* @__PURE__ */ Cn.createElement("div", null, f4.name, " ")))), /* @__PURE__ */ Cn.createElement("div", { + }, [props2.editMode]); + const ref2 = _2(null); + const showMenu = () => { + const offset2 = ref2.current.getBoundingClientRect(); + menuRef.current = showSelectMenu( + { x: offset2.left - 4, y: offset2.bottom - 4 }, + menuProps() + ); + }; + const editable = props2.editMode > 0; + return /* @__PURE__ */ Cn.createElement("div", { + className: props2.baseClass, + ref: ref2 + }, value.length > 0 ? value.map((o3, i4) => /* @__PURE__ */ Cn.createElement("div", { + key: i4, className: "mk-cell-option-item" - }, /* @__PURE__ */ Cn.createElement("div", { - className: (0, import_classnames.default)(`mk-icon-xsmall`), - onClick: (e4) => newProperty(e4), + }, (getLabelString ? getLabelString(o3).length > 0 : o3.length > 0) ? /* @__PURE__ */ Cn.createElement(Cn.Fragment, null, /* @__PURE__ */ Cn.createElement("div", { + className: valueClass && valueClass(o3), + onClick: () => openItem && openItem(o3) + }, getLabelString ? getLabelString(o3) : o3), editable && props2.multi ? /* @__PURE__ */ Cn.createElement("div", { + className: "mk-icon-xsmall", + onClick: () => removeValue(o3), dangerouslySetInnerHTML: { - __html: uiIconSet["mk-ui-plus"] + __html: uiIconSet["mk-ui-close"] } - })))))), (dbSchema == null ? void 0 : dbSchema.primary) == "true" && /* @__PURE__ */ Cn.createElement(Cn.Fragment, null, /* @__PURE__ */ Cn.createElement("div", { - className: (0, import_classnames.default)("mk-section-title") - }, "Metadata"), /* @__PURE__ */ Cn.createElement(SyncMetadataComponent, { - plugin: props2.plugin, - columns: cols, - syncColumn: (columns, table) => saveMetadata([columns], table), - files: data.map((f4) => getAbstractFileAtPath(app, f4.File)).filter((f4) => f4) - }))) : /* @__PURE__ */ Cn.createElement(ContextDesigner, null)), /* @__PURE__ */ Cn.createElement("div", { - className: "mk-section-tabs" - }, /* @__PURE__ */ Cn.createElement("div", { - className: (0, import_classnames.default)( - "mk-section-title", - section == 0 && "mk-is-active" - ), - onClick: () => setSection(0) - }, /* @__PURE__ */ Cn.createElement("div", { - className: (0, import_classnames.default)(`mk-icon-small`), + }) : /* @__PURE__ */ Cn.createElement(Cn.Fragment, null)) : /* @__PURE__ */ Cn.createElement("div", null, i18n_default.labels.select), editable && !props2.multi && value.length > 0 ? /* @__PURE__ */ Cn.createElement(Cn.Fragment, null, /* @__PURE__ */ Cn.createElement("span", null), /* @__PURE__ */ Cn.createElement("div", { + onClick: (e4) => editable && !props2.multi && showMenu(), + className: "mk-cell-option-select mk-icon-xxsmall mk-icon-rotated", dangerouslySetInnerHTML: { - __html: uiIconSet["mk-ui-edit"] + __html: uiIconSet["mk-ui-collapse-sm"] } - }), "Properties"), /* @__PURE__ */ Cn.createElement("div", { - className: (0, import_classnames.default)( - "mk-section-title", - section == 1 && "mk-is-active" - ), - onClick: () => setSection(1) + })) : /* @__PURE__ */ Cn.createElement(Cn.Fragment, null))) : editable && !props2.multi ? /* @__PURE__ */ Cn.createElement("div", { + className: "mk-cell-option-item" }, /* @__PURE__ */ Cn.createElement("div", { - className: (0, import_classnames.default)(`mk-icon-small`), - dangerouslySetInnerHTML: { - __html: uiIconSet["mk-ui-stack"] - } - }), "Layout"))); -}; - -// src/components/ui/modals/contextEditorModal.tsx -var import_obsidian19 = require("obsidian"); -var ContextEditorModal = class extends import_obsidian19.Modal { - constructor(plugin, context, view) { - super(plugin.app); - this.context = context; - this.view = view; - this.plugin = plugin; - } - onOpen() { - let { contentEl } = this; - let myModal = this; - myModal.modalEl.toggleClass("mk-context-maker", true); - let headerText; - headerText = i18n_default.labels.contextMaker; - const queryEl = contentEl.createDiv("mk-context-maker-container"); - const root = createRoot(queryEl); - root.render( - /* @__PURE__ */ Cn.createElement(MDBProvider, { - plugin: this.plugin, - context: this.context, - schema: this.view - }, /* @__PURE__ */ Cn.createElement(ContextBuilderView, { - plugin: this.plugin - })) - ); - } - onClose() { - let { contentEl } = this; - contentEl.empty(); - } -}; - -// src/components/ui/modals/mergeColumnModal.ts -var import_obsidian20 = require("obsidian"); -var MergeColumnModal = class extends import_obsidian20.Modal { - constructor(columns, mergeColumn) { - super(app); - this.columns = columns; - this.mergeColumn = mergeColumn; - } - onOpen() { - let { contentEl } = this; - let myModal = this; - let headerText = i18n_default.labels.mergeProperties; - const headerEl = contentEl.createEl("div", { text: headerText }); - headerEl.addClass("modal-title"); - const containerEl = contentEl.createEl("div"); - containerEl.style.cssText = "width: 100%; height: 2.5em; margin-bottom: 15px;"; - const select = containerEl.createEl("select"); - for (var i4 = 0; i4 < this.columns.length; i4++) { - var opt = document.createElement("option"); - opt.value = i4.toString(); - opt.innerHTML = this.columns[i4].name + this.columns[i4].table; - select.appendChild(opt); - } - const select2 = containerEl.createEl("select"); - for (var i4 = 0; i4 < this.columns.length; i4++) { - var opt = document.createElement("option"); - opt.value = i4.toString(); - opt.innerHTML = this.columns[i4].name + this.columns[i4].table; - select2.appendChild(opt); - } - let changeButtonText = i18n_default.buttons.merge; - const changeButton = contentEl.createEl("button", { - text: changeButtonText - }); - const cancelButton = contentEl.createEl("button", { - text: i18n_default.buttons.cancel - }); - cancelButton.style.cssText = "float: right;"; - cancelButton.addEventListener("click", () => { - myModal.close(); - }); - const onClickAction = async () => { - this.mergeColumn( - this.columns[parseInt(select.value)], - this.columns[parseInt(select2.value)] - ); - myModal.close(); - }; - changeButton.addEventListener("click", onClickAction); - } - onClose() { - let { contentEl } = this; - contentEl.empty(); - } + onClick: (e4) => !props2.multi && showMenu() + }, i18n_default.labels.select)) : props2.editMode == -1 ? /* @__PURE__ */ Cn.createElement("div", { + className: "mk-cell-option-item mk-cell-empty" + }, /* @__PURE__ */ Cn.createElement("div", null, i18n_default.menu.none)) : /* @__PURE__ */ Cn.createElement(Cn.Fragment, null), editable && props2.multi ? /* @__PURE__ */ Cn.createElement("div", { + onClick: (e4) => editable && showMenu(), + className: "mk-cell-option-new mk-icon-small", + dangerouslySetInnerHTML: { __html: uiIconSet["mk-ui-plus"] } + }) : /* @__PURE__ */ Cn.createElement(Cn.Fragment, null)); }; -// src/components/ui/modals/saveViewModal.ts -var import_obsidian21 = require("obsidian"); -var SaveViewModal = class extends import_obsidian21.Modal { - constructor(schema, saveSchema, action) { - super(app); - this.schema = schema; - this.saveSchema = saveSchema; - this.action = action; - } - onOpen() { - let { contentEl } = this; - let myModal = this; - let headerText; - if (this.action == "new view") - headerText = i18n_default.labels.saveView; - if (this.action == "new table") - headerText = i18n_default.labels.saveTable; - if (this.action == "rename view") - headerText = i18n_default.labels.renameView; - if (this.action == "rename table") - headerText = i18n_default.labels.renameTable; - const headerEl = contentEl.createEl("div", { text: headerText }); - headerEl.addClass("modal-title"); - const inputEl = contentEl.createEl("input"); - inputEl.style.cssText = "width: 100%; height: 2.5em; margin-bottom: 15px;"; - inputEl.focus(); - let changeButtonText; - if (this.action == "new view") - changeButtonText = i18n_default.buttons.saveView; - if (this.action == "new table") - changeButtonText = i18n_default.buttons.saveTable; - if (this.action == "rename view") - changeButtonText = i18n_default.buttons.renameView; - if (this.action == "rename table") - changeButtonText = i18n_default.buttons.renameTable; - const changeButton = contentEl.createEl("button", { - text: changeButtonText - }); - const cancelButton = contentEl.createEl("button", { - text: i18n_default.buttons.cancel - }); - cancelButton.style.cssText = "float: right;"; - cancelButton.addEventListener("click", () => { - myModal.close(); - }); - const onClickAction = async () => { - let newName = inputEl.value; - if (this.action == "new view" || this.action == "new table") { - this.saveSchema({ ...this.schema, id: newName, name: newName }); - } else { - this.saveSchema({ ...this.schema, name: newName }); - } - myModal.close(); +// src/components/SpaceView/Contexts/DataTypeView/ContextCell.tsx +var ContextCell = (props2) => { + var _a2, _b2, _c2; + const stringValueToLink = (strings) => strings.map((f4) => { + return { + label: parseLinkDisplayString(f4), + path: parseLinkString(f4), + ref: false }; - changeButton.addEventListener("click", onClickAction); - inputEl.addEventListener("keydown", (e4) => { - if (e4.key === "Enter") { - e4.preventDefault(); - onClickAction(); - } - }); - } - onClose() { - let { contentEl } = this; - contentEl.empty(); - } -}; - -// src/components/ContextView/FilterBar/FilterBar.tsx -var import_obsidian22 = require("obsidian"); - -// src/components/ContextView/FilterBar/SearchBar.tsx -var SearchBar = (props2) => { - const clearSearch = () => { - props2.setSearchString(""); - }; - return /* @__PURE__ */ Cn.createElement("div", { - className: "mk-view-search" - }, /* @__PURE__ */ Cn.createElement("button", { - dangerouslySetInnerHTML: { __html: uiIconSet["mk-ui-search"] } - }), /* @__PURE__ */ Cn.createElement(Cn.Fragment, null, /* @__PURE__ */ Cn.createElement("input", { - onChange: (e4) => props2.setSearchString(e4.target.value), - placeholder: i18n_default.labels.searchPlaceholder, - className: "mk-search-bar" - }), /* @__PURE__ */ Cn.createElement("button", { - dangerouslySetInnerHTML: { __html: uiIconSet["mk-ui-clear"] }, - onClick: () => clearSearch() - }))); -}; - -// src/components/ContextView/FilterBar/FilterBar.tsx -var FilterBar = (props2) => { - const ctxRef = _2(null); - const { - tables, - data, - setDBSchema, - loadContextFields, - cols, - deleteSchema, - saveSchema, - saveDB: saveDB2, - saveContextDB, - setSchema, - setSearchString, - predicate, - tagContexts, - savePredicate, - hideColumn, - saveColumn, - sortColumn, - delColumn, - schema, - dbSchema, - contextInfo, - contextTable, - tableData - } = q2(MDBContext); - const filteredCols = cols.filter((f4) => f4.hidden != "true"); - const saveViewType = (type) => { - saveSchema({ - ...schema, - type - }); - }; - const views = tables.filter((f4) => f4.type != "db" && f4.def == (dbSchema == null ? void 0 : dbSchema.id)); - const selectView = (_dbschema, value) => { - setDBSchema(_dbschema); - value && setSchema(tables.find((f4) => f4.id == value)); - }; - const openView = (e4, view) => { - const dbSchema2 = tables.find((f4) => f4.type == "db" && f4.id == view.def); - if (dbSchema2) { - selectView(dbSchema2, view.id); - return; - } - return; - }; - const showViewMenu = (e4, _dbschema) => { - const views2 = tables.filter((f4) => f4.type != "db" && f4.def == _dbschema.id); - const offset = e4.target.getBoundingClientRect(); - showSelectMenu( - { x: offset.left, y: offset.top + 30 }, - { - multi: false, - editable: false, - value: tagContexts, - options: views2.map((m5) => ({ name: m5.name, value: m5.id })), - saveOptions: (_9, value) => selectView(_dbschema, value[0]), - placeholder: i18n_default.labels.viewItemSelectPlaceholder, - searchable: false, - showAll: true - } + }); + const initialValue = stringValueToLink( + props2.multi ? (_a2 = parseMultiString(props2.initialValue)) != null ? _a2 : [] : [props2.initialValue] + ); + const [propValues, setPropValues] = h2( + (_c2 = (_b2 = props2.plugin.index.contextsIndex.get(props2.space)) == null ? void 0 : _b2.spaceMap[props2.spaceField]) == null ? void 0 : _c2[props2.path] + ); + p2(() => { + var _a3, _b3; + setPropValues( + (_b3 = (_a3 = props2.plugin.index.contextsIndex.get(props2.space)) == null ? void 0 : _a3.spaceMap[props2.spaceField]) == null ? void 0 : _b3[props2.path] ); - }; - const clearFilters = () => { - savePredicate({ - ...predicate, - filters: [], - sort: [] - }); - }; - const clearHiddenCols = () => { - savePredicate({ - ...predicate, - colsHidden: [] - }); - }; - const removeFilter = (filter) => { - const newFilters = [ - ...predicate.filters.filter((f4) => f4.field != filter.field) - ]; - savePredicate({ - ...predicate, - filters: newFilters - }); - }; - const viewContextMenu = (e4, _schema) => { - const fileMenu = new import_obsidian22.Menu(); - fileMenu.addSeparator(); - fileMenu.addItem((menuItem) => { - menuItem.setTitle("Copy Embed Link"); - menuItem.onClick(() => { - navigator.clipboard.writeText( - contextEmbedStringFromContext(contextInfo, _schema.id) - ); - }); - }); - fileMenu.addItem((menuItem) => { - menuItem.setTitle("Rename View"); - menuItem.onClick(() => { - let vaultChangeModal = new SaveViewModal( - _schema, - (s5) => saveSchema(s5), - "rename view" - ); - vaultChangeModal.open(); - }); - }); - fileMenu.addItem((menuItem) => { - menuItem.setTitle("Delete View"); - menuItem.onClick(() => { - deleteSchema(_schema); - }); - }); - if (isMouseEvent(e4)) { - fileMenu.showAtPosition({ x: e4.pageX, y: e4.pageY }); - } else { - fileMenu.showAtPosition({ - x: e4.nativeEvent.locationX, - y: e4.nativeEvent.locationY - }); - } - }; - const showFilterMenu = (e4) => { - const menu = new import_obsidian22.Menu(); - menu.addItem((item) => { - item.setTitle(i18n_default.menu.tableView); - item.setIcon("table-2"); - item.onClick(() => { - saveViewType("table"); - }); - }); - menu.addItem((item) => { - item.setTitle(i18n_default.menu.cardView); - item.setIcon("layout-grid"); - item.onClick(() => { - saveViewType("card"); - }); - }); - menu.addItem((item) => { - item.setTitle(i18n_default.menu.listView); - item.setIcon("layout-list"); - item.onClick(() => { - saveViewType("list"); - }); - }); - if (dbSchema == null ? void 0 : dbSchema.primary) { - menu.addItem((item) => { - item.setTitle(i18n_default.menu.flowView); - item.setIcon("infinity"); - item.onClick(() => { - saveViewType("flow"); - }); - }); - } - menu.addSeparator(); - menu.addItem((item) => { - item.setTitle(i18n_default.menu.groupBy); - item.setIcon("columns"); - item.onClick(() => { - showGroupByMenu(e4); - }); - }); - menu.addItem((item) => { - item.setTitle(i18n_default.menu.sortBy); - item.setIcon("sort-desc"); - item.onClick(() => { - showSortMenu(e4); - }); - }); - menu.addSeparator(); - menu.addItem((item) => { - item.setTitle(i18n_default.menu.newFilter); - item.setIcon("filter"); - item.onClick(() => { - showAddFilterMenu(e4); - }); - }); - menu.addItem((item) => { - item.setTitle(i18n_default.menu.clearFilters); - item.setIcon("x-square"); - item.onClick(() => { - clearFilters(); - }); - }); - menu.addSeparator(); - menu.addItem((item) => { - item.setTitle(i18n_default.menu.unhideFields); - item.setIcon("eye"); - item.onClick(() => { - clearHiddenCols(); - }); - }); - const offset = e4.target.getBoundingClientRect(); - menu.showAtPosition({ x: offset.left, y: offset.top + 30 }); - }; - const addSort = (_9, sort) => { - var _a2; - const field = sort[0]; - const fieldType = (_a2 = filteredCols.find((f4) => f4.name + f4.table == field)) == null ? void 0 : _a2.type; - if (fieldType) { - const type = defaultPredicateFnForType(fieldType, sortFnTypes); - const newSort = { - field, - fn: type - }; - savePredicate({ - ...predicate, - sort: [ - ...predicate.sort.filter((s5) => s5.field != newSort.field), - newSort - ] - }); + }, [props2.space, props2.spaceField]); + const options = stringValueToLink([ + ...props2.plugin.index.spacesMap.getInverse(props2.space) + ]).map((f4) => ({ + name: f4.label, + value: f4.path + })); + const [value, setValue] = h2(initialValue); + const allValues = F2( + () => [ + ...value, + ...(propValues != null ? propValues : []).map((f4) => ({ + label: parseLinkDisplayString(f4), + path: parseLinkString(f4), + ref: true + })) + ], + [value, propValues] + ); + const removeValue = (v3) => { + if (v3.ref) { + const newPropValues = propValues.filter((f4) => f4 != v3.path); + setPropValues(newPropValues); + updateContextValue( + props2.plugin, + props2.plugin.index.spacesIndex.get(props2.space).space, + v3.path, + props2.spaceField, + props2.path, + deletePropertyMultiValue + ); + } else { + const newValues = value.filter((f4) => f4.path != v3.path); + setValue(newValues); + props2.saveValue(serializeMultiString(newValues.map((f4) => f4.path))); } }; - const saveGroupBy = (_9, groupBy2) => { - savePredicate({ - ...predicate, - groupBy: groupBy2 - }); - }; - const removeSort = (sort) => { - const newSort = [...predicate.sort.filter((f4) => f4.field != sort.field)]; - savePredicate({ - ...predicate, - sort: newSort - }); + p2(() => { + var _a3; + setValue( + stringValueToLink( + props2.multi ? (_a3 = parseMultiString(props2.initialValue)) != null ? _a3 : [] : [props2.initialValue] + ) + ); + }, [props2.initialValue]); + const saveOptions = (_options, _value) => { + insertContextItems(props2.plugin, _value, props2.space); + if (!props2.multi) { + setValue( + _value.map((f4) => ({ + path: f4, + label: fileNameToString(folderPathToString(f4)), + ref: false + })) + ); + props2.saveValue(serializeMultiString(_value)); + } else { + const newValue = _value[0]; + if (newValue) { + const newValues = uniq([...value.map((f4) => f4.path), newValue]); + setValue( + newValues.map((f4) => ({ + label: fileNameToString(folderPathToString(f4)), + path: f4, + ref: false + })) + ); + props2.saveValue(serializeMultiString(newValues)); + } + } }; - const addFilter = (_9, filter) => { - var _a2; - const field = filter[0]; - const fieldType = (_a2 = filteredCols.find((f4) => f4.name + f4.table == field)) == null ? void 0 : _a2.type; - if (fieldType) { - const type = defaultPredicateFnForType(fieldType, filterFnTypes); - const newFilter = fieldType == "boolean" ? { - field, - fn: type, - value: "true" - } : { - field, - fn: type, - value: "" - }; - savePredicate({ - ...predicate, - filters: [ - ...predicate.filters.filter((s5) => s5.field != newFilter.field), - newFilter - ] - }); + const openLink = async (o3) => { + const file = getAbstractFileAtPath(props2.plugin, o3.path); + if (file) { + openAFile(file, props2.plugin, false); } }; - const changeSortMenu = (e4, sort) => { - var _a2; - const offset = e4.target.getBoundingClientRect(); - const saveSort = (_9, newType) => { - const type = newType[0]; - const newSort = { - ...sort, - fn: type - }; - savePredicate({ - ...predicate, - sort: [ - ...predicate.sort.filter((s5) => s5.field != newSort.field), - newSort - ] - }); + const menuProps = () => { + const _options = !props2.multi ? [{ name: i18n_default.menu.none, value: "" }, ...options] : options; + return { + plugin: props2.plugin, + multi: false, + editable: true, + value: allValues.map((f4) => f4.path), + options: _options, + saveOptions, + placeholder: i18n_default.labels.contextItemSelectPlaceholder, + searchable: true, + showAll: true, + onHide: () => props2.setEditMode(null) }; - const fieldType = (_a2 = filteredCols.find( - (f4) => f4.name + f4.table == sort.field - )) == null ? void 0 : _a2.type; - const sortsForType = predicateFnsForType(fieldType, sortFnTypes); - showSelectMenu( - { x: offset.left, y: offset.top + 30 }, - { - multi: false, - editable: false, - value: [], - options: sortsForType.map((f4) => ({ - name: sortFnTypes[f4].label, - value: f4 - })), - saveOptions: saveSort, - placeholder: i18n_default.labels.sortItemSelectPlaceholder, - searchable: false, - showAll: true - } - ); }; - const showColsMenu = (e4) => { - let vaultChangeModal = new ContextEditorModal( - props2.plugin, - contextInfo, - schema == null ? void 0 : schema.id + return /* @__PURE__ */ Cn.createElement(OptionCellBase, { + baseClass: "mk-cell-context", + menuProps, + openItem: openLink, + getLabelString: (o3) => o3.label, + value: allValues, + multi: props2.multi, + editMode: props2.editMode, + removeValue + }); +}; + +// src/utils/date.ts +var formatDate = (plugin, date, dateFormat) => { + let dateString; + try { + dateString = format( + date, + (dateFormat == null ? void 0 : dateFormat.length) > 0 ? dateFormat : plugin.settings.defaultDateFormat ); - vaultChangeModal.open(); + } catch (e4) { + dateString = "Date Format Invalid"; + } + return dateString; +}; + +// src/components/SpaceView/Contexts/DataTypeView/DateCell.tsx +var DateCell = (props2) => { + const [value, setValue] = h2(props2.initialValue); + p2(() => { + setValue(props2.initialValue); + }, [props2.initialValue]); + const date = F2(() => { + const dateTime = Date.parse(value); + return dateTime > 0 ? new Date(dateTime + new Date().getTimezoneOffset() * 60 * 1e3) : null; + }, [value]); + const saveValue = (date2) => { + const newValue = formatDate(props2.plugin, date2, "yyyy-MM-dd"); + props2.saveValue(newValue); + setValue(newValue); + props2.setEditMode(null); }; - const saveField = (field, oldField) => { - if (field.name.length > 0) { - if (field.name != oldField.name || field.type != oldField.type || field.value != oldField.value || field.attrs != oldField.attrs) { - const saveResult = saveColumn(field, oldField); + const menuRef = _2(null); + const ref2 = _2(null); + p2(() => { + if (props2.editMode == 2 /* EditModeActive */) { + if (ref2.current) { + showPicker(); + ref2.current.focus(); } } - }; - const showMenu = (e4, field) => { - const offset = e4.target.getBoundingClientRect(); - const options = optionValuesForColumn( - field.name, - field.table == "" ? tableData : contextTable[field.table] - ); - showPropertyMenu( - props2.plugin, - { x: offset.left, y: offset.top + 30 }, - true, - options, - field, - cols, - contextInfo.contextPath, - (newField) => saveField(newField, field), - (newField, val) => { - }, - hideColumn, - delColumn, - sortColumn, - predicate.colsHidden.includes(field.name + field.table) - ); - }; - const changeFilterMenu = (e4, filter) => { - var _a2; - const offset = e4.target.getBoundingClientRect(); - const saveFilter = (_9, newType) => { - const type = newType[0]; - const newFilter = { - ...filter, - fn: type - }; - savePredicate({ - ...predicate, - filters: [ - ...predicate.filters.filter((s5) => s5.field != newFilter.field), - newFilter - ] - }); - }; - const fieldType = (_a2 = filteredCols.find( - (f4) => f4.name + f4.table == filter.field - )) == null ? void 0 : _a2.type; - const filtersForType = predicateFnsForType(fieldType, filterFnTypes); - showSelectMenu( - { x: offset.left, y: offset.top + 30 }, - { - multi: false, - editable: false, - value: [], - options: filtersForType.map((f4) => ({ - name: filterFnLabels[f4], - value: f4 - })), - saveOptions: saveFilter, - placeholder: i18n_default.labels.filterItemSelectPlaceholder, - searchable: false, - showAll: true + }, [props2.editMode]); + const showPicker = T2( + (e4) => { + if (props2.editMode <= 0) { + return; } - ); + const offset2 = e4 ? e4.target.getBoundingClientRect() : ref2.current.getBoundingClientRect(); + menuRef.current = showDatePickerMenu( + { x: offset2.left - 4, y: offset2.bottom - 4 }, + date, + saveValue + ); + }, + [date] + ); + const onKeyDown = (e4) => { + e4.stopPropagation(); + if (e4.key == "Enter" || e4.key == "Escape") { + e4.target.blur(); + saveValue(date); + menuRef.current.hide(); + } }; - const showAddFilterMenu = (e4) => { - const offset = e4.target.getBoundingClientRect(); - showSelectMenu( - { x: offset.left, y: offset.top + 30 }, - { - multi: false, - editable: false, - value: [], - options: filteredCols.filter((f4) => predicateFnsForType(f4.type, filterFnTypes).length > 0).map((f4) => ({ - name: f4.name + f4.table, - value: f4.name + f4.table - })), - saveOptions: addFilter, - placeholder: i18n_default.labels.propertyItemSelectPlaceholder, - searchable: false, - showAll: true - } - ); + const format2 = F2( + () => { + var _a2; + return (_a2 = safelyParseJSON(props2.propertyValue)) == null ? void 0 : _a2.format; + }, + [props2.propertyValue] + ); + return /* @__PURE__ */ Cn.createElement("div", { + className: "mk-cell-date", + onClick: (e4) => !value && showPicker(e4) + }, props2.editMode == 2 ? /* @__PURE__ */ Cn.createElement("input", { + onClick: (e4) => e4.stopPropagation(), + className: "mk-cell-text", + ref: ref2, + type: "text", + value, + onChange: (e4) => setValue(e4.target.value), + onMouseDown: () => showPicker(), + onKeyDown + }) : /* @__PURE__ */ Cn.createElement("div", { + className: "mk-cell-date-value", + onClick: (e4) => showPicker(e4) + }, date ? formatDate(props2.plugin, date, (format2 == null ? void 0 : format2.length) > 0 ? format2 : null) : value)); +}; + +// src/components/SpaceView/Contexts/DataTypeView/FileCell.tsx +var import_obsidian28 = require("obsidian"); +var FileCell = (props2) => { + const fileOrCleanPath = (f4) => { + if (!f4) + return { + path: "" + }; + const fileCache = props2.plugin.index.filesIndex.get(f4); + return fileCache ? { path: f4, fileCache } : { path: f4 }; }; - const showSortMenu = (e4) => { - const offset = e4.target.getBoundingClientRect(); - showSelectMenu( - { x: offset.left, y: offset.top + 30 }, - { - multi: false, - editable: false, - value: [], - options: filteredCols.map((f4) => ({ - name: f4.name + f4.table, - value: f4.name + f4.table - })), - saveOptions: addSort, - placeholder: i18n_default.labels.sortItemSelectPlaceholder, - searchable: false, - showAll: true - } - ); + const value = F2( + () => { + var _a2; + return (props2.multi ? (_a2 = parseMultiString(props2.initialValue)) != null ? _a2 : [] : [props2.initialValue]).map((f4) => fileOrCleanPath(f4)); + }, + [props2.initialValue] + ); + const ref2 = _2(null); + const onKeyDown = (e4) => { + e4.stopPropagation(); + e4.key == "Enter" && e4.target.blur(); }; - const showGroupByMenu = (e4) => { - const offset = e4.target.getBoundingClientRect(); - showSelectMenu( - { x: offset.left, y: offset.top + 30 }, - { - multi: false, - editable: false, - value: [], - options: filteredCols.filter((f4) => f4.primary != "true").map((f4) => ({ - name: f4.name + f4.table, - value: f4.name + f4.table - })), - saveOptions: saveGroupBy, - placeholder: i18n_default.labels.propertyItemSelectPlaceholder, - searchable: false, - showAll: true - } - ); + const fileExists = (name) => { + if (!name) + return false; + return getAbstractFileAtPath(props2.plugin, name) ? true : false; }; - const showAddMenu = (e4) => { - const fileMenu = new import_obsidian22.Menu(); - const folder = getAbstractFileAtPath( - app, - contextInfo.contextPath - ); - fileMenu.addItem((menuItem) => { - menuItem.setIcon("edit"); - menuItem.setTitle(i18n_default.buttons.createNote); - menuItem.onClick((ev) => { - newFileInFolder(props2.plugin, folder); - }); - }); - fileMenu.addItem((menuItem) => { - menuItem.setIcon("layout-dashboard"); - menuItem.setTitle(i18n_default.buttons.createCanvas); - menuItem.onClick((ev) => { - createNewCanvasFile(props2.plugin, folder, ""); - }); - }); - fileMenu.addItem((menuItem) => { - menuItem.setIcon("folder-plus"); - menuItem.setTitle(i18n_default.buttons.createFolder); - menuItem.onClick((ev) => { - let vaultChangeModal = new VaultChangeModal( - props2.plugin, - folder, - "create folder", - "/" - ); - vaultChangeModal.open(); - }); - }); - if (isMouseEvent(e4)) { - fileMenu.showAtPosition({ x: e4.pageX, y: e4.pageY }); + const onBlur = () => { + var _a2; + if (!ref2.current) + return; + if (fileExists((_a2 = ref2.current) == null ? void 0 : _a2.value)) { + new import_obsidian28.Notice(i18n_default.notice.fileExists); } else { - fileMenu.showAtPosition({ - x: e4.nativeEvent.locationX, - y: e4.nativeEvent.locationY - }); + props2.saveValue(ref2.current.value); + props2.setEditMode(null); } - return false; - }; - const showFMMenu2 = (e4) => { - const menu = new import_obsidian22.Menu(); - menu.addItem((menuItem) => { - menuItem.setIcon("log-in"); - menuItem.setTitle(i18n_default.menu.mergeProperties); - menuItem.onClick(() => { - showMergeColumnModal(); - }); - }); - const offset = e4.target.getBoundingClientRect(); - menu.showAtPosition({ x: offset.left, y: offset.top + 30 }); }; - const mergeColumn = (fromCol, toCol) => { - const fromTable = fromCol.table == "" ? tableData : contextTable[fromCol.table]; - if (toCol.table == "") { - saveDB2({ - ...tableData, - rows: tableData.rows.map((r3, i4) => { - const foundRow = fromTable.rows.find((f4) => f4.File == r3.File); - return foundRow ? { ...r3, [toCol.name]: foundRow[fromCol.name] } : r3; - }) - }); + const newFile = async (file) => { + const filePath = file.path.replace(/\//g, "").replace(/\./g, ""); + const path = `${props2.folder}/${filePath}.md`; + if (filePath.length == 0) { + return; + } + if (fileExists(path)) { + new import_obsidian28.Notice(i18n_default.notice.fileExists); } else { - saveContextDB( - { - ...contextTable[toCol.table], - rows: contextTable[toCol.table].rows.map((r3, i4) => { - const foundRow = fromTable.rows.find((f4) => f4.File == r3.File); - return foundRow ? { ...r3, [toCol.name]: foundRow[fromCol.name] } : r3; - }) - }, - toCol.table + await createNewMarkdownFile( + props2.plugin, + getAbstractFileAtPath(props2.plugin, props2.folder), + filePath ); } }; - const showMergeColumnModal = () => { + const deleteRow = () => { + props2.deleteRow(); + }; + p2(() => { + var _a2; + if (props2.editMode == 2) { + (_a2 = ref2 == null ? void 0 : ref2.current) == null ? void 0 : _a2.focus(); + } + }, [props2.editMode]); + return /* @__PURE__ */ Cn.createElement("div", { + className: "mk-cell-file" + }, value.map((v3, i4) => { + var _a2; + if (props2.editMode == 0) { + if (v3.fileCache) { + return /* @__PURE__ */ Cn.createElement("div", { + key: i4, + className: "mk-cell-file-title" + }, v3 && v3.fileCache ? v3.fileCache.name : "", ((_a2 = v3.fileCache.extension) == null ? void 0 : _a2.length) > 0 && v3.fileCache.extension != "md" && /* @__PURE__ */ Cn.createElement("span", { + className: "nav-file-tag" + }, v3.fileCache.extension), /* @__PURE__ */ Cn.createElement("button", { + "aria-label": i18n_default.buttons.toggleFlow, + className: "mk-cell-file-flow mk-inline-button", + dangerouslySetInnerHTML: { + __html: uiIconSet["mk-ui-flow-hover"] + }, + onClick: (e4) => { + if (props2.openFlow) { + props2.openFlow(e4); + e4.stopPropagation(); + } + } + })); + } else { + return /* @__PURE__ */ Cn.createElement("div", { + key: i4, + className: "mk-cell-file-title" + }, v3.path); + } + } + if (v3.fileCache) { + return /* @__PURE__ */ Cn.createElement(Cn.Fragment, null, /* @__PURE__ */ Cn.createElement("div", { + className: "mk-cell-file-item", + onContextMenu: (e4) => triggerFileMenu( + props2.plugin, + getAbstractFileAtPath(props2.plugin, v3.fileCache.path), + v3.fileCache.isFolder, + e4, + null + ) + }, /* @__PURE__ */ Cn.createElement(FileSticker, { + plugin: props2.plugin, + fileCache: v3.fileCache + }), /* @__PURE__ */ Cn.createElement("div", { + className: "mk-cell-file-name", + onClick: (e4) => openAFile( + getAbstractFileAtPath(props2.plugin, v3.fileCache.path), + props2.plugin, + e4.ctrlKey || e4.metaKey ? e4.altKey ? "split" : "tab" : false + ) + }, v3 && v3.fileCache ? v3.fileCache.name : ""))); + } + return /* @__PURE__ */ Cn.createElement(Cn.Fragment, null, /* @__PURE__ */ Cn.createElement("div", { + className: "mk-cell-file-item" + }, /* @__PURE__ */ Cn.createElement("div", { + className: "mk-file-icon" + }, /* @__PURE__ */ Cn.createElement("button", { + onClick: (e4) => newFile(v3), + dangerouslySetInnerHTML: { + __html: uiIconSet["mk-ui-new-file"] + } + })), props2.editMode > 1 ? /* @__PURE__ */ Cn.createElement("input", { + className: "mk-cell-file-name", + type: "text", + placeholder: "New Note", + ref: ref2, + value: v3.path, + onKeyDown, + onBlur + }) : /* @__PURE__ */ Cn.createElement("div", { + className: "mk-cell-file-name" + }, v3.path))); + })); +}; + +// src/components/SpaceView/Contexts/DataTypeView/FilePropertyCell.tsx +var humanFileSize = (bytes, si = false, dp = 1) => { + const thresh = si ? 1e3 : 1024; + if (Math.abs(bytes) < thresh) { + return bytes + " B"; + } + const units = si ? ["kB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"] : ["KiB", "MiB", "GiB", "TiB", "PiB", "EiB", "ZiB", "YiB"]; + let u4 = -1; + const r3 = 10 ** dp; + do { + bytes /= thresh; + ++u4; + } while (Math.round(Math.abs(bytes) * r3) / r3 >= thresh && u4 < units.length - 1); + return bytes.toFixed(dp) + " " + units[u4]; +}; +var LookUpCell = (props2) => { + const [cache, setCache] = h2(null); + const initialValue = props2.initialValue; + const { field, property } = parsePropString(props2.propertyValue); + if (property == "folder") { + return /* @__PURE__ */ Cn.createElement("div", { + className: "mk-cell-fileprop", + onClick: () => { + openTFolder( + getAbstractFileAtPath(props2.plugin, initialValue), + props2.plugin, + false + ); + } + }, folderPathToString(initialValue)); + } + if (property == "extension") { + return /* @__PURE__ */ Cn.createElement("div", { + className: "mk-cell-fileprop" + }, initialValue); + } else if (property == "ctime" || property == "mtime") { + const date = new Date(parseInt(initialValue)).getTime() ? new Date(parseInt(initialValue)) : null; + return /* @__PURE__ */ Cn.createElement("div", { + className: "mk-cell-fileprop" + }, date && formatDistance3(new Date(date), new Date(), { addSuffix: true })); + } else if (property == "size" || property == "File.size") { + return /* @__PURE__ */ Cn.createElement("div", { + className: "mk-cell-fileprop" + }, humanFileSize(parseInt(initialValue))); + } + return /* @__PURE__ */ Cn.createElement("div", { + className: "mk-cell-fileprop" + }, initialValue); +}; + +// src/components/SpaceView/Contexts/DataTypeView/NumberCell.tsx +var NumberCell = (props2) => { + const { initialValue, saveValue } = props2; + const [value, setValue] = Cn.useState(initialValue); + const ref2 = _2(null); + const onBlur = () => { + if (initialValue != value) + saveValue(value); + }; + const onKeyDown = (e4) => { + e4.stopPropagation(); + if (e4.key == "Enter") { + e4.target.blur(); + props2.setEditMode(null); + } + if (e4.key == "Escape") { + setValue(initialValue); + e4.target.blur(); + props2.setEditMode(null); + } + }; + Cn.useEffect(() => { + setValue(initialValue); + }, [initialValue]); + p2(() => { var _a2; - let vaultChangeModal = new MergeColumnModal( - [ - ...(_a2 = filteredCols == null ? void 0 : filteredCols.map((f4) => ({ ...f4, table: "" }))) != null ? _a2 : [], - ...tagContexts.reduce( - (p3, c4) => { - var _a3, _b2; - return [ - ...p3, - ...(_b2 = (_a3 = contextTable[c4]) == null ? void 0 : _a3.cols.filter( - (f4) => f4.name != FilePropertyName && f4.hidden != "true" && f4.type != "fileprop" - ).map((f4) => ({ ...f4, table: c4 }))) != null ? _b2 : [] - ]; - }, - [] - ) - ], - mergeColumn - ); - vaultChangeModal.open(); - }; - const showSaveViewModal = () => { - let vaultChangeModal = new SaveViewModal(schema, saveSchema, "new view"); - vaultChangeModal.open(); + if (props2.editMode == 2) { + (_a2 = ref2 == null ? void 0 : ref2.current) == null ? void 0 : _a2.focus(); + } + }, [props2.editMode]); + return props2.editMode > 1 ? /* @__PURE__ */ Cn.createElement("input", { + className: "mk-cell-text", + type: "number", + ref: ref2, + value, + onChange: (e4) => setValue(e4.target.value), + onKeyDown, + onBlur + }) : /* @__PURE__ */ Cn.createElement("div", { + className: "mk-cell-number" + }, value); +}; + +// src/components/SpaceView/Contexts/DataTypeView/TextCell.tsx +var TextCell = (props2) => { + const { initialValue, saveValue } = props2; + const [value, setValue] = Cn.useState(initialValue); + const ref2 = _2(null); + const onBlur = () => { + if (initialValue != value) + saveValue(value); }; - const editViewModal = () => { - let vaultChangeModal = new SaveViewModal(schema, saveSchema, "rename view"); - vaultChangeModal.open(); + const onKeyDown = (e4) => { + e4.stopPropagation(); + if (e4.key == "Enter") { + e4.target.blur(); + props2.setEditMode(null); + } + if (e4.key == "Escape") { + setValue(initialValue); + e4.target.blur(); + props2.setEditMode(null); + } }; - const selectFilterValue = (e4, filter) => { - var _a2, _b2, _c2; - switch (filterFnTypes[filter.fn].valueType) { - case "text": - case "number": - { - const menu = new import_obsidian22.Menu(); - menu.setUseNativeMenu(false); - const saveFilterValue = (value) => { - const newFilter = { - ...filter, - value - }; - savePredicate({ - ...predicate, - filters: [ - ...predicate.filters.filter((s5) => s5.field != newFilter.field), - newFilter - ] - }); - }; - menu.addItem((menuItem) => { - inputMenuItem( - menuItem, - filter.value, - (value) => saveFilterValue(value) - ); - menuItem.setIcon("type"); - }); - const offset = e4.target.getBoundingClientRect(); - menu.showAtPosition({ x: offset.left, y: offset.top + 30 }); - } - break; - case "date": { - const saveValue = (date2) => { - const newFilter = { - ...filter, - value: date2.valueOf().toString() - }; - savePredicate({ - ...predicate, - filters: [ - ...predicate.filters.filter((s5) => s5.field != newFilter.field), - newFilter - ] - }); - }; - const offset = e4.target.getBoundingClientRect(); - const date = new Date(filter.value); - showDatePickerMenu( - { x: offset.left, y: offset.top + 30 }, - date.getTime() ? date : null, - saveValue - ); - break; - } - case "list": - { - const col = cols.find((f4) => f4.name + f4.table == filter.field); - const saveOptions = (options, values) => { - const newFilter = { - ...filter, - value: serializeMultiString(values) - }; - savePredicate({ - ...predicate, - filters: [ - ...predicate.filters.filter((s5) => s5.field != newFilter.field), - newFilter - ] - }); - }; - if (col.type.startsWith("option")) { - const offset = e4.target.getBoundingClientRect(); - showSelectMenu( - { x: offset.left, y: offset.top + 30 }, - { - multi: true, - editable: false, - value: parseMultiString(filter.value), - options: parseMultiString(col.value).map((f4) => ({ - name: f4, - value: f4 - })), - saveOptions, - placeholder: i18n_default.labels.optionItemSelectPlaceholder, - searchable: true, - showAll: true - } - ); - } else if (col.type.startsWith("context")) { - const contextData = (_b2 = (_a2 = contextTable[col.table]) == null ? void 0 : _a2.rows) != null ? _b2 : []; - const offset = e4.target.getBoundingClientRect(); - showSelectMenu( - { x: offset.left, y: offset.top + 30 }, - { - multi: true, - editable: false, - value: parseMultiString(filter.value), - options: (_c2 = contextData.map((f4) => ({ - name: filePathToString(f4[FilePropertyName]), - value: f4[FilePropertyName] - }))) != null ? _c2 : [], - saveOptions, - placeholder: i18n_default.labels.optionItemSelectPlaceholder, - searchable: true, - showAll: true - } - ); - } - } - break; + Cn.useEffect(() => { + setValue(initialValue); + }, [initialValue]); + p2(() => { + var _a2; + if (props2.editMode == 2) { + (_a2 = ref2 == null ? void 0 : ref2.current) == null ? void 0 : _a2.focus(); + } + }, [props2.editMode]); + return props2.editMode > 1 ? /* @__PURE__ */ Cn.createElement("input", { + onClick: (e4) => e4.stopPropagation(), + className: "mk-cell-text", + ref: ref2, + type: "text", + value, + onChange: (e4) => setValue(e4.target.value), + onKeyDown, + onBlur + }) : /* @__PURE__ */ Cn.createElement("div", { + className: "mk-cell-text" + }, value); +}; + +// src/components/SpaceView/Contexts/TableView/TableView.tsx +var import_lodash11 = __toESM(require_lodash()); +var import_obsidian29 = require("obsidian"); + +// src/components/SpaceView/Contexts/DataTypeView/ImageCell.tsx +var ImageCell = (props2) => { + const { initialValue, saveValue } = props2; + const [value, setValue] = Cn.useState(initialValue); + const menuRef = _2(null); + p2(() => { + if (props2.editMode == 2 /* EditModeActive */) { + if (!menuRef.current) + showModal(); } + }, []); + const file = F2(() => { + const f4 = getAbstractFileAtPath(props2.plugin, value); + return f4 ? props2.plugin.app.vault.getResourcePath(f4) : value; + }, [value]); + Cn.useEffect(() => { + setValue(initialValue); + }, [initialValue]); + const showModal = () => { + const vaultChangeModal = new imageModal( + props2.plugin, + props2.plugin.app, + (image) => saveValue(image) + ); + vaultChangeModal.open(); + props2.setEditMode(null); }; - return /* @__PURE__ */ Cn.createElement(Cn.Fragment, null, /* @__PURE__ */ Cn.createElement("div", { - className: "mk-view-config" - }, /* @__PURE__ */ Cn.createElement("div", { - className: "mk-view-selector" + return /* @__PURE__ */ Cn.createElement("div", { + className: "mk-cell-image" + }, /* @__PURE__ */ Cn.createElement("img", { + src: file + }), props2.editMode > 0 ? /* @__PURE__ */ Cn.createElement("div", { + className: "mk-image-selector" }, /* @__PURE__ */ Cn.createElement("div", { - className: "mk-view-selector-spacer" - }), views.map((f4) => /* @__PURE__ */ Cn.createElement("div", { - className: `${(schema == null ? void 0 : schema.id) == f4.id ? "mk-is-active" : ""}`, - onContextMenu: (e4) => viewContextMenu(e4, f4) - }, /* @__PURE__ */ Cn.createElement("button", { - onClick: (e4) => openView(e4, f4) - }, f4.name))), /* @__PURE__ */ Cn.createElement("button", { - onClick: (e4) => showSaveViewModal() - }, "+")), /* @__PURE__ */ Cn.createElement("span", null), /* @__PURE__ */ Cn.createElement("div", { - className: "mk-view-options" - }, /* @__PURE__ */ Cn.createElement(SearchBar, { - setSearchString - }), /* @__PURE__ */ Cn.createElement("button", { - onClick: (e4) => showFilterMenu(e4), - dangerouslySetInnerHTML: { - __html: uiIconSet["mk-ui-view-options"] - } - }), (dbSchema == null ? void 0 : dbSchema.primary) && /* @__PURE__ */ Cn.createElement("button", { - onClick: (e4) => showColsMenu(e4), - dangerouslySetInnerHTML: { __html: uiIconSet["mk-ui-build"] } - }), contextInfo.type == "folder" && (dbSchema == null ? void 0 : dbSchema.id) == "files" && /* @__PURE__ */ Cn.createElement("button", { - className: "mk-button-new", - onClick: (e4) => showAddMenu(e4), - dangerouslySetInnerHTML: { __html: uiIconSet["mk-ui-plus"] } - }))), (predicate.filters.length > 0 || predicate.sort.length > 0 || predicate.groupBy.length > 0) && /* @__PURE__ */ Cn.createElement("div", { - className: "mk-filter-bar" - }, predicate.groupBy.length > 0 && /* @__PURE__ */ Cn.createElement("div", { - className: "mk-filter" - }, /* @__PURE__ */ Cn.createElement("span", null, "Group By"), /* @__PURE__ */ Cn.createElement("span", { - onClick: (e4) => showGroupByMenu(e4) - }, predicate.groupBy[0]), /* @__PURE__ */ Cn.createElement("div", { - onClick: () => saveGroupBy(null, []), - dangerouslySetInnerHTML: { __html: uiIconSet["mk-ui-close"] } - })), predicate.sort.map((f4) => /* @__PURE__ */ Cn.createElement("div", { - className: "mk-filter" - }, /* @__PURE__ */ Cn.createElement("span", null, f4.field), /* @__PURE__ */ Cn.createElement("span", { - onClick: (e4) => changeSortMenu(e4, f4) - }, sortFnTypes[f4.fn].label), /* @__PURE__ */ Cn.createElement("div", { - onClick: () => removeSort(f4), + onClick: showModal, + className: "mk-hover-button mk-icon-xsmall", + dangerouslySetInnerHTML: { __html: uiIconSet["mk-ui-edit"] } + }), (value == null ? void 0 : value.length) > 0 && /* @__PURE__ */ Cn.createElement("div", { + onClick: () => saveValue(""), + className: "mk-hover-button mk-icon-xsmall", dangerouslySetInnerHTML: { __html: uiIconSet["mk-ui-close"] } - }))), predicate.filters.map((f4) => { - var _a2; - return /* @__PURE__ */ Cn.createElement("div", { - className: "mk-filter" - }, /* @__PURE__ */ Cn.createElement("span", null, f4.field), /* @__PURE__ */ Cn.createElement("span", { - onClick: (e4) => changeFilterMenu(e4, f4) - }, filterFnLabels[f4.fn]), /* @__PURE__ */ Cn.createElement(FilterValueSpan, { - fieldType: (_a2 = cols.find((c4) => c4.name + c4.table == f4.field)) == null ? void 0 : _a2.type, - filter: f4, - selectFilterValue - }), /* @__PURE__ */ Cn.createElement("div", { - onClick: () => removeFilter(f4), - dangerouslySetInnerHTML: { __html: uiIconSet["mk-ui-close"] } - })); - }), /* @__PURE__ */ Cn.createElement("span", null))); -}; -var FilterValueSpan = (props2) => { - const { filter, selectFilterValue, fieldType } = props2; - const fnType = filterFnTypes[filter.fn]; - if (!fieldType || !fnType || fnType.valueType == "none") { - return /* @__PURE__ */ Cn.createElement(Cn.Fragment, null); - } else if (filter.value.length == 0) { - return /* @__PURE__ */ Cn.createElement("span", { - onClick: (e4) => selectFilterValue(e4, filter) - }, "Select"); - } else if (fieldType.startsWith("option") || fieldType.startsWith("context")) { - const options = parseMultiString(filter.value); - return /* @__PURE__ */ Cn.createElement("span", { - onClick: (e4) => selectFilterValue(e4, filter) - }, " ", options.map((f4) => /* @__PURE__ */ Cn.createElement("span", null, f4))); - } - return /* @__PURE__ */ Cn.createElement("span", { - onClick: (e4) => selectFilterValue(e4, filter) - }, filter.value); + })) : /* @__PURE__ */ Cn.createElement(Cn.Fragment, null)); }; -// src/components/Spaces/SpaceEditor.tsx -var SpaceEditor = k3( - (props2, ref) => { - var _a2, _b2; - const [def, setDef] = h2( - (_a2 = props2.def) != null ? _a2 : { - type: "smart", - folder: "", - filters: [{ type: "any", trueFalse: true, filters: [] }] - } +// src/components/SpaceView/Contexts/DataTypeView/LinkCell.tsx +var LinkCell = (props2) => { + var _a2; + const initialValue = (props2.multi ? (_a2 = parseMultiString(props2.initialValue)) != null ? _a2 : [] : [props2.initialValue]).filter((f4) => f4); + const stringValueToLink = (strings) => strings.map((f4) => { + return { + label: parseLinkDisplayString(f4), + value: parseLinkString(f4) + }; + }); + p2(() => { + var _a3; + setValue( + resolveLinks( + stringValueToLink( + props2.multi ? (_a3 = parseMultiString(props2.initialValue)) != null ? _a3 : [] : [props2.initialValue] + ) + ) ); - const selectFilterValue = (e4, filter, i4, k5) => { - var _a3; - const saveFilterValue = (value) => { - setDefFilterValue(value, i4, k5); - }; - switch ((_a3 = filterFnTypes[filter.fn]) == null ? void 0 : _a3.valueType) { - case "text": - case "number": - { - const menu = new import_obsidian23.Menu(); - menu.setUseNativeMenu(false); - menu.addItem((menuItem) => { - inputMenuItem( - menuItem, - filter.value, - (value) => saveFilterValue(value) - ); - menuItem.setIcon("type"); - }); - const offset = e4.target.getBoundingClientRect(); - menu.showAtPosition({ x: offset.left, y: offset.top + 30 }); - } - break; - case "date": { - const saveValue = (date2) => { - saveFilterValue(date2.valueOf().toString()); - }; - const offset = e4.target.getBoundingClientRect(); - const date = new Date(filter.value); - showDatePickerMenu( - { x: offset.left, y: offset.top + 30 }, - date.getTime() ? date : null, - saveValue - ); - break; - } - case "list": - { - const fieldType = filter.fType; - const saveOptions = (options2, values) => { - saveFilterValue(serializeMultiString(values)); - }; - let options = []; - if (fieldType.startsWith("option")) { - options = parseMultiString(filter.value).map((f4) => ({ - name: f4, - value: f4 - })); - } else if (fieldType.startsWith("tags")) { - options = loadTags(props2.plugin).map((f4) => ({ - value: f4, - name: f4 - })); - } else if (fieldType.startsWith("links")) { - options = getAllAbstractFilesInVault(props2.plugin, app).map( - (f4) => ({ - name: fileNameToString(f4.name), - value: f4.path, - description: f4.path - }) - ); - } - const offset = e4.target.getBoundingClientRect(); - showSelectMenu( - { x: offset.left, y: offset.top + 30 }, - { - multi: true, - editable: true, - value: parseMultiString(filter.value), - options, - saveOptions, - placeholder: i18n_default.labels.optionItemSelectPlaceholder, - searchable: false, - showAll: true - } - ); - } - break; + }, [props2.initialValue]); + const resolveLinks = (links) => links.map((f4) => ({ + value: f4.value, + label: filePathToString(f4.value), + file: getFileFromString( + props2.plugin, + f4.value, + getFolderPathFromString(props2.plugin, props2.file) + ) + })); + const ref2 = _2(null); + const [value, setValue] = h2( + resolveLinks(stringValueToLink(initialValue)) + ); + const removeValue = (v3) => { + const newValues = value.filter((f4) => f4.value != v3.value); + setValue(newValues); + props2.saveValue(serializeMultiString(newValues.map((f4) => f4.value))); + }; + const saveOptions = (_12, _value) => { + if (!props2.multi) { + setValue(resolveLinks(stringValueToLink(_value))); + props2.saveValue(serializeMultiString(_value)); + } else { + const newValue = _value[0]; + if (newValue) { + const newValues = uniq([...value.map((f4) => f4.value), newValue]); + setValue(resolveLinks(stringValueToLink(newValues))); + props2.saveValue(serializeMultiString(newValues)); } + } + }; + const menuProps = () => { + const options = getAllAbstractFilesInVault(props2.plugin).map((f4) => ({ + name: fileNameToString(f4.name), + value: f4.path, + description: f4.path + })); + const _options = !props2.multi ? [{ name: i18n_default.menu.none, value: "" }, ...options] : options; + return { + plugin: props2.plugin, + multi: false, + editable: true, + value: value.map((f4) => f4.value), + options: _options, + saveOptions, + placeholder: i18n_default.labels.linkItemSelectPlaceholder, + detail: true, + searchable: true }; - const addDefGroup = () => { - setDef({ - ...def, - filters: [ - ...def.filters, - { - type: "any", - trueFalse: true, - filters: [] - } - ] - }); - }; - const removeDefGroup = (groupIndex) => { - setDef({ - ...def, - filters: def.filters.filter((f4, i4) => i4 == groupIndex ? false : true) + }; + const openLink = async (o3) => { + if (o3.file) { + openTFile(o3.file, props2.plugin, false); + } else { + const file = await props2.plugin.files.newFile("/", o3.value, "md"); + openTFile(file, props2.plugin, false); + setValue(resolveLinks(value)); + } + }; + return /* @__PURE__ */ Cn.createElement(OptionCellBase, { + baseClass: "mk-cell-link", + menuProps, + getLabelString: (o3) => o3.label, + valueClass: (o3) => o3.file ? "mk-cell-link-item" : "mk-cell-link-unresolved", + openItem: openLink, + value, + multi: props2.multi, + editMode: props2.editMode, + removeValue + }); +}; + +// src/components/SpaceView/Contexts/DataTypeView/ObjectCell.tsx +var ObjectEditor = (props2) => { + const { value, type, saveValue, saveType } = props2; + const saveKey = (key2, newKey) => { + if (key2 != newKey) + saveValue({ + ...value, + [newKey]: value[key2], + [key2]: void 0 }); - }; - const typeForField = (type, field) => { - if (type == "frontmatter") { - return "text"; - } - if (type == "filemeta") { - return fileMeta[field].vType; - } - if (type == "fileprop") { - return fileProps[field].vType; - } - return "text"; - }; - const setDefFilter = (filter, groupIndex, filterIndex) => { - var _a3; - let type; - let field; - let fType; - const filterTuple = filter.split("."); - type = filterTuple[0]; - if (type == "frontmatter") { - fType = filterTuple[1]; - field = filterTuple[2]; - } else { - field = filterTuple[1]; - fType = typeForField(type, field); - } - if (def.filters.length == 0) { - setDef({ - ...def, - filters: [ - { - type: "any", - trueFalse: true, - filters: [ - { - type, - field, - fType, - fn: "", - value: "" - } - ] - } - ] - }); - return; - } - if (((_a3 = def.filters[groupIndex]) == null ? void 0 : _a3.filters.length) == 0) { - setDef({ - ...def, - filters: def.filters.map( - (f4, i4) => i4 == groupIndex ? { - ...f4, - filters: [ - { - type, - field, - fType, - fn: "", - value: "" - } - ] - } : f4 - ) + }; + const saveVal = (key2, val) => { + saveValue({ + ...value, + [key2]: val + }); + }; + const selectType = (e4, key2) => { + showSelectMenu(e4.target.getBoundingClientRect(), { + plugin: props2.plugin, + multi: false, + editable: false, + searchable: false, + saveOptions: (_12, values) => { + var _a2; + return saveType({ + ...type != null ? type : {}, + [key2]: { ...(_a2 = type == null ? void 0 : type[key2]) != null ? _a2 : {}, type: values[0] } }); - return; - } - setDef({ - ...def, - filters: def.filters.map( - (f4, i4) => i4 == groupIndex ? { - ...f4, - filters: f4.filters.map( - (g4, k5) => k5 == filterIndex ? { - ...g4, - type, - fType, - field - } : g4 - ) - } : f4 - ) - }); - }; - const setDefFilterFn = (fn2, groupIndex, filterIndex) => { - setDef({ - ...def, - filters: def.filters.map( - (f4, i4) => i4 == groupIndex ? { - ...f4, - filters: f4.filters.map( - (g4, k5) => k5 == filterIndex ? { - ...g4, - fn: fn2 - } : g4 - ) - } : f4 - ) - }); - }; - const setDefFilterValue = (value, groupIndex, filterIndex) => { - setDef({ - ...def, - filters: def.filters.map( - (f4, i4) => i4 == groupIndex ? { - ...f4, - filters: f4.filters.map( - (g4, k5) => k5 == filterIndex ? { - ...g4, - value - } : g4 - ) - } : f4 + }, + value: [], + showAll: true, + options: fieldTypes.map((f4, i4) => ({ + id: i4 + 1, + name: f4.label, + value: f4.type, + icon: "" + })) + }); + }; + return /* @__PURE__ */ Cn.createElement(Cn.Fragment, null, Object.keys(value).map((f4, i4) => { + var _a2, _b2, _c2, _d2, _e2, _f, _g, _h, _i, _j; + return /* @__PURE__ */ Cn.createElement(Cn.Fragment, null, /* @__PURE__ */ Cn.createElement("div", { + key: i4, + className: "mk-cell-object-row" + }, /* @__PURE__ */ Cn.createElement("div", { + className: "mk-file-context-field" + }, /* @__PURE__ */ Cn.createElement("div", { + className: "mk-file-context-field-icon", + onClick: (e4) => selectType(e4, f4), + dangerouslySetInnerHTML: { + __html: stickerFromString( + (_b2 = fieldTypeForType((_a2 = type == null ? void 0 : type[f4]) == null ? void 0 : _a2.type)) == null ? void 0 : _b2.icon, + props2.plugin ) - }); - }; - const addDefFilter = (groupIndex) => { - if (groupIndex == 0 && def.filters.length == 0) { - setDef({ - ...def, - filters: [ - { - type: "any", - trueFalse: true, - filters: [ - { - type: "", - fType: "", - field: "", - value: "", - fn: "" - } - ] - } - ] + } + }), /* @__PURE__ */ Cn.createElement("input", { + onClick: (e4) => e4.stopPropagation(), + className: "mk-file-context-field-key", + type: "text", + value: f4, + onBlur: (e4) => saveKey(f4, e4.target.value) + })), !((_c2 = type == null ? void 0 : type[f4]) == null ? void 0 : _c2.type) || !type[f4].type.startsWith("object") && /* @__PURE__ */ Cn.createElement("div", { + className: "mk-file-context-value" + }, /* @__PURE__ */ Cn.createElement(DataTypeView, { + initialValue: value[f4], + plugin: props2.plugin, + row: value, + column: { + name: f4, + schemaId: "", + table: "", + type: (_e2 = (_d2 = type == null ? void 0 : type[f4]) == null ? void 0 : _d2.type) != null ? _e2 : "text", + value: (_f = type == null ? void 0 : type[f4]) == null ? void 0 : _f.value + }, + editable: true, + updateValue: (value2) => saveVal(f4, value2), + updateFieldValue: (fieldValue, value2) => { + var _a3, _b3, _c3; + return saveType({ + ...type != null ? type : {}, + [f4]: { + ...(_a3 = type == null ? void 0 : type[f4]) != null ? _a3 : {}, + type: (_c3 = (_b3 = type == null ? void 0 : type[f4]) == null ? void 0 : _b3.type) != null ? _c3 : "text", + value: fieldValue + } }); - } else { - setDef({ - ...def, - filters: def.filters.map( - (f4, i4) => i4 == groupIndex ? { - ...f4, - filters: [ - ...f4.filters, - { - type: "", - fType: "", - field: "", - value: "", - fn: "" - } - ] - } : f4 - ) + } + }))), ((_g = type == null ? void 0 : type[f4]) == null ? void 0 : _g.type) && type[f4].type.startsWith("object") && /* @__PURE__ */ Cn.createElement("div", { + className: "mk-file-context-value" + }, /* @__PURE__ */ Cn.createElement(DataTypeView, { + initialValue: value[f4], + plugin: props2.plugin, + row: value, + column: { + name: f4, + schemaId: "", + table: "", + type: (_i = (_h = type == null ? void 0 : type[f4]) == null ? void 0 : _h.type) != null ? _i : "text", + value: (_j = type == null ? void 0 : type[f4]) == null ? void 0 : _j.value + }, + editable: true, + updateValue: (value2) => saveVal(f4, value2), + updateFieldValue: (fieldValue, value2) => { + var _a3, _b3, _c3; + return saveType({ + ...type != null ? type : {}, + [f4]: { + ...(_a3 = type == null ? void 0 : type[f4]) != null ? _a3 : {}, + type: (_c3 = (_b3 = type == null ? void 0 : type[f4]) == null ? void 0 : _b3.type) != null ? _c3 : "text", + value: fieldValue + } }); } - }; - const removeDefFilter = (filterIndex, groupIndex) => { - setDef({ - ...def, - filters: def.filters.map( - (f4, i4) => i4 == groupIndex ? { - ...f4, - filters: f4.filters.filter( - (g4, k5) => k5 == filterIndex ? false : true - ) - } : f4 + }))); + })); +}; +var ObjectCell = (props2) => { + var _a2; + const parsedValue = parseFieldValue(props2.propertyValue, "object"); + const type = parsedValue.type; + const { initialValue, plugin } = props2; + const [value, setValue] = Cn.useState( + props2.multi ? ensureArray(safelyParseJSON(initialValue)) : (_a2 = safelyParseJSON(initialValue)) != null ? _a2 : {} + ); + const saveType = (newType) => { + props2.savePropValue( + JSON.stringify({ ...parsedValue, type: newType }), + JSON.stringify(value) + ); + }; + const saveValue = (newValue) => { + props2.saveValue(JSON.stringify(newValue)); + }; + const saveMultiValue = (newValue, index) => { + props2.saveValue( + JSON.stringify( + value.map( + (f4, i4) => i4 == index ? newValue : f4 ) + ) + ); + }; + const newKey = (key2) => { + if (key2) + saveValue({ + ...value, + [key2]: "" }); - }; - const setGroupType = (groupIndex, type) => { - if (groupIndex == 0 && def.filters.length == 0) { - setDef({ - ...def, - filters: [ - { - type, - trueFalse: true, - filters: [] - } - ] - }); - } else { - setDef({ - ...def, - filters: def.filters.map( - (f4, i4) => i4 == groupIndex ? { - ...f4, - type - } : f4 - ) - }); + }; + Cn.useEffect(() => { + var _a3; + props2.multi ? ensureArray(safelyParseJSON(initialValue)) : (_a3 = safelyParseJSON(initialValue)) != null ? _a3 : {}; + }, [initialValue, props2.multi]); + return props2.editMode <= 1 /* EditModeView */ ? /* @__PURE__ */ Cn.createElement(Cn.Fragment, null) : /* @__PURE__ */ Cn.createElement("div", { + className: "mk-cell-object" + }, props2.multi ? value.map((f4, i4) => /* @__PURE__ */ Cn.createElement(ObjectEditor, { + saveType, + value: f4, + type, + plugin, + key: i4, + saveValue: (val) => saveMultiValue(val, i4) + })) : /* @__PURE__ */ Cn.createElement(ObjectEditor, { + plugin, + value, + type, + saveValue, + saveType + }), /* @__PURE__ */ Cn.createElement("div", { + className: "mk-file-context-field" + }, /* @__PURE__ */ Cn.createElement("input", { + onClick: (e4) => e4.stopPropagation(), + className: "mk-cell-text", + type: "text", + placeholder: "New Property", + value: "", + onBlur: (e4) => newKey(e4.target.value) + }))); +}; + +// src/components/SpaceView/Contexts/DataTypeView/SuperCell.tsx +var SuperCell = (props2) => { + const superProperty = F2(() => { + var _a2; + const parsedValue = parseFieldValue(props2.propertyValue, "super"); + const superPropertyName = parsedValue.dynamic ? (_a2 = props2.row) == null ? void 0 : _a2[parsedValue.field] : parsedValue.field; + const property = props2.plugin.index.superProperties.get(superPropertyName); + return property ? { + ...property, + value: JSON.stringify( + props2.plugin.index.valueForSuperproperty( + superPropertyName, + property + ) + ) + } : null; + }, [props2.propertyValue]); + return /* @__PURE__ */ Cn.createElement(Cn.Fragment, null, superProperty && /* @__PURE__ */ Cn.createElement(DataTypeView, { + ...props2, + updateFieldValue: (_12, f4) => props2.saveValue(f4), + updateValue: props2.saveValue, + column: { ...superProperty, table: "" }, + editable: true + })); +}; + +// src/components/SpaceView/Contexts/DataTypeView/TagCell.tsx +var TagCell = (props2) => { + var _a2; + const initialValue = ((_a2 = parseMultiString(props2.initialValue)) != null ? _a2 : []).filter( + (f4) => (f4 == null ? void 0 : f4.length) > 0 + ); + const [value, setValue] = h2(initialValue); + p2(() => { + var _a3; + setValue((_a3 = parseMultiString(props2.initialValue)) != null ? _a3 : []); + }, [props2.initialValue]); + const removeValue = (v3) => { + const newValues = value.filter((f4) => f4 != v3); + setValue(newValues); + props2.saveValue(serializeMultiString(newValues)); + }; + const saveOptions = (_options, _value) => { + if (!props2.multi) { + setValue(_value); + props2.saveValue(serializeMultiString(_value)); + } else { + const newValue = _value[0]; + if (newValue) { + const newValues = uniq([...value, newValue]); + setValue(newValues); + props2.saveValue(serializeMultiString(newValues)); } + } + }; + const menuProps = () => { + const options = loadTags(props2.plugin).map((f4) => ({ + name: f4, + value: f4 + })); + const _options = !props2.multi ? [{ name: i18n_default.menu.none, value: "" }, ...options] : options; + return { + plugin: props2.plugin, + multi: false, + editable: true, + value, + options: _options, + saveOptions, + placeholder: i18n_default.labels.tagItemSelectPlaceholder, + searchable: true, + showAll: true, + onHide: () => props2.setEditMode(null) }; - const selectGroupType = (e4, i4) => { - const offset = e4.target.getBoundingClientRect(); - const filters = ["any", "all"]; - showSelectMenu( - { x: offset.left, y: offset.top + 30 }, - { - multi: false, - editable: false, - value: [], - options: filters.map((f4) => ({ name: f4, value: f4 })), - saveOptions: (_9, value) => setGroupType(i4, value[0]), - searchable: false, - showAll: true - } + }; + return /* @__PURE__ */ Cn.createElement(OptionCellBase, { + baseClass: "mk-cell-tag", + menuProps, + value, + multi: props2.multi, + editMode: props2.editMode, + removeValue + }); +}; + +// src/components/SpaceView/Contexts/TableView/TableView.tsx +var TableView = (props2) => { + const { spaceInfo, readMode, spaceCache } = q2(SpaceContext); + const { + tableData, + dbSchema, + contextTable, + saveDB: saveDB2 + } = q2(ContextMDBContext); + const { + selectedRows, + selectRows, + sortedColumns: cols, + filteredData: data2, + predicate, + savePredicate, + updateFieldValue, + updateValue: updateValue2 + } = q2(ContextEditorContext); + const [activeId, setActiveId] = h2(null); + const [lastSelectedIndex, setLastSelectedIndex] = h2(null); + const [selectedColumn, setSelectedColumn] = h2(null); + const [currentEdit, setCurrentEdit] = h2(null); + const [overId, setOverId] = h2(null); + const [openFlows, setOpenFlows] = h2([]); + const [colsSize, setColsSize] = h2({}); + const ref2 = _2(null); + p2(() => { + setColsSize({ ...predicate.colsSize, "+": 30 }); + }, [predicate]); + p2(() => { + setCurrentEdit(null); + }, [selectedColumn, lastSelectedIndex]); + p2(() => { + if (currentEdit == null) { + ref2.current.focus(); + } + }, [currentEdit]); + const saveColsSize = (colSize) => { + const newColSize = colSize(colsSize); + setColsSize(newColSize); + debouncedSavePredicate(newColSize); + }; + const debouncedSavePredicate = T2( + (0, import_lodash11.debounce)( + (nextValue) => savePredicate({ + ...predicate, + colsSize: nextValue + }), + 1e3 + ), + [predicate] + ); + const newRow = (index, data3) => { + if ((dbSchema == null ? void 0 : dbSchema.id) == "files") { + newFileInSpace(props2.plugin, spaceCache, null, false, true); + } else { + saveDB2(createNewRow(tableData, { File: "", ...data3 != null ? data3 : {} }, index)); + } + }; + const deleteRow = (rowIndex) => { + const row = tableData.rows.find((f4, i4) => i4 == rowIndex); + if (getAbstractFileAtPath(props2.plugin, row.File)) { + deleteFile(props2.plugin, getAbstractFileAtPath(props2.plugin, row.File)); + } + if (row) { + saveDB2({ + ...tableData, + rows: tableData.rows.filter((f4, i4) => i4 != rowIndex) + }); + } + }; + const toggleFlow = (path) => { + setOpenFlows( + (f4) => f4.find((p3) => p3 == path) ? f4.filter((p3) => p3 != path) : uniq([...f4, path]) + ); + }; + const selectItem = (modifier, index) => { + if (modifier == 3) { + const file = getAbstractFileAtPath( + props2.plugin, + tableData.rows[parseInt(index)].File ); - }; - const selectFilter = (e4, i4, k5) => { - const offset = e4.target.getBoundingClientRect(); - const { type, field, fType } = def.filters[i4].filters[k5]; - const filters = predicateFnsForType(fType, filterFnTypes); - showSelectMenu( - { x: offset.left, y: offset.top + 30 }, - { - multi: false, - editable: true, - value: [], - options: filters.map((f4) => ({ name: filterFnLabels[f4], value: f4 })), - saveOptions: (_9, value) => setDefFilterFn(value[0], i4, k5), - placeholder: i18n_default.labels.contextItemSelectPlaceholder, - searchable: true, - showAll: true - } + if (file) + openAFile(file, props2.plugin, false); + return; + } + if (modifier == 2) { + selectedRows.some((f4) => f4 == index) ? selectRows( + null, + selectedRows.filter((f4) => f4 != index) + ) : selectRows(index, uniq([...selectedRows, index])); + } else if (modifier == 1) { + selectRows( + index, + uniq([ + ...selectedRows, + ...selectRange( + lastSelectedIndex, + index, + data2.map((f4) => f4._index) + ) + ]) + ); + } else { + selectRows(index, [index]); + } + setLastSelectedIndex(index); + }; + const onKeyDown = (e4) => { + const setCellValue = (value) => { + var _a2; + const columnTuple = selectedColumn.split("#"); + updateValue2( + columnTuple[0], + value, + (_a2 = columnTuple[1]) != null ? _a2 : "", + parseInt(lastSelectedIndex), + "" ); }; - const selectField = (e4, i4, k5) => { - const offset = e4.target.getBoundingClientRect(); - const allFiles = retrieveAllFiles( - props2.plugin.index.vaultDBCache, - props2.plugin.settings + const clearCell = () => { + setCellValue(""); + }; + const copyCell = () => { + navigator.clipboard.writeText( + tableData.rows[parseInt(lastSelectedIndex)][selectedColumn] ); - const frontmatter = allMetadataForFiles( - props2.plugin, - allFiles.map((f5) => getAbstractFileAtPath(app, f5.path)).filter((f5) => f5 instanceof import_obsidian23.TFile) + }; + const nextRow = () => { + const newIndex = selectNextIndex( + lastSelectedIndex, + data2.map((f4) => f4._index) ); - const fmTypes = guestimateTypes( - allFiles.map((f5) => f5.path), - props2.plugin, - false + selectRows(newIndex, [newIndex]); + setLastSelectedIndex(newIndex); + }; + const lastRow = () => { + const newIndex = selectPrevIndex( + lastSelectedIndex, + data2.map((f4) => f4._index) ); - const f4 = [ - ...Object.keys(fileMeta).map((f5) => ({ - name: fileMeta[f5].label, - value: "filemeta." + f5 - })), - ...Object.keys(fileProps).map((f5) => ({ - name: fileProps[f5].label, - value: "fileprop." + f5 - })), - ...frontmatter.map((f5) => ({ - name: f5.name, - value: "frontmatter." + fmTypes[f5.name] + "." + f5.name - })) - ]; - showSelectMenu( - { x: offset.left, y: offset.top + 30 }, - { - multi: false, - editable: false, - value: [], - options: f4, - saveOptions: (_9, value) => setDefFilter(value[0], i4, k5), - placeholder: i18n_default.labels.contextItemSelectPlaceholder, - searchable: true, - showAll: true + selectRows(newIndex, [newIndex]); + setLastSelectedIndex(newIndex); + }; + if (e4.key == "c" && e4.metaKey) { + copyCell(); + } + if (e4.key == "x" && e4.metaKey) { + copyCell(); + clearCell(); + } + if (e4.key == "v" && e4.metaKey) { + navigator.clipboard.readText().then((f4) => setCellValue(f4)); + } + if (e4.key == "Escape") { + selectRows(null, []); + setLastSelectedIndex(null); + } + if (e4.key == "Backspace" || e4.key == "Delete") { + clearCell(); + } + if (e4.key == "Enter") { + if (selectedColumn && lastSelectedIndex) { + if (e4.shiftKey) { + newRow(parseInt(lastSelectedIndex) + 1); + nextRow(); + } else { + setCurrentEdit([selectedColumn, lastSelectedIndex]); } + } + return; + } + if (e4.key == "ArrowDown") { + nextRow(); + e4.preventDefault(); + } + if (e4.key == "ArrowUp") { + lastRow(); + e4.preventDefault(); + } + if (e4.key == "ArrowLeft") { + const newIndex = selectPrevIndex( + selectedColumn, + columns.map((f4) => f4.accessorKey).filter((f4) => f4 != "+") ); - }; - p2(() => { - ref.current = def; - }, [def]); - return /* @__PURE__ */ Cn.createElement("div", { - className: "mk-space-settings" - }, def.type == "smart" ? /* @__PURE__ */ Cn.createElement("div", { - className: "mk-query" - }, def.filters.length == 0 ? /* @__PURE__ */ Cn.createElement(DefFilterGroup, { - selectGroupType, - group: null, - addDefGroup, - addDefFilter, - selectField, - i: 0, - removeDefGroup - }) : def.filters.map((f4, i4) => /* @__PURE__ */ Cn.createElement(DefFilterGroup, { - key: i4, - group: f4, - selectGroupType, - addDefGroup, - addDefFilter, - selectField, - i: i4, - removeDefGroup - }, f4.filters.map((filter, k5) => /* @__PURE__ */ Cn.createElement(DefFilter, { - key: k5, - filter, - i: i4, - k: k5, - selectField, - selectFilter, - selectFilterValue, - addDefFilter, - removeDefFilter - }))))) : /* @__PURE__ */ Cn.createElement("div", { - className: "setting-item mod-toggle" - }, /* @__PURE__ */ Cn.createElement("div", { - className: "setting-item-info" - }, /* @__PURE__ */ Cn.createElement("div", { - className: "setting-item-name" - }, "Sync to Folder"), /* @__PURE__ */ Cn.createElement("div", { - className: "setting-item-description" - }, "Select a folder to sync this space with all notes from a folder", /* @__PURE__ */ Cn.createElement("br", null), "Note: Existing items in the space will be removed from the space.")), /* @__PURE__ */ Cn.createElement("div", { - className: "setting-item-control" - }, /* @__PURE__ */ Cn.createElement("button", { - onClick: (e4) => { - const offset = e4.target.getBoundingClientRect(); - showSelectMenu( - { x: offset.left, y: offset.top + 30 }, - { - multi: false, - editable: false, - value: [], - options: [ - { name: "None", value: "" }, - ...getAllFoldersInVault(app).map((f4) => ({ - name: getFolderName(f4.path, app), - description: f4.path, - value: f4.path - })) - ], - saveOptions: (_9, values) => { - setDef((prev) => ({ ...prev, folder: values[0] })); + setSelectedColumn(newIndex); + } + if (e4.key == "ArrowRight") { + const newIndex = selectNextIndex( + selectedColumn, + columns.map((f4) => f4.accessorKey).filter((f4) => f4 != "+") + ); + setSelectedColumn(newIndex); + } + }; + const columns = F2( + () => { + var _a2; + return [ + ...(_a2 = cols.map((f4) => { + return { + header: f4.name, + accessorKey: f4.name + f4.table, + meta: { + table: f4.table, + editable: f4.name != FilePropertyName, + schemaId: dbSchema == null ? void 0 : dbSchema.id }, - searchable: true - } - ); - } - }, ((_b2 = def.folder) == null ? void 0 : _b2.length) > 0 ? getFolderName(def.folder, app) : "None")))); - } -); -SpaceEditor.displayName = "SpaceEditor"; -var SpaceEditor_default = SpaceEditor; -var DefFilter = (props2) => { - var _a2; - const { - filter, - selectField, - selectFilter, - selectFilterValue, - addDefFilter, - removeDefFilter, - i: i4, - k: k5 - } = props2; - return /* @__PURE__ */ Cn.createElement("div", { - className: "mk-query-filter" - }, /* @__PURE__ */ Cn.createElement("div", { - className: "mk-filter" - }, /* @__PURE__ */ Cn.createElement("span", { - onClick: (e4) => selectField(e4, i4, k5) - }, filter.field.length == 0 ? "Select" : filter.field), filter.field.length > 0 && /* @__PURE__ */ Cn.createElement("span", { - onClick: (e4) => selectFilter(e4, i4, k5) - }, !filterFnLabels[filter.fn] ? "Select" : filterFnLabels[filter.fn]), filter.field.length > 0 && filterFnLabels[filter.fn] && ((_a2 = filterFnTypes[filter.fn]) == null ? void 0 : _a2.valueType) != "none" && /* @__PURE__ */ Cn.createElement("span", null, /* @__PURE__ */ Cn.createElement(FilterValueSpan, { - fieldType: filter.fType, - filter, - selectFilterValue: (e4, h5) => selectFilterValue(e4, h5, i4, k5) - }))), /* @__PURE__ */ Cn.createElement("span", null), /* @__PURE__ */ Cn.createElement("button", { - "aria-label": i18n_default.buttons.addTag, - onClick: (e4) => addDefFilter(i4) - }, /* @__PURE__ */ Cn.createElement("div", { - className: "mk-icon-xsmall", - dangerouslySetInnerHTML: { __html: uiIconSet["mk-ui-plus"] } - })), /* @__PURE__ */ Cn.createElement("button", { - onClick: () => removeDefFilter(k5, i4) - }, /* @__PURE__ */ Cn.createElement("div", { - className: "mk-icon-xsmall", - dangerouslySetInnerHTML: { __html: uiIconSet["mk-ui-close"] } - }))); -}; -var DefFilterGroup = (props2) => { - var _a2; - const { - group, - selectGroupType, - addDefGroup, - addDefFilter, - selectField, - i: i4, - removeDefGroup - } = props2; - return /* @__PURE__ */ Cn.createElement("div", { - className: "mk-query-group" - }, /* @__PURE__ */ Cn.createElement("div", { - className: "mk-query-group-type" - }, /* @__PURE__ */ Cn.createElement("div", { - className: "mk-filter" - }, "Match", " ", /* @__PURE__ */ Cn.createElement("span", { - onClick: (e4) => selectGroupType(e4, i4) - }, (_a2 = group == null ? void 0 : group.type) != null ? _a2 : "any"), " ", "of the following"), /* @__PURE__ */ Cn.createElement("span", null), /* @__PURE__ */ Cn.createElement("button", { - "aria-label": i18n_default.buttons.addTag, - onClick: (e4) => addDefGroup() - }, /* @__PURE__ */ Cn.createElement("div", { - className: "mk-icon-xsmall", - dangerouslySetInnerHTML: { __html: uiIconSet["mk-ui-plus"] } - })), i4 > 0 ? /* @__PURE__ */ Cn.createElement("button", { - onClick: () => removeDefGroup(i4) - }, /* @__PURE__ */ Cn.createElement("div", { - className: "mk-icon-xsmall", - dangerouslySetInnerHTML: { __html: uiIconSet["mk-ui-close"] } - })) : /* @__PURE__ */ Cn.createElement(Cn.Fragment, null)), /* @__PURE__ */ Cn.createElement("div", { - className: "mk-filter-bar mk-query-filters" - }, !group || group.filters.length == 0 ? /* @__PURE__ */ Cn.createElement("div", { - className: "mk-query-filter" - }, /* @__PURE__ */ Cn.createElement("div", { - className: "mk-filter" - }, /* @__PURE__ */ Cn.createElement("span", { - onClick: (e4) => selectField(e4, i4, 0) - }, "Select")), /* @__PURE__ */ Cn.createElement("span", null), /* @__PURE__ */ Cn.createElement("button", { - "aria-label": i18n_default.buttons.addTag, - onClick: (e4) => addDefFilter(i4) - }, /* @__PURE__ */ Cn.createElement("div", { - className: "mk-icon-xsmall", - dangerouslySetInnerHTML: { __html: uiIconSet["mk-ui-plus"] } - }))) : /* @__PURE__ */ Cn.createElement(Cn.Fragment, null, props2.children))); -}; - -// src/components/ui/modals/editSpaceModal.tsx -var import_obsidian24 = require("obsidian"); -var EditSpaceModal = class extends import_obsidian24.Modal { - constructor(plugin, space, action) { - super(plugin.app); - this.space = space; - this.action = action; - this.plugin = plugin; - } - onOpen() { - const { contentEl } = this; - let headerText; - if (this.action === "rename") { - if (this.space.def.type == "smart") { - headerText = i18n_default.labels.renameSectionSmart; - } else { - headerText = i18n_default.labels.renameSection; + cell: ({ + getValue, + row: { index }, + column: { colId }, + cell, + table: table2 + }) => { + const initialValue = getValue(); + const rowIndex = parseInt( + data2[index]["_index" + f4.table] + ); + const tableIndex = parseInt(data2[index]["_index"]); + const saveValue = (value2) => { + var _a3; + setCurrentEdit(null); + if (initialValue != value2) + (_a3 = table2.options.meta) == null ? void 0 : _a3.updateData( + f4.name, + value2, + f4.table, + rowIndex + ); + }; + const saveFieldValue = (fieldValue, value2) => { + var _a3; + (_a3 = table2.options.meta) == null ? void 0 : _a3.updateFieldValue( + f4.name, + fieldValue, + value2, + f4.table, + rowIndex + ); + }; + const editMode = readMode ? -1 /* EditModeReadOnly */ : !cell.getIsGrouped() ? platformIsMobile() ? 3 /* EditModeAlways */ : currentEdit && currentEdit[0] == f4.name + f4.table && currentEdit[1] == tableIndex.toString() ? 2 /* EditModeActive */ : 1 /* EditModeView */ : -1 /* EditModeReadOnly */; + const cellProps = { + initialValue, + saveValue, + plugin: props2.plugin, + setEditMode: setCurrentEdit, + editMode, + propertyValue: f4.value + }; + const value = parseFieldValue(f4.value, f4.type); + const fieldType = fieldTypeForType(f4.type); + if (!fieldType) { + return /* @__PURE__ */ Cn.createElement(Cn.Fragment, null, initialValue); + } + if (fieldType.type == "file") { + return /* @__PURE__ */ Cn.createElement(FileCell, { + ...cellProps, + multi: fieldType.multiType == f4.type, + folder: spaceInfo.path, + isFolder: spaceInfo.uri.type == "folder", + openFlow: () => toggleFlow(initialValue), + deleteRow: () => deleteRow(index) + }); + } else if (fieldType.type == "boolean") { + return /* @__PURE__ */ Cn.createElement(BooleanCell, { + ...cellProps, + column: f4 + }); + } else if (fieldType.type == "option") { + return /* @__PURE__ */ Cn.createElement(OptionCell, { + ...cellProps, + options: f4.value, + multi: fieldType.multiType == f4.type, + saveOptions: saveFieldValue + }); + } else if (fieldType.type == "date") { + return /* @__PURE__ */ Cn.createElement(DateCell, { + ...cellProps + }); + } else if (fieldType.type == "context") { + return /* @__PURE__ */ Cn.createElement(ContextCell, { + ...cellProps, + multi: fieldType.multiType == f4.type, + space: value.space, + spaceField: value.field, + path: data2[index][FilePropertyName] + }); + } else if (fieldType.type == "fileprop") { + return /* @__PURE__ */ Cn.createElement(LookUpCell, { + ...cellProps, + file: data2[index][FilePropertyName] + }); + } else if (fieldType.type == "tag") { + return /* @__PURE__ */ Cn.createElement(TagCell, { + ...cellProps, + multi: fieldType.multiType == f4.type + }); + } else if (fieldType.type == "number") { + return /* @__PURE__ */ Cn.createElement(NumberCell, { + ...cellProps + }); + } else if (fieldType.type == "link") { + return /* @__PURE__ */ Cn.createElement(LinkCell, { + ...cellProps, + multi: fieldType.multiType == f4.type, + file: data2[index][FilePropertyName] + }); + } else if (fieldType.type == "image") { + return /* @__PURE__ */ Cn.createElement(ImageCell, { + ...cellProps + }); + } else if (fieldType.type == "object") { + return /* @__PURE__ */ Cn.createElement(ObjectCell, { + ...cellProps, + multi: fieldType.multiType == f4.type, + savePropValue: saveFieldValue + }); + } else if (fieldType.type == "super") { + return /* @__PURE__ */ Cn.createElement(SuperCell, { + ...cellProps, + row: data2[index] + }); + } else { + return /* @__PURE__ */ Cn.createElement(TextCell, { + ...cellProps + }); + } + } + }; + })) != null ? _a2 : [], + ...readMode ? [] : [ + { + header: "+", + meta: { schemaId: dbSchema == null ? void 0 : dbSchema.id }, + accessorKey: "+", + size: 20, + cell: () => /* @__PURE__ */ Cn.createElement(Cn.Fragment, null) + } + ] + ]; + }, + [cols, currentEdit, predicate, contextTable, toggleFlow, openFlows] + ); + const groupBy2 = F2( + () => { + var _a2; + return ((_a2 = predicate.groupBy) == null ? void 0 : _a2.length) > 0 && cols.find((f4) => f4.name + f4.table == predicate.groupBy[0]) ? predicate.groupBy : []; + }, + [predicate, cols] + ); + const table = useReactTable({ + data: data2, + columns, + columnResizeMode: "onChange", + state: { + columnVisibility: predicate.colsHidden.reduce( + (p3, c4) => ({ ...p3, [c4]: false }), + {} + ), + columnOrder: predicate.colsOrder, + columnSizing: { + ...columns.reduce((p3, c4) => ({ ...p3, [c4.accessorKey]: 150 }), {}), + ...colsSize + }, + grouping: groupBy2, + expanded: true + }, + onColumnSizingChange: saveColsSize, + getCoreRowModel: getCoreRowModel(), + getExpandedRowModel: getExpandedRowModel(), + getGroupedRowModel: getGroupedRowModel(), + meta: { + updateData: updateValue2, + updateFieldValue + } + }); + const sensors = useSensors( + useSensor(MouseSensor, { + activationConstraint: { + distance: 10 } - headerText = i18n_default.labels.renameSection; - } else if (this.action === "create") { - if (this.space.def.type == "smart") { - headerText = i18n_default.labels.createSectionSmart; - } else { - headerText = i18n_default.labels.createSection; + }), + useSensor(TouchSensor, { + activationConstraint: { + delay: 250, + tolerance: 5 } + }) + ); + const measuring = { + droppable: { + strategy: MeasuringStrategy.Always } - const headerEl = contentEl.createEl("div", { text: headerText }); - headerEl.addClass("modal-title"); - const inputEl = contentEl.createEl("input"); - inputEl.style.cssText = "width: 100%; height: 2.5em; margin-bottom: 15px;"; - if (this.action === "rename") { - inputEl.value = this.space.name; - } - inputEl.focus(); - const queryEl = contentEl.createDiv("mk-space-query"); - const root = createRoot(queryEl); - this.ref = Cn.createRef(); - root.render( - /* @__PURE__ */ Cn.createElement(SpaceEditor_default, { - plugin: this.plugin, - def: this.space.def, - ref: this.ref - }) - ); - let changeButtonText; - if (this.action === "rename") { - changeButtonText = i18n_default.buttons.saveSpace; - } else if (this.action === "create") { - changeButtonText = i18n_default.buttons.saveSpace; + }; + function handleDragStart(event) { + const { + active: { id: activeId2 } + } = event; + setActiveId(activeId2); + setOverId(overId); + document.body.style.setProperty("cursor", "grabbing"); + } + function handleDragOver({ over }) { + var _a2; + const overId2 = over == null ? void 0 : over.id; + if (overId2) { + setOverId((_a2 = over == null ? void 0 : over.id) != null ? _a2 : null); } - const changeButton = contentEl.createEl("button", { - text: changeButtonText + } + const saveFilter = (filter) => { + savePredicate({ + ...predicate, + filters: [ + ...predicate.filters.filter((s5) => s5.field != filter.field), + filter + ] }); - const cancelButton = contentEl.createEl("button", { - text: i18n_default.buttons.cancel + }; + const selectCell = (e4, index, column) => { + if (platformIsMobile() || column == "+") + return; + selectItem(0, data2[index]["_index"]); + setSelectedColumn(column); + if (e4.detail === 1) { + } else if (e4.detail === 2) { + setCurrentEdit([column, data2[index]["_index"]]); + } + }; + const showContextMenu = (e4, index) => { + e4.preventDefault(); + const menu = new import_obsidian29.Menu(); + menu.addItem((item) => { + item.setIcon("trash"); + item.setTitle(i18n_default.menu.deleteRow); + item.onClick(() => { + deleteRow(index); + }); }); - cancelButton.style.cssText = "float: right;"; - cancelButton.addEventListener("click", () => { - this.close(); + if (isMouseEvent(e4)) { + menu.showAtPosition({ x: e4.pageX, y: e4.pageY }); + } else { + menu.showAtPosition({ + x: e4.nativeEvent.locationX, + y: e4.nativeEvent.locationY + }); + } + }; + function handleDragEnd({ active, over }) { + resetState(); + savePredicate({ + ...predicate, + colsOrder: arrayMove( + predicate.colsOrder, + predicate.colsOrder.findIndex((f4) => f4 == activeId), + predicate.colsOrder.findIndex((f4) => f4 == overId) + ) }); - const onClickAction = async () => { - const newName = inputEl.value.replace(/\//g, ""); - if (newName.length == 0) { - new import_obsidian24.Notice(i18n_default.notice.newSpaceName); - return; + } + function handleDragCancel() { + resetState(); + } + function resetState() { + setOverId(null); + setActiveId(null); + document.body.style.setProperty("cursor", ""); + } + return /* @__PURE__ */ Cn.createElement(DndContext, { + sensors, + collisionDetection: closestCenter, + measuring, + onDragStart: handleDragStart, + onDragOver: handleDragOver, + onDragEnd: handleDragEnd, + onDragCancel: handleDragCancel + }, /* @__PURE__ */ Cn.createElement("div", { + className: "mk-table", + ref: ref2, + tabIndex: 1, + onKeyDown + }, /* @__PURE__ */ Cn.createElement("table", { + ...{} + }, /* @__PURE__ */ Cn.createElement("thead", null, table.getHeaderGroups().map((headerGroup) => /* @__PURE__ */ Cn.createElement("tr", { + key: headerGroup.id + }, /* @__PURE__ */ Cn.createElement("th", null), headerGroup.headers.map((header) => { + var _a2; + return /* @__PURE__ */ Cn.createElement("th", { + className: "mk-th", + key: header.id, + style: { + minWidth: header.column.getIsGrouped() ? "0px" : (_a2 = colsSize[header.column.columnDef.accessorKey]) != null ? _a2 : "150px" } - if (this.plugin.index.spacesIndex.has(newName) && newName != this.space.name) { - new import_obsidian24.Notice(i18n_default.notice.duplicateSpaceName); - return; + }, header.isPlaceholder ? null : header.column.columnDef.header != "+" ? header.column.getIsGrouped() ? /* @__PURE__ */ Cn.createElement(Cn.Fragment, null) : /* @__PURE__ */ Cn.createElement(ColumnHeader, { + plugin: props2.plugin, + editable: header.column.columnDef.meta.editable, + column: cols.find( + (f4) => f4.name == header.column.columnDef.header && f4.table == header.column.columnDef.meta.table + ) + }) : /* @__PURE__ */ Cn.createElement(ColumnHeader, { + plugin: props2.plugin, + isNew: true, + editable: true, + column: { + name: "", + schemaId: header.column.columnDef.meta.schemaId, + type: "text", + table: "" } - if (this.action === "rename") { - saveSpace(this.plugin, this.space.name, { - ...this.space, - def: this.ref.current, - name: newName - }); - } else if (this.action === "create") { - insertSpaceAtIndex( - this.plugin, - { name: newName, pinned: "home", def: this.ref.current }, - 0 - ); + }), /* @__PURE__ */ Cn.createElement("div", { + ...{ + onMouseDown: header.getResizeHandler(), + onTouchStart: header.getResizeHandler(), + className: `mk-resizer ${header.column.getIsResizing() ? "isResizing" : ""}` } - this.close(); - }; - changeButton.addEventListener("click", onClickAction); - inputEl.addEventListener("keydown", (e4) => { - if (e4.key === "Enter") - onClickAction(); - }); - } - onClose() { - const { contentEl } = this; - contentEl.empty(); + })); + })))), /* @__PURE__ */ Cn.createElement("tbody", null, table.getRowModel().rows.map((row) => /* @__PURE__ */ Cn.createElement(Cn.Fragment, null, /* @__PURE__ */ Cn.createElement("tr", { + className: (selectedRows == null ? void 0 : selectedRows.some( + (f4) => f4 == data2[row.index]["_index"] + )) && "mk-is-active", + onContextMenu: (e4) => { + const rowIndex = parseInt( + data2[row.index]["_index"] + ); + showContextMenu(e4, rowIndex); + }, + key: row.id + }, /* @__PURE__ */ Cn.createElement("td", null), row.getVisibleCells().map( + (cell, i4) => { + var _a2, _b2; + return cell.getIsGrouped() ? /* @__PURE__ */ Cn.createElement("td", { + key: i4, + className: "mk-td-group", + colSpan: cols.length + (readMode ? 0 : 1) + }, /* @__PURE__ */ Cn.createElement("div", { + ...{ + onClick: row.getToggleExpandedHandler(), + style: { + display: "flex", + alignItems: "center", + cursor: "normal" + } + } + }, flexRender( + cell.column.columnDef.cell, + cell.getContext() + ), " ", "(", row.subRows.length, ")")) : cell.getIsAggregated() ? flexRender( + (_a2 = cell.column.columnDef.aggregatedCell) != null ? _a2 : cell.column.columnDef.cell, + cell.getContext() + ) : /* @__PURE__ */ Cn.createElement("td", { + onClick: (e4) => selectCell( + e4, + cell.row.index, + cell.column.columnDef.accessorKey + ), + className: `${cell.column.columnDef.accessorKey == selectedColumn ? "mk-selected-cell " : ""} mk-td ${cell.getIsPlaceholder() ? "mk-td-empty" : ""}`, + key: cell.id, + style: { + minWidth: cell.getIsPlaceholder() ? "0px" : (_b2 = colsSize[cell.column.columnDef.accessorKey]) != null ? _b2 : "50px" + } + }, cell.getIsPlaceholder() ? null : flexRender( + cell.column.columnDef.cell, + cell.getContext() + )); + } + ))))), /* @__PURE__ */ Cn.createElement("tfoot", null, !readMode ? /* @__PURE__ */ Cn.createElement("tr", null, /* @__PURE__ */ Cn.createElement("th", { + className: "mk-row-new", + colSpan: cols.length + (readMode ? 1 : 2), + onClick: () => { + newRow(); + } + }, "+ New")) : /* @__PURE__ */ Cn.createElement(Cn.Fragment, null))), z3( + /* @__PURE__ */ Cn.createElement(DragOverlay, { + dropAnimation: null, + zIndex: 1600 + }, activeId ? /* @__PURE__ */ Cn.createElement(ColumnHeader, { + plugin: props2.plugin, + editable: false, + column: { + name: activeId, + schemaId: tableData.schema.id, + type: "text", + table: "" + } + }) : null), + document.body + ))); +}; + +// src/components/SpaceView/Contexts/DataTypeView/BooleanCell.tsx +var BooleanCell = (props2) => { + const { initialValue, saveValue } = props2; + const [value, setValue] = Cn.useState(initialValue == "true"); + const onChange = () => { + if (props2.editMode == -1 /* EditModeReadOnly */) { + return; + } + setValue(!value); + saveValue(!value ? "true" : "false"); + }; + p2(() => { + if (props2.editMode == 2 /* EditModeActive */) { + setValue(!value); + saveValue(!value ? "true" : "false"); + props2.setEditMode(null); + } + }, [props2.editMode]); + Cn.useEffect(() => { + setValue(initialValue == "true"); + }, [initialValue]); + if (props2.editMode < 1 /* EditModeView */) { + return /* @__PURE__ */ Cn.createElement("div", { + className: "mk-cell-boolean" + }, /* @__PURE__ */ Cn.createElement("input", { + type: "checkbox", + checked: value, + onChange + })); } + return /* @__PURE__ */ Cn.createElement("div", { + className: "mk-cell-boolean" + }, /* @__PURE__ */ Cn.createElement("input", { + type: "checkbox", + checked: value, + onChange + })); }; -// src/components/ui/menus/fileMenu.tsx -var import_obsidian25 = require("obsidian"); +// src/components/UI/menus/colorPickerMenu.tsx +var import_obsidian30 = require("obsidian"); // src/utils/color.ts var colors = [ @@ -38781,2039 +50893,2655 @@ var colors = [ ["Charcoal", "#4b6584"] ]; -// src/components/ui/menus/fileMenu.tsx -var triggerSectionAddMenu = (plugin, e4) => { - const fileMenu = new import_obsidian25.Menu(); - fileMenu.addItem((menuItem) => { - menuItem.setIcon("plus"); - menuItem.setTitle(i18n_default.buttons.createSection); - menuItem.onClick((ev) => { - let vaultChangeModal = new EditSpaceModal( - plugin, - { - name: "", - def: { - type: "focus", - folder: "", - filters: [] - } - }, - "create" - ); - vaultChangeModal.open(); - }); +// src/components/UI/menus/colorPickerMenu.tsx +var ColorPicker = (props2) => { + const [value, setValue] = h2(props2.color); + return /* @__PURE__ */ Cn.createElement("div", null, colors.map((c4, i4) => /* @__PURE__ */ Cn.createElement("div", { + key: i4, + onMouseDown: () => { + setValue(c4[1]); + props2.saveValue(c4[1]); + props2.hide(); + }, + className: "mk-color", + style: { background: c4[1] } + }))); +}; +var showColorPickerMenu = (point, value, setValue) => { + const menu = new import_obsidian30.Menu(); + menu.dom.toggleClass("mk-menu", true); + menu.setUseNativeMenu(false); + const frag = document.createDocumentFragment(); + const div = frag.createEl("div"); + div.addEventListener("click", (e4) => { + e4.stopImmediatePropagation(); }); - fileMenu.addItem((menuItem) => { - menuItem.setIcon("plus"); - menuItem.setTitle(i18n_default.buttons.createSectionSmart); - menuItem.onClick((ev) => { - let vaultChangeModal = new EditSpaceModal( - plugin, - { - name: "", - def: { - type: "smart", - folder: "", - filters: [] - } - }, - "create" - ); - vaultChangeModal.open(); - }); + div.addEventListener("mousedown", (e4) => { + e4.stopImmediatePropagation(); }); - if (isMouseEvent(e4)) { - fileMenu.showAtPosition({ x: e4.pageX, y: e4.pageY }); - } else { - fileMenu.showAtPosition({ - x: e4.nativeEvent.locationX, - y: e4.nativeEvent.locationY + div.addEventListener("mouseup", (e4) => { + e4.stopImmediatePropagation(); + }); + div.addEventListener("keydown", (e4) => { + }); + const root = createRoot(div); + root.render( + /* @__PURE__ */ Cn.createElement(ColorPicker, { + color: value, + saveValue: setValue, + hide: () => menu.hide() + }) + ); + menu.addItem((item) => { + item.setTitle(frag); + }); + const keys = [...menu.scope.keys]; + for (let i4 = 0; i4 < keys.length; i4++) { + if (keys[i4].key != "Escape") { + menu.scope.unregister(keys[i4]); + } + } + menu.showAtPosition(point); + return menu; +}; + +// src/components/SpaceView/Contexts/DataTypeView/ColorCell.tsx +var ColorCell = (props2) => { + const showMenu = (e4) => { + const handleChangeComplete = (color) => { + props2.saveValue(color); + }; + const offset2 = e4.target.getBoundingClientRect(); + showColorPickerMenu( + { x: offset2.left, y: offset2.top + 30 }, + props2.initialValue, + handleChangeComplete + ); + }; + return /* @__PURE__ */ Cn.createElement("div", null, /* @__PURE__ */ Cn.createElement("div", { + className: "mk-setter-color", + onClick: (e4) => showMenu(e4), + style: { + backgroundColor: props2.initialValue, + width: 30, + height: 30 + } + })); +}; + +// src/components/SpaceView/Contexts/DataTypeView/IconCell.tsx +var IconCell = (props2) => { + const value = F2( + () => { + var _a2; + return props2.multi ? (_a2 = parseMultiString(props2.initialValue)) != null ? _a2 : [] : [props2.initialValue]; + }, + [props2.initialValue] + ); + const ref2 = _2(null); + p2(() => { + var _a2; + if (props2.editMode == 2) { + (_a2 = ref2 == null ? void 0 : ref2.current) == null ? void 0 : _a2.focus(); + } + }, [props2.editMode]); + const triggerStickerMenu = (e4) => { + e4.stopPropagation(); + const vaultChangeModal = new stickerModal( + props2.plugin.app, + props2.plugin, + (emoji) => props2.saveValue(emoji) + ); + vaultChangeModal.open(); + }; + return /* @__PURE__ */ Cn.createElement("div", { + className: "mk-cell-icon" + }, value.map((v3, i4) => /* @__PURE__ */ Cn.createElement("button", { + key: i4, + "aria-label": i18n_default.buttons.changeIcon, + dangerouslySetInnerHTML: { + __html: stickerFromString(v3, props2.plugin) + }, + onClick: (e4) => triggerStickerMenu(e4) + }))); +}; + +// src/components/SpaceView/Contexts/DataTypeView/SpaceCell.tsx +var SpaceCell = (props2) => { + const path = F2( + () => uriByString(props2.plugin, props2.initialValue), + [props2.initialValue] + ); + const openLink = async () => { + if (path) { + openPath(props2.plugin, path); + } + }; + const menuRef = _2(null); + const ref2 = _2(null); + const menuProps = () => ({ + multi: false, + plugin: props2.plugin, + editable: true, + value: [props2.initialValue], + options: props2.plugin.index.allSpaces().map((f4) => ({ + name: f4.name, + value: f4.name, + description: f4.name + })), + saveOptions: (_12, value) => props2.saveValue(value[0]), + removeOption: () => { + }, + placeholder: i18n_default.labels.optionItemSelectPlaceholder, + searchable: true, + showAll: true, + onHide: () => props2.setEditMode(null) + }); + const showMenu = () => { + const offset2 = ref2.current.getBoundingClientRect(); + menuRef.current = showSelectMenu( + { x: offset2.left - 4, y: offset2.bottom - 4 }, + menuProps() + ); + }; + return /* @__PURE__ */ Cn.createElement("div", { + ref: ref2 + }, /* @__PURE__ */ Cn.createElement("div", { + className: "mk-cell-option-item" + }, /* @__PURE__ */ Cn.createElement("div", { + onClick: () => openLink() + }, path.path), /* @__PURE__ */ Cn.createElement("span", null), /* @__PURE__ */ Cn.createElement("div", { + onClick: (e4) => showMenu(), + className: "mk-cell-option-select mk-icon-xxsmall mk-icon-rotated", + dangerouslySetInnerHTML: { + __html: uiIconSet["mk-ui-collapse-sm"] + } + }))); +}; + +// src/components/SpaceView/Contexts/DataTypeView/DataTypeView.tsx +var DataTypeView = (props2) => { + const { initialValue, column, row } = props2; + const saveValue = (value2) => { + props2.updateValue(value2); + }; + const saveFieldValue = (fieldValue, value2) => { + props2.updateFieldValue(fieldValue, value2); + }; + const viewProps = { + initialValue, + saveValue, + editMode: props2.editable == true ? 3 : 0, + setEditMode: () => { + }, + plugin: props2.plugin, + propertyValue: column.value + }; + const fieldType = fieldTypeForType(column.type); + const value = parseFieldValue(column.value, column.type); + if (!fieldType) { + return /* @__PURE__ */ Cn.createElement(Cn.Fragment, null); + } + if (fieldType.type == "file") { + return /* @__PURE__ */ Cn.createElement(FileCell, { + isFolder: false, + ...viewProps, + multi: fieldType.multiType == column.type, + openFlow: props2.openFlow + }); + } else if (fieldType.type == "icon") { + return /* @__PURE__ */ Cn.createElement(IconCell, { + ...viewProps, + multi: fieldType.multiType == column.type + }); + } else if (fieldType.type == "boolean") { + return /* @__PURE__ */ Cn.createElement(BooleanCell, { + ...viewProps, + column + }); + } else if (fieldType.type == "option") { + return /* @__PURE__ */ Cn.createElement(OptionCell, { + ...viewProps, + options: column.value, + multi: fieldType.multiType == column.type, + saveOptions: saveFieldValue + }); + } else if (fieldType.type == "date") { + return /* @__PURE__ */ Cn.createElement(DateCell, { + ...viewProps }); - } - return false; -}; -var triggerSectionMenu = (plugin, space, spaces2, e4, activeFile2) => { - if (!space) - return; - const fileMenu = new import_obsidian25.Menu(); - const spaceName = space.name; - fileMenu.addItem((menuItem) => { - menuItem.setIcon("edit"); - menuItem.setTitle(i18n_default.buttons.createNote); - menuItem.onClick((ev) => { - newFileInSpace(plugin, space, activeFile2); + } else if (fieldType.type == "context") { + return /* @__PURE__ */ Cn.createElement(ContextCell, { + ...viewProps, + multi: fieldType.multiType == column.type, + space: value.space, + spaceField: value.field, + path: row == null ? void 0 : row["File"] }); - }); - fileMenu.addItem((menuItem) => { - menuItem.setIcon("layout-dashboard"); - menuItem.setTitle(i18n_default.buttons.createCanvas); - menuItem.onClick((ev) => { - newFileInSpace(plugin, space, activeFile2, true); + } else if (fieldType.type == "fileprop") { + return /* @__PURE__ */ Cn.createElement(LookUpCell, { + ...viewProps, + file: row == null ? void 0 : row["File"] }); - }); - fileMenu.addItem((menuItem) => { - menuItem.setIcon("folder-plus"); - menuItem.setTitle(i18n_default.buttons.createFolder); - menuItem.onClick((ev) => { - newFolderInSpace(plugin, space, activeFile2); + } else if (fieldType.type == "number") { + return /* @__PURE__ */ Cn.createElement(NumberCell, { + ...viewProps }); - }); - fileMenu.addSeparator(); - fileMenu.addItem((menuItem) => { - const pinned = (space == null ? void 0 : space.pinned) == "false" || (space == null ? void 0 : space.pinned) == "home"; - menuItem.setTitle(i18n_default.menu.homeSpace); - menuItem.setIcon("home"); - menuItem.setChecked(pinned); - menuItem.onClick((ev) => { - toggleSpacePin(plugin, spaceName, "home"); + } else if (fieldType.type == "link") { + return /* @__PURE__ */ Cn.createElement(LinkCell, { + ...viewProps, + multi: fieldType.multiType == column.type, + file: row == null ? void 0 : row["File"] }); - }); - fileMenu.addItem((menuItem) => { - const pinned = (space == null ? void 0 : space.pinned) == "true" || (space == null ? void 0 : space.pinned) == "pinned"; - menuItem.setTitle(i18n_default.menu.pinSpace); - menuItem.setIcon("pin"); - menuItem.setChecked(pinned); - menuItem.onClick((ev) => { - toggleSpacePin(plugin, spaceName, "pinned"); + } else if (fieldType.type == "tag") { + return /* @__PURE__ */ Cn.createElement(TagCell, { + ...viewProps, + multi: fieldType.multiType == column.type }); - }); - fileMenu.addItem((menuItem) => { - const space2 = spaces2.find((f4) => f4.name == spaceName); - const pinned = (space2 == null ? void 0 : space2.pinned) == "none"; - menuItem.setTitle(i18n_default.menu.unpinSpace); - menuItem.setIcon("pin-off"); - menuItem.onClick((ev) => { - toggleSpacePin(plugin, spaceName, "none"); + } else if (fieldType.type == "image") { + return /* @__PURE__ */ Cn.createElement(ImageCell, { + ...viewProps }); - }); - if (plugin.settings.spacesStickers) { - fileMenu.addSeparator(); - fileMenu.addItem((menuItem) => { - menuItem.setTitle(i18n_default.buttons.changeIcon); - menuItem.setIcon("lucide-sticker"); - menuItem.onClick((ev) => { - const vaultChangeModal = new stickerModal( - plugin.app, - plugin, - (emoji) => saveSpaceIcon(plugin, spaceName, emoji) - ); - vaultChangeModal.open(); - }); + } else if (fieldType.type == "object") { + return /* @__PURE__ */ Cn.createElement(ObjectCell, { + ...viewProps, + multi: fieldType.multiType == column.type, + savePropValue: saveFieldValue }); - fileMenu.addItem((menuItem) => { - menuItem.setTitle(i18n_default.buttons.removeIcon); - menuItem.setIcon("lucide-file-minus"); - menuItem.onClick((ev) => { - removeSpaceIcon(plugin, spaceName); - }); + } else if (fieldType.type == "color") { + return /* @__PURE__ */ Cn.createElement(ColorCell, { + ...viewProps + }); + } else if (fieldType.type == "space") { + return /* @__PURE__ */ Cn.createElement(SpaceCell, { + ...viewProps }); } - fileMenu.addSeparator(); - fileMenu.addItem((menuItem) => { - menuItem.setTitle(i18n_default.menu.collapseAll); - menuItem.setIcon("lucide-chevrons-down-up"); - menuItem.onClick((ev) => { - plugin.settings.expandedFolders = { - ...plugin.settings.expandedFolders, - [spaceName]: [] - }; - plugin.saveSettings(); + if (fieldType.type == "super") { + return /* @__PURE__ */ Cn.createElement(SuperCell, { + ...viewProps, + row }); + } + return /* @__PURE__ */ Cn.createElement(TextCell, { + ...viewProps }); - fileMenu.addSeparator(); - if (space.def.type == "focus") { - fileMenu.addItem((menuItem) => { - const sortOption = ["rank", true]; - menuItem.setIcon("arrow-up-down"); - menuItem.setTitle(i18n_default.menu.customSort); - menuItem.setChecked( - space.sort == JSON.stringify(sortOption) || space.sort == "" - ); - menuItem.onClick((ev) => { - updateSpaceSort(plugin, spaceName, sortOption); - }); - }); +}; + +// src/components/SpaceView/Contexts/CardsView/CardColumnView.tsx +var CardColumnView = k3( + ({ + id: id2, + children, + columns = 1, + handleProps, + horizontal, + hover, + onClick, + onRemove, + plugin, + field, + label, + file, + placeholder, + style, + scrollable, + shadow, + unstyled, + ...props2 + }, ref2) => { + const Component5 = "div"; + const { updateValue: updateValue2, updateFieldValue, contextTable } = q2(ContextEditorContext); + return /* @__PURE__ */ Cn.createElement(Component5, { + ...props2, + ref: ref2, + style: { + ...style, + "--columns": columns + }, + className: (0, import_classnames.default)( + "mk-list-group", + unstyled && "unstyled", + horizontal && "horizontal", + hover && "hover", + placeholder && "placeholder", + scrollable && "scrollable", + shadow && "shadow" + ), + onClick, + tabIndex: onClick ? 0 : void 0 + }, label != null && field ? /* @__PURE__ */ Cn.createElement("div", { + className: "mk-list-group-header" + }, /* @__PURE__ */ Cn.createElement(DataTypeView, { + initialValue: label, + plugin, + row: { File: file }, + column: field, + editable: false, + updateValue: (value) => updateValue2( + field.name, + value, + field.table, + parseInt(id2) * -1, + file + ), + updateFieldValue: (value, fieldValue) => updateFieldValue( + field.name, + fieldValue, + value, + field.table, + parseInt(id2) * -1, + file + ), + contextTable + }), /* @__PURE__ */ Cn.createElement("div", { + className: "Actions", + ...handleProps + })) : null, placeholder ? children : /* @__PURE__ */ Cn.createElement("ul", null, children)); } - fileMenu.addItem((menuItem) => { - menuItem.setTitle(i18n_default.menu.sortBy); - menuItem.setIcon("sort-desc"); - menuItem.onClick((ev) => { - const sortMenu = new import_obsidian25.Menu(); - sortMenu.addItem((menuItem2) => { - const sortOption = ["path", true]; - menuItem2.setTitle(i18n_default.menu.fileNameSortAlphaAsc); - menuItem2.setChecked(space.sort == JSON.stringify(sortOption)); - menuItem2.onClick((ev2) => { - updateSpaceSort(plugin, spaceName, sortOption); - }); - }); - sortMenu.addItem((menuItem2) => { - const sortOption = ["path", false]; - menuItem2.setTitle(i18n_default.menu.fileNameSortAlphaDesc); - menuItem2.setChecked(space.sort == JSON.stringify(sortOption)); - menuItem2.onClick((ev2) => { - updateSpaceSort(plugin, spaceName, sortOption); - }); - }); - sortMenu.addSeparator(); - sortMenu.addItem((menuItem2) => { - const sortOption = ["ctime", false]; - menuItem2.setTitle(i18n_default.menu.createdTimeSortAsc); - menuItem2.setChecked(space.sort == JSON.stringify(sortOption)); - menuItem2.onClick((ev2) => { - updateSpaceSort(plugin, spaceName, sortOption); - }); - }); - sortMenu.addItem((menuItem2) => { - const sortOption = ["ctime", true]; - menuItem2.setTitle(i18n_default.menu.createdTimeSortDesc); - menuItem2.setChecked(space.sort == JSON.stringify(sortOption)); - menuItem2.onClick((ev2) => { - updateSpaceSort(plugin, spaceName, sortOption); - }); - }); - const offset = e4.target.getBoundingClientRect(); - if (isMouseEvent(e4)) { - sortMenu.showAtPosition({ x: offset.left, y: offset.top + 30 }); - } else { - sortMenu.showAtPosition({ - x: e4.nativeEvent.locationX, - y: e4.nativeEvent.locationY - }); +); +CardColumnView.displayName = "CardColumnView"; +var CardColumnView_default = CardColumnView; + +// src/components/SpaceView/Contexts/CardsView/CardFrame.tsx +var CardFrame = (props2) => { + const mapFramePropsFromDBRow = (predicate, value) => value && predicate.frameProps ? applyFunctionToObject( + replaceKeysByValue(value, predicate.frameProps), + wrapQuotes + ) : {}; + const newProps = props2.value; + return /* @__PURE__ */ Cn.createElement(FrameRootView, { + root: props2.root, + plugin: props2.plugin, + props: newProps, + contexts: {} + }); +}; + +// src/components/SpaceView/Contexts/CardsView/CardView.tsx +var import_classnames2 = __toESM(require_classnames()); + +// src/components/SpaceView/Contexts/DataTypeView/PreviewCell.tsx +var PreviewCell = (props2) => { + var _a2; + const [vaultItem, setVaultItem] = h2(null); + const previewImage = F2(() => { + if (vaultItem == null ? void 0 : vaultItem.banner) + return vaultItem.banner; + if (props2.initialValue) + return props2.initialValue; + if (!props2.row || !props2.columns) + return null; + const imageCol = props2.columns.find((f4) => f4.type == "image"); + if (!imageCol) + return null; + return props2.row[imageCol.name + imageCol.table]; + }, [props2.row, props2.columns]); + const previewFile = F2(() => { + return getAbstractFileAtPath(props2.plugin, previewImage); + }, [previewImage]); + const loadIcon = () => { + setVaultItem(props2.plugin.index.filesIndex.get(props2.file)); + }; + p2(() => { + loadIcon(); + window.addEventListener(eventTypes.spacesChange, loadIcon); + return () => { + window.removeEventListener(eventTypes.spacesChange, loadIcon); + }; + }, [props2.file]); + return previewImage ? /* @__PURE__ */ Cn.createElement("div", { + className: "mk-file-preview", + style: { + backgroundSize: "cover", + backgroundPositionY: "50%", + backgroundImage: `url(${previewFile ? props2.plugin.app.vault.getResourcePath(previewFile) : previewImage})` + } + }) : /* @__PURE__ */ Cn.createElement("div", { + className: "mk-file-preview", + style: ((_a2 = vaultItem == null ? void 0 : vaultItem.color) == null ? void 0 : _a2.length) > 0 ? { + "--label-color": `${vaultItem.color}`, + "--icon-color": `#ffffff` + } : { + "--label-color": `var(--background-secondary-alt)`, + "--icon-color": `var(--text-muted)` + } + }, /* @__PURE__ */ Cn.createElement("div", { + className: "mk-file-icon", + dangerouslySetInnerHTML: (vaultItem == null ? void 0 : vaultItem.sticker) ? { __html: stickerFromString(vaultItem.sticker, props2.plugin) } : (vaultItem == null ? void 0 : vaultItem.isFolder) ? { __html: uiIconSet["mk-ui-folder"] } : { __html: uiIconSet["mk-ui-file"] } + })); +}; + +// src/components/SpaceView/Contexts/CardsView/CardView.tsx +var CardView = Cn.memo( + Cn.forwardRef( + ({ + color, + dragOverlay, + dragging, + disabled, + fadeIn, + handle, + height, + index, + listeners, + selected, + onSelect, + onRemove, + renderItem, + plugin, + leaf, + id: id2, + sorting, + style, + transition, + transform, + value, + cols, + wrapperStyle, + ...props2 + }, ref2) => { + const onClickHandler = (e4) => { + if (!onSelect) { + return; + } + if (e4.detail === 1) { + onSelect( + { + metaKey: e4.metaKey, + ctrlKey: e4.ctrlKey, + altKey: e4.altKey, + shiftKey: e4.shiftKey + }, + value["_index"] + ); + } else if (e4.detail === 2) { + console.log(e4); + onSelect( + { + doubleClick: true, + metaKey: e4.metaKey, + ctrlKey: e4.ctrlKey, + altKey: e4.altKey + }, + value["_index"] + ); + } + }; + const { updateValue: updateValue2, updateFieldValue, contextTable, predicate } = q2(ContextEditorContext); + p2(() => { + if (!dragOverlay) { + return; + } + document.body.style.cursor = "grabbing"; + return () => { + document.body.style.cursor = ""; + }; + }, [dragOverlay]); + const [openFlow, setOpenFlow] = h2(false); + return renderItem ? /* @__PURE__ */ Cn.createElement("li", { + className: (0, import_classnames2.default)( + fadeIn && "fadeIn", + sorting && "sorting", + dragOverlay && "dragOverlay", + selected && "mk-is-active" + ), + onClick: onClickHandler, + style: { + ...wrapperStyle, + transition, + "--translate-x": transform ? `${Math.round(transform.x)}px` : void 0, + "--translate-y": transform ? `${Math.round(transform.y)}px` : void 0, + "--scale-x": (transform == null ? void 0 : transform.scaleX) ? `${transform.scaleX}` : void 0, + "--scale-y": (transform == null ? void 0 : transform.scaleY) ? `${transform.scaleY}` : void 0, + "--index": index, + "--color": color + }, + ref: ref2 + }, renderItem({ + dragOverlay: Boolean(dragOverlay), + dragging: Boolean(dragging), + sorting: Boolean(sorting), + index, + fadeIn: Boolean(fadeIn), + listeners, + ref: ref2, + style, + transform, + transition, + value, + predicate + })) : /* @__PURE__ */ Cn.createElement("li", { + className: (0, import_classnames2.default)( + "mk-list-item", + fadeIn && "fadeIn", + sorting && "sorting", + dragOverlay && "dragOverlay", + selected && "mk-is-active" + ), + onClick: onClickHandler, + style: { + ...wrapperStyle, + transition, + "--translate-x": transform ? `${Math.round(transform.x)}px` : void 0, + "--translate-y": transform ? `${Math.round(transform.y)}px` : void 0, + "--scale-x": (transform == null ? void 0 : transform.scaleX) ? `${transform.scaleX}` : void 0, + "--scale-y": (transform == null ? void 0 : transform.scaleY) ? `${transform.scaleY}` : void 0, + "--index": index, + "--color": color + }, + ref: ref2 + }, value && /* @__PURE__ */ Cn.createElement(PreviewCell, { + row: value, + columns: cols, + plugin, + initialValue: "", + saveValue: () => { + }, + file: value[FilePropertyName] + }), /* @__PURE__ */ Cn.createElement("div", { + className: "mk-list-content" + }, /* @__PURE__ */ Cn.createElement("div", { + className: (0, import_classnames2.default)( + "mk-list-fields", + dragging && "dragging", + handle && "withHandle", + dragOverlay && "dragOverlay", + disabled && "disabled", + color && "color" + ), + style, + "data-cypress": "draggable-item", + ...listeners, + ...props2, + tabIndex: !handle ? 0 : void 0 + }, value && cols.map((f4) => { + var _a2; + return ((_a2 = value[f4.name + f4.table]) == null ? void 0 : _a2.length) > 0 ? /* @__PURE__ */ Cn.createElement(DataTypeView, { + openFlow: () => setOpenFlow((o3) => !o3), + plugin, + initialValue: value[f4.name + f4.table], + column: f4, + row: value, + editable: false, + updateValue: (v3) => updateValue2( + f4.name, + v3, + f4.table, + parseInt(id2), + value[FilePropertyName] + ), + updateFieldValue: (v3, fv) => updateFieldValue( + f4.name, + fv, + v3, + f4.table, + parseInt(id2), + value[FilePropertyName] + ), + contextTable + }) : /* @__PURE__ */ Cn.createElement(Cn.Fragment, null); + })), /* @__PURE__ */ Cn.createElement(FlowView, { + leaf, + plugin, + path: value.File, + load: openFlow + }))); + } + ) +); + +// src/components/SpaceView/Contexts/CardsView/CardsView.tsx +var animateLayoutChanges = (args) => args.isSorting || args.wasDragging ? defaultAnimateLayoutChanges(args) : true; +function DroppableContainer({ + children, + columns = 1, + disabled, + id: id2, + items, + style, + ...props2 +}) { + var _a2; + const { + active, + attributes, + isDragging, + listeners, + over, + setNodeRef, + transition, + transform + } = useSortable({ + id: id2, + data: { + type: "container" + }, + animateLayoutChanges + }); + const isOverContainer = over ? id2 === over.id && ((_a2 = active == null ? void 0 : active.data.current) == null ? void 0 : _a2.type) !== "container" || items.includes(over.id) : false; + return /* @__PURE__ */ Cn.createElement(CardColumnView_default, { + id: id2, + ref: disabled ? void 0 : setNodeRef, + style: { + ...style, + transition, + transform: CSS.Translate.toString(transform), + opacity: isDragging ? 0.5 : void 0 + }, + hover: isOverContainer, + handleProps: { + ...attributes, + ...listeners + }, + columns, + ...props2 + }, children); +} +var PLACEHOLDER_ID = "placeholder"; +var CardsView = ({ + adjustScale: adjustScale2 = false, + itemCount = 3, + cancelDrop, + columns, + handle = false, + items: initialItems, + containerStyle, + getItemStyles = () => ({}), + wrapperStyle = () => ({}), + minimal = false, + modifiers, + strategy = verticalListSortingStrategy, + vertical = false, + scrollable, + plugin +}) => { + var _a2, _b2; + const { tableData } = q2(ContextMDBContext); + const { + filteredData, + selectedRows, + schema, + selectRows, + sortedColumns: cols, + predicate, + updateValue: updateValue2, + contextTable, + saveContextDB + } = q2(ContextEditorContext); + const getFrameListItemsByPath = (ref2) => { + const path = uriByString(plugin, ref2); + const context = plugin.index.framesIndex.get(path.basePath); + return context == null ? void 0 : context.listitems[path.ref]; + }; + const frame = F2(() => { + return (predicate == null ? void 0 : predicate.frame) ? getFrameListItemsByPath(predicate.frame) : null; + }, [predicate]); + const frameRoot = F2(() => { + if (frame) { + return buildRootFromMDBFrame(plugin, frame); + } + return null; + }, [frame]); + const renderItem = frameRoot ? (props2) => /* @__PURE__ */ Cn.createElement(CardFrame, { + plugin, + root: frameRoot, + value: props2.value, + predicate: props2.predicate + }) : null; + const groupBy2 = ((_a2 = predicate.groupBy) == null ? void 0 : _a2.length) > 0 ? cols.find((f4) => f4.name + f4.table == predicate.groupBy[0]) : null; + const displayCols = (_b2 = cols == null ? void 0 : cols.filter( + (f4) => !(f4.name == (groupBy2 == null ? void 0 : groupBy2.name) && f4.table == groupBy2.table) + )) != null ? _b2 : []; + const viewType = predicate.view; + const items = F2(() => { + var _a3, _b3; + if (groupBy2) { + const options = uniq([ + "", + ...(_a3 = parseMultiString(groupBy2.value)) != null ? _a3 : [], + ...filteredData.reduce( + (p3, c4) => { + var _a4; + return [...p3, (_a4 = c4[groupBy2.name + groupBy2.table]) != null ? _a4 : ""]; + }, + [] + ) + ]); + return options.reduce( + (p3, c4) => { + return { + ...p3, + [c4]: filteredData.filter((r3) => r3[groupBy2.name + groupBy2.table] == c4).map((r3) => r3._index) + }; + }, + { "": [] } + ); + } + return { + "": (_b3 = filteredData == null ? void 0 : filteredData.map((r3) => r3._index)) != null ? _b3 : [] + }; + }, [filteredData, predicate]); + const containers = F2( + () => Object.keys(items).map((f4, i4) => "-" + i4.toString()), + [items] + ); + const [activeId, setActiveId] = h2(null); + const [overId, setOverId] = h2(null); + const recentlyMovedToNewContainer = _2(false); + const isSortingContainer = activeId ? containers.includes(activeId) : false; + const [lastSelectedIndex, setLastSelectedIndex] = h2(null); + const sensors = useSensors( + useSensor(MouseSensor, { + activationConstraint: { + distance: 10 } + }), + useSensor(TouchSensor, { + activationConstraint: { + delay: 250, + tolerance: 5 + } + }), + useSensor(KeyboardSensor, { + coordinateGetter: sortableKeyboardCoordinates + }) + ); + const findContainer = (id2) => { + if (id2.charAt(0) == "-") { + return id2; + } + return "-" + Object.keys(items).findIndex((key2) => items[key2].includes(id2)).toString(); + }; + const getIndex = (id2) => { + const container = findContainer(id2); + if (!container) { + return -1; + } + const index = items[Object.keys(items)[parseInt(container) * -1]].indexOf(id2); + return index; + }; + const resetState = () => { + setActiveId(null); + setOverId(null); + }; + const onDragCancel = () => { + resetState(); + }; + p2(() => { + requestAnimationFrame(() => { + recentlyMovedToNewContainer.current = false; }); - }); - fileMenu.addSeparator(); - fileMenu.addItem((menuItem) => { - menuItem.setTitle(i18n_default.menu.edit); - menuItem.setIcon("pencil"); - menuItem.onClick((ev) => { - let vaultChangeModal = new EditSpaceModal(plugin, space, "rename"); - vaultChangeModal.open(); - }); - }); - fileMenu.addItem((menuItem) => { - menuItem.setTitle(i18n_default.menu.deleteSpace); - menuItem.setIcon("trash"); - menuItem.onClick((ev) => { - removeSpace(plugin, space.name); - }); - }); - if (isMouseEvent(e4)) { - fileMenu.showAtPosition({ x: e4.pageX, y: e4.pageY }); - } else { - fileMenu.showAtPosition({ - x: e4.nativeEvent.locationX, - y: e4.nativeEvent.locationY - }); - } - return false; -}; -var triggerMultiFileMenu = (plugin, selectedFiles2, e4) => { - const files = selectedFiles2.map((s5) => s5.item.path); - const spaces2 = plugin.index.allSpaces(); - const spaceItems = retrieveSpaceItems(plugin, spaces2); - const fileMenu = new import_obsidian25.Menu(); - fileMenu.addSeparator(); - fileMenu.addItem((menuItem) => { - menuItem.setIcon("plus"); - menuItem.setTitle("Add to Space"); - menuItem.onClick((ev) => { - let vaultChangeModal = new AddToSpaceModal( + }, [items]); + const selectItem = (modifier, index) => { + if (platformIsMobile()) { + const file = getAbstractFileAtPath( plugin, - selectedFiles2.map((f4) => f4.path) + tableData.rows[parseInt(index)].File ); - vaultChangeModal.open(); - }); - }); - if (plugin.settings.spacesStickers) { - fileMenu.addSeparator(); - fileMenu.addItem((menuItem) => { - menuItem.setIcon("palette"); - disclosureMenuItem( - menuItem, - false, - false, - i18n_default.menu.changeColor, - "", - [ - { name: "None", value: "" }, - ...colors.map((f4) => ({ name: f4[0], value: f4[1] })) - ], - (_9, values) => { - saveFileColors(plugin, files, values[0]); - } + if (file) + openAFile(file, plugin, false); + return; + } + if (modifier.doubleClick) { + const file = getAbstractFileAtPath( + plugin, + tableData.rows[parseInt(index)].File ); - }); - fileMenu.addItem((menuItem) => { - menuItem.setTitle(i18n_default.buttons.changeIcon); - menuItem.setIcon("lucide-sticker"); - menuItem.onClick((ev) => { - const vaultChangeModal = new stickerModal( - plugin.app, + if (file) + openAFile( + file, plugin, - (emoji) => saveFileIcons(plugin, files, emoji) + modifier.ctrlKey || modifier.metaKey ? modifier.altKey ? "split" : "tab" : false ); - vaultChangeModal.open(); - }); - }); - fileMenu.addItem((menuItem) => { - menuItem.setTitle(i18n_default.buttons.removeIcon); - menuItem.setIcon("lucide-file-minus"); - menuItem.onClick((ev) => { - removeFileIcons(plugin, files); + return; + } else if (modifier.shiftKey) { + selectedRows.some((f4) => f4 == index) ? selectRows( + null, + selectedRows.filter((f4) => f4 != index) + ) : selectRows(index, uniq([...selectedRows, index])); + } else if (modifier.metaKey) { + selectRows( + index, + uniq([ + ...selectedRows, + ...selectRange( + lastSelectedIndex, + index, + filteredData.map((f4) => f4._index) + ) + ]) + ); + } else { + selectRows(index, [index]); + } + setLastSelectedIndex(index); + }; + const onKeyDown = (e4) => { + if (e4.key == "Escape") { + selectRows(null, []); + setLastSelectedIndex(null); + } + if (e4.key == "Enter") { + const file = getAbstractFileAtPath( + plugin, + tableData.rows[parseInt(lastSelectedIndex)].File + ); + if (file) + openAFile(file, plugin, false); + return; + } + if (e4.key == "ArrowDown") { + const newIndex = selectNextIndex( + lastSelectedIndex, + filteredData.map((f4) => f4._index) + ); + selectRows(newIndex, [newIndex]); + setLastSelectedIndex(newIndex); + } + if (e4.key == "ArrowUp") { + const newIndex = selectPrevIndex( + lastSelectedIndex, + filteredData.map((f4) => f4._index) + ); + selectRows(newIndex, [newIndex]); + setLastSelectedIndex(newIndex); + } + }; + return /* @__PURE__ */ Cn.createElement(DndContext, { + sensors, + collisionDetection: closestCenter, + measuring: { + droppable: { + strategy: MeasuringStrategy.Always + } + }, + onDragStart: ({ active }) => { + setActiveId(active.id); + }, + onDragOver: ({ active, over }) => { + const overId2 = over == null ? void 0 : over.id; + if (overId2) + setOverId(overId2); + }, + onDragEnd: ({ active, over }) => { + if (active.id in items && (over == null ? void 0 : over.id)) { + return; + } + const activeContainer = findContainer(active.id); + if (!activeContainer) { + resetState(); + return; + } + const overId2 = over == null ? void 0 : over.id; + if (!overId2) { + resetState(); + return; + } + if (overId2 === PLACEHOLDER_ID) { + return; + } + const overContainer = findContainer(overId2); + if (overContainer) { + const activeIndex = items[Object.keys(items)[parseInt(activeContainer) * -1]].indexOf(active.id); + const overIndex = items[Object.keys(items)[parseInt(overContainer) * -1]].indexOf(overId2); + if (activeContainer != overContainer) { + updateValue2( + groupBy2.name, + Object.keys(items)[parseInt(overContainer) * -1], + groupBy2.table, + groupBy2.table == "" ? parseInt(activeId) : parseInt( + filteredData.find((f4) => f4._index == activeId)["_index" + groupBy2.table] + ), + "" + ); + } + } + resetState(); + }, + cancelDrop, + onDragCancel, + modifiers + }, /* @__PURE__ */ Cn.createElement("div", { + className: (0, import_classnames3.default)( + viewType == "card" ? "mk-cards-container" : "mk-list-container", + viewType == "card" && containers.length == 1 && "mk-cards-grid" + ), + onKeyDown + }, /* @__PURE__ */ Cn.createElement("div", { + className: "mk-list-view" + }, /* @__PURE__ */ Cn.createElement(SortableContext, { + items: [...containers, PLACEHOLDER_ID], + strategy: vertical ? verticalListSortingStrategy : horizontalListSortingStrategy + }, containers.map((containerId) => /* @__PURE__ */ Cn.createElement(DroppableContainer, { + key: containerId, + id: containerId, + plugin, + label: minimal ? void 0 : `${Object.keys(items)[parseInt(containerId) * -1]}`, + field: groupBy2, + columns, + items: items[Object.keys(items)[parseInt(containerId) * -1]], + scrollable, + style: containerStyle, + unstyled: minimal + }, /* @__PURE__ */ Cn.createElement(SortableContext, { + items: items[Object.keys(items)[parseInt(containerId) * -1]], + strategy + }, items[Object.keys(items)[parseInt(containerId) * -1]].map( + (value, index) => { + return /* @__PURE__ */ Cn.createElement(SortableItem2, { + disabled: isSortingContainer, + key: value, + id: value, + plugin, + value: filteredData.find((f4) => f4._index == value), + cols: displayCols, + index, + handle, + style: getItemStyles, + wrapperStyle, + renderItem, + onSelect: selectItem, + selected: selectedRows == null ? void 0 : selectedRows.some((f4) => f4 == value), + containerId, + getIndex }); - }); + } + ))))))), z3( + /* @__PURE__ */ Cn.createElement(DragOverlay, { + adjustScale: adjustScale2 + }, activeId ? containers.includes(activeId) ? renderContainerDragOverlay(activeId) : renderSortableItemDragOverlay(activeId) : null), + document.body + )); + function renderSortableItemDragOverlay(id2) { + return /* @__PURE__ */ Cn.createElement("div", { + className: viewType == "card" ? "mk-cards-container" : "mk-list-container" + }, /* @__PURE__ */ Cn.createElement(CardView, { + plugin, + value: filteredData.find((f4) => f4._index == id2), + handle, + id: id2, + cols: displayCols, + style: getItemStyles({ + containerId: findContainer(id2), + overIndex: -1, + index: getIndex(id2), + value: id2, + isSorting: true, + isDragging: true, + isDragOverlay: true + }), + color: getColor(id2), + wrapperStyle: wrapperStyle({ index: 0 }), + renderItem, + dragOverlay: true + })); } - fileMenu.addSeparator(); - fileMenu.addItem((menuItem) => { - menuItem.setTitle(i18n_default.menu.deleteFiles); - menuItem.setIcon("trash"); - menuItem.onClick((ev) => { - deleteFiles(plugin, files); - }); + function renderContainerDragOverlay(containerId) { + return /* @__PURE__ */ Cn.createElement(CardColumnView_default, { + id: containerId, + plugin, + label: `Column ${containerId}`, + field: groupBy2, + columns, + style: { + height: "100%" + }, + shadow: true, + unstyled: false + }, items[Object.keys(items)[parseInt(containerId) * -1]].map( + (item, index) => /* @__PURE__ */ Cn.createElement(CardView, { + key: item, + id: item, + plugin, + value: filteredData.find((f4) => f4._index == item), + cols: displayCols, + handle, + style: getItemStyles({ + containerId, + overIndex: -1, + index: getIndex(item), + value: item, + isDragging: false, + isSorting: false, + isDragOverlay: false + }), + color: getColor(item), + selected: selectedRows.some((f4) => f4 == item), + onSelect: selectItem, + wrapperStyle: wrapperStyle({ index }), + renderItem + }) + )); + } + function getNextContainerId() { + const containeIds = Object.keys(items); + const lastContaineId = containeIds[containeIds.length - 1]; + return String.fromCharCode(lastContaineId.charCodeAt(0) + 1); + } +}; +function getColor(id2) { + switch (id2[0]) { + case "A": + return "#7193f1"; + case "B": + return "#ffda6c"; + case "C": + return "#00bcd4"; + case "D": + return "#ef769f"; + } + return void 0; +} +function SortableItem2({ + disabled, + id: id2, + plugin, + index, + handle, + renderItem, + style, + containerId, + onSelect, + selected, + getIndex, + cols, + value, + wrapperStyle +}) { + const { + setNodeRef, + listeners, + isDragging, + isSorting, + over, + overIndex, + transform, + transition + } = useSortable({ + id: id2 }); - fileMenu.addItem((menuItem) => { - menuItem.setIcon("go-to-file"); - menuItem.setTitle(i18n_default.menu.openFilePane); - menuItem.onClick((ev) => { - files.forEach( - (file) => openAFile(getAbstractFileAtPath(app, file), plugin, true) - ); - }); + const mounted = useMountStatus(); + const mountedWhileDragging = isDragging && !mounted; + return /* @__PURE__ */ Cn.createElement(CardView, { + ref: disabled ? void 0 : setNodeRef, + value, + plugin, + id: id2, + cols, + dragging: isDragging, + sorting: isSorting, + handle, + index, + wrapperStyle: wrapperStyle({ index }), + style: style({ + index, + value: id2, + isDragging, + isSorting, + overIndex: over ? getIndex(over.id) : overIndex, + containerId + }), + onSelect, + selected, + color: getColor(id2), + transition, + transform, + fadeIn: mountedWhileDragging, + listeners, + renderItem }); - if (!internalPluginLoaded("file-explorer", plugin.app)) { - fileMenu.addItem((menuItem) => { - menuItem.setTitle(i18n_default.menu.moveFile); - menuItem.setIcon("paper-plane"); - menuItem.onClick((ev) => { - let fileMoveSuggester = new MoveSuggestionModal(plugin.app, files); - fileMoveSuggester.open(); - }); - }); +} +function useMountStatus() { + const [isMounted, setIsMounted] = h2(false); + p2(() => { + const timeout = setTimeout(() => setIsMounted(true), 500); + return () => clearTimeout(timeout); + }, []); + return isMounted; +} + +// src/components/SpaceView/Contexts/FlowListView/FlowListView.tsx +var import_obsidian31 = require("obsidian"); +var FlowListView = (props2) => { + const { filteredData: data2 } = q2(ContextEditorContext); + const flowItems = F2(() => { + return data2.map((f4) => getAbstractFileAtPath(props2.plugin, f4.File)).filter((f4) => f4 instanceof import_obsidian31.TFile && f4.extension == "md"); + }, [data2]); + return /* @__PURE__ */ Cn.createElement("div", { + className: "mk-flow-container" + }, flowItems.map((f4, i4) => /* @__PURE__ */ Cn.createElement("div", { + key: i4 + }, /* @__PURE__ */ Cn.createElement("span", null, fileNameToString(f4.name)), /* @__PURE__ */ Cn.createElement(FlowView, { + leaf: props2.leaf, + plugin: props2.plugin, + path: f4.path, + load: true + })))); +}; + +// src/components/SpaceView/Contexts/ContextListView.tsx +var ContextListView = (props2) => { + const { predicate } = q2(ContextEditorContext); + const { dbSchema } = q2(ContextMDBContext); + const [error, resetError] = P2(); + if (error) + console.log(error); + return /* @__PURE__ */ Cn.createElement(Cn.Fragment, null, !props2.minMode && /* @__PURE__ */ Cn.createElement(FilterBar, { + plugin: props2.plugin + }), predicate ? predicate.view == "flow" ? /* @__PURE__ */ Cn.createElement(FlowListView, { + plugin: props2.plugin + }) : predicate.view == "table" || predicate.view == "db" ? /* @__PURE__ */ Cn.createElement(TableView, { + plugin: props2.plugin + }) : /* @__PURE__ */ Cn.createElement(CardsView, { + plugin: props2.plugin + }) : /* @__PURE__ */ Cn.createElement(Cn.Fragment, null), " "); +}; + +// src/components/SpaceView/Editor/EmbedView/EmbedContextViewComponent.tsx +var EmbedFrameView = (props2) => { + var _a2, _b2, _c2; + const getFileCache = (file) => { + if (!file || file.path == "/") + return null; + const cache = props2.plugin.index.filesIndex.get(file.path); + return cache; + }; + const [fileCache, setFileCache] = h2( + getFileCache(getAbstractFileAtPath(props2.plugin, props2.source)) + ); + const refreshFile = () => { + return; + }; + const cacheChanged = (evt) => { + if (evt.detail.type == "file" && evt.detail.name == props2.source) { + refreshFile(); + } + }; + p2(() => { + window.addEventListener(eventTypes.spacesChange, cacheChanged); + refreshFile(); + return () => { + window.removeEventListener(eventTypes.spacesChange, cacheChanged); + }; + }, [props2.source]); + const mdbFrame = (_a2 = props2.plugin.index.framesIndex.get(props2.path.path)) == null ? void 0 : _a2.frames[props2.path.ref]; + const root = mdbFrame ? buildRootFromMDBFrame(props2.plugin, mdbFrame) : null; + return root && /* @__PURE__ */ Cn.createElement(Cn.Fragment, null, props2.path.fullPath, /* @__PURE__ */ Cn.createElement(FrameRootView, { + root, + plugin: props2.plugin, + props: (_c2 = (_b2 = props2.path.query) != null ? _b2 : fileCache == null ? void 0 : fileCache.frontmatter) != null ? _c2 : {}, + contexts: {}, + source: props2.source + })); +}; +var EmbedContextView = (props2) => { + const context = spaceInfoByPath(props2.plugin, props2.path.fullPath); + return context && /* @__PURE__ */ Cn.createElement(SpaceContextProvider, { + plugin: props2.plugin, + space: context + }, /* @__PURE__ */ Cn.createElement(ContextMDBProvider, { + plugin: props2.plugin, + schema: props2.path.ref + }, /* @__PURE__ */ Cn.createElement(FramesMDBProvider, { + plugin: props2.plugin + }, /* @__PURE__ */ Cn.createElement(ContextEditorProvider, { + plugin: props2.plugin + }, /* @__PURE__ */ Cn.createElement(ContextListView, { + plugin: props2.plugin, + minMode: props2.minMode + }))))); +}; +var EmbedViewComponent = (props2) => { + const path = uriByString(props2.plugin, props2.path); + return /* @__PURE__ */ Cn.createElement(Cn.Fragment, null, path.refType == "context" ? /* @__PURE__ */ Cn.createElement(EmbedContextView, { + plugin: props2.plugin, + path + }) : path.refType == "frame" ? /* @__PURE__ */ Cn.createElement(EmbedFrameView, { + plugin: props2.plugin, + path, + source: props2.source + }) : path.type == "url" ? /* @__PURE__ */ Cn.createElement("iframe", { + width: "853", + height: "480", + src: `${path.fullPath}`, + frameBorder: "0", + allow: "accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture", + allowFullScreen: true, + title: "Embedded youtube" + }) : /* @__PURE__ */ Cn.createElement(Cn.Fragment, null)); +}; + +// src/components/SpaceView/Editor/EmbedView/EmbedContextView.tsx +var EMBED_CONTEXT_VIEW_TYPE = "make-inline-context"; +var EmbedContextView2 = class extends import_obsidian32.ItemView { + constructor(leaf, plugin) { + super(leaf); + this.navigation = true; + this.plugin = plugin; } - if (isMouseEvent(e4)) { - fileMenu.showAtPosition({ x: e4.pageX, y: e4.pageY }); - } else { - fileMenu.showAtPosition({ - x: e4.nativeEvent.locationX, - y: e4.nativeEvent.locationY - }); + getViewType() { + return EMBED_CONTEXT_VIEW_TYPE; } - return false; -}; -var triggerFileMenu = (plugin, file, isFolder, e4, source = "file-explorer") => { - const spaces2 = plugin.index.allSpaces(); - const spaceItems = retrieveSpaceItems(plugin, spaces2); - const cache = plugin.index.filesIndex.get(file.path); - const fileMenu = new import_obsidian25.Menu(); - if (isFolder) { - fileMenu.addSeparator(); - fileMenu.addItem((menuItem) => { - menuItem.setIcon("edit"); - menuItem.setTitle(i18n_default.buttons.createNote); - menuItem.onClick((ev) => { - newFileInFolder(plugin, file); - }); - }); - fileMenu.addItem((menuItem) => { - menuItem.setIcon("layout-dashboard"); - menuItem.setTitle(i18n_default.buttons.createCanvas); - menuItem.onClick((ev) => { - createNewCanvasFile(plugin, file, ""); - }); - }); - fileMenu.addItem((menuItem) => { - menuItem.setIcon("folder-plus"); - menuItem.setTitle(i18n_default.buttons.createFolder); - menuItem.onClick((ev) => { - let vaultChangeModal = new VaultChangeModal( - plugin, - file, - "create folder", - "/" - ); - vaultChangeModal.open(); - }); - }); + getDisplayText() { + return this.path; } - fileMenu.addSeparator(); - fileMenu.addItem((menuItem) => { - menuItem.setIcon("plus-square"); - menuItem.setTitle("Add to Space"); - menuItem.onClick((ev) => { - let vaultChangeModal = new AddToSpaceModal(plugin, [file.path]); - vaultChangeModal.open(); - }); - }); - fileMenu.addItem((menuItem) => { - menuItem.setIcon("minus-square"); - menuItem.setTitle("Remove from Space"); - menuItem.onClick((ev) => { - let vaultChangeModal = new RemoveFromSpaceModal(plugin, file.path); - vaultChangeModal.open(); - }); - }); - if (isFolder) { - fileMenu.addItem((menuItem) => { - menuItem.setTitle(i18n_default.menu.createFolderSpace); - menuItem.setIcon("folder-plus"); - menuItem.onClick((ev) => { - insertSpaceAtIndex( - plugin, - { - name: file.name, - pinned: "home", - def: { type: "focus", folder: file.path, filters: [] } - }, - 0 - ); - }); - }); + async onClose() { + this.destroy(); } - if (isFolder && cache) { - fileMenu.addSeparator(); - fileMenu.addItem((menuItem) => { - menuItem.setTitle(i18n_default.menu.customSort); - menuItem.setIcon("arrow-up-down"); - menuItem.setChecked(cache.folderSort == ""); - menuItem.onClick((ev) => { - saveFolderSort(plugin, file.path, ""); - }); - }); - fileMenu.addItem((menuItem) => { - menuItem.setTitle(i18n_default.menu.sortBy); - menuItem.setIcon("sort-desc"); - menuItem.onClick((ev) => { - const sortMenu = new import_obsidian25.Menu(); - sortMenu.addItem((menuItem2) => { - menuItem2.setTitle(i18n_default.menu.fileNameSortAlphaAsc); - menuItem2.setChecked(cache.folderSort == "path_asc"); - menuItem2.onClick((ev2) => { - saveFolderSort(plugin, file.path, "path_asc"); - }); - }); - sortMenu.addItem((menuItem2) => { - menuItem2.setTitle(i18n_default.menu.fileNameSortAlphaDesc); - menuItem2.setChecked(cache.folderSort == "path_desc"); - menuItem2.onClick((ev2) => { - saveFolderSort(plugin, file.path, "path_desc"); - }); - }); - sortMenu.addSeparator(); - sortMenu.addItem((menuItem2) => { - menuItem2.setTitle(i18n_default.menu.createdTimeSortAsc); - menuItem2.setChecked(cache.folderSort == "ctime_asc"); - menuItem2.onClick((ev2) => { - saveFolderSort(plugin, file.path, "ctime_asc"); - }); - }); - sortMenu.addItem((menuItem2) => { - menuItem2.setTitle(i18n_default.menu.createdTimeSortDesc); - menuItem2.setChecked(cache.folderSort == "ctime_desc"); - menuItem2.onClick((ev2) => { - saveFolderSort(plugin, file.path, "ctime_desc"); - }); - }); - sortMenu.addSeparator(); - sortMenu.addItem((menuItem2) => { - menuItem2.setTitle(i18n_default.menu.modifiedTimeSortAsc); - menuItem2.setChecked(cache.folderSort == "mtime_asc"); - menuItem2.onClick((ev2) => { - saveFolderSort(plugin, file.path, "mtime_asc"); - }); - }); - sortMenu.addItem((menuItem2) => { - menuItem2.setTitle(i18n_default.menu.modifiedTimeSortDesc); - menuItem2.setChecked(cache.folderSort == "mtime_desc"); - menuItem2.onClick((ev2) => { - saveFolderSort(plugin, file.path, "mtime_desc"); - }); - }); - const offset = e4.target.getBoundingClientRect(); - if (isMouseEvent(e4)) { - sortMenu.showAtPosition({ x: offset.left, y: offset.top + 30 }); - } else { - sortMenu.showAtPosition({ - x: e4.nativeEvent.locationX, - y: e4.nativeEvent.locationY - }); - } - }); - }); + onunload() { + this.destroy(); } - if (plugin.settings.spacesStickers) { - fileMenu.addSeparator(); - fileMenu.addItem((menuItem) => { - menuItem.setIcon("palette"); - disclosureMenuItem( - menuItem, - false, - false, - i18n_default.menu.changeColor, - "", - [ - { name: "None", value: "" }, - ...colors.map((f4) => ({ name: f4[0], value: f4[1] })) - ], - (_9, values) => { - saveFileColor(plugin, file.path, values[0]); - } - ); - }); - fileMenu.addItem((menuItem) => { - menuItem.setTitle(i18n_default.buttons.changeIcon); - menuItem.setIcon("lucide-sticker"); - menuItem.onClick((ev) => { - const vaultChangeModal = new stickerModal( - plugin.app, - plugin, - (emoji) => saveFileIcon(plugin, file, emoji) - ); - vaultChangeModal.open(); - }); - }); - fileMenu.addItem((menuItem) => { - menuItem.setTitle(i18n_default.buttons.removeIcon); - menuItem.setIcon("lucide-file-minus"); - menuItem.onClick((ev) => { - removeFileIcon(plugin, file); - }); - }); + destroy() { + if (this.root) + this.root.unmount(); } - fileMenu.addSeparator(); - fileMenu.addItem((menuItem) => { - menuItem.setTitle(i18n_default.menu.rename); - menuItem.setIcon("pencil"); - menuItem.onClick((ev) => { - let vaultChangeModal = new VaultChangeModal(plugin, file, "rename"); - vaultChangeModal.open(); - }); - }); - fileMenu.addItem((menuItem) => { - menuItem.setTitle(i18n_default.menu.delete); - menuItem.setIcon("trash"); - menuItem.onClick((ev) => { - let deleteOption = plugin.settings.deleteFileOption; - if (deleteOption === "permanent") { - plugin.app.vault.delete(file, true); - } else if (deleteOption === "system-trash") { - plugin.app.vault.trash(file, true); - } else if (deleteOption === "trash") { - plugin.app.vault.trash(file, false); - } - }); - }); - if (!isFolder) { - fileMenu.addItem((menuItem) => { - menuItem.setTitle(i18n_default.menu.changeToFolderNote); - menuItem.setIcon("file-plus-2"); - menuItem.onClick((ev) => { - if (file instanceof import_obsidian25.TFile) - noteToFolderNote(plugin, file, true); - }); - }); + async onOpen() { + this.destroy(); } - fileMenu.addItem((menuItem) => { - menuItem.setIcon("go-to-file"); - menuItem.setTitle(i18n_default.menu.openFilePane); - menuItem.onClick((ev) => { - openFileInNewPane(plugin, { ...file, isFolder }); - }); - }); - fileMenu.addItem((menuItem) => { - menuItem.setTitle(i18n_default.menu.duplicate); - menuItem.setIcon("documents"); - menuItem.onClick((ev) => { - if (file.basename && file.extension) - plugin.app.vault.copy( - file, - `${file.parent.path}/${file.basename} 1.${file.extension}` - ); - }); - }); - if (!internalPluginLoaded("file-explorer", plugin.app)) { - fileMenu.addItem((menuItem) => { - menuItem.setTitle(i18n_default.menu.moveFile); - menuItem.setIcon("paper-plane"); - menuItem.onClick((ev) => { - let fileMoveSuggester = new MoveSuggestionModal(plugin.app, [ - file.path - ]); - fileMoveSuggester.open(); - }); - }); + async setState(state, result) { + this.path = state.path; + this.source = state.source; + this.constructInlineContext(this.path); + await super.setState(state, result); + const context = uriByString(this.plugin, this.path); + const title = pathDisplayName(context, this.plugin); + this.leaf.tabHeaderInnerTitleEl.innerText = title; + this.leaf.view.titleEl = title; + const headerEl = this.leaf.view.headerEl; + if (headerEl) { + headerEl.querySelector(".view-header-title").innerText = title; + } + return; } - plugin.app.workspace.trigger("file-menu", fileMenu, file, source); - if (isMouseEvent(e4)) { - fileMenu.showAtPosition({ x: e4.pageX, y: e4.pageY }); - } else { - fileMenu.showAtPosition({ - x: e4.nativeEvent.locationX, - y: e4.nativeEvent.locationY - }); + getState() { + const state = super.getState(); + state.path = this.path; + state.source = this.source; + return state; + } + constructInlineContext(file) { + this.destroy(); + this.root = createRoot(this.contentEl); + this.root.render( + /* @__PURE__ */ Cn.createElement("div", null, /* @__PURE__ */ Cn.createElement(EmbedViewComponent, { + plugin: this.plugin, + path: this.path, + source: this.source + })) + ); } - return false; }; -// src/components/ContextView/DataTypeView/FileCell.tsx -var import_obsidian26 = require("obsidian"); -var FileCell = (props2) => { - const fileOrCleanPath = (f4) => { - if (!f4) - return { - path: "" - }; - const fileCache = props2.plugin.index.filesIndex.get(f4); - return fileCache ? { path: f4, fileCache } : { path: f4 }; - }; - const value = F2( - () => { - var _a2; - return (props2.multi ? (_a2 = parseMultiString(props2.initialValue)) != null ? _a2 : [] : [props2.initialValue]).map((f4) => fileOrCleanPath(f4)); - }, - [props2.initialValue] - ); - const ref = _2(null); - const onKeyDown = (e4) => { - e4.stopPropagation(); - e4.key == "Enter" && e4.target.blur(); - }; - const fileExists = (name) => { - if (!name) - return false; - return getAbstractFileAtPath(app, name) ? true : false; - }; - const onBlur = () => { - var _a2; - if (!ref.current) - return; - if (fileExists((_a2 = ref.current) == null ? void 0 : _a2.value)) { - new import_obsidian26.Notice(i18n_default.notice.fileExists); - } else { - props2.saveValue(ref.current.value); - props2.setEditMode(null); - } +// src/components/SpaceView/Editor/FlowEditor.tsx +var import_obsidian33 = require("obsidian"); +var popovers = /* @__PURE__ */ new WeakMap(); +var mouseCoords = { x: 0, y: 0 }; +function nosuper(base2) { + const derived = function() { + return Object.setPrototypeOf(new import_obsidian33.Component(), new.target.prototype); }; - const newFile = async (file) => { - const filePath = file.path.replace(/\//g, "").replace(/\./g, ""); - const path = `${props2.folder}/${filePath}.md`; - if (filePath.length == 0) { - return; + derived.prototype = base2.prototype; + return Object.setPrototypeOf(derived, base2); +} +var _a, _b, _c, _d, _e; +var FlowEditor = class extends nosuper(import_obsidian33.HoverPopover) { + constructor(parent, targetEl, plugin, waitTime, onShowCallback) { + super(); + this.targetEl = targetEl; + this.plugin = plugin; + this.onShowCallback = onShowCallback; + this.abortController = this.addChild(new import_obsidian33.Component()); + this.detaching = false; + this.opening = false; + this.rootSplit = new import_obsidian33.WorkspaceSplit( + this.plugin.app.workspace, + "vertical" + ); + this.targetRect = (_a = this.targetEl) == null ? void 0 : _a.getBoundingClientRect(); + this.oldPopover = (_b = this.parent) == null ? void 0 : _b.flowEditor; + this.document = (_e = (_d = (_c = this.targetEl) == null ? void 0 : _c.ownerDocument) != null ? _d : window.activeDocument) != null ? _e : window.document; + this.id = genId(); + this.hoverEl = this.document.defaultView.createDiv({ + cls: "mk-floweditor mk-hover-popover", + attr: { id: "he" + this.id } + }); + if (waitTime === void 0) { + waitTime = 300; } - if (fileExists(path)) { - new import_obsidian26.Notice(i18n_default.notice.fileExists); - } else { - await createNewMarkdownFile( - props2.plugin, - getAbstractFileAtPath(app, props2.folder), - filePath - ); + this.onTarget = true; + this.parent = parent; + this.waitTime = waitTime; + this.state = import_obsidian33.PopoverState.Showing; + const { hoverEl } = this; + this.abortController.load(); + this.timer = window.setTimeout(this.show.bind(this), waitTime); + this.setActive = this._setActive.bind(this); + if (hoverEl) { + hoverEl.addEventListener("mousedown", this.setActive); + hoverEl.addEventListener("mousedown", (e4) => e4.stopPropagation()); } - }; - const deleteRow = () => { - props2.deleteRow(); - }; - p2(() => { - var _a2; - if (props2.editMode == 2) { - (_a2 = ref == null ? void 0 : ref.current) == null ? void 0 : _a2.focus(); + popovers.set(this.hoverEl, this); + this.hoverEl.addClass("hover-editor"); + this.containerEl = this.hoverEl.createDiv("popover-content"); + this.setTitleBar(); + this.hoverEl.style.height = "auto"; + this.hoverEl.style.width = "100%"; + this.hoverEl.addEventListener("keydown", (e4) => e4.stopPropagation()); + } + static activeWindows() { + const windows = [window]; + const { floatingSplit } = app.workspace; + if (floatingSplit) { + for (const split of floatingSplit.children) { + if (split.win) + windows.push(split.win); + } } - }, [props2.editMode]); - return /* @__PURE__ */ Cn.createElement("div", { - className: "mk-cell-file" - }, value.map((v3, i4) => { - var _a2; - if (props2.editMode == 0) { - if (v3.fileCache) { - return /* @__PURE__ */ Cn.createElement("div", { - key: i4, - className: "mk-cell-file-title" - }, v3 && v3.fileCache ? v3.fileCache.name : "", ((_a2 = v3.fileCache.extension) == null ? void 0 : _a2.length) > 0 && v3.fileCache.extension != "md" && /* @__PURE__ */ Cn.createElement("span", { - className: "nav-file-tag" - }, v3.fileCache.extension), /* @__PURE__ */ Cn.createElement("button", { - "aria-label": i18n_default.buttons.toggleFlow, - className: "mk-cell-file-flow mk-inline-button", - dangerouslySetInnerHTML: { - __html: uiIconSet["mk-ui-flow-hover"] - }, - onClick: (e4) => { - if (props2.openFlow) { - props2.openFlow(e4); - e4.stopPropagation(); - } - } - })); - } else { - return /* @__PURE__ */ Cn.createElement("div", { - key: i4, - className: "mk-cell-file-title" - }, v3.path); + return windows; + } + static containerForDocument(doc) { + if (doc !== document && app.workspace.floatingSplit) + for (const container of app.workspace.floatingSplit.children) { + if (container.doc === doc) + return container; } + return app.workspace.rootSplit; + } + static activePopovers() { + return this.activeWindows().flatMap(this.popoversForWindow); + } + static popoversForWindow(win) { + var _a2, _b2; + return Array.prototype.slice.call( + (_b2 = (_a2 = win == null ? void 0 : win.document) == null ? void 0 : _a2.body.querySelectorAll(".mk-hover-popover")) != null ? _b2 : [] + ).map((el) => popovers.get(el)).filter((he2) => he2); + } + static forLeaf(leaf) { + const el = leaf && document.body.matchParent.call(leaf.containerEl, ".mk-hover-popover"); + return el ? popovers.get(el) : void 0; + } + onunload() { + this.hide(); + } + _setActive() { + this.plugin.app.workspace.setActiveLeaf(this.leaves()[0], { focus: true }); + } + getDefaultMode() { + var _a2, _b2; + return ((_b2 = (_a2 = this.parent) == null ? void 0 : _a2.view) == null ? void 0 : _b2.getMode) ? this.parent.view.getMode() : "preview"; + } + updateLeaves() { + if (this.onTarget && this.targetEl && !this.document.contains(this.targetEl)) { + this.onTarget = false; + this.transition(); } - if (v3.fileCache) { - return /* @__PURE__ */ Cn.createElement(Cn.Fragment, null, /* @__PURE__ */ Cn.createElement("div", { - className: "mk-cell-file-item", - onContextMenu: (e4) => triggerFileMenu( - props2.plugin, - getAbstractFileAtPath(app, v3.fileCache.path), - v3.fileCache.isFolder, - e4 - ) - }, /* @__PURE__ */ Cn.createElement(FileSticker, { - plugin: props2.plugin, - fileCache: v3.fileCache - }), /* @__PURE__ */ Cn.createElement("div", { - className: "mk-cell-file-name", - onClick: (e4) => openAFile( - getAbstractFileAtPath(app, v3.fileCache.path), - props2.plugin, - e4.ctrlKey || e4.metaKey ? e4.altKey ? "split" : "tab" : false - ) - }, v3 && v3.fileCache ? v3.fileCache.name : ""))); + let leafCount = 0; + this.plugin.app.workspace.iterateLeaves((leaf) => { + leafCount++; + }, this.rootSplit); + if (leafCount === 0) { + this.hide(); + } else if (leafCount > 1) { } - return /* @__PURE__ */ Cn.createElement(Cn.Fragment, null, /* @__PURE__ */ Cn.createElement("div", { - className: "mk-cell-file-item" - }, /* @__PURE__ */ Cn.createElement("div", { - className: "mk-file-icon" - }, /* @__PURE__ */ Cn.createElement("button", { - onClick: (e4) => newFile(v3), - dangerouslySetInnerHTML: { - __html: uiIconSet["mk-ui-new-file"] - } - })), props2.editMode > 1 ? /* @__PURE__ */ Cn.createElement("input", { - className: "mk-cell-file-name", - type: "text", - placeholder: "Untitled", - ref, - value: v3.path, - onKeyDown, - onBlur - }) : /* @__PURE__ */ Cn.createElement("div", { - className: "mk-cell-file-name" - }, v3.path))); - })); -}; - -// src/components/ContextView/DataTypeView/FilePropertyCell.tsx -var humanFileSize = (bytes, si = false, dp = 1) => { - const thresh = si ? 1e3 : 1024; - if (Math.abs(bytes) < thresh) { - return bytes + " B"; + this.hoverEl.setAttribute("data-leaf-count", leafCount.toString()); } - const units = si ? ["kB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"] : ["KiB", "MiB", "GiB", "TiB", "PiB", "EiB", "ZiB", "YiB"]; - let u4 = -1; - const r3 = 10 ** dp; - do { - bytes /= thresh; - ++u4; - } while (Math.round(Math.abs(bytes) * r3) / r3 >= thresh && u4 < units.length - 1); - return bytes.toFixed(dp) + " " + units[u4]; -}; -var LookUpCell = (props2) => { - const [cache, setCache] = h2(null); - const initialValue = props2.initialValue; - const { field, property } = parsePropString(props2.propertyValue); - if (property == "folder") { - return /* @__PURE__ */ Cn.createElement("div", { - className: "mk-cell-fileprop", - onClick: () => { - openTFolder( - getAbstractFileAtPath(app, initialValue), - props2.plugin, - false - ); + setTitleBar() { + this.titleEl = this.document.defaultView.createDiv("mk-flow-titlebar"); + this.containerEl.prepend(this.titleEl); + } + attachLeaf() { + this.rootSplit.getRoot = () => this.plugin.app.workspace[this.document === document ? "rootSplit" : "floatingSplit"]; + this.rootSplit.getContainer = () => FlowEditor.containerForDocument(this.document); + this.titleEl.insertAdjacentElement("afterend", this.rootSplit.containerEl); + const leaf = this.plugin.app.workspace.createLeafInParent( + this.rootSplit, + 0 + ); + leaf.isFlowBlock = true; + this.updateLeaves(); + return leaf; + } + onload() { + super.onload(); + this.registerEvent( + this.plugin.app.workspace.on("layout-change", this.updateLeaves, this) + ); + this.registerEvent( + app.workspace.on("layout-change", () => { + this.rootSplit.children.forEach((item, index) => { + if (item instanceof import_obsidian33.WorkspaceTabs) { + this.rootSplit.replaceChild(index, item.children[0]); + } + }); + }) + ); + } + leaves() { + const leaves = []; + this.plugin.app.workspace.iterateLeaves((leaf) => { + leaves.push(leaf); + }, this.rootSplit); + return leaves; + } + async onShow() { + var _a2, _b2; + const closeDelay = 600; + setTimeout(() => this.waitTime = closeDelay, closeDelay); + (_a2 = this.oldPopover) == null ? void 0 : _a2.hide(); + this.oldPopover = null; + this.hoverEl.toggleClass("is-new", true); + this.document.body.addEventListener( + "click", + () => { + this.hoverEl.toggleClass("is-new", false); + }, + { once: true, capture: true } + ); + if (this.parent) { + this.parent.flowEditor = this; + this.parent.view.addChild(this); + } + await ((_b2 = this.onShowCallback) == null ? void 0 : _b2.call(this, this)); + this.onShowCallback = void 0; + const viewHeaderEl = this.hoverEl.querySelector(".view-header"); + viewHeaderEl == null ? void 0 : viewHeaderEl.remove(); + const sizer = this.hoverEl.querySelector(".workspace-leaf"); + if (sizer) + this.hoverEl.appendChild(sizer); + const inlineTitle = this.hoverEl.querySelector(".inline-title"); + inlineTitle == null ? void 0 : inlineTitle.remove(); + } + transition() { + if (this.shouldShow()) { + if (this.state === import_obsidian33.PopoverState.Hiding) { + this.state = import_obsidian33.PopoverState.Shown; + clearTimeout(this.timer); + } + } else { + if (this.state === import_obsidian33.PopoverState.Showing) { + this.hide(); + } else { + if (this.state === import_obsidian33.PopoverState.Shown) { + this.state = import_obsidian33.PopoverState.Hiding; + this.timer = window.setTimeout(() => { + if (this.shouldShow()) { + this.transition(); + } else { + this.hide(); + } + }, this.waitTime); + } } - }, folderPathToString(initialValue)); + } } - if (property == "extension") { - return /* @__PURE__ */ Cn.createElement("div", { - className: "mk-cell-fileprop" - }, initialValue); - } else if (property == "ctime" || property == "mtime") { - const date = new Date(parseInt(initialValue)).getTime() ? new Date(parseInt(initialValue)) : null; - return /* @__PURE__ */ Cn.createElement("div", { - className: "mk-cell-fileprop" - }, date && formatDistance3(new Date(date), new Date(), { addSuffix: true })); - } else if (property == "size" || property == "File.size") { - return /* @__PURE__ */ Cn.createElement("div", { - className: "mk-cell-fileprop" - }, humanFileSize(parseInt(initialValue))); + shouldShow() { + return this.shouldShowSelf() || this.shouldShowChild(); } - return /* @__PURE__ */ Cn.createElement("div", { - className: "mk-cell-fileprop" - }, initialValue); -}; - -// src/components/ContextView/DataTypeView/NumberCell.tsx -var NumberCell = (props2) => { - const { initialValue, saveValue } = props2; - const [value, setValue] = Cn.useState(initialValue); - const ref = _2(null); - const onBlur = () => { - if (initialValue != value) - saveValue(value); - }; - const onKeyDown = (e4) => { - e4.stopPropagation(); - if (e4.key == "Enter") { - e4.target.blur(); - props2.setEditMode(null); - } - if (e4.key == "Escape") { - setValue(initialValue); - e4.target.blur(); - props2.setEditMode(null); + shouldShowChild() { + return FlowEditor.activePopovers().some((popover) => { + if (popover !== this && popover.targetEl && this.hoverEl.contains(popover.targetEl)) { + return popover.shouldShow(); + } + return false; + }); + } + shouldShowSelf() { + return !this.detaching && !!(this.onTarget || this.state == import_obsidian33.PopoverState.Shown || this.document.querySelector( + `body>.modal-container, body > #he${this.id} ~ .menu, body > #he${this.id} ~ .suggestion-container` + )); + } + show() { + if (!this.targetEl || this.document.body.contains(this.targetEl)) { + this.state = import_obsidian33.PopoverState.Shown; + this.timer = 0; + this.shownPos = mouseCoords; + this.targetEl.replaceChildren(this.hoverEl); + this.onShow(); + app.workspace.onLayoutChange(); + this.load(); + } else { + this.hide(); } - }; - Cn.useEffect(() => { - setValue(initialValue); - }, [initialValue]); - p2(() => { + } + onHide() { var _a2; - if (props2.editMode == 2) { - (_a2 = ref == null ? void 0 : ref.current) == null ? void 0 : _a2.focus(); + this.oldPopover = null; + if (((_a2 = this.parent) == null ? void 0 : _a2.flowEditor) === this) { + this.parent.flowEditor = null; } - }, [props2.editMode]); - return props2.editMode > 1 ? /* @__PURE__ */ Cn.createElement("input", { - className: "mk-cell-text", - type: "number", - step: "any", - ref, - value, - onChange: (e4) => setValue(e4.target.value), - onKeyDown, - onBlur - }) : /* @__PURE__ */ Cn.createElement("div", { - className: "mk-cell-number" - }, value); -}; - -// src/components/ContextView/DataTypeView/TextCell.tsx -var TextCell = (props2) => { - const { initialValue, saveValue } = props2; - const [value, setValue] = Cn.useState(initialValue); - const ref = _2(null); - const onBlur = () => { - if (initialValue != value) - saveValue(value); - }; - const onKeyDown = (e4) => { - e4.stopPropagation(); - if (e4.key == "Enter") { - e4.target.blur(); - props2.setEditMode(null); + } + hide() { + var _a2; + this.onTarget = false; + this.detaching = true; + if (this.timer) { + clearTimeout(this.timer); + this.timer = 0; } - if (e4.key == "Escape") { - setValue(initialValue); - e4.target.blur(); - props2.setEditMode(null); + this.hoverEl.hide(); + if (this.opening) + return; + const leaves = this.leaves(); + if (leaves.length) { + leaves.forEach((leaf) => { + leaf.detach(); + }); + } else { + this.parent = null; + (_a2 = this.abortController) == null ? void 0 : _a2.unload(); + this.abortController = void 0; + return this.nativeHide(); } - }; - Cn.useEffect(() => { - setValue(initialValue); - }, [initialValue]); - p2(() => { + } + nativeHide() { var _a2; - if (props2.editMode == 2) { - (_a2 = ref == null ? void 0 : ref.current) == null ? void 0 : _a2.focus(); + const { hoverEl, targetEl } = this; + this.state = import_obsidian33.PopoverState.Hidden; + hoverEl.detach(); + if (targetEl) { + const parent = targetEl.matchParent(".mk-hover-popover"); + if (parent) + (_a2 = popovers.get(parent)) == null ? void 0 : _a2.transition(); } - }, [props2.editMode]); - return props2.editMode > 1 ? /* @__PURE__ */ Cn.createElement("input", { - onClick: (e4) => e4.stopPropagation(), - className: "mk-cell-text", - ref, - type: "text", - value, - onChange: (e4) => setValue(e4.target.value), - onKeyDown, - onBlur - }) : /* @__PURE__ */ Cn.createElement("div", { - className: "mk-cell-text" - }, value); + this.onHide(); + this.unload(); + } + resolveLink(linkText, sourcePath) { + const link = (0, import_obsidian33.parseLinktext)(linkText); + const tFile = link ? this.plugin.app.metadataCache.getFirstLinkpathDest( + link.path, + sourcePath != null ? sourcePath : "" + ) : null; + return tFile; + } + async openContext(file, openState, useLeaf) { + if (this.detaching) + return; + const leaf = useLeaf != null ? useLeaf : this.attachLeaf(); + this.opening = true; + try { + await leaf.openFile(file, openState); + } catch (e4) { + console.error(e4); + } finally { + this.opening = false; + if (this.detaching) + this.hide(); + } + return leaf; + } + async openFile(file, openState, useLeaf) { + if (this.detaching) + return; + const leaf = useLeaf != null ? useLeaf : this.attachLeaf(); + this.opening = true; + try { + await leaf.openFile(file, openState); + } catch (e4) { + console.error(e4); + } finally { + this.opening = false; + if (this.detaching) + this.hide(); + } + return leaf; + } + buildState(parentMode, eState) { + return { + active: false, + state: {}, + eState + }; + } + buildEphemeralState(file, link) { + const cache = this.plugin.app.metadataCache.getFileCache(file); + const subpath = cache ? (0, import_obsidian33.resolveSubpath)(cache, (link == null ? void 0 : link.subpath) || "") : void 0; + const eState = { subpath: link == null ? void 0 : link.subpath }; + if (subpath) { + eState.line = subpath.start.line; + eState.startLoc = subpath.start; + eState.endLoc = subpath.end || void 0; + } + return eState; + } }; -// src/components/ContextView/TableView/TableView.tsx -var import_lodash6 = __toESM(require_lodash()); -var import_obsidian31 = require("obsidian"); - -// src/utils/ui/selection.ts -var selectNextIndex = (currIndex, array) => { - if (!currIndex && array.length > 0) - return array[0]; - const pos = array.indexOf(currIndex); - if (pos < array.length - 1) - return array[pos + 1]; - return currIndex; +// src/utils/flow/flowEditor.ts +var import_obsidian34 = require("obsidian"); +var parseOutReferences = (ostr) => { + const str = ostr.split("|")[0]; + const refIndex = str.lastIndexOf("#"); + return refIndex > 0 ? [str.substring(0, refIndex), str.substring(refIndex + 1)] : [str, void 0]; }; -var selectPrevIndex = (currIndex, array) => { - const pos = array.indexOf(currIndex); - if (pos > 0) - return array[pos - 1]; - return array[0]; +var getFileFromString = (plugin, url, source) => { + return plugin.app.metadataCache.getFirstLinkpathDest(url, source != null ? source : ""); }; -var selectRange = (currSel, newSel, array) => { - const lastIndex = array.findIndex((f4) => f4 == currSel); - const newIndex = array.findIndex((f4) => f4 == newSel); - if (lastIndex < newIndex) { - return array.filter((f4, i4) => i4 > lastIndex && i4 <= newIndex); +var getLineRangeFromRef = (file, ref2, plugin) => { + var _a2; + if (!ref2) { + return [void 0, void 0]; } - return array.filter((f4, i4) => i4 < lastIndex && i4 >= newIndex); -}; - -// src/components/ContextView/DataTypeView/ImageCell.tsx -var ImageCell = (props2) => { - const { initialValue, saveValue } = props2; - const [value, setValue] = Cn.useState(initialValue); - const menuRef = _2(null); - p2(() => { - if (props2.editMode == 2 /* EditModeActive */) { - if (!menuRef.current) - showModal(); - } - }, []); - const file = F2(() => { - const f4 = getAbstractFileAtPath(app, value); - return f4 ? app.vault.getResourcePath(f4) : value; - }, [value]); - Cn.useEffect(() => { - setValue(initialValue); - }, [initialValue]); - const showModal = () => { - let vaultChangeModal = new imageModal( - props2.plugin, - props2.plugin.app, - (image) => saveValue(image) + const cache = plugin.app.metadataCache.getFileCache(file); + const headings = cache.headings; + const blocks = cache.blocks; + const sections = cache.sections; + if (blocks && ref2.charAt(0) == "^" && blocks[ref2.substring(1)]) { + return [ + blocks[ref2.substring(1)].position.start.line + 1, + blocks[ref2.substring(1)].position.end.line + 1 + ]; + } + const heading = headings == null ? void 0 : headings.find((f4) => f4.heading.replace("#", " ") == ref2); + if (heading) { + const index = headings.findIndex((f4) => f4.heading == heading.heading); + const level = (_a2 = headings[index]) == null ? void 0 : _a2.level; + const nextIndex2 = headings.findIndex( + (f4, i4) => i4 > index && f4.level <= level ); - vaultChangeModal.open(); - props2.setEditMode(null); - }; - return /* @__PURE__ */ Cn.createElement("div", { - className: "mk-cell-image" - }, /* @__PURE__ */ Cn.createElement("img", { - src: file - }), props2.editMode > 0 ? /* @__PURE__ */ Cn.createElement("div", { - className: "mk-image-selector" - }, /* @__PURE__ */ Cn.createElement("div", { - onClick: showModal, - className: "mk-hover-button mk-icon-xsmall", - dangerouslySetInnerHTML: { __html: uiIconSet["mk-ui-edit"] } - }), (value == null ? void 0 : value.length) > 0 && /* @__PURE__ */ Cn.createElement("div", { - onClick: () => saveValue(""), - className: "mk-hover-button mk-icon-xsmall", - dangerouslySetInnerHTML: { __html: uiIconSet["mk-ui-close"] } - })) : /* @__PURE__ */ Cn.createElement(Cn.Fragment, null)); -}; - -// src/utils/flow/flowEditor.ts -var import_state5 = require("@codemirror/state"); - -// src/cm-extensions/flowEditor/atomic.ts -var import_state4 = require("@codemirror/state"); - -// src/cm-extensions/flowEditor/selectiveEditor.ts -var import_state3 = require("@codemirror/state"); -var import_view3 = require("@codemirror/view"); - -// node_modules/tslib/modules/index.js -var import_tslib = __toESM(require_tslib(), 1); -var { - __extends, - __assign: __assign2, - __rest: __rest2, - __decorate, - __param, - __esDecorate, - __runInitializers, - __propKey, - __setFunctionName, - __metadata, - __awaiter, - __generator, - __exportStar, - __createBinding, - __values, - __read, - __spread, - __spreadArrays, - __spreadArray: __spreadArray2, - __await, - __asyncGenerator, - __asyncDelegator, - __asyncValues, - __makeTemplateObject, - __importStar, - __importDefault, - __classPrivateFieldGet, - __classPrivateFieldSet, - __classPrivateFieldIn -} = import_tslib.default; - -// src/cm-extensions/flowEditor/selectiveEditor.ts -var combinedRangeFacets = (rangeA, rangeB) => { - const startRange = !(rangeA == null ? void 0 : rangeA[0]) ? rangeB[0] : !(rangeB == null ? void 0 : rangeB[0]) ? rangeA[0] : Math.max(rangeA == null ? void 0 : rangeA[0], rangeB == null ? void 0 : rangeB[0]); - const endRange = !(rangeA == null ? void 0 : rangeA[1]) ? rangeB[1] : !(rangeB == null ? void 0 : rangeB[1]) ? rangeA[1] : Math.min(rangeA == null ? void 0 : rangeA[1], rangeB == null ? void 0 : rangeB[1]); - return [isNaN(startRange) ? null : startRange, isNaN(endRange) ? null : endRange]; + const start = plugin.settings.editorFlowStyle == "classic" ? heading.position.start.line + 1 : heading.position.start.line + 2; + if (index < headings.length - 1 && nextIndex2 != -1) { + return [start, headings[nextIndex2].position.end.line]; + } + return [start, sections[sections.length - 1].position.end.line + 1]; + } + return [void 0, void 0]; }; -var editableRange = import_state3.Annotation.define(); -var contentRange = import_state3.Annotation.define(); -var hiddenLine = import_view3.Decoration.replace({ inclusive: true, block: true }); -var hideLine = import_state3.StateField.define({ - create() { - return import_view3.Decoration.none; - }, - update(value, tr) { - let builder = new import_state3.RangeSetBuilder(); - const betterFacet = combinedRangeFacets(tr.state.field(selectiveLinesFacet, false), tr.state.field(frontmatterFacet, false)); - if ((betterFacet == null ? void 0 : betterFacet[0]) != null) { - const starterLine = Math.min( - tr.state.doc.lines, - betterFacet[0] - ); - builder.add( - tr.state.doc.line(1).from, - tr.state.doc.line(starterLine).from - 1, - hiddenLine - ); - if (tr.newDoc.lines != betterFacet[1]) - builder.add( - tr.state.doc.line( - Math.min(tr.newDoc.lines, betterFacet[1]) - ).to, - tr.state.doc.line(tr.newDoc.lines).to, - hiddenLine - ); +var loadFlowEditorByDOM2 = (plugin, el, view, id2) => { + setTimeout(async () => { + let counter = 0; + while (!el.parentElement && counter++ <= 50) + await sleep(50); + if (!el.parentElement) + return; + let dom = el; + while (!dom.hasClass("mk-floweditor") && !dom.hasClass("workspace") && dom.parentElement) { + dom = dom.parentElement; } - const dec = builder.finish(); - return dec; - }, - provide: (f4) => import_view3.EditorView.decorations.from(f4) -}); -var frontmatterFacet = import_state3.StateField.define({ - create: () => [void 0, void 0], - update(value, tr) { - if (tr.annotation(contentRange)) { - if (tr.annotation(contentRange)[0]) { - return [ - tr.annotation(contentRange)[0], - Math.min(tr.state.doc.lines, tr.annotation(contentRange)[1]) - ]; - } - return tr.annotation(contentRange); + if (!dom.hasClass("mk-floweditor") && !dom.hasClass("workspace") && !(dom.nodeName == "HTML")) { + return; } - return value; - } -}); -var selectiveLinesFacet = import_state3.StateField.define({ - create: () => [void 0, void 0], - update(value, tr) { - if (tr.annotation(editableRange)) { - if (tr.annotation(editableRange)[0]) { - return [ - tr.annotation(editableRange)[0], - Math.min(tr.state.doc.lines, tr.annotation(editableRange)[1]) - ]; + setTimeout(async () => { + var _a2, _b2; + let leafFound = false; + if (plugin.app.workspace.activeEditor) { + if (((_b2 = (_a2 = plugin.app.workspace.activeEditor) == null ? void 0 : _a2.editor) == null ? void 0 : _b2.cm.dom) == view.dom) { + leafFound = true; + plugin.app.workspace.iterateLeaves((leaf) => { + var _a3, _b3; + if (((_a3 = leaf.view.editor) == null ? void 0 : _a3.cm.dom) == view.dom) { + loadFlowEditorsForLeafForID( + leaf, + plugin.app.workspace.activeEditor.editor.cm, + (_b3 = plugin.app.workspace.activeEditor.file) == null ? void 0 : _b3.path, + plugin, + id2 + ); + } + }, plugin.app.workspace["rootSplit"]); + } } - return tr.annotation(editableRange); - } - return value; + if (!leafFound) { + plugin.app.workspace.iterateLeaves((leaf) => { + var _a3, _b3; + const cm = (_a3 = leaf.view.editor) == null ? void 0 : _a3.cm; + if (cm && view.dom == cm.dom) { + leafFound = true; + loadFlowEditorsForLeafForID( + leaf, + cm, + (_b3 = leaf.view.file) == null ? void 0 : _b3.path, + plugin, + id2 + ); + } + }, plugin.app.workspace["rootSplit"]); + } + }); + }); +}; +var loadFlowEditorsForLeafForID = (leaf, cm, source, plugin, id2) => { + const stateField = cm.state.field(flowEditorInfo, false); + if (!stateField) + return; + const flowInfo = stateField.find((f4) => f4.id == id2); + if (flowInfo && flowInfo.expandedState == 2) { + loadFlowEditor(leaf, cm, flowInfo, source, plugin); } -}); -var lineRangeToPosRange = (state, range) => { - return { - from: state.doc.line(range[0]).from, - to: state.doc.line(Math.min(state.doc.lines, range[1])).to - }; }; -var smartDelete = import_state3.EditorState.transactionFilter.of( - (tr) => { - if (tr.isUserEvent("delete") && !tr.annotation(import_state3.Transaction.userEvent).endsWith(".smart")) { - const initialSelections = tr.startState.selection.ranges.map((range) => ({ - from: range.from, - to: range.to - })); - const betterFacet = combinedRangeFacets(tr.startState.field(selectiveLinesFacet, false), tr.startState.field(frontmatterFacet, false)); - if (initialSelections.length > 0 && (betterFacet == null ? void 0 : betterFacet[0])) { - const posRange = lineRangeToPosRange( - tr.startState, - betterFacet +var loadFlowEditor = (leaf, cm, flowEditorInfo2, source, plugin) => { + const dom = cm.dom.querySelector( + "#mk-flow-" + flowEditorInfo2.id + ); + const path = uriByString(plugin, flowEditorInfo2.link, source); + if (dom) { + if (path.type == "folder" || path.type == "tag" || path.type == "space") { + if (!dom.hasAttribute("ready")) { + dom.setAttribute("ready", ""); + createFlowEditorInElement( + flowEditorInfo2.id, + leaf, + source, + dom, + "context", + path ); - if (tr.changes.touchesRange(0, posRange.from - 1)) { - const minFrom = Math.max(posRange.from, initialSelections[0].from); - const minTo = Math.min(posRange.to, initialSelections[0].to); - return [{ - changes: { - from: Math.min(minFrom, minTo), - to: Math.max(minFrom, minTo) - }, - annotations: import_state3.Transaction.userEvent.of( - `${tr.annotation(import_state3.Transaction.userEvent)}.smart` - ) - }]; + return; + } + } else if (path.type == "file") { + const file = getFileFromString(plugin, path.path, source); + const aFile = getAbstractFileAtPath(plugin, path.path); + if (file) { + const selectiveRange = getLineRangeFromRef(file, path.ref, plugin); + if (!dom.hasAttribute("ready")) { + dom.setAttribute("ready", ""); + createFlowEditorInElement( + flowEditorInfo2.id, + leaf, + source, + dom, + path.ref ? "block" : "flow", + { ...path, fullPath: file.path, path: file.path }, + selectiveRange[0], + selectiveRange[1] + ); + } + } else { + if (aFile instanceof import_obsidian34.TFolder) { + if (!dom.hasAttribute("ready")) { + dom.setAttribute("ready", ""); + createFlowEditorInElement( + flowEditorInfo2.id, + leaf, + source, + dom, + path.ref ? "block" : "flow", + path + ); + } + return; } + dom.empty(); + const createDiv = dom.createDiv("file-embed"); + createDiv.toggleClass("mod-empty", true); + const createFile = async (e4) => { + e4.stopPropagation(); + e4.stopImmediatePropagation(); + await plugin.files.newFile("/", path.path, "md"); + loadFlowEditor(leaf, cm, flowEditorInfo2, source, plugin); + }; + createDiv.setText(`"${path}" ` + i18n_default.labels.noFile); + createDiv.addEventListener("click", createFile); } } - return tr; } -); -var preventModifyTargetRanges = import_state3.EditorState.transactionFilter.of( - (tr) => { - let newTrans = []; - try { - const editableLines = tr.startState.field(selectiveLinesFacet, false); - const contentLines = tr.startState.field(frontmatterFacet, false); - const selectiveLines = combinedRangeFacets(editableLines, contentLines); - if (tr.isUserEvent("input") || tr.isUserEvent("delete") || tr.isUserEvent("move")) { - if (selectiveLines == null ? void 0 : selectiveLines[0]) { - const posRange = lineRangeToPosRange( - tr.startState, - selectiveLines - ); - if (!tr.changes.touchesRange(posRange.from, posRange.to)) { - return []; +}; +var focusPortal = async (plugin, evt) => { + const { id: id2, parent, top } = evt.detail; + if (parent) { + plugin.app.workspace.iterateLeaves((leaf) => { + var _a2; + const cm = (_a2 = leaf.view.editor) == null ? void 0 : _a2.cm; + if (cm) { + const stateField = cm.state.field(flowEditorInfo, false); + if (stateField) { + const foundInfo = stateField.find((f4) => f4.id == id2); + if (foundInfo) { + cm.focus(); + if (top) { + cm.dispatch({ + selection: import_state5.EditorSelection.single(foundInfo.from - 4), + annotations: arrowKeyAnnotation.of(1) + }); + } else { + if (foundInfo.to + 2 == cm.state.doc.length) { + cm.dispatch({ + changes: [ + { + from: foundInfo.to + 2, + to: foundInfo.to + 2, + insert: cm.state.lineBreak + } + ], + selection: import_state5.EditorSelection.single(foundInfo.to + 3), + annotations: arrowKeyAnnotation.of(2) + }); + } else { + cm.dispatch({ + selection: import_state5.EditorSelection.single(foundInfo.to + 3), + annotations: arrowKeyAnnotation.of(2) + }); + } + } } } } - if (tr.state.doc.lines != tr.startState.doc.lines) { - const numberNewLines = tr.state.doc.lines - tr.startState.doc.lines; - if (selectiveLines == null ? void 0 : selectiveLines[0]) { - const posRange = lineRangeToPosRange( - tr.startState, - selectiveLines - ); - if (tr.changes.touchesRange(0, posRange.from - 1)) { - const newAnnotations = []; - if (editableLines[0]) { - newAnnotations.push(editableRange.of([ - editableLines[0] + numberNewLines, - editableLines[1] + numberNewLines - ])); - } - if (contentLines[0]) { - newAnnotations.push(contentRange.of([ - contentLines[0] + numberNewLines, - contentLines[1] + numberNewLines - ])); - } - newTrans.push({ - annotations: newAnnotations + }, plugin.app.workspace["rootSplit"]); + } else { + plugin.app.workspace.iterateLeaves((leaf) => { + var _a2; + const cm = (_a2 = leaf.view.editor) == null ? void 0 : _a2.cm; + if (cm) { + const stateField = cm.state.field(flowIDStateField, false); + if (stateField && stateField == id2) { + cm.focus(); + const lineRange = cm.state.field(selectiveLinesFacet, false); + const posRange = lineRange && lineRange[0] != void 0 ? lineRangeToPosRange(cm.state, lineRange) : { from: 0, to: cm.state.doc.length }; + if (top) { + cm.dispatch({ + selection: import_state5.EditorSelection.single(posRange.from) }); - } else if (tr.changes.touchesRange(posRange.from - 1, posRange.to)) { - const newAnnotations = []; - if (editableLines[0]) { - newAnnotations.push(editableRange.of([ - editableLines[0], - editableLines[1] + numberNewLines - ])); - } - if (contentLines[0]) { - newAnnotations.push(contentRange.of([ - contentLines[0], - contentLines[1] + numberNewLines - ])); - } - newTrans.push({ - annotations: newAnnotations + } else { + cm.dispatch({ + selection: import_state5.EditorSelection.single(posRange.to) }); } } } - } catch (e4) { - return []; - } - return [tr, ...newTrans]; + }, plugin.app.workspace["rootSplit"]); } -); -var readOnlyRangesExtension = [smartDelete, preventModifyTargetRanges]; -var editBlockExtensions = () => [ - readOnlyRangesExtension, - hideLine, - selectiveLinesFacet, - frontmatterFacet -]; - -// src/cm-extensions/flowEditor/atomic.ts -var arrowKeyAnnotation = import_state4.Annotation.define(); -var atomicSelect = import_state4.EditorState.transactionFilter.of( - (tr) => { - if (tr.isUserEvent("delete") || tr.isUserEvent("input")) { - return tr; +}; +var openFileFromPortal = (plugin, evt) => { + const { file: fullLink, source } = evt.detail; + const [link, ref2] = parseOutReferences(fullLink); + const file = getFileFromString(plugin, link, source); + openAFile(file, plugin, false); +}; +var spawnLeafFromFile = async (plugin, parentLeaf, source, path, el, type, from, to, file, onLeafAttachCallback) => { + if (type == "context") { + spawnPortal(plugin, parentLeaf, el, null, async (editor) => { + const newLeaf = editor.attachLeaf(); + await newLeaf.setViewState({ + type: EMBED_CONTEXT_VIEW_TYPE, + state: { path: path.fullPath, source } + }); + if (onLeafAttachCallback) + onLeafAttachCallback(newLeaf); + }); + return; + } + const portalFile = file != null ? file : plugin.app.vault.getAbstractFileByPath(path.path); + spawnPortal(plugin, parentLeaf, el, path.path, async (editor) => { + let leaf; + if (portalFile) { + leaf = await editor.openFile(portalFile).then((newLeaf) => { + var _a2; + if (newLeaf.view.setMode) + newLeaf.view.setMode(newLeaf.view.editMode); + if (from && to) { + (_a2 = newLeaf.view.editor) == null ? void 0 : _a2.cm.dispatch({ + annotations: [editableRange.of([from, to])] + }); + } + if (onLeafAttachCallback) + onLeafAttachCallback(newLeaf); + }); + } else { + const newFile = await plugin.files.newFile( + "/", + path.path, + "md" + ); + leaf = await editor.openFile(newFile).then((newLeaf) => { + if (onLeafAttachCallback) + onLeafAttachCallback(newLeaf); + }); } - const flowID = tr.startState.field(flowIDStateField, false); - if (tr.annotation(arrowKeyAnnotation) && flowID) { - const oldSel = tr.startState.selection.main; - const lineRange = tr.state.field(selectiveLinesFacet, false); - const posRange = lineRange && lineRange[0] != void 0 ? lineRangeToPosRange(tr.startState, lineRange) : { from: 0, to: tr.startState.doc.length }; - if (oldSel.from <= posRange.from && tr.annotation(arrowKeyAnnotation) == 3) { - focusFlowEditorParent(flowID, true); - } - if (oldSel.to >= posRange.to && tr.annotation(arrowKeyAnnotation) == 4) { - focusFlowEditorParent(flowID, false); - } - return tr; + return leaf; + }); +}; +var spawnNewPortal = async (plugin, evt) => { + const { path, leaf, el, source, ref: ref2, from, to, type } = evt.detail; + spawnLeafFromFile(plugin, leaf, source, path, el, type, from, to, null, (newLeaf) => { + var _a2, _b2, _c2; + if (!((_a2 = newLeaf == null ? void 0 : newLeaf.view) == null ? void 0 : _a2.editor)) { + return; } - const selection = tr.newSelection.main; - if (selection.from == 0 && selection.to == 0 || selection.from != selection.to) - return tr; - const flowEditors = tr.state.field(flowEditorInfo, false); - if (flowEditors) { - for (let info of flowEditors) { - if (info.embed == 1) { - if (info.from - 3 <= selection.from && info.to + 2 >= selection.to && info.expandedState == 2) { - const top = tr.annotation(arrowKeyAnnotation) == 1 || tr.startState.selection.main.from > selection.from ? false : true; - focusFlowEditor(info.id, top); - return { - selection: import_state4.EditorSelection.single(info.from - 4) - }; - break; - } + const view = (_b2 = newLeaf.view.editor) == null ? void 0 : _b2.cm; + view.dispatch({ + annotations: [ + portalTypeAnnotation.of(evt.detail.type), + flowIDAnnotation.of(evt.detail.id) + ] + }); + view.dom.addEventListener("keydown", (e4) => { + if (e4.key == "ArrowUp") { + if (e4.metaKey == true) { + view.dispatch({ + annotations: arrowKeyAnnotation.of(3) + }); + } else { + view.dispatch({ + annotations: arrowKeyAnnotation.of(1) + }); + } + } + if (e4.key == "ArrowDown") { + if (e4.metaKey == true) { + view.dispatch({ + annotations: arrowKeyAnnotation.of(4) + }); + } else { + view.dispatch({ + annotations: arrowKeyAnnotation.of(2) + }); } } + }); + if (from && to) { + (_c2 = newLeaf.view.editor) == null ? void 0 : _c2.cm.dispatch({ + annotations: [editableRange.of([from, to])] + }); } - return tr; - } -); - -// src/components/ContextView/EmbedContextView.tsx -var import_obsidian28 = require("obsidian"); - -// src/components/ContextView/CardsView/CardsView.tsx -var import_classnames4 = __toESM(require_classnames()); - -// src/components/ContextView/CardsView/CardColumnView.tsx -var import_classnames2 = __toESM(require_classnames()); -var CardColumnView = k3( - ({ - id: id2, - children, - columns = 1, - handleProps, - horizontal, - hover, - onClick, - onRemove, + }); +}; +var spawnPortal = (plugin, parentLeaf, initiatingEl, fileName, onShowCallback) => { + const parent = parentLeaf != null ? parentLeaf : plugin.app.workspace.activeLeaf; + if (!initiatingEl) + initiatingEl = parent.containerEl; + const hoverPopover = new FlowEditor( + parent, + initiatingEl, plugin, - field, - label, - file, - placeholder, - style, - scrollable, - shadow, - unstyled, - ...props2 - }, ref) => { - const Component4 = "div"; - const { updateValue: updateValue2, updateFieldValue, contextTable } = q2(MDBContext); - return /* @__PURE__ */ Cn.createElement(Component4, { - ...props2, - ref, - style: { - ...style, - "--columns": columns - }, - className: (0, import_classnames2.default)( - "mk-list-group", - unstyled && "unstyled", - horizontal && "horizontal", - hover && "hover", - placeholder && "placeholder", - scrollable && "scrollable", - shadow && "shadow" - ), - onClick, - tabIndex: onClick ? 0 : void 0 - }, label != null && field ? /* @__PURE__ */ Cn.createElement("div", { - className: "mk-list-group-header" - }, /* @__PURE__ */ Cn.createElement(DataTypeView, { - initialValue: label, - plugin, - index: parseInt(id2) * -1, - file, - column: field, - editable: false, - updateValue: (value) => updateValue2( - field.name, - value, - field.table, - parseInt(id2) * -1, - file - ), - updateFieldValue: (value, fieldValue) => updateFieldValue( - field.name, - fieldValue, - value, - field.table, - parseInt(id2) * -1, - file - ), - contextTable - }), /* @__PURE__ */ Cn.createElement("div", { - className: "Actions", - ...handleProps - })) : null, placeholder ? children : /* @__PURE__ */ Cn.createElement("ul", null, children)); - } -); - -// src/components/ContextView/CardsView/CardView.tsx -var import_classnames3 = __toESM(require_classnames()); + void 0, + onShowCallback + ); + if (fileName) + hoverPopover.titleEl.textContent = fileName.substring( + 0, + fileName.lastIndexOf(".") + ); +}; -// src/components/FlowEditor/FlowView.tsx -var FlowView = (props2) => { - const ref = _2(null); - const loadFile = async () => { - const div = ref.current; - const { path: link, ref: refStr, type } = pathByString(props2.path); +// src/components/SpaceView/Editor/FlowView.tsx +var FlowView = k3((props2, ref2) => { + var _a2; + A2(ref2, () => ({ + triggerMenu(e4) { + var _a3, _b2; + if (((_b2 = (_a3 = leafRef.current) == null ? void 0 : _a3.view) == null ? void 0 : _b2.editor) && fileRef.current) { + const menu = new import_obsidian35.Menu(); + leafRef.current.view.onPaneMenu(menu, "more-options"); + if (isMouseEvent(e4)) { + menu.showAtPosition({ x: e4.pageX, y: e4.pageY }); + } else { + menu.showAtPosition({ + x: e4.nativeEvent.locationX, + y: e4.nativeEvent.locationY + }); + } + return false; + } + } + })); + const flowRef = _2(null); + const [existsPas, setExistsPas] = h2(false); + const [loaded, setLoaded] = h2(false); + const leafRef = _2(null); + const fileRef = _2(null); + const loadFile = async (force) => { + var _a3; + const div = flowRef.current; + let file; + const path = uriByString(props2.plugin, props2.path, props2.source); + const { ref: refStr, type } = path; + let from = props2.from; + let to = props2.to; + if (path.type == "file") { + file = getAbstractFileAtPath(props2.plugin, path.path); + if (!file) { + if (!force) { + setExistsPas(true); + setLoaded(false); + return; + } else { + file = await createMarkdownFileAtPath(props2.plugin, props2.path); + setExistsPas(false); + } + } else { + setExistsPas(false); + } + if (((_a3 = path.refStr) == null ? void 0 : _a3.length) > 0) { + [from, to] = getLineRangeFromRef(file, path.refStr, props2.plugin); + } + } + setLoaded(true); const portalType = type == "tag" || type == "folder" ? "context" : "doc"; await spawnLeafFromFile( props2.plugin, - link, + props2.leaf, + props2.source, + path, div, portalType, - refStr, - props2.from, - props2.to + from, + to, + file, + (leaf) => { + leafRef.current = leaf; + fileRef.current = file; + } ); }; const toggleFlow = () => { if (props2.load) { loadFile(); } else { - ref.current.empty(); + if (flowRef == null ? void 0 : flowRef.current) + flowRef.current.empty(); } }; p2(() => { toggleFlow(); }, [props2.load, props2.path, props2.from, props2.to]); - return /* @__PURE__ */ Cn.createElement("div", { - className: "mk-flowspace-editor", - ref - }); -}; + return /* @__PURE__ */ Cn.createElement(Cn.Fragment, null, /* @__PURE__ */ Cn.createElement("div", { + className: `${(_a2 = props2.classname) != null ? _a2 : ""} mk-flowspace-editor`, + ref: flowRef + }), existsPas ? /* @__PURE__ */ Cn.createElement("div", { + onClick: () => loadFile(true), + className: "mk-placeholder", + style: { color: "var(--text-faint)" } + }, "Create a Note") : /* @__PURE__ */ Cn.createElement(Cn.Fragment, null)); +}); +FlowView.displayName = "FlowView"; -// src/components/ContextView/CardsView/CardView.tsx -var CardView = Cn.memo( - Cn.forwardRef( - ({ - color, - dragOverlay, - dragging, - disabled, - fadeIn, - handle, - height, - index, - listeners, - selected, - onSelect, - onRemove, - renderItem, - plugin, - id: id2, - sorting, - style, - transition, - transform, - value, - cols, - wrapperStyle, - ...props2 - }, ref) => { - const onClickHandler = (e4) => { - if (!onSelect) { - return; - } - if (e4.detail === 1) { - onSelect( - { - metaKey: e4.metaKey, - ctrlKey: e4.ctrlKey, - altKey: e4.altKey, - shiftKey: e4.shiftKey - }, - value["_index"] - ); - } else if (e4.detail === 2) { - console.log(e4); - onSelect( - { - doubleClick: true, - metaKey: e4.metaKey, - ctrlKey: e4.ctrlKey, - altKey: e4.altKey - }, - value["_index"] - ); - } - }; - const { updateValue: updateValue2, updateFieldValue, contextTable } = q2(MDBContext); - p2(() => { - if (!dragOverlay) { - return; +// src/components/SpaceView/Frames/EditorNodes/FlowNodeView.tsx +function parseContent2(input) { + const regex1 = /!\[!\[(.*?)\]\]/; + const regex2 = /!!\[\[(.*?)\]\]/; + const match1 = input.match(regex1); + const match2 = input.match(regex2); + return match1 ? match1[1] : match2 ? match2[1] : input; +} +var FlowNodeView = (props2) => { + var _a2, _b2; + const fullPath = (_b2 = (_a2 = props2.instance.state[props2.treeNode.id]) == null ? void 0 : _a2.props) == null ? void 0 : _b2.value; + const path = fullPath ? parseContent2(fullPath) : null; + const { saveNodes } = q2(FramesEditorContext); + const selectLink = (e4) => { + showLinkMenu( + e4, + props2.plugin, + (link) => saveNodes([ + { + ...props2.treeNode.node, + props: { ...props2.treeNode.node.props, value: wrapQuotes(link) } } - document.body.style.cursor = "grabbing"; - return () => { - document.body.style.cursor = ""; - }; - }, [dragOverlay]); - const [openFlow, setOpenFlow] = h2(false); - return renderItem ? renderItem({ - dragOverlay: Boolean(dragOverlay), - dragging: Boolean(dragging), - sorting: Boolean(sorting), - index, - fadeIn: Boolean(fadeIn), - listeners, - ref, - style, - transform, - transition, - value - }) : /* @__PURE__ */ Cn.createElement("li", { - className: (0, import_classnames3.default)( - "mk-list-item", - fadeIn && "fadeIn", - sorting && "sorting", - dragOverlay && "dragOverlay", - selected && "mk-is-active" - ), - onClick: onClickHandler, - style: { - ...wrapperStyle, - transition, - "--translate-x": transform ? `${Math.round(transform.x)}px` : void 0, - "--translate-y": transform ? `${Math.round(transform.y)}px` : void 0, - "--scale-x": (transform == null ? void 0 : transform.scaleX) ? `${transform.scaleX}` : void 0, - "--scale-y": (transform == null ? void 0 : transform.scaleY) ? `${transform.scaleY}` : void 0, - "--index": index, - "--color": color - }, - ref - }, value && cols.filter((f4) => f4.type == "preview" && f4.table == "").map((f4) => /* @__PURE__ */ Cn.createElement(DataTypeView, { - row: value, - cols, - plugin, - initialValue: value[f4.name + f4.table], - column: f4, - index: parseInt(id2), - file: value[FilePropertyName], - editable: false, - updateValue: (v3) => updateValue2( - f4.name, - v3, - f4.table, - parseInt(id2), - value[FilePropertyName] - ), - updateFieldValue: (v3, fv) => updateFieldValue( - f4.name, - fv, - v3, - f4.table, - parseInt(id2), - value[FilePropertyName] - ), - contextTable - })), /* @__PURE__ */ Cn.createElement("div", { - className: "mk-list-content" - }, /* @__PURE__ */ Cn.createElement("div", { - className: (0, import_classnames3.default)( - "mk-list-fields", - dragging && "dragging", - handle && "withHandle", - dragOverlay && "dragOverlay", - disabled && "disabled", - color && "color" - ), - style, - "data-cypress": "draggable-item", - ...listeners, - ...props2, - tabIndex: !handle ? 0 : void 0 - }, value && cols.map((f4) => { - var _a2; - return ((_a2 = value[f4.name + f4.table]) == null ? void 0 : _a2.length) > 0 ? /* @__PURE__ */ Cn.createElement(DataTypeView, { - openFlow: () => setOpenFlow((o3) => !o3), - plugin, - initialValue: value[f4.name + f4.table], - column: f4, - index: parseInt(id2), - file: value[FilePropertyName], - editable: false, - updateValue: (v3) => updateValue2( - f4.name, - v3, - f4.table, - parseInt(id2), - value[FilePropertyName] - ), - updateFieldValue: (v3, fv) => updateFieldValue( - f4.name, - fv, - v3, - f4.table, - parseInt(id2), - value[FilePropertyName] - ), - contextTable - }) : /* @__PURE__ */ Cn.createElement(Cn.Fragment, null); - })), /* @__PURE__ */ Cn.createElement(FlowView, { - plugin, - path: value.File, - load: openFlow - }))); - } - ) -); - -// src/components/ContextView/CardsView/CardsView.tsx -var animateLayoutChanges = (args) => args.isSorting || args.wasDragging ? defaultAnimateLayoutChanges(args) : true; -function DroppableContainer({ - children, - columns = 1, - disabled, - id: id2, - items, - style, - ...props2 -}) { - var _a2; + ]) + ); + }; + return props2.instance.state[props2.treeNode.id] && path ? /* @__PURE__ */ Cn.createElement(Cn.Fragment, null, /* @__PURE__ */ Cn.createElement(FlowView, { + source: props2.source, + plugin: props2.plugin, + path, + load: true, + classname: "mk-flow-node", + ref: props2.menuRef + })) : /* @__PURE__ */ Cn.createElement("div", { + className: "mk-frame-placeholder", + onClick: (e4) => selectLink(e4) + }, "Select Note"); +}; + +// src/components/SpaceView/Frames/EditorNodes/FrameNodeView.tsx +var defaultFrameStyles = { + position: "relative" +}; +var FrameEditorNodeView = (props2) => { + var _a2, _b2; + return /* @__PURE__ */ Cn.createElement(Cn.Fragment, null, /* @__PURE__ */ Cn.createElement(Resizable, { + className: (0, import_classnames4.default)( + props2.column ? "mk-frame-column" : "mk-frame-bounds" + ), + enable: props2.column ? { right: true } : { + top: true, + right: true, + bottom: true, + left: true, + topRight: true, + bottomRight: true, + bottomLeft: true, + topLeft: true + }, + onResizeStop: (e4, direction, ref2, d5) => { + props2.resize({ + width: ref2.clientWidth, + height: props2.column ? "" : ref2.clientHeight + }); + }, + onResizeStart: (e4) => { + e4.stopPropagation(); + }, + size: { + width: (_a2 = props2.size.width) != null ? _a2 : "100%", + height: (_b2 = props2.size.height) != null ? _b2 : "100%" + }, + ...props2.listeners + })); +}; +var FrameNodeView = (props2) => { + var _a2, _b2, _c2, _d2, _e2, _f, _g, _h, _i, _j, _k, _l, _m, _n2, _o, _p, _q, _r, _s; + const { + selectedNodes, + saveState, + hoverNode, + saveNodes, + addNode, + deleteNode, + dragNode + } = q2(FramesEditorContext); + const { frameSchema } = q2(FramesMDBContext); const { - active, attributes, - isDragging, listeners, - over, - setNodeRef, - transition, + setNodeRef: setDraggableNodeRef, transform - } = useSortable({ - id: id2, + } = useDraggable({ + id: frameSchema.id + props2.treeNode.id, data: { - type: "container" + id: props2.treeNode.id, + type: "item", + parent: props2.treeNode.node.parentId, + frame: frameSchema.id }, - animateLayoutChanges + disabled: props2.treeNode.editorProps.dragMode == 0 }); - const isOverContainer = over ? id2 === over.id && ((_a2 = active == null ? void 0 : active.data.current) == null ? void 0 : _a2.type) !== "container" || items.includes(over.id) : false; - return /* @__PURE__ */ Cn.createElement(CardColumnView, { - id: id2, - ref: disabled ? void 0 : setNodeRef, - style: { - ...style, - transition, - transform: CSS.Translate.toString(transform), - opacity: isDragging ? 0.5 : void 0 - }, - hover: isOverContainer, - handleProps: { - ...attributes, - ...listeners + const { setNodeRef } = useDroppable({ + id: frameSchema.id + props2.treeNode.id, + data: { + id: props2.treeNode.id, + type: "item", + parent: props2.treeNode.node.parentId, + frame: frameSchema.id }, - columns, - ...props2 - }, children); -} -var PLACEHOLDER_ID = "placeholder"; -var CardsView = ({ - adjustScale: adjustScale2 = false, - itemCount = 3, - cancelDrop, - columns, - handle = false, - items: initialItems, - containerStyle, - getItemStyles = () => ({}), - wrapperStyle = () => ({}), - minimal = false, - modifiers, - renderItem, - strategy = verticalListSortingStrategy, - vertical = false, - scrollable, - plugin -}) => { - var _a2, _b2; - const { - tableData, - filteredData, - selectedRows, - selectRows, - sortedColumns: cols, - predicate, - updateValue: updateValue2, - contextTable, - schema, - saveDB: saveDB2, - saveContextDB - } = q2(MDBContext); - const groupBy2 = ((_a2 = predicate.groupBy) == null ? void 0 : _a2.length) > 0 ? cols.find((f4) => f4.name + f4.table == predicate.groupBy[0]) : null; - const displayCols = (_b2 = cols == null ? void 0 : cols.filter( - (f4) => !(f4.name == (groupBy2 == null ? void 0 : groupBy2.name) && f4.table == groupBy2.table) - )) != null ? _b2 : []; - const viewType = schema.type; - const items = F2(() => { - var _a3, _b3; - if (groupBy2) { - const options = uniq([ - "", - ...(_a3 = parseMultiString(groupBy2.value)) != null ? _a3 : [], - ...filteredData.reduce( - (p3, c4) => { - var _a4; - return [...p3, (_a4 = c4[groupBy2.name + groupBy2.table]) != null ? _a4 : ""]; - }, - [] - ) - ]); - return options.reduce( - (p3, c4) => { - return { - ...p3, - [c4]: filteredData.filter((r3) => r3[groupBy2.name + groupBy2.table] == c4).map((r3) => r3._index) - }; - }, - { "": [] } - ); - } - return { - "": (_b3 = filteredData == null ? void 0 : filteredData.map((r3) => r3._index)) != null ? _b3 : [] - }; - }, [filteredData, predicate]); - const containers = F2( - () => Object.keys(items).map((f4, i4) => "-" + i4.toString()), - [items] - ); - const [activeId, setActiveId] = h2(null); - const [overId, setOverId] = h2(null); - const recentlyMovedToNewContainer = _2(false); - const isSortingContainer = activeId ? containers.includes(activeId) : false; - const [lastSelectedIndex, setLastSelectedIndex] = h2(null); - const sensors = useSensors( - useSensor(MouseSensor, { - activationConstraint: { - distance: 10 - } - }), - useSensor(TouchSensor, { - activationConstraint: { - delay: 250, - tolerance: 5 + disabled: props2.treeNode.editorProps.dropMode == 0 + }); + const menuRef = _2(null); + const ref2 = _2(null); + const saveNodeValue = (values, node) => { + const newNodes = { + ...node, + props: { + ...node.props, + ...values } - }), - useSensor(KeyboardSensor, { - coordinateGetter: sortableKeyboardCoordinates - }) - ); - const findContainer = (id2) => { - if (id2.charAt(0) == "-") { - return id2; - } - return "-" + Object.keys(items).findIndex((key2) => items[key2].includes(id2)).toString(); - }; - const getIndex = (id2) => { - const container = findContainer(id2); - if (!container) { - return -1; - } - const index = items[Object.keys(items)[parseInt(container) * -1]].indexOf(id2); - return index; + }; + saveNodes([newNodes]); }; - const resetState = () => { - setActiveId(null); - setOverId(null); + const saveStyleValue = (values, node) => { + const newNodes = { + ...node, + styles: { + ...node.styles, + ...values + } + }; + saveNodes([newNodes]); }; - const onDragCancel = () => { - resetState(); + const isSelected = selectedNodes.some((f4) => props2.treeNode.id == f4.id); + const innerComponents = props2.treeNode.node.type == "text" ? /* @__PURE__ */ Cn.createElement(TextNodeView, { + treeNode: props2.treeNode, + instance: props2.instance, + editable: !props2.treeNode.isRef + }) : props2.treeNode.node.type == "icon" ? /* @__PURE__ */ Cn.createElement(IconNodeView, { + plugin: props2.plugin, + treeNode: props2.treeNode, + instance: props2.instance, + editable: !props2.treeNode.isRef + }) : props2.treeNode.node.type == "image" ? /* @__PURE__ */ Cn.createElement(ImageNodeView, { + treeNode: props2.treeNode, + instance: props2.instance, + editable: !props2.treeNode.isRef, + plugin: props2.plugin + }) : props2.treeNode.node.type == "space" ? /* @__PURE__ */ Cn.createElement(SpaceNodeView, { + treeNode: props2.treeNode, + instance: props2.instance, + plugin: props2.plugin, + editable: !props2.treeNode.isRef + }) : props2.treeNode.node.type == "flow" ? /* @__PURE__ */ Cn.createElement(FlowNodeView, { + treeNode: props2.treeNode, + instance: props2.instance, + plugin: props2.plugin, + editable: !props2.treeNode.isRef, + menuRef + }) : (props2.treeNode.node.type == "column" || props2.treeNode.node.type == "container") && props2.treeNode.children.length == 0 ? /* @__PURE__ */ Cn.createElement(RowPlaceholder, { + plugin: props2.plugin, + id: props2.treeNode.id, + parentId: props2.treeNode.node.parentId + }) : props2.treeNode.children.map((c4, i4) => /* @__PURE__ */ Cn.createElement(FrameNodeView, { + editMode: props2.editMode, + plugin: props2.plugin, + key: i4, + treeNode: c4, + instance: props2.instance + })); + const parseAs = (role) => role == "checkbox" || role == "text" || role == "range" || role == "number" ? "input" : role; + const tag = (_c2 = parseAs((_b2 = (_a2 = props2.instance.state[props2.treeNode.id]) == null ? void 0 : _a2.styles) == null ? void 0 : _b2.as)) != null ? _c2 : "div"; + const type = tag == "input" ? (_e2 = (_d2 = props2.instance.state[props2.treeNode.id]) == null ? void 0 : _d2.styles) == null ? void 0 : _e2.as : null; + const onResize = (size) => { + saveNodes([ + { + ...props2.treeNode.node, + styles: { ...props2.treeNode.node.styles, ...size } + } + ]); }; - p2(() => { - requestAnimationFrame(() => { - recentlyMovedToNewContainer.current = false; + const selectNode = (nodes) => { + const evt = new CustomEvent(eventTypes.frameLayerSelected, { + detail: { selection: nodes.map((f4) => f4.id) } }); - }, [items]); - const selectItem = (modifier, index) => { - if (platformIsMobile()) { - const file = getAbstractFileAtPath( - app, - tableData.rows[parseInt(index)].File - ); - if (file) - openAFile(file, plugin, false); - return; - } - if (modifier.doubleClick) { - const file = getAbstractFileAtPath( - app, - tableData.rows[parseInt(index)].File - ); - if (file) - openAFile( - file, - plugin, - modifier.ctrlKey || modifier.metaKey ? modifier.altKey ? "split" : "tab" : false - ); + window.dispatchEvent(evt); + }; + const onClick = (e4) => { + var _a3, _b3; + if (isSelected) return; - } else if (modifier.shiftKey) { - selectedRows.some((f4) => f4 == index) ? selectRows( - null, - selectedRows.filter((f4) => f4 != index) - ) : selectRows(index, uniq([...selectedRows, index])); - } else if (modifier.metaKey) { - selectRows( - index, - uniq([ - ...selectedRows, - ...selectRange( - lastSelectedIndex, - index, - filteredData.map((f4) => f4._index) - ) - ]) + if (typeof ((_a3 = props2.instance.state[props2.treeNode.id].actions) == null ? void 0 : _a3.onClick) == "function") { + (_b3 = props2.instance.state[props2.treeNode.id].actions) == null ? void 0 : _b3.onClick( + e4, + props2.instance.state, + (s5) => saveState(s5, props2.instance), + props2.plugin.index.api ); - } else { - selectRows(index, [index]); + e4.stopPropagation(); + } else if (props2.editMode > 1) { + if (e4.shiftKey) { + selectNode([ + ...selectedNodes.filter((f4) => f4.id != props2.treeNode.node.id), + props2.treeNode.node + ]); + } else { + selectNode([props2.treeNode.node]); + } + e4.stopPropagation(); } - setLastSelectedIndex(index); }; const onKeyDown = (e4) => { - if (e4.key == "Escape") { - selectRows(null, []); - setLastSelectedIndex(null); - } - if (e4.key == "Enter") { - const file = getAbstractFileAtPath( - app, - tableData.rows[parseInt(lastSelectedIndex)].File - ); - if (file) - openAFile(file, plugin, false); - return; - } - if (e4.key == "ArrowDown") { - const newIndex = selectNextIndex( - lastSelectedIndex, - filteredData.map((f4) => f4._index) - ); - selectRows(newIndex, [newIndex]); - setLastSelectedIndex(newIndex); - } - if (e4.key == "ArrowUp") { - const newIndex = selectPrevIndex( - lastSelectedIndex, - filteredData.map((f4) => f4._index) - ); - selectRows(newIndex, [newIndex]); - setLastSelectedIndex(newIndex); + if (e4.key == "Backspace" || e4.key == "Delete") { + deleteNode(props2.treeNode.node); } }; - return /* @__PURE__ */ Cn.createElement(DndContext, { - sensors, - collisionDetection: closestCenter, - measuring: { - droppable: { - strategy: MeasuringStrategy.Always - } - }, - onDragStart: ({ active }) => { - setActiveId(active.id); - }, - onDragOver: ({ active, over }) => { - const overId2 = over == null ? void 0 : over.id; - if (overId2) - setOverId(overId2); - }, - onDragEnd: ({ active, over }) => { - if (active.id in items && (over == null ? void 0 : over.id)) { - return; - } - const activeContainer = findContainer(active.id); - if (!activeContainer) { - resetState(); - return; - } - const overId2 = over == null ? void 0 : over.id; - if (!overId2) { - resetState(); - return; - } - if (overId2 === PLACEHOLDER_ID) { - return; - } - const overContainer = findContainer(overId2); - if (overContainer) { - const activeIndex = items[Object.keys(items)[parseInt(activeContainer) * -1]].indexOf(active.id); - const overIndex = items[Object.keys(items)[parseInt(overContainer) * -1]].indexOf(overId2); - if (activeContainer != overContainer) { - updateValue2( - groupBy2.name, - Object.keys(items)[parseInt(overContainer) * -1], - groupBy2.table, - groupBy2.table == "" ? parseInt(activeId) : parseInt( - filteredData.find((f4) => f4._index == activeId)["_index" + groupBy2.table] - ), - "" - ); - } + const canResize = isSelected && props2.treeNode.editorProps.resizeMode == 1 || props2.treeNode.editorProps.resizeMode == 2; + const dropMode = props2.treeNode.editorProps.dropMode; + const inner = tag == "input" ? /* @__PURE__ */ Cn.createElement("input", { + "data-path": props2.treeNode.id, + type, + onChange: (e4) => { + var _a3, _b3; + if (typeof ((_a3 = props2.instance.state[props2.treeNode.id].actions) == null ? void 0 : _a3.onChange) == "function") { + (_b3 = props2.instance.state[props2.treeNode.id].actions) == null ? void 0 : _b3.onChange( + e4.target.value, + props2.instance.state, + (s5) => saveState(s5, props2.instance), + props2.plugin.index.api + ); } - resetState(); }, - cancelDrop, - onDragCancel, - modifiers - }, /* @__PURE__ */ Cn.createElement("div", { - className: (0, import_classnames4.default)( - viewType == "card" ? "mk-cards-container" : "mk-list-container", - viewType == "card" && containers.length == 1 && "mk-cards-grid" - ), - onKeyDown - }, /* @__PURE__ */ Cn.createElement("div", { - className: "mk-list-view" - }, /* @__PURE__ */ Cn.createElement(SortableContext, { - items: [...containers, PLACEHOLDER_ID], - strategy: vertical ? verticalListSortingStrategy : horizontalListSortingStrategy - }, containers.map((containerId) => /* @__PURE__ */ Cn.createElement(DroppableContainer, { - key: containerId, - id: containerId, - plugin, - label: minimal ? void 0 : `${Object.keys(items)[parseInt(containerId) * -1]}`, - field: groupBy2, - columns, - items: items[Object.keys(items)[parseInt(containerId) * -1]], - scrollable, - style: containerStyle, - unstyled: minimal - }, /* @__PURE__ */ Cn.createElement(SortableContext, { - items: items[Object.keys(items)[parseInt(containerId) * -1]], - strategy - }, items[Object.keys(items)[parseInt(containerId) * -1]].map( - (value, index) => { - return /* @__PURE__ */ Cn.createElement(SortableItem2, { - disabled: isSortingContainer, - key: value, - id: value, - plugin, - value: filteredData.find((f4) => f4._index == value), - cols: displayCols, - index, - handle, - style: getItemStyles, - wrapperStyle, - renderItem, - onSelect: selectItem, - selected: selectedRows == null ? void 0 : selectedRows.some((f4) => f4 == value), - containerId, - getIndex - }); + style: { + "--translate-x": `${(_f = transform == null ? void 0 : transform.x) != null ? _f : 0}px`, + "--translate-y": `${(_g = transform == null ? void 0 : transform.y) != null ? _g : 0}px`, + ...(_h = props2.instance.state[props2.treeNode.id]) == null ? void 0 : _h.styles } - ))))))), z3( - /* @__PURE__ */ Cn.createElement(DragOverlay, { - adjustScale: adjustScale2 - }, activeId ? containers.includes(activeId) ? renderContainerDragOverlay(activeId) : renderSortableItemDragOverlay(activeId) : null), - document.body - )); - function renderSortableItemDragOverlay(id2) { - return /* @__PURE__ */ Cn.createElement("div", { - className: viewType == "card" ? "mk-cards-container" : "mk-list-container" - }, /* @__PURE__ */ Cn.createElement(CardView, { - plugin, - value: filteredData.find((f4) => f4._index == id2), - handle, - id: id2, - cols: displayCols, - style: getItemStyles({ - containerId: findContainer(id2), - overIndex: -1, - index: getIndex(id2), - value: id2, - isSorting: true, - isDragging: true, - isDragOverlay: true - }), - color: getColor(id2), - wrapperStyle: wrapperStyle({ index: 0 }), - renderItem, - dragOverlay: true - })); - } - function renderContainerDragOverlay(containerId) { - return /* @__PURE__ */ Cn.createElement(CardColumnView, { - id: containerId, - plugin, - label: `Column ${containerId}`, - field: groupBy2, - columns, - style: { - height: "100%" + }) : Cn.createElement( + tag, + { + type, + ref: (el) => { + ref2.current = el; }, - shadow: true, - unstyled: false - }, items[Object.keys(items)[parseInt(containerId) * -1]].map( - (item, index) => /* @__PURE__ */ Cn.createElement(CardView, { - key: item, - id: item, - plugin, - value: filteredData.find((f4) => f4._index == item), - cols: displayCols, - handle, - style: getItemStyles({ - containerId, - overIndex: -1, - index: getIndex(item), - value: item, - isDragging: false, - isSorting: false, - isDragOverlay: false - }), - color: getColor(item), - selected: selectedRows.some((f4) => f4 == item), - onSelect: selectItem, - wrapperStyle: wrapperStyle({ index }), - renderItem - }) - )); - } - function getNextContainerId() { - const containeIds = Object.keys(items); - const lastContaineId = containeIds[containeIds.length - 1]; - return String.fromCharCode(lastContaineId.charCodeAt(0) + 1); - } -}; -function getColor(id2) { - switch (id2[0]) { - case "A": - return "#7193f1"; - case "B": - return "#ffda6c"; - case "C": - return "#00bcd4"; - case "D": - return "#ef769f"; - } - return void 0; -} -function SortableItem2({ - disabled, - id: id2, - plugin, - index, - handle, - renderItem, - style, - containerId, - onSelect, - selected, - getIndex, - cols, - value, - wrapperStyle -}) { - const { - setNodeRef, - listeners, - isDragging, - isSorting, - over, - overIndex, - transform, - transition - } = useSortable({ - id: id2 - }); - const mounted = useMountStatus(); - const mountedWhileDragging = isDragging && !mounted; - return /* @__PURE__ */ Cn.createElement(CardView, { - ref: disabled ? void 0 : setNodeRef, - value, - plugin, - id: id2, - cols, - dragging: isDragging, - sorting: isSorting, - handle, - index, - wrapperStyle: wrapperStyle({ index }), - style: style({ - index, - value: id2, - isDragging, - isSorting, - overIndex: over ? getIndex(over.id) : overIndex, - containerId - }), - onSelect, - selected, - color: getColor(id2), - transition, - transform, - fadeIn: mountedWhileDragging, - listeners, - renderItem - }); -} -function useMountStatus() { - const [isMounted, setIsMounted] = h2(false); - p2(() => { - const timeout = setTimeout(() => setIsMounted(true), 500); - return () => clearTimeout(timeout); - }, []); - return isMounted; -} + className: `mk-frame ${(_k = (_j = (_i = props2.instance.state[props2.treeNode.id]) == null ? void 0 : _i.styles) == null ? void 0 : _j.class) != null ? _k : ""}`, + "data-path": props2.treeNode.id, + onClick, + style: { + ...defaultFrameStyles, + ...(_l = props2.instance.state[props2.treeNode.id]) == null ? void 0 : _l.styles, + "--translate-x": `${(_m = transform == null ? void 0 : transform.x) != null ? _m : 0}px`, + "--translate-y": `${(_n2 = transform == null ? void 0 : transform.y) != null ? _n2 : 0}px`, + ...props2.editMode == -1 && props2.treeNode.node.parentId == props2.instance.root.id ? { left: 0, top: 0 } : {} + } + }, + [ + ...[ + dragNode && props2.editMode > 0 && dropMode > 0 /* DropModeNone */ && /* @__PURE__ */ Cn.createElement(FrameEditorDropZone, { + parentId: props2.treeNode.node.parentId, + key: `|${props2.treeNode.node.id}`, + insertRow: hoverNode == props2.treeNode.id, + columnInsert: hoverNode == `|${props2.treeNode.node.id}`, + plugin: props2.plugin, + height: `100%`, + width: `${dropMode != 3 /* DropModeColumnOnly */ ? (_o = ref2.current) == null ? void 0 : _o.parentElement.clientWidth : (_p = ref2.current) == null ? void 0 : _p.clientWidth}px`, + id: `|${props2.treeNode.node.id}`, + mode: dropMode, + dropRef: setNodeRef + }) + ], + ...props2.editMode > 0 && canResize ? [ + /* @__PURE__ */ Cn.createElement(FrameEditorNodeView, { + key: props2.treeNode.id, + size: (_q = props2.instance.state[props2.treeNode.id]) == null ? void 0 : _q.styles, + column: props2.treeNode.node.type == "column", + resize: onResize + }) + ] : [], + ...props2.editMode > 0 && props2.treeNode.editorProps.dragMode == 2 && !isSelected ? [ + /* @__PURE__ */ Cn.createElement("div", { + key: props2.treeNode.id, + tabIndex: -1, + className: (0, import_classnames4.default)( + "mk-frame-bounds", + dragNode == props2.treeNode.id ? "is-selected" : "" + ), + onKeyDown, + ...listeners + }) + ] : [], + innerComponents + ] + ); + return props2.instance.state[props2.treeNode.id] && (props2.editMode != 0 && props2.treeNode.editorProps.dragMode == 1 ? /* @__PURE__ */ Cn.createElement(SelectableFrameNode, { + node: props2.treeNode.id, + maxWidth: (_s = (_r = props2.instance.state[props2.treeNode.id]) == null ? void 0 : _r.styles) == null ? void 0 : _s.maxWidth, + selected: selectedNodes.some((f4) => props2.treeNode.id == f4.id), + ...platformIsMobile() ? { + dragRef: setDraggableNodeRef, + listeners, + attributes + } : {} + }, selectedNodes.length == 1 && selectedNodes[0].id == props2.treeNode.id ? /* @__PURE__ */ Cn.createElement(HoverPropsMenu, { + plugin: props2.plugin, + node: props2.treeNode.node, + triggerMenu: (e4) => { + var _a3; + return (_a3 = menuRef == null ? void 0 : menuRef.current) == null ? void 0 : _a3.triggerMenu(e4); + }, + duplicateFrame: () => { + addNode(props2.treeNode.node, props2.treeNode.node); + }, + deleteFrame: () => deleteNode(props2.treeNode.node), + fields: propertiesForNode(props2.treeNode.node), + schemaProps: Object.keys(props2.instance.root.node.props).map( + (f4) => ({ + name: f4, + schemaId: props2.instance.root.id, + type: props2.instance.root.node.types[f4], + value: props2.instance.root.node.propsValue[f4] + }) + ), + savePropValue: (key2, value) => saveNodeValue({ [key2]: value }, props2.treeNode.node), + saveStyleValue: (key2, value) => saveStyleValue({ [key2]: value }, props2.treeNode.node) + }) : selectedNodes.length > 1 && selectedNodes[0].id == props2.treeNode.id && /* @__PURE__ */ Cn.createElement(HoverMultiMenu, { + plugin: props2.plugin + }), inner, !platformIsMobile() && /* @__PURE__ */ Cn.createElement(FrameHoverMenu, { + plugin: props2.plugin, + node: props2.treeNode.node, + dragRef: setDraggableNodeRef, + attributes, + listeners + })) : /* @__PURE__ */ Cn.createElement(Cn.Fragment, null, inner)); +}; +var SelectableFrameNode = (props2) => { + var _a2, _b2; + const ref2 = _2(null); + const { selectableNodeBounds, selectNodes } = q2(FramesEditorContext); + const resetSize = () => { + if (ref2.current) { + const { left, top, width, height } = ref2.current.getBoundingClientRect(); + selectableNodeBounds.current[props2.node] = { + left, + top, + width, + height + }; + } + }; + return /* @__PURE__ */ Cn.createElement("div", { + className: `mk-f ${props2.selected ? "is-selected" : ""}`, + onClick: () => !props2.selected && selectNodes([]), + ...(_a2 = props2.listeners) != null ? _a2 : {}, + ...(_b2 = props2.attributes) != null ? _b2 : {}, + style: { + ...props2.maxWidth ? { maxWidth: props2.maxWidth } : {} + } + }, props2.children); +}; -// src/components/ContextView/FlowListView/FlowListView.tsx -var import_obsidian27 = require("obsidian"); -var FlowListView = (props2) => { - const { filteredData: data } = q2(MDBContext); - const flowItems = F2(() => { - return data.map((f4) => getAbstractFileAtPath(app, f4.File)).filter((f4) => f4 instanceof import_obsidian27.TFile && f4.extension == "md"); - }, [data]); +// src/components/SpaceView/Frames/FrameEditorView.tsx +var import_obsidian36 = require("obsidian"); + +// src/components/SpaceView/Frames/Setters/CodeEditorSetter.tsx +var CodeEditorSetter = (props2) => { return /* @__PURE__ */ Cn.createElement("div", { - className: "mk-flow-container" - }, flowItems.map((f4) => /* @__PURE__ */ Cn.createElement("div", null, /* @__PURE__ */ Cn.createElement("span", null, fileNameToString(f4.name)), /* @__PURE__ */ Cn.createElement(FlowView, { - plugin: props2.plugin, - path: f4.path, - load: true - })))); + className: "mk-setter-code" + }, /* @__PURE__ */ Cn.createElement("div", { + onClick: () => props2.editCode(props2.node, props2.name, props2.type), + dangerouslySetInnerHTML: { __html: uiIconSet["mk-mark-code"] } + }), /* @__PURE__ */ Cn.createElement("div", { + className: "mk-setter-code-value" + }, props2.value)); }; -// src/components/ContextView/ContextListView.tsx -var ContextListView = (props2) => { - const { schema } = q2(MDBContext); - const [error, resetError] = P2(); - if (error) - console.log(error); - return schema ? schema.type == "flow" ? /* @__PURE__ */ Cn.createElement(FlowListView, { - plugin: props2.plugin - }) : schema.type == "table" ? /* @__PURE__ */ Cn.createElement(TableView, { - plugin: props2.plugin - }) : /* @__PURE__ */ Cn.createElement(CardsView, { - plugin: props2.plugin - }) : /* @__PURE__ */ Cn.createElement(Cn.Fragment, null); +// src/components/SpaceView/Frames/Panels/PropsPanel.tsx +var PropsPanel = (props2) => { + const { spaceInfo } = q2(SpaceContext); + const { saveNodes, root, selectedNodes } = q2(FramesEditorContext); + const saveContexts = (values, node) => { + const newRoot = { + ...node, + contexts: { + ...node.contexts, + ...values + } + }; + saveNodes([newRoot]); + }; + const saveNodeValue = (values, node) => { + const newNodes = { + ...node, + props: { + ...node.props, + ...values + } + }; + saveNodes([newNodes]); + }; + const saveRootProperty = (name) => { + saveProperty({ + schemaId: root.node.id, + type: "text", + name + }); + }; + const { properties: properties2, saveProperty, delProperty } = q2(FramesEditorContext); + const showMenu = (e4, field) => { + const offset2 = e4.target.getBoundingClientRect(); + showPropertyMenu({ + plugin: props2.plugin, + position: { x: offset2.left, y: offset2.top + 30 }, + editable: true, + options: [], + field: { ...field, table: "" }, + fields: properties2.map((f4) => ({ ...f4, table: "" })), + contextPath: spaceInfo.path, + saveField: (newField) => saveProperty(newField, field), + deleteColumn: delProperty, + editCode: () => props2.editCode(root.node.id, "props", field.name) + }); + }; + const showContextMenu = (e4) => { + const offset2 = e4.target.getBoundingClientRect(); + const f4 = loadTags(props2.plugin); + showSelectMenu( + { x: offset2.left, y: offset2.top + 30 }, + { + plugin: props2.plugin, + multi: false, + editable: true, + value: [], + options: f4.map((m5) => ({ name: m5, value: m5 })), + saveOptions: (_12, value) => addTag(value[0]), + placeholder: i18n_default.labels.contextItemSelectPlaceholder, + searchable: true, + showAll: true + } + ); + }; + const addTag = (tag) => { + saveContexts({ ...props2.contexts, [tag]: "" }, root.node); + }; + const [newProp, setNewProp] = h2(""); + return /* @__PURE__ */ Cn.createElement("div", { + className: "mk-file-context-component" + }, /* @__PURE__ */ Cn.createElement("div", { + className: "mk-file-context-title" + }, "Properties"), properties2.map((f4, i4) => /* @__PURE__ */ Cn.createElement("div", { + className: "mk-file-context-row", + key: i4 + }, /* @__PURE__ */ Cn.createElement("div", { + className: "mk-file-context-field", + onClick: (e4) => showMenu(e4, f4), + "aria-label": f4.type + }, f4.name), /* @__PURE__ */ Cn.createElement("div", { + className: "mk-file-context-value" + }, stringIsConst(root.node.props[f4.name]) ? /* @__PURE__ */ Cn.createElement(DataTypeView, { + plugin: props2.plugin, + initialValue: removeQuotes(root.node.props[f4.name]), + column: { ...f4, table: "" }, + editable: !spaceInfo.readOnly, + updateFieldValue: (fieldValue, value) => { + saveProperty({ ...f4, value: fieldValue }, f4); + saveNodeValue({ [f4.name]: `"${value}"` }, root.node); + }, + updateValue: (value) => saveNodeValue({ [f4.name]: `"${value}"` }, root.node) + }) : /* @__PURE__ */ Cn.createElement(CodeEditorSetter, { + name: f4.name, + value: root.node.props[f4.name], + type: "props", + node: root.id, + editCode: props2.editCode + })))), /* @__PURE__ */ Cn.createElement("div", null, /* @__PURE__ */ Cn.createElement(TextCell, { + initialValue: newProp, + saveValue: (value) => saveRootProperty(value), + editMode: 2 /* EditModeActive */, + setEditMode: () => null, + plugin: props2.plugin, + propertyValue: "" + }))); }; -// src/components/ContextView/EmbedContextViewComponent.tsx -var EmbedContextViewComponent = (props2) => { - const context = mdbContextByPath(props2.plugin, props2.path); - return /* @__PURE__ */ Cn.createElement(Cn.Fragment, null, context && /* @__PURE__ */ Cn.createElement(MDBProvider, { +// src/components/SpaceView/Frames/FrameEditor.tsx +var FrameEditor = (props2) => { + var _a2; + const activationConstraint = { + distance: { y: 0 }, + tolerance: { x: 0 } + }; + const mouseSensor = useSensor(MouseSensor, { + activationConstraint + }); + const touchSensor = useSensor(TouchSensor, { + activationConstraint + }); + const keyboardSensor = useSensor(KeyboardSensor, {}); + const sensors = useSensors(mouseSensor, touchSensor, keyboardSensor); + const [tab, setTab] = h2(0); + const { frameSchema } = q2(FramesMDBContext); + const [preselectedProp, setPreselectedProp] = h2(null); + const [preselectedPropType, setPreselectedPropType] = h2(null); + const { + root, + instance, + nodes, + saveNodes: saveFrames, + saveProperty, + setHoverNode, + selectNodes, + selectedNodes, + properties: properties2 + } = q2(FramesEditorContext); + const nodesSelected = (evt) => { + selectNodes( + evt.detail.selection.map((f4) => nodes.find((n2) => n2.id == f4)).filter((f4) => f4) + ); + }; + p2(() => { + window.addEventListener(eventTypes.frameLayerSelected, nodesSelected); + return () => { + window.removeEventListener(eventTypes.frameLayerSelected, nodesSelected); + }; + }, [nodes]); + const editCode = (node, key2, type) => { + setTab(1); + if (!((selectedNodes == null ? void 0 : selectedNodes.length) > 0)) { + if (selectedNodes[0].id != node) { + selectNodes(nodes); + } + } else { + } + setPreselectedProp(key2); + setPreselectedPropType(type); + }; + return /* @__PURE__ */ Cn.createElement(DndContext, { + sensors + }, /* @__PURE__ */ Cn.createElement("div", { + className: "mk-frame-editor" + }, /* @__PURE__ */ Cn.createElement("div", { + className: "mk-frame-container" + }, instance.root && /* @__PURE__ */ Cn.createElement("div", { + className: "mk-frame-main" + }, /* @__PURE__ */ Cn.createElement("div", { + className: "mk-frame-canvas" + }, /* @__PURE__ */ Cn.createElement("div", { + className: "mk-frame-props-editor" + }, /* @__PURE__ */ Cn.createElement(PropsPanel, { + contexts: (_a2 = root.node.contexts) != null ? _a2 : {}, plugin: props2.plugin, - context, - schema: props2.schema - }, /* @__PURE__ */ Cn.createElement("div", null, /* @__PURE__ */ Cn.createElement(ContextListView, { - plugin: props2.plugin - })))); + editCode + })), /* @__PURE__ */ Cn.createElement("div", { + className: "mk-frame-canvas-editor" + }, /* @__PURE__ */ Cn.createElement(FrameNodeView, { + editMode: 2, + plugin: props2.plugin, + treeNode: instance.root, + instance + }))))))); }; -// src/components/ContextView/EmbedContextView.tsx -var EMBED_CONTEXT_VIEW_TYPE = "make-inline-context"; -var EmbedContextView = class extends import_obsidian28.ItemView { - constructor(leaf, plugin) { +// src/components/SpaceView/Frames/FrameEditorView.tsx +var FRAME_EDITOR_TYPE = "mk-frame-editor"; +var openFrameEditor = async (plugin, path, schema) => { + const leaf = plugin.app.workspace.getLeaf(false); + plugin.openFileContextLeaf(); + const viewType = FRAME_EDITOR_TYPE; + plugin.app.workspace.setActiveLeaf(leaf, { focus: true }); + await leaf.setViewState({ + type: viewType, + state: { path, schema } + }); + await plugin.app.workspace.requestSaveLayout(); + if (path) { + const evt2 = new CustomEvent(eventTypes.activePathChange, { + detail: { path: uriByString(plugin, path) } + }); + window.dispatchEvent(evt2); + const evt = new CustomEvent(eventTypes.frameSelected, { + detail: { path: uriByString(plugin, path + "#*" + schema) } + }); + window.dispatchEvent(evt); + } +}; +var FrameEditorView = class extends import_obsidian36.ItemView { + constructor(leaf, plugin, viewType) { super(leaf); this.navigation = true; this.plugin = plugin; + this.viewType = viewType; } getViewType() { - return EMBED_CONTEXT_VIEW_TYPE; + return FRAME_EDITOR_TYPE; } getDisplayText() { - return this.contextPath; + var _a2; + return (_a2 = this.space) == null ? void 0 : _a2.name; } async onClose() { this.destroy(); @@ -40826,1790 +53554,2419 @@ var EmbedContextView = class extends import_obsidian28.ItemView { this.destroy(); } async setState(state, result) { - this.contextPath = state.contextPath; - this.ref = state.ref ? state.ref.substring(1, state.ref.length) : null; - this.constructInlineContext(this.contextPath); + this.space = spaceInfoByPath(this.plugin, state.path); + this.schema = state.schema; + if (!this.space) + return; + this.constructNote(this.space, this.schema); + const displayName = pathDisplayName(this.space.uri, this.plugin); await super.setState(state, result); - const context = mdbContextByPath(this.plugin, this.contextPath); - const title = contextDisplayName(context); - this.leaf.tabHeaderInnerTitleEl.innerText = title; - this.leaf.view.titleEl = title; + this.leaf.tabHeaderInnerTitleEl.innerText = displayName; + this.leaf.view.titleEl = displayName; const headerEl = this.leaf.view.headerEl; if (headerEl) { - headerEl.querySelector(".view-header-title").innerText = title; + headerEl.querySelector(".view-header-title").innerText = displayName; } + result.history = true; return; } getState() { - let state = super.getState(); - state.contextPath = this.contextPath; + var _a2, _b2; + const state = super.getState(); + state.path = (_b2 = (_a2 = this.space) == null ? void 0 : _a2.uri) == null ? void 0 : _b2.fullPath; + state.schema = this.schema; return state; } - constructInlineContext(file) { + constructNote(space, schema) { this.destroy(); this.root = createRoot(this.contentEl); this.root.render( - /* @__PURE__ */ Cn.createElement("div", null, /* @__PURE__ */ Cn.createElement(EmbedContextViewComponent, { + /* @__PURE__ */ Cn.createElement("div", { + className: "mk-space-view" + }, /* @__PURE__ */ Cn.createElement(SpaceContextProvider, { plugin: this.plugin, - path: this.contextPath, - schema: this.ref - })) + space + }, /* @__PURE__ */ Cn.createElement(FramesMDBProvider, { + plugin: this.plugin, + schema + }, /* @__PURE__ */ Cn.createElement(FramesEditorProvider, { + plugin: this.plugin, + props: {}, + editMode: 2 + }, /* @__PURE__ */ Cn.createElement(FrameEditor, { + plugin: this.plugin + }))))) ); } }; -// src/components/FlowEditor/FlowEditor.tsx -var import_obsidian29 = require("obsidian"); -var popovers = /* @__PURE__ */ new WeakMap(); -var mouseCoords = { x: 0, y: 0 }; -function nosuper(base) { - const derived = function() { - return Object.setPrototypeOf(new import_obsidian29.Component(), new.target.prototype); - }; - derived.prototype = base.prototype; - return Object.setPrototypeOf(derived, base); -} -var _a, _b, _c, _d, _e; -var FlowEditor = class extends nosuper(import_obsidian29.HoverPopover) { - constructor(parent, targetEl, plugin, waitTime, onShowCallback) { - super(); - this.targetEl = targetEl; - this.plugin = plugin; - this.onShowCallback = onShowCallback; - this.abortController = this.addChild(new import_obsidian29.Component()); - this.detaching = false; - this.opening = false; - this.rootSplit = new import_obsidian29.WorkspaceSplit( - window.app.workspace, - "vertical" - ); - this.targetRect = (_a = this.targetEl) == null ? void 0 : _a.getBoundingClientRect(); - this.oldPopover = (_b = this.parent) == null ? void 0 : _b.flowEditor; - this.document = (_e = (_d = (_c = this.targetEl) == null ? void 0 : _c.ownerDocument) != null ? _d : window.activeDocument) != null ? _e : window.document; - this.id = genId(); - this.hoverEl = this.document.defaultView.createDiv({ - cls: "mk-floweditor mk-hover-popover", - attr: { id: "he" + this.id } - }); - if (waitTime === void 0) { - waitTime = 300; - } - this.onTarget = true; - this.parent = parent; - this.waitTime = waitTime; - this.state = import_obsidian29.PopoverState.Showing; - const { hoverEl } = this; - this.abortController.load(); - this.timer = window.setTimeout(this.show.bind(this), waitTime); - this.setActive = this._setActive.bind(this); - if (hoverEl) { - hoverEl.addEventListener("mousedown", this.setActive); - hoverEl.addEventListener("mousedown", (e4) => e4.stopPropagation()); - } - popovers.set(this.hoverEl, this); - this.hoverEl.addClass("hover-editor"); - this.containerEl = this.hoverEl.createDiv("popover-content"); - this.setTitleBar(); - this.hoverEl.style.height = "auto"; - this.hoverEl.style.width = "100%"; - this.hoverEl.addEventListener("keydown", (e4) => e4.stopPropagation()); +// src/components/UI/modals/saveViewModal.ts +var import_obsidian37 = require("obsidian"); +var SaveViewModal = class extends import_obsidian37.Modal { + constructor(schema, saveSchema, action) { + super(app); + this.schema = schema; + this.saveSchema = saveSchema; + this.action = action; } - static activeWindows() { - const windows = [window]; - const { floatingSplit } = app.workspace; - if (floatingSplit) { - for (const split of floatingSplit.children) { - if (split.win) - windows.push(split.win); + onOpen() { + const { contentEl } = this; + let headerText; + if (this.action == "new view") + headerText = i18n_default.labels.saveView; + if (this.action == "rename view") + headerText = i18n_default.labels.renameView; + const headerEl = contentEl.createEl("div", { text: headerText }); + headerEl.addClass("modal-title"); + const inputEl = contentEl.createEl("input"); + inputEl.style.cssText = "width: 100%; height: 2.5em; margin-bottom: 15px;"; + inputEl.focus(); + let changeButtonText; + if (this.action == "new view") + changeButtonText = i18n_default.buttons.saveView; + if (this.action == "rename view") + changeButtonText = i18n_default.buttons.renameView; + const changeButton = contentEl.createEl("button", { + text: changeButtonText + }); + const cancelButton = contentEl.createEl("button", { + text: i18n_default.buttons.cancel + }); + cancelButton.style.cssText = "float: right;"; + cancelButton.addEventListener("click", () => { + this.close(); + }); + const onClickAction = async () => { + const newName = inputEl.value; + if (this.action == "new view") { + this.saveSchema({ ...this.schema, id: newName.replace(/ /g, "_"), name: newName }); + } else { + this.saveSchema({ ...this.schema, name: newName }); } - } - return windows; - } - static containerForDocument(doc) { - if (doc !== document && app.workspace.floatingSplit) - for (const container of app.workspace.floatingSplit.children) { - if (container.doc === doc) - return container; + this.close(); + }; + changeButton.addEventListener("click", onClickAction); + inputEl.addEventListener("keydown", (e4) => { + if (e4.key === "Enter") { + e4.preventDefault(); + onClickAction(); } - return app.workspace.rootSplit; - } - static activePopovers() { - return this.activeWindows().flatMap(this.popoversForWindow); - } - static popoversForWindow(win) { - var _a2, _b2; - return Array.prototype.slice.call( - (_b2 = (_a2 = win == null ? void 0 : win.document) == null ? void 0 : _a2.body.querySelectorAll(".mk-hover-popover")) != null ? _b2 : [] - ).map((el) => popovers.get(el)).filter((he2) => he2); - } - static forLeaf(leaf) { - const el = leaf && document.body.matchParent.call(leaf.containerEl, ".mk-hover-popover"); - return el ? popovers.get(el) : void 0; - } - _setActive() { - this.plugin.app.workspace.setActiveLeaf(this.leaves()[0], { focus: true }); - } - getDefaultMode() { - var _a2, _b2; - return ((_b2 = (_a2 = this.parent) == null ? void 0 : _a2.view) == null ? void 0 : _b2.getMode) ? this.parent.view.getMode() : "preview"; - } - updateLeaves() { - if (this.onTarget && this.targetEl && !this.document.contains(this.targetEl)) { - this.onTarget = false; - this.transition(); - } - let leafCount = 0; - this.plugin.app.workspace.iterateLeaves((leaf) => { - leafCount++; - }, this.rootSplit); - if (leafCount === 0) { - this.hide(); - } else if (leafCount > 1) { - } - this.hoverEl.setAttribute("data-leaf-count", leafCount.toString()); - } - setTitleBar() { - this.titleEl = this.document.defaultView.createDiv("mk-flow-titlebar"); - this.containerEl.prepend(this.titleEl); - } - attachLeaf() { - this.rootSplit.getRoot = () => this.plugin.app.workspace[this.document === document ? "rootSplit" : "floatingSplit"]; - this.rootSplit.getContainer = () => FlowEditor.containerForDocument(this.document); - this.titleEl.insertAdjacentElement("afterend", this.rootSplit.containerEl); - let leaf = this.plugin.app.workspace.createLeafInParent(this.rootSplit, 0); - leaf.isFlowBlock = true; - this.updateLeaves(); - return leaf; - } - onload() { - super.onload(); - this.registerEvent( - this.plugin.app.workspace.on("layout-change", this.updateLeaves, this) - ); - this.registerEvent( - app.workspace.on("layout-change", () => { - this.rootSplit.children.forEach((item, index) => { - if (item instanceof import_obsidian29.WorkspaceTabs) { - this.rootSplit.replaceChild(index, item.children[0]); - } - }); - }) - ); + }); } - leaves() { - const leaves = []; - this.plugin.app.workspace.iterateLeaves((leaf) => { - leaves.push(leaf); - }, this.rootSplit); - return leaves; + onClose() { + const { contentEl } = this; + contentEl.empty(); } - async onShow() { - var _a2, _b2; - const closeDelay = 600; - setTimeout(() => this.waitTime = closeDelay, closeDelay); - (_a2 = this.oldPopover) == null ? void 0 : _a2.hide(); - this.oldPopover = null; - this.hoverEl.toggleClass("is-new", true); - this.document.body.addEventListener( - "click", - () => { - this.hoverEl.toggleClass("is-new", false); - }, - { once: true, capture: true } +}; + +// src/components/SpaceView/Contexts/ContextBuilder/ContextFrameView.tsx +var PLACEHOLDER_ID2 = "_placeholder"; +var ContextFrameView = (props2) => { + const { predicate, savePredicate, cols, data: data2 } = q2(ContextEditorContext); + const { frameSchemas, saveSchema } = q2(FramesMDBContext); + const { spaceInfo } = q2(SpaceContext); + const selectedFrame = (predicate == null ? void 0 : predicate.frame) ? uriByString(props2.plugin, predicate.frame).ref : null; + const selectFrame = (frameRef) => { + savePredicate({ ...predicate, view: "frame", frame: frameRef }); + }; + const setFrameProps = (frameProps) => { + savePredicate({ ...predicate, frameProps }); + }; + const newSchema = (schema) => { + selectFrame(schema.id); + saveSchema(schema); + }; + const addFrame = () => { + const vaultChangeModal = new SaveViewModal( + { name: "", type: "listitem", id: "frame" }, + newSchema, + "new view" ); - if (this.parent) { - this.parent.flowEditor = this; - } - await ((_b2 = this.onShowCallback) == null ? void 0 : _b2.call(this, this)); - this.onShowCallback = void 0; - const viewHeaderEl = this.hoverEl.querySelector(".view-header"); - viewHeaderEl == null ? void 0 : viewHeaderEl.remove(); - const sizer = this.hoverEl.querySelector(".workspace-leaf"); - if (sizer) - this.hoverEl.appendChild(sizer); - const inlineTitle = this.hoverEl.querySelector(".inline-title"); - inlineTitle == null ? void 0 : inlineTitle.remove(); - } - transition() { - if (this.shouldShow()) { - if (this.state === import_obsidian29.PopoverState.Hiding) { - this.state = import_obsidian29.PopoverState.Shown; - clearTimeout(this.timer); - } - } else { - if (this.state === import_obsidian29.PopoverState.Showing) { - this.hide(); - } else { - if (this.state === import_obsidian29.PopoverState.Shown) { - this.state = import_obsidian29.PopoverState.Hiding; - this.timer = window.setTimeout(() => { - if (this.shouldShow()) { - this.transition(); - } else { - this.hide(); - } - }, this.waitTime); - } + vaultChangeModal.open(); + }; + const sensors = useSensors( + useSensor(MouseSensor, { + activationConstraint: { + distance: 10 } - } - } - shouldShow() { - return this.shouldShowSelf() || this.shouldShowChild(); - } - shouldShowChild() { - return FlowEditor.activePopovers().some((popover) => { - if (popover !== this && popover.targetEl && this.hoverEl.contains(popover.targetEl)) { - return popover.shouldShow(); + }), + useSensor(TouchSensor, { + activationConstraint: { + delay: 250, + tolerance: 5 } - return false; + }), + useSensor(KeyboardSensor, { + coordinateGetter: sortableKeyboardCoordinates + }) + ); + const saveViewType = (type) => { + savePredicate({ + ...predicate, + view: type, + frame: "" }); - } - shouldShowSelf() { - return !this.detaching && !!(this.onTarget || this.state == import_obsidian29.PopoverState.Shown || this.document.querySelector( - `body>.modal-container, body > #he${this.id} ~ .menu, body > #he${this.id} ~ .suggestion-container` - )); - } - show() { - if (!this.targetEl || this.document.body.contains(this.targetEl)) { - this.state = import_obsidian29.PopoverState.Shown; - this.timer = 0; - this.shownPos = mouseCoords; - this.targetEl.replaceChildren(this.hoverEl); - this.onShow(); - app.workspace.onLayoutChange(); - this.load(); - } else { - this.hide(); - } - } - onHide() { - var _a2; - this.oldPopover = null; - if (((_a2 = this.parent) == null ? void 0 : _a2.flowEditor) === this) { - this.parent.flowEditor = null; - } - } - hide() { - var _a2; - this.onTarget = false; - this.detaching = true; - if (this.timer) { - clearTimeout(this.timer); - this.timer = 0; - } - this.hoverEl.hide(); - if (this.opening) - return; - const leaves = this.leaves(); - if (leaves.length) { - leaves.forEach((leaf) => leaf.detach()); - } else { - this.parent = null; - (_a2 = this.abortController) == null ? void 0 : _a2.unload(); - this.abortController = void 0; - return this.nativeHide(); + }; + return /* @__PURE__ */ Cn.createElement(Cn.Fragment, null, /* @__PURE__ */ Cn.createElement("div", { + className: "mk-context-view-editor" + }, selectedFrame ? /* @__PURE__ */ Cn.createElement(DndContext, { + sensors, + measuring: { + droppable: { + strategy: MeasuringStrategy.Always + } } - } - nativeHide() { + }, /* @__PURE__ */ Cn.createElement(FramesMDBProvider, { + plugin: props2.plugin, + schema: selectedFrame + }, /* @__PURE__ */ Cn.createElement(FramesEditorProvider, { + plugin: props2.plugin, + props: data2[0], + editMode: 1 + }, /* @__PURE__ */ Cn.createElement(FrameListView, { + plugin: props2.plugin, + cols + })))) : predicate.view == "table" ? /* @__PURE__ */ Cn.createElement("div", { + className: "mk-table" + }, /* @__PURE__ */ Cn.createElement("table", null, /* @__PURE__ */ Cn.createElement("tr", null, cols.map((f4, i4) => /* @__PURE__ */ Cn.createElement("th", { + key: i4, + className: "mk-th" + }, /* @__PURE__ */ Cn.createElement("div", { + className: "mk-col-header" + }, f4.name)))), /* @__PURE__ */ Cn.createElement("tr", null, cols.map((f4, i4) => { var _a2; - const { hoverEl, targetEl } = this; - this.state = import_obsidian29.PopoverState.Hidden; - hoverEl.detach(); - if (targetEl) { - const parent = targetEl.matchParent(".mk-hover-popover"); - if (parent) - (_a2 = popovers.get(parent)) == null ? void 0 : _a2.transition(); - } - this.onHide(); - this.unload(); - } - resolveLink(linkText, sourcePath) { - const link = (0, import_obsidian29.parseLinktext)(linkText); - const tFile = link ? this.plugin.app.metadataCache.getFirstLinkpathDest( - link.path, - sourcePath != null ? sourcePath : "" - ) : null; - return tFile; - } - async openContext(file, openState, useLeaf) { - if (this.detaching) - return; - const leaf = useLeaf != null ? useLeaf : this.attachLeaf(); - this.opening = true; - try { - await leaf.openFile(file, openState); - } catch (e4) { - console.error(e4); - } finally { - this.opening = false; - if (this.detaching) - this.hide(); - } - return leaf; - } - async openFile(file, openState, useLeaf) { - if (this.detaching) - return; - const leaf = useLeaf != null ? useLeaf : this.attachLeaf(); - this.opening = true; - try { - await leaf.openFile(file, openState); - } catch (e4) { - console.error(e4); - } finally { - this.opening = false; - if (this.detaching) - this.hide(); - } - return leaf; - } - buildState(parentMode, eState) { - return { - active: false, - state: {}, - eState - }; - } - buildEphemeralState(file, link) { - const cache = this.plugin.app.metadataCache.getFileCache(file); - const subpath = cache ? (0, import_obsidian29.resolveSubpath)(cache, (link == null ? void 0 : link.subpath) || "") : void 0; - const eState = { subpath: link == null ? void 0 : link.subpath }; - if (subpath) { - eState.line = subpath.start.line; - eState.startLoc = subpath.start; - eState.endLoc = subpath.end || void 0; + return /* @__PURE__ */ Cn.createElement("td", { + key: i4, + className: "mk-td" + }, /* @__PURE__ */ Cn.createElement(DataTypeView, { + column: f4, + editable: false, + initialValue: (_a2 = data2[0]) == null ? void 0 : _a2[f4.name], + row: data2[0], + plugin: props2.plugin + })); + })))) : /* @__PURE__ */ Cn.createElement(Cn.Fragment, null)), /* @__PURE__ */ Cn.createElement("div", { + className: "mk-context-view-selector" + }, /* @__PURE__ */ Cn.createElement("div", { + onClick: () => saveViewType("table") + }, /* @__PURE__ */ Cn.createElement("div", { + dangerouslySetInnerHTML: { + __html: stickerFromString("lucide//table-2", props2.plugin) } - return eState; - } -}; - -// src/utils/flow/flowEditor.ts -var import_obsidian30 = require("obsidian"); -var parseOutReferences = (ostr) => { - const str = ostr.split("|")[0]; - const refIndex = str.lastIndexOf("#"); - return refIndex > 0 ? [str.substring(0, refIndex), str.substring(refIndex + 1)] : [str, void 0]; -}; -var getFileFromString = (url, source) => { - return app.metadataCache.getFirstLinkpathDest(url, source != null ? source : ""); -}; -var getLineRangeFromRef = (file, ref, plugin) => { - var _a2; - if (!ref) { - return [void 0, void 0]; - } - const cache = app.metadataCache.getFileCache(file); - const headings = cache.headings; - const blocks = cache.blocks; - const sections = cache.sections; - if (blocks && ref.charAt(0) == "^" && blocks[ref.substring(1)]) { - return [ - blocks[ref.substring(1)].position.start.line + 1, - blocks[ref.substring(1)].position.end.line + 1 - ]; - } - const heading = headings == null ? void 0 : headings.find((f4) => f4.heading.replace("#", " ") == ref); - if (heading) { - const index = headings.findIndex((f4) => f4.heading == heading.heading); - const level = (_a2 = headings[index]) == null ? void 0 : _a2.level; - const nextIndex2 = headings.findIndex( - (f4, i4) => i4 > index && f4.level <= level - ); - const start = plugin.settings.editorFlowStyle == "classic" ? heading.position.start.line + 1 : heading.position.start.line + 2; - if (index < headings.length - 1 && nextIndex2 != -1) { - return [start, headings[nextIndex2].position.end.line]; + }), "Table"), /* @__PURE__ */ Cn.createElement("div", { + onClick: () => saveViewType("list") + }, /* @__PURE__ */ Cn.createElement("div", { + dangerouslySetInnerHTML: { + __html: stickerFromString("lucide//layout-list", props2.plugin) } - return [start, sections[sections.length - 1].position.end.line + 1]; - } - return [void 0, void 0]; -}; -var loadFlowEditorByDOM2 = (make, el, view, id2) => { - setTimeout(async () => { - let counter = 0; - while (!el.parentElement && counter++ <= 50) - await sleep(50); - if (!el.parentElement) - return; - let dom = el; - while (!dom.hasClass("mk-floweditor") && !dom.hasClass("workspace") && dom.parentElement) { - dom = dom.parentElement; + }), "List"), /* @__PURE__ */ Cn.createElement("div", { + onClick: () => saveViewType("card") + }, /* @__PURE__ */ Cn.createElement("div", { + dangerouslySetInnerHTML: { + __html: stickerFromString("lucide//layout-grid", props2.plugin) } - if (!dom.hasClass("mk-floweditor") && !dom.hasClass("workspace") && !(dom.nodeName == "HTML")) { - return; + }), "Card"), /* @__PURE__ */ Cn.createElement("div", { + onClick: () => saveViewType("flow") + }, /* @__PURE__ */ Cn.createElement("div", { + dangerouslySetInnerHTML: { + __html: stickerFromString("lucide//infinity", props2.plugin) } - setTimeout(async () => { - var _a2, _b2, _c2; - let leafFound = false; - if (app.workspace.activeEditor) { - if (((_b2 = (_a2 = app.workspace.activeEditor) == null ? void 0 : _a2.editor) == null ? void 0 : _b2.cm.dom) == view.dom) { - leafFound = true; - loadFlowEditorsForLeafForID( - app.workspace.activeEditor.editor.cm, - (_c2 = app.workspace.activeEditor.file) == null ? void 0 : _c2.path, - make, - id2 - ); + }), "Flow"), frameSchemas.filter((f4) => f4.type == "listitem").map((f4, i4) => /* @__PURE__ */ Cn.createElement("div", { + key: i4, + onClick: () => selectFrame(`${spaceInfo.path}/#^${f4.id}`), + onContextMenu: () => openFrameEditor(props2.plugin, spaceInfo.path, f4.id) + }, /* @__PURE__ */ Cn.createElement("div", { + dangerouslySetInnerHTML: { + __html: stickerFromString("lucide//square", props2.plugin) + } + }), f4.name)), /* @__PURE__ */ Cn.createElement("div", { + onClick: () => addFrame() + }, /* @__PURE__ */ Cn.createElement("div", { + dangerouslySetInnerHTML: { + __html: stickerFromString("lucide//plus", props2.plugin) + } + }), "New"))); +}; +var FrameListView = (props2) => { + const { frameSchema } = q2(FramesMDBContext); + const { + instance, + root, + saveState, + hoverNode, + setHoverNode, + dragNode, + moveToRank, + nodes, + setDragNode, + addNode, + saveNodes, + moveNodeFromSchema + } = q2(FramesEditorContext); + const _instance = F2(() => { + return instance ? { + ...instance, + root: instance.root ? { + ...instance.root, + node: { + ...instance.root.node, + props: props2.cols.reduce( + (p3, c4) => ({ + ...p3, + [c4.name]: "" + }), + {} + ) } + } : null + } : null; + }, [props2.cols, instance]); + const activeRunID = _2(null); + p2( + () => () => { + activeRunID.current = null; + }, + [] + ); + const resetState = () => { + setHoverNode(null); + setDragNode(null); + }; + const getDragLayer = () => { + var _a2; + if (dragNode === null) { + return null; + } + const node = (_a2 = findParent(instance.root, dragNode)) == null ? void 0 : _a2.children.find( + (f4) => f4.id == dragNode + ); + if (!node) + return null; + return /* @__PURE__ */ Cn.createElement(FrameNodeView, { + editMode: 1, + plugin: props2.plugin, + treeNode: node, + instance + }); + }; + useDndMonitor({ + onDragStart({ active }) { + if (active.data.current.frame == frameSchema.id) + setDragNode(active.data.current.id); + }, + onDragOver({ active, over }) { + const overId = over == null ? void 0 : over.data.current.id; + if ((over == null ? void 0 : over.data.current.frame) == frameSchema.id) { + if (overId) + setHoverNode(overId); } - if (!leafFound) { - app.workspace.iterateLeaves((leaf) => { - var _a3, _b3; - const cm = (_a3 = leaf.view.editor) == null ? void 0 : _a3.cm; - if (cm && view.dom == cm.dom) { - leafFound = true; - loadFlowEditorsForLeafForID( - cm, - (_b3 = leaf.view.file) == null ? void 0 : _b3.path, - make, - id2 - ); - } - }, app.workspace["rootSplit"]); + }, + onDragCancel() { + resetState(); + }, + onDragEnd({ active, over }) { + if (!active) { + resetState(); + return; } - }); - }); -}; -var loadFlowEditorsForLeafForID = (cm, source, make, id2) => { - const stateField = cm.state.field(flowEditorInfo, false); - if (!stateField) - return; - const flowInfo = stateField.find((f4) => f4.id == id2); - if (flowInfo && flowInfo.expandedState == 2) { - loadFlowEditor(cm, flowInfo, source, make); - } -}; -var loadFlowEditor = (cm, flowEditorInfo2, source, make) => { - const dom = cm.dom.querySelector( - "#mk-flow-" + flowEditorInfo2.id - ); - const { path, type, ref } = pathByString(flowEditorInfo2.link, source); - if (dom) { - if (type == "folder" || type == "tag" || type == "space") { - const context = mdbContextByPath( - make, - path - ); - if (!dom.hasAttribute("ready")) { - dom.setAttribute("ready", ""); - createFlowEditorInElement( - flowEditorInfo2.id, - dom, - "context", - context.contextPath, - ref - ); + let overId = hoverNode; + let overNewColumn = false; + if ((overId == null ? void 0 : overId.charAt(0)) == "|") { + overId = overId.substring(1); + overNewColumn = true; + } + if (overId == active.data.current.id) { + resetState(); return; } - } else if (type == "file") { - const file = getFileFromString(path, source); - const aFile = getAbstractFileAtPath(app, path); - if (file) { - const selectiveRange = getLineRangeFromRef(file, ref, make); - if (!dom.hasAttribute("ready")) { - dom.setAttribute("ready", ""); - createFlowEditorInElement( - flowEditorInfo2.id, - dom, - ref ? "block" : "flow", - file.path, - ref, - selectiveRange[0], - selectiveRange[1] + const overParentNode = findParent(instance.root, overId); + const overNode = overParentNode == null ? void 0 : overParentNode.children.find( + (f4) => f4.id == overId + ); + const activeParentNode = findParent( + instance.root, + active.data.current.id + ); + const activeNode = activeParentNode == null ? void 0 : activeParentNode.children.find( + (f4) => f4.id == active.data.current.id + ); + if (overNewColumn) { + if (overNode.node.type == "column") { + const column = { + ...newUniqueNode(columnNode, overParentNode.id, [], frameSchema.id), + rank: overNode.node.rank > activeNode.node.rank ? overNode.node.rank : overNode.node.rank + 1 + }; + const nodes2 = [column, { ...activeNode.node, parentId: column.id }]; + if (active.data.current.frame != frameSchema.id) { + saveNodes([column]).then( + () => moveNodeFromSchema( + active.data.current.id, + active.data.current.frame, + column.id, + { + position: `'relative'`, + left: "0", + top: "0" + } + ) + ); + } else { + saveNodes(nodes2); + } + } else { + const newColumns = newUniqueNode( + columnsNode, + overParentNode.id, + nodes, + frameSchema.id ); - } - } else { - if (aFile instanceof import_obsidian30.TFolder) { - if (!dom.hasAttribute("ready")) { - dom.setAttribute("ready", ""); - createFlowEditorInElement( - flowEditorInfo2.id, - dom, - ref ? "block" : "flow", - path + const column1 = newUniqueNode( + columnNode, + newColumns.id, + [...nodes, newColumns], + frameSchema.id + ); + const column2 = newUniqueNode( + columnNode, + newColumns.id, + [...nodes, newColumns, column1], + frameSchema.id + ); + const newNodes = [ + newColumns, + column1, + column2, + { ...overNode.node, parentId: column1.id } + ]; + if (active.data.current.frame != frameSchema.id) { + saveNodes(newNodes).then( + () => moveNodeFromSchema( + active.data.current.id, + active.data.current.frame, + column2.id, + { + position: `'relative'`, + left: "0", + top: "0" + } + ) ); + } else { + saveNodes([ + ...newNodes, + { ...activeNode.node, parentId: column2.id } + ]); } - return; } - dom.empty(); - const createDiv = dom.createDiv("file-embed"); - createDiv.toggleClass("mod-empty", true); - const createFile = async (e4) => { - e4.stopPropagation(); - e4.stopImmediatePropagation(); - await app.fileManager.createNewMarkdownFile(app.vault.getRoot(), path); - loadFlowEditor(cm, flowEditorInfo2, source, make); - }; - createDiv.setText(`"${path}" ` + i18n_default.labels.noFile); - createDiv.addEventListener("click", createFile); + resetState(); + return; } - } - } -}; -var focusPortal = async (plugin, evt) => { - const { id: id2, parent, top } = evt.detail; - if (parent) { - app.workspace.iterateLeaves((leaf) => { - var _a2; - const cm = (_a2 = leaf.view.editor) == null ? void 0 : _a2.cm; - if (cm) { - const stateField = cm.state.field(flowEditorInfo, false); - if (stateField) { - const foundInfo = stateField.find((f4) => f4.id == id2); - if (foundInfo) { - cm.focus(); - if (top) { - cm.dispatch({ - selection: import_state5.EditorSelection.single(foundInfo.from - 4), - annotations: arrowKeyAnnotation.of(1) - }); - } else { - if (foundInfo.to + 2 == cm.state.doc.length) { - cm.dispatch({ - changes: [ - { - from: foundInfo.to + 2, - to: foundInfo.to + 2, - insert: cm.state.lineBreak - } - ], - selection: import_state5.EditorSelection.single(foundInfo.to + 3), - annotations: arrowKeyAnnotation.of(2) - }); - } else { - cm.dispatch({ - selection: import_state5.EditorSelection.single(foundInfo.to + 3), - annotations: arrowKeyAnnotation.of(2) - }); - } - } + if (active.data.current.frame != frameSchema.id) { + moveNodeFromSchema( + active.data.current.id, + active.data.current.frame, + overNode.node.parentId, + { + position: `'relative'`, + left: "0", + top: "0" } - } + ); + resetState(); + return; } - }, app.workspace["rootSplit"]); - } else { - app.workspace.iterateLeaves((leaf) => { - var _a2; - const cm = (_a2 = leaf.view.editor) == null ? void 0 : _a2.cm; - if (cm) { - const stateField = cm.state.field(flowIDStateField, false); - if (stateField && stateField == id2) { - cm.focus(); - const lineRange = cm.state.field(selectiveLinesFacet, false); - const posRange = lineRange && lineRange[0] != void 0 ? lineRangeToPosRange(cm.state, lineRange) : { from: 0, to: cm.state.doc.length }; - if (top) { - cm.dispatch({ - selection: import_state5.EditorSelection.single(posRange.from) - }); - } else { - cm.dispatch({ - selection: import_state5.EditorSelection.single(posRange.to) - }); - } - } + if ((overParentNode == null ? void 0 : overParentNode.id) == (activeParentNode == null ? void 0 : activeParentNode.id)) { + console.group("same parent", overNode); + if (overNode) + moveToRank(activeNode.node, overNode.node.rank); + } else { + if (overNode) + saveNodes([{ ...activeNode.node, parentId: overNode.node.parentId }]); + } + if (!overId) { + resetState(); + return; + } + if (overId === PLACEHOLDER_ID2) { + saveNodes([{ ...activeNode.node, parentId: overNode.node.id }]); + resetState(); + return; } - }, app.workspace["rootSplit"]); + resetState(); + } + }); + return (_instance == null ? void 0 : _instance.root) && /* @__PURE__ */ Cn.createElement(Cn.Fragment, null, /* @__PURE__ */ Cn.createElement(FrameNodeView, { + editMode: 1, + plugin: props2.plugin, + treeNode: _instance.root, + instance: _instance + }), /* @__PURE__ */ Cn.createElement(RowPlaceholder, { + plugin: props2.plugin, + id: PLACEHOLDER_ID2, + parentId: frameSchema.id + }), z3( + /* @__PURE__ */ Cn.createElement(DragOverlay, null, getDragLayer()), + document.body + )); +}; + +// src/components/UI/modals/contextEditorModal.tsx +var import_obsidian38 = require("obsidian"); +var ContextEditorModal = class extends import_obsidian38.Modal { + constructor(plugin, space, db, view, type) { + super(plugin.app); + this.space = space; + this.view = view; + this.db = db; + this.plugin = plugin; + this.type = type; + } + onOpen() { + const { contentEl } = this; + this.modalEl.toggleClass("mk-context-maker", true); + const queryEl = contentEl.createDiv("mk-context-maker-container"); + const root = createRoot(queryEl); + this.titleEl.textContent = this.type == 0 ? "Properties" : "View"; + root.render( + /* @__PURE__ */ Cn.createElement(SpaceContextProvider, { + plugin: this.plugin, + space: this.space + }, /* @__PURE__ */ Cn.createElement(ContextMDBProvider, { + plugin: this.plugin, + schema: this.db + }, /* @__PURE__ */ Cn.createElement(FramesMDBProvider, { + plugin: this.plugin + }, /* @__PURE__ */ Cn.createElement(ContextEditorProvider, { + plugin: this.plugin, + schema: this.view + }, this.type == 0 ? /* @__PURE__ */ Cn.createElement(SpacePropertyEditorContext, { + plugin: this.plugin + }) : /* @__PURE__ */ Cn.createElement(ContextFrameView, { + plugin: this.plugin + }))))) + ); + } + onClose() { + const { contentEl } = this; + contentEl.empty(); } }; -var openFileFromPortal = (plugin, evt) => { - const { file: fullLink, source } = evt.detail; - const [link, ref] = parseOutReferences(fullLink); - const file = getFileFromString(link, source); - openAFile(file, plugin, false); +var SpacePropertyEditorContext = (props2) => { + var _a2, _b2; + const { spaceCache } = q2(SpaceContext); + const { + predicate, + savePredicate, + sortedColumns, + hideColumn, + delColumn, + saveColumn + } = q2(ContextEditorContext); + const { tableData } = q2(ContextMDBContext); + const saveContexts = (contexts) => { + saveSpaceMetadataValue( + props2.plugin, + spaceCache.path, + props2.plugin.settings.fmKeyContexts, + contexts + ); + }; + return /* @__PURE__ */ Cn.createElement(SpacePropertyEditor, { + plugin: props2.plugin, + colsOrder: predicate.colsOrder, + setColumnOrder: (cols) => savePredicate({ ...predicate, colsOrder: cols }), + colsHidden: predicate.colsHidden, + columns: (_a2 = tableData == null ? void 0 : tableData.cols) != null ? _a2 : [], + contexts: (_b2 = spaceCache == null ? void 0 : spaceCache.contexts) != null ? _b2 : [], + saveContexts, + hideColumn, + delColumn, + saveColumn + }); }; -var spawnLeafFromFile = async (plugin, file, el, type, ref, from, to, onLeafAttachCallback) => { - if (type == "context") { - spawnPortal(plugin, el, null, async (editor) => { - const newLeaf = editor.attachLeaf(); - await newLeaf.setViewState({ - type: EMBED_CONTEXT_VIEW_TYPE, - state: { contextPath: file, ref } + +// src/components/SpaceView/Contexts/FilterBar/FilterBar.tsx +var import_obsidian39 = require("obsidian"); + +// src/components/SpaceView/Contexts/FilterBar/SearchBar.tsx +var SearchBar = (props2) => { + const clearSearch = () => { + props2.setSearchString(""); + }; + return /* @__PURE__ */ Cn.createElement("div", { + className: "mk-view-search" + }, /* @__PURE__ */ Cn.createElement("button", { + dangerouslySetInnerHTML: { __html: uiIconSet["mk-ui-search"] } + }), /* @__PURE__ */ Cn.createElement(Cn.Fragment, null, /* @__PURE__ */ Cn.createElement("input", { + onChange: (e4) => props2.setSearchString(e4.target.value), + placeholder: i18n_default.labels.searchPlaceholder, + className: "mk-search-bar" + }), /* @__PURE__ */ Cn.createElement("button", { + dangerouslySetInnerHTML: { __html: uiIconSet["mk-ui-clear"] }, + onClick: () => clearSearch() + }))); +}; + +// src/components/SpaceView/Contexts/FilterBar/FilterBar.tsx +var FilterBar = (props2) => { + const ctxRef = _2(null); + const { spaceInfo, spaceCache } = q2(SpaceContext); + const { + dbSchemas: schemas, + setDBSchema, + saveDB: saveDB2, + saveContextDB, + dbSchema, + contextTable, + tableData + } = q2(ContextMDBContext); + const { + data: data2, + loadContextFields, + cols, + schema, + setSchema, + setSearchString, + predicate, + savePredicate, + hideColumn, + saveColumn, + sortColumn, + delColumn, + views + } = q2(ContextEditorContext); + const { saveSchema, frameSchemas, deleteSchema } = q2(FramesMDBContext); + const filteredCols = cols.filter((f4) => f4.hidden != "true"); + const saveViewType = (type) => { + savePredicate({ + ...predicate, + view: type + }); + }; + const selectView = (_dbschema, value) => { + setDBSchema(_dbschema); + value && setSchema(views.find((f4) => f4.id == value)); + }; + const openView = (e4, view) => { + const dbSchema2 = schemas.find((f4) => f4.type == "db" && f4.id == view.def.db); + if (dbSchema2) { + selectView(dbSchema2, view.id); + return; + } + return; + }; + const clearFilters = () => { + savePredicate({ + ...predicate, + filters: [], + sort: [] + }); + }; + const clearHiddenCols = () => { + savePredicate({ + ...predicate, + colsHidden: [] + }); + }; + const removeFilter = (filter) => { + const newFilters = [ + ...predicate.filters.filter((f4) => f4.field != filter.field) + ]; + savePredicate({ + ...predicate, + filters: newFilters + }); + }; + const viewContextMenu = (e4, _schema) => { + const fileMenu = new import_obsidian39.Menu(); + fileMenu.addSeparator(); + fileMenu.addItem((menuItem) => { + menuItem.setTitle("Copy Embed Link"); + menuItem.onClick(() => { + navigator.clipboard.writeText( + contextEmbedStringFromContext(spaceInfo, _schema.id) + ); }); - if (onLeafAttachCallback) - onLeafAttachCallback(newLeaf); }); - } - const portalFile = plugin.app.vault.getAbstractFileByPath(file); - if (!portalFile || !Object.keys(app.embedRegistry.embedByExtension).some( - (f4) => f4 == portalFile.extension - )) - return null; - spawnPortal(plugin, el, portalFile.name, async (editor) => { - return editor.openFile(portalFile, { active: false }).then((newLeaf) => { - var _a2; - if (newLeaf.view.setMode) - newLeaf.view.setMode(newLeaf.view.editMode); - if (from && to) { - (_a2 = newLeaf.view.editor) == null ? void 0 : _a2.cm.dispatch({ - annotations: [editableRange.of([from, to])] - }); - if (onLeafAttachCallback) - onLeafAttachCallback(newLeaf); - } + fileMenu.addItem((menuItem) => { + menuItem.setTitle("Rename View"); + menuItem.onClick(() => { + const vaultChangeModal = new SaveViewModal( + _schema, + (s5) => saveSchema(s5), + "rename view" + ); + vaultChangeModal.open(); + }); }); - }); -}; -var spawnNewPortal = async (plugin, evt) => { - const { file, el, ref, from, to, type } = evt.detail; - spawnLeafFromFile(plugin, file, el, type, ref, from, to, (newLeaf) => { - var _a2, _b2, _c2; - if (!((_a2 = newLeaf == null ? void 0 : newLeaf.view) == null ? void 0 : _a2.editor)) { - return; + fileMenu.addItem((menuItem) => { + menuItem.setTitle("Delete View"); + menuItem.onClick(() => { + deleteSchema(_schema); + }); + }); + if (isMouseEvent(e4)) { + fileMenu.showAtPosition({ x: e4.pageX, y: e4.pageY }); + } else { + fileMenu.showAtPosition({ + x: e4.nativeEvent.locationX, + y: e4.nativeEvent.locationY + }); } - const view = (_b2 = newLeaf.view.editor) == null ? void 0 : _b2.cm; - view.dispatch({ - annotations: [ - portalTypeAnnotation.of(evt.detail.type), - flowIDAnnotation.of(evt.detail.id) - ] + }; + const showFilterMenu = (e4) => { + const menu = new import_obsidian39.Menu(); + menu.addItem((item) => { + item.setTitle(i18n_default.menu.tableView); + item.setIcon("table-2"); + item.onClick(() => { + saveViewType("table"); + }); + }); + menu.addItem((item) => { + item.setTitle(i18n_default.menu.cardView); + item.setIcon("layout-grid"); + item.onClick(() => { + saveViewType("card"); + }); + }); + menu.addItem((item) => { + item.setTitle(i18n_default.menu.listView); + item.setIcon("layout-list"); + item.onClick(() => { + saveViewType("list"); + }); + }); + if (dbSchema == null ? void 0 : dbSchema.primary) { + menu.addItem((item) => { + item.setTitle(i18n_default.menu.flowView); + item.setIcon("infinity"); + item.onClick(() => { + saveViewType("flow"); + }); + }); + } + menu.addSeparator(); + menu.addItem((item) => { + item.setTitle(i18n_default.menu.groupBy); + item.setIcon("columns"); + item.onClick(() => { + showGroupByMenu(e4); + }); + }); + menu.addItem((item) => { + item.setTitle(i18n_default.menu.sortBy); + item.setIcon("sort-desc"); + item.onClick(() => { + showSortMenu(e4); + }); + }); + menu.addSeparator(); + menu.addItem((item) => { + item.setTitle(i18n_default.menu.newFilter); + item.setIcon("filter"); + item.onClick(() => { + showAddFilterMenu(e4); + }); + }); + menu.addItem((item) => { + item.setTitle(i18n_default.menu.clearFilters); + item.setIcon("x-square"); + item.onClick(() => { + clearFilters(); + }); + }); + menu.addSeparator(); + menu.addItem((item) => { + item.setTitle(i18n_default.menu.unhideFields); + item.setIcon("eye"); + item.onClick(() => { + clearHiddenCols(); + }); + }); + const offset2 = e4.target.getBoundingClientRect(); + menu.showAtPosition({ x: offset2.left, y: offset2.top + 30 }); + }; + const addSort = (_12, sort) => { + var _a2; + const field = sort[0]; + const fieldType = (_a2 = filteredCols.find((f4) => f4.name + f4.table == field)) == null ? void 0 : _a2.type; + if (fieldType) { + const type = defaultPredicateFnForType(fieldType, sortFnTypes); + const newSort = { + field, + fn: type + }; + savePredicate({ + ...predicate, + sort: [ + ...predicate.sort.filter((s5) => s5.field != newSort.field), + newSort + ] + }); + } + }; + const saveGroupBy = (_12, groupBy2) => { + savePredicate({ + ...predicate, + groupBy: groupBy2 }); - view.dom.addEventListener("keydown", (e4) => { - if (e4.key == "ArrowUp") { - if (e4.metaKey == true) { - view.dispatch({ - annotations: arrowKeyAnnotation.of(3) - }); - } else { - view.dispatch({ - annotations: arrowKeyAnnotation.of(1) - }); - } - } - if (e4.key == "ArrowDown") { - if (e4.metaKey == true) { - view.dispatch({ - annotations: arrowKeyAnnotation.of(4) - }); - } else { - view.dispatch({ - annotations: arrowKeyAnnotation.of(2) - }); - } - } + }; + const removeSort = (sort) => { + const newSort = [...predicate.sort.filter((f4) => f4.field != sort.field)]; + savePredicate({ + ...predicate, + sort: newSort }); - if (from && to) { - (_c2 = newLeaf.view.editor) == null ? void 0 : _c2.cm.dispatch({ - annotations: [editableRange.of([from, to])] + }; + const addFilter = (_12, filter) => { + var _a2; + const field = filter[0]; + const fieldType = (_a2 = filteredCols.find((f4) => f4.name + f4.table == field)) == null ? void 0 : _a2.type; + if (fieldType) { + const type = defaultPredicateFnForType(fieldType, filterFnTypes); + const newFilter = fieldType == "boolean" ? { + field, + fn: type, + value: "true" + } : { + field, + fn: type, + value: "" + }; + savePredicate({ + ...predicate, + filters: [ + ...predicate.filters.filter((s5) => s5.field != newFilter.field), + newFilter + ] }); } - }); -}; -var spawnPortal = (plugin, initiatingEl, fileName, onShowCallback) => { - const parent = plugin.app.workspace.activeLeaf; - if (!initiatingEl) - initiatingEl = parent.containerEl; - const hoverPopover = new FlowEditor( - parent, - initiatingEl, - plugin, - void 0, - onShowCallback - ); - if (fileName) - hoverPopover.titleEl.textContent = fileName.substring( - 0, - fileName.lastIndexOf(".") - ); -}; - -// src/components/ContextView/DataTypeView/LinkCell.tsx -var LinkCell = (props2) => { - var _a2; - const initialValue = (props2.multi ? (_a2 = parseMultiString(props2.initialValue)) != null ? _a2 : [] : [props2.initialValue]).filter((f4) => f4); - const stringValueToLink = (strings) => strings.map((f4) => { - return { - label: parseLinkDisplayString(f4), - value: parseLinkString(f4) + }; + const changeSortMenu = (e4, sort) => { + var _a2; + const offset2 = e4.target.getBoundingClientRect(); + const saveSort = (_12, newType) => { + const type = newType[0]; + const newSort = { + ...sort, + fn: type + }; + savePredicate({ + ...predicate, + sort: [ + ...predicate.sort.filter((s5) => s5.field != newSort.field), + newSort + ] + }); }; - }); - p2(() => { - var _a3; - setValue( - resolveLinks( - stringValueToLink( - props2.multi ? (_a3 = parseMultiString(props2.initialValue)) != null ? _a3 : [] : [props2.initialValue] - ) - ) + const fieldType = (_a2 = filteredCols.find( + (f4) => f4.name + f4.table == sort.field + )) == null ? void 0 : _a2.type; + const sortsForType = predicateFnsForType(fieldType, sortFnTypes); + showSelectMenu( + { x: offset2.left, y: offset2.top + 30 }, + { + plugin: props2.plugin, + multi: false, + editable: false, + value: [], + options: sortsForType.map((f4) => ({ + name: sortFnTypes[f4].label, + value: f4 + })), + saveOptions: saveSort, + placeholder: i18n_default.labels.sortItemSelectPlaceholder, + searchable: false, + showAll: true + } ); - }, [props2.initialValue]); - const resolveLinks = (links) => links.map((f4) => ({ - value: f4.value, - label: filePathToString(f4.value), - file: getFileFromString(f4.value, getFolderPathFromString(props2.file)) - })); - const ref = _2(null); - const [value, setValue] = h2( - resolveLinks(stringValueToLink(initialValue)) - ); - const removeValue = (v3) => { - const newValues = value.filter((f4) => f4.value != v3.value); - setValue(newValues); - props2.saveValue(serializeMultiString(newValues.map((f4) => f4.value))); }; - const saveOptions = (_9, _value) => { - if (!props2.multi) { - setValue(resolveLinks(stringValueToLink(_value))); - props2.saveValue(serializeMultiString(_value)); - } else { - const newValue = _value[0]; - if (newValue) { - const newValues = uniq([...value.map((f4) => f4.value), newValue]); - setValue(resolveLinks(stringValueToLink(newValues))); - props2.saveValue(serializeMultiString(newValues)); + const showViewsMenu = (e4) => { + const vaultChangeModal = new ContextEditorModal( + props2.plugin, + spaceInfo, + dbSchema == null ? void 0 : dbSchema.id, + schema == null ? void 0 : schema.id, + 1 + ); + vaultChangeModal.open(); + }; + const showColsMenu = (e4) => { + const vaultChangeModal = new ContextEditorModal( + props2.plugin, + spaceInfo, + dbSchema == null ? void 0 : dbSchema.id, + schema == null ? void 0 : schema.id, + 0 + ); + vaultChangeModal.open(); + }; + const saveField = (field, oldField) => { + if (field.name.length > 0) { + if (field.name != oldField.name || field.type != oldField.type || field.value != oldField.value || field.attrs != oldField.attrs) { + const saveResult = saveColumn(field, oldField); } } }; - const menuProps = () => { - const options = getAllAbstractFilesInVault(props2.plugin, app).map((f4) => ({ - name: fileNameToString(f4.name), - value: f4.path, - description: f4.path - })); - const _options = !props2.multi ? [{ name: i18n_default.menu.none, value: "" }, ...options] : options; - return { - multi: false, + const showMenu = (e4, field) => { + const offset2 = e4.target.getBoundingClientRect(); + const options = optionValuesForColumn( + field.name, + field.table == "" ? tableData : contextTable[field.table] + ); + showPropertyMenu({ + plugin: props2.plugin, + position: { x: offset2.left, y: offset2.top + 30 }, editable: true, - value: value.map((f4) => f4.value), - options: _options, - saveOptions, - placeholder: i18n_default.labels.linkItemSelectPlaceholder, - detail: true, - searchable: true + options, + field, + fields: cols, + contextPath: spaceInfo.path, + saveField: (newField) => saveField(newField, field), + hide: hideColumn, + deleteColumn: delColumn, + sortColumn, + hidden: predicate.colsHidden.includes(field.name + field.table) + }); + }; + const changeFilterMenu = (e4, filter) => { + var _a2; + const offset2 = e4.target.getBoundingClientRect(); + const saveFilter = (_12, newType) => { + const type = newType[0]; + const newFilter = { + ...filter, + fn: type + }; + savePredicate({ + ...predicate, + filters: [ + ...predicate.filters.filter((s5) => s5.field != newFilter.field), + newFilter + ] + }); }; + const fieldType = (_a2 = filteredCols.find( + (f4) => f4.name + f4.table == filter.field + )) == null ? void 0 : _a2.type; + const filtersForType = predicateFnsForType(fieldType, filterFnTypes); + showSelectMenu( + { x: offset2.left, y: offset2.top + 30 }, + { + plugin: props2.plugin, + multi: false, + editable: false, + value: [], + options: filtersForType.map((f4) => ({ + name: filterFnLabels[f4], + value: f4 + })), + saveOptions: saveFilter, + placeholder: i18n_default.labels.filterItemSelectPlaceholder, + searchable: false, + showAll: true + } + ); }; - const openLink = async (o3) => { - if (o3.file) { - openTFile(o3.file, props2.plugin, false); - } else { - const file = await app.fileManager.createNewMarkdownFile( - app.vault.getRoot(), - o3.value - ); - openTFile(file, props2.plugin, false); - setValue(resolveLinks(value)); - } + const showAddFilterMenu = (e4) => { + const offset2 = e4.target.getBoundingClientRect(); + showSelectMenu( + { x: offset2.left, y: offset2.top + 30 }, + { + plugin: props2.plugin, + multi: false, + editable: false, + value: [], + options: filteredCols.filter((f4) => predicateFnsForType(f4.type, filterFnTypes).length > 0).map((f4) => ({ + name: f4.name + f4.table, + value: f4.name + f4.table + })), + saveOptions: addFilter, + placeholder: i18n_default.labels.propertyItemSelectPlaceholder, + searchable: false, + showAll: true + } + ); }; - return /* @__PURE__ */ Cn.createElement(OptionCellBase, { - baseClass: "mk-cell-link", - menuProps, - getLabelString: (o3) => o3.label, - valueClass: (o3) => o3.file ? "mk-cell-link-item" : "mk-cell-link-unresolved", - openItem: openLink, - value, - multi: props2.multi, - editMode: props2.editMode, - removeValue - }); -}; - -// src/components/ContextView/DataTypeView/TagCell.tsx -var TagCell = (props2) => { - var _a2; - const initialValue = ((_a2 = parseMultiString(props2.initialValue)) != null ? _a2 : []).filter( - (f4) => (f4 == null ? void 0 : f4.length) > 0 - ); - const [value, setValue] = h2(initialValue); - p2(() => { - var _a3; - setValue((_a3 = parseMultiString(props2.initialValue)) != null ? _a3 : []); - }, [props2.initialValue]); - const removeValue = (v3) => { - const newValues = value.filter((f4) => f4 != v3); - setValue(newValues); - props2.saveValue(serializeMultiString(newValues)); + const showSortMenu = (e4) => { + const offset2 = e4.target.getBoundingClientRect(); + showSelectMenu( + { x: offset2.left, y: offset2.top + 30 }, + { + plugin: props2.plugin, + multi: false, + editable: false, + value: [], + options: filteredCols.map((f4) => ({ + name: f4.name + f4.table, + value: f4.name + f4.table + })), + saveOptions: addSort, + placeholder: i18n_default.labels.sortItemSelectPlaceholder, + searchable: false, + showAll: true + } + ); }; - const saveOptions = (_options, _value) => { - if (!props2.multi) { - setValue(_value); - props2.saveValue(serializeMultiString(_value)); - } else { - const newValue = _value[0]; - if (newValue) { - const newValues = uniq([...value, newValue]); - setValue(newValues); - props2.saveValue(serializeMultiString(newValues)); + const showGroupByMenu = (e4) => { + const offset2 = e4.target.getBoundingClientRect(); + showSelectMenu( + { x: offset2.left, y: offset2.top + 30 }, + { + plugin: props2.plugin, + multi: false, + editable: false, + value: [], + options: filteredCols.filter((f4) => f4.name != FilePropertyName).map((f4) => ({ + name: f4.name + f4.table, + value: f4.name + f4.table + })), + saveOptions: saveGroupBy, + placeholder: i18n_default.labels.propertyItemSelectPlaceholder, + searchable: false, + showAll: true + } + ); + }; + const showSaveViewModal = () => { + const vaultChangeModal = new SaveViewModal(schema, saveSchema, "new view"); + vaultChangeModal.open(); + }; + const editViewModal = () => { + const vaultChangeModal = new SaveViewModal( + schema, + saveSchema, + "rename view" + ); + vaultChangeModal.open(); + }; + const selectFilterValue = (e4, filter) => { + var _a2, _b2, _c2; + switch (filterFnTypes[filter.fn].valueType) { + case "text": + case "number": + { + const menu = new import_obsidian39.Menu(); + menu.setUseNativeMenu(false); + const saveFilterValue = (value) => { + const newFilter = { + ...filter, + value + }; + savePredicate({ + ...predicate, + filters: [ + ...predicate.filters.filter((s5) => s5.field != newFilter.field), + newFilter + ] + }); + }; + menu.addItem((menuItem) => { + inputMenuItem( + menuItem, + filter.value, + (value) => saveFilterValue(value) + ); + menuItem.setIcon("type"); + }); + const offset2 = e4.target.getBoundingClientRect(); + menu.showAtPosition({ x: offset2.left, y: offset2.top + 30 }); + } + break; + case "date": { + const saveValue = (date2) => { + const newFilter = { + ...filter, + value: date2.valueOf().toString() + }; + savePredicate({ + ...predicate, + filters: [ + ...predicate.filters.filter((s5) => s5.field != newFilter.field), + newFilter + ] + }); + }; + const offset2 = e4.target.getBoundingClientRect(); + const date = new Date(filter.value); + showDatePickerMenu( + { x: offset2.left, y: offset2.top + 30 }, + date.getTime() ? date : null, + saveValue + ); + break; } + case "list": + { + const col = cols.find((f4) => f4.name + f4.table == filter.field); + const saveOptions = (options, values) => { + const newFilter = { + ...filter, + value: serializeMultiString(values) + }; + savePredicate({ + ...predicate, + filters: [ + ...predicate.filters.filter((s5) => s5.field != newFilter.field), + newFilter + ] + }); + }; + if (col.type.startsWith("option")) { + const offset2 = e4.target.getBoundingClientRect(); + showSelectMenu( + { x: offset2.left, y: offset2.top + 30 }, + { + plugin: props2.plugin, + multi: true, + editable: false, + value: parseMultiString(filter.value), + options: parseMultiString(col.value).map((f4) => ({ + name: f4, + value: f4 + })), + saveOptions, + placeholder: i18n_default.labels.optionItemSelectPlaceholder, + searchable: true, + showAll: true + } + ); + } else if (col.type.startsWith("context")) { + const contextData = (_b2 = (_a2 = contextTable[col.table]) == null ? void 0 : _a2.rows) != null ? _b2 : []; + const offset2 = e4.target.getBoundingClientRect(); + showSelectMenu( + { x: offset2.left, y: offset2.top + 30 }, + { + plugin: props2.plugin, + multi: true, + editable: false, + value: parseMultiString(filter.value), + options: (_c2 = contextData.map((f4) => ({ + name: filePathToString(f4[FilePropertyName]), + value: f4[FilePropertyName] + }))) != null ? _c2 : [], + saveOptions, + placeholder: i18n_default.labels.optionItemSelectPlaceholder, + searchable: true, + showAll: true + } + ); + } + } + break; } }; - const menuProps = () => { - const options = loadTags(props2.plugin).map((f4) => ({ - name: f4, - value: f4 + return /* @__PURE__ */ Cn.createElement(Cn.Fragment, null, /* @__PURE__ */ Cn.createElement("div", { + className: "mk-view-config" + }, /* @__PURE__ */ Cn.createElement("div", { + className: "mk-view-selector" + }, views.map((f4, i4) => /* @__PURE__ */ Cn.createElement("div", { + key: i4, + className: `${(schema == null ? void 0 : schema.id) == f4.id ? "mk-is-active" : ""}`, + onContextMenu: (e4) => viewContextMenu(e4, f4) + }, /* @__PURE__ */ Cn.createElement("button", { + onClick: (e4) => openView(e4, f4) + }, f4.name))), /* @__PURE__ */ Cn.createElement("button", { + onClick: (e4) => showSaveViewModal() + }, "+")), /* @__PURE__ */ Cn.createElement("span", null), /* @__PURE__ */ Cn.createElement("div", { + className: "mk-view-options" + }, /* @__PURE__ */ Cn.createElement(SearchBar, { + setSearchString + }), /* @__PURE__ */ Cn.createElement("button", { + onClick: (e4) => showFilterMenu(e4), + dangerouslySetInnerHTML: { + __html: uiIconSet["mk-ui-view-options"] + } + }), /* @__PURE__ */ Cn.createElement("div", null, /* @__PURE__ */ Cn.createElement("button", { + onClick: (e4) => showColsMenu(e4), + dangerouslySetInnerHTML: { __html: uiIconSet["mk-ui-list"] } + })), (dbSchema == null ? void 0 : dbSchema.id) == "files" && /* @__PURE__ */ Cn.createElement("button", { + className: "mk-button-new", + onClick: (e4) => showSpaceAddMenu(props2.plugin, e4, spaceCache, true), + dangerouslySetInnerHTML: { __html: uiIconSet["mk-ui-plus"] } + }))), (predicate.filters.length > 0 || predicate.sort.length > 0 || predicate.groupBy.length > 0) && /* @__PURE__ */ Cn.createElement("div", { + className: "mk-filter-bar" + }, predicate.groupBy.length > 0 && /* @__PURE__ */ Cn.createElement("div", { + className: "mk-filter" + }, /* @__PURE__ */ Cn.createElement("span", null, "Group By"), /* @__PURE__ */ Cn.createElement("span", { + onClick: (e4) => showGroupByMenu(e4) + }, predicate.groupBy[0]), /* @__PURE__ */ Cn.createElement("div", { + onClick: () => saveGroupBy(null, []), + dangerouslySetInnerHTML: { __html: uiIconSet["mk-ui-close"] } + })), predicate.sort.map((f4, i4) => /* @__PURE__ */ Cn.createElement("div", { + key: i4, + className: "mk-filter" + }, /* @__PURE__ */ Cn.createElement("span", null, f4.field), /* @__PURE__ */ Cn.createElement("span", { + onClick: (e4) => changeSortMenu(e4, f4) + }, sortFnTypes[f4.fn].label), /* @__PURE__ */ Cn.createElement("div", { + onClick: () => removeSort(f4), + dangerouslySetInnerHTML: { __html: uiIconSet["mk-ui-close"] } + }))), predicate.filters.map((f4, i4) => { + var _a2; + return /* @__PURE__ */ Cn.createElement("div", { + key: i4, + className: "mk-filter" + }, /* @__PURE__ */ Cn.createElement("span", null, f4.field), /* @__PURE__ */ Cn.createElement("span", { + onClick: (e4) => changeFilterMenu(e4, f4) + }, filterFnLabels[f4.fn]), /* @__PURE__ */ Cn.createElement(FilterValueSpan, { + fieldType: (_a2 = cols.find((c4) => c4.name + c4.table == f4.field)) == null ? void 0 : _a2.type, + filter: f4, + selectFilterValue + }), /* @__PURE__ */ Cn.createElement("div", { + onClick: () => removeFilter(f4), + dangerouslySetInnerHTML: { __html: uiIconSet["mk-ui-close"] } })); - const _options = !props2.multi ? [{ name: i18n_default.menu.none, value: "" }, ...options] : options; - return { - multi: false, - editable: true, - value, - options: _options, - saveOptions, - placeholder: i18n_default.labels.tagItemSelectPlaceholder, - searchable: true, - showAll: true, - onHide: () => props2.setEditMode(null) - }; - }; - return /* @__PURE__ */ Cn.createElement(OptionCellBase, { - baseClass: "mk-cell-tag", - menuProps, - value, - multi: props2.multi, - editMode: props2.editMode, - removeValue - }); + }), /* @__PURE__ */ Cn.createElement("span", null))); +}; +var FilterValueSpan = (props2) => { + const { filter, selectFilterValue, fieldType } = props2; + const fnType = filterFnTypes[filter.fn]; + if (!fieldType || !fnType || fnType.valueType == "none") { + return /* @__PURE__ */ Cn.createElement(Cn.Fragment, null); + } else if (filter.value.length == 0) { + return /* @__PURE__ */ Cn.createElement("span", { + onClick: (e4) => selectFilterValue(e4, filter) + }, "Select"); + } else if (fieldType.startsWith("option") || fieldType.startsWith("context")) { + const options = parseMultiString(filter.value); + return /* @__PURE__ */ Cn.createElement("span", { + onClick: (e4) => selectFilterValue(e4, filter) + }, " ", options.map((f4, i4) => /* @__PURE__ */ Cn.createElement("span", { + key: i4 + }, f4))); + } + return /* @__PURE__ */ Cn.createElement("span", { + onClick: (e4) => selectFilterValue(e4, filter) + }, filter.value); }; -// src/components/ContextView/TableView/TableView.tsx -var TableView = (props2) => { - const { - selectedRows, - selectRows, - tableData, - sortedColumns: cols, - filteredData: data, - contextInfo, - readMode, - dbSchema, - contextTable, - predicate, - savePredicate, - saveDB: saveDB2, - updateFieldValue, - updateValue: updateValue2 - } = q2(MDBContext); - const [activeId, setActiveId] = h2(null); - const [lastSelectedIndex, setLastSelectedIndex] = h2(null); - const [selectedColumn, setSelectedColumn] = h2(null); - const [currentEdit, setCurrentEdit] = h2(null); - const [overId, setOverId] = h2(null); - const [openFlows, setOpenFlows] = h2([]); - const [colsSize, setColsSize] = h2({}); - const ref = _2(null); - p2(() => { - setColsSize({ ...predicate.colsSize, "+": 30 }); - }, [predicate]); - p2(() => { - setCurrentEdit(null); - }, [selectedColumn, lastSelectedIndex]); - p2(() => { - if (currentEdit == null) { - ref.current.focus(); - } - }, [currentEdit]); - const saveColsSize = (colSize) => { - const newColSize = colSize(colsSize); - setColsSize(newColSize); - debouncedSavePredicate(newColSize); - }; - const debouncedSavePredicate = T2( - (0, import_lodash6.debounce)( - (nextValue) => savePredicate({ - ...predicate, - colsSize: nextValue - }), - 1e3 - ), - [predicate] - ); - const newRow = (index, data2) => { - saveDB2(createNewRow(tableData, { File: "", ...data2 != null ? data2 : {} }, index)); - }; - const deleteRow = (rowIndex) => { - const row = tableData.rows.find((f4, i4) => i4 == rowIndex); - if (getAbstractFileAtPath(app, row.File)) { - deleteFile(props2.plugin, getAbstractFileAtPath(app, row.File)); - } - if (row) { - saveDB2({ - ...tableData, - rows: tableData.rows.filter((f4, i4) => i4 != rowIndex) - }); +// src/components/Navigator/SpaceQuery.tsx +var SpaceQuery = (props2) => { + const { filters, setFilters } = props2; + const selectFilterValue = (e4, filter, i4, k5) => { + var _a2; + const saveFilterValue = (value) => { + setDefFilterValue(value, i4, k5); + }; + switch ((_a2 = filterFnTypes[filter.fn]) == null ? void 0 : _a2.valueType) { + case "text": + case "number": + { + const menu = new import_obsidian40.Menu(); + menu.setUseNativeMenu(false); + menu.addItem((menuItem) => { + inputMenuItem( + menuItem, + filter.value, + (value) => saveFilterValue(value) + ); + menuItem.setIcon("type"); + }); + const offset2 = e4.target.getBoundingClientRect(); + menu.showAtPosition({ x: offset2.left, y: offset2.top + 30 }); + } + break; + case "date": { + const saveValue = (date2) => { + saveFilterValue(date2.valueOf().toString()); + }; + const offset2 = e4.target.getBoundingClientRect(); + const date = new Date(filter.value); + showDatePickerMenu( + { x: offset2.left, y: offset2.top + 30 }, + date.getTime() ? date : null, + saveValue + ); + break; + } + case "list": + { + const fieldType = filter.fType; + const saveOptions = (options2, values) => { + saveFilterValue(serializeMultiString(values)); + }; + let options = []; + if (fieldType.startsWith("option")) { + options = parseMultiString(filter.value).map((f4) => ({ + name: f4, + value: f4 + })); + } else if (fieldType.startsWith("tags")) { + options = loadTags(props2.plugin).map((f4) => ({ + value: f4, + name: f4 + })); + } else if (fieldType.startsWith("links")) { + options = getAllAbstractFilesInVault(props2.plugin).map((f4) => ({ + name: fileNameToString(f4.name), + value: f4.path, + description: f4.path + })); + } + const offset2 = e4.target.getBoundingClientRect(); + showSelectMenu( + { x: offset2.left, y: offset2.top + 30 }, + { + plugin: props2.plugin, + multi: true, + editable: true, + value: parseMultiString(filter.value), + options, + saveOptions, + placeholder: i18n_default.labels.optionItemSelectPlaceholder, + searchable: false, + showAll: true + } + ); + } + break; } }; - const toggleFlow = (path) => { - setOpenFlows( - (f4) => f4.find((p3) => p3 == path) ? f4.filter((p3) => p3 != path) : uniq([...f4, path]) - ); + const addDefGroup = () => { + setFilters((p3) => [ + ...p3, + { + type: "any", + trueFalse: true, + filters: [] + } + ]); }; - const selectItem = (modifier, index) => { - if (modifier == 3) { - const file = getAbstractFileAtPath( - app, - tableData.rows[parseInt(index)].File - ); - if (file) - openAFile(file, props2.plugin, false); - return; - } - if (modifier == 2) { - selectedRows.some((f4) => f4 == index) ? selectRows( - null, - selectedRows.filter((f4) => f4 != index) - ) : selectRows(index, uniq([...selectedRows, index])); - } else if (modifier == 1) { - selectRows( - index, - uniq([ - ...selectedRows, - ...selectRange( - lastSelectedIndex, - index, - data.map((f4) => f4._index) - ) - ]) - ); - } else { - selectRows(index, [index]); - } - setLastSelectedIndex(index); + const removeDefGroup = (groupIndex) => { + setFilters(filters.filter((f4, i4) => i4 == groupIndex ? false : true)); }; - const onKeyDown = (e4) => { - const setCellValue = (value) => { - var _a2; - const columnTuple = selectedColumn.split("#"); - updateValue2( - columnTuple[0], - value, - (_a2 = columnTuple[1]) != null ? _a2 : "", - parseInt(lastSelectedIndex), - "" - ); - }; - const clearCell = () => { - setCellValue(""); - }; - const copyCell = () => { - navigator.clipboard.writeText( - tableData.rows[parseInt(lastSelectedIndex)][selectedColumn] - ); - }; - const nextRow = () => { - const newIndex = selectNextIndex( - lastSelectedIndex, - data.map((f4) => f4._index) - ); - selectRows(newIndex, [newIndex]); - setLastSelectedIndex(newIndex); - }; - const lastRow = () => { - const newIndex = selectPrevIndex( - lastSelectedIndex, - data.map((f4) => f4._index) - ); - selectRows(newIndex, [newIndex]); - setLastSelectedIndex(newIndex); - }; - if (e4.key == "c" && e4.metaKey) { - copyCell(); - } - if (e4.key == "x" && e4.metaKey) { - copyCell(); - clearCell(); + const typeForField = (type, field) => { + if (type == "frontmatter") { + return "text"; } - if (e4.key == "v" && e4.metaKey) { - navigator.clipboard.readText().then((f4) => setCellValue(f4)); + if (type == "filemeta") { + return fileMeta[field].vType; } - if (e4.key == "Escape") { - selectRows(null, []); - setLastSelectedIndex(null); + if (type == "fileprop") { + return fileProps[field].vType; } - if (e4.key == "Backspace" || e4.key == "Delete") { - clearCell(); + return "text"; + }; + const setDefFilter = (filter, groupIndex, filterIndex) => { + var _a2; + let field; + let fType; + const filterTuple = filter.split("."); + const type = filterTuple[0]; + if (type == "frontmatter") { + fType = filterTuple[1]; + field = filterTuple[2]; + } else { + field = filterTuple[1]; + fType = typeForField(type, field); } - if (e4.key == "Enter") { - if (selectedColumn && lastSelectedIndex) { - if (e4.shiftKey) { - newRow(parseInt(lastSelectedIndex) + 1); - nextRow(); - } else { - setCurrentEdit([selectedColumn, lastSelectedIndex]); + if (filters.length == 0) { + setFilters([ + { + type: "any", + trueFalse: true, + filters: [ + { + type, + field, + fType, + fn: "", + value: "" + } + ] } - } + ]); return; } - if (e4.key == "ArrowDown") { - nextRow(); - e4.preventDefault(); - } - if (e4.key == "ArrowUp") { - lastRow(); - e4.preventDefault(); - } - if (e4.key == "ArrowLeft") { - const newIndex = selectPrevIndex( - selectedColumn, - columns.map((f4) => f4.accessorKey).filter((f4) => f4 != "+") + if (((_a2 = filters[groupIndex]) == null ? void 0 : _a2.filters.length) == 0) { + setFilters( + filters.map( + (f4, i4) => i4 == groupIndex ? { + ...f4, + filters: [ + { + type, + field, + fType, + fn: "", + value: "" + } + ] + } : f4 + ) ); - setSelectedColumn(newIndex); + return; } - if (e4.key == "ArrowRight") { - const newIndex = selectNextIndex( - selectedColumn, - columns.map((f4) => f4.accessorKey).filter((f4) => f4 != "+") + setFilters( + filters.map( + (f4, i4) => { + var _a3; + return i4 == groupIndex ? { + ...f4, + filters: !f4.filters || filterIndex == f4.filters.length ? [ + ...(_a3 = f4.filters) != null ? _a3 : [], + { + type, + fType, + field, + fn: "", + value: "" + } + ] : f4.filters.map( + (g4, k5) => k5 == filterIndex ? { + ...g4, + type, + fType, + field + } : g4 + ) + } : f4; + } + ) + ); + }; + const setDefFilterFn = (fn2, groupIndex, filterIndex) => { + setFilters( + filters.map( + (f4, i4) => i4 == groupIndex ? { + ...f4, + filters: f4.filters.map( + (g4, k5) => k5 == filterIndex ? { + ...g4, + fn: fn2 + } : g4 + ) + } : f4 + ) + ); + }; + const setDefFilterValue = (value, groupIndex, filterIndex) => { + setFilters( + filters.map( + (f4, i4) => i4 == groupIndex ? { + ...f4, + filters: f4.filters.map( + (g4, k5) => k5 == filterIndex ? { + ...g4, + value + } : g4 + ) + } : f4 + ) + ); + }; + const removeDefFilter = (filterIndex, groupIndex) => { + setFilters( + filters.map( + (f4, i4) => i4 == groupIndex ? { + ...f4, + filters: f4.filters.filter( + (g4, k5) => k5 == filterIndex ? false : true + ) + } : f4 + ) + ); + }; + const setGroupType = (groupIndex, type) => { + if (groupIndex == 0 && filters.length == 0) { + setFilters([ + { + type, + trueFalse: true, + filters: [] + } + ]); + } else { + setFilters( + filters.map( + (f4, i4) => i4 == groupIndex ? { + ...f4, + type + } : f4 + ) ); - setSelectedColumn(newIndex); } }; - const columns = F2( - () => { - var _a2; - return [ - ...(_a2 = cols == null ? void 0 : cols.filter((f4) => f4.type != "preview").map((f4) => { - return { - header: f4.name, - accessorKey: f4.name + f4.table, - meta: { - table: f4.table, - editable: f4.primary != "true", - schemaId: dbSchema == null ? void 0 : dbSchema.id - }, - cell: ({ - getValue, - row: { index }, - column: { colId }, - cell, - table: table2 - }) => { - const initialValue = getValue(); - const rowIndex = parseInt( - data[index]["_index" + f4.table] - ); - const tableIndex = parseInt(data[index]["_index"]); - const saveValue = (value) => { - var _a3; - setCurrentEdit(null); - if (initialValue != value) - (_a3 = table2.options.meta) == null ? void 0 : _a3.updateData( - f4.name, - value, - f4.table, - rowIndex - ); - }; - const saveFieldValue = (fieldValue, value) => { - var _a3; - (_a3 = table2.options.meta) == null ? void 0 : _a3.updateFieldValue( - f4.name, - fieldValue, - value, - f4.table, - rowIndex - ); - }; - const editMode = readMode ? -1 /* EditModeReadOnly */ : !cell.getIsGrouped() ? platformIsMobile() ? 3 /* EditModeAlways */ : currentEdit && currentEdit[0] == f4.name + f4.table && currentEdit[1] == tableIndex.toString() ? 2 /* EditModeActive */ : 1 /* EditModeView */ : -1 /* EditModeReadOnly */; - const cellProps = { - initialValue, - saveValue, - plugin: props2.plugin, - setEditMode: setCurrentEdit, - editMode, - propertyValue: f4.value - }; - const fieldType = fieldTypeForType(f4.type); - if (!fieldType) { - return /* @__PURE__ */ Cn.createElement(Cn.Fragment, null, initialValue); - } - if (fieldType.type == "file") { - return /* @__PURE__ */ Cn.createElement(FileCell, { - ...cellProps, - multi: fieldType.multiType == f4.type, - folder: contextInfo.contextPath, - isFolder: contextInfo.type == "folder", - openFlow: () => toggleFlow(initialValue), - deleteRow: () => deleteRow(index) - }); - } else if (fieldType.type == "boolean") { - return /* @__PURE__ */ Cn.createElement(BooleanCell, { - ...cellProps, - column: f4 - }); - } else if (fieldType.type == "option") { - return /* @__PURE__ */ Cn.createElement(OptionCell, { - ...cellProps, - options: f4.value, - multi: fieldType.multiType == f4.type, - saveOptions: saveFieldValue - }); - } else if (fieldType.type == "date") { - return /* @__PURE__ */ Cn.createElement(DateCell, { - ...cellProps - }); - } else if (fieldType.type == "context") { - return /* @__PURE__ */ Cn.createElement(ContextCell, { - ...cellProps, - multi: fieldType.multiType == f4.type, - contextTable: contextTable[f4.value], - contextTag: f4.value - }); - } else if (fieldType.type == "fileprop") { - return /* @__PURE__ */ Cn.createElement(LookUpCell, { - ...cellProps, - file: data[index][FilePropertyName] - }); - } else if (fieldType.type == "tag") { - return /* @__PURE__ */ Cn.createElement(TagCell, { - ...cellProps, - multi: fieldType.multiType == f4.type - }); - } else if (fieldType.type == "number") { - return /* @__PURE__ */ Cn.createElement(NumberCell, { - ...cellProps - }); - } else if (fieldType.type == "link") { - return /* @__PURE__ */ Cn.createElement(LinkCell, { - ...cellProps, - multi: fieldType.multiType == f4.type, - file: data[index][FilePropertyName] - }); - } else if (fieldType.type == "image") { - return /* @__PURE__ */ Cn.createElement(ImageCell, { - ...cellProps - }); - } else { - return /* @__PURE__ */ Cn.createElement(TextCell, { - ...cellProps - }); - } - } - }; - })) != null ? _a2 : [], - ...readMode ? [] : [ - { - header: "+", - meta: { schemaId: dbSchema == null ? void 0 : dbSchema.id }, - accessorKey: "+", - size: 20, - cell: () => /* @__PURE__ */ Cn.createElement(Cn.Fragment, null) - } - ] - ]; - }, - [cols, currentEdit, predicate, contextTable, toggleFlow, openFlows] - ); - const groupBy2 = F2( - () => { - var _a2; - return ((_a2 = predicate.groupBy) == null ? void 0 : _a2.length) > 0 && cols.find((f4) => f4.name + f4.table == predicate.groupBy[0]) ? predicate.groupBy : []; - }, - [predicate, cols] - ); - const table = useReactTable({ - data, - columns, - columnResizeMode: "onChange", - state: { - columnVisibility: predicate.colsHidden.reduce( - (p3, c4) => ({ ...p3, [c4]: false }), - {} - ), - columnOrder: predicate.colsOrder, - columnSizing: { - ...columns.reduce((p3, c4) => ({ ...p3, [c4.accessorKey]: 150 }), {}), - ...colsSize - }, - grouping: groupBy2, - expanded: true - }, - onColumnSizingChange: saveColsSize, - getCoreRowModel: getCoreRowModel(), - getExpandedRowModel: getExpandedRowModel(), - getGroupedRowModel: getGroupedRowModel(), - meta: { - updateData: updateValue2, - updateFieldValue + const selectGroupType = (e4, i4) => { + const offset2 = e4.target.getBoundingClientRect(); + const filters2 = ["any", "all"]; + showSelectMenu( + { x: offset2.left, y: offset2.top + 30 }, + { + plugin: props2.plugin, + multi: false, + editable: false, + value: [], + options: filters2.map((f4) => ({ name: f4, value: f4 })), + saveOptions: (_12, value) => setGroupType(i4, value[0]), + searchable: false, + showAll: true + } + ); + }; + const selectFilter = (e4, i4, k5) => { + const offset2 = e4.target.getBoundingClientRect(); + const { type, field, fType } = filters[i4].filters[k5]; + const _filters = predicateFnsForType(fType, filterFnTypes); + showSelectMenu( + { x: offset2.left, y: offset2.top + 30 }, + { + plugin: props2.plugin, + multi: false, + editable: true, + value: [], + options: _filters.map((f4) => ({ name: filterFnLabels[f4], value: f4 })), + saveOptions: (_12, value) => setDefFilterFn(value[0], i4, k5), + placeholder: i18n_default.labels.contextItemSelectPlaceholder, + searchable: true, + showAll: true + } + ); + }; + const selectField = (e4, i4, k5) => { + const offset2 = e4.target.getBoundingClientRect(); + const allFiles = retrieveAllFiles( + props2.plugin.index.vaultDBCache, + props2.plugin.settings + ); + const frontmatter = allMetadataForFiles( + props2.plugin, + allFiles.map((f5) => getAbstractFileAtPath(props2.plugin, f5.path)).filter((f5) => f5 instanceof import_obsidian40.TFile) + ); + const fmTypes = guestimateTypes( + allFiles.map((f5) => f5.path), + props2.plugin, + false + ); + const f4 = [ + ...Object.keys(fileMeta).map((f5) => ({ + name: fileMeta[f5].label, + value: "filemeta." + f5 + })), + ...Object.keys(fileProps).map((f5) => ({ + name: fileProps[f5].label, + value: "fileprop." + f5 + })), + ...frontmatter.map((f5) => ({ + name: f5.name, + value: "frontmatter." + fmTypes[f5.name] + "." + f5.name + })) + ]; + showSelectMenu( + { x: offset2.left, y: offset2.top + 30 }, + { + plugin: props2.plugin, + multi: false, + editable: false, + value: [], + options: f4, + saveOptions: (_12, value) => setDefFilter(value[0], i4, k5), + placeholder: i18n_default.labels.contextItemSelectPlaceholder, + searchable: true, + showAll: true + } + ); + }; + return /* @__PURE__ */ Cn.createElement("div", { + className: "mk-query" + }, filters.length == 0 ? /* @__PURE__ */ Cn.createElement(DefFilterGroup, { + selectGroupType, + group: null, + addDefGroup, + selectField, + i: 0, + removeDefGroup + }) : filters.map((f4, i4) => /* @__PURE__ */ Cn.createElement(DefFilterGroup, { + key: i4, + group: f4, + selectGroupType, + addDefGroup, + selectField, + i: i4, + removeDefGroup + }, f4.filters.map((filter, k5) => /* @__PURE__ */ Cn.createElement(DefFilter, { + key: k5, + filter, + i: i4, + k: k5, + selectField, + selectFilter, + selectFilterValue, + removeDefFilter + }))))); +}; +var DefFilter = (props2) => { + var _a2; + const { + filter, + selectField, + selectFilter, + selectFilterValue, + removeDefFilter, + i: i4, + k: k5 + } = props2; + return /* @__PURE__ */ Cn.createElement("div", { + className: "mk-filter" + }, /* @__PURE__ */ Cn.createElement("span", { + onClick: (e4) => selectField(e4, i4, k5) + }, filter.field.length == 0 ? "Select" : filter.field), filter.field.length > 0 && /* @__PURE__ */ Cn.createElement("span", { + onClick: (e4) => selectFilter(e4, i4, k5) + }, !filterFnLabels[filter.fn] ? "Select" : filterFnLabels[filter.fn]), filter.field.length > 0 && filterFnLabels[filter.fn] && ((_a2 = filterFnTypes[filter.fn]) == null ? void 0 : _a2.valueType) != "none" && /* @__PURE__ */ Cn.createElement("span", null, /* @__PURE__ */ Cn.createElement(FilterValueSpan, { + fieldType: filter.fType, + filter, + selectFilterValue: (e4, h5) => selectFilterValue(e4, h5, i4, k5) + })), /* @__PURE__ */ Cn.createElement("span", { + onClick: () => removeDefFilter(k5, i4) + }, /* @__PURE__ */ Cn.createElement("div", { + className: "mk-icon-xsmall", + dangerouslySetInnerHTML: { __html: uiIconSet["mk-ui-close"] } + }))); +}; +var DefFilterGroup = (props2) => { + var _a2; + const { + group, + selectGroupType, + addDefGroup, + selectField, + i: i4, + removeDefGroup + } = props2; + return /* @__PURE__ */ Cn.createElement("div", { + className: "mk-query-group" + }, /* @__PURE__ */ Cn.createElement("div", { + className: "mk-query-group-type" + }, /* @__PURE__ */ Cn.createElement("span", { + onClick: (e4) => selectGroupType(e4, i4), + dangerouslySetInnerHTML: { + __html: uiIconSet[`mk-ui-${(_a2 = group == null ? void 0 : group.type) != null ? _a2 : "any"}`] } - }); - const sensors = useSensors( - useSensor(MouseSensor, { - activationConstraint: { - distance: 10 - } - }), - useSensor(TouchSensor, { - activationConstraint: { - delay: 250, - tolerance: 5 - } - }) - ); - const measuring = { - droppable: { - strategy: MeasuringStrategy.Always + })), /* @__PURE__ */ Cn.createElement("div", { + className: "mk-filter-bar mk-query-filters" + }, props2.children, /* @__PURE__ */ Cn.createElement("div", { + className: "mk-filter", + onClick: (e4) => { + var _a3; + return selectField(e4, i4, (_a3 = group == null ? void 0 : group.filters.length) != null ? _a3 : 0); } - }; - function handleDragStart(event) { - const { - active: { id: activeId2 } - } = event; - setActiveId(activeId2); - setOverId(overId); - document.body.style.setProperty("cursor", "grabbing"); - } - function handleDragOver({ over }) { - var _a2; - const overId2 = over == null ? void 0 : over.id; - if (overId2) { - setOverId((_a2 = over == null ? void 0 : over.id) != null ? _a2 : null); + }, /* @__PURE__ */ Cn.createElement("span", null, /* @__PURE__ */ Cn.createElement("span", { + className: "mk-icon-xsmall", + dangerouslySetInnerHTML: { __html: uiIconSet["mk-ui-plus"] } + }), "Filter"))), /* @__PURE__ */ Cn.createElement("div", { + className: "mk-icon-small", + dangerouslySetInnerHTML: { + __html: uiIconSet["mk-ui-close"] + }, + onClick: (e4) => { + removeDefGroup(i4); } - } - const saveFilter = (filter) => { - savePredicate({ - ...predicate, - filters: [ - ...predicate.filters.filter((s5) => s5.field != filter.field), - filter - ] + })); +}; + +// src/components/Navigator/SpaceEditor.tsx +var SpaceEditor = (props2) => { + var _a2, _b2, _c2, _d2, _e2, _f, _g, _h, _i, _j, _k, _l, _m, _n2; + const [metadata, setMetadata] = h2((_a2 = props2.metadata) != null ? _a2 : {}); + const [columns, setColumns] = h2([]); + const [predicate, setPredicate] = h2(defaultPredicate); + const [name, setName] = h2((_c2 = (_b2 = props2.space) == null ? void 0 : _b2.name) != null ? _c2 : ""); + const saveMetadata = (metadata2) => { + setMetadata(metadata2); + }; + const saveQuery = (q5) => { + saveMetadata({ + ...metadata, + filters: q5 }); }; - const selectCell = (e4, index, column) => { - if (platformIsMobile() || column == "+") + const linkCaches = F2( + () => { + var _a3; + return ((_a3 = metadata == null ? void 0 : metadata.links) != null ? _a3 : []).map((f4) => uriByString(props2.plugin, f4)).filter((f4) => f4).map((f4) => props2.plugin.index.cacheForURI(f4)).filter((f4) => f4); + }, + [metadata] + ); + const saveSpace = async () => { + var _a3, _b3; + const newName = name.replace(/\//g, ""); + const parentPath = (_b3 = (_a3 = props2.space) == null ? void 0 : _a3.parent) != null ? _b3 : props2.parent.path; + const newPath = !parentPath || parentPath == "/" ? newName : parentPath + "/" + newName; + if (newName.length == 0) { + new import_obsidian41.Notice(i18n_default.notice.newSpaceName); return; - selectItem(0, data[index]["_index"]); - setSelectedColumn(column); - if (e4.detail === 1) { - } else if (e4.detail === 2) { - setCurrentEdit([column, data[index]["_index"]]); } - }; - const showContextMenu = (e4, index) => { - e4.preventDefault(); - const menu = new import_obsidian31.Menu(); - menu.addItem((item) => { - item.setIcon("trash"); - item.setTitle(i18n_default.menu.deleteRow); - item.onClick(() => { - deleteRow(index); + if (props2.plugin.index.spacesIndex.has(newPath) && (!props2.space || newPath != props2.space.path)) { + new import_obsidian41.Notice(i18n_default.notice.duplicateSpaceName); + return; + } + if (props2.space) { + saveSpaceCache(props2.plugin, props2.space.space, metadata).then((f4) => { + if (newName != props2.space.name) + renamePath(props2.plugin, props2.space.space.uri, newName); }); - }); - if (isMouseEvent(e4)) { - menu.showAtPosition({ x: e4.pageX, y: e4.pageY }); } else { - menu.showAtPosition({ - x: e4.nativeEvent.locationX, - y: e4.nativeEvent.locationY - }); + let newMetadata = metadata; + if (props2.parent && props2.parent.type == "tag") { + newMetadata = { + ...metadata != null ? metadata : {}, + tags: [props2.parent.name.replace("#", "")] + }; + } + const newSpace = await insertSpaceAtIndex( + props2.plugin, + newPath, + newMetadata != null ? newMetadata : {} + ); + insertContextColumns(props2.plugin, newSpace.space, columns); + if (!props2.dontOpen) + openSpace(newPath, props2.plugin, false); } }; - function handleDragEnd({ active, over }) { - resetState(); - savePredicate({ - ...predicate, - colsOrder: arrayMove( - predicate.colsOrder, - predicate.colsOrder.findIndex((f4) => f4 == activeId), - predicate.colsOrder.findIndex((f4) => f4 == overId) - ) - }); - } - function handleDragCancel() { - resetState(); - } - function resetState() { - setOverId(null); - setActiveId(null); - document.body.style.setProperty("cursor", ""); - } - return /* @__PURE__ */ Cn.createElement(DndContext, { - sensors, - collisionDetection: closestCenter, - measuring, - onDragStart: handleDragStart, - onDragOver: handleDragOver, - onDragEnd: handleDragEnd, - onDragCancel: handleDragCancel + const folderContents = ((_d2 = props2.space) == null ? void 0 : _d2.type) == "folder" ? (_f = (_e2 = getAbstractFileAtPath(props2.plugin, props2.space.path)) == null ? void 0 : _e2.children) != null ? _f : [] : []; + return /* @__PURE__ */ Cn.createElement(Cn.Fragment, null, /* @__PURE__ */ Cn.createElement("div", { + className: "mk-space-editor" }, /* @__PURE__ */ Cn.createElement("div", { - className: "mk-table", - ref, - tabIndex: 1, - onKeyDown - }, /* @__PURE__ */ Cn.createElement("table", { - ...{} - }, /* @__PURE__ */ Cn.createElement("thead", null, table.getHeaderGroups().map((headerGroup) => /* @__PURE__ */ Cn.createElement("tr", { - key: headerGroup.id - }, /* @__PURE__ */ Cn.createElement("th", null), headerGroup.headers.map((header) => { - var _a2; - return /* @__PURE__ */ Cn.createElement("th", { - className: "mk-th", - key: header.id, - style: { - minWidth: header.column.getIsGrouped() ? "0px" : (_a2 = colsSize[header.column.columnDef.accessorKey]) != null ? _a2 : "150px" - } - }, header.isPlaceholder ? null : header.column.columnDef.header != "+" ? header.column.getIsGrouped() ? /* @__PURE__ */ Cn.createElement(Cn.Fragment, null) : /* @__PURE__ */ Cn.createElement(ColumnHeader, { - plugin: props2.plugin, - editable: header.column.columnDef.meta.editable, - column: cols.find( - (f4) => f4.name == header.column.columnDef.header && f4.table == header.column.columnDef.meta.table + className: "mk-space-editor-appearance" + }, /* @__PURE__ */ Cn.createElement("div", { + className: `mk-file-icon` + }, /* @__PURE__ */ Cn.createElement("button", { + "aria-label": i18n_default.buttons.changeIcon, + style: ((_g = metadata.color) == null ? void 0 : _g.length) > 0 ? { + "--label-color": `${metadata.color}`, + "--icon-color": `#ffffff` + } : { + "--icon-color": `var(--text-muted)` + }, + dangerouslySetInnerHTML: metadata.sticker ? { + __html: stickerFromString(metadata.sticker, props2.plugin) + } : { + __html: stickerFromString( + iconForSpaceType( + (_i = (_h = props2.space) == null ? void 0 : _h.type) != null ? _i : "folder", + (_j = props2.space) == null ? void 0 : _j.path, + true + ), + props2.plugin ) - }) : /* @__PURE__ */ Cn.createElement(ColumnHeader, { - plugin: props2.plugin, - isNew: true, - editable: true, - column: { - name: "", - schemaId: header.column.columnDef.meta.schemaId, - type: "text", - table: "" - } - }), /* @__PURE__ */ Cn.createElement("div", { - ...{ - onMouseDown: header.getResizeHandler(), - onTouchStart: header.getResizeHandler(), - className: `mk-resizer ${header.column.getIsResizing() ? "isResizing" : ""}` - } - })); - })))), /* @__PURE__ */ Cn.createElement("tbody", null, table.getRowModel().rows.map((row) => /* @__PURE__ */ Cn.createElement(Cn.Fragment, null, /* @__PURE__ */ Cn.createElement("tr", { - className: (selectedRows == null ? void 0 : selectedRows.some( - (f4) => f4 == data[row.index]["_index"] - )) && "mk-is-active", - onContextMenu: (e4) => { - const rowIndex = parseInt( - data[row.index]["_index"] - ); - showContextMenu(e4, rowIndex); }, - key: row.id - }, /* @__PURE__ */ Cn.createElement("td", null), row.getVisibleCells().map( - (cell) => { - var _a2, _b2; - return cell.getIsGrouped() ? /* @__PURE__ */ Cn.createElement("td", { - className: "mk-td-group", - colSpan: cols.length + (readMode ? 0 : 1) - }, /* @__PURE__ */ Cn.createElement("div", { - ...{ - onClick: row.getToggleExpandedHandler(), - style: { - display: "flex", - alignItems: "center", - cursor: "normal" + onClick: (e4) => { + const vaultChangeModal = new stickerModal( + props2.plugin.app, + props2.plugin, + (emoji) => saveMetadata({ ...metadata, sticker: emoji }) + ); + vaultChangeModal.open(); + } + })), /* @__PURE__ */ Cn.createElement("div", { + className: "mk-space-editor-input" + }, /* @__PURE__ */ Cn.createElement("input", { + autoFocus: true, + placeholder: "Space Name", + value: name, + onChange: (e4) => setName(e4.target.value) + }))), /* @__PURE__ */ Cn.createElement("div", { + className: "mk-space-editor-section" + }, /* @__PURE__ */ Cn.createElement("div", { + className: "mk-space-editor-title" + }, "Items", /* @__PURE__ */ Cn.createElement("span", null), /* @__PURE__ */ Cn.createElement("button", { + "aria-label": "Add Smart Search", + onClick: (e4) => { + var _a3; + return saveMetadata({ + ...metadata, + filters: [ + ...(_a3 = metadata.filters) != null ? _a3 : [], + { + type: "any", + trueFalse: true, + filters: [] } - } - }, flexRender( - cell.column.columnDef.cell, - cell.getContext() - ), " ", "(", row.subRows.length, ")")) : cell.getIsAggregated() ? flexRender( - (_a2 = cell.column.columnDef.aggregatedCell) != null ? _a2 : cell.column.columnDef.cell, - cell.getContext() - ) : /* @__PURE__ */ Cn.createElement("td", { - onClick: (e4) => selectCell( - e4, - cell.row.index, - cell.column.columnDef.accessorKey - ), - className: `${cell.column.columnDef.accessorKey == selectedColumn ? "mk-selected-cell " : ""} mk-td ${cell.getIsPlaceholder() ? "mk-td-empty" : ""}`, - key: cell.id, - style: { - minWidth: cell.getIsPlaceholder() ? "0px" : (_b2 = colsSize[cell.column.columnDef.accessorKey]) != null ? _b2 : "50px" - } - }, cell.getIsPlaceholder() ? null : flexRender( - cell.column.columnDef.cell, - cell.getContext() - )); + ] + }); + }, + dangerouslySetInnerHTML: { + __html: stickerFromString("lucide//zoom-in", props2.plugin) } - ))))), /* @__PURE__ */ Cn.createElement("tfoot", null, contextInfo.type == "folder" && !readMode ? /* @__PURE__ */ Cn.createElement("tr", null, /* @__PURE__ */ Cn.createElement("th", { - className: "mk-row-new", - colSpan: cols.length + (readMode ? 1 : 2), + }), /* @__PURE__ */ Cn.createElement("button", { + onClick: (e4) => showLinkMenu( + e4, + props2.plugin, + (link) => { + var _a3; + return saveMetadata({ + ...metadata, + links: [...(_a3 = metadata.links) != null ? _a3 : [], link] + }); + } + ) + }, "Add Item")), ((_k = props2.space) == null ? void 0 : _k.type) == "tag" ? /* @__PURE__ */ Cn.createElement(Cn.Fragment, null) : /* @__PURE__ */ Cn.createElement("div", { + className: "mk-space-editor-contents" + }, folderContents.map((f4, i4) => /* @__PURE__ */ Cn.createElement("div", { + key: i4, + className: "mk-space-editor-link" + }, /* @__PURE__ */ Cn.createElement(FileStickerContainer, { + plugin: props2.plugin, + path: uriByString(props2.plugin, f4.path) + }), f4.name, /* @__PURE__ */ Cn.createElement("span", null))), linkCaches.map((f4, i4) => /* @__PURE__ */ Cn.createElement("div", { + key: i4, + className: "mk-space-editor-link" + }, /* @__PURE__ */ Cn.createElement(FileSticker, { + plugin: props2.plugin, + fileCache: f4 + }), f4.name, /* @__PURE__ */ Cn.createElement("span", null), /* @__PURE__ */ Cn.createElement("div", { + className: "mk-icon-small", + dangerouslySetInnerHTML: { + __html: uiIconSet["mk-ui-close"] + }, + onClick: (e4) => { + var _a3; + saveMetadata({ + ...metadata, + links: [ + ...((_a3 = metadata.links) != null ? _a3 : []).filter((g4) => g4 != f4.path) + ] + }); + } + }))), ((_l = metadata == null ? void 0 : metadata.filters) == null ? void 0 : _l.length) > 0 && /* @__PURE__ */ Cn.createElement(SpaceQuery, { + plugin: props2.plugin, + filters: (_m = metadata.filters) != null ? _m : [], + setFilters: saveQuery + }))), !props2.space && /* @__PURE__ */ Cn.createElement("div", { + className: "mk-space-editor-section" + }, /* @__PURE__ */ Cn.createElement("div", { + className: "mk-space-editor-title" + }, "Properties"), /* @__PURE__ */ Cn.createElement(SpacePropertyEditor, { + plugin: props2.plugin, + colsOrder: predicate.colsOrder, + setColumnOrder: function(cols) { + setPredicate({ ...predicate, colsOrder: cols }); + }, + colsHidden: predicate.colsHidden, + columns, + contexts: (_n2 = metadata.contexts) != null ? _n2 : [], + saveContexts: function(contexts) { + setMetadata({ ...metadata, contexts }); + }, + hideColumn: function(col, hidden) { + setPredicate({ + ...predicate, + colsHidden: hidden ? [ + ...predicate.colsHidden.filter((s5) => s5 != col.name), + col.name + ] : predicate.colsHidden.filter((s5) => s5 != col.name) + }); + }, + delColumn: function(column) { + setColumns(columns.filter((f4, i4) => f4.name != column.name)); + }, + saveColumn: function(column, oldColumn) { + const oldFieldIndex = oldColumn ? columns.findIndex((f4) => f4.name == oldColumn.name) : -1; + const newFields = oldFieldIndex == -1 ? [...columns, column] : columns.map((f4, i4) => i4 == oldFieldIndex ? column : f4); + setColumns(newFields); + } + }))), /* @__PURE__ */ Cn.createElement("div", { + className: "mk-space-editor-controls" + }, /* @__PURE__ */ Cn.createElement("button", { + className: "mod-cta", onClick: () => { - newRow(); + saveSpace(); + props2.close(); } - }, "+ New")) : /* @__PURE__ */ Cn.createElement(Cn.Fragment, null))), z3( - /* @__PURE__ */ Cn.createElement(DragOverlay, { - dropAnimation: null, - zIndex: 1600 - }, activeId ? /* @__PURE__ */ Cn.createElement(ColumnHeader, { - plugin: props2.plugin, - editable: false, - column: { - name: activeId, - schemaId: tableData.schema.id, - type: "text", - table: "" - } - }) : null), - document.body - ))); + }, "Save"), /* @__PURE__ */ Cn.createElement("button", { + onClick: () => props2.close() + }, "Cancel"))); }; +var SpaceEditor_default = SpaceEditor; -// src/components/ContextView/DataTypeView/BooleanCell.tsx -var BooleanCell = (props2) => { - const { initialValue, saveValue } = props2; - const [value, setValue] = Cn.useState(initialValue == "true"); - const onChange = () => { - if (props2.editMode == -1 /* EditModeReadOnly */) { - return; +// src/components/UI/modals/editSpaceModal.tsx +var import_obsidian42 = require("obsidian"); +var EditSpaceModal = class extends import_obsidian42.Modal { + constructor(plugin, space, action, metadata, parent, dontOpen) { + super(plugin.app); + this.space = space; + if (this.space) { + this.name = space.name; } - setValue(!value); - saveValue(!value ? "true" : "false"); - }; - p2(() => { - if (props2.editMode == 2 /* EditModeActive */) { - setValue(!value); - saveValue(!value ? "true" : "false"); - props2.setEditMode(null); + this.parent = parent; + this.action = action; + this.plugin = plugin; + this.metadata = metadata; + this.dontOpen = dontOpen; + } + onOpen() { + const { contentEl } = this; + let headerText; + if (this.action === "rename") { + headerText = i18n_default.labels.renameSection; + } else if (this.action === "create") { + headerText = i18n_default.labels.createSection; } - }, [props2.editMode]); - Cn.useEffect(() => { - setValue(initialValue == "true"); - }, [initialValue]); - if (props2.editMode < 1 /* EditModeView */) { - return /* @__PURE__ */ Cn.createElement("div", { - className: "mk-cell-boolean" - }, /* @__PURE__ */ Cn.createElement("input", { - type: "checkbox", - checked: value, - onChange - }), /* @__PURE__ */ Cn.createElement("div", null, props2.column.name)); + this.titleEl.innerText = headerText; + const queryEl = contentEl.createDiv("mk-space-query"); + const root = createRoot(queryEl); + root.render( + /* @__PURE__ */ Cn.createElement(SpaceEditor_default, { + plugin: this.plugin, + space: this.space, + parent: this.parent, + metadata: this.metadata, + close: () => this.close() + }) + ); + } + onClose() { + const { contentEl } = this; + contentEl.empty(); + } +}; + +// src/components/UI/menus/fileMenu.tsx +var import_obsidian43 = require("obsidian"); +var showSpaceAddMenu = (plugin, e4, space, dontOpen) => { + const fileMenu = new import_obsidian43.Menu(); + fileMenu.addItem((menuItem) => { + menuItem.setIcon("edit"); + menuItem.setTitle(i18n_default.buttons.createNote); + menuItem.onClick((ev) => { + newFileInSpace(plugin, space, null, false, dontOpen); + }); + }); + fileMenu.addItem((menuItem) => { + menuItem.setIcon("layout-dashboard"); + menuItem.setTitle(i18n_default.buttons.createCanvas); + menuItem.onClick((ev) => { + newFileInSpace(plugin, space, null, true, dontOpen); + }); + }); + fileMenu.addItem((menuItem) => { + menuItem.setIcon("plus"); + menuItem.setTitle(i18n_default.buttons.createFolder); + menuItem.onClick((ev) => { + const vaultChangeModal = new EditSpaceModal( + plugin, + null, + "create", + null, + space, + dontOpen + ); + vaultChangeModal.open(); + }); + }); + if (isMouseEvent(e4)) { + fileMenu.showAtPosition({ x: e4.pageX, y: e4.pageY }); + } else { + fileMenu.showAtPosition({ + x: e4.nativeEvent.locationX, + y: e4.nativeEvent.locationY + }); + } + return false; +}; +var triggerSpaceMenu = (plugin, space, e4, activeFile, parentSpace) => { + if (!space) + return; + const spaceMenu = new import_obsidian43.Menu(); + spaceMenu.addItem((menuItem) => { + menuItem.setIcon("arrow-up-right"); + menuItem.setTitle("Open Space"); + menuItem.onClick((ev) => { + openSpace(space.path, plugin, false); + }); + }); + spaceMenu.addItem((menuItem) => { + menuItem.setIcon("arrow-up-right"); + menuItem.setTitle("Reveal in Finder"); + menuItem.onClick((ev) => { + const file = getAbstractFileAtPath( + plugin, + space.type == "folder" ? space.path : `${plugin.settings.spacesFolder}/${space.name}` + ); + if (file instanceof import_obsidian43.TFolder) { + const leaf = plugin.app.workspace.getLeaf(false); + app.workspace.setActiveLeaf(leaf, { focus: true }); + leaf.openFile(file, { eState: { focus: true } }); + } + }); + }); + spaceMenu.addSeparator(); + spaceMenu.addItem((menuItem) => { + menuItem.setIcon("edit"); + menuItem.setTitle(i18n_default.buttons.createNote); + menuItem.onClick((ev) => { + newFileInSpace(plugin, space, activeFile); + }); + }); + spaceMenu.addItem((menuItem) => { + menuItem.setIcon("layout-dashboard"); + menuItem.setTitle(i18n_default.buttons.createCanvas); + menuItem.onClick((ev) => { + newFileInSpace(plugin, space, activeFile, true); + }); + }); + spaceMenu.addItem((menuItem) => { + menuItem.setIcon("folder-plus"); + menuItem.setTitle(i18n_default.buttons.createFolder); + menuItem.onClick((ev) => { + const vaultChangeModal = new EditSpaceModal( + plugin, + null, + "create", + null, + space + ); + vaultChangeModal.open(); + }); + }); + spaceMenu.addSeparator(); + spaceMenu.addItem((menuItem) => { + menuItem.setIcon("plus-square"); + menuItem.setTitle("Add to Space"); + menuItem.onClick((ev) => { + showSpacesMenu(e4, plugin, (link) => { + movePathsToSpace( + plugin, + [space.path], + plugin.index.spacesIndex.get(link), + -1, + "link" + ); + }); + }); + }); + spaceMenu.addItem((menuItem) => { + const pinned = plugin.settings.waypoints.some((f4) => f4 == space.path); + menuItem.setTitle(pinned ? i18n_default.menu.unpinSpace : i18n_default.menu.pinSpace); + menuItem.setIcon("pin"); + menuItem.onClick((ev) => { + toggleSpacePin(plugin, space.path, "pinned", pinned); + }); + }); + if (parentSpace && parentSpace != space.parent) { + const spaceCache = plugin.index.spacesIndex.get(parentSpace); + if (spaceCache) { + spaceMenu.addItem((menuItem) => { + menuItem.setIcon("minus-square"); + menuItem.setTitle(i18n_default.menu.removeFromSpace); + menuItem.onClick((ev) => { + removePathsFromSpace(plugin, spaceCache, [space.path]); + }); + }); + } + } + spaceMenu.addSeparator(); + if (plugin.settings.spacesStickers) { + spaceMenu.addSeparator(); + spaceMenu.addItem((menuItem) => { + menuItem.setIcon("palette"); + disclosureMenuItem( + plugin, + menuItem, + false, + false, + i18n_default.menu.changeColor, + "", + [ + { name: "None", value: "" }, + ...colors.map((f4) => ({ name: f4[0], value: f4[1] })) + ], + (_12, values) => { + saveSpaceColor(plugin, space.path, values[0]); + } + ); + }); + spaceMenu.addItem((menuItem) => { + menuItem.setTitle(i18n_default.buttons.changeIcon); + menuItem.setIcon("lucide-sticker"); + menuItem.onClick((ev) => { + const vaultChangeModal = new stickerModal( + plugin.app, + plugin, + (emoji) => saveSpaceSticker(plugin, space.path, emoji) + ); + vaultChangeModal.open(); + }); + }); + spaceMenu.addItem((menuItem) => { + menuItem.setTitle(i18n_default.buttons.removeIcon); + menuItem.setIcon("lucide-file-minus"); + menuItem.onClick((ev) => { + removeSpaceIcon(plugin, space.path); + }); + }); + } + spaceMenu.addSeparator(); + spaceMenu.addItem((menuItem) => { + menuItem.setTitle(i18n_default.menu.sortBy); + menuItem.setIcon("sort-desc"); + menuItem.onClick((ev) => { + const sortMenu = new import_obsidian43.Menu(); + sortMenu.addItem((menuItem2) => { + menuItem2.setIcon("arrow-up-down"); + menuItem2.setTitle(i18n_default.menu.groupSpaces); + menuItem2.setChecked(space.metadata.sort.group == true); + menuItem2.onClick((ev2) => { + updateSpaceSort(plugin, space.path, { + field: space.metadata.sort.field, + asc: space.metadata.sort.asc, + group: !space.metadata.sort.group + }); + }); + }); + sortMenu.addSeparator(); + sortMenu.addItem((menuItem2) => { + const sortOption = { + field: "rank", + asc: true, + group: space.metadata.sort.group + }; + menuItem2.setIcon("arrow-up-down"); + menuItem2.setTitle(i18n_default.menu.customSort); + menuItem2.setChecked( + space.metadata.sort.field == sortOption.field && space.metadata.sort.asc == sortOption.asc + ); + menuItem2.onClick((ev2) => { + updateSpaceSort(plugin, space.path, sortOption); + }); + }); + sortMenu.addSeparator(); + sortMenu.addItem((menuItem2) => { + const sortOption = { + field: "name", + asc: true, + group: space.metadata.sort.group + }; + menuItem2.setTitle(i18n_default.menu.fileNameSortAlphaAsc); + menuItem2.setChecked( + space.metadata.sort.field == sortOption.field && space.metadata.sort.asc == sortOption.asc + ); + menuItem2.onClick((ev2) => { + updateSpaceSort(plugin, space.path, sortOption); + }); + }); + sortMenu.addItem((menuItem2) => { + const sortOption = { + field: "name", + asc: false, + group: space.metadata.sort.group + }; + menuItem2.setTitle(i18n_default.menu.fileNameSortAlphaDesc); + menuItem2.setChecked( + space.metadata.sort.field == sortOption.field && space.metadata.sort.asc == sortOption.asc + ); + menuItem2.onClick((ev2) => { + updateSpaceSort(plugin, space.path, sortOption); + }); + }); + sortMenu.addSeparator(); + sortMenu.addItem((menuItem2) => { + const sortOption = { + field: "ctime", + asc: false, + group: space.metadata.sort.group + }; + menuItem2.setTitle(i18n_default.menu.createdTimeSortAsc); + menuItem2.setChecked( + space.metadata.sort.field == sortOption.field && space.metadata.sort.asc == sortOption.asc + ); + menuItem2.onClick((ev2) => { + updateSpaceSort(plugin, space.path, sortOption); + }); + }); + sortMenu.addItem((menuItem2) => { + const sortOption = { + field: "ctime", + asc: true, + group: space.metadata.sort.group + }; + menuItem2.setTitle(i18n_default.menu.createdTimeSortDesc); + menuItem2.setChecked( + space.metadata.sort.field == sortOption.field && space.metadata.sort.asc == sortOption.asc + ); + menuItem2.onClick((ev2) => { + updateSpaceSort(plugin, space.path, sortOption); + }); + }); + const offset2 = e4.target.getBoundingClientRect(); + if (isMouseEvent(e4)) { + sortMenu.showAtPosition({ x: offset2.left, y: offset2.top + 30 }); + } else { + sortMenu.showAtPosition({ + x: e4.nativeEvent.locationX, + y: e4.nativeEvent.locationY + }); + } + }); + }); + spaceMenu.addSeparator(); + if (space.type == "folder") + spaceMenu.addItem((menuItem) => { + menuItem.setTitle(i18n_default.menu.edit); + menuItem.setIcon("pencil"); + menuItem.onClick((ev) => { + const vaultChangeModal = new EditSpaceModal( + plugin, + space, + "rename", + space.metadata + ); + vaultChangeModal.open(); + }); + }); + if (space.type != "vault") + spaceMenu.addItem((menuItem) => { + menuItem.setTitle(i18n_default.menu.deleteSpace); + menuItem.setIcon("trash"); + menuItem.onClick((ev) => { + removeSpace(plugin, space.path); + }); + }); + if (isMouseEvent(e4)) { + spaceMenu.showAtPosition({ x: e4.pageX, y: e4.pageY }); + } else { + spaceMenu.showAtPosition({ + x: e4.nativeEvent.locationX, + y: e4.nativeEvent.locationY + }); } - return /* @__PURE__ */ Cn.createElement("div", { - className: "mk-cell-text" - }, /* @__PURE__ */ Cn.createElement("input", { - type: "checkbox", - checked: value, - onChange - })); + return false; }; - -// src/components/ContextView/DataTypeView/ObjectCell.tsx -var ObjectCell = (props2) => { - const { initialValue, saveValue } = props2; - const [value, setValue] = Cn.useState(safelyParseJSON(initialValue)); - const saveKey = (key2, newKey) => { - if (key2 != newKey) - saveValue({ - ...value, - [newKey]: value[key2], - [key2]: void 0 +var triggerMultiFileMenu = (plugin, selectedFiles, e4) => { + const files = selectedFiles.map((s5) => s5.item.path); + const fileMenu = new import_obsidian43.Menu(); + fileMenu.addSeparator(); + fileMenu.addItem((menuItem) => { + menuItem.setIcon("plus"); + menuItem.setTitle("Add to Space"); + menuItem.onClick((ev) => { + showSpacesMenu(ev, plugin, (link) => { + movePathsToSpace( + plugin, + selectedFiles.map((f4) => f4.path), + plugin.index.spacesIndex.get(link), + -1, + "link" + ); }); - }; - const saveVal = (key2, val) => { - saveValue({ - ...value, - [key2]: val }); - }; - Cn.useEffect(() => { - setValue(safelyParseJSON(initialValue)); - }, [initialValue]); - return /* @__PURE__ */ Cn.createElement("div", { - className: "mk-cell-object" - }, Object.keys(value).map((f4) => /* @__PURE__ */ Cn.createElement("div", { - className: "mk-cell-object-row" - }, /* @__PURE__ */ Cn.createElement("input", { - onClick: (e4) => e4.stopPropagation(), - className: "mk-cell-text", - type: "text", - value: f4, - onBlur: (e4) => saveKey(f4, e4.target.value) - }), /* @__PURE__ */ Cn.createElement("input", { - onClick: (e4) => e4.stopPropagation(), - className: "mk-cell-text", - type: "text", - value: value[f4], - onBlur: (e4) => saveVal(f4, e4.target.value) - })))); -}; - -// src/components/ContextView/DataTypeView/PreviewCell.tsx -var PreviewCell = (props2) => { - var _a2; - const [vaultItem, setVaultItem] = h2(null); - const previewImage = F2(() => { - if (vaultItem == null ? void 0 : vaultItem.banner) - return vaultItem.banner; - if (props2.initialValue) - return props2.initialValue; - if (!props2.row || !props2.columns) - return null; - const imageCol = props2.columns.find((f4) => f4.type == "image"); - if (!imageCol) - return null; - return props2.row[imageCol.name + imageCol.table]; - }, [props2.row, props2.columns]); - const previewFile = F2(() => { - return getAbstractFileAtPath(app, previewImage); - }, [previewImage]); - const loadIcon = () => { - setVaultItem(props2.plugin.index.filesIndex.get(props2.file)); - }; - p2(() => { - loadIcon(); - window.addEventListener(eventTypes.spacesChange, loadIcon); - return () => { - window.removeEventListener(eventTypes.spacesChange, loadIcon); - }; - }, [props2.file]); - return previewImage ? /* @__PURE__ */ Cn.createElement("div", { - className: "mk-file-preview", - style: { - backgroundSize: "cover", - backgroundPositionY: "50%", - backgroundImage: `url(${previewFile ? app.vault.getResourcePath(previewFile) : previewImage})` - } - }) : /* @__PURE__ */ Cn.createElement("div", { - className: "mk-file-preview", - style: ((_a2 = vaultItem == null ? void 0 : vaultItem.color) == null ? void 0 : _a2.length) > 0 ? { - "--label-color": `${vaultItem.color}`, - "--icon-color": `#ffffff` - } : { - "--label-color": `var(--background-secondary-alt)`, - "--icon-color": `var(--text-muted)` - } - }, /* @__PURE__ */ Cn.createElement("div", { - className: "mk-file-icon", - dangerouslySetInnerHTML: (vaultItem == null ? void 0 : vaultItem.sticker) ? { __html: stickerFromString(vaultItem.sticker, props2.plugin) } : (vaultItem == null ? void 0 : vaultItem.isFolder) ? { __html: uiIconSet["mk-ui-folder"] } : { __html: uiIconSet["mk-ui-file"] } - })); -}; - -// src/components/ContextView/DataTypeView/DataTypeView.tsx -var DataTypeView = (props2) => { - const { initialValue, index, column, file } = props2; - const saveValue = (value) => { - props2.updateValue(value); - }; - const saveFieldValue = (fieldValue, value) => { - props2.updateFieldValue(fieldValue, value); - }; - const viewProps = { - initialValue, - saveValue, - editMode: props2.editable == true ? 3 : 0, - setEditMode: () => { - }, - plugin: props2.plugin, - propertyValue: column.value - }; - const fieldType = fieldTypeForType(column.type); - if (!fieldType) { - return /* @__PURE__ */ Cn.createElement(Cn.Fragment, null); - } - if (fieldType.type == "preview") { - return /* @__PURE__ */ Cn.createElement(PreviewCell, { - ...viewProps, - file, - row: props2.row, - columns: props2.cols + }); + if (plugin.settings.spacesStickers) { + fileMenu.addSeparator(); + fileMenu.addItem((menuItem) => { + menuItem.setIcon("palette"); + disclosureMenuItem( + plugin, + menuItem, + false, + false, + i18n_default.menu.changeColor, + "", + [ + { name: "None", value: "" }, + ...colors.map((f4) => ({ name: f4[0], value: f4[1] })) + ], + (_12, values) => { + saveColorForPaths(plugin, files, values[0]); + } + ); }); - } else if (fieldType.type == "file") { - return /* @__PURE__ */ Cn.createElement(FileCell, { - isFolder: false, - ...viewProps, - multi: fieldType.multiType == column.type, - openFlow: props2.openFlow + fileMenu.addItem((menuItem) => { + menuItem.setTitle(i18n_default.buttons.changeIcon); + menuItem.setIcon("lucide-sticker"); + menuItem.onClick((ev) => { + const vaultChangeModal = new stickerModal( + plugin.app, + plugin, + (emoji) => saveIconsForPaths(plugin, files, emoji) + ); + vaultChangeModal.open(); + }); }); - } else if (fieldType.type == "boolean") { - return /* @__PURE__ */ Cn.createElement(BooleanCell, { - ...viewProps, - column + fileMenu.addItem((menuItem) => { + menuItem.setTitle(i18n_default.buttons.removeIcon); + menuItem.setIcon("lucide-file-minus"); + menuItem.onClick((ev) => { + removeIconsForPaths(plugin, files); + }); }); - } else if (fieldType.type == "option") { - return /* @__PURE__ */ Cn.createElement(OptionCell, { - ...viewProps, - options: column.value, - multi: fieldType.multiType == column.type, - saveOptions: saveFieldValue + } + fileMenu.addSeparator(); + fileMenu.addItem((menuItem) => { + menuItem.setTitle(i18n_default.menu.deleteFiles); + menuItem.setIcon("trash"); + menuItem.onClick((ev) => { + deleteFiles(plugin, files); }); - } else if (fieldType.type == "date") { - return /* @__PURE__ */ Cn.createElement(DateCell, { - ...viewProps + }); + fileMenu.addItem((menuItem) => { + menuItem.setIcon("go-to-file"); + menuItem.setTitle(i18n_default.menu.openFilePane); + menuItem.onClick((ev) => { + files.forEach( + (file) => openAFile(getAbstractFileAtPath(plugin, file), plugin, true) + ); }); - } else if (fieldType.type == "context") { - return /* @__PURE__ */ Cn.createElement(ContextCell, { - ...viewProps, - multi: fieldType.multiType == column.type, - contextTable: props2.contextTable[column.value], - contextTag: column.value + }); + if (!internalPluginLoaded("file-explorer", plugin.app)) { + fileMenu.addItem((menuItem) => { + menuItem.setTitle(i18n_default.menu.moveFile); + menuItem.setIcon("paper-plane"); + menuItem.onClick((ev) => { + const fileMoveSuggester = new MoveSuggestionModal(plugin, files); + fileMoveSuggester.open(); + }); }); - } else if (fieldType.type == "fileprop") { - return /* @__PURE__ */ Cn.createElement(LookUpCell, { - ...viewProps, - file + } + if (isMouseEvent(e4)) { + fileMenu.showAtPosition({ x: e4.pageX, y: e4.pageY }); + } else { + fileMenu.showAtPosition({ + x: e4.nativeEvent.locationX, + y: e4.nativeEvent.locationY }); - } else if (fieldType.type == "number") { - return /* @__PURE__ */ Cn.createElement(NumberCell, { - ...viewProps + } + return false; +}; +var triggerFileMenu = (plugin, file, isFolder, e4, space) => { + const cache = plugin.index.filesIndex.get(file.path); + const fileMenu = new import_obsidian43.Menu(); + fileMenu.addSeparator(); + fileMenu.addItem((menuItem) => { + menuItem.setIcon("plus-square"); + menuItem.setTitle("Add to Space"); + menuItem.onClick((ev) => { + showSpacesMenu(ev, plugin, (link) => { + movePathsToSpace( + plugin, + [file.path], + plugin.index.spacesIndex.get(link), + -1, + "link" + ); + }); }); - } else if (fieldType.type == "link") { - return /* @__PURE__ */ Cn.createElement(LinkCell, { - ...viewProps, - multi: fieldType.multiType == column.type, - file + }); + if (file instanceof import_obsidian43.TFile && file.extension == "md") + fileMenu.addItem((menuItem) => { + menuItem.setTitle(i18n_default.menu.changeToFolderNote); + menuItem.setIcon("file-plus-2"); + menuItem.onClick((ev) => { + if (file instanceof import_obsidian43.TFile) + noteToFolderNote(plugin, file, true); + }); }); - } else if (fieldType.type == "tag") { - return /* @__PURE__ */ Cn.createElement(TagCell, { - ...viewProps, - multi: fieldType.multiType == column.type + if (plugin.settings.spacesStickers) { + fileMenu.addSeparator(); + fileMenu.addItem((menuItem) => { + menuItem.setIcon("palette"); + disclosureMenuItem( + plugin, + menuItem, + false, + false, + i18n_default.menu.changeColor, + "", + [ + { name: "None", value: "" }, + ...colors.map((f4) => ({ name: f4[0], value: f4[1] })) + ], + (_12, values) => { + saveFileColor(plugin, file.path, values[0]); + } + ); }); - } else if (fieldType.type == "image") { - return /* @__PURE__ */ Cn.createElement(ImageCell, { - ...viewProps + fileMenu.addItem((menuItem) => { + menuItem.setTitle(i18n_default.buttons.changeIcon); + menuItem.setIcon("lucide-sticker"); + menuItem.onClick((ev) => { + const vaultChangeModal = new stickerModal( + plugin.app, + plugin, + (emoji) => saveFileIcon(plugin, file, emoji) + ); + vaultChangeModal.open(); + }); }); - } else if (fieldType.type == "object") { - return /* @__PURE__ */ Cn.createElement(ObjectCell, { - ...viewProps + fileMenu.addItem((menuItem) => { + menuItem.setTitle(i18n_default.buttons.removeIcon); + menuItem.setIcon("lucide-file-minus"); + menuItem.onClick((ev) => { + removeFileIcon(plugin, file); + }); }); } - return /* @__PURE__ */ Cn.createElement(TextCell, { - ...viewProps + fileMenu.addSeparator(); + fileMenu.addItem((menuItem) => { + menuItem.setTitle(i18n_default.menu.rename); + menuItem.setIcon("pencil"); + menuItem.onClick((ev) => { + const vaultChangeModal = new VaultChangeModal(plugin, file, "rename"); + vaultChangeModal.open(); + }); }); -}; - -// src/components/FileContextView/FileContextList.tsx -var FileContextList = (props2) => { - const { path } = props2; - const { - tableData, - newColumn, - cols, - tagContexts, - contextTable, - contextInfo, - saveColumn, - hideColumn, - delColumn, - sortColumn, - updateFieldValue, - updateValue: updateValue2, - loadContextFields, - predicate - } = q2(MDBContext); - const [collapsed, setCollapsed] = h2( - !props2.plugin.settings.inlineContextSectionsExpanded - ); - const fileContext = F2(() => { - const td = tableData ? { - folder: { - cols: tableData.cols.filter( - (f4) => f4.name != FilePropertyName && !(f4.type == "fileprop" && (f4.value.startsWith(FilePropertyName) || f4.value.indexOf(".") == -1)) && f4.hidden != "true" && f4.type != "preview" - ), - data: tableData.rows.find((r3) => r3.File == path), - dataIndex: tableData.rows.findIndex((r3) => r3.File == path) - } - } : {}; - const tags = tagContexts.reduce( - (p3, c4) => contextTable[c4] ? { - ...p3, - [c4]: { - cols: contextTable[c4].cols.filter( - (f4) => f4.name != FilePropertyName && f4.type != "fileprop" && f4.hidden != "true" && f4.type != "preview" - ), - data: contextTable[c4].rows.find( - (r3, index) => index == parseInt(props2.path) - ), - dataIndex: contextTable[c4].rows.findIndex( - (r3) => r3.File == path - ) - } - } : p3, - {} - ); - return { - ...tags, - ...td - }; - }, [tableData, contextTable, tagContexts, path]); - const saveField = (field, oldField) => { - if (field.name.length > 0) { - if (field.name != oldField.name || field.type != oldField.type || field.value != oldField.value || field.attrs != oldField.attrs) { - const saveResult = saveColumn(field, oldField); + fileMenu.addItem((menuItem) => { + menuItem.setTitle(i18n_default.menu.delete); + menuItem.setIcon("trash"); + menuItem.onClick((ev) => { + const deleteOption = plugin.settings.deleteFileOption; + if (deleteOption === "permanent") { + plugin.app.vault.delete(file, true); + } else if (deleteOption === "system-trash") { + plugin.app.vault.trash(file, true); + } else if (deleteOption === "trash") { + plugin.app.vault.trash(file, false); } - } - }; - const saveContext = (field, oldField, value) => { - const newContext = value[0]; - initiateContextIfNotExists(props2.plugin, newContext).then((f4) => { - if (f4) { - return insertContextItems( - props2.plugin, - optionValuesForColumn( - field.name, - field.table == "" ? tableData : contextTable[field.table] - ), - newContext + }); + }); + fileMenu.addItem((menuItem) => { + menuItem.setIcon("go-to-file"); + menuItem.setTitle(i18n_default.menu.openFilePane); + menuItem.onClick((ev) => { + openFileInNewPane(plugin, { ...file, isFolder }); + }); + }); + fileMenu.addItem((menuItem) => { + menuItem.setTitle(i18n_default.menu.duplicate); + menuItem.setIcon("documents"); + menuItem.onClick((ev) => { + if (file.basename && file.extension) + plugin.app.vault.copy( + file, + `${file.parent.path}/${file.basename} 1.${file.extension}` ); - } - }).then((f4) => loadContextFields(newContext)); - const newField = { - ...field, - value: newContext != null ? newContext : "" - }; - saveColumn(newField, oldField); - }; - const showMenu = (e4, field) => { - const offset = e4.target.getBoundingClientRect(); - const options = optionValuesForColumn( - field.name, - field.table == "" ? tableData : contextTable[field.table] - ); - showPropertyMenu( - props2.plugin, - { x: offset.left, y: offset.top + 30 }, - true, - options, - field, - cols, - contextInfo.contextPath, - (newField) => saveField(newField, field), - (newField, val) => saveContext(newField, field, val), - hideColumn, - delColumn, - sortColumn, - predicate.colsHidden.includes(field.name + field.table) - ); - }; - return /* @__PURE__ */ Cn.createElement(Cn.Fragment, null, fileContext.folder && fileContext.folder.data && fileContext.folder.cols.length > 0 && /* @__PURE__ */ Cn.createElement("div", { - className: "mk-file-context-section" - }, /* @__PURE__ */ Cn.createElement("div", { - className: "mk-file-context-title", - onClick: (e4) => { - setCollapsed(!collapsed); - e4.stopPropagation(); - } - }, /* @__PURE__ */ Cn.createElement("div", { - className: `mk-icon-xsmall`, - dangerouslySetInnerHTML: { - __html: contextInfo.type == "folder" ? uiIconSet["mk-ui-folder"] : contextInfo.type == "space" ? uiIconSet["mk-ui-spaces"] : uiIconSet["mk-ui-tags"] - } - }), contextDisplayName(contextInfo), /* @__PURE__ */ Cn.createElement("button", { - className: `mk-collapse mk-inline-button mk-icon-xxsmall ${collapsed ? "mk-collapsed" : ""}`, - dangerouslySetInnerHTML: { - __html: uiIconSet["mk-ui-collapse-sm"] - } - })), !collapsed ? /* @__PURE__ */ Cn.createElement(Cn.Fragment, null, fileContext.folder.cols.map((f4, i4) => /* @__PURE__ */ Cn.createElement("div", { - key: i4, - className: "mk-file-context-row" - }, /* @__PURE__ */ Cn.createElement("div", { - className: "mk-file-context-field", - onClick: (e4) => showMenu(e4, { ...f4, table: "" }) - }, f4.name), /* @__PURE__ */ Cn.createElement("div", { - className: "mk-file-context-value" - }, /* @__PURE__ */ Cn.createElement(DataTypeView, { - plugin: props2.plugin, - initialValue: fileContext.folder.data[f4.name], - index: fileContext.folder.dataIndex, - file: fileContext.folder.data[FilePropertyName], - column: { ...f4, table: "" }, - editable: !contextInfo.readOnly, - updateValue: (v3) => updateValue2( - f4.name, - v3, - "", - fileContext.folder.dataIndex, - fileContext.folder.data[FilePropertyName] - ), - updateFieldValue: (fv, v3) => updateFieldValue( - f4.name, - fv, - v3, - "", - fileContext.folder.dataIndex, - fileContext.folder.data[FilePropertyName] - ), - contextTable - }))))) : /* @__PURE__ */ Cn.createElement(Cn.Fragment, null))); + }); + }); + if (!internalPluginLoaded("file-explorer", plugin.app)) { + fileMenu.addItem((menuItem) => { + menuItem.setTitle(i18n_default.menu.moveFile); + menuItem.setIcon("paper-plane"); + menuItem.onClick((ev) => { + const fileMoveSuggester = new MoveSuggestionModal(plugin, [file.path]); + fileMoveSuggester.open(); + }); + }); + } + plugin.app.workspace.trigger("file-menu", fileMenu, file, "file-explorer"); + if (isMouseEvent(e4)) { + fileMenu.showAtPosition({ x: e4.pageX, y: e4.pageY }); + } else { + fileMenu.showAtPosition({ + x: e4.nativeEvent.locationX, + y: e4.nativeEvent.locationY + }); + } + return false; }; -// src/components/ui/menus/fmMenu.tsx -var import_obsidian32 = require("obsidian"); +// src/components/InlineFileContext/InlineFileContextView.tsx +var import_he = __toESM(require_he()); + +// src/components/UI/menus/fmMenu.tsx +var import_obsidian44 = require("obsidian"); var showFMMenu = (plugin, position, property, deleteProperty, syncProperty, renameProperty, changeType) => { - const menu = new import_obsidian32.Menu(); + const menu = new import_obsidian44.Menu(); menu.setUseNativeMenu(false); menu.addItem((menuItem) => { var _a2; @@ -42648,113 +56005,31 @@ var showFMMenu = (plugin, position, property, deleteProperty, syncProperty, rena return menu; }; -// src/components/ui/modals/moveMetadataModal.tsx -var import_obsidian33 = require("obsidian"); -var MovePropertyModal = class extends import_obsidian33.Modal { - constructor(plugin, syncProperty, property, file) { - super(plugin.app); - this.plugin = plugin; - this.file = file; - let closeButton = this.modalEl.querySelector( - ".modal-close-button" - ); - closeButton.style.display = "none"; - this.syncProperty = syncProperty; - this.property = property; - } - onOpen() { - let { contentEl } = this; - let myModal = this; - let headerText; - const headerEl = contentEl.createEl("div", { text: headerText }); - headerEl.addClass("modal-title"); - headerEl.innerHTML = i18n_default.labels.syncMetadata; - const root = createRoot(contentEl); - root.render( - /* @__PURE__ */ Cn.createElement(MovePropertyComponent, { - plugin: this.plugin, - syncProperty: this.syncProperty, - close: () => this.close(), - property: this.property, - file: this.file - }) - ); - } - onClose() { - let { contentEl } = this; - contentEl.empty(); - } -}; -var MovePropertyComponent = (props2) => { - const { plugin } = props2; - const [table, setTable] = h2(""); - const saveContexts = (_9, value) => { - setTable(value[0]); - }; - const showContextMenu = async (e4) => { - const offset = e4.target.getBoundingClientRect(); - const tags = allTagsForFile(props2.file); - showSelectMenu( - { x: offset.left, y: offset.top + 30 }, - { - multi: false, - editable: false, - value: [], - options: [ - { name: props2.file.parent.name, value: "" }, - ...tags.map((m5) => ({ name: m5, value: m5 })) - ], - saveOptions: saveContexts, - placeholder: i18n_default.labels.tagItemSelectPlaceholder, - searchable: false, - showAll: true - } - ); - }; - const sync = () => { - props2.syncProperty(props2.property, table); - props2.close(); - }; - return /* @__PURE__ */ Cn.createElement("div", { - className: "modal-content" - }, /* @__PURE__ */ Cn.createElement("div", { - className: "setting-item setting-item-heading" - }, i18n_default.labels.syncProperties), /* @__PURE__ */ Cn.createElement("div", { - className: "setting-item" - }, /* @__PURE__ */ Cn.createElement("div", { - className: "setting-item-info" - }, /* @__PURE__ */ Cn.createElement("div", { - className: "setting-item-name" - }, i18n_default.labels.selectContext), /* @__PURE__ */ Cn.createElement("div", { - className: "setting-item-description" - }, i18n_default.descriptions.selectContext)), /* @__PURE__ */ Cn.createElement("div", { - className: "setting-item-control" - }, /* @__PURE__ */ Cn.createElement("button", { - onClick: (e4) => showContextMenu(e4) - }, table == "" ? i18n_default.buttons.currentFolder : table))), /* @__PURE__ */ Cn.createElement("button", { - style: { marginRight: 8 }, - onClick: () => sync() - }, i18n_default.buttons.sync), /* @__PURE__ */ Cn.createElement("button", { - onClick: () => props2.close() - }, i18n_default.buttons.cancel)); -}; +// src/utils/obsidian/obsidian.ts +var corePluginEnabled = (app2, plugin) => app2.internalPlugins.getPluginById(plugin) ? true : false; -// src/components/FileContextView/FrontmatterView.tsx +// src/components/Explorer/FrontmatterView.tsx var FrontmatterView = (props2) => { const { metadataPath, path } = props2; const [values, setValues] = h2({}); const [cols, setCols] = h2([]); + const [excludeKeys, setExcludeKeys] = h2([]); const refreshData = async () => { - var _a2; - const fileContexts = (_a2 = props2.plugin.index.contextsMap.get(path)) != null ? _a2 : /* @__PURE__ */ new Set(); - const columns = [...fileContexts].map((f4) => { - var _a3, _b2; - return (_b2 = (_a3 = props2.plugin.index.contextsIndex.get(f4)) == null ? void 0 : _a3.cols) != null ? _b2 : []; - }).reduce((p3, c4) => [...p3, ...c4], []); + var _a2, _b2; + const fileContexts = (_a2 = props2.plugin.index.spacesMap.get(path)) != null ? _a2 : /* @__PURE__ */ new Set(); + const columns = [...fileContexts].map( + (f4) => { + var _a3, _b3, _c2, _d2; + return (_d2 = (_c2 = (_b3 = (_a3 = props2.plugin.index.contextsIndex.get(f4)) == null ? void 0 : _a3.tables) == null ? void 0 : _b3["files"]) == null ? void 0 : _c2.cols) != null ? _d2 : []; + } + ).reduce((p3, c4) => [...p3, ...c4], []); const newCols = []; const newValues = {}; - const types = guestimateTypes([metadataPath], props2.plugin, false); - const fm = frontMatterForFile(getAbstractFileAtPath(app, metadataPath)); + const types2 = guestimateTypes([metadataPath], props2.plugin, false); + const fm = frontMatterForFile( + props2.plugin, + getAbstractFileAtPath(props2.plugin, metadataPath) + ); const fmKeys = uniqCaseInsensitive(frontMatterKeys(fm)).filter( (f4) => !columns.some((g4) => g4.name == f4) ); @@ -42762,7 +56037,7 @@ var FrontmatterView = (props2) => { table: "", name: f4, schemaId: "", - type: yamlTypeToMDBType(types[f4]) + type: yamlTypeToMDBType(types2[f4]) })); if (fm) { newCols.push(...cols2); @@ -42771,8 +56046,11 @@ var FrontmatterView = (props2) => { }); } if (props2.plugin.dataViewAPI() && props2.plugin.settings.dataviewInlineContext) { - const types2 = guestimateTypes([metadataPath], props2.plugin, true); - const fm2 = frontMatterForFile(getAbstractFileAtPath(app, metadataPath)); + const types3 = guestimateTypes([metadataPath], props2.plugin, true); + const fm2 = frontMatterForFile( + props2.plugin, + getAbstractFileAtPath(props2.plugin, metadataPath) + ); const fmKeys2 = uniqCaseInsensitive(frontMatterKeys(fm2)); const dvValues = props2.plugin.dataViewAPI().page(metadataPath); const dvKeys = uniqCaseInsensitive( @@ -42786,7 +56064,7 @@ var FrontmatterView = (props2) => { table: "", name: f4, schemaId: "", - type: yamlTypeToMDBType(types2[f4]) + type: yamlTypeToMDBType(types3[f4]) })); const dv = dvKeys.reduce( (p3, c4) => ({ @@ -42806,63 +56084,52 @@ var FrontmatterView = (props2) => { return !((_a3 = props2.excludeKeys) == null ? void 0 : _a3.some((g4) => g4 == f4.name)); }) ); + setExcludeKeys([ + ...columns.map((f4) => f4.name), + ...(_b2 = props2.excludeKeys) != null ? _b2 : [] + ]); setValues(newValues); }; - p2(() => { - refreshData(); - }, [path, props2.tags]); const mdbChanged = (evt) => { - if (evt.detail.type == "context" && evt.detail.contextPath && props2.tags.find( - (f4) => tagContextFromTag(props2.plugin, f4).contextPath == evt.detail.contextPath - )) { + if (evt.detail.type == "context" && evt.detail.contextPath && props2.spaces.find((f4) => f4 == evt.detail.contextPath)) { refreshData(); } else if (evt.detail.type == "file" && evt.detail.name == path) { refreshData(); } }; p2(() => { + refreshData(); window.addEventListener(eventTypes.spacesChange, mdbChanged); return () => { window.removeEventListener(eventTypes.spacesChange, mdbChanged); }; - }, [path, props2.tags]); + }, [path, props2.spaces]); const saveFMValue = (value, f4) => { saveFrontmatterValue(props2.plugin, metadataPath, f4.name, value, f4.type); }; const deleteFMValue = (property) => { deleteFrontmatterValue(props2.plugin, metadataPath, property.name); }; - const saveMetadata = async (property, table) => { + const saveMetadata = async (property, space) => { + var _a2; const field = { ...property, schemaId: "files" }; - let context; - let tag; - if (table == "") { - context = folderContextFromFolder(props2.plugin, props2.folder); - tag = false; - } else { - context = tagContextFromTag(props2.plugin, table); - tag = true; - } - await insertContextColumn(props2.plugin, context, field); + const spaceInfo = (_a2 = props2.plugin.index.spacesIndex.get(space)) == null ? void 0 : _a2.space; + if (!spaceInfo) + return; + await insertContextColumn(props2.plugin, spaceInfo, field); await updateContextValue( props2.plugin, - context, + spaceInfo, path, field.name, values[field.name] ); }; - const syncFMValue = (property) => { - let vaultChangeModal = new MovePropertyModal( - props2.plugin, - saveMetadata, - property, - getAbstractFileAtPath(app, metadataPath) - ); - vaultChangeModal.open(); + const syncFMValue = (e4, property) => { + showSpacesMenu(e4, props2.plugin, (space) => saveMetadata(property, space)); }; const renameFMKey = (key2, name) => { renameFrontmatterKey(props2.plugin, metadataPath, key2, name); @@ -42872,33 +56139,35 @@ var FrontmatterView = (props2) => { }; const selectType = (p3, key2) => { showSelectMenu(p3, { + plugin: props2.plugin, multi: false, editable: false, searchable: false, - saveOptions: (_9, v3) => selectedType(v3, key2), + saveOptions: (_12, v3) => selectedType(v3, key2), value: [], showAll: true, options: fieldTypes.filter((f4) => f4.metadata).map((f4, i4) => ({ id: i4 + 1, name: f4.label, value: f4.type, - icon: "" + icon: f4.icon })) }); }; const showMenu = (e4, property) => { - const offset = e4.target.getBoundingClientRect(); + const offset2 = e4.target.getBoundingClientRect(); showFMMenu( props2.plugin, - { x: offset.left, y: offset.top + 30 }, + { x: offset2.left, y: offset2.top + 30 }, property, deleteFMValue, - syncFMValue, + () => syncFMValue(e4, property), renameFMKey, selectType ); }; - return cols.length > 0 ? /* @__PURE__ */ Cn.createElement(Cn.Fragment, null, /* @__PURE__ */ Cn.createElement("div", { + const propertiesPlugin = corePluginEnabled(props2.plugin.app, "properties"); + return !propertiesPlugin || props2.force ? /* @__PURE__ */ Cn.createElement(Cn.Fragment, null, /* @__PURE__ */ Cn.createElement("div", { className: "mk-file-context-section" }, /* @__PURE__ */ Cn.createElement(Cn.Fragment, null, cols.map((f4, i4) => /* @__PURE__ */ Cn.createElement("div", { key: i4, @@ -42906,50 +56175,233 @@ var FrontmatterView = (props2) => { }, /* @__PURE__ */ Cn.createElement("div", { className: "mk-file-context-field", onClick: (e4) => showMenu(e4, f4) - }, f4.name), /* @__PURE__ */ Cn.createElement("div", { + }, /* @__PURE__ */ Cn.createElement("div", { + className: "mk-file-context-field-icon", + dangerouslySetInnerHTML: { + __html: stickerFromString(stickerForField(f4), props2.plugin) + } + }), /* @__PURE__ */ Cn.createElement("div", { + className: "mk-file-context-field-key" + }, f4.name)), /* @__PURE__ */ Cn.createElement("div", { className: "mk-file-context-value" }, /* @__PURE__ */ Cn.createElement(DataTypeView, { plugin: props2.plugin, initialValue: values[f4.name], - index: 0, - file: metadataPath, + row: { File: metadataPath }, column: { ...f4, table: "" }, editable: props2.editable, updateValue: (value) => saveFMValue(value, f4), updateFieldValue: (fieldValue, value) => saveFMValue(value, f4), contextTable: {} - }))))))) : /* @__PURE__ */ Cn.createElement(Cn.Fragment, null); + }))))))) : excludeKeys.length > 0 ? /* @__PURE__ */ Cn.createElement("style", null, `${excludeKeys.map((f4) => `.metadata-property[data-property-key="${f4}"]`).join(", ")} + { + display: none; + }`) : /* @__PURE__ */ Cn.createElement(Cn.Fragment, null); }; -// src/components/FileContextView/NoteBannerView.tsx -var import_obsidian34 = require("obsidian"); +// src/components/Explorer/ContextPropertiesView.tsx +var ContextPropertiesView = (props2) => { + var _a2; + const spaces = F2( + () => props2.spacePaths.map((f4) => { + var _a3; + return (_a3 = props2.plugin.index.spacesIndex.get(f4)) == null ? void 0 : _a3.space; + }).filter((f4) => f4), + [props2.spacePaths] + ); + return /* @__PURE__ */ Cn.createElement("div", { + className: "mk-file-context-properties" + }, spaces.map((space, i4) => /* @__PURE__ */ Cn.createElement(SpaceContextProvider, { + key: i4, + plugin: props2.plugin, + space + }, /* @__PURE__ */ Cn.createElement(ContextMDBProvider, { + key: i4, + plugin: props2.plugin, + file: props2.path + }, /* @__PURE__ */ Cn.createElement(ContextEditorProvider, { + plugin: props2.plugin + }, /* @__PURE__ */ Cn.createElement(FileContextList, { + plugin: props2.plugin, + path: props2.path, + color: "var(--tag-background)" + }))))), props2.metadataFilePath ? /* @__PURE__ */ Cn.createElement(FrontmatterView, { + plugin: props2.plugin, + path: props2.path, + metadataPath: props2.metadataFilePath, + spaces: spaces.map((f4) => f4.path), + force: props2.showMetadata, + excludeKeys: (_a2 = props2.hiddenFields) != null ? _a2 : [], + editable: props2.editable + }) : /* @__PURE__ */ Cn.createElement(Cn.Fragment, null)); +}; +var FileContextList = (props2) => { + const { path } = props2; + const { spaceInfo, spaceCache } = q2(SpaceContext); + const { tableData, dbSchema } = q2(ContextMDBContext); + const { + newColumn, + cols, + saveColumn, + hideColumn, + delColumn, + sortColumn, + updateFieldValue, + updateValue: updateValue2, + loadContextFields, + predicate + } = q2(ContextEditorContext); + const fileContext = F2(() => { + return tableData ? { + cols: tableData.cols.filter( + (f4) => f4.primary != "true" && f4.hidden != "true" + ), + data: tableData.rows.find((r3) => r3.File == path), + dataIndex: tableData.rows.findIndex((r3) => r3.File == path) + } : null; + }, [tableData, path]); + const saveField = (field, oldField) => { + if (field.name.length > 0) { + if (field.name != oldField.name || field.type != oldField.type || field.value != oldField.value || field.attrs != oldField.attrs) { + const saveResult = saveColumn(field, oldField); + } + } + }; + const showMenu = (e4, field) => { + const offset2 = e4.target.getBoundingClientRect(); + const options = optionValuesForColumn(field.name, tableData); + showPropertyMenu({ + plugin: props2.plugin, + position: { x: offset2.left, y: offset2.top + 30 }, + editable: true, + options, + field, + fields: cols, + contextPath: spaceInfo.path, + saveField: (newField) => saveField(newField, field), + hide: hideColumn, + deleteColumn: delColumn, + hidden: predicate.colsHidden.includes(field.name + field.table) + }); + }; + return fileContext && fileContext.cols.length > 0 && /* @__PURE__ */ Cn.createElement(Cn.Fragment, null, fileContext.cols.map((f4, i4) => { + var _a2, _b2, _c2, _d2; + return /* @__PURE__ */ Cn.createElement(Cn.Fragment, null, /* @__PURE__ */ Cn.createElement("div", { + key: i4, + className: "mk-file-context-row" + }, /* @__PURE__ */ Cn.createElement("div", { + className: "mk-file-context-field", + onClick: (e4) => showMenu(e4, { ...f4, table: "" }) + }, /* @__PURE__ */ Cn.createElement("div", { + className: "mk-file-context-field-icon", + dangerouslySetInnerHTML: { + __html: stickerFromString(stickerForField(f4), props2.plugin) + } + }), /* @__PURE__ */ Cn.createElement("div", { + className: "mk-file-context-field-key" + }, f4.name, /* @__PURE__ */ Cn.createElement("div", { + className: "mk-file-context-field-space mk-icon-xsmall", + dangerouslySetInnerHTML: { + __html: stickerFromString( + spaceCache.sticker, + props2.plugin + ) + } + }))), !f4.type.startsWith("object") && /* @__PURE__ */ Cn.createElement("div", { + className: "mk-file-context-value" + }, /* @__PURE__ */ Cn.createElement(DataTypeView, { + plugin: props2.plugin, + initialValue: (_a2 = fileContext.data) == null ? void 0 : _a2[f4.name], + row: (_b2 = fileContext.data) != null ? _b2 : {}, + column: { ...f4, table: "" }, + editable: !spaceInfo.readOnly, + updateValue: (v3) => { + var _a3; + return updateValue2( + f4.name, + v3, + "", + fileContext.dataIndex, + (_a3 = fileContext.data) == null ? void 0 : _a3[FilePropertyName] + ); + }, + updateFieldValue: (fv, v3) => { + var _a3; + return updateFieldValue( + f4.name, + fv, + v3, + "", + fileContext.dataIndex, + (_a3 = fileContext.data) == null ? void 0 : _a3[FilePropertyName] + ); + }, + contextTable: {} + }))), f4.type.startsWith("object") && /* @__PURE__ */ Cn.createElement("div", { + className: "mk-file-context-row" + }, /* @__PURE__ */ Cn.createElement(DataTypeView, { + plugin: props2.plugin, + initialValue: (_c2 = fileContext.data) == null ? void 0 : _c2[f4.name], + row: (_d2 = fileContext.data) != null ? _d2 : {}, + column: { ...f4, table: "" }, + editable: !spaceInfo.readOnly, + updateValue: (v3) => { + var _a3; + return updateValue2( + f4.name, + v3, + "", + fileContext.dataIndex, + (_a3 = fileContext.data) == null ? void 0 : _a3[FilePropertyName] + ); + }, + updateFieldValue: (fv, v3) => { + var _a3; + return updateFieldValue( + f4.name, + fv, + v3, + "", + fileContext.dataIndex, + (_a3 = fileContext.data) == null ? void 0 : _a3[FilePropertyName] + ); + }, + contextTable: {} + }))); + })); +}; + +// src/components/InlineFileContext/NoteBannerView.tsx +var import_obsidian46 = require("obsidian"); var NoteBannerView = (props2) => { + var _a2; const [banner, setBanner] = h2(null); p2(() => { - var _a2; if (props2.link) { - const newBanner = (_a2 = getAbstractFileAtPath(app, props2.link)) != null ? _a2 : props2.link; - setBanner(newBanner); + let path = uriByString(props2.plugin, props2.link); + if (props2.path) + path = uriByString(props2.plugin, props2.link, props2.path.path); + setBanner(path); } else { setBanner(null); } }, [props2.link]); const triggerBannerContextMenu = (e4) => { - if (!props2.file) + if (!props2.path || props2.path.type == "file") return; e4.preventDefault(); - const fileMenu = new import_obsidian34.Menu(); + const fileMenu = new import_obsidian46.Menu(); fileMenu.addSeparator(); fileMenu.addItem((menuItem) => { menuItem.setTitle(i18n_default.buttons.changeBanner); menuItem.setIcon("lucide-image"); menuItem.onClick((ev) => { - let vaultChangeModal = new imageModal( + const vaultChangeModal = new imageModal( props2.plugin, props2.plugin.app, (image) => saveFrontmatterValue( props2.plugin, - props2.file.path, + props2.path.path, props2.plugin.settings.fmKeyBanner, image, "image", @@ -42965,7 +56417,7 @@ var NoteBannerView = (props2) => { menuItem.onClick((ev) => { deleteFrontmatterValue( props2.plugin, - props2.file.path, + props2.path.path, props2.plugin.settings.fmKeyBanner ); }); @@ -42980,69 +56432,84 @@ var NoteBannerView = (props2) => { } return false; }; - return /* @__PURE__ */ Cn.createElement("div", { + const file = getAbstractFileAtPath(props2.plugin, banner == null ? void 0 : banner.path); + return banner ? /* @__PURE__ */ Cn.createElement("div", { className: `mk-note-header`, onContextMenu: triggerBannerContextMenu - }, banner && /* @__PURE__ */ Cn.createElement("img", { - src: banner instanceof import_obsidian34.TFile ? app.vault.getResourcePath(banner) : banner - })); + }, banner.type == "file" && file ? /* @__PURE__ */ Cn.createElement("img", { + src: props2.plugin.app.vault.getResourcePath(file) + }) : banner.type == "url" ? /* @__PURE__ */ Cn.createElement("img", { + src: banner.path + }) : banner.refType == "frame" ? /* @__PURE__ */ Cn.createElement(EmbedFrameView, { + source: (_a2 = props2.path) == null ? void 0 : _a2.path, + plugin: props2.plugin, + path: banner + }) : /* @__PURE__ */ Cn.createElement(Cn.Fragment, null)) : /* @__PURE__ */ Cn.createElement(Cn.Fragment, null); }; -// src/components/FileContextView/InlineFileContextView.tsx +// src/components/InlineFileContext/InlineFileContextView.tsx var InlineFileContextView = (props2) => { - var _a2, _b2; - const { file } = props2; - const folderPath = (_a2 = file == null ? void 0 : file.parent) == null ? void 0 : _a2.path; - const getFileCache = (file2) => { - if (!file2 || file2.path == "/") + const [metadataFilePath, setMetadataFilePath] = h2(); + const refreshCache = (path) => { + if (!path) + return null; + const uri = uriByString(props2.plugin, path); + if (uri.type == "space" || uri.type == "tag") { + const cache3 = props2.plugin.index.spacesIndex.get(path); + if (cache3) { + setMetadataFilePath(cache3.space.defPath); + } + return cache3; + } + if (path == "/") return null; - const cache = props2.plugin.index.filesIndex.get(file2.path); - if (!cache) { + const cache2 = props2.plugin.index.filesIndex.get(path); + if (!cache2) { return props2.plugin.index.filesIndex.get( - folderPathFromFolderNoteFile(props2.plugin.settings, tFileToAFile(file2)) + folderPathFromFolderNoteFile( + props2.plugin.settings, + tFileToAFile(getAbstractFileAtPath(props2.plugin, props2.path)) + ) ); } - return cache; + if (cache2.isFolder && cache2.folderNote) { + setMetadataFilePath(cache2.folderNote.folderNotePath); + return cache2; + } + setMetadataFilePath(cache2.path); + return cache2; }; - const [fileCache, setFileCache] = h2( - getFileCache(props2.file) + const [cache, setCache] = h2( + refreshCache(props2.path) ); - const metadataFilePath = F2(() => { - if (!fileCache) - return null; - if (fileCache.isFolder && fileCache.folderNote) { - return fileCache.folderNote.folderNotePath; - } - return fileCache.path; - }, [fileCache]); const showHeader = props2.showHeader; const [collapsed, setCollapsed] = h2( !showHeader ? false : !props2.plugin.settings.inlineContextExpanded ); - const tags = (_b2 = fileCache == null ? void 0 : fileCache.tags) != null ? _b2 : []; - const contexts = F2(() => { - var _a3; - return ((_a3 = fileCache == null ? void 0 : fileCache.contexts) != null ? _a3 : []).map((f4) => props2.plugin.index.contextsIndex.get(f4)).filter((f4) => f4).map((f4) => f4.info); - }, [fileCache]); - const banner = fileCache == null ? void 0 : fileCache.banner; + const spaces = F2( + () => (cache == null ? void 0 : cache.cacheType) == "file" ? spacesFromFileCache(cache, props2.plugin).map( + (f4) => f4.path + ) : [], + [cache] + ); + const banner = cache == null ? void 0 : cache.banner; p2(() => { props2.plugin.settings.inlineContextExpanded = !collapsed; props2.plugin.saveSettings(); }, [collapsed]); const fileNameRef = _2(null); const refreshFile = () => { - if (!file) { + if (!props2.path) { return; } - const fileCache2 = getFileCache(file); - setFileCache(fileCache2); + setCache(refreshCache(props2.path)); }; const cacheChanged = (evt) => { - var _a3; - if (evt.detail.type == "file" && (evt.detail.name == (file == null ? void 0 : file.path) || evt.detail.name == ((_a3 = fileCache == null ? void 0 : fileCache.folderNote) == null ? void 0 : _a3.folderPath))) { + var _a2; + if (evt.detail.type == "file" && (evt.detail.name == props2.path || evt.detail.name == ((_a2 = cache == null ? void 0 : cache.folderNote) == null ? void 0 : _a2.folderPath))) { refreshFile(); } - if (evt.detail.type == "context" && contexts.some((f4) => f4.contextPath == evt.detail.name)) { + if (evt.detail.type == "space" && (spaces.some((f4) => f4 == evt.detail.name) || (cache == null ? void 0 : cache.path) == evt.detail.name)) { refreshFile(); } }; @@ -43052,108 +56519,61 @@ var InlineFileContextView = (props2) => { return () => { window.removeEventListener(eventTypes.spacesChange, cacheChanged); }; - }, [file]); - const changeCover = (e4) => { - const vaultChangeModal = new imageModal( - props2.plugin, - props2.plugin.app, - (image) => saveFrontmatterValue( - props2.plugin, - fileCache.path, - props2.plugin.settings.fmKeyBanner, - image, - "image", - true - ) - ); - vaultChangeModal.open(); - }; - const showContextMenu = (e4) => { - const offset = e4.target.getBoundingClientRect(); - const f4 = loadTags(props2.plugin); - showSelectMenu( - { x: offset.left, y: offset.top + 30 }, - { - multi: false, - editable: true, - value: [], - options: f4.map((m5) => ({ name: m5, value: m5 })), - saveOptions: (_9, value) => addTag2(value[0]), - placeholder: i18n_default.labels.contextItemSelectPlaceholder, - searchable: true, - showAll: true + }, [props2.path]); + const addToSpace = async (spacePath) => { + const spaceCache = props2.plugin.index.spacesIndex.get(spacePath); + if (spaceCache) { + movePathsToSpace(props2.plugin, [props2.path], spaceCache, -1, "link"); + } else { + const newSpaceURI = uriByString(props2.plugin, spacePath); + if (newSpaceURI.type == "tag") { + if (metadataFilePath) + addTagToNote( + props2.plugin, + newSpaceURI.space, + getAbstractFileAtPath(props2.plugin, metadataFilePath) + ); } - ); - }; - const addTag2 = (tag) => { - if (file instanceof import_obsidian35.TFile && file.extension == "md") - addTagToNote(tag, file); - }; - const removeTag = (tag) => { - if (file instanceof import_obsidian35.TFile && file.extension == "md") - removeTagFromFile(tag, file); - }; - const saveField = (source, field) => { - if (source == "fm") { - saveFrontmatterValue( - props2.plugin, - fileCache.path, - field.name, - "", - field.type, - true - ); - return; } - if (source == "") { - insertContextColumn( - props2.plugin, - mdbContextByPath(props2.plugin, fileCache.parent), - field - ); - return; + }; + const removeFromSpace = (spacePath) => { + const spaceCache = props2.plugin.index.spacesIndex.get(spacePath); + if (spaceCache) { + removePathsFromSpace(props2.plugin, spaceCache, [props2.path]); } - insertContextColumn( - props2.plugin, - tagContextFromTag(props2.plugin, source), - field - ); }; - const fileName = F2( - () => { - var _a3; - return (_a3 = fileCache == null ? void 0 : fileCache.name) != null ? _a3 : fileNameToString(file == null ? void 0 : file.name); - }, - [fileCache, file] - ); - const propertiesPlugin = corePluginEnabled(app, "properties"); + const fileName = F2(() => { + var _a2; + return (_a2 = cache == null ? void 0 : cache.name) != null ? _a2 : ""; + }, [cache]); const newProperty = (e4) => { - const offset = e4.target.getBoundingClientRect(); + const offset2 = e4.target.getBoundingClientRect(); showNewPropertyMenu( props2.plugin, - { x: offset.left, y: offset.top + 30 }, - tags, + { x: offset2.left, y: offset2.top + 30 }, + spaces, [], saveField, "files", - folderPath, + null, true ); }; const onBlur = (e4) => { + const file = getAbstractFileAtPath(props2.plugin, metadataFilePath); const newValue = import_he.default.decode(e4.target.innerHTML); if (newValue != fileName) { if (props2.plugin.settings.spacesUseAlias) { saveFrontmatterValue( props2.plugin, - fileCache.path, + cache.path, props2.plugin.settings.fmKeyAlias, newValue.trim(), "text", true ); } else { - renameFile(props2.plugin, file, newValue.trim() + ".md"); + renameFile(props2.plugin, file, newValue.trim()); } } }; @@ -43164,7 +56584,7 @@ var InlineFileContextView = (props2) => { e4.stopPropagation(); }; const onKeyDown = (e4) => { - var _a3, _b3; + var _a2, _b2; e4.stopPropagation(); if (e4.key == "a" && e4.metaKey) { e4.preventDefault(); @@ -43176,22 +56596,94 @@ var InlineFileContextView = (props2) => { } if (e4.key == "Enter") { e4.target.blur(); - (_a3 = props2.editorView) == null ? void 0 : _a3.focus(); + (_a2 = props2.editorView) == null ? void 0 : _a2.focus(); e4.preventDefault(); } if (e4.key == "Escape") { e4.target.blur(); - (_b3 = props2.editorView) == null ? void 0 : _b3.focus(); + (_b2 = props2.editorView) == null ? void 0 : _b2.focus(); e4.preventDefault(); } }; y2(() => { - var _a3; - (_a3 = props2.editorView) == null ? void 0 : _a3.requestMeasure(); + var _a2; + (_a2 = props2.editorView) == null ? void 0 : _a2.requestMeasure(); }, []); + const changeCover = (e4) => { + const vaultChangeModal = new imageModal( + props2.plugin, + props2.plugin.app, + (image) => { + if ((cache == null ? void 0 : cache.cacheType) == "file") { + saveFrontmatterValue( + props2.plugin, + cache == null ? void 0 : cache.path, + props2.plugin.settings.fmKeyBanner, + image, + "image", + true + ); + } else if ((cache == null ? void 0 : cache.cacheType) == "space") { + saveSpaceMetadataValue( + props2.plugin, + cache.path, + props2.plugin.settings.fmKeyBanner, + image + ); + } + } + ); + vaultChangeModal.open(); + }; + const showAddMenu = (e4) => { + showSpacesMenu( + e4, + props2.plugin, + (link, isNew) => { + if (isNew) { + if (link.charAt(0) == "#") { + addTagToNote( + props2.plugin, + link, + getAbstractFileAtPath(props2.plugin, metadataFilePath) + ); + } else { + insertSpaceAtIndex(props2.plugin, link, { links: [props2.path] }); + } + } else { + addToSpace(link); + } + }, + false, + true + ); + }; + const saveField = (source, field) => { + if (source == "fm") { + saveFrontmatterValue( + props2.plugin, + cache.path, + field.name, + "", + field.type, + true + ); + return; + } + insertContextColumn( + props2.plugin, + spaceFromFolder(props2.plugin, source), + field + ); + }; + const showContextMenu = (e4) => { + const spaceCache = props2.plugin.index.spacesIndex.get(props2.path); + if (spaceCache) + triggerSpaceMenu(props2.plugin, spaceCache, e4, null, null); + }; p2(() => { - var _a3; - if (fileName == null ? void 0 : fileName.startsWith("Untitled")) { + var _a2; + if ((fileName == null ? void 0 : fileName.startsWith("New Note")) || (fileName == null ? void 0 : fileName.startsWith("Untitled"))) { selectElementContents(fileNameRef.current); } const pasteEvent = (e4) => { @@ -43199,29 +56691,29 @@ var InlineFileContextView = (props2) => { const text2 = e4.clipboardData.getData("text/plain"); document.execCommand("insertText", false, text2); }; - (_a3 = fileNameRef.current) == null ? void 0 : _a3.addEventListener("paste", pasteEvent); + (_a2 = fileNameRef.current) == null ? void 0 : _a2.addEventListener("paste", pasteEvent); return () => { - var _a4; - (_a4 = fileNameRef.current) == null ? void 0 : _a4.removeEventListener("paste", pasteEvent); + var _a3; + (_a3 = fileNameRef.current) == null ? void 0 : _a3.removeEventListener("paste", pasteEvent); }; }, [fileNameRef, fileName]); return /* @__PURE__ */ Cn.createElement(Cn.Fragment, null, props2.showBanner && /* @__PURE__ */ Cn.createElement(NoteBannerView, { plugin: props2.plugin, link: banner, - file: props2.file + path: uriByString(props2.plugin, props2.path) }), /* @__PURE__ */ Cn.createElement("div", { className: "mk-file-context-component" }, props2.showBanner && banner && /* @__PURE__ */ Cn.createElement("div", { className: `mk-spacer`, style: { - "--header-height": ((platformIsMobile() ? 1 : 0) * 26 + 138 + (!props2.plugin.settings.spacesStickers || props2.plugin.settings.inlineContextNameLayout == "horizontal" ? 1 : 0) * 50).toString() + "px" + "--mk-header-height": ((platformIsMobile() ? 1 : 0) * 26 + 138 + (!props2.plugin.settings.spacesStickers || props2.plugin.settings.inlineContextNameLayout == "horizontal" ? 1 : 0) * 50).toString() + "px" }, onContextMenu: (e4) => e4.preventDefault() }), showHeader && /* @__PURE__ */ Cn.createElement("div", { className: `mk-file-context-file ${props2.plugin.settings.inlineContextNameLayout == "horizontal" ? "mk-file-context-file-horizontal" : ""}` - }, props2.plugin.settings.spacesStickers && fileCache ? /* @__PURE__ */ Cn.createElement(FileSticker, { + }, props2.plugin.settings.spacesStickers && cache ? /* @__PURE__ */ Cn.createElement(FileSticker, { plugin: props2.plugin, - fileCache + fileCache: cache }) : /* @__PURE__ */ Cn.createElement(Cn.Fragment, null), /* @__PURE__ */ Cn.createElement("div", { className: "mk-inline-title inline-title", ref: fileNameRef, @@ -43235,7 +56727,7 @@ var InlineFileContextView = (props2) => { __html: fileName } }), /* @__PURE__ */ Cn.createElement("div", { - className: `mk-collapse mk-icon-xsmall mk-file-context-collapse ${collapsed ? "mk-collapsed" : ""}`, + className: `mk-collapse mk-icon-xsmall mk-fold ${collapsed ? "mk-collapsed" : ""}`, dangerouslySetInnerHTML: { __html: uiIconSet["mk-ui-collapse"] }, @@ -43250,242 +56742,293 @@ var InlineFileContextView = (props2) => { }, /* @__PURE__ */ Cn.createElement("div", { className: "mk-icon-xsmall", dangerouslySetInnerHTML: { __html: uiIconSet["mk-ui-plus"] } - }), platformIsMobile() ? "Property" : "Add Property"), /* @__PURE__ */ Cn.createElement("button", { - onClick: (e4) => showContextMenu(e4) + }), platformIsMobile() ? "Property" : "Property"), /* @__PURE__ */ Cn.createElement("button", { + onClick: (e4) => showAddMenu(e4) }, /* @__PURE__ */ Cn.createElement("div", { className: "mk-icon-xsmall", - dangerouslySetInnerHTML: { __html: uiIconSet["mk-ui-tags"] } - }), platformIsMobile() ? "Tag" : "Add Tag"), props2.showBanner || props2.isFolderNote ? /* @__PURE__ */ Cn.createElement("button", { + dangerouslySetInnerHTML: { + __html: stickerFromString( + "lucide//plus-square", + props2.plugin + ) + } + }), platformIsMobile() ? "Space" : "Space"), cache && /* @__PURE__ */ Cn.createElement("button", { onClick: (e4) => changeCover(e4) }, /* @__PURE__ */ Cn.createElement("div", { className: "mk-icon-xsmall", dangerouslySetInnerHTML: { __html: uiIconSet["mk-make-image"] } - }), platformIsMobile() ? "Cover" : "Change Cover") : /* @__PURE__ */ Cn.createElement(Cn.Fragment, null)), tags.length > 0 ? /* @__PURE__ */ Cn.createElement(TagsView, { + }), platformIsMobile() ? "Cover" : "Cover"), (cache == null ? void 0 : cache.cacheType) == "space" && /* @__PURE__ */ Cn.createElement("button", { + "aria-label": i18n_default.buttons.moreOptions, + className: "mk-icon-xsmall mk-inline-button", + onClick: (e4) => { + showContextMenu(e4); + }, + dangerouslySetInnerHTML: { + __html: uiIconSet["mk-ui-options"] + } + })), cache && /* @__PURE__ */ Cn.createElement(NoteSpacesBar, { + path: cache == null ? void 0 : cache.path, plugin: props2.plugin, - tags, - removeTag, - canOpen: true - }) : /* @__PURE__ */ Cn.createElement(Cn.Fragment, null)) : /* @__PURE__ */ Cn.createElement("div", { + removeSpace: removeFromSpace, + addSpace: addToSpace + })) : /* @__PURE__ */ Cn.createElement("div", { style: { height: 16 } - })), !collapsed && fileCache ? /* @__PURE__ */ Cn.createElement("div", { - className: "mk-file-context-component" - }, metadataFilePath && !propertiesPlugin && /* @__PURE__ */ Cn.createElement(FrontmatterView, { + })), !collapsed ? /* @__PURE__ */ Cn.createElement(ContextPropertiesView, { plugin: props2.plugin, - path: fileCache.path, - metadataPath: metadataFilePath, - folder: folderPath, - tags, - excludeKeys: showHeader || props2.isFolderNote ? FMMetadataKeys(props2.plugin) : [], + spacePaths: spaces, + path: props2.path, + metadataFilePath, + showMetadata: props2.showMetadata, + hiddenFields: props2.hiddenFields, editable: props2.editable - }), contexts.map((context, i4) => /* @__PURE__ */ Cn.createElement(MDBProvider, { - key: i4, - plugin: props2.plugin, - context, - file: fileCache.path - }, /* @__PURE__ */ Cn.createElement(FileContextList, { - plugin: props2.plugin, - path: fileCache.path, - color: "var(--tag-background)" - }))), props2.editable ? /* @__PURE__ */ Cn.createElement("div", { - style: { height: props2.showHeader ? 16 : 8 } - }) : /* @__PURE__ */ Cn.createElement(Cn.Fragment, null)) : /* @__PURE__ */ Cn.createElement(Cn.Fragment, null)); + }) : /* @__PURE__ */ Cn.createElement(Cn.Fragment, null)); }; -// src/components/ContextView/FilterBar/TableSelector.tsx -var import_obsidian37 = require("obsidian"); -var TableSelector = (props2) => { - const { folderNoteOpen, viewFolderNote } = props2; - const { - tables, - setDBSchema, - deleteSchema, - saveSchema, - saveDB: saveDB2, - setSchema, - dbSchema, - contextInfo - } = q2(MDBContext); - const saveNewSchemas = (_schema) => { - const newSchema = { - ..._schema, - id: uniqueNameFromString( - sanitizeTableName(_schema.id), - tables.map((f4) => f4.id) - ) - }; - saveSchema(newSchema).then( - (f4) => saveDB2({ - schema: newSchema, - cols: defaultTableFields.map((f5) => ({ ...f5, schemaId: newSchema.id })), - rows: [] - }) - ); - }; - const newTable = (e4) => { - let vaultChangeModal = new SaveViewModal( - { - id: "", - name: "", - type: "db" - }, - saveNewSchemas, - "new table" - ); - vaultChangeModal.open(); - }; - const selectView = (_dbschema, value) => { - viewFolderNote(false); - setDBSchema(_dbschema); - value && setSchema(tables.find((f4) => f4.id == value)); - }; - const openView = (e4, _dbschema) => { - const views = tables.filter((f4) => f4.type != "db" && f4.def == _dbschema.id); - if (views.length == 0) { - selectView(_dbschema); - return; +// src/types/space.ts +var FMMetadataKeys = (plugin) => [plugin.settings.fmKeyBanner, plugin.settings.fmKeySticker, plugin.settings.fmKeyColor]; +var tagsSpace = { + name: "Tags", + alias: "Tags", + path: "spaces://$tags", + metadata: { + contexts: [] + }, + sticker: "lucide//tags", + space: null, + contexts: [], + type: "default", + cacheType: "space" +}; + +// src/utils/frames/editor/dropFrame.ts +var shouldDeleteColumn = (nodeParent) => { + if (nodeParent.node.type == "column" && nodeParent.children.length == 1) { + return true; + } + return false; +}; +var shouldDeleteColumnContainer = (nodeParent) => { + if (nodeParent.node.type == "container" && nodeParent.children.length == 1) { + return true; + } + return false; +}; +var shouldCollapseColumnContainer = (nodeParent) => { + if (nodeParent.node.type == "container" && nodeParent.children.length == 2) { + return true; + } + return false; +}; +var dropFrame = (activeNode, overNode, root, nodes, newColumn) => { + let saveNodes = []; + const deleteNodes = []; + const schemaId = root.node.schemaId; + const overParentNode = findParent(root, overNode.id); + const activeParentNode = findParent(root, activeNode.id); + if (!overParentNode || !activeParentNode) { + return [[], []]; + } + if (newColumn) { + const baseLevelNode = overNode.node.parentId == root.id; + const containerType = overNode.node.type == "container"; + const columnType = overNode.node.type == "column"; + let columnContainerIsBaseLevel = false; + if (columnType) { + if (overParentNode.node.parentId == root.id) + columnContainerIsBaseLevel = true; + } + const createColumnContainer = baseLevelNode && !containerType; + const insertColumn2 = baseLevelNode && containerType || columnType && columnContainerIsBaseLevel; + if (createColumnContainer) { + const newColumns = { ...newUniqueNode( + columnsNode, + overParentNode.id, + nodes, + schemaId + ), rank: overNode.node.rank }; + const column1 = newUniqueNode( + columnNode, + newColumns.id, + [...nodes, newColumns], + schemaId + ); + const column2 = newUniqueNode( + columnNode, + newColumns.id, + [...nodes, newColumns, column1], + schemaId + ); + const newNodes = [ + newColumns, + column1, + column2, + { ...overNode.node, rank: 0, parentId: column1.id } + ]; + saveNodes.push( + ...newNodes, + { ...activeNode.node, rank: 0, parentId: column2.id } + ); + } else if (insertColumn2) { + const column = { + ...newUniqueNode(columnNode, overParentNode.id, nodes, schemaId), + rank: overNode.node.rank > activeNode.node.rank ? overNode.node.rank : overNode.node.rank + 1 + }; + const newNodes = [column, { ...activeNode.node, parentId: column.id }]; + saveNodes.push(...newNodes); } - selectView(_dbschema, views[0].id); - return; - }; - const folderNoteOptions = (e4) => { - triggerFileMenu( - props2.plugin, - getAbstractFileAtPath(app, props2.folderNotePath), - false, - e4, - "link-context-menu" - ); - }; - const viewContextMenu = (e4, _schema) => { - const fileMenu = new import_obsidian37.Menu(); - fileMenu.addSeparator(); - fileMenu.addItem((menuItem) => { - menuItem.setTitle("Rename Table"); - menuItem.onClick(() => { - let vaultChangeModal = new SaveViewModal( - _schema, - (s5) => saveSchema(s5), - "rename table" - ); - vaultChangeModal.open(); - }); - }); - fileMenu.addItem((menuItem) => { - menuItem.setTitle("Delete Table"); - menuItem.onClick(() => { - deleteSchema(_schema); - }); - }); - if (isMouseEvent(e4)) { - fileMenu.showAtPosition({ x: e4.pageX, y: e4.pageY }); - } else { - fileMenu.showAtPosition({ - x: e4.nativeEvent.locationX, - y: e4.nativeEvent.locationY - }); + } else { + const newRank = overNode.node.rank + 1; + const items = nodes.filter((f4) => f4.parentId == overParentNode.id && f4.id != activeNode.id).sort((a5, b4) => a5.rank - b4.rank).map((f4, i4) => ({ ...f4, rank: i4 })); + const newItem = { ...activeNode.node, parentId: overNode.node.parentId }; + const newItems = insert(items, newRank, newItem).map((f4, i4) => ({ + ...f4, + rank: i4 + })); + saveNodes.push(...newItems); + } + if (shouldDeleteColumn(activeParentNode)) { + const columnParentNode = findParent(root, activeParentNode.id); + deleteNodes.push(activeParentNode.node); + if (shouldDeleteColumnContainer(columnParentNode)) { + deleteNodes.push(columnParentNode.node); + } else if (shouldCollapseColumnContainer(columnParentNode)) { + const removeColumn = columnParentNode.children.filter((f4) => f4.id != activeParentNode.id); + deleteNodes.push(...removeColumn.map((f4) => f4.node), columnParentNode.node); + const moveToParentNodes = removeColumn.flatMap((f4) => f4.children.map((f5) => ({ ...f5.node, parentId: root.id }))); + saveNodes = [...saveNodes.map((f4) => moveToParentNodes.some((g4) => g4.id == f4.id) ? { ...f4, parentId: root.id } : f4), ...moveToParentNodes.filter((g4) => !saveNodes.some((f4) => g4.id == f4.id))]; } - }; - return /* @__PURE__ */ Cn.createElement("div", { - className: "mk-table-selector" - }, viewFolderNote && /* @__PURE__ */ Cn.createElement("button", { - className: `mk-folder-note ${folderNoteOpen ? "mk-is-active" : ""}`, - onClick: () => viewFolderNote(true), - onContextMenu: (e4) => folderNoteOptions(e4) - }, props2.folderNoteName), tables.filter((f4) => f4.type == "db").map((f4) => /* @__PURE__ */ Cn.createElement("button", { - className: `${!folderNoteOpen && (dbSchema == null ? void 0 : dbSchema.id) == f4.id ? "mk-is-active" : ""}`, - onClick: (e4) => openView(e4, f4), - onContextMenu: (e4) => !f4.primary && viewContextMenu(e4, f4) - }, f4.name)), contextInfo.type == "folder" && /* @__PURE__ */ Cn.createElement("button", { - onClick: (e4) => newTable(e4) - }, "+")); -}; - -// src/components/ContextView/ContextViewComponent.tsx -var ContextViewComponent = (props2) => { - var _a2, _b2; - const context = props2.context; - const contextCache = props2.plugin.index.contextsIndex.get( - context.contextPath + } + return [saveNodes, deleteNodes]; +}; + +// src/components/SpaceView/Contexts/SpaceBodyView.tsx +var PLACEHOLDER_ID3 = "_placeholder"; +var SpaceBodyView = (props2) => { + const { frameSchema } = q2(FramesMDBContext); + const { + instance, + root, + saveState, + hoverNode, + setHoverNode, + dragNode, + moveToRank, + nodes, + setDragNode, + addNode, + saveNodes, + moveNodeFromSchema + } = q2(FramesEditorContext); + const activeRunID = _2(null); + p2( + () => () => { + activeRunID.current = null; + }, + [] ); - const [folderCache, setFolderCache] = h2(null); - const [currentFlowNotePath, setCurrentFlowNotePath] = h2(null); - const refreshCache = () => { - if (props2.context.type == "folder") { - setFolderCache( - props2.plugin.index.filesIndex.get(props2.context.contextPath) - ); - return; - } - setFolderCache(null); + const resetState = () => { + setHoverNode(null); + setDragNode(null); }; - const name = (_a2 = contextCache == null ? void 0 : contextCache.name) != null ? _a2 : contextDisplayName(props2.context); - const ref = _2(null); - const [flowOpen, setFlowOpen] = h2( - props2.plugin.settings.folderNoteDefaultView && props2.plugin.settings.enableFolderNote + const dragTreeNode = F2( + () => { + var _a2; + return dragNode && instance.root && ((_a2 = findParent(instance.root, dragNode)) == null ? void 0 : _a2.children.find( + (f4) => f4.id == dragNode + )); + }, + [dragNode, instance] ); - const folderRef = _2(""); - const loadFile = async () => { - if (!folderCache) - return; - const folderNotePath = folderNotePathFromAFile( - props2.plugin.settings, - folderCache - ); - let folderNote = getAbstractFileAtPath(app, folderNotePath); - if ((currentFlowNotePath == null ? void 0 : currentFlowNotePath.path) != (folderNote == null ? void 0 : folderNote.path)) - setCurrentFlowNotePath(folderNote); - folderRef.current = folderNotePath; - const div = ref.current; - if (!folderNote) { - folderNote = await app.fileManager.createNewMarkdownFile( - app.vault.getRoot(), - folderNotePath - ); - } - spawnPortal(props2.plugin, div, folderCache.name, async (editor) => { - var _a3, _b3; - const leaf = await editor.openFile(folderNote); - if (!((_a3 = leaf == null ? void 0 : leaf.view) == null ? void 0 : _a3.editor)) { + useDndMonitor({ + onDragStart({ active }) { + if (active.data.current.frame == frameSchema.id) + setDragNode(active.data.current.id); + }, + onDragOver({ active, over }) { + const overId = over == null ? void 0 : over.data.current.id; + if ((over == null ? void 0 : over.data.current.frame) == frameSchema.id) { + if (overId) + setHoverNode(overId); + } + }, + onDragCancel() { + resetState(); + }, + onDragEnd({ active, over }) { + if (!active) { + resetState(); return; } - const view = (_b3 = leaf.view.editor) == null ? void 0 : _b3.cm; - view.dispatch({ - annotations: [portalTypeAnnotation.of("foldernote")] - }); - }); - }; - const cacheChanged = (evt) => { - if (evt.detail.type == "file") { - if (evt.detail.name == context.contextPath || evt.detail.name == (folderCache == null ? void 0 : folderCache.path)) { - refreshCache(); + let overId = hoverNode; + let overNewColumn = false; + if ((overId == null ? void 0 : overId.charAt(0)) == "|") { + overId = overId.substring(1); + overNewColumn = true; } + if (overId == active.data.current.id) { + resetState(); + return; + } + const overParentNode = findParent(instance.root, overId); + const overNode = overParentNode == null ? void 0 : overParentNode.children.find( + (f4) => f4.id == overId + ); + const activeParentNode = findParent( + instance.root, + active.data.current.id + ); + const activeNode = activeParentNode == null ? void 0 : activeParentNode.children.find( + (f4) => f4.id == active.data.current.id + ); + if (overId === PLACEHOLDER_ID3) { + saveNodes([{ ...activeNode.node, parentId: overNode.node.id }]); + } else if (overNode && activeNode) { + const [newNodes, deleteNodes] = dropFrame( + activeNode, + overNode, + instance.root, + nodes, + overNewColumn + ); + saveNodes(newNodes, deleteNodes); + } + resetState(); } - }; - p2(() => { - window.addEventListener(eventTypes.spacesChange, cacheChanged); - refreshCache(); - return () => { - window.removeEventListener(eventTypes.spacesChange, cacheChanged); - }; - }, [props2.context]); - p2(() => { - if (flowOpen && folderCache) { - loadFile(); - } else { - if (ref.current) - ref.current.empty(); - } - }, [flowOpen, folderCache]); - const viewFolderNote = (open) => { - setFlowOpen(open); - }; + }); + return /* @__PURE__ */ Cn.createElement(Cn.Fragment, null, instance.root && /* @__PURE__ */ Cn.createElement(Cn.Fragment, null, /* @__PURE__ */ Cn.createElement(FrameNodeView, { + editMode: 1, + plugin: props2.plugin, + treeNode: instance.root, + instance + }), /* @__PURE__ */ Cn.createElement(RowPlaceholder, { + plugin: props2.plugin, + id: PLACEHOLDER_ID3, + parentId: "main" + })), z3( + /* @__PURE__ */ Cn.createElement(DragOverlay, { + dropAnimation: null, + zIndex: 1600 + }, dragTreeNode && /* @__PURE__ */ Cn.createElement(FrameView, { + plugin: props2.plugin, + treeNode: dragTreeNode, + instance, + saveState + })), + document.body + )); +}; + +// src/components/SpaceView/TitleComponent.tsx +var TitleComponent = (props2) => { const fileNameRef = _2(null); + const name = pathDisplayName(props2.space.space.uri, props2.plugin); + const contentEditable = !(props2.space.space.readOnly || props2.space.type == "vault"); const onBlur = (e4) => { const newValue = e4.target.innerHTML; if (newValue != name) { - renameContext(props2.plugin, context, newValue); + renamePath(props2.plugin, props2.space.space.uri, newValue); } }; const onKeyPress = (e4) => { @@ -43513,33 +57056,17 @@ var ContextViewComponent = (props2) => { e4.preventDefault(); } }; - return /* @__PURE__ */ Cn.createElement("div", { - className: `mk-folder-scroller markdown-source-view mod-cm6 ${props2.plugin.settings.readableLineWidth ? "is-readable-line-width" : ""}` - }, props2.plugin.settings.enableFolderNote && props2.context.type == "folder" ? /* @__PURE__ */ Cn.createElement(MDBProvider, { - plugin: props2.plugin, - context - }, (folderCache == null ? void 0 : folderCache.banner) && /* @__PURE__ */ Cn.createElement(NoteBannerView, { - plugin: props2.plugin, - link: folderCache.banner - }), /* @__PURE__ */ Cn.createElement("div", { - className: "mk-sizer-override cm-sizer" - }, /* @__PURE__ */ Cn.createElement("div", { - className: "mk-folder-header embedded-backlinks" - }, folderCache && /* @__PURE__ */ Cn.createElement("div", { - className: `mk-spacer`, - style: { - "--header-height": folderCache.banner ? ((platformIsMobile() ? 1 : 0) * 26 + 138 + (!folderCache.sticker || props2.plugin.settings.inlineContextNameLayout == "horizontal" ? 1 : 0) * 50).toString() + "px" : 0 - }, - onContextMenu: (e4) => e4.preventDefault() - }), /* @__PURE__ */ Cn.createElement("div", { - className: `mk-file-context-file ${props2.plugin.settings.inlineContextNameLayout == "horizontal" ? "mk-file-context-file-horizontal" : ""}` - }, props2.plugin.settings.spacesStickers && folderCache ? /* @__PURE__ */ Cn.createElement(FileSticker, { + return /* @__PURE__ */ Cn.createElement(Cn.Fragment, null, props2.plugin.settings.spacesStickers && props2.space ? /* @__PURE__ */ Cn.createElement(FileStickerContainer, { plugin: props2.plugin, - fileCache: folderCache + path: props2.space.space.uri }) : /* @__PURE__ */ Cn.createElement(Cn.Fragment, null), /* @__PURE__ */ Cn.createElement("div", { + className: "mk-title-container" + }, props2.space.type == "tag" ? /* @__PURE__ */ Cn.createElement("div", { + className: "mk-title-prefix" + }, "#") : "", /* @__PURE__ */ Cn.createElement("div", { className: "mk-inline-title inline-title", ref: fileNameRef, - contentEditable: true, + contentEditable, onBlur, onDrop: (e4) => e4.preventDefault(), onKeyDown, @@ -43548,150 +57075,169 @@ var ContextViewComponent = (props2) => { dangerouslySetInnerHTML: { __html: name } - })), /* @__PURE__ */ Cn.createElement(TableSelector, { + }))); +}; + +// src/components/SpaceView/SpaceComponent.tsx +var SpaceComponent = (props2) => { + const path = props2.path; + const [spaceCache, setSpaceCache] = h2(null); + const reloadSpace = T2(() => { + const newSpace = props2.plugin.index.spacesIndex.get(path.fullPath); + setSpaceCache(newSpace); + }, [path]); + const { spaceInfo } = q2(SpaceContext); + const defFile = F2( + () => spaceCache ? getAbstractFileAtPath(props2.plugin, spaceCache.space.defPath) : null, + [spaceCache] + ); + p2(() => reloadSpace(), []); + const refreshSpace = T2( + async (evt) => { + if (evt.detail.type == "space") { + if (evt.detail.name == spaceInfo.path) { + reloadSpace(); + } + } + }, + [spaceInfo, reloadSpace] + ); + const [collapsed, setCollapsed] = h2( + !props2.plugin.settings.inlineContextExpanded + ); + p2(() => { + window.addEventListener(eventTypes.spacesChange, refreshSpace); + return () => { + window.removeEventListener(eventTypes.spacesChange, refreshSpace); + }; + }, [refreshSpace]); + const [selectedView, setSelectedView] = h2(0); + const banner = F2(() => { + var _a2; + if (props2.path.type == "space" && spaceCache) { + return spaceCache.metadata.banner; + } + if (props2.path.type == "folder") { + return (_a2 = props2.plugin.index.filesIndex.get(props2.path.path)) == null ? void 0 : _a2.banner; + } + return null; + }, [spaceCache, props2.path]); + const frameProps = F2(() => { + var _a2; + if (!spaceInfo) { + return {}; + } + const folderNote = spaceInfo.defPath; + return { + ...(_a2 = spaceCache == null ? void 0 : spaceCache.frontmatter) != null ? _a2 : {}, + note: folderNote, + space: props2.path.fullPath + "/#^files" + }; + }, [spaceInfo, props2.path]); + const sensors = useSensors( + useSensor(MouseSensor, { + activationConstraint: { + distance: 10 + } + }), + useSensor(TouchSensor, { + activationConstraint: { + delay: 250, + tolerance: 5 + } + }), + useSensor(KeyboardSensor, { + coordinateGetter: sortableKeyboardCoordinates + }) + ); + return /* @__PURE__ */ Cn.createElement(DndContext, { + sensors, + measuring: { + droppable: { + strategy: MeasuringStrategy.Always + } + } + }, /* @__PURE__ */ Cn.createElement(FramesEditorProvider, { plugin: props2.plugin, - folderNoteName: (_b2 = getFolderFromPath(app, props2.context.contextPath)) == null ? void 0 : _b2.name, - folderNoteOpen: flowOpen, - folderNotePath: folderNotePathFromAFile( - props2.plugin.settings, - tFileToAFile( - getAbstractFileAtPath(app, props2.context.contextPath) - ) - ), - viewFolderNote - }))), context && !flowOpen && /* @__PURE__ */ Cn.createElement(Cn.Fragment, null, /* @__PURE__ */ Cn.createElement(FilterBar, { - plugin: props2.plugin - }), /* @__PURE__ */ Cn.createElement(ContextListView, { - plugin: props2.plugin - })), flowOpen && /* @__PURE__ */ Cn.createElement("div", { - className: "mk-folder-outer" - }, currentFlowNotePath && props2.plugin.settings.inlineContext && props2.plugin.settings.makerMode && /* @__PURE__ */ Cn.createElement("div", { - className: "mk-sizer-override cm-sizer" + props: frameProps, + editMode: 1 }, /* @__PURE__ */ Cn.createElement("div", { - className: "mk-inline-context embedded-backlinks" - }, /* @__PURE__ */ Cn.createElement(InlineFileContextView, { - plugin: props2.plugin, - file: currentFlowNotePath, - showHeader: false, - showBanner: false, - editable: true, - isFolderNote: true - }))), /* @__PURE__ */ Cn.createElement("div", { - className: "mk-flowspace-editor mk-foldernote", - ref - }))) : /* @__PURE__ */ Cn.createElement(MDBProvider, { + className: "mk-space-scroller markdown-source-view mod-cm6 is-readable-line-width" + }, spaceCache && /* @__PURE__ */ Cn.createElement(NoteBannerView, { plugin: props2.plugin, - context + link: spaceCache.metadata.banner + }), (spaceCache == null ? void 0 : spaceCache.metadata.banner) && /* @__PURE__ */ Cn.createElement("div", { + className: "mk-spacer", + style: { + "--mk-header-height": ((platformIsMobile() ? 1 : 0) * 26 + 138 + (!props2.plugin.settings.spacesStickers || props2.plugin.settings.inlineContextNameLayout == "horizontal" ? 1 : 0) * 50).toString() + "px" + } + }), spaceCache && /* @__PURE__ */ Cn.createElement(SpaceOuter, null, /* @__PURE__ */ Cn.createElement("div", { + className: "mk-space-header" }, /* @__PURE__ */ Cn.createElement("div", { - className: "mk-context-header cm-sizer mk-sizer-override" + className: `mk-file-context-file ${props2.plugin.settings.inlineContextNameLayout == "horizontal" ? "mk-file-context-file-horizontal" : ""}` }, /* @__PURE__ */ Cn.createElement("div", { - className: "mk-inline-title inline-title", - ref: fileNameRef, - contentEditable: true, - onBlur, - onDrop: (e4) => e4.preventDefault(), - onKeyDown, - onKeyPress, - onKeyUp, - dangerouslySetInnerHTML: { - __html: name - } - }), props2.context.type == "folder" && /* @__PURE__ */ Cn.createElement(TableSelector, { - plugin: props2.plugin - })), /* @__PURE__ */ Cn.createElement(FilterBar, { - plugin: props2.plugin - }), /* @__PURE__ */ Cn.createElement(ContextListView, { - plugin: props2.plugin - }))); -}; - -// src/components/ContextView/ContextView.tsx -var CONTEXT_VIEW_TYPE = "make-folder-view"; -var ContextView = class extends import_obsidian38.ItemView { - constructor(leaf, plugin, viewType) { - super(leaf); - this.navigation = true; - this.plugin = plugin; - this.viewType = viewType; - } - getViewType() { - return CONTEXT_VIEW_TYPE; - } - getDisplayText() { - return contextDisplayName(this.context); - } - async onClose() { - this.destroy(); - } - destroy() { - if (this.root) - this.root.unmount(); - } - async onOpen() { - this.destroy(); - } - async setState(state, result) { - this.contextPath = state.contextPath; - this.context = mdbContextByPath(this.plugin, this.contextPath); - if (!this.context) - return; - this.constructContext(this.context); - const displayName = contextDisplayName(this.context); - await super.setState(state, result); - this.leaf.tabHeaderInnerTitleEl.innerText = displayName; - this.leaf.view.titleEl = displayName; - const headerEl = this.leaf.view.headerEl; - if (headerEl) { - headerEl.querySelector(".view-header-title").innerText = displayName; + className: "mk-space-title" + }, /* @__PURE__ */ Cn.createElement(TitleComponent, { + plugin: props2.plugin, + space: spaceCache + }), /* @__PURE__ */ Cn.createElement("div", { + className: `mk-collapse mk-icon-xsmall mk-fold ${collapsed ? "mk-collapsed" : ""}`, + dangerouslySetInnerHTML: { + __html: uiIconSet["mk-ui-collapse"] + }, + onClick: (e4) => { + setCollapsed(!collapsed); + e4.stopPropagation(); } - result.history = true; - return; - } - getState() { - let state = super.getState(); - state.contextPath = this.contextPath; - return state; - } - constructContext(context) { - this.destroy(); - this.root = createRoot(this.contentEl); - this.root.render( - /* @__PURE__ */ Cn.createElement("div", { - className: "mk-folder-view" - }, /* @__PURE__ */ Cn.createElement(ContextViewComponent, { - context, - plugin: this.plugin - })) - ); - } -}; - -// src/components/FileView/FileView.tsx -var import_obsidian40 = require("obsidian"); - -// src/components/FileView/FileLinkViewComponent.tsx -var import_obsidian39 = require("obsidian"); -var FileLinkViewComponent = (props2) => { - const ref = _2(null); - const [markdown, setMarkdown] = h2(""); - p2(() => { - if (ref.current) - import_obsidian39.MarkdownRenderer.renderMarkdown(markdown, ref.current, props2.path, null); - }, [markdown]); + })), !collapsed && /* @__PURE__ */ Cn.createElement(InlineFileContextView, { + plugin: props2.plugin, + path: spaceCache.path, + showHeader: false, + showMetadata: true, + hiddenFields: [ + ...FMMetadataKeys(props2.plugin), + ...FMSpaceKeys(props2.plugin) + ], + showBanner: false, + editable: true, + showFolder: spaceCache.space.uri.type == "folder" + }))), /* @__PURE__ */ Cn.createElement("div", { + className: "mk-space-body" + }, /* @__PURE__ */ Cn.createElement(SpaceBodyView, { + selectedView, + plugin: props2.plugin + })))))); +}; +var SpaceOuter = (props2) => { + const { selectNodes, selectableNodeBounds, selectedNodes, nodes } = q2(FramesEditorContext); + const [selectionBox, setSelectionBox] = h2(); + const selectableItems = _2([]); + const ref2 = _2(null); + const [dragging, setDragging] = h2(false); + const onKeyDown = (e4) => { + if (e4.key === "Escape") { + selectNodes([]); + } + }; p2(() => { - fetch(props2.path).then((res) => res.text()).then((f4) => setMarkdown(f4)); - }, [props2.path]); + window.addEventListener("keydown", onKeyDown); + return () => { + window.removeEventListener("keydown", onKeyDown); + }; + }, []); return /* @__PURE__ */ Cn.createElement("div", { - className: "markdown-preview-view markdown-rendered node-insert-event is-readable-line-width allow-fold-headings show-indentation-guide allow-fold-lists show-frontmatter" - }, /* @__PURE__ */ Cn.createElement("div", { - className: "markdown-preview-sizer markdown-preview-section", - ref - })); + className: "mk-space-outer cm-line", + ref: ref2, + onClick: () => { + if (!dragging) + selectNodes([]); + } + }, props2.children); }; -// src/components/FileView/FileView.tsx -var FILE_VIEW_TYPE = "make-file-view"; -var FileLinkView = class extends import_obsidian40.ItemView { +// src/components/SpaceView/Contexts/SpaceView.tsx +var SPACE_VIEW_TYPE = "mk-space"; +var SpaceView = class extends import_obsidian47.ItemView { constructor(leaf, plugin, viewType) { super(leaf); this.navigation = true; @@ -43699,10 +57245,10 @@ var FileLinkView = class extends import_obsidian40.ItemView { this.viewType = viewType; } getViewType() { - return FILE_VIEW_TYPE; + return SPACE_VIEW_TYPE; } getDisplayText() { - return this.path; + return pathDisplayName(this.path, this.plugin); } async onClose() { this.destroy(); @@ -43715,50 +57261,80 @@ var FileLinkView = class extends import_obsidian40.ItemView { this.destroy(); } async setState(state, result) { - this.path = state.path; - this.constructView(this.path); - const displayName = this.path; + this.path = uriByString(this.plugin, state.path); + if (!this.path) + return; + this.constructNote(this.path); + const displayName = pathDisplayName(this.path, this.plugin); await super.setState(state, result); this.leaf.tabHeaderInnerTitleEl.innerText = displayName; this.leaf.view.titleEl = displayName; const headerEl = this.leaf.view.headerEl; if (headerEl) { - headerEl.querySelector(".view-header-title").innerText = displayName; + headerEl.querySelector(".view-header-title").innerText = this.path.type == "tag" ? "#" + displayName : displayName; + if (this.path.type == "folder") { + const titleParent = headerEl.querySelector(".view-header-title-parent"); + titleParent.empty(); + const parentPaths = getParentFolderPaths(this.path.fullPath); + if (titleParent) { + parentPaths.forEach((f4) => { + const breadcrumb = titleParent.createEl("span"); + breadcrumb.addClass("view-header-breadcrumb"); + breadcrumb.innerText = folderPathToString(f4); + breadcrumb.addEventListener( + "click", + () => openSpace(f4, this.plugin, false) + ); + const breadcrumbSeparator = titleParent.createEl("span"); + breadcrumbSeparator.addClass("view-header-breadcrumb-separator"); + breadcrumbSeparator.innerText = "/"; + }); + } + } } result.history = true; return; } getState() { - let state = super.getState(); - state.path = this.path; + const state = super.getState(); + state.path = this.path.fullPath; return state; } - constructView(path) { + constructNote(path) { this.destroy(); this.root = createRoot(this.contentEl); + const space = spaceInfoByPath(this.plugin, path.fullPath); this.root.render( /* @__PURE__ */ Cn.createElement("div", { - className: "markdown-reading-view" - }, /* @__PURE__ */ Cn.createElement(FileLinkViewComponent, { + className: "mk-space-view" + }, space && /* @__PURE__ */ Cn.createElement(SpaceContextProvider, { + plugin: this.plugin, + space + }, /* @__PURE__ */ Cn.createElement(FramesMDBProvider, { + plugin: this.plugin, + schema: "main" + }, /* @__PURE__ */ Cn.createElement(SpaceComponent, { path, - plugin: this.plugin - })) + plugin: this.plugin, + leaf: this.leaf + })))) ); } }; // src/utils/file.ts -var import_obsidian41 = require("obsidian"); +var import_obsidian48 = require("obsidian"); var tFileToAFile = (file) => { - var _a2, _b2; + var _a2, _b2, _c2; if (!file) return null; - if (file instanceof import_obsidian41.TFile && file.stat) { + if (file instanceof import_obsidian48.TFile && file.stat) { return { isFolder: false, name: file.basename, + filename: file.name, path: file.path, - parent: file.parent.path, + parent: (_a2 = file.parent) == null ? void 0 : _a2.path, stat: file.stat, extension: file.extension }; @@ -43766,17 +57342,18 @@ var tFileToAFile = (file) => { return { isFolder: true, name: file.name, + filename: file.name, path: file.path, - parent: (_b2 = (_a2 = file.parent) == null ? void 0 : _a2.path) != null ? _b2 : "/" + parent: (_c2 = (_b2 = file.parent) == null ? void 0 : _b2.path) != null ? _c2 : "/" }; }; -var defaultNoteFolder = (plugin, activeFile2) => { +var defaultNoteFolder = (plugin, activeFile) => { var _a2; - return (_a2 = plugin.settings.newFileLocation == "folder" ? getFolderFromPath(app, plugin.settings.newFileFolderPath) : plugin.settings.newFileLocation == "current" && activeFile2 ? getFolderFromPath(app, activeFile2.path) : plugin.app.vault.getRoot()) != null ? _a2 : plugin.app.vault.getRoot(); + return (_a2 = plugin.settings.newFileLocation == "folder" ? getFolderFromPath(plugin, plugin.settings.newFileFolderPath) : plugin.settings.newFileLocation == "current" && activeFile && activeFile.type == "folder" ? getFolderFromPath(plugin, activeFile.path) : plugin.app.vault.getRoot()) != null ? _a2 : plugin.app.vault.getRoot(); }; -var defaultConfigFile = async (app2) => { - return await app2.vault.adapter.read( - (0, import_obsidian41.normalizePath)(app2.vault.configDir + "/app.json") +var defaultConfigFile = async (plugin) => { + return await plugin.app.vault.adapter.read( + (0, import_obsidian48.normalizePath)(plugin.app.vault.configDir + "/app.json") ); }; var appendFilesMetaData = (plugin, propType, filesString) => { @@ -43809,31 +57386,80 @@ var appendFileMetaData = (propType, file) => { } return value; }; -var moveFile = async (folder, file) => { - await app.vault.rename(file, folder.path + "/" + file.name); +var moveFile = async (plugin, folder, file) => { + await plugin.app.vault.rename(file, folder.path + "/" + file.name); +}; +var copyFile = async (plugin, folder, file) => { + const newPath = folder.path + "/" + file.name; + if (file instanceof import_obsidian48.TFolder) { + if (!abstractFileAtPathExists(plugin, newPath)) { + plugin.app.vault.createFolder(newPath); + } + } else if (file instanceof import_obsidian48.TFile) { + await plugin.app.vault.copy(file, folder.path + "/" + file.name); + } +}; +var uniqueFileName = (oldName, name, extension, folder) => { + let newName = sanitizeFileName(name); + let uniqueName = false; + let append = 1; + while (!uniqueName) { + if (!folder.children.some((f4) => f4.name == `${newName}.${extension}` && f4.name != oldName)) { + uniqueName = true; + } else { + newName = `${newName} ${append}`; + append += 1; + } + } + return `${newName}.${extension}`; +}; +var uniqueFolderName = (oldName, name, folder) => { + let newName = sanitizeFolderName(name); + let uniqueName = false; + let append = 1; + while (!uniqueName) { + if (!folder.children.some((f4) => f4.name == `${newName}` && f4.name != oldName)) { + uniqueName = true; + } else { + newName = `${newName} ${append}`; + append += 1; + } + } + return `${newName}`; }; var renameFile = async (plugin, file, newName) => { const afile = tFileToAFile(file); - await app.fileManager.renameFile( - file, - file.parent.path == "/" ? newName : file.parent.path + "/" + newName + const fileName = afile.isFolder ? uniqueFolderName(file.name, newName, file.parent) : uniqueFileName(file.name, newName, afile.extension, file.parent); + const newPath = file.parent.path == "/" ? fileName : file.parent.path + "/" + fileName; + await plugin.files.renameFile( + file.path, + newPath ); - if (afile.isFolder && plugin.settings.enableFolderNote) { - const folderNotePath = folderNotePathFromAFile(plugin.settings, afile); - const folderNote = getAbstractFileAtPath(app, folderNotePath); - if (folderNote) - await app.fileManager.renameFile( - folderNote, - folderNotePathFromAFile(plugin.settings, tFileToAFile(file)) - ); + return fileName; +}; +var folderRenamed = async (plugin, oldPath, newPath) => { + const oldName = folderPathToString(oldPath); + const newName = folderPathToString(newPath); + if (newPath.startsWith(plugin.settings.spacesFolder)) { + const spaceNote = getAbstractFileAtPath(plugin, `${newPath}/${oldName}.md`); + if (spaceNote) + renameFile(plugin, spaceNote, newName); + } else if (plugin.settings.enableFolderNote) { + const folder = getAbstractFileAtPath(plugin, newPath); + const afile = tFileToAFile(folder); + const folderNotePath = folderNotePathFromAFile(plugin.settings, { ...afile, name: oldName }); + await plugin.files.renameFile( + folderNotePath, + folderNotePathFromAFile(plugin.settings, afile) + ); } }; -function getAllAbstractFilesInVault(plugin, app2) { +function getAllAbstractFilesInVault(plugin) { const files = []; - const rootFolder = app2.vault.getRoot(); + const rootFolder = plugin.app.vault.getRoot(); function recursiveFx(folder) { for (const child of folderChildren(plugin, folder)) { - if (child instanceof import_obsidian41.TFolder) { + if (child instanceof import_obsidian48.TFolder) { const childFolder = child; if (childFolder.children) recursiveFx(childFolder); @@ -43845,17 +57471,17 @@ function getAllAbstractFilesInVault(plugin, app2) { return files; } var removeTrailingSlashFromFolder = (path) => path == "/" ? path : path.slice(-1) == "/" ? path.substring(0, path.length - 1) : path; -var getFolderFromPath = (app2, path) => { +var getFolderFromPath = (plugin, path) => { if (!path) return null; - const afile = getAbstractFileAtPath(app2, removeTrailingSlashFromFolder(path)); + const afile = getAbstractFileAtPath(plugin, removeTrailingSlashFromFolder(path)); if (!afile) return null; - return afile instanceof import_obsidian41.TFolder ? afile : afile.parent; + return afile instanceof import_obsidian48.TFolder ? afile : afile.parent; }; -var getFolderPathFromString = (file) => { +var getFolderPathFromString = (plugin, file) => { var _a2; - return (_a2 = getFolderFromPath(app, file)) == null ? void 0 : _a2.path; + return (_a2 = getFolderFromPath(plugin, file)) == null ? void 0 : _a2.path; }; var getParentPathFromString = (file) => { const indexOfLastSlash = file.lastIndexOf("/"); @@ -43866,8 +57492,9 @@ var getParentPathFromString = (file) => { }; var deleteFiles = (plugin, files) => { files.forEach((f4) => { - const file = getAbstractFileAtPath(app, f4); - deleteFile(plugin, file); + const file = getAbstractFileAtPath(plugin, f4); + if (file) + deleteFile(plugin, file); }); }; var deleteFile = (plugin, file) => { @@ -43880,66 +57507,89 @@ var deleteFile = (plugin, file) => { return plugin.app.vault.trash(file, false); } }; -var getFolderName = (folderPath, app2) => { - if (folderPath === "/") - return app2.vault.getName(); - const index = folderPath.lastIndexOf("/"); - if (index !== -1) - return folderPath.substring(index + 1); - return folderPath; +var getParentFolderPaths = (path) => { + const folderPaths = []; + const parts = path.split("/"); + let current2 = ""; + for (let i4 = 0; i4 < parts.length; i4++) { + current2 += `${i4 === 0 ? "" : "/"}` + parts[i4]; + if (current2 != path) { + folderPaths.push(current2); + } + } + return folderPaths; }; -var openFile = async (file, plugin, newLeaf) => { - openAFile(getAbstractFileAtPath(plugin.app, file.path), plugin, newLeaf); +var openPath2 = async (path, plugin, newLeaf) => { + openAFile(getAbstractFileAtPath(plugin, path), plugin, newLeaf); }; -var openSpace = async (spaceName, plugin, newLeaf) => { +var openSpace = async (spacePath, plugin, newLeaf) => { + if (spacePath == tagsSpace.path) + return; if (!plugin.settings.contextEnabled) return; - const leaf = app.workspace.getLeaf(newLeaf); - const viewType = CONTEXT_VIEW_TYPE; - app.workspace.setActiveLeaf(leaf, { focus: true }); + const leaf = getLeaf(plugin, newLeaf); + const viewType = SPACE_VIEW_TYPE; + plugin.app.workspace.setActiveLeaf(leaf, { focus: true }); await leaf.setViewState({ type: viewType, - state: { contextPath: spaceContextPathFromName(spaceName) } + state: { path: spacePath } }); - await app.workspace.requestSaveLayout(); + await plugin.app.workspace.requestSaveLayout(); if (platformIsMobile()) { - app.workspace.leftSplit.collapse(); + plugin.app.workspace.leftSplit.collapse(); } const evt = new CustomEvent(eventTypes.activePathChange, { - detail: { path: pathByString(spaceContextPathFromName(spaceName)) } + detail: { path: uriByString(plugin, spacePath) } }); window.dispatchEvent(evt); }; -var openURL = async (url) => { - const leaf = app.workspace.getLeaf(false); +var getLeaf = (plugin, location) => { + let leaf = plugin.app.workspace.getLeaf(false); + if (location == "right") { + leaf = plugin.app.workspace.getRightLeaf(false); + } else if (location == "left") { + leaf = plugin.app.workspace.getLeftLeaf(false); + } else { + leaf = plugin.app.workspace.getLeaf(location); + } + return leaf; +}; +var openURL = async (url, plugin, location) => { + const leaf = getLeaf(plugin, location); if (url.endsWith(".md")) { const viewType = FILE_VIEW_TYPE; - app.workspace.setActiveLeaf(leaf, { focus: true }); + plugin.app.workspace.setActiveLeaf(leaf, { focus: true }); await leaf.setViewState({ type: viewType, state: { path: url } }); - await app.workspace.requestSaveLayout(); + await plugin.app.workspace.requestSaveLayout(); } else if (url.endsWith(".mdb")) { - const viewType = CONTEXT_VIEW_TYPE; - app.workspace.setActiveLeaf(leaf, { focus: true }); + const viewType = SPACE_VIEW_TYPE; + plugin.app.workspace.setActiveLeaf(leaf, { focus: true }); await leaf.setViewState({ type: viewType, - state: { contextPath: url } + state: { path: url } + }); + await plugin.app.workspace.requestSaveLayout(); + } else { + plugin.app.workspace.setActiveLeaf(leaf, { focus: true }); + await leaf.setViewState({ + type: EMBED_CONTEXT_VIEW_TYPE, + state: { path: url } }); - await app.workspace.requestSaveLayout(); } if (platformIsMobile()) { - app.workspace.leftSplit.collapse(); + plugin.app.workspace.leftSplit.collapse(); } }; -function getAllFoldersInVault(app2) { +function getAllFoldersInVault(plugin) { const folders = []; - const rootFolder = app2.vault.getRoot(); + const rootFolder = plugin.app.vault.getRoot(); folders.push(rootFolder); function recursiveFx(folder) { for (const child of folder.children) { - if (child instanceof import_obsidian41.TFolder) { + if (child instanceof import_obsidian48.TFolder) { const childFolder = child; folders.push(childFolder); if (childFolder.children) @@ -43951,19 +57601,23 @@ function getAllFoldersInVault(app2) { return folders; } var openAFile = async (file, plugin, newLeaf) => { - if (file instanceof import_obsidian41.TFolder) { + if (file instanceof import_obsidian48.TFolder) { openTFolder(file, plugin, newLeaf); - } else if (file instanceof import_obsidian41.TFile) { + } else if (file instanceof import_obsidian48.TFile) { openTFile(file, plugin, newLeaf); + } else { + return; } - let evt = new CustomEvent(eventTypes.activePathChange, { - detail: { path: pathByString(file.path) } + const evt = new CustomEvent(eventTypes.activePathChange, { + detail: { path: uriByString(plugin, file.path) } }); window.dispatchEvent(evt); }; var openTFile = async (file, plugin, newLeaf) => { - let leaf = app.workspace.getLeaf(newLeaf); - app.workspace.setActiveLeaf(leaf, { focus: true }); + if (!file) + return; + const leaf = getLeaf(plugin, newLeaf); + plugin.app.workspace.setActiveLeaf(leaf, { focus: true }); await leaf.openFile(file, { eState: { focus: true } }); const fileCache = plugin.index.filesIndex.get(file.path); if ((fileCache == null ? void 0 : fileCache.sticker) && leaf.tabHeaderInnerIconEl) { @@ -43972,79 +57626,80 @@ var openTFile = async (file, plugin, newLeaf) => { } }; var openTFolder = async (file, plugin, newLeaf) => { - let leaf = app.workspace.getLeaf(newLeaf); - const viewType = CONTEXT_VIEW_TYPE; - app.workspace.setActiveLeaf(leaf, { focus: true }); + const leaf = getLeaf(plugin, newLeaf); + const viewType = SPACE_VIEW_TYPE; + plugin.app.workspace.setActiveLeaf(leaf, { focus: true }); await leaf.setViewState({ type: viewType, - state: { contextPath: file.path } + state: { path: file.path } }); const fileCache = plugin.index.filesIndex.get(file.path); if ((fileCache == null ? void 0 : fileCache.sticker) && leaf.tabHeaderInnerIconEl) { const icon = stickerFromString(fileCache.sticker, plugin); leaf.tabHeaderInnerIconEl.innerHTML = icon; } - await app.workspace.requestSaveLayout(); + await plugin.app.workspace.requestSaveLayout(); if (platformIsMobile()) { - app.workspace.leftSplit.collapse(); + plugin.app.workspace.leftSplit.collapse(); } }; var openTagContext = async (tag, plugin, newLeaf) => { - let leaf = app.workspace.getLeaf(newLeaf); - const viewType = CONTEXT_VIEW_TYPE; - app.workspace.setActiveLeaf(leaf, { focus: true }); - await leaf.setViewState({ type: viewType, state: { contextPath: tag } }); - await app.workspace.requestSaveLayout(); + const leaf = getLeaf(plugin, newLeaf); + const viewType = SPACE_VIEW_TYPE; + plugin.app.workspace.setActiveLeaf(leaf, { focus: true }); + await leaf.setViewState({ type: viewType, state: { path: "spaces://" + tag } }); + await plugin.app.workspace.requestSaveLayout(); if (platformIsMobile()) { - app.workspace.leftSplit.collapse(); + plugin.app.workspace.leftSplit.collapse(); } const evt = new CustomEvent(eventTypes.activePathChange, { - detail: { path: pathByString(tag) } + detail: { path: uriByString(plugin, tag) } }); window.dispatchEvent(evt); }; -var getAbstractFileAtPath = (app2, path) => { - return app2.vault.getAbstractFileByPath(path); +var getAbstractFileAtPath = (plugin, path) => { + return plugin.app.vault.getAbstractFileByPath(path); }; -var abstractFileAtPathExists = (app2, path) => { - return app2.vault.getAbstractFileByPath(path) ? true : false; +var abstractFileAtPathExists = (plugin, path) => { + return plugin.app.vault.getAbstractFileByPath(path) ? true : false; }; var openFileInNewPane = (plugin, file) => { - openFile(file, plugin, true); + openPath2(file.path, plugin, true); }; var createNewCanvasFile = async (plugin, folder, newFileName, dontOpen) => { - const newFile = await app.fileManager.createNewMarkdownFile( - folder, - newFileName - ); - await app.vault.modify(newFile, "{}"); - await renameFile( - plugin, - newFile, - newFile.name.substring(0, newFile.name.lastIndexOf(".")) + ".canvas" - ); + const newFile = await plugin.files.newFile(folder.path, newFileName, "canvas"); if (dontOpen) { return newFile; } await openAFile(newFile, plugin, false); const evt = new CustomEvent(eventTypes.activePathChange, { - detail: { path: pathByString(newFile.path) } + detail: { path: uriByString(plugin, newFile.path) } }); window.dispatchEvent(evt); return newFile; }; +var createMarkdownFileAtPath = async (plugin, path) => { + const folderPath = filePathToFolderPath(path); + let folder = getAbstractFileAtPath(plugin, folderPath); + if (!folder || !(folder instanceof import_obsidian48.TFolder)) { + folder = await plugin.app.vault.createFolder(folderPath); + } + return plugin.files.newFile(folder.path, folderPathToString(path), "md"); +}; var createNewMarkdownFile = async (plugin, folder, newFileName, content, dontOpen) => { - const newFile = await app.fileManager.createNewMarkdownFile( - folder, - newFileName + const fileName = (newFileName == null ? void 0 : newFileName.length) > 0 ? newFileName : "New Note"; + const newFile = await plugin.files.newFile( + folder.path, + fileName, + "md" ); if (content && content !== "") - await app.vault.modify(newFile, content); + await plugin.app.vault.modify(newFile, content); if (dontOpen) { return newFile; } await openAFile(newFile, plugin, false); - const titleEl = app.workspace.activeLeaf.view.containerEl.querySelector( + const titleEl = plugin.app.workspace.activeLeaf.view.containerEl.querySelector( ".inline-title" ); if (titleEl) { @@ -44052,796 +57707,167 @@ var createNewMarkdownFile = async (plugin, folder, newFileName, content, dontOpe selectElementContents(titleEl); } const evt = new CustomEvent(eventTypes.activePathChange, { - detail: { path: pathByString(newFile.path) } + detail: { path: uriByString(plugin, newFile.path) } }); window.dispatchEvent(evt); return newFile; }; var platformIsMobile = () => { - return import_obsidian41.Platform.isMobile; -}; -var newFileInFolder = async (plugin, data, dontOpen) => { - await createNewMarkdownFile( - plugin, - data.parent.children.find((f4) => f4.name == data.name), - "", - "", - dontOpen - ); + return import_obsidian48.Platform.isMobile; }; var noteToFolderNote = async (plugin, file, open) => { const folderPath = fileNameToString(file.path); - const folder = getAbstractFileAtPath(app, folderPath); - if (folder && folder instanceof import_obsidian41.TFolder) { + const folder = getAbstractFileAtPath(plugin, folderPath); + if (folder && folder instanceof import_obsidian48.TFolder) { if (open) { openTFolder(folder, plugin, false); } return; } - await app.vault.createFolder(folderPath); + await plugin.app.vault.createFolder(folderPath); plugin.index.filesIndex.delete(file.path); - const newFolderNotePath = folderNotePathFromAFile(plugin.settings, tFileToAFile(getAbstractFileAtPath(app, folderPath))); + const newFolderNotePath = folderNotePathFromAFile(plugin.settings, tFileToAFile(getAbstractFileAtPath(plugin, folderPath))); if (newFolderNotePath != file.path) { - await app.vault.rename(file, newFolderNotePath); + await plugin.app.vault.rename(file, newFolderNotePath); } if (open) { - openTFolder(getAbstractFileAtPath(app, folderPath), plugin, false); + openTFolder(getAbstractFileAtPath(plugin, folderPath), plugin, false); } }; var folderNoteCache = (plugin, file) => { if (!file.extension || file.extension.length == 0) { const folderNotePath = folderNotePathFromAFile(plugin.settings, file); - if (abstractFileAtPathExists(app, folderNotePath)) { + if (abstractFileAtPathExists(plugin, folderNotePath)) { return { folderNotePath, folderPath: file.path }; } } else if (file.extension == "md") { - const folderPath = getAbstractFileAtPath(app, folderPathFromFolderNoteFile(plugin.settings, file)); - if (folderPath instanceof import_obsidian41.TFolder && folderPath.name == file.name) { + const folderPath = folderPathFromFolderNoteFile(plugin.settings, file); + if (!folderPath) + return null; + const folder = getAbstractFileAtPath(plugin, folderPath); + if (folder instanceof import_obsidian48.TFolder && folder.name == file.name) { return { folderNotePath: file.path, - folderPath: folderPath.path + folderPath: folder.path }; } } return null; }; -// src/components/ui/modals/vaultChangeModals.ts -var VaultChangeModal = class extends import_obsidian42.Modal { - constructor(plugin, file, action, space) { - super(plugin.app); - this.file = file; - this.action = action; - this.plugin = plugin; - this.space = space; - } - onOpen() { - const { contentEl } = this; - const myModal = this; - let headerText; - if (this.action === "rename") { - headerText = i18n_default.labels.rename; - } else if (this.action === "create folder") { - headerText = i18n_default.labels.createFolder; - } else if (this.action === "create note") { - headerText = i18n_default.labels.createNote; - } - const headerEl = contentEl.createEl("div", { text: headerText }); - headerEl.addClass("modal-title"); - const inputEl = contentEl.createEl("input"); - inputEl.style.cssText = "width: 100%; height: 2.5em; margin-bottom: 15px;"; - if (this.action === "rename") { - if (this.file instanceof import_obsidian42.TFolder) { - inputEl.value = this.file.name; - } else { - inputEl.value = this.file.name.substring( - 0, - indexOfCharElseEOS(".", this.file.name) - ); - } - } - inputEl.focus(); - let changeButtonText; - if (this.action === "rename") { - changeButtonText = i18n_default.buttons.rename; - } else if (this.action === "create folder") { - changeButtonText = i18n_default.buttons.createFolder; - } else if (this.action === "create note") { - changeButtonText = i18n_default.buttons.createNote; - } - const changeButton = contentEl.createEl("button", { - text: changeButtonText - }); - const cancelButton = contentEl.createEl("button", { - text: i18n_default.buttons.cancel - }); - cancelButton.style.cssText = "float: right;"; - cancelButton.addEventListener("click", () => { - myModal.close(); - }); - const onClickAction = async () => { - let newName = inputEl.value; - if (this.action === "rename") { - if (this.file instanceof import_obsidian42.TFile) { - newName = this.file.name.lastIndexOf(".") == -1 ? newName : newName + this.file.name.substring(this.file.name.lastIndexOf(".")); - } - renameFile(this.plugin, this.file, newName); - } else if (this.action === "create folder") { - const path = !this.file || this.file.path == "/" ? newName : this.file.path + "/" + newName; - if (getAbstractFileAtPath(app, path)) { - new import_obsidian42.Notice(i18n_default.notice.folderExists); - return; - } - this.app.vault.createFolder(path); - if (this.space != "/") - addPathsToSpace(this.plugin, this.space, [path]); - } - myModal.close(); - }; - changeButton.addEventListener("click", onClickAction); - inputEl.addEventListener("keydown", (e4) => { - if (e4.key === "Enter") - onClickAction(); - }); - } - onClose() { - const { contentEl } = this; - contentEl.empty(); - } -}; -var MoveSuggestionModal = class extends import_obsidian42.FuzzySuggestModal { - constructor(app2, files) { - super(app2); - this.files = files; - } - getItemText(item) { - return item.path; - } - getItems() { - return getAllFoldersInVault(this.app); - } - onChooseItem(item, evt) { - this.files.forEach((f4) => { - const file = getAbstractFileAtPath(app, f4); - if (file) { - this.app.vault.rename(file, item.path + "/" + file.name); - } - }); - } -}; -var AddToSpaceModal = class extends import_obsidian42.FuzzySuggestModal { - constructor(plugin, files) { - super(app); - this.plugin = plugin; - this.files = files; - } - getItemText(space) { - return space.name; - } - getItems() { - return this.plugin.index.allSpaces().filter((f4) => f4.def.type == "focus"); - } - onChooseItem(space, evt) { - this.files.forEach((f4) => { - var _a2; - const file = this.plugin.index.filesIndex.get(f4); - if (file) { - if (((_a2 = space.def.folder) == null ? void 0 : _a2.length) > 0) { - moveAFileToNewParentAtIndex(this.plugin, file, space.def.folder, 0); - } else { - insertSpaceItemAtIndex(this.plugin, space.name, file.path, 0); - } - } - }); - } -}; -var RemoveFromSpaceModal = class extends import_obsidian42.FuzzySuggestModal { - constructor(plugin, file) { - super(app); - this.plugin = plugin; - this.file = this.plugin.index.filesIndex.get(file); - } - getItemText(space) { - return space.name; - } - getItems() { - return this.file ? this.plugin.index.allSpaces().filter((f4) => { - var _a2; - return f4.def.type == "focus" && !(((_a2 = f4.def.folder) == null ? void 0 : _a2.length) > 0) && this.file.spaces.includes(f4.name); - }) : []; - } - onChooseItem(space, evt) { - removePathsFromSpace(this.plugin, space.name, [this.file.path]); - } -}; - -// src/superstate/spacesStore/spaces.ts -var import_lodash8 = __toESM(require_lodash()); -var import_obsidian43 = require("obsidian"); - -// src/schemas/spaces.ts -var vaultSchema = { - uniques: ["path"], - cols: ["path", "parent", "created", "sticker", "color", "folder", "rank"], - rows: [] -}; -var spaceSchema = { - uniques: ["name"], - cols: ["name", "sticker", "color", "pinned", "sort", "def", "rank"], - rows: [] -}; -var spaceItemsSchema = { - uniques: [], - cols: ["space", "path", "rank"], - rows: [] -}; - -// src/superstate/cacheParsers.ts -var import_lodash7 = __toESM(require_lodash()); -var fileMetadataToVaultItem = (cache) => { - var _a2, _b2; - return { - path: cache.path, - parent: cache.parent, - color: cache.color, - created: (_b2 = (_a2 = cache.ctime) == null ? void 0 : _a2.toString()) != null ? _b2 : "", - sticker: cache.sticker, - folder: cache.isFolder ? "true" : "false", - rank: cache.rank - }; -}; -var parseSpaceCache = (space, spaceItems) => { - return { - name: space.name, - space, - spaceItems - }; -}; - -// src/superstate/spacesStore/spaces.ts -var rebuildIndex = async (plugin, save) => { - var _a2, _b2; - console.time("Make.md Vault Index"); - const newTables = indexCurrentFileTree(plugin, (_a2 = plugin.index.vaultDBCache) != null ? _a2 : [], (_b2 = plugin.index.spacesItemsDBCache) != null ? _b2 : []); - if (save && (!import_lodash8.default.isEqual(newTables.vault.rows, plugin.index.vaultDBCache) || !import_lodash8.default.isEqual(newTables.spaceItems.rows, plugin.index.spacesItemsDBCache))) { - await plugin.index.saveSpacesDatabaseToDisk(newTables, save); - } - plugin.index.initialize(); - console.timeEnd("Make.md Vault Index"); -}; -var spaceToTreeNode = (space, collapsed, sortable) => { - return { - id: space.name, - spaceItem: space, - parentId: null, - depth: 0, - index: 0, - space: space.name, - path: space.name + "//", - item: null, - collapsed, - sortable, - childrenCount: 0 - }; -}; -var vaulItemToTreeNode = (item, space, path, depth, i4, collapsed, sortable, childrenCount) => ({ - item, - file: getAbstractFileAtPath(app, item.path), - space, - id: (space == "/" ? "" : space) + "//" + item.path, - parentId: (space == "/" ? "" : space) + "//" + path, - depth, - path, - index: i4, - collapsed, - sortable, - childrenCount -}); -var spaceRowHeight = (plugin) => { - return platformIsMobile() ? 40 : plugin.settings.spaceRowHeight; -}; -var folderSortFn = (sortStrategy, direction) => (a5, b4) => { - var _a2, _b2; - if (sortStrategy == "rank") { - return ((_a2 = a5.rank) != null ? _a2 : "").localeCompare((_b2 = b4.rank) != null ? _b2 : "", void 0, { numeric: true }); - } - const sortFns = [ - compareByField("isFolder", false), - compareByField(sortStrategy, direction) - ]; - return sortFns.reduce((p3, c4) => { - return p3 == 0 ? c4(a5, b4) : p3; - }, 0); -}; -var flattenedTreeFromVaultItems = (root, space, vaultItems, openNodes, depth, sortStrategy, direction) => { - if (!vaultItems[root]) { - return []; - } - const flattenTree = (path, vaultItems2, openNodes2, depth2, index, folderSort) => { - const items = []; - let i4 = index; - const [sortStrat, dir] = folderSort.length > 0 ? parseSortStrat(folderSort) : [sortStrategy, direction]; - vaultItems2[path].sort(folderSortFn(sortStrat, dir)).forEach((item) => { - const collapsed = !openNodes2.includes(item.path); - i4 = i4 + 1; - const newItems = []; - if (vaultItems2[item.path] && !collapsed) { - newItems.push( - ...flattenTree(item.path, vaultItems2, openNodes2, depth2 + 1, i4, item.folderSort) - ); - } - const node = vaulItemToTreeNode( - item, - space, - path, - depth2, - i4, - collapsed, - sortStrategy == "rank", - newItems.length - ); - if (node.file) - newItems.splice(0, 0, node); - items.push(...newItems); - }); - return items; - }; - return flattenTree(root, vaultItems, openNodes, depth, 0, ""); -}; -var vaultItemForPath = (plugin, path) => { +// src/utils/spaces/space.ts +var pathIsSpace = (plugin, path) => { if (!path) - return null; - return plugin.index.vaultDBCache.find((f4) => f4.path == path); -}; -var saveFileSticker = async (plugin, path, sticker) => { - if (plugin.settings.spacesEnabled) { - const newVaultDB = plugin.index.vaultDBCache.map((f4) => f4.path == path ? { ...f4, sticker } : f4); - await plugin.index.saveSpacesDatabaseToDisk({ vault: { ...vaultSchema, rows: newVaultDB } }); - } - saveFrontmatterValue( - plugin, - path, - plugin.settings.fmKeySticker, - sticker, - "text", - true - ); - plugin.index.reloadFile(getAbstractFileAtPath(app, path)).then((f4) => plugin.index.broadcast("space")); -}; -var saveFolderSort = async (plugin, path, sort) => { - if (plugin.settings.spacesEnabled) { - const newVaultDB = plugin.index.vaultDBCache.map((f4) => f4.path == path ? { ...f4, folder: sort } : f4); - await plugin.index.saveSpacesDatabaseToDisk({ vault: { ...vaultSchema, rows: newVaultDB } }); - plugin.index.reloadFile(getAbstractFileAtPath(app, path)).then((f4) => plugin.index.broadcast("vault")); - } -}; -var saveFileColor = async (plugin, path, color) => { - if (plugin.settings.spacesEnabled) { - const newVaultDB = plugin.index.vaultDBCache.map((f4) => f4.path == path ? { ...f4, color } : f4); - await plugin.index.saveSpacesDatabaseToDisk({ vault: { ...vaultSchema, rows: newVaultDB } }); - } - saveFrontmatterValue( - plugin, - path, - plugin.settings.fmKeyColor, - color, - "text", - true - ); - plugin.index.reloadFile(getAbstractFileAtPath(app, path)).then((f4) => plugin.index.broadcast("space")); -}; -var saveSpaceSticker = async (plugin, name, sticker) => { - const newSpaceDB = plugin.index.spacesDBCache.map((f4) => f4.name == name ? { ...f4, sticker } : f4); - await plugin.index.saveSpacesDatabaseToDisk({ spaces: { ...spaceSchema, rows: newSpaceDB } }); - plugin.index.reloadSpace(name); -}; -var updateFileRank = async (plugin, item, rank) => { - let fixedRank = rank; - if (parseInt(item.rank) > rank) - fixedRank = rank + 1; - const newItems = insert( - plugin.index.vaultDBCache.filter((f4) => f4.parent == item.parent).filter((f4) => f4.path != item.path).map((f4, i4) => f4.rank ? f4 : { ...f4, rank: i4.toString() }).sort( - (a5, b4) => a5.rank.localeCompare(b4.rank, void 0, { numeric: true }) - ), - fixedRank, - item - ).map((f4, index) => ({ path: f4.path, rank: index.toString() })); - const newVaultDB = plugin.index.vaultDBCache.map((f4) => { - const newItem = newItems.find((g4) => g4.path == f4.path); - if (newItem) { - return { ...f4, ...newItem }; - } - return f4; - }); - await plugin.index.saveSpacesDatabaseToDisk({ vault: { ...vaultSchema, rows: newVaultDB } }); - const promises = newItems.map((f4) => plugin.index.reloadFile(getAbstractFileAtPath(app, f4.path))); - await Promise.all(promises); - plugin.index.broadcast("space"); -}; -var moveAFileToNewParentAtIndex = async (plugin, item, newParent, index) => { - var _a2; - const currFile = getAbstractFileAtPath(app, item.path); - const newPath = newParent == "/" ? currFile.name : newParent + "/" + currFile.name; - const newItem = { - ...fileMetadataToVaultItem(item), - path: newPath, - parent: newParent, - rank: index.toString() - }; - if (getAbstractFileAtPath(app, newPath)) { - new import_obsidian43.Notice(i18n_default.notice.fileExists); - return; - } - const allRows = plugin.index.vaultDBCache.filter((f4) => f4.parent == newParent); - const rows = insert( - (_a2 = allRows.sort( - (a5, b4) => { - var _a3, _b2; - return ((_a3 = a5.rank) != null ? _a3 : "").localeCompare((_b2 = b4.rank) != null ? _b2 : "", void 0, { numeric: true }); - } - )) != null ? _a2 : [], - index, - newItem - ).map((f4, i4) => ({ ...f4, rank: i4.toString() })); - const newVaultTable = [...plugin.index.vaultDBCache, newItem].filter((f4) => f4.path != item.path).map((f4) => { - const newItem2 = rows.find((g4) => g4.path == f4.path); - if (newItem2) { - return { ...f4, ...newItem2 }; - } - return f4; - }); - await plugin.index.saveSpacesDatabaseToDisk({ vault: { ...vaultSchema, rows: newVaultTable } }); - const afile = getAbstractFileAtPath(app, item.path); - await moveFile(getAbstractFileAtPath(app, newParent), afile); - const promises = rows.map((f4) => plugin.index.reloadFile(getAbstractFileAtPath(app, f4.path))); - await Promise.all(promises); - plugin.index.broadcast("space"); -}; -var insertSpaceAtIndex = async (plugin, newSpace, rank) => { - const spaces2 = plugin.index.allSpaces(); - const spaceExists = spaces2.find((f4) => f4.name == newSpace.name); - let fixedRank = rank; - let newSpaceRows = plugin.index.spacesDBCache; - if (spaceExists) { - const newRow = { ...serializeSpace(spaceExists), ...serializeSpace(newSpace) }; - newSpaceRows = newSpaceRows.map((f4) => f4.name == newRow.name ? newRow : f4); - if (parseInt(spaceExists.rank) < rank) - fixedRank = rank - 1; - } else { - const newRow = serializeSpace(newSpace); - newSpaceRows.push(newRow); - } - const newSpaces = insert( - spaces2.filter((f4) => f4.name != newSpace.name), - fixedRank, - newSpace - ).map((f4, index) => ({ name: f4.name, rank: index.toString() })); - newSpaceRows = newSpaceRows.map((f4) => { - const foundSpace = newSpaces.find((s5) => s5.name == f4.name); - if (foundSpace) { - return { - ...f4, - rank: foundSpace.rank - }; - } - return f4; - }); - await plugin.index.saveSpacesDatabaseToDisk({ spaces: { ...spaceSchema, rows: newSpaceRows } }); - plugin.index.initializeSpaces().then((f4) => plugin.index.initalizeFiles()); -}; -var insertSpaceItemAtIndex = async (plugin, spaceName, path, rank) => { - var _a2; - const space = (_a2 = plugin.index.spacesIndex.get(spaceName)) == null ? void 0 : _a2.space; - if (!space) - return; - const newSpace = { - space: space.name, - path, - rank: rank.toString() - }; - const spaceExists = plugin.index.spacesItemsDBCache.filter((f4) => f4.space == space.name); - const pathExists = spaceExists.find((f4) => f4.path == path); - let fixedRank = rank; - let newSpaceItemsRows = plugin.index.spacesItemsDBCache; - if (!pathExists) { - newSpaceItemsRows.push(newSpace); - fixedRank = rank + 1; - } else { - if (parseInt(pathExists.rank) > rank) - fixedRank = rank + 1; - } - const newSpaceItems = insert( - spaceExists.filter((f4) => f4.path != path), - fixedRank, - newSpace - ).map((f4, index) => ({ - space: f4.space, - path: f4.path, - rank: index.toString() - })); - newSpaceItemsRows = newSpaceItemsRows.map((f4) => { - if (f4.space != space.name) - return f4; - const foundItem = newSpaceItems.find((s5) => s5.path == f4.path); - if (foundItem) { - return { - ...f4, - ...foundItem - }; - } - return f4; - }); - await plugin.index.saveSpacesDatabaseToDisk({ spaceItems: { ...spaceItemsSchema, rows: newSpaceItemsRows } }); - await plugin.index.reloadSpace(space.name); - const promises = newSpaceItemsRows.map((f4) => plugin.index.reloadFile(getAbstractFileAtPath(app, f4.path))); - await Promise.all(promises); - plugin.index.broadcast("vault"); + return false; + const uri = uriByString(plugin, path); + if (uri.type == "space" || uri.type == "tag" || uri.type == "folder" || uri.type == "vault") + return true; + return false; }; -var saveSpace = async (plugin, space, newSpace) => { - const newSpaceRows = plugin.index.spacesDBCache.map((f4) => f4.name == space ? serializeSpace(newSpace) : f4); - const newSpaceItemsRows = plugin.index.spacesItemsDBCache.map((f4) => f4.space == space ? { ...f4, space: newSpace.name } : f4); - await plugin.index.saveSpacesDatabaseToDisk({ spaces: { ...spaceSchema, rows: newSpaceRows }, spaceItems: { ...spaceItemsSchema, rows: newSpaceItemsRows } }); - plugin.settings.expandedSpaces = plugin.settings.expandedSpaces.map( - (f4) => f4 == space ? newSpace.name : f4 - ); - plugin.saveSettings(); - if (space != newSpace.name) { - renameSpaceContextFile(plugin, space, newSpace.name); - plugin.index.renameSpace(space, newSpace.name); +var spaceFolderPathFromSpace = (path, plugin) => { + if (plugin.settings.spacesMDBInHidden) { + if (path == "/") + return ".space/"; + return path + ".space/"; } - plugin.index.reloadSpace(space); - plugin.index.initalizeFiles(); -}; -var removeSpace = async (plugin, space) => { - const newSpaceRows = plugin.index.spacesDBCache.filter((f4) => f4.name != space); - const newSpaceItemsRows = plugin.index.spacesItemsDBCache.filter((f4) => f4.space != space); - await plugin.index.saveSpacesDatabaseToDisk({ spaces: { ...spaceSchema, rows: newSpaceRows }, spaceItems: { ...spaceItemsSchema, rows: newSpaceItemsRows } }); - deleteSpaceContext(plugin, space); - plugin.index.deleteSpace(space); -}; -var updateSpaceSort = (plugin, spaceName, sort) => { - var _a2; - const space = (_a2 = plugin.index.spacesIndex.get(spaceName)) == null ? void 0 : _a2.space; - if (space) - saveSpace(plugin, spaceName, { - ...space, - sort: JSON.stringify(sort) - }); + return path; }; -var toggleSpacePin = (plugin, spaceName, type) => { +var folderForSpace = (space, plugin) => getFolderPathFromString(plugin, plugin.settings.spacesFolder) + "/" + space; +var spacesFromFileCache = (cache, plugin) => { var _a2; - const space = (_a2 = plugin.index.spacesIndex.get(spaceName)) == null ? void 0 : _a2.space; - if (space) - saveSpace(plugin, spaceName, { - ...space, - pinned: type - }); -}; -var addPathsToSpace = async (plugin, space, paths) => { - const newSpaceItemsRows = [...plugin.index.spacesItemsDBCache, ...paths.map((p3) => ({ space, path: p3 }))]; - await plugin.index.saveSpacesDatabaseToDisk({ spaceItems: { ...spaceItemsSchema, rows: newSpaceItemsRows } }); - await plugin.index.reloadSpace(space); - const promises = paths.map((f4) => plugin.index.reloadFile(getAbstractFileAtPath(app, f4))); - await Promise.all(promises); - plugin.index.broadcast("vault"); -}; -var removePathsFromSpace = async (plugin, space, paths) => { - const newSpaceItemsRows = plugin.index.spacesItemsDBCache.filter((f4) => !(f4.space == space && paths.includes(f4.path))); - await plugin.index.saveSpacesDatabaseToDisk({ spaceItems: { ...spaceItemsSchema, rows: newSpaceItemsRows } }); - await plugin.index.reloadSpace(space); - const promises = paths.map((f4) => plugin.index.reloadFile(getAbstractFileAtPath(app, f4))); - await Promise.all(promises); - plugin.index.broadcast("vault"); -}; -var retrieveSpaceItems = (plugin, spaces2) => { - const retrievedSpaces = {}; - spaces2.forEach((space) => { - const rows = plugin.index.spacesItemsDBCache.filter((f4) => f4.space == space.name); - retrievedSpaces[space.name] = rows.sort( - (a5, b4) => { - var _a2, _b2; - return ((_a2 = a5.rank) != null ? _a2 : "").localeCompare((_b2 = b4.rank) != null ? _b2 : "", void 0, { numeric: true }); - } - ); - }); - return retrievedSpaces; -}; -var retrieveFolders = async (plugin, paths) => { - const retrievedFolders = {}; - paths.forEach((folder) => { - const files = []; - for (const k5 of plugin.index.filesIndex.values()) { - if (k5.parent == folder) - files.push(k5); - } - retrievedFolders[folder] = files.filter( - excludeVaultItemPredicate(plugin.settings) - ).map((f4) => plugin.index.filesIndex.get(f4.path)).filter((f4) => f4); - }); - return retrievedFolders; -}; -var retrieveAllRecursiveChildren = (vaultDB, settings, folder) => { - return vaultDB.filter((f4) => f4["parent"].startsWith(folder)).filter( - excludeVaultItemPredicate(settings) - ); -}; -var retrieveAllFiles = (vaultDB, settings) => { - return vaultDB.filter( - excludeVaultItemPredicate(settings) - ); -}; -var initiateDB = (db) => { - replaceDB(db, { - vault: vaultSchema, - spaces: spaceSchema, - spaceItems: spaceItemsSchema - }); -}; -var indexCurrentFileTree = (plugin, vaultDB, spaceItemsDB) => { - const treeItems = getAllAbstractFilesInVault(plugin, app).map((file) => { - var _a2; - return { - path: file.path, - parent: (_a2 = file.parent) == null ? void 0 : _a2.path, - created: file instanceof import_obsidian43.TFile ? file.stat.ctime.toString() : void 0, - folder: file instanceof import_obsidian43.TFolder ? "true" : "false" - }; - }); - const currentPaths = vaultDB; - const deleteRows = currentPaths.filter( - (item) => !treeItems.some((i4) => i4.path == item.path) - ); - const fixRows = currentPaths.filter( - (item) => treeItems.some((i4) => i4.path == item.path && i4.parent != item.parent) - ).map((item) => ({ - ...item, - ...treeItems.find((i4) => i4.path == item.path) - })); - const newRows = treeItems.filter( - (item) => !currentPaths.some((i4) => i4.path == item.path) - ); - const newVaultRows = [...vaultDB.map((f4) => { - const newItem = fixRows.find((g4) => g4.path == f4.path); - if (newItem) { - return { ...f4, ...newItem }; - } - return f4; - }).filter((f4) => !deleteRows.some((g4) => g4.path == f4.path)), ...newRows]; - const newSpaceItemsRows = spaceItemsDB.filter((f4) => !deleteRows.some((g4) => g4.path == f4.path)); - return { - vault: { - ...vaultSchema, - rows: newVaultRows - }, - spaceItems: { - ...spaceItemsSchema, - rows: newSpaceItemsRows - } - }; -}; -var newFolderInSpace = (plugin, space, activeFile2) => { - const vaultChangeModal = new VaultChangeModal( - plugin, - (space == null ? void 0 : space.def.folder.length) > 0 ? getFolderFromPath(app, space.def.folder) : defaultNoteFolder(plugin, activeFile2), - "create folder", - space.name - ); - vaultChangeModal.open(); -}; -var newFileInSpace = async (plugin, space, activeFile2, canvas) => { - let newFile; - if (canvas) { - newFile = await createNewCanvasFile( - plugin, - (space == null ? void 0 : space.def.folder.length) > 0 ? getFolderFromPath(app, space.def.folder) : defaultNoteFolder(plugin, activeFile2), - "" - ); - } else { - newFile = await createNewMarkdownFile( - plugin, - (space == null ? void 0 : space.def.folder.length) > 0 ? getFolderFromPath(app, space.def.folder) : defaultNoteFolder(plugin, activeFile2), - "" - ); - } - if (space.name != "/") - addPathsToSpace(plugin, space.name, [newFile.path]); + return ((_a2 = cache == null ? void 0 : cache.spaces) != null ? _a2 : []).map((f4) => plugin.index.spacesIndex.get(f4)).filter((f4) => f4).map((f4) => f4.space); }; // src/utils/contexts/contexts.ts -var renameContext = (plugin, context, newName) => { - var _a2; - if (context.type == "tag") { - renameTag(plugin, tagPathToTag(context.contextPath), newName); - } else if (context.type == "space") { - const space = (_a2 = plugin.index.spacesIndex.get(spaceNameFromContextPath(context.contextPath))) == null ? void 0 : _a2.space; - if (space) { - saveSpace(plugin, space.name, { ...space, name: newName }); - } - } else if (context.type == "folder") { - renameFile(plugin, getAbstractFileAtPath(app, context.contextPath), newName); +var renamePath = async (plugin, path, newName) => { + if (path.type == "tag") { + await renameTag(plugin, path.space, newName); + } else if (path.type == "folder") { + return await renameFile(plugin, getAbstractFileAtPath(plugin, path.path), newName); } }; -var contextEmbedStringFromContext = (context, schema) => { - if (context.type == "folder") { - if (context.contextPath == "/") - return `![![/#^${schema}]]`; - return `![![${context.contextPath}/#^${schema}]]`; +var contextEmbedStringFromContext = (space, schema) => { + if (space.uri.type == "folder") { + return `![![${space.path}/#^${schema}]]`; } - return `![![${context.contextPath}#^${schema}]]`; -}; -var spaceContextFromSpace = (plugin, space, readOnly) => { - return { - type: "space", - sticker: "", - banner: "", - contextPath: space, - isRemote: false, - readOnly, - dbPath: getFolderPathFromString(plugin.settings.tagContextFolder) + "/" + spaceNameFromContextPath(space) + ".mdb" - }; + if (space.uri.type == "vault") { + return `![![/#^${schema}]]`; + } + return `![![${space.path}#^${schema}]]`; }; -var tagContextFromTag = (plugin, tag, readOnly) => { +var spaceFromTag = (plugin, tag, readOnly) => { + const path = tagSpacePathFromTag(tag); + const folderPath = getFolderPathFromString(plugin, plugin.settings.spacesFolder) + "/" + tagToTagPath(tag); return { - type: "tag", - sticker: "", - banner: "", - contextPath: tag, + name: tag, + path, + uri: uriByString(plugin, path), isRemote: false, readOnly, - dbPath: getFolderPathFromString(plugin.settings.tagContextFolder) + "/" + tagToTagPath(tag) + ".mdb" + folderPath, + defPath: `${folderPath}/${encodeSpaceName(tag)}.md`, + framePath: spaceFolderPathFromSpace(folderPath + "/", plugin) + "frames.mdb", + dbPath: spaceFolderPathFromSpace(folderPath + "/", plugin) + plugin.settings.folderContextFile + ".mdb" }; }; -var mdbContextByDBPath = (plugin, dbPath) => { - if (dbPath.match(urlRegex)) { - return remoteContextFromURL(plugin, dbPath); - } - if (dbPath.startsWith(plugin.settings.tagContextFolder)) { - const contextPath = filePathToString(dbPath); - if (contextPath.charAt(0) == "#") - return tagContextFromTag(plugin, tagPathToTag(dbPath)); - return spaceContextFromSpace(plugin, spaceContextPathFromName(contextPath)); - } - return dbPath.endsWith((plugin == null ? void 0 : plugin.settings.folderContextFile) + ".mdb") ? folderContextFromFolder(plugin, getFolderFromPath(app, dbPath).path) : null; -}; var remoteContextFromURL = (plugin, url) => { return { - type: "unknown", - sticker: "", - banner: "", - contextPath: url, + name: url, + path: url, + uri: uriByString(plugin, url), isRemote: true, readOnly: true, - dbPath: url + folderPath: url, + defPath: url, + dbPath: url, + framePath: url }; }; -var mdbContextByPath = (plugin, contextPath) => { +var spaceInfoByPath = (plugin, contextPath) => { if (!contextPath) return; - if (contextPath.match(urlRegex)) { - return remoteContextFromURL(plugin, contextPath); + const path = uriByString(plugin, contextPath); + if (path.type == "url") { + return remoteContextFromURL(plugin, path.fullPath); } - const viewType = pathTypeByString(contextPath); - if (viewType == "space") { - return spaceContextFromSpace(plugin, contextPath); - } else if (viewType == "folder") { - return folderContextFromFolder(plugin, removeTrailingSlashFromFolder(contextPath)); - } else if (viewType == "tag") { - return tagContextFromTag(plugin, contextPath); + if (path.type == "folder") { + return spaceFromFolder(plugin, removeTrailingSlashFromFolder(path.path)); + } else if (path.type == "tag") { + return spaceFromTag(plugin, path.space); + } else if (path.type == "vault") { + return spaceFromFolder(plugin, "/"); } return null; }; -var folderContextFromFolder = (plugin, folder, readOnly) => { +var spaceFromFolder = (plugin, folder, readOnly) => { + if (folder == "/") { + const vaultName = plugin.app.vault.getName(); + return { + name: vaultName, + uri: uriForFolder(folder), + path: folder, + isRemote: false, + readOnly, + folderPath: folder, + defPath: vaultName + ".md", + dbPath: spaceFolderPathFromSpace(folder, plugin) + plugin.settings.folderContextFile + ".mdb", + framePath: spaceFolderPathFromSpace(folder, plugin) + "views.mdb" + }; + } + const folderName = folderPathToString(folder); return { - type: "folder", - sticker: "", - banner: "", - contextPath: folder, + name: folderName, + uri: uriForFolder(folder), + path: folder, isRemote: false, readOnly, - dbPath: (folder == "/" ? "" : folder + "/") + plugin.settings.folderContextFile + ".mdb" + folderPath: folder, + defPath: folder + "/" + folderName + ".md", + dbPath: spaceFolderPathFromSpace(folder + "/", plugin) + plugin.settings.folderContextFile + ".mdb", + framePath: spaceFolderPathFromSpace(folder + "/", plugin) + "views.mdb" }; }; var linkContextRow = (plugin, row, fields) => { @@ -44862,13 +57888,13 @@ var linkContextRow = (plugin, row, fields) => { if (col.type.includes("context")) { const context = col.value; const contextCache = plugin.index.contextsIndex.get(context); - if (contextCache) { + if (contextCache.tables["files"]) { return { ...p3, [c4.name]: linkContextProp( property, row[col.name], - contextCache.rows + contextCache.tables["files"].rows ) }; } @@ -44884,27 +57910,99 @@ var linkContextProp = (propType, rows, contextTableRows) => { return serializeMultiString(uniq(contextRows.map((f4) => f4[propType]).filter((f4) => f4))); }; -// src/utils/contexts/mdtable.ts -var createTable2 = (object, columns) => { - const columnNames = columns.map((f4) => f4.name); - const base = "|"; - let outputString = base + columnNames.join(base) + "|\n"; - columns.forEach((f4) => { - outputString += base + "----"; - }); - outputString += base + "\n"; - object.forEach((row) => { - outputString += columnNames.map((c4) => base + row[c4]).join("") + "|\n"; - }); - return outputString; +// src/components/SpaceView/Editor/FlowEditorHover.tsx +var FlowEditorHover = (props2) => { + var _a2, _b2; + const fields = (_b2 = (_a2 = props2.plugin.index.framesIndex.get(props2.path.path)) == null ? void 0 : _a2.frames[props2.path.ref]) == null ? void 0 : _b2.cols; + const convertTable = () => { + const context = spaceInfoByPath(props2.plugin, props2.path.fullPath); + getMDBTable(props2.plugin, context, props2.path.ref, "context").then( + (mdbTable) => { + const markdown = createTable(mdbTable.rows, mdbTable.cols); + props2.view.dispatch({ + changes: { + from: props2.pos.from - 4, + to: props2.pos.to + 2, + insert: markdown + } + }); + } + ); + }; + const cutTable = () => { + navigator.clipboard.writeText(`![![${props2.path.fullPath}]]`); + props2.view.dispatch({ + changes: { from: props2.pos.from - 4, to: props2.pos.to + 2 } + }); + }; + const deleteTable = () => { + props2.view.dispatch({ + changes: { from: props2.pos.from - 4, to: props2.pos.to + 2 } + }); + }; + const toggleFlow = () => { + props2.view.dispatch({ + changes: { from: props2.pos.from - 4, to: props2.pos.from - 3 } + }); + }; + const openLink = () => { + openFileFlowEditor(props2.path.fullPath, "/"); + }; + const [propsEditor, setPropsEditor] = h2(false); + return /* @__PURE__ */ Cn.createElement(Cn.Fragment, null, /* @__PURE__ */ Cn.createElement("div", { + className: "mk-flowblock-menu" + }, props2.path.type == "file" ? /* @__PURE__ */ Cn.createElement(Cn.Fragment, null, props2.toggle && /* @__PURE__ */ Cn.createElement("div", { + "aria-label": i18n_default.buttons.toggleFlow, + onClick: toggleFlow, + className: `mk-hover-button ${props2.toggleState ? "mk-toggle-on" : ""}`, + dangerouslySetInnerHTML: { + __html: uiIconSet["mk-ui-flow-hover"] + } + }), /* @__PURE__ */ Cn.createElement("div", { + "aria-label": i18n_default.buttons.openLink, + onClick: openLink, + className: "mk-hover-button", + dangerouslySetInnerHTML: { __html: uiIconSet["mk-ui-open-link"] } + })) : props2.path.refType == "frame" ? /* @__PURE__ */ Cn.createElement(Cn.Fragment, null, /* @__PURE__ */ Cn.createElement("div", { + "aria-label": i18n_default.buttons.convertTable, + onClick: () => setPropsEditor((p3) => !p3), + className: "mk-icon-xsmall mk-hover-button", + dangerouslySetInnerHTML: { __html: uiIconSet["mk-ui-sync"] } + }), /* @__PURE__ */ Cn.createElement("div", { + "aria-label": i18n_default.buttons.convertTable, + onClick: () => openFrameEditor(props2.plugin, props2.path.path, props2.path.ref), + className: "mk-icon-xsmall mk-hover-button", + dangerouslySetInnerHTML: { __html: uiIconSet["mk-ui-sync"] } + }), /* @__PURE__ */ Cn.createElement("div", { + "aria-label": i18n_default.buttons.deleteTable, + onClick: deleteTable, + className: "mk-icon-xsmall mk-hover-button", + dangerouslySetInnerHTML: { __html: uiIconSet["mk-ui-close"] } + })) : /* @__PURE__ */ Cn.createElement(Cn.Fragment, null, /* @__PURE__ */ Cn.createElement("div", { + "aria-label": i18n_default.buttons.convertTable, + onClick: convertTable, + className: "mk-icon-xsmall mk-hover-button", + dangerouslySetInnerHTML: { __html: uiIconSet["mk-ui-sync"] } + }), /* @__PURE__ */ Cn.createElement("div", { + "aria-label": i18n_default.buttons.cutTable, + onClick: cutTable, + className: "mk-icon-xsmall mk-hover-button", + dangerouslySetInnerHTML: { __html: uiIconSet["mk-ui-cut"] } + }), /* @__PURE__ */ Cn.createElement("div", { + "aria-label": i18n_default.buttons.deleteTable, + onClick: deleteTable, + className: "mk-icon-xsmall mk-hover-button", + dangerouslySetInnerHTML: { __html: uiIconSet["mk-ui-close"] } + })), " ")); }; // src/cm-extensions/flowEditor/flowEditor.tsx +var import_obsidian49 = require("obsidian"); var toggleFlowEditor = import_state6.Annotation.define(); var cacheFlowEditorHeight = import_state6.Annotation.define(); var preloadFlowEditor = import_state6.EditorState.transactionFilter.of( (tr) => { - let newTrans = []; + const newTrans = []; const value = tr.state.field(flowEditorInfo, false); if (value && !tr.annotation(toggleFlowEditor)) { newTrans.push( @@ -44935,9 +58033,9 @@ var internalLinkToggle = import_view4.ViewPlugin.fromClass( if (!e4.shiftKey) { return; } - let pos = view.posAtDOM(e4.target); - let { from: lineFrom, to: lineTo, text: text2 } = view.state.doc.lineAt(pos); - for (let match2 of text2.matchAll(/(?!\!)\[\[([^\]]+)\]\]/g)) { + const pos = view.posAtDOM(e4.target); + const { from: lineFrom, to: lineTo, text: text2 } = view.state.doc.lineAt(pos); + for (const match2 of text2.matchAll(/(?!!)\[\[([^\]]+)\]\]/g)) { const stateField = view.state.field(flowEditorInfo, false); const info = stateField.find( (f4) => f4.to == lineFrom + match2.index + match2[1].length + 2 && pos >= f4.from && pos <= f4.to @@ -44954,7 +58052,7 @@ var internalLinkToggle = import_view4.ViewPlugin.fromClass( } ); var internalLinkHover = hoverTooltip((view, pos, side) => { - let { from: lineFrom, to: lineTo, text: text2 } = view.state.doc.lineAt(pos); + const { from: lineFrom, to: lineTo } = view.state.doc.lineAt(pos); let hovObject = null; iterateTreeInSelection({ from: lineFrom, to: lineTo }, view.state, { enter: ({ name, from, to }) => { @@ -44967,7 +58065,7 @@ var internalLinkHover = hoverTooltip((view, pos, side) => { end: to, above: true, create(view2) { - let dom = document.createElement("div"); + const dom = document.createElement("div"); dom.toggleClass("mk-flow-hover", true); dom.toggleClass("menu", true); const openHoverDiv = dom.createDiv(); @@ -45002,19 +58100,19 @@ var flowEditorInfo = import_state6.StateField.define({ }, update(value, tr) { var _a2, _b2, _c2, _d2, _e2, _f, _g, _h, _i, _j, _k, _l; - let newValues = []; + const newValues = []; const previous = value; - let usedContainers = []; - let str = tr.newDoc.sliceString(0); + const usedContainers = []; + const str = tr.newDoc.sliceString(0); const reverseExpandedState = (state) => { const news = state != 2 ? 2 : 0; return news; }; - for (let match2 of str.matchAll(/(?:!\[!\[|!!\[\[)([^\]]+)\]\]/g)) { + for (const match2 of str.matchAll(/(?:!\[!\[|!!\[\[)([^\]]+)\]\]/g)) { const link = match2[1]; const existingLinks = previous.filter((f4) => f4.link == link); - const offset = usedContainers.filter((f4) => f4 == link).length; - const existingInfo = existingLinks[offset]; + const offset2 = usedContainers.filter((f4) => f4 == link).length; + const existingInfo = existingLinks[offset2]; const id2 = existingInfo ? existingInfo.id : genId(); usedContainers.push(link); const info = { @@ -45029,12 +58127,12 @@ var flowEditorInfo = import_state6.StateField.define({ }; newValues.push(info); } - for (let match2 of str.matchAll(/\[\[([^\]]+)\]\]/g)) { + for (const match2 of str.matchAll(/\[\[([^\]]+)\]\]/g)) { if (str.charAt(match2.index - 1) != "!") { const link = match2[1]; const existingLinks = previous.filter((f4) => f4.link == link); - const offset = usedContainers.filter((f4) => f4 == link).length; - const existingInfo = existingLinks[offset]; + const offset2 = usedContainers.filter((f4) => f4 == link).length; + const existingInfo = existingLinks[offset2]; const id2 = existingInfo ? existingInfo.id : genId(); usedContainers.push(link); const info = { @@ -45051,8 +58149,8 @@ var flowEditorInfo = import_state6.StateField.define({ } else if (str.charAt(match2.index - 2) != "!") { const link = match2[1]; const existingLinks = previous.filter((f4) => f4.link == link); - const offset = usedContainers.filter((f4) => f4 == link).length; - const existingInfo = existingLinks[offset]; + const offset2 = usedContainers.filter((f4) => f4 == link).length; + const existingInfo = existingLinks[offset2]; const id2 = existingInfo ? existingInfo.id : genId(); usedContainers.push(link); const info = { @@ -45073,9 +58171,9 @@ var flowEditorInfo = import_state6.StateField.define({ } }); var flowEditorRangeset = (state, plugin) => { - let builder = new import_state6.RangeSetBuilder(); + const builder = new import_state6.RangeSetBuilder(); const infoFields = state.field(flowEditorInfo, false); - for (let info of infoFields) { + for (const info of infoFields) { const { from, to, embed: embedType, expandedState } = info; const lineFix = from - 3 == state.doc.lineAt(from).from && to + 2 == state.doc.lineAt(from).to; if (expandedState == 2) { @@ -45135,58 +58233,24 @@ var FlowEditorSelector = class extends import_view4.WidgetType { this.plugin = plugin; } eq(other) { - return false; + return other.info.id === this.info.id; } toDOM(view) { const div = document.createElement("div"); div.toggleClass("mk-floweditor-selector", true); const reactEl = createRoot(div); - if (this.info.link && view.state.field(import_obsidian44.editorInfoField, false)) { - const infoField = view.state.field(import_obsidian44.editorInfoField, false); + if (this.info.link && view.state.field(import_obsidian49.editorInfoField, false)) { + const infoField = view.state.field(import_obsidian49.editorInfoField, false); const file = infoField.file; - const path = pathByString(this.info.link, file.path); + const path = uriByString(this.plugin, this.info.link, file.path); reactEl.render( /* @__PURE__ */ Cn.createElement(FlowEditorHover, { + plugin: this.plugin, toggle: true, - path: path.path, - type: path.type, + path, toggleState: true, - convertTable: () => { - const context = mdbContextByPath(this.plugin, path.path); - getMDBTable( - this.plugin, - context, - path.ref.substring(1, path.ref.length) - ).then((mdbTable) => { - const markdown = createTable2(mdbTable.rows, mdbTable.cols); - view.dispatch({ - changes: { - from: this.info.from - 4, - to: this.info.to + 2, - insert: markdown - } - }); - }); - }, - cutTable: () => { - navigator.clipboard.writeText(`![![${this.info.link}]]`); - view.dispatch({ - changes: { from: this.info.from - 4, to: this.info.to + 2 } - }); - }, - deleteTable: () => { - view.dispatch({ - changes: { from: this.info.from - 4, to: this.info.to + 2 } - }); - }, - toggleFlow: () => { - view.dispatch({ - changes: { from: this.info.from - 4, to: this.info.from - 3 } - }); - }, - openLink: () => { - openFileFlowEditor(this.flowInfo.link, "/"); - } + view, + pos: { from: this.info.from, to: this.info.to } }) ); } @@ -45210,9 +58274,9 @@ var flowEditorWidgetDecoration = (info) => import_view4.Decoration.widget({ // src/cm-extensions/flowEditor/flowViewUpdates.ts var import_view5 = require("@codemirror/view"); -var flowViewUpdates = import_view5.EditorView.updateListener.of((v3) => { +var flowViewUpdates = (plugin) => import_view5.EditorView.updateListener.of((v3) => { if (v3.heightChanged) { - app.workspace.iterateRootLeaves((leaf) => { + plugin.app.workspace.iterateRootLeaves((leaf) => { var _a2, _b2; const cm = (_a2 = leaf.view.editor) == null ? void 0 : _a2.cm; if (cm && v3.view.dom == cm.dom && cm.state.field(flowTypeStateField, false)) { @@ -45229,7 +58293,7 @@ var flowViewUpdates = import_view5.EditorView.updateListener.of((v3) => { if (v3.heightChanged) { const flowID = v3.state.field(flowIDStateField, false); if (flowID) { - app.workspace.iterateLeaves((leaf) => { + plugin.app.workspace.iterateLeaves((leaf) => { var _a2; const cm = (_a2 = leaf.view.editor) == null ? void 0 : _a2.cm; if (cm) { @@ -45245,7 +58309,7 @@ var flowViewUpdates = import_view5.EditorView.updateListener.of((v3) => { } } } - }, app.workspace["rootSplit"]); + }, plugin.app.workspace["rootSplit"]); } } }); @@ -45299,7 +58363,7 @@ var newPosAfterFormatting = (pos, moveDirLeft, state) => { const end = moveDirLeft ? pos : line.to; let newPos = start; let lastFormatPos = start; - let exitFormatRange = false; + const exitFormatRange = false; iterateTreeInSelection({ from: start, to: end }, state, { enter: (node) => { if (exitFormatRange) @@ -45355,7 +58419,7 @@ var nodeNameContainsMark = (name, markString) => { var edgeIsMark = (pos, state, mark) => posIsMark(pos, state, mark.mark); var edgeIsMarkFormat = (pos, state, mark) => posIsMark(pos, state, mark.formatting) ? true : mark.altFormatting ? posIsMark(pos, state, mark.altFormatting) : false; var transactionChangesForMark = (range, mark, state) => { - let newTrans = []; + const newTrans = []; if (rangeIsMark(state, mark, range)) { if (edgeIsMarkFormat(range.from, state, mark) && !edgeIsMarkFormat(range.to, state, mark)) { newTrans.push(addMarkAtPos(range.to, mark)); @@ -45380,7 +58444,7 @@ var transactionChangesForMark = (range, mark, state) => { return newTrans; }; var removeAllInternalMarks = (sel, state, mark) => { - let returnTrans = []; + const returnTrans = []; iterateTreeInSelection({ from: sel.from, to: sel.to }, state, { enter: ({ name, from, to }) => { if (nodeNameContainsMark(name, mark.formatting) || (mark.altFormatting ? nodeNameContainsMark(name, mark.altFormatting) : false)) @@ -45404,7 +58468,7 @@ var toggleMarkExtension = import_state7.EditorState.transactionFilter.of( return tr; } const selection = tr.startState.selection.main; - let newTrans = []; + const newTrans = []; if (selection.head == selection.anchor) { if (tr.startState.sliceDoc( selection.head - mark.formatChar.length, @@ -45435,8 +58499,8 @@ var toggleMarkExtension = import_state7.EditorState.transactionFilter.of( } const range = expandRange(selection, tr.startState); newTrans.push(removeAllInternalMarks(range, tr.startState, mark)); - let newFrom = range.from; - let newTo = range.to; + const newFrom = range.from; + const newTo = range.to; newTrans.push(...transactionChangesForMark(range, mark, tr.startState)); return [tr, ...newTrans, { selection: { anchor: newFrom, head: newTo } }]; } @@ -45521,7 +58585,7 @@ var InlineMenuComponent = (props2) => { const makeMenu = (e4) => { var _a2; e4.preventDefault(); - const cm = (_a2 = props2.cm) != null ? _a2 : getActiveCM(); + const cm = (_a2 = props2.cm) != null ? _a2 : getActiveCM(props2.plugin); if (!cm) return; const end = cm.state.selection.main.to; @@ -45541,7 +58605,7 @@ var InlineMenuComponent = (props2) => { const toggleMarkAction = (e4, s5) => { var _a2; e4.preventDefault(); - const cm = (_a2 = props2.cm) != null ? _a2 : getActiveCM(); + const cm = (_a2 = props2.cm) != null ? _a2 : getActiveCM(props2.plugin); if (!cm) return; if (s5.mark) { @@ -45584,7 +58648,7 @@ var InlineMenuComponent = (props2) => { }), /* @__PURE__ */ Cn.createElement("div", { "aria-label": !platformIsMobile() ? i18n_default.commands.image : void 0, onMouseDown: () => { - const view = getActiveMarkdownView(); + const view = getActiveMarkdownView(props2.plugin); props2.plugin.app.commands.commands["editor:attach-file"].editorCallback(view.editor, view); }, className: "mk-mark", @@ -45592,7 +58656,7 @@ var InlineMenuComponent = (props2) => { }), /* @__PURE__ */ Cn.createElement("div", { "aria-label": !platformIsMobile() ? i18n_default.commands.toggleKeyboard : void 0, onMouseDown: () => { - const view = getActiveMarkdownView(); + const view = getActiveMarkdownView(props2.plugin); props2.plugin.app.commands.commands["editor:indent-list"].editorCallback(view.editor, view); }, className: "mk-mark", @@ -45600,7 +58664,7 @@ var InlineMenuComponent = (props2) => { }), /* @__PURE__ */ Cn.createElement("div", { "aria-label": !platformIsMobile() ? i18n_default.commands.toggleKeyboard : void 0, onMouseDown: () => { - const view = getActiveMarkdownView(); + const view = getActiveMarkdownView(props2.plugin); props2.plugin.app.commands.commands["editor:unindent-list"].editorCallback(view.editor, view); }, className: "mk-mark", @@ -45608,7 +58672,7 @@ var InlineMenuComponent = (props2) => { }), /* @__PURE__ */ Cn.createElement("div", { "aria-label": !platformIsMobile() ? i18n_default.commands.toggleKeyboard : void 0, onMouseDown: () => { - const view = getActiveMarkdownView(); + const view = getActiveMarkdownView(props2.plugin); props2.plugin.app.commands.commands["editor:toggle-keyboard"].editorCallback(view.editor, view); }, className: "mk-mark", @@ -45627,7 +58691,7 @@ var InlineMenuComponent = (props2) => { var _a2; setMode(1); setColorMode(null); - const cm = (_a2 = props2.cm) != null ? _a2 : getActiveCM(); + const cm = (_a2 = props2.cm) != null ? _a2 : getActiveCM(props2.plugin); if (!cm) return; const selection = cm.state.selection.main; @@ -45654,6 +58718,7 @@ var InlineMenuComponent = (props2) => { dangerouslySetInnerHTML: { __html: uiIconSet["mk-ui-close"] } }) : /* @__PURE__ */ Cn.createElement(Cn.Fragment, null), resolveStyles().map((s5, i4) => { return /* @__PURE__ */ Cn.createElement(Mark, { + key: i4, i: i4, style: s5, active: props2.activeMarks.find((f4) => f4 == s5.mark) ? true : false, @@ -45707,15 +58772,15 @@ var cursorTooltipField = (plugin) => import_state8.StateField.define({ var getCursorTooltips = (plugin) => (state) => { return state.selection.ranges.filter((range) => !range.empty).map((range) => { const expandedRange = expandRange(range, state); - let line = state.doc.lineAt(range.head); - let activeMarks = oMarks.map((f4) => rangeIsMark(state, f4, expandedRange) ? f4.mark : "").filter((f4) => f4 != ""); + const line = state.doc.lineAt(range.head); + const activeMarks = oMarks.map((f4) => rangeIsMark(state, f4, expandedRange) ? f4.mark : "").filter((f4) => f4 != ""); return { pos: Math.min(range.head, range.anchor), above: true, strictSide: true, arrow: false, create: (view) => { - let dom = document.createElement("div"); + const dom = document.createElement("div"); dom.className = "cm-tooltip-cursor"; const reactElement = createRoot(dom); reactElement.render( @@ -45747,7 +58812,7 @@ var placeholderExtension = (plugin) => import_state9.StateField.define({ return import_view6.Decoration.none; }, update(value, tr) { - let builder = new import_state9.RangeSetBuilder(); + const builder = new import_state9.RangeSetBuilder(); const currentLine = tr.state.doc.lineAt(tr.state.selection.main.head); if ((currentLine == null ? void 0 : currentLine.length) == 0) builder.add(currentLine.from, currentLine.from, placeholderLine(plugin)); @@ -45759,9 +58824,9 @@ var placeholderExtension = (plugin) => import_state9.StateField.define({ // src/cm-extensions/inlineContext/inlineContext.tsx var import_state10 = require("@codemirror/state"); -var import_obsidian45 = require("obsidian"); +var import_obsidian50 = require("obsidian"); var frontmatterHider = (plugin) => import_state10.EditorState.transactionFilter.of((tr) => { - let newTrans = []; + const newTrans = []; const isFM = (typeString) => { if (typeString.contains("hmd-frontmatter")) { return true; @@ -45769,7 +58834,7 @@ var frontmatterHider = (plugin) => import_state10.EditorState.transactionFilter. return false; }; let fmStart = 1; - let fmEnd = tr.state.doc.lines; + const fmEnd = tr.state.doc.lines; iterateTreeInDocument(tr.state, { enter: ({ type, from, to }) => { if (isFM(type.name)) { @@ -45777,7 +58842,7 @@ var frontmatterHider = (plugin) => import_state10.EditorState.transactionFilter. } } }); - const livePreview = tr.state.field(import_obsidian45.editorLivePreviewField); + const livePreview = tr.state.field(import_obsidian50.editorLivePreviewField, false); if (fmStart > 1 && fmStart <= tr.state.doc.lines && plugin.settings.hideFrontmatter && livePreview) { newTrans.push({ annotations: [contentRange.of([fmStart, fmEnd])] @@ -45840,7 +58905,7 @@ var cmExtensions = (plugin, mobile) => { flowEditorField(plugin), flowEditorInfo, flowIDStateField, - flowViewUpdates + flowViewUpdates(plugin) ); if (plugin.settings.internalLinkClickFlow) { extensions.push(internalLinkToggle); @@ -45852,64 +58917,64 @@ var cmExtensions = (plugin, mobile) => { return extensions; }; -// src/components/MakeMenu/MakeMenu.tsx -var import_obsidian47 = require("obsidian"); +// src/components/SpaceView/Editor/MakeMenu/MakeMenu.tsx +var import_obsidian52 = require("obsidian"); -// src/components/MakeMenu/commands/default.ts +// src/components/SpaceView/Editor/MakeMenu/commands/default.ts var default_default2 = [ { label: "todo", value: "- [ ] ", - icon: "mk-make-todo" + icon: "ui//mk-make-todo" }, { label: "list", value: `- `, - icon: "mk-make-list" + icon: "ui//mk-make-list" }, { label: "ordered-list", value: `1. `, - icon: "mk-make-ordered" + icon: "ui//mk-make-ordered" }, { label: "h1", value: "# ", - icon: "mk-make-h1" + icon: "ui//mk-make-h1" }, { label: "h2", value: "## ", - icon: "mk-make-h2" + icon: "ui//mk-make-h2" }, { label: "h3", value: "### ", - icon: "mk-make-h3" + icon: "ui//mk-make-h3" }, { label: "quote", value: "> ", - icon: "mk-make-quote" + icon: "ui//mk-make-quote" }, { label: "divider", value: ` --- `, - icon: "mk-make-hr" + icon: "ui//mk-make-hr" }, { label: "link", value: "", offset: [-1, 1], - icon: "mk-make-link" + icon: "ui//mk-make-link" }, { label: "image", value: "![](Paste Link)", offset: [-1, 4], - icon: "mk-make-image" + icon: "ui//mk-make-image" }, { label: "codeblock", @@ -45918,47 +58983,58 @@ var default_default2 = [ Type/Paste Your Code \`\`\``, offset: [-4, 5], - icon: "mk-make-codeblock" + icon: "ui//mk-make-codeblock" }, { label: "callout", value: `> [!NOTE] > Content`, offset: [-7, 12], - icon: "mk-make-callout" + icon: "ui//mk-make-callout" }, { label: "note", value: "[[Note Name]]", offset: [-2, 2], - icon: "mk-make-note" + icon: "ui//mk-make-note" }, { label: "table", value: "table", - icon: "mk-make-table" + icon: "ui//mk-make-table" }, { label: "flow", value: `!![[Note Name]]`, offset: [-2, 4], - icon: "mk-make-flow" + icon: "ui//mk-make-flow" }, { label: "tag", value: "#tag", offset: [0, 1], - icon: "mk-make-tag" + icon: "ui//mk-make-tag" } ]; -// src/components/MakeMenu/commands/index.ts +// src/components/SpaceView/Editor/MakeMenu/commands/index.ts function resolveCommands(plugin) { - return default_default2; + const allFrames = plugin.settings.quickFrames.flatMap((f4) => { + var _a2; + return (_a2 = plugin.index.framesIndex.get(f4)) == null ? void 0 : _a2.schemas.map((g4) => ({ ...g4, path: f4 })); + }).map((f4) => { + var _a2; + return { + label: f4.name, + value: `![![${f4.path}#*${f4.id}]]`, + icon: (_a2 = safelyParseJSON(f4.def)) == null ? void 0 : _a2.icon + }; + }); + return [...default_default2]; } -// src/components/MakeMenu/MakeMenu.tsx -var MakeMenu = class extends import_obsidian47.EditorSuggest { +// src/components/SpaceView/Editor/MakeMenu/MakeMenu.tsx +var MakeMenu = class extends import_obsidian52.EditorSuggest { constructor(app2, plugin) { super(app2); this.inCmd = false; @@ -45999,24 +59075,25 @@ var MakeMenu = class extends import_obsidian47.EditorSuggest { return suggestions.length > 0 ? suggestions : [{ label: i18n_default.commandsSuggest.noResult, value: "", icon: "" }]; } renderSuggestion(value, el) { + var _a2; if (value.value == "") { el.setText(i18n_default.commandsSuggest.noResult); return; } const div = el.createDiv("mk-slash-item"); const icon = div.createDiv("mk-slash-icon"); - icon.innerHTML = uiIconSet[value.icon]; + icon.innerHTML = stickerFromString(value.icon, this.plugin); const title = div.createDiv(); - title.setText(i18n_default.commands[value.label]); + title.setText((_a2 = i18n_default.commands[value.label]) != null ? _a2 : value.label); } selectSuggestion(cmd, _evt) { if (cmd.label === i18n_default.commandsSuggest.noResult) return; if (cmd.value == "table") { - this.plugin.createInlineTable(this.file.parent.path).then((f4) => { + createInlineTable(this.plugin, this.file.parent.path).then((f4) => { this.context.editor.replaceRange( contextEmbedStringFromContext( - folderContextFromFolder(this.plugin, this.file.parent.path), + spaceFromFolder(this.plugin, this.file.parent.path), f4 ), { ...this.context.start, ch: this.cmdStartCh }, @@ -46050,9 +59127,9 @@ var MakeMenu = class extends import_obsidian47.EditorSuggest { } }; -// src/components/StickerMenu/StickerMenu.tsx -var import_obsidian48 = require("obsidian"); -var StickerMenu = class extends import_obsidian48.EditorSuggest { +// src/components/SpaceView/Editor/StickerMenu/StickerMenu.tsx +var import_obsidian53 = require("obsidian"); +var StickerMenu = class extends import_obsidian53.EditorSuggest { constructor(app2, plugin) { super(app2); this.inCmd = false; @@ -46122,10 +59199,10 @@ var StickerMenu = class extends import_obsidian48.EditorSuggest { }; // src/main.ts -var import_obsidian65 = require("obsidian"); +var import_obsidian67 = require("obsidian"); // src/utils/flow/markdownPost.tsx -var getCMFromElement = (el) => { +var getCMFromElement = (el, plugin) => { let dom = el; while (!dom.hasClass("cm-editor") && dom.parentElement) { dom = dom.parentElement; @@ -46134,19 +59211,19 @@ var getCMFromElement = (el) => { return; } let rcm; - app.workspace.iterateLeaves((leaf) => { + plugin.app.workspace.iterateLeaves((leaf) => { var _a2; const cm = (_a2 = leaf.view.editor) == null ? void 0 : _a2.cm; if (cm && dom == cm.dom) { rcm = cm; return true; } - }, app.workspace["rootSplit"]); + }, plugin.app.workspace["rootSplit"]); return rcm; }; var replaceAllTables = (plugin, el, ctx) => { el.querySelectorAll("p").forEach((element) => { - for (let match2 of element.textContent.matchAll( + for (const match2 of element.textContent.matchAll( /(?:!\[!\[|!!\[\[)([^\]]+)\]\]/g )) { const link = match2[1]; @@ -46193,63 +59270,24 @@ var replaceMarkdownForReadingMode = (el, callback) => { } }); }; -var replaceAllEmbed = (el, ctx) => { +var replaceAllEmbed = (el, ctx, plugin) => { replaceMarkdownForEmbeds(el, (dom) => { - var nodes2 = dom.querySelectorAll(".markdown-embed-link"); - for (var i4 = 0; i4 < nodes2.length; i4++) { - if (nodes2[i4].parentNode === dom) { - dom.removeChild(nodes2[i4]); + const nodes = dom.querySelectorAll(".markdown-embed-link"); + for (let i4 = 0; i4 < nodes.length; i4++) { + if (nodes[i4].parentNode === dom) { + dom.removeChild(nodes[i4]); const div = dom.createDiv("mk-floweditor-selector"); const reactEl = createRoot(div); + const cm = getCMFromElement(dom, plugin); + const pos = cm == null ? void 0 : cm.posAtDOM(dom); reactEl.render( /* @__PURE__ */ Cn.createElement(FlowEditorHover, { toggle: true, - type: "file", - path: ctx.sourcePath, + path: uriByString(plugin, ctx.sourcePath), toggleState: false, - toggleFlow: (e4) => { - const cm = getCMFromElement(dom); - const pos = cm == null ? void 0 : cm.posAtDOM(dom); - if (!cm) - return; - iterateTreeInSelection({ from: pos - 3, to: pos + 4 }, cm.state, { - enter: (node) => { - if (node.name.contains("hmd-internal-link")) { - if (cm.state.sliceDoc(node.from - 4, node.from - 3) != "!") { - if (cm.state.sliceDoc(node.to + 2, node.to + 3) != cm.state.lineBreak) { - cm.dispatch({ - changes: [ - { - from: node.from - 3, - to: node.from - 3, - insert: "!" - }, - { - from: node.to + 2, - to: node.to + 2, - insert: cm.state.lineBreak - } - ] - }); - } else { - cm.dispatch({ - changes: { - from: node.from - 3, - to: node.from - 3, - insert: "!" - } - }); - } - } - } - } - }); - e4.stopPropagation(); - }, - openLink: (e4) => { - e4.stopPropagation(); - openFileFlowEditor(ctx.sourcePath, "/"); - } + view: cm, + pos: { from: pos - 3, to: pos + 4 }, + plugin }) ); } @@ -46257,5111 +59295,3012 @@ var replaceAllEmbed = (el, ctx) => { }); }; -// src/components/Spaces/FileTreeView.tsx -var import_obsidian55 = require("obsidian"); +// src/components/Navigator/FileTreeView.tsx +var import_obsidian56 = require("obsidian"); -// node_modules/recoil/es/recoil.js -function isPromise(p3) { - return !!p3 && typeof p3.then === "function"; -} -var Recoil_isPromise = isPromise; -function nullthrows(x5, message) { - if (x5 != null) { - return x5; - } - throw new Error(message !== null && message !== void 0 ? message : "Got unexpected null or undefined"); -} -var Recoil_nullthrows = nullthrows; -var Canceled = class { -}; -var CANCELED = new Canceled(); -var loadableAccessors = { - valueMaybe() { - return void 0; - }, - valueOrThrow() { - const error = new Error( - `Loadable expected value, but in "${this.state}" state` - ); - throw error; - }, - errorMaybe() { - return void 0; - }, - errorOrThrow() { - const error = new Error( - `Loadable expected error, but in "${this.state}" state` - ); - throw error; - }, - promiseMaybe() { - return void 0; - }, - promiseOrThrow() { - const error = new Error( - `Loadable expected promise, but in "${this.state}" state` - ); - throw error; - }, - is(other) { - return other.state === this.state && other.contents === this.contents; - }, - map(map) { - if (this.state === "hasError") { - return this; - } - if (this.state === "hasValue") { - try { - const next = map(this.contents); - return Recoil_isPromise(next) ? loadableWithPromise(next.then((value) => ({ - __value: value - }))) : loadableWithValue(next); - } catch (e4) { - return Recoil_isPromise(e4) ? loadableWithPromise(e4.next(() => map(this.contents))) : loadableWithError(e4); - } - } - if (this.state === "loading") { - return loadableWithPromise( - this.contents.then((value) => ({ - __value: map(value.__value) - })).catch((e4) => { - if (Recoil_isPromise(e4)) { - return e4.then(() => map(this.contents)); - } - throw e4; - }) - ); - } - const error = new Error("Invalid Loadable state"); - throw error; - } -}; -function loadableWithValue(value) { - return Object.freeze({ - state: "hasValue", - contents: value, - ...loadableAccessors, - getValue() { - return this.contents; - }, - toPromise() { - return Promise.resolve(this.contents); - }, - valueMaybe() { - return this.contents; - }, - valueOrThrow() { - return this.contents; - } - }); -} -function loadableWithError(error) { - return Object.freeze({ - state: "hasError", - contents: error, - ...loadableAccessors, - getValue() { - throw this.contents; - }, - toPromise() { - return Promise.reject(this.contents); - }, - errorMaybe() { - return this.contents; - }, - errorOrThrow() { - return this.contents; - } - }); -} -function loadableWithPromise(promise) { - return Object.freeze({ - state: "loading", - contents: promise, - ...loadableAccessors, - getValue() { - throw this.contents.then(({ - __value - }) => __value); - }, - toPromise() { - return this.contents.then(({ - __value - }) => __value); - }, - promiseMaybe() { - return this.contents.then(({ - __value - }) => __value); - }, - promiseOrThrow() { - return this.contents.then(({ - __value - }) => __value); - } - }); -} -function loadableLoading() { - return loadableWithPromise(new Promise(() => { - })); -} -function loadableAll(inputs) { - return inputs.every((i4) => i4.state === "hasValue") ? loadableWithValue(inputs.map((i4) => i4.contents)) : inputs.some((i4) => i4.state === "hasError") ? loadableWithError(Recoil_nullthrows(inputs.find((i4) => i4.state === "hasError"), "Invalid loadable passed to loadableAll").contents) : loadableWithPromise(Promise.all(inputs.map((i4) => i4.contents)).then((value) => ({ - __value: value - }))); -} -var Recoil_Loadable = { - loadableWithValue, - loadableWithError, - loadableWithPromise, - loadableLoading, - loadableAll, - Canceled, - CANCELED -}; -var _useMutableSource; -var useMutableSource = (_useMutableSource = Cn.useMutableSource) !== null && _useMutableSource !== void 0 ? _useMutableSource : Cn.unstable_useMutableSource; -function mutableSourceExists() { - return useMutableSource && !(typeof window !== "undefined" && window.$disableRecoilValueMutableSource_TEMP_HACK_DO_NOT_USE); -} -var Recoil_mutableSource = { - mutableSourceExists, - useMutableSource -}; -var { - mutableSourceExists: mutableSourceExists$1 -} = Recoil_mutableSource; -var gks = (/* @__PURE__ */ new Map()).set("recoil_hamt_2020", true).set("recoil_memory_managament_2020", true).set("recoil_suppress_rerender_in_callback", true); -function Recoil_gkx(gk) { - var _gks$get; - if (gk === "recoil_early_rendering_2021" && !mutableSourceExists$1()) { - return false; - } - return (_gks$get = gks.get(gk)) !== null && _gks$get !== void 0 ? _gks$get : false; -} -Recoil_gkx.setPass = (gk) => { - gks.set(gk, true); -}; -Recoil_gkx.setFail = (gk) => { - gks.set(gk, false); -}; -var Recoil_gkx_1 = Recoil_gkx; -function recoverableViolation(message, projectName, { - error -} = {}) { - if (true) { - console.error(message, error); - } - return null; -} -var recoverableViolation_1 = recoverableViolation; -var Recoil_recoverableViolation = recoverableViolation_1; -function setByAddingToSet(set, v3) { - const next = new Set(set); - next.add(v3); - return next; -} -function setByDeletingFromSet(set, v3) { - const next = new Set(set); - next.delete(v3); - return next; -} -function mapBySettingInMap(map, k5, v3) { - const next = new Map(map); - next.set(k5, v3); - return next; -} -function mapByUpdatingInMap(map, k5, updater) { - const next = new Map(map); - next.set(k5, updater(next.get(k5))); - return next; -} -function mapByDeletingFromMap(map, k5) { - const next = new Map(map); - next.delete(k5); - return next; -} -function mapByDeletingMultipleFromMap(map, ks) { - const next = new Map(map); - ks.forEach((k5) => next.delete(k5)); - return next; -} -var Recoil_CopyOnWrite = { - setByAddingToSet, - setByDeletingFromSet, - mapBySettingInMap, - mapByUpdatingInMap, - mapByDeletingFromMap, - mapByDeletingMultipleFromMap -}; -function* filterIterable(iterable, predicate) { - let index = 0; - for (const value of iterable) { - if (predicate(value, index++)) { - yield value; - } - } -} -var Recoil_filterIterable = filterIterable; -function mapIterable(iterable, callback) { - return function* () { - let index = 0; - for (const value of iterable) { - yield callback(value, index++); - } - }(); -} -var Recoil_mapIterable = mapIterable; -function sprintf(format2, ...args) { - let index = 0; - return format2.replace(/%s/g, () => String(args[index++])); -} -var sprintf_1 = sprintf; -function expectationViolation(format2, ...args) { - if (true) { - const message = sprintf_1.call(null, format2, ...args); - const error = new Error(message); - error.name = "Expectation Violation"; - console.error(error); - } -} -var expectationViolation_1 = expectationViolation; -var Recoil_expectationViolation = expectationViolation_1; -function _defineProperty(obj, key2, value) { - if (key2 in obj) { - Object.defineProperty(obj, key2, { - value, - enumerable: true, - configurable: true, - writable: true - }); - } else { - obj[key2] = value; - } - return obj; -} -var AbstractRecoilValue = class { - constructor(newKey) { - _defineProperty(this, "key", void 0); - this.key = newKey; - } -}; -var RecoilState = class extends AbstractRecoilValue { -}; -var RecoilValueReadOnly = class extends AbstractRecoilValue { -}; -function isRecoilValue(x5) { - return x5 instanceof RecoilState || x5 instanceof RecoilValueReadOnly; -} -var Recoil_RecoilValue = { - AbstractRecoilValue, - RecoilState, - RecoilValueReadOnly, - isRecoilValue -}; -var Recoil_RecoilValue_1 = Recoil_RecoilValue.AbstractRecoilValue; -var Recoil_RecoilValue_2 = Recoil_RecoilValue.RecoilState; -var Recoil_RecoilValue_3 = Recoil_RecoilValue.RecoilValueReadOnly; -var Recoil_RecoilValue_4 = Recoil_RecoilValue.isRecoilValue; -var Recoil_RecoilValue$1 = /* @__PURE__ */ Object.freeze({ - __proto__: null, - AbstractRecoilValue: Recoil_RecoilValue_1, - RecoilState: Recoil_RecoilValue_2, - RecoilValueReadOnly: Recoil_RecoilValue_3, - isRecoilValue: Recoil_RecoilValue_4 +// src/context/SidebarContext.tsx +var import_lodash12 = __toESM(require_lodash()); +var NavigatorContext = F({ + dragPaths: [], + setDragPaths: import_lodash12.default.noop, + selectedFiles: [], + setSelectedFiles: import_lodash12.default.noop, + activeFile: null, + setActiveFile: import_lodash12.default.noop, + activeViewSpace: null, + waypoints: [], + setWaypoints: import_lodash12.default.noop, + spaces: [], + setSpaces: import_lodash12.default.noop, + saveActiveSpace: import_lodash12.default.noop, + activeQuery: [], + setActiveQuery: import_lodash12.default.noop, + queryResults: [], + queryMode: false, + setQueryMode: import_lodash12.default.noop, + modifier: null, + setModifier: import_lodash12.default.noop }); -var DefaultValue = class { -}; -var DEFAULT_VALUE = new DefaultValue(); -var RecoilValueNotReady = class extends Error { - constructor(key2) { - super(`Tried to set the value of Recoil selector ${key2} using an updater function, but it is an async selector in a pending or error state; this is not supported.`); - } -}; -var nodes = /* @__PURE__ */ new Map(); -var recoilValues = /* @__PURE__ */ new Map(); -function recoilValuesForKeys(keys) { - return Recoil_mapIterable(keys, (key2) => Recoil_nullthrows(recoilValues.get(key2))); -} -function registerNode(node) { - if (nodes.has(node.key)) { - const message = `Duplicate atom key "${node.key}". This is a FATAL ERROR in - production. But it is safe to ignore this warning if it occurred because of - hot module replacement.`; - console.warn(message); - } - nodes.set(node.key, node); - const recoilValue = node.set == null ? new Recoil_RecoilValue$1.RecoilValueReadOnly(node.key) : new Recoil_RecoilValue$1.RecoilState(node.key); - recoilValues.set(node.key, recoilValue); - return recoilValue; -} -var NodeMissingError = class extends Error { -}; -function getNode(key2) { - const node = nodes.get(key2); - if (node == null) { - throw new NodeMissingError(`Missing definition for RecoilValue: "${key2}""`); - } - return node; -} -function getNodeMaybe(key2) { - return nodes.get(key2); -} -var configDeletionHandlers = /* @__PURE__ */ new Map(); -function deleteNodeConfigIfPossible(key2) { - var _node$shouldDeleteCon; - if (!Recoil_gkx_1("recoil_memory_managament_2020")) { - return; - } - const node = nodes.get(key2); - if (node === null || node === void 0 ? void 0 : (_node$shouldDeleteCon = node.shouldDeleteConfigOnRelease) === null || _node$shouldDeleteCon === void 0 ? void 0 : _node$shouldDeleteCon.call(node)) { - var _getConfigDeletionHan; - nodes.delete(key2); - (_getConfigDeletionHan = getConfigDeletionHandler(key2)) === null || _getConfigDeletionHan === void 0 ? void 0 : _getConfigDeletionHan(); - configDeletionHandlers.delete(key2); - } -} -function setConfigDeletionHandler(key2, fn2) { - if (!Recoil_gkx_1("recoil_memory_managament_2020")) { - return; - } - if (fn2 === void 0) { - configDeletionHandlers.delete(key2); - } else { - configDeletionHandlers.set(key2, fn2); - } -} -function getConfigDeletionHandler(key2) { - return configDeletionHandlers.get(key2); -} -var Recoil_Node = { - nodes, - recoilValues, - registerNode, - getNode, - getNodeMaybe, - deleteNodeConfigIfPossible, - setConfigDeletionHandler, - getConfigDeletionHandler, - recoilValuesForKeys, - NodeMissingError, - DefaultValue, - DEFAULT_VALUE, - RecoilValueNotReady -}; -var RetentionZone = class { -}; -function retentionZone() { - return new RetentionZone(); -} -var Recoil_RetentionZone = { - RetentionZone, - retentionZone -}; -var { - setByAddingToSet: setByAddingToSet$1 -} = Recoil_CopyOnWrite; -var { - getNode: getNode$1, - getNodeMaybe: getNodeMaybe$1, - recoilValuesForKeys: recoilValuesForKeys$1 -} = Recoil_Node; -var { - RetentionZone: RetentionZone$1 -} = Recoil_RetentionZone; -var emptySet = Object.freeze(/* @__PURE__ */ new Set()); -var ReadOnlyRecoilValueError = class extends Error { -}; -function initializeRetentionForNode(store, nodeKey, retainedBy) { - if (!Recoil_gkx_1("recoil_memory_managament_2020")) { - return () => void 0; - } - const { - nodesRetainedByZone: nodesRetainedByZone2 - } = store.getState().retention; - function addToZone(zone) { - let set = nodesRetainedByZone2.get(zone); - if (!set) { - nodesRetainedByZone2.set(zone, set = /* @__PURE__ */ new Set()); - } - set.add(nodeKey); - } - if (retainedBy instanceof RetentionZone$1) { - addToZone(retainedBy); - } else if (Array.isArray(retainedBy)) { - for (const zone of retainedBy) { - addToZone(zone); - } - } - return () => { - if (!Recoil_gkx_1("recoil_memory_managament_2020")) { - return; - } - const nodesRetainedByZone3 = store.getState().retention.nodesRetainedByZone; - function deleteFromZone(zone) { - const set = nodesRetainedByZone3.get(zone); - if (set) { - set.delete(nodeKey); - } - if (set && set.size === 0) { - nodesRetainedByZone3.delete(zone); - } - } - if (retainedBy instanceof RetentionZone$1) { - deleteFromZone(retainedBy); - } else if (Array.isArray(retainedBy)) { - for (const zone of retainedBy) { - deleteFromZone(zone); +var SidebarProvider = (props2) => { + const [modifier, setModifier] = h2(null); + const [dragPaths, setDragPaths] = h2([]); + const [selectedFiles, setSelectedFiles] = h2([]); + const [activeFile, setActiveFile] = h2(null); + const [activeQuery, setActiveQuery] = h2([]); + const [queryMode, setQueryMode] = h2(false); + const [activeViewSpacePath, setActiveViewSpacePath] = h2( + props2.plugin.settings.activeView + ); + const [waypointPaths, setWaypointPaths] = h2( + props2.plugin.settings.waypoints + ); + const [spaces, setSpaces] = h2( + props2.plugin.index.allSpaces() + ); + const waypoints = F2( + () => waypointPaths.map((f4) => spaces.find((g4) => g4.path == f4)).filter((f4) => f4), + [spaces, waypointPaths] + ); + const queryResults = F2(() => { + const paths = []; + props2.plugin.index.filesIndex.forEach((f4) => { + if (fileByDef(activeQuery, f4)) { + paths.push(f4.path); } - } + }); + return paths; + }, [activeQuery]); + const activeViewSpace = F2(() => { + const activeSpace = spaces.find((f4) => f4.path == activeViewSpacePath); + return activeSpace; + }, [activeViewSpacePath, spaces]); + p2(() => { + settingsReloaded(); + loadCachedSpaces(); + }, []); + const settingsReloaded = () => { + setActiveViewSpacePath(props2.plugin.settings.activeView); + setWaypointPaths(props2.plugin.settings.waypoints); }; -} -function initializeNodeIfNewToStore(store, treeState, key2, trigger) { - const storeState = store.getState(); - if (storeState.nodeCleanupFunctions.has(key2)) { - return; - } - const config = getNode$1(key2); - const retentionCleanup = initializeRetentionForNode(store, key2, config.retainedBy); - const nodeCleanup = config.init(store, treeState, trigger); - storeState.nodeCleanupFunctions.set(key2, () => { - nodeCleanup(); - retentionCleanup(); - }); -} -function cleanUpNode(store, key2) { - var _state$nodeCleanupFun; - const state = store.getState(); - (_state$nodeCleanupFun = state.nodeCleanupFunctions.get(key2)) === null || _state$nodeCleanupFun === void 0 ? void 0 : _state$nodeCleanupFun(); - state.nodeCleanupFunctions.delete(key2); -} -function getNodeLoadable(store, state, key2) { - initializeNodeIfNewToStore(store, state, key2, "get"); - return getNode$1(key2).get(store, state); -} -function peekNodeLoadable(store, state, key2) { - return getNode$1(key2).peek(store, state); -} -function setUnvalidatedAtomValue_DEPRECATED(state, key2, newValue) { - var _node$invalidate; - const node = getNodeMaybe$1(key2); - node === null || node === void 0 ? void 0 : (_node$invalidate = node.invalidate) === null || _node$invalidate === void 0 ? void 0 : _node$invalidate.call(node, state); - return { - ...state, - atomValues: state.atomValues.clone().delete(key2), - nonvalidatedAtoms: state.nonvalidatedAtoms.clone().set(key2, newValue), - dirtyAtoms: setByAddingToSet$1(state.dirtyAtoms, key2) - }; -} -function setNodeValue(store, state, key2, newValue) { - const node = getNode$1(key2); - if (node.set == null) { - throw new ReadOnlyRecoilValueError(`Attempt to set read-only RecoilValue: ${key2}`); - } - const set = node.set; - initializeNodeIfNewToStore(store, state, key2, "set"); - return set(store, state, newValue); -} -function peekNodeInfo(store, state, key2) { - var _graph$nodeDeps$get, _storeState$nodeToCom, _storeState$nodeToCom2; - const storeState = store.getState(); - const graph2 = store.getGraph(state.version); - const type = storeState.knownAtoms.has(key2) ? "atom" : storeState.knownSelectors.has(key2) ? "selector" : void 0; - const downstreamNodes = Recoil_filterIterable(getDownstreamNodes(store, state, /* @__PURE__ */ new Set([key2])), (nodeKey) => nodeKey !== key2); - return { - loadable: peekNodeLoadable(store, state, key2), - isActive: storeState.knownAtoms.has(key2) || storeState.knownSelectors.has(key2), - isSet: type === "selector" ? false : state.atomValues.has(key2), - isModified: state.dirtyAtoms.has(key2), - type, - deps: recoilValuesForKeys$1((_graph$nodeDeps$get = graph2.nodeDeps.get(key2)) !== null && _graph$nodeDeps$get !== void 0 ? _graph$nodeDeps$get : []), - subscribers: { - nodes: recoilValuesForKeys$1(downstreamNodes), - components: Recoil_mapIterable((_storeState$nodeToCom = (_storeState$nodeToCom2 = storeState.nodeToComponentSubscriptions.get(key2)) === null || _storeState$nodeToCom2 === void 0 ? void 0 : _storeState$nodeToCom2.values()) !== null && _storeState$nodeToCom !== void 0 ? _storeState$nodeToCom : [], ([name]) => ({ - name - })) - } + const setActiveViewSpaceByPath = (path) => { + setQueryMode(false); + props2.plugin.settings.activeView = path; + props2.plugin.saveSettings(); }; -} -function getDownstreamNodes(store, state, keys) { - const visitedNodes = /* @__PURE__ */ new Set(); - const visitingNodes = Array.from(keys); - const graph2 = store.getGraph(state.version); - for (let key2 = visitingNodes.pop(); key2; key2 = visitingNodes.pop()) { - var _graph$nodeToNodeSubs; - visitedNodes.add(key2); - const subscribedNodes = (_graph$nodeToNodeSubs = graph2.nodeToNodeSubscriptions.get(key2)) !== null && _graph$nodeToNodeSubs !== void 0 ? _graph$nodeToNodeSubs : emptySet; - for (const downstreamNode of subscribedNodes) { - if (!visitedNodes.has(downstreamNode)) { - visitingNodes.push(downstreamNode); - } + const setWaypoints = (paths) => { + props2.plugin.settings.waypoints = paths; + props2.plugin.saveSettings(); + }; + const loadCachedSpaces = T2(() => { + const _spaces = props2.plugin.index.allSpaces(); + setSpaces(_spaces); + }, [activeViewSpace]); + p2(() => { + window.addEventListener(eventTypes.spacesChange, loadCachedSpaces); + window.addEventListener(eventTypes.settingsChanged, settingsReloaded); + return () => { + window.removeEventListener(eventTypes.spacesChange, loadCachedSpaces); + window.addEventListener(eventTypes.settingsChanged, settingsReloaded); + }; + }, [loadCachedSpaces, settingsReloaded]); + return /* @__PURE__ */ Cn.createElement(NavigatorContext.Provider, { + value: { + dragPaths, + setDragPaths, + selectedFiles, + setSelectedFiles, + activeFile, + setActiveFile, + activeViewSpace, + activeQuery, + setActiveQuery, + waypoints, + setWaypoints, + spaces, + setSpaces, + saveActiveSpace: setActiveViewSpaceByPath, + queryResults, + queryMode, + setQueryMode, + modifier, + setModifier } - } - return visitedNodes; -} -var Recoil_FunctionalCore = { - getNodeLoadable, - peekNodeLoadable, - setNodeValue, - cleanUpNode, - setUnvalidatedAtomValue_DEPRECATED, - peekNodeInfo, - getDownstreamNodes, - initializeNodeIfNewToStore + }, props2.children); }; -var { - CANCELED: CANCELED$1 -} = Recoil_Loadable; -var { - getDownstreamNodes: getDownstreamNodes$1, - getNodeLoadable: getNodeLoadable$1, - setNodeValue: setNodeValue$1 -} = Recoil_FunctionalCore; -var { - getNodeMaybe: getNodeMaybe$2 -} = Recoil_Node; -var { - DefaultValue: DefaultValue$1, - RecoilValueNotReady: RecoilValueNotReady$1 -} = Recoil_Node; -var { - AbstractRecoilValue: AbstractRecoilValue$1, - RecoilState: RecoilState$1, - RecoilValueReadOnly: RecoilValueReadOnly$1, - isRecoilValue: isRecoilValue$1 -} = Recoil_RecoilValue$1; -function getRecoilValueAsLoadable(store, { - key: key2 -}, treeState = store.getState().currentTree) { - var _storeState$nextTree, _storeState$previousT; - const storeState = store.getState(); - if (!(treeState.version === storeState.currentTree.version || treeState.version === ((_storeState$nextTree = storeState.nextTree) === null || _storeState$nextTree === void 0 ? void 0 : _storeState$nextTree.version) || treeState.version === ((_storeState$previousT = storeState.previousTree) === null || _storeState$previousT === void 0 ? void 0 : _storeState$previousT.version))) { - Recoil_recoverableViolation("Tried to read from a discarded tree"); - } - const loadable = getNodeLoadable$1(store, treeState, key2); - if (loadable.state === "loading") { - loadable.contents.catch(() => { - return CANCELED$1; - }); - } - return loadable; -} -function applyAtomValueWrites(atomValues, writes) { - const result = atomValues.clone(); - writes.forEach((v3, k5) => { - if (v3.state === "hasValue" && v3.contents instanceof DefaultValue$1) { - result.delete(k5); - } else { - result.set(k5, v3); - } - }); - return result; -} -function valueFromValueOrUpdater(store, state, { - key: key2 -}, valueOrUpdater) { - if (typeof valueOrUpdater === "function") { - const current = getNodeLoadable$1(store, state, key2); - if (current.state === "loading") { - throw new RecoilValueNotReady$1(key2); - } else if (current.state === "hasError") { - throw current.contents; - } - return valueOrUpdater(current.contents); - } else { - return valueOrUpdater; - } -} -function applyAction(store, state, action) { - if (action.type === "set") { - const { - recoilValue, - valueOrUpdater - } = action; - const newValue = valueFromValueOrUpdater(store, state, recoilValue, valueOrUpdater); - const writes = setNodeValue$1(store, state, recoilValue.key, newValue); - for (const [key2, loadable] of writes.entries()) { - writeLoadableToTreeState(state, key2, loadable); - } - } else if (action.type === "setLoadable") { - const { - recoilValue: { - key: key2 - }, - loadable - } = action; - writeLoadableToTreeState(state, key2, loadable); - } else if (action.type === "markModified") { - const { - recoilValue: { - key: key2 - } - } = action; - state.dirtyAtoms.add(key2); - } else if (action.type === "setUnvalidated") { - var _node$invalidate; - const { - recoilValue: { - key: key2 - }, - unvalidatedValue - } = action; - const node = getNodeMaybe$2(key2); - node === null || node === void 0 ? void 0 : (_node$invalidate = node.invalidate) === null || _node$invalidate === void 0 ? void 0 : _node$invalidate.call(node, state); - state.atomValues.delete(key2); - state.nonvalidatedAtoms.set(key2, unvalidatedValue); - state.dirtyAtoms.add(key2); - } else { - Recoil_recoverableViolation(`Unknown action ${action.type}`); + +// src/components/Navigator/SpaceTree/SpaceTreeItem.tsx +var import_classnames6 = __toESM(require_classnames()); + +// node_modules/react-dropzone/dist/es/index.js +var import_prop_types = __toESM(require_prop_types()); + +// node_modules/file-selector/dist/es5/file.js +var COMMON_MIME_TYPES = /* @__PURE__ */ new Map([ + ["aac", "audio/aac"], + ["abw", "application/x-abiword"], + ["arc", "application/x-freearc"], + ["avif", "image/avif"], + ["avi", "video/x-msvideo"], + ["azw", "application/vnd.amazon.ebook"], + ["bin", "application/octet-stream"], + ["bmp", "image/bmp"], + ["bz", "application/x-bzip"], + ["bz2", "application/x-bzip2"], + ["cda", "application/x-cdf"], + ["csh", "application/x-csh"], + ["css", "text/css"], + ["csv", "text/csv"], + ["doc", "application/msword"], + ["docx", "application/vnd.openxmlformats-officedocument.wordprocessingml.document"], + ["eot", "application/vnd.ms-fontobject"], + ["epub", "application/epub+zip"], + ["gz", "application/gzip"], + ["gif", "image/gif"], + ["heic", "image/heic"], + ["heif", "image/heif"], + ["htm", "text/html"], + ["html", "text/html"], + ["ico", "image/vnd.microsoft.icon"], + ["ics", "text/calendar"], + ["jar", "application/java-archive"], + ["jpeg", "image/jpeg"], + ["jpg", "image/jpeg"], + ["js", "text/javascript"], + ["json", "application/json"], + ["jsonld", "application/ld+json"], + ["mid", "audio/midi"], + ["midi", "audio/midi"], + ["mjs", "text/javascript"], + ["mp3", "audio/mpeg"], + ["mp4", "video/mp4"], + ["mpeg", "video/mpeg"], + ["mpkg", "application/vnd.apple.installer+xml"], + ["odp", "application/vnd.oasis.opendocument.presentation"], + ["ods", "application/vnd.oasis.opendocument.spreadsheet"], + ["odt", "application/vnd.oasis.opendocument.text"], + ["oga", "audio/ogg"], + ["ogv", "video/ogg"], + ["ogx", "application/ogg"], + ["opus", "audio/opus"], + ["otf", "font/otf"], + ["png", "image/png"], + ["pdf", "application/pdf"], + ["php", "application/x-httpd-php"], + ["ppt", "application/vnd.ms-powerpoint"], + ["pptx", "application/vnd.openxmlformats-officedocument.presentationml.presentation"], + ["rar", "application/vnd.rar"], + ["rtf", "application/rtf"], + ["sh", "application/x-sh"], + ["svg", "image/svg+xml"], + ["swf", "application/x-shockwave-flash"], + ["tar", "application/x-tar"], + ["tif", "image/tiff"], + ["tiff", "image/tiff"], + ["ts", "video/mp2t"], + ["ttf", "font/ttf"], + ["txt", "text/plain"], + ["vsd", "application/vnd.visio"], + ["wav", "audio/wav"], + ["weba", "audio/webm"], + ["webm", "video/webm"], + ["webp", "image/webp"], + ["woff", "font/woff"], + ["woff2", "font/woff2"], + ["xhtml", "application/xhtml+xml"], + ["xls", "application/vnd.ms-excel"], + ["xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"], + ["xml", "application/xml"], + ["xul", "application/vnd.mozilla.xul+xml"], + ["zip", "application/zip"], + ["7z", "application/x-7z-compressed"], + ["mkv", "video/x-matroska"], + ["mov", "video/quicktime"], + ["msg", "application/vnd.ms-outlook"] +]); +function toFileWithPath(file, path) { + var f4 = withMimeType(file); + if (typeof f4.path !== "string") { + var webkitRelativePath = file.webkitRelativePath; + Object.defineProperty(f4, "path", { + value: typeof path === "string" ? path : typeof webkitRelativePath === "string" && webkitRelativePath.length > 0 ? webkitRelativePath : file.name, + writable: false, + configurable: false, + enumerable: true + }); } -} -function writeLoadableToTreeState(state, key2, loadable) { - if (loadable.state === "hasValue" && loadable.contents instanceof DefaultValue$1) { - state.atomValues.delete(key2); - } else { - state.atomValues.set(key2, loadable); + return f4; +} +function withMimeType(file) { + var name = file.name; + var hasExtension = name && name.lastIndexOf(".") !== -1; + if (hasExtension && !file.type) { + var ext = name.split(".").pop().toLowerCase(); + var type = COMMON_MIME_TYPES.get(ext); + if (type) { + Object.defineProperty(file, "type", { + value: type, + writable: false, + configurable: false, + enumerable: true + }); + } } - state.dirtyAtoms.add(key2); - state.nonvalidatedAtoms.delete(key2); + return file; } -function applyActionsToStore(store, actions) { - store.replaceState((state) => { - const newState = copyTreeState(state); - for (const action of actions) { - applyAction(store, newState, action); - } - invalidateDownstreams(store, newState); - return newState; + +// node_modules/file-selector/dist/es5/file-selector.js +var FILES_TO_IGNORE = [ + ".DS_Store", + "Thumbs.db" +]; +function fromEvent(evt) { + return __awaiter(this, void 0, void 0, function() { + return __generator(this, function(_a2) { + if (isObject(evt) && isDataTransfer(evt.dataTransfer)) { + return [2, getDataTransferFiles(evt.dataTransfer, evt.type)]; + } else if (isChangeEvt(evt)) { + return [2, getInputFiles(evt)]; + } else if (Array.isArray(evt) && evt.every(function(item) { + return "getFile" in item && typeof item.getFile === "function"; + })) { + return [2, getFsHandleFiles(evt)]; + } + return [2, []]; + }); }); } -function queueOrPerformStateUpdate(store, action) { - if (batchStack.length) { - const actionsByStore = batchStack[batchStack.length - 1]; - let actions = actionsByStore.get(store); - if (!actions) { - actionsByStore.set(store, actions = []); - } - actions.push(action); - } else { - applyActionsToStore(store, [action]); - } -} -var batchStack = []; -function batchStart() { - const actionsByStore = /* @__PURE__ */ new Map(); - batchStack.push(actionsByStore); - return () => { - for (const [store, actions] of actionsByStore) { - applyActionsToStore(store, actions); - } - const popped = batchStack.pop(); - if (popped !== actionsByStore) { - Recoil_recoverableViolation("Incorrect order of batch popping"); - } - }; +function isDataTransfer(value) { + return isObject(value); } -function copyTreeState(state) { - return { - ...state, - atomValues: state.atomValues.clone(), - nonvalidatedAtoms: state.nonvalidatedAtoms.clone(), - dirtyAtoms: new Set(state.dirtyAtoms) - }; +function isChangeEvt(value) { + return isObject(value) && isObject(value.target); } -function invalidateDownstreams(store, state) { - const downstreams = getDownstreamNodes$1(store, state, state.dirtyAtoms); - for (const key2 of downstreams) { - var _getNodeMaybe, _getNodeMaybe$invalid; - (_getNodeMaybe = getNodeMaybe$2(key2)) === null || _getNodeMaybe === void 0 ? void 0 : (_getNodeMaybe$invalid = _getNodeMaybe.invalidate) === null || _getNodeMaybe$invalid === void 0 ? void 0 : _getNodeMaybe$invalid.call(_getNodeMaybe, state); - } +function isObject(v3) { + return typeof v3 === "object" && v3 !== null; } -function setRecoilValue(store, recoilValue, valueOrUpdater) { - queueOrPerformStateUpdate(store, { - type: "set", - recoilValue, - valueOrUpdater +function getInputFiles(evt) { + return fromList(evt.target.files).map(function(file) { + return toFileWithPath(file); }); } -function setRecoilValueLoadable(store, recoilValue, loadable) { - if (loadable instanceof DefaultValue$1) { - return setRecoilValue(store, recoilValue, loadable); - } - queueOrPerformStateUpdate(store, { - type: "setLoadable", - recoilValue, - loadable +function getFsHandleFiles(handles) { + return __awaiter(this, void 0, void 0, function() { + var files; + return __generator(this, function(_a2) { + switch (_a2.label) { + case 0: + return [4, Promise.all(handles.map(function(h5) { + return h5.getFile(); + }))]; + case 1: + files = _a2.sent(); + return [2, files.map(function(file) { + return toFileWithPath(file); + })]; + } + }); }); } -function markRecoilValueModified(store, recoilValue) { - queueOrPerformStateUpdate(store, { - type: "markModified", - recoilValue +function getDataTransferFiles(dt, type) { + return __awaiter(this, void 0, void 0, function() { + var items, files; + return __generator(this, function(_a2) { + switch (_a2.label) { + case 0: + if (!dt.items) + return [3, 2]; + items = fromList(dt.items).filter(function(item) { + return item.kind === "file"; + }); + if (type !== "drop") { + return [2, items]; + } + return [4, Promise.all(items.map(toFilePromises))]; + case 1: + files = _a2.sent(); + return [2, noIgnoredFiles(flatten(files))]; + case 2: + return [2, noIgnoredFiles(fromList(dt.files).map(function(file) { + return toFileWithPath(file); + }))]; + } + }); }); } -function setUnvalidatedRecoilValue(store, recoilValue, unvalidatedValue) { - queueOrPerformStateUpdate(store, { - type: "setUnvalidated", - recoilValue, - unvalidatedValue +function noIgnoredFiles(files) { + return files.filter(function(file) { + return FILES_TO_IGNORE.indexOf(file.name) === -1; }); } -var subscriptionID = 0; -function subscribeToRecoilValue(store, { - key: key2 -}, callback, componentDebugName = null) { - const subID = subscriptionID++; - const storeState = store.getState(); - if (!storeState.nodeToComponentSubscriptions.has(key2)) { - storeState.nodeToComponentSubscriptions.set(key2, /* @__PURE__ */ new Map()); +function fromList(items) { + if (items === null) { + return []; } - Recoil_nullthrows(storeState.nodeToComponentSubscriptions.get(key2)).set(subID, [componentDebugName !== null && componentDebugName !== void 0 ? componentDebugName : "", callback]); - if (Recoil_gkx_1("recoil_early_rendering_2021")) { - const nextTree = store.getState().nextTree; - if (nextTree && nextTree.dirtyAtoms.has(key2)) { - callback(nextTree); - } + var files = []; + for (var i4 = 0; i4 < items.length; i4++) { + var file = items[i4]; + files.push(file); } - return { - release: () => { - const storeState2 = store.getState(); - const subs = storeState2.nodeToComponentSubscriptions.get(key2); - if (subs === void 0 || !subs.has(subID)) { - Recoil_recoverableViolation(`Subscription missing at release time for atom ${key2}. This is a bug in Recoil.`); - return; - } - subs.delete(subID); - if (subs.size === 0) { - storeState2.nodeToComponentSubscriptions.delete(key2); - } - } - }; -} -var Recoil_RecoilValueInterface = { - RecoilValueReadOnly: RecoilValueReadOnly$1, - AbstractRecoilValue: AbstractRecoilValue$1, - RecoilState: RecoilState$1, - getRecoilValueAsLoadable, - setRecoilValue, - setRecoilValueLoadable, - markRecoilValueModified, - setUnvalidatedRecoilValue, - subscribeToRecoilValue, - isRecoilValue: isRecoilValue$1, - applyAtomValueWrites, - batchStart, - writeLoadableToTreeState, - invalidateDownstreams, - copyTreeState, - invalidateDownstreams_FOR_TESTING: invalidateDownstreams -}; -var { - unstable_batchedUpdates -} = Cn; -var ReactBatchedUpdates = { - unstable_batchedUpdates -}; -var { - unstable_batchedUpdates: unstable_batchedUpdates$1 -} = ReactBatchedUpdates; -var Recoil_ReactBatchedUpdates = { - unstable_batchedUpdates: unstable_batchedUpdates$1 -}; -var { - batchStart: batchStart$1 -} = Recoil_RecoilValueInterface; -var { - unstable_batchedUpdates: unstable_batchedUpdates$2 -} = Recoil_ReactBatchedUpdates; -var batcher = unstable_batchedUpdates$2; -var setBatcher = (newBatcher) => { - batcher = newBatcher; -}; -var getBatcher = () => batcher; -var batchUpdates = (callback) => { - batcher(() => { - let batchEnd = () => void 0; - try { - batchEnd = batchStart$1(); - callback(); - } finally { - batchEnd(); - } - }); -}; -var Recoil_Batching = { - getBatcher, - setBatcher, - batchUpdates -}; -function enqueueExecution(s5, f4) { - f4(); -} -var Recoil_Queue = { - enqueueExecution -}; -function differenceSets(set, ...setsWithValuesToRemove) { - const ret = /* @__PURE__ */ new Set(); - FIRST: - for (const value of set) { - for (const otherSet of setsWithValuesToRemove) { - if (otherSet.has(value)) { - continue FIRST; - } - } - ret.add(value); - } - return ret; + return files; } -var Recoil_differenceSets = differenceSets; -function mapMap(map, callback) { - const result = /* @__PURE__ */ new Map(); - map.forEach((value, key2) => { - result.set(key2, callback(value, key2)); - }); - return result; +function toFilePromises(item) { + if (typeof item.webkitGetAsEntry !== "function") { + return fromDataTransferItem(item); + } + var entry = item.webkitGetAsEntry(); + if (entry && entry.isDirectory) { + return fromDirEntry(entry); + } + return fromDataTransferItem(item); } -var Recoil_mapMap = mapMap; -function graph() { - return { - nodeDeps: /* @__PURE__ */ new Map(), - nodeToNodeSubscriptions: /* @__PURE__ */ new Map() - }; +function flatten(items) { + return items.reduce(function(acc, files) { + return __spreadArray2(__spreadArray2([], __read(acc), false), __read(Array.isArray(files) ? flatten(files) : [files]), false); + }, []); } -function cloneGraph(graph2) { - return { - nodeDeps: Recoil_mapMap(graph2.nodeDeps, (s5) => new Set(s5)), - nodeToNodeSubscriptions: Recoil_mapMap(graph2.nodeToNodeSubscriptions, (s5) => new Set(s5)) - }; +function fromDataTransferItem(item) { + var file = item.getAsFile(); + if (!file) { + return Promise.reject("".concat(item, " is not a File")); + } + var fwp = toFileWithPath(file); + return Promise.resolve(fwp); } -function mergeDependencyMapIntoGraph(deps, graph2, olderGraph) { - const { - nodeDeps, - nodeToNodeSubscriptions - } = graph2; - deps.forEach((upstreams, downstream) => { - const existingUpstreams = nodeDeps.get(downstream); - if (existingUpstreams && olderGraph && existingUpstreams !== olderGraph.nodeDeps.get(downstream)) { - return; - } - nodeDeps.set(downstream, new Set(upstreams)); - const addedUpstreams = existingUpstreams == null ? upstreams : Recoil_differenceSets(upstreams, existingUpstreams); - addedUpstreams.forEach((upstream) => { - if (!nodeToNodeSubscriptions.has(upstream)) { - nodeToNodeSubscriptions.set(upstream, /* @__PURE__ */ new Set()); - } - const existing = Recoil_nullthrows(nodeToNodeSubscriptions.get(upstream)); - existing.add(downstream); +function fromEntry(entry) { + return __awaiter(this, void 0, void 0, function() { + return __generator(this, function(_a2) { + return [2, entry.isDirectory ? fromDirEntry(entry) : fromFileEntry(entry)]; }); - if (existingUpstreams) { - const removedUpstreams = Recoil_differenceSets(existingUpstreams, upstreams); - removedUpstreams.forEach((upstream) => { - if (!nodeToNodeSubscriptions.has(upstream)) { - return; - } - const existing = Recoil_nullthrows(nodeToNodeSubscriptions.get(upstream)); - existing.delete(downstream); - if (existing.size === 0) { - nodeToNodeSubscriptions.delete(upstream); - } - }); - } }); } -function saveDependencyMapToStore(dependencyMap, store, version) { - var _storeState$nextTree, _storeState$previousT, _storeState$previousT2, _storeState$previousT3; - const storeState = store.getState(); - if (!(version === storeState.currentTree.version || version === ((_storeState$nextTree = storeState.nextTree) === null || _storeState$nextTree === void 0 ? void 0 : _storeState$nextTree.version) || version === ((_storeState$previousT = storeState.previousTree) === null || _storeState$previousT === void 0 ? void 0 : _storeState$previousT.version))) { - Recoil_recoverableViolation("Tried to save dependencies to a discarded tree"); - } - const graph2 = store.getGraph(version); - mergeDependencyMapIntoGraph(dependencyMap, graph2); - if (version === ((_storeState$previousT2 = storeState.previousTree) === null || _storeState$previousT2 === void 0 ? void 0 : _storeState$previousT2.version)) { - const currentGraph = store.getGraph(storeState.currentTree.version); - mergeDependencyMapIntoGraph(dependencyMap, currentGraph, graph2); - } - if (version === ((_storeState$previousT3 = storeState.previousTree) === null || _storeState$previousT3 === void 0 ? void 0 : _storeState$previousT3.version) || version === storeState.currentTree.version) { - var _storeState$nextTree2; - const nextVersion = (_storeState$nextTree2 = storeState.nextTree) === null || _storeState$nextTree2 === void 0 ? void 0 : _storeState$nextTree2.version; - if (nextVersion !== void 0) { - const nextGraph = store.getGraph(nextVersion); - mergeDependencyMapIntoGraph(dependencyMap, nextGraph, graph2); +function fromDirEntry(entry) { + var reader = entry.createReader(); + return new Promise(function(resolve, reject) { + var entries = []; + function readEntries() { + var _this = this; + reader.readEntries(function(batch) { + return __awaiter(_this, void 0, void 0, function() { + var files, err_1, items; + return __generator(this, function(_a2) { + switch (_a2.label) { + case 0: + if (!!batch.length) + return [3, 5]; + _a2.label = 1; + case 1: + _a2.trys.push([1, 3, , 4]); + return [4, Promise.all(entries)]; + case 2: + files = _a2.sent(); + resolve(files); + return [3, 4]; + case 3: + err_1 = _a2.sent(); + reject(err_1); + return [3, 4]; + case 4: + return [3, 6]; + case 5: + items = Promise.all(batch.map(fromEntry)); + entries.push(items); + readEntries(); + _a2.label = 6; + case 6: + return [2]; + } + }); + }); + }, function(err) { + reject(err); + }); } - } + readEntries(); + }); } -function mergeDepsIntoDependencyMap(from, into) { - from.forEach((upstreamDeps, downstreamNode) => { - if (!into.has(downstreamNode)) { - into.set(downstreamNode, /* @__PURE__ */ new Set()); - } - const deps = Recoil_nullthrows(into.get(downstreamNode)); - upstreamDeps.forEach((dep) => deps.add(dep)); +function fromFileEntry(entry) { + return __awaiter(this, void 0, void 0, function() { + return __generator(this, function(_a2) { + return [2, new Promise(function(resolve, reject) { + entry.file(function(file) { + var fwp = toFileWithPath(file, entry.fullPath); + resolve(fwp); + }, function(err) { + reject(err); + }); + })]; + }); }); } -function addToDependencyMap(downstream, upstream, dependencyMap) { - if (!dependencyMap.has(downstream)) { - dependencyMap.set(downstream, /* @__PURE__ */ new Set()); - } - Recoil_nullthrows(dependencyMap.get(downstream)).add(upstream); -} -var Recoil_Graph = { - addToDependencyMap, - cloneGraph, - graph, - mergeDepsIntoDependencyMap, - saveDependencyMapToStore -}; -function createCommonjsModule(fn2, module2) { - return module2 = { exports: {} }, fn2(module2, module2.exports), module2.exports; -} -var hamt_1 = createCommonjsModule(function(module2) { - var _typeof5 = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function(obj) { - return typeof obj; - } : function(obj) { - return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; - }; - var hamt = {}; - var SIZE = 5; - var BUCKET_SIZE = Math.pow(2, SIZE); - var MASK = BUCKET_SIZE - 1; - var MAX_INDEX_NODE = BUCKET_SIZE / 2; - var MIN_ARRAY_NODE = BUCKET_SIZE / 4; - var nothing = {}; - var constant = function constant2(x5) { - return function() { - return x5; - }; - }; - var hash = hamt.hash = function(str) { - var type = typeof str === "undefined" ? "undefined" : _typeof5(str); - if (type === "number") - return str; - if (type !== "string") - str += ""; - var hash2 = 0; - for (var i4 = 0, len = str.length; i4 < len; ++i4) { - var c4 = str.charCodeAt(i4); - hash2 = (hash2 << 5) - hash2 + c4 | 0; - } - return hash2; - }; - var popcount = function popcount2(x5) { - x5 -= x5 >> 1 & 1431655765; - x5 = (x5 & 858993459) + (x5 >> 2 & 858993459); - x5 = x5 + (x5 >> 4) & 252645135; - x5 += x5 >> 8; - x5 += x5 >> 16; - return x5 & 127; - }; - var hashFragment = function hashFragment2(shift, h5) { - return h5 >>> shift & MASK; - }; - var toBitmap = function toBitmap2(x5) { - return 1 << x5; - }; - var fromBitmap = function fromBitmap2(bitmap, bit) { - return popcount(bitmap & bit - 1); - }; - var arrayUpdate = function arrayUpdate2(mutate2, at, v3, arr) { - var out = arr; - if (!mutate2) { - var len = arr.length; - out = new Array(len); - for (var i4 = 0; i4 < len; ++i4) { - out[i4] = arr[i4]; - } - } - out[at] = v3; - return out; - }; - var arraySpliceOut = function arraySpliceOut2(mutate2, at, arr) { - var newLen = arr.length - 1; - var i4 = 0; - var g4 = 0; - var out = arr; - if (mutate2) { - i4 = g4 = at; - } else { - out = new Array(newLen); - while (i4 < at) { - out[g4++] = arr[i4++]; - } - } - ++i4; - while (i4 <= newLen) { - out[g4++] = arr[i4++]; - } - if (mutate2) { - out.length = newLen; - } - return out; - }; - var arraySpliceIn = function arraySpliceIn2(mutate2, at, v3, arr) { - var len = arr.length; - if (mutate2) { - var _i = len; - while (_i >= at) { - arr[_i--] = arr[_i]; - } - arr[at] = v3; - return arr; - } - var i4 = 0, g4 = 0; - var out = new Array(len + 1); - while (i4 < at) { - out[g4++] = arr[i4++]; - } - out[at] = v3; - while (i4 < len) { - out[++g4] = arr[i4++]; - } - return out; - }; - var LEAF = 1; - var COLLISION = 2; - var INDEX = 3; - var ARRAY = 4; - var empty2 = { - __hamt_isEmpty: true - }; - var isEmptyNode = function isEmptyNode2(x5) { - return x5 === empty2 || x5 && x5.__hamt_isEmpty; - }; - var Leaf = function Leaf2(edit, hash2, key2, value) { - return { - type: LEAF, - edit, - hash: hash2, - key: key2, - value, - _modify: Leaf__modify - }; - }; - var Collision = function Collision2(edit, hash2, children) { - return { - type: COLLISION, - edit, - hash: hash2, - children, - _modify: Collision__modify - }; - }; - var IndexedNode = function IndexedNode2(edit, mask, children) { - return { - type: INDEX, - edit, - mask, - children, - _modify: IndexedNode__modify - }; - }; - var ArrayNode = function ArrayNode2(edit, size, children) { - return { - type: ARRAY, - edit, - size, - children, - _modify: ArrayNode__modify - }; - }; - var isLeaf = function isLeaf2(node) { - return node === empty2 || node.type === LEAF || node.type === COLLISION; - }; - var expand = function expand2(edit, frag, child, bitmap, subNodes) { - var arr = []; - var bit = bitmap; - var count3 = 0; - for (var i4 = 0; bit; ++i4) { - if (bit & 1) - arr[i4] = subNodes[count3++]; - bit >>>= 1; - } - arr[frag] = child; - return ArrayNode(edit, count3 + 1, arr); - }; - var pack = function pack2(edit, count3, removed, elements) { - var children = new Array(count3 - 1); - var g4 = 0; - var bitmap = 0; - for (var i4 = 0, len = elements.length; i4 < len; ++i4) { - if (i4 !== removed) { - var elem = elements[i4]; - if (elem && !isEmptyNode(elem)) { - children[g4++] = elem; - bitmap |= 1 << i4; - } - } - } - return IndexedNode(edit, bitmap, children); - }; - var mergeLeaves = function mergeLeaves2(edit, shift, h1, n1, h22, n2) { - if (h1 === h22) - return Collision(edit, h1, [n2, n1]); - var subH1 = hashFragment(shift, h1); - var subH2 = hashFragment(shift, h22); - return IndexedNode(edit, toBitmap(subH1) | toBitmap(subH2), subH1 === subH2 ? [mergeLeaves2(edit, shift + SIZE, h1, n1, h22, n2)] : subH1 < subH2 ? [n1, n2] : [n2, n1]); - }; - var updateCollisionList = function updateCollisionList2(mutate2, edit, keyEq, h5, list, f4, k5, size) { - var len = list.length; - for (var i4 = 0; i4 < len; ++i4) { - var child = list[i4]; - if (keyEq(k5, child.key)) { - var value = child.value; - var _newValue = f4(value); - if (_newValue === value) - return list; - if (_newValue === nothing) { - --size.value; - return arraySpliceOut(mutate2, i4, list); - } - return arrayUpdate(mutate2, i4, Leaf(edit, h5, k5, _newValue), list); - } - } - var newValue = f4(); - if (newValue === nothing) - return list; - ++size.value; - return arrayUpdate(mutate2, len, Leaf(edit, h5, k5, newValue), list); - }; - var canEditNode = function canEditNode2(edit, node) { - return edit === node.edit; - }; - var Leaf__modify = function Leaf__modify2(edit, keyEq, shift, f4, h5, k5, size) { - if (keyEq(k5, this.key)) { - var _v = f4(this.value); - if (_v === this.value) - return this; - else if (_v === nothing) { - --size.value; - return empty2; - } - if (canEditNode(edit, this)) { - this.value = _v; - return this; - } - return Leaf(edit, h5, k5, _v); - } - var v3 = f4(); - if (v3 === nothing) - return this; - ++size.value; - return mergeLeaves(edit, shift, this.hash, this, h5, Leaf(edit, h5, k5, v3)); - }; - var Collision__modify = function Collision__modify2(edit, keyEq, shift, f4, h5, k5, size) { - if (h5 === this.hash) { - var canEdit = canEditNode(edit, this); - var list = updateCollisionList(canEdit, edit, keyEq, this.hash, this.children, f4, k5, size); - if (list === this.children) - return this; - return list.length > 1 ? Collision(edit, this.hash, list) : list[0]; - } - var v3 = f4(); - if (v3 === nothing) - return this; - ++size.value; - return mergeLeaves(edit, shift, this.hash, this, h5, Leaf(edit, h5, k5, v3)); - }; - var IndexedNode__modify = function IndexedNode__modify2(edit, keyEq, shift, f4, h5, k5, size) { - var mask = this.mask; - var children = this.children; - var frag = hashFragment(shift, h5); - var bit = toBitmap(frag); - var indx = fromBitmap(mask, bit); - var exists = mask & bit; - var current = exists ? children[indx] : empty2; - var child = current._modify(edit, keyEq, shift + SIZE, f4, h5, k5, size); - if (current === child) - return this; - var canEdit = canEditNode(edit, this); - var bitmap = mask; - var newChildren = void 0; - if (exists && isEmptyNode(child)) { - bitmap &= ~bit; - if (!bitmap) - return empty2; - if (children.length <= 2 && isLeaf(children[indx ^ 1])) - return children[indx ^ 1]; - newChildren = arraySpliceOut(canEdit, indx, children); - } else if (!exists && !isEmptyNode(child)) { - if (children.length >= MAX_INDEX_NODE) - return expand(edit, frag, child, mask, children); - bitmap |= bit; - newChildren = arraySpliceIn(canEdit, indx, child, children); - } else { - newChildren = arrayUpdate(canEdit, indx, child, children); - } - if (canEdit) { - this.mask = bitmap; - this.children = newChildren; - return this; - } - return IndexedNode(edit, bitmap, newChildren); - }; - var ArrayNode__modify = function ArrayNode__modify2(edit, keyEq, shift, f4, h5, k5, size) { - var count3 = this.size; - var children = this.children; - var frag = hashFragment(shift, h5); - var child = children[frag]; - var newChild = (child || empty2)._modify(edit, keyEq, shift + SIZE, f4, h5, k5, size); - if (child === newChild) - return this; - var canEdit = canEditNode(edit, this); - var newChildren = void 0; - if (isEmptyNode(child) && !isEmptyNode(newChild)) { - ++count3; - newChildren = arrayUpdate(canEdit, frag, newChild, children); - } else if (!isEmptyNode(child) && isEmptyNode(newChild)) { - --count3; - if (count3 <= MIN_ARRAY_NODE) - return pack(edit, count3, frag, children); - newChildren = arrayUpdate(canEdit, frag, empty2, children); - } else { - newChildren = arrayUpdate(canEdit, frag, newChild, children); - } - if (canEdit) { - this.size = count3; - this.children = newChildren; - return this; - } - return ArrayNode(edit, count3, newChildren); - }; - empty2._modify = function(edit, keyEq, shift, f4, h5, k5, size) { - var v3 = f4(); - if (v3 === nothing) - return empty2; - ++size.value; - return Leaf(edit, h5, k5, v3); - }; - function Map2(editable, edit, config, root, size) { - this._editable = editable; - this._edit = edit; - this._config = config; - this._root = root; - this._size = size; - } - Map2.prototype.setTree = function(newRoot, newSize) { - if (this._editable) { - this._root = newRoot; - this._size = newSize; - return this; - } - return newRoot === this._root ? this : new Map2(this._editable, this._edit, this._config, newRoot, newSize); - }; - var tryGetHash = hamt.tryGetHash = function(alt, hash2, key2, map) { - var node = map._root; - var shift = 0; - var keyEq = map._config.keyEq; - while (true) { - switch (node.type) { - case LEAF: { - return keyEq(key2, node.key) ? node.value : alt; - } - case COLLISION: { - if (hash2 === node.hash) { - var children = node.children; - for (var i4 = 0, len = children.length; i4 < len; ++i4) { - var child = children[i4]; - if (keyEq(key2, child.key)) - return child.value; - } - } - return alt; - } - case INDEX: { - var frag = hashFragment(shift, hash2); - var bit = toBitmap(frag); - if (node.mask & bit) { - node = node.children[fromBitmap(node.mask, bit)]; - shift += SIZE; - break; - } - return alt; - } - case ARRAY: { - node = node.children[hashFragment(shift, hash2)]; - if (node) { - shift += SIZE; - break; - } - return alt; - } - default: - return alt; - } - } - }; - Map2.prototype.tryGetHash = function(alt, hash2, key2) { - return tryGetHash(alt, hash2, key2, this); - }; - var tryGet = hamt.tryGet = function(alt, key2, map) { - return tryGetHash(alt, map._config.hash(key2), key2, map); - }; - Map2.prototype.tryGet = function(alt, key2) { - return tryGet(alt, key2, this); - }; - var getHash = hamt.getHash = function(hash2, key2, map) { - return tryGetHash(void 0, hash2, key2, map); - }; - Map2.prototype.getHash = function(hash2, key2) { - return getHash(hash2, key2, this); - }; - var get = hamt.get = function(key2, map) { - return tryGetHash(void 0, map._config.hash(key2), key2, map); - }; - Map2.prototype.get = function(key2, alt) { - return tryGet(alt, key2, this); - }; - var hasHash = hamt.has = function(hash2, key2, map) { - return tryGetHash(nothing, hash2, key2, map) !== nothing; - }; - Map2.prototype.hasHash = function(hash2, key2) { - return hasHash(hash2, key2, this); - }; - var has = hamt.has = function(key2, map) { - return hasHash(map._config.hash(key2), key2, map); - }; - Map2.prototype.has = function(key2) { - return has(key2, this); - }; - var defKeyCompare = function defKeyCompare2(x5, y5) { - return x5 === y5; - }; - hamt.make = function(config) { - return new Map2(0, 0, { - keyEq: config && config.keyEq || defKeyCompare, - hash: config && config.hash || hash - }, empty2, 0); - }; - hamt.empty = hamt.make(); - var isEmpty = hamt.isEmpty = function(map) { - return map && !!isEmptyNode(map._root); - }; - Map2.prototype.isEmpty = function() { - return isEmpty(this); - }; - var modifyHash = hamt.modifyHash = function(f4, hash2, key2, map) { - var size = { - value: map._size - }; - var newRoot = map._root._modify(map._editable ? map._edit : NaN, map._config.keyEq, 0, f4, hash2, key2, size); - return map.setTree(newRoot, size.value); - }; - Map2.prototype.modifyHash = function(hash2, key2, f4) { - return modifyHash(f4, hash2, key2, this); - }; - var modify = hamt.modify = function(f4, key2, map) { - return modifyHash(f4, map._config.hash(key2), key2, map); - }; - Map2.prototype.modify = function(key2, f4) { - return modify(f4, key2, this); - }; - var setHash = hamt.setHash = function(hash2, key2, value, map) { - return modifyHash(constant(value), hash2, key2, map); - }; - Map2.prototype.setHash = function(hash2, key2, value) { - return setHash(hash2, key2, value, this); - }; - var set = hamt.set = function(key2, value, map) { - return setHash(map._config.hash(key2), key2, value, map); - }; - Map2.prototype.set = function(key2, value) { - return set(key2, value, this); - }; - var del = constant(nothing); - var removeHash = hamt.removeHash = function(hash2, key2, map) { - return modifyHash(del, hash2, key2, map); - }; - Map2.prototype.removeHash = Map2.prototype.deleteHash = function(hash2, key2) { - return removeHash(hash2, key2, this); - }; - var remove = hamt.remove = function(key2, map) { - return removeHash(map._config.hash(key2), key2, map); - }; - Map2.prototype.remove = Map2.prototype.delete = function(key2) { - return remove(key2, this); - }; - var beginMutation = hamt.beginMutation = function(map) { - return new Map2(map._editable + 1, map._edit + 1, map._config, map._root, map._size); - }; - Map2.prototype.beginMutation = function() { - return beginMutation(this); - }; - var endMutation = hamt.endMutation = function(map) { - map._editable = map._editable && map._editable - 1; - return map; - }; - Map2.prototype.endMutation = function() { - return endMutation(this); - }; - var mutate = hamt.mutate = function(f4, map) { - var transient = beginMutation(map); - f4(transient); - return endMutation(transient); - }; - Map2.prototype.mutate = function(f4) { - return mutate(f4, this); - }; - var appk = function appk2(k5) { - return k5 && lazyVisitChildren(k5[0], k5[1], k5[2], k5[3], k5[4]); - }; - var lazyVisitChildren = function lazyVisitChildren2(len, children, i4, f4, k5) { - while (i4 < len) { - var child = children[i4++]; - if (child && !isEmptyNode(child)) - return lazyVisit(child, f4, [len, children, i4, f4, k5]); - } - return appk(k5); - }; - var lazyVisit = function lazyVisit2(node, f4, k5) { - switch (node.type) { - case LEAF: - return { - value: f4(node), - rest: k5 - }; - case COLLISION: - case ARRAY: - case INDEX: - var children = node.children; - return lazyVisitChildren(children.length, children, 0, f4, k5); - default: - return appk(k5); - } - }; - var DONE = { - done: true - }; - function MapIterator(v3) { - this.v = v3; + +// node_modules/react-dropzone/dist/es/utils/index.js +var import_attr_accept = __toESM(require_es()); +function _toConsumableArray(arr) { + return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); +} +function _nonIterableSpread() { + throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); +} +function _iterableToArray(iter) { + if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) + return Array.from(iter); +} +function _arrayWithoutHoles(arr) { + if (Array.isArray(arr)) + return _arrayLikeToArray(arr); +} +function ownKeys(object, enumerableOnly) { + var keys = Object.keys(object); + if (Object.getOwnPropertySymbols) { + var symbols = Object.getOwnPropertySymbols(object); + enumerableOnly && (symbols = symbols.filter(function(sym) { + return Object.getOwnPropertyDescriptor(object, sym).enumerable; + })), keys.push.apply(keys, symbols); + } + return keys; +} +function _objectSpread(target) { + for (var i4 = 1; i4 < arguments.length; i4++) { + var source = null != arguments[i4] ? arguments[i4] : {}; + i4 % 2 ? ownKeys(Object(source), true).forEach(function(key2) { + _defineProperty(target, key2, source[key2]); + }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function(key2) { + Object.defineProperty(target, key2, Object.getOwnPropertyDescriptor(source, key2)); + }); } - MapIterator.prototype.next = function() { - if (!this.v) - return DONE; - var v0 = this.v; - this.v = appk(v0.rest); - return v0; - }; - MapIterator.prototype[Symbol.iterator] = function() { - return this; - }; - var visit = function visit2(map, f4) { - return new MapIterator(lazyVisit(map._root, f4)); - }; - var buildPairs = function buildPairs2(x5) { - return [x5.key, x5.value]; - }; - var entries = hamt.entries = function(map) { - return visit(map, buildPairs); - }; - Map2.prototype.entries = Map2.prototype[Symbol.iterator] = function() { - return entries(this); - }; - var buildKeys = function buildKeys2(x5) { - return x5.key; - }; - var keys = hamt.keys = function(map) { - return visit(map, buildKeys); - }; - Map2.prototype.keys = function() { - return keys(this); - }; - var buildValues = function buildValues2(x5) { - return x5.value; - }; - var values = hamt.values = Map2.prototype.values = function(map) { - return visit(map, buildValues); - }; - Map2.prototype.values = function() { - return values(this); - }; - var fold = hamt.fold = function(f4, z5, m5) { - var root = m5._root; - if (root.type === LEAF) - return f4(z5, root.value, root.key); - var toVisit = [root.children]; - var children = void 0; - while (children = toVisit.pop()) { - for (var i4 = 0, len = children.length; i4 < len; ) { - var child = children[i4++]; - if (child && child.type) { - if (child.type === LEAF) - z5 = f4(z5, child.value, child.key); - else - toVisit.push(child.children); - } - } - } - return z5; - }; - Map2.prototype.fold = function(f4, z5) { - return fold(f4, z5, this); - }; - var forEach = hamt.forEach = function(f4, map) { - return fold(function(_9, value, key2) { - return f4(value, key2, map); - }, null, map); - }; - Map2.prototype.forEach = function(f4) { - return forEach(f4, this); - }; - var count2 = hamt.count = function(map) { - return map._size; - }; - Map2.prototype.count = function() { - return count2(this); - }; - Object.defineProperty(Map2.prototype, "size", { - get: Map2.prototype.count - }); - if (module2.exports) { - module2.exports = hamt; + return target; +} +function _defineProperty(obj, key2, value) { + if (key2 in obj) { + Object.defineProperty(obj, key2, { value, enumerable: true, configurable: true, writable: true }); } else { - (void 0).hamt = hamt; - } -}); -var BuiltInMap = class { - constructor(existing) { - _defineProperty(this, "_map", void 0); - this._map = new Map(existing === null || existing === void 0 ? void 0 : existing.entries()); - } - keys() { - return this._map.keys(); - } - entries() { - return this._map.entries(); - } - get(k5) { - return this._map.get(k5); - } - has(k5) { - return this._map.has(k5); - } - set(k5, v3) { - this._map.set(k5, v3); - return this; - } - delete(k5) { - this._map.delete(k5); - return this; - } - clone() { - return persistentMap(this); - } - toMap() { - return new Map(this._map); + obj[key2] = value; } -}; -var HashArrayMappedTrieMap = class { - constructor(existing) { - _defineProperty(this, "_hamt", hamt_1.empty.beginMutation()); - if (existing instanceof HashArrayMappedTrieMap) { - const h5 = existing._hamt.endMutation(); - existing._hamt = h5.beginMutation(); - this._hamt = h5.beginMutation(); - } else if (existing) { - for (const [k5, v3] of existing.entries()) { - this._hamt.set(k5, v3); - } + return obj; +} +function _slicedToArray(arr, i4) { + return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i4) || _unsupportedIterableToArray(arr, i4) || _nonIterableRest(); +} +function _nonIterableRest() { + throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); +} +function _unsupportedIterableToArray(o3, minLen) { + if (!o3) + return; + if (typeof o3 === "string") + return _arrayLikeToArray(o3, minLen); + var n2 = Object.prototype.toString.call(o3).slice(8, -1); + if (n2 === "Object" && o3.constructor) + n2 = o3.constructor.name; + if (n2 === "Map" || n2 === "Set") + return Array.from(o3); + if (n2 === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n2)) + return _arrayLikeToArray(o3, minLen); +} +function _arrayLikeToArray(arr, len) { + if (len == null || len > arr.length) + len = arr.length; + for (var i4 = 0, arr2 = new Array(len); i4 < len; i4++) { + arr2[i4] = arr[i4]; + } + return arr2; +} +function _iterableToArrayLimit(arr, i4) { + var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]; + if (_i == null) + return; + var _arr = []; + var _n2 = true; + var _d2 = false; + var _s, _e2; + try { + for (_i = _i.call(arr); !(_n2 = (_s = _i.next()).done); _n2 = true) { + _arr.push(_s.value); + if (i4 && _arr.length === i4) + break; + } + } catch (err) { + _d2 = true; + _e2 = err; + } finally { + try { + if (!_n2 && _i["return"] != null) + _i["return"](); + } finally { + if (_d2) + throw _e2; } } - keys() { - return this._hamt.keys(); - } - entries() { - return this._hamt.entries(); - } - get(k5) { - return this._hamt.get(k5); - } - has(k5) { - return this._hamt.has(k5); - } - set(k5, v3) { - this._hamt.set(k5, v3); - return this; - } - delete(k5) { - this._hamt.delete(k5); - return this; - } - clone() { - return persistentMap(this); - } - toMap() { - return new Map(this._hamt); - } -}; -function persistentMap(existing) { - if (Recoil_gkx_1("recoil_hamt_2020")) { - return new HashArrayMappedTrieMap(existing); - } else { - return new BuiltInMap(existing); - } + return _arr; +} +function _arrayWithHoles(arr) { + if (Array.isArray(arr)) + return arr; } -var Recoil_PersistentMap = { - persistentMap +var FILE_INVALID_TYPE = "file-invalid-type"; +var FILE_TOO_LARGE = "file-too-large"; +var FILE_TOO_SMALL = "file-too-small"; +var TOO_MANY_FILES = "too-many-files"; +var getInvalidTypeRejectionErr = function getInvalidTypeRejectionErr2(accept) { + accept = Array.isArray(accept) && accept.length === 1 ? accept[0] : accept; + var messageSuffix = Array.isArray(accept) ? "one of ".concat(accept.join(", ")) : accept; + return { + code: FILE_INVALID_TYPE, + message: "File type must be ".concat(messageSuffix) + }; }; -var Recoil_PersistentMap_1 = Recoil_PersistentMap.persistentMap; -var Recoil_PersistentMap$1 = /* @__PURE__ */ Object.freeze({ - __proto__: null, - persistentMap: Recoil_PersistentMap_1 -}); -var { - graph: graph$1 -} = Recoil_Graph; -var { - persistentMap: persistentMap$1 -} = Recoil_PersistentMap$1; -var nextTreeStateVersion = 0; -var getNextTreeStateVersion = () => nextTreeStateVersion++; -function makeEmptyTreeState() { - const version = getNextTreeStateVersion(); +var getTooLargeRejectionErr = function getTooLargeRejectionErr2(maxSize) { return { - version, - stateID: version, - transactionMetadata: {}, - dirtyAtoms: /* @__PURE__ */ new Set(), - atomValues: persistentMap$1(), - nonvalidatedAtoms: persistentMap$1() + code: FILE_TOO_LARGE, + message: "File is larger than ".concat(maxSize, " ").concat(maxSize === 1 ? "byte" : "bytes") }; -} -function makeEmptyStoreState() { - const currentTree = makeEmptyTreeState(); +}; +var getTooSmallRejectionErr = function getTooSmallRejectionErr2(minSize) { return { - currentTree, - nextTree: null, - previousTree: null, - commitDepth: 0, - knownAtoms: /* @__PURE__ */ new Set(), - knownSelectors: /* @__PURE__ */ new Set(), - transactionSubscriptions: /* @__PURE__ */ new Map(), - nodeTransactionSubscriptions: /* @__PURE__ */ new Map(), - nodeToComponentSubscriptions: /* @__PURE__ */ new Map(), - queuedComponentCallbacks_DEPRECATED: [], - suspendedComponentResolvers: /* @__PURE__ */ new Set(), - graphsByVersion: (/* @__PURE__ */ new Map()).set(currentTree.version, graph$1()), - versionsUsedByComponent: /* @__PURE__ */ new Map(), - retention: { - referenceCounts: /* @__PURE__ */ new Map(), - nodesRetainedByZone: /* @__PURE__ */ new Map(), - retainablesToCheckForRelease: /* @__PURE__ */ new Set() - }, - nodeCleanupFunctions: /* @__PURE__ */ new Map() - }; -} -var Recoil_State = { - makeEmptyTreeState, - makeEmptyStoreState, - getNextTreeStateVersion -}; -function unionSets(...sets) { - const result = /* @__PURE__ */ new Set(); - for (const set of sets) { - for (const value of set) { - result.add(value); - } + code: FILE_TOO_SMALL, + message: "File is smaller than ".concat(minSize, " ").concat(minSize === 1 ? "byte" : "bytes") + }; +}; +var TOO_MANY_FILES_REJECTION = { + code: TOO_MANY_FILES, + message: "Too many files" +}; +function fileAccepted(file, accept) { + var isAcceptable = file.type === "application/x-moz-file" || (0, import_attr_accept.default)(file, accept); + return [isAcceptable, isAcceptable ? null : getInvalidTypeRejectionErr(accept)]; +} +function fileMatchSize(file, minSize, maxSize) { + if (isDefined(file.size)) { + if (isDefined(minSize) && isDefined(maxSize)) { + if (file.size > maxSize) + return [false, getTooLargeRejectionErr(maxSize)]; + if (file.size < minSize) + return [false, getTooSmallRejectionErr(minSize)]; + } else if (isDefined(minSize) && file.size < minSize) + return [false, getTooSmallRejectionErr(minSize)]; + else if (isDefined(maxSize) && file.size > maxSize) + return [false, getTooLargeRejectionErr(maxSize)]; + } + return [true, null]; +} +function isDefined(value) { + return value !== void 0 && value !== null; +} +function allFilesAccepted(_ref) { + var files = _ref.files, accept = _ref.accept, minSize = _ref.minSize, maxSize = _ref.maxSize, multiple = _ref.multiple, maxFiles = _ref.maxFiles, validator = _ref.validator; + if (!multiple && files.length > 1 || multiple && maxFiles >= 1 && files.length > maxFiles) { + return false; } - return result; + return files.every(function(file) { + var _fileAccepted = fileAccepted(file, accept), _fileAccepted2 = _slicedToArray(_fileAccepted, 1), accepted = _fileAccepted2[0]; + var _fileMatchSize = fileMatchSize(file, minSize, maxSize), _fileMatchSize2 = _slicedToArray(_fileMatchSize, 1), sizeMatch = _fileMatchSize2[0]; + var customErrors = validator ? validator(file) : null; + return accepted && sizeMatch && !customErrors; + }); } -var Recoil_unionSets = unionSets; -function someSet(set, callback, context) { - const iterator = set.entries(); - let current = iterator.next(); - while (!current.done) { - const entry = current.value; - if (callback.call(context, entry[1], entry[0], set)) { - return true; - } - current = iterator.next(); +function isPropagationStopped(event) { + if (typeof event.isPropagationStopped === "function") { + return event.isPropagationStopped(); + } else if (typeof event.cancelBubble !== "undefined") { + return event.cancelBubble; } return false; } -var Recoil_someSet = someSet; -var { - cleanUpNode: cleanUpNode$1 -} = Recoil_FunctionalCore; -var { - deleteNodeConfigIfPossible: deleteNodeConfigIfPossible$1, - getNode: getNode$2 -} = Recoil_Node; -var { - RetentionZone: RetentionZone$2 -} = Recoil_RetentionZone; -var emptySet$1 = /* @__PURE__ */ new Set(); -function releaseRetainablesNowOnCurrentTree(store, retainables) { - const storeState = store.getState(); - const treeState = storeState.currentTree; - if (storeState.nextTree) { - Recoil_recoverableViolation("releaseNodesNowOnCurrentTree should only be called at the end of a batch"); - return; - } - const nodes2 = /* @__PURE__ */ new Set(); - for (const r3 of retainables) { - if (r3 instanceof RetentionZone$2) { - for (const n2 of nodesRetainedByZone(storeState, r3)) { - nodes2.add(n2); - } - } else { - nodes2.add(r3); - } - } - const releasableNodes = findReleasableNodes(store, nodes2); - for (const node of releasableNodes) { - releaseNode(store, treeState, node); - } -} -function findReleasableNodes(store, searchFromNodes) { - const storeState = store.getState(); - const treeState = storeState.currentTree; - const graph2 = store.getGraph(treeState.version); - const releasableNodes = /* @__PURE__ */ new Set(); - const nonReleasableNodes = /* @__PURE__ */ new Set(); - findReleasableNodesInner(searchFromNodes); - return releasableNodes; - function findReleasableNodesInner(searchFromNodes2) { - const releasableNodesFoundThisIteration = /* @__PURE__ */ new Set(); - const downstreams = getDownstreamNodesInTopologicalOrder( - store, - treeState, - searchFromNodes2, - releasableNodes, - nonReleasableNodes - ); - for (const node of downstreams) { - var _storeState$retention; - if (getNode$2(node).retainedBy === "recoilRoot") { - nonReleasableNodes.add(node); - continue; - } - if (((_storeState$retention = storeState.retention.referenceCounts.get(node)) !== null && _storeState$retention !== void 0 ? _storeState$retention : 0) > 0) { - nonReleasableNodes.add(node); - continue; - } - if (zonesThatCouldRetainNode(node).some((z5) => storeState.retention.referenceCounts.get(z5))) { - nonReleasableNodes.add(node); - continue; - } - const nodeChildren = graph2.nodeToNodeSubscriptions.get(node); - if (nodeChildren && Recoil_someSet(nodeChildren, (child) => nonReleasableNodes.has(child))) { - nonReleasableNodes.add(node); - continue; - } - releasableNodes.add(node); - releasableNodesFoundThisIteration.add(node); - } - const parents = /* @__PURE__ */ new Set(); - for (const node of releasableNodesFoundThisIteration) { - for (const parent of (_graph$nodeDeps$get = graph2.nodeDeps.get(node)) !== null && _graph$nodeDeps$get !== void 0 ? _graph$nodeDeps$get : emptySet$1) { - var _graph$nodeDeps$get; - if (!releasableNodes.has(parent)) { - parents.add(parent); - } - } - } - if (parents.size) { - findReleasableNodesInner(parents); - } +function isEvtWithFiles(event) { + if (!event.dataTransfer) { + return !!event.target && !!event.target.files; } + return Array.prototype.some.call(event.dataTransfer.types, function(type) { + return type === "Files" || type === "application/x-moz-file"; + }); } -function getDownstreamNodesInTopologicalOrder(store, treeState, nodes2, doNotDescendInto1, doNotDescendInto2) { - const graph2 = store.getGraph(treeState.version); - const answer = []; - const visited = /* @__PURE__ */ new Set(); - while (nodes2.size > 0) { - visit(Recoil_nullthrows(nodes2.values().next().value)); +function onDocumentDragOver(event) { + event.preventDefault(); +} +function isIe(userAgent) { + return userAgent.indexOf("MSIE") !== -1 || userAgent.indexOf("Trident/") !== -1; +} +function isEdge(userAgent) { + return userAgent.indexOf("Edge/") !== -1; +} +function isIeOrEdge() { + var userAgent = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : window.navigator.userAgent; + return isIe(userAgent) || isEdge(userAgent); +} +function composeEventHandlers() { + for (var _len = arguments.length, fns = new Array(_len), _key = 0; _key < _len; _key++) { + fns[_key] = arguments[_key]; } - return answer; - function visit(node) { - if (doNotDescendInto1.has(node) || doNotDescendInto2.has(node)) { - nodes2.delete(node); - return; - } - if (visited.has(node)) { - return; + return function(event) { + for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { + args[_key2 - 1] = arguments[_key2]; } - const children = graph2.nodeToNodeSubscriptions.get(node); - if (children) { - for (const child of children) { - visit(child); + return fns.some(function(fn2) { + if (!isPropagationStopped(event) && fn2) { + fn2.apply(void 0, [event].concat(args)); } - } - visited.add(node); - nodes2.delete(node); - answer.push(node); - } + return isPropagationStopped(event); + }); + }; } -function releaseNode(store, treeState, node) { - if (!Recoil_gkx_1("recoil_memory_managament_2020")) { - return; - } - cleanUpNode$1(store, node); - const storeState = store.getState(); - storeState.knownAtoms.delete(node); - storeState.knownSelectors.delete(node); - storeState.nodeTransactionSubscriptions.delete(node); - storeState.retention.referenceCounts.delete(node); - const zones = zonesThatCouldRetainNode(node); - for (const zone of zones) { - var _storeState$retention2; - (_storeState$retention2 = storeState.retention.nodesRetainedByZone.get(zone)) === null || _storeState$retention2 === void 0 ? void 0 : _storeState$retention2.delete(node); - } - treeState.atomValues.delete(node); - treeState.dirtyAtoms.delete(node); - treeState.nonvalidatedAtoms.delete(node); - const graph2 = storeState.graphsByVersion.get(treeState.version); - if (graph2) { - const deps = graph2.nodeDeps.get(node); - if (deps !== void 0) { - graph2.nodeDeps.delete(node); - for (const dep of deps) { - var _graph$nodeToNodeSubs; - (_graph$nodeToNodeSubs = graph2.nodeToNodeSubscriptions.get(dep)) === null || _graph$nodeToNodeSubs === void 0 ? void 0 : _graph$nodeToNodeSubs.delete(node); - } - } - graph2.nodeToNodeSubscriptions.delete(node); - } - deleteNodeConfigIfPossible$1(node); -} -function nodesRetainedByZone(storeState, zone) { - var _storeState$retention3; - return (_storeState$retention3 = storeState.retention.nodesRetainedByZone.get(zone)) !== null && _storeState$retention3 !== void 0 ? _storeState$retention3 : emptySet$1; -} -function zonesThatCouldRetainNode(node) { - const retainedBy = getNode$2(node).retainedBy; - if (retainedBy === void 0 || retainedBy === "components" || retainedBy === "recoilRoot") { - return []; - } else if (retainedBy instanceof RetentionZone$2) { - return [retainedBy]; - } else { - return retainedBy; +function canUseFileSystemAccessAPI() { + return "showOpenFilePicker" in window; +} +function pickerOptionsFromAccept(accept) { + if (isDefined(accept)) { + var acceptForPicker = Object.entries(accept).filter(function(_ref2) { + var _ref3 = _slicedToArray(_ref2, 2), mimeType = _ref3[0], ext = _ref3[1]; + var ok = true; + if (!isMIMEType(mimeType)) { + console.warn('Skipped "'.concat(mimeType, '" because it is not a valid MIME type. Check https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types/Common_types for a list of valid MIME types.')); + ok = false; + } + if (!Array.isArray(ext) || !ext.every(isExt)) { + console.warn('Skipped "'.concat(mimeType, '" because an invalid file extension was provided.')); + ok = false; + } + return ok; + }).reduce(function(agg, _ref4) { + var _ref5 = _slicedToArray(_ref4, 2), mimeType = _ref5[0], ext = _ref5[1]; + return _objectSpread(_objectSpread({}, agg), {}, _defineProperty({}, mimeType, ext)); + }, {}); + return [{ + description: "Files", + accept: acceptForPicker + }]; + } + return accept; +} +function acceptPropAsAcceptAttr(accept) { + if (isDefined(accept)) { + return Object.entries(accept).reduce(function(a5, _ref6) { + var _ref7 = _slicedToArray(_ref6, 2), mimeType = _ref7[0], ext = _ref7[1]; + return [].concat(_toConsumableArray(a5), [mimeType], _toConsumableArray(ext)); + }, []).filter(function(v3) { + return isMIMEType(v3) || isExt(v3); + }).join(","); } + return void 0; } -function scheduleOrPerformPossibleReleaseOfRetainable(store, retainable) { - const state = store.getState(); - if (state.nextTree) { - state.retention.retainablesToCheckForRelease.add(retainable); - } else { - releaseRetainablesNowOnCurrentTree(store, /* @__PURE__ */ new Set([retainable])); - } +function isAbort(v3) { + return v3 instanceof DOMException && (v3.name === "AbortError" || v3.code === v3.ABORT_ERR); } -function updateRetainCount(store, retainable, delta) { - var _map$get; - if (!Recoil_gkx_1("recoil_memory_managament_2020")) { - return; - } - const map = store.getState().retention.referenceCounts; - const newCount = ((_map$get = map.get(retainable)) !== null && _map$get !== void 0 ? _map$get : 0) + delta; - if (newCount === 0) { - updateRetainCountToZero(store, retainable); - } else { - map.set(retainable, newCount); - } +function isSecurityError(v3) { + return v3 instanceof DOMException && (v3.name === "SecurityError" || v3.code === v3.SECURITY_ERR); } -function updateRetainCountToZero(store, retainable) { - if (!Recoil_gkx_1("recoil_memory_managament_2020")) { - return; - } - const map = store.getState().retention.referenceCounts; - map.delete(retainable); - scheduleOrPerformPossibleReleaseOfRetainable(store, retainable); +function isMIMEType(v3) { + return v3 === "audio/*" || v3 === "video/*" || v3 === "image/*" || v3 === "text/*" || /\w+\/[-+.\w]+/g.test(v3); } -function releaseScheduledRetainablesNow(store) { - if (!Recoil_gkx_1("recoil_memory_managament_2020")) { - return; - } - const state = store.getState(); - releaseRetainablesNowOnCurrentTree(store, state.retention.retainablesToCheckForRelease); - state.retention.retainablesToCheckForRelease.clear(); +function isExt(v3) { + return /^.*\.[\w]+$/.test(v3); } -function retainedByOptionWithDefault(r3) { - return r3 === void 0 ? "recoilRoot" : r3; + +// node_modules/react-dropzone/dist/es/index.js +var _excluded = ["children"]; +var _excluded2 = ["open"]; +var _excluded3 = ["refKey", "role", "onKeyDown", "onFocus", "onBlur", "onClick", "onDragEnter", "onDragOver", "onDragLeave", "onDrop"]; +var _excluded4 = ["refKey", "onChange", "onClick"]; +function _toConsumableArray2(arr) { + return _arrayWithoutHoles2(arr) || _iterableToArray2(arr) || _unsupportedIterableToArray2(arr) || _nonIterableSpread2(); } -var Recoil_Retention = { - updateRetainCount, - updateRetainCountToZero, - releaseScheduledRetainablesNow, - retainedByOptionWithDefault -}; -function* concatIterables(iters) { - for (const iter of iters) { - for (const val of iter) { - yield val; - } - } +function _nonIterableSpread2() { + throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } -var Recoil_concatIterables = concatIterables; -var isSSR = typeof window === "undefined"; -var isReactNative = typeof navigator !== "undefined" && navigator.product === "ReactNative"; -var Recoil_Environment = { - isSSR, - isReactNative -}; -var { - isSSR: isSSR$1 -} = Recoil_Environment; -var { - batchUpdates: batchUpdates$1 -} = Recoil_Batching; -var { - initializeNodeIfNewToStore: initializeNodeIfNewToStore$1, - peekNodeInfo: peekNodeInfo$1 -} = Recoil_FunctionalCore; -var { - graph: graph$2 -} = Recoil_Graph; -var { - DEFAULT_VALUE: DEFAULT_VALUE$1, - recoilValues: recoilValues$1, - recoilValuesForKeys: recoilValuesForKeys$2 -} = Recoil_Node; -var { - AbstractRecoilValue: AbstractRecoilValue$2, - getRecoilValueAsLoadable: getRecoilValueAsLoadable$1, - setRecoilValue: setRecoilValue$1, - setUnvalidatedRecoilValue: setUnvalidatedRecoilValue$1 -} = Recoil_RecoilValueInterface; -var { - updateRetainCount: updateRetainCount$1 -} = Recoil_Retention; -var { - getNextTreeStateVersion: getNextTreeStateVersion$1, - makeEmptyStoreState: makeEmptyStoreState$1 -} = Recoil_State; -var retainWarning = ` -Recoil Snapshots only last for the duration of the callback they are provided to. To keep a Snapshot longer, do this: - - const release = snapshot.retain(); +function _iterableToArray2(iter) { + if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) + return Array.from(iter); +} +function _arrayWithoutHoles2(arr) { + if (Array.isArray(arr)) + return _arrayLikeToArray2(arr); +} +function _slicedToArray2(arr, i4) { + return _arrayWithHoles2(arr) || _iterableToArrayLimit2(arr, i4) || _unsupportedIterableToArray2(arr, i4) || _nonIterableRest2(); +} +function _nonIterableRest2() { + throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); +} +function _unsupportedIterableToArray2(o3, minLen) { + if (!o3) + return; + if (typeof o3 === "string") + return _arrayLikeToArray2(o3, minLen); + var n2 = Object.prototype.toString.call(o3).slice(8, -1); + if (n2 === "Object" && o3.constructor) + n2 = o3.constructor.name; + if (n2 === "Map" || n2 === "Set") + return Array.from(o3); + if (n2 === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n2)) + return _arrayLikeToArray2(o3, minLen); +} +function _arrayLikeToArray2(arr, len) { + if (len == null || len > arr.length) + len = arr.length; + for (var i4 = 0, arr2 = new Array(len); i4 < len; i4++) { + arr2[i4] = arr[i4]; + } + return arr2; +} +function _iterableToArrayLimit2(arr, i4) { + var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]; + if (_i == null) + return; + var _arr = []; + var _n2 = true; + var _d2 = false; + var _s, _e2; try { - await useTheSnapshotAsynchronously(snapshot); - } finally { - release(); - } - -This is currently a DEV-only warning but will become a thrown exception in the next release of Recoil. -`; -var Snapshot = class { - constructor(storeState) { - _defineProperty(this, "_store", void 0); - _defineProperty(this, "_refCount", 0); - _defineProperty(this, "getLoadable", (recoilValue) => { - this.checkRefCount_INTERNAL(); - return getRecoilValueAsLoadable$1(this._store, recoilValue); - }); - _defineProperty(this, "getPromise", (recoilValue) => { - this.checkRefCount_INTERNAL(); - return this.getLoadable(recoilValue).toPromise(); - }); - _defineProperty(this, "getNodes_UNSTABLE", (opt) => { - this.checkRefCount_INTERNAL(); - if ((opt === null || opt === void 0 ? void 0 : opt.isModified) === true) { - if ((opt === null || opt === void 0 ? void 0 : opt.isInitialized) === false) { - return []; - } - const state = this._store.getState().currentTree; - return recoilValuesForKeys$2(state.dirtyAtoms); - } - const knownAtoms = this._store.getState().knownAtoms; - const knownSelectors = this._store.getState().knownSelectors; - return (opt === null || opt === void 0 ? void 0 : opt.isInitialized) == null ? recoilValues$1.values() : opt.isInitialized === true ? recoilValuesForKeys$2(Recoil_concatIterables([this._store.getState().knownAtoms, this._store.getState().knownSelectors])) : Recoil_filterIterable(recoilValues$1.values(), ({ - key: key2 - }) => !knownAtoms.has(key2) && !knownSelectors.has(key2)); - }); - _defineProperty(this, "getInfo_UNSTABLE", ({ - key: key2 - }) => { - this.checkRefCount_INTERNAL(); - return peekNodeInfo$1(this._store, this._store.getState().currentTree, key2); - }); - _defineProperty(this, "map", (mapper) => { - this.checkRefCount_INTERNAL(); - const mutableSnapshot = new MutableSnapshot(this, batchUpdates$1); - mapper(mutableSnapshot); - return cloneSnapshot(mutableSnapshot.getStore_INTERNAL()); - }); - _defineProperty(this, "asyncMap", async (mapper) => { - this.checkRefCount_INTERNAL(); - const mutableSnapshot = new MutableSnapshot(this, batchUpdates$1); - await mapper(mutableSnapshot); - return cloneSnapshot(mutableSnapshot.getStore_INTERNAL()); - }); - this._store = { - getState: () => storeState, - replaceState: (replacer) => { - storeState.currentTree = replacer(storeState.currentTree); - }, - getGraph: (version) => { - const graphs = storeState.graphsByVersion; - if (graphs.has(version)) { - return Recoil_nullthrows(graphs.get(version)); - } - const newGraph = graph$2(); - graphs.set(version, newGraph); - return newGraph; - }, - subscribeToTransactions: () => ({ - release: () => { - } - }), - addTransactionMetadata: () => { - throw new Error("Cannot subscribe to Snapshots"); - } - }; - for (const nodeKey of this._store.getState().nodeCleanupFunctions.keys()) { - initializeNodeIfNewToStore$1(this._store, storeState.currentTree, nodeKey, "get"); - updateRetainCount$1(this._store, nodeKey, 1); - } - this.retain(); - this.autorelease_INTERNAL(); - } - retain() { - if (!Recoil_gkx_1("recoil_memory_managament_2020")) { - return () => void 0; - } - this._refCount++; - let released = false; - return () => { - if (!released) { - released = true; - this.release_INTERNAL(); - } - }; - } - autorelease_INTERNAL() { - if (!Recoil_gkx_1("recoil_memory_managament_2020")) { - return; - } - if (!isSSR$1) { - window.setTimeout(() => this.release_INTERNAL(), 0); - } - } - release_INTERNAL() { - if (!Recoil_gkx_1("recoil_memory_managament_2020")) { - return; + for (_i = _i.call(arr); !(_n2 = (_s = _i.next()).done); _n2 = true) { + _arr.push(_s.value); + if (i4 && _arr.length === i4) + break; } - this._refCount--; - if (this._refCount === 0) - ; - } - checkRefCount_INTERNAL() { - if (Recoil_gkx_1("recoil_memory_managament_2020") && this._refCount <= 0) { - if (true) { - Recoil_recoverableViolation(retainWarning); - } + } catch (err) { + _d2 = true; + _e2 = err; + } finally { + try { + if (!_n2 && _i["return"] != null) + _i["return"](); + } finally { + if (_d2) + throw _e2; } } - getStore_INTERNAL() { - this.checkRefCount_INTERNAL(); - return this._store; - } - getID() { - this.checkRefCount_INTERNAL(); - return this.getID_INTERNAL(); - } - getID_INTERNAL() { - this.checkRefCount_INTERNAL(); - return this._store.getState().currentTree.stateID; + return _arr; +} +function _arrayWithHoles2(arr) { + if (Array.isArray(arr)) + return arr; +} +function ownKeys2(object, enumerableOnly) { + var keys = Object.keys(object); + if (Object.getOwnPropertySymbols) { + var symbols = Object.getOwnPropertySymbols(object); + enumerableOnly && (symbols = symbols.filter(function(sym) { + return Object.getOwnPropertyDescriptor(object, sym).enumerable; + })), keys.push.apply(keys, symbols); } -}; -function cloneStoreState(store, treeState, bumpVersion = false) { - const storeState = store.getState(); - const version = bumpVersion ? getNextTreeStateVersion$1() : treeState.version; - return { - currentTree: bumpVersion ? { - version, - stateID: version, - transactionMetadata: { - ...treeState.transactionMetadata - }, - dirtyAtoms: new Set(treeState.dirtyAtoms), - atomValues: treeState.atomValues.clone(), - nonvalidatedAtoms: treeState.nonvalidatedAtoms.clone() - } : treeState, - commitDepth: 0, - nextTree: null, - previousTree: null, - knownAtoms: new Set(storeState.knownAtoms), - knownSelectors: new Set(storeState.knownSelectors), - transactionSubscriptions: /* @__PURE__ */ new Map(), - nodeTransactionSubscriptions: /* @__PURE__ */ new Map(), - nodeToComponentSubscriptions: /* @__PURE__ */ new Map(), - queuedComponentCallbacks_DEPRECATED: [], - suspendedComponentResolvers: /* @__PURE__ */ new Set(), - graphsByVersion: (/* @__PURE__ */ new Map()).set(version, store.getGraph(treeState.version)), - versionsUsedByComponent: /* @__PURE__ */ new Map(), - retention: { - referenceCounts: /* @__PURE__ */ new Map(), - nodesRetainedByZone: /* @__PURE__ */ new Map(), - retainablesToCheckForRelease: /* @__PURE__ */ new Set() - }, - nodeCleanupFunctions: /* @__PURE__ */ new Map() - }; -} -function freshSnapshot(initializeState) { - const snapshot = new Snapshot(makeEmptyStoreState$1()); - return initializeState != null ? snapshot.map(initializeState) : snapshot; -} -function cloneSnapshot(store, version = "current") { - const storeState = store.getState(); - const treeState = version === "current" ? storeState.currentTree : Recoil_nullthrows(storeState.previousTree); - return new Snapshot(cloneStoreState(store, treeState)); -} -var MutableSnapshot = class extends Snapshot { - constructor(snapshot, batch) { - super(cloneStoreState(snapshot.getStore_INTERNAL(), snapshot.getStore_INTERNAL().getState().currentTree, true)); - _defineProperty(this, "_batch", void 0); - _defineProperty(this, "set", (recoilState, newValueOrUpdater) => { - this.checkRefCount_INTERNAL(); - const store = this.getStore_INTERNAL(); - this._batch(() => { - updateRetainCount$1(store, recoilState.key, 1); - setRecoilValue$1(this.getStore_INTERNAL(), recoilState, newValueOrUpdater); - }); - }); - _defineProperty(this, "reset", (recoilState) => { - this.checkRefCount_INTERNAL(); - const store = this.getStore_INTERNAL(); - this._batch(() => { - updateRetainCount$1(store, recoilState.key, 1); - setRecoilValue$1(this.getStore_INTERNAL(), recoilState, DEFAULT_VALUE$1); - }); - }); - _defineProperty(this, "setUnvalidatedAtomValues_DEPRECATED", (values) => { - this.checkRefCount_INTERNAL(); - const store = this.getStore_INTERNAL(); - batchUpdates$1(() => { - for (const [k5, v3] of values.entries()) { - updateRetainCount$1(store, k5, 1); - setUnvalidatedRecoilValue$1(store, new AbstractRecoilValue$2(k5), v3); - } - }); + return keys; +} +function _objectSpread2(target) { + for (var i4 = 1; i4 < arguments.length; i4++) { + var source = null != arguments[i4] ? arguments[i4] : {}; + i4 % 2 ? ownKeys2(Object(source), true).forEach(function(key2) { + _defineProperty2(target, key2, source[key2]); + }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys2(Object(source)).forEach(function(key2) { + Object.defineProperty(target, key2, Object.getOwnPropertyDescriptor(source, key2)); }); - this._batch = batch; - } -}; -var Recoil_Snapshot = { - Snapshot, - MutableSnapshot, - freshSnapshot, - cloneSnapshot -}; -var Recoil_Snapshot_1 = Recoil_Snapshot.Snapshot; -var Recoil_Snapshot_2 = Recoil_Snapshot.MutableSnapshot; -var Recoil_Snapshot_3 = Recoil_Snapshot.freshSnapshot; -var Recoil_Snapshot_4 = Recoil_Snapshot.cloneSnapshot; -var Recoil_Snapshot$1 = /* @__PURE__ */ Object.freeze({ - __proto__: null, - Snapshot: Recoil_Snapshot_1, - MutableSnapshot: Recoil_Snapshot_2, - freshSnapshot: Recoil_Snapshot_3, - cloneSnapshot: Recoil_Snapshot_4 -}); -var { - getNextTreeStateVersion: getNextTreeStateVersion$2, - makeEmptyStoreState: makeEmptyStoreState$2 -} = Recoil_State; -var { - cleanUpNode: cleanUpNode$2, - getDownstreamNodes: getDownstreamNodes$2, - setNodeValue: setNodeValue$2, - setUnvalidatedAtomValue_DEPRECATED: setUnvalidatedAtomValue_DEPRECATED$1 -} = Recoil_FunctionalCore; -var { - graph: graph$3 -} = Recoil_Graph; -var { - cloneGraph: cloneGraph$1 -} = Recoil_Graph; -var { - applyAtomValueWrites: applyAtomValueWrites$1 -} = Recoil_RecoilValueInterface; -var { - releaseScheduledRetainablesNow: releaseScheduledRetainablesNow$1 -} = Recoil_Retention; -var { - freshSnapshot: freshSnapshot$1 -} = Recoil_Snapshot$1; -var { - useCallback, - useContext, - useEffect, - useMemo, - useRef, - useState -} = Cn; -function notInAContext() { - throw new Error("This component must be used inside a component."); -} -var defaultStore = Object.freeze({ - getState: notInAContext, - replaceState: notInAContext, - getGraph: notInAContext, - subscribeToTransactions: notInAContext, - addTransactionMetadata: notInAContext -}); -var stateReplacerIsBeingExecuted = false; -function startNextTreeIfNeeded(store) { - if (stateReplacerIsBeingExecuted) { - throw new Error("An atom update was triggered within the execution of a state updater function. State updater functions provided to Recoil must be pure functions."); - } - const storeState = store.getState(); - if (storeState.nextTree === null) { - if (Recoil_gkx_1("recoil_memory_managament_2020") && Recoil_gkx_1("recoil_release_on_cascading_update_killswitch_2021")) { - if (storeState.commitDepth > 0) { - releaseScheduledRetainablesNow$1(store); - } - } - const version = storeState.currentTree.version; - const nextVersion = getNextTreeStateVersion$2(); - storeState.nextTree = { - ...storeState.currentTree, - version: nextVersion, - stateID: nextVersion, - dirtyAtoms: /* @__PURE__ */ new Set(), - transactionMetadata: {} - }; - storeState.graphsByVersion.set(nextVersion, cloneGraph$1(Recoil_nullthrows(storeState.graphsByVersion.get(version)))); } + return target; } -var AppContext = Cn.createContext({ - current: defaultStore -}); -var useStoreRef = () => useContext(AppContext); -var MutableSourceContext = Cn.createContext(null); -function useRecoilMutableSource() { - const mutableSource = useContext(MutableSourceContext); - if (mutableSource == null) { - Recoil_expectationViolation("Attempted to use a Recoil hook outside of a . must be an ancestor of any component that uses Recoil hooks."); +function _defineProperty2(obj, key2, value) { + if (key2 in obj) { + Object.defineProperty(obj, key2, { value, enumerable: true, configurable: true, writable: true }); + } else { + obj[key2] = value; } - return mutableSource; + return obj; } -function notifyComponents(store, storeState, treeState) { - const dependentNodes = getDownstreamNodes$2(store, treeState, treeState.dirtyAtoms); - for (const key2 of dependentNodes) { - const comps = storeState.nodeToComponentSubscriptions.get(key2); - if (comps) { - for (const [_subID, [_debugName, callback]] of comps) { - callback(treeState); - } +function _objectWithoutProperties(source, excluded) { + if (source == null) + return {}; + var target = _objectWithoutPropertiesLoose(source, excluded); + var key2, i4; + if (Object.getOwnPropertySymbols) { + var sourceSymbolKeys = Object.getOwnPropertySymbols(source); + for (i4 = 0; i4 < sourceSymbolKeys.length; i4++) { + key2 = sourceSymbolKeys[i4]; + if (excluded.indexOf(key2) >= 0) + continue; + if (!Object.prototype.propertyIsEnumerable.call(source, key2)) + continue; + target[key2] = source[key2]; } } + return target; } -function sendEndOfBatchNotifications(store) { - const storeState = store.getState(); - const treeState = storeState.currentTree; - const dirtyAtoms = treeState.dirtyAtoms; - if (dirtyAtoms.size) { - for (const [key2, subscriptions] of storeState.nodeTransactionSubscriptions) { - if (dirtyAtoms.has(key2)) { - for (const [_9, subscription] of subscriptions) { - subscription(store); - } - } - } - for (const [_9, subscription] of storeState.transactionSubscriptions) { - subscription(store); - } - if (!Recoil_gkx_1("recoil_early_rendering_2021") || storeState.suspendedComponentResolvers.size) { - notifyComponents(store, storeState, treeState); - storeState.suspendedComponentResolvers.forEach((cb) => cb()); - storeState.suspendedComponentResolvers.clear(); - } +function _objectWithoutPropertiesLoose(source, excluded) { + if (source == null) + return {}; + var target = {}; + var sourceKeys = Object.keys(source); + var key2, i4; + for (i4 = 0; i4 < sourceKeys.length; i4++) { + key2 = sourceKeys[i4]; + if (excluded.indexOf(key2) >= 0) + continue; + target[key2] = source[key2]; } - storeState.queuedComponentCallbacks_DEPRECATED.forEach((cb) => cb(treeState)); - storeState.queuedComponentCallbacks_DEPRECATED.splice(0, storeState.queuedComponentCallbacks_DEPRECATED.length); + return target; } -function endBatch(storeRef) { - const storeState = storeRef.current.getState(); - storeState.commitDepth++; - try { - const { - nextTree - } = storeState; - if (nextTree === null) { +var Dropzone = /* @__PURE__ */ k3(function(_ref, ref2) { + var children = _ref.children, params = _objectWithoutProperties(_ref, _excluded); + var _useDropzone = useDropzone(params), open = _useDropzone.open, props2 = _objectWithoutProperties(_useDropzone, _excluded2); + A2(ref2, function() { + return { + open + }; + }, [open]); + return /* @__PURE__ */ Cn.createElement(_, null, children(_objectSpread2(_objectSpread2({}, props2), {}, { + open + }))); +}); +Dropzone.displayName = "Dropzone"; +var defaultProps2 = { + disabled: false, + getFilesFromEvent: fromEvent, + maxSize: Infinity, + minSize: 0, + multiple: true, + maxFiles: 0, + preventDropOnDocument: true, + noClick: false, + noKeyboard: false, + noDrag: false, + noDragEventsBubbling: false, + validator: null, + useFsAccessApi: true, + autoFocus: false +}; +Dropzone.defaultProps = defaultProps2; +Dropzone.propTypes = { + children: import_prop_types.default.func, + accept: import_prop_types.default.objectOf(import_prop_types.default.arrayOf(import_prop_types.default.string)), + multiple: import_prop_types.default.bool, + preventDropOnDocument: import_prop_types.default.bool, + noClick: import_prop_types.default.bool, + noKeyboard: import_prop_types.default.bool, + noDrag: import_prop_types.default.bool, + noDragEventsBubbling: import_prop_types.default.bool, + minSize: import_prop_types.default.number, + maxSize: import_prop_types.default.number, + maxFiles: import_prop_types.default.number, + disabled: import_prop_types.default.bool, + getFilesFromEvent: import_prop_types.default.func, + onFileDialogCancel: import_prop_types.default.func, + onFileDialogOpen: import_prop_types.default.func, + useFsAccessApi: import_prop_types.default.bool, + autoFocus: import_prop_types.default.bool, + onDragEnter: import_prop_types.default.func, + onDragLeave: import_prop_types.default.func, + onDragOver: import_prop_types.default.func, + onDrop: import_prop_types.default.func, + onDropAccepted: import_prop_types.default.func, + onDropRejected: import_prop_types.default.func, + onError: import_prop_types.default.func, + validator: import_prop_types.default.func +}; +var initialState = { + isFocused: false, + isFileDialogActive: false, + isDragActive: false, + isDragAccept: false, + isDragReject: false, + acceptedFiles: [], + fileRejections: [] +}; +function useDropzone() { + var props2 = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {}; + var _defaultProps$props = _objectSpread2(_objectSpread2({}, defaultProps2), props2), accept = _defaultProps$props.accept, disabled = _defaultProps$props.disabled, getFilesFromEvent = _defaultProps$props.getFilesFromEvent, maxSize = _defaultProps$props.maxSize, minSize = _defaultProps$props.minSize, multiple = _defaultProps$props.multiple, maxFiles = _defaultProps$props.maxFiles, onDragEnter = _defaultProps$props.onDragEnter, onDragLeave = _defaultProps$props.onDragLeave, onDragOver = _defaultProps$props.onDragOver, onDrop = _defaultProps$props.onDrop, onDropAccepted = _defaultProps$props.onDropAccepted, onDropRejected = _defaultProps$props.onDropRejected, onFileDialogCancel = _defaultProps$props.onFileDialogCancel, onFileDialogOpen = _defaultProps$props.onFileDialogOpen, useFsAccessApi = _defaultProps$props.useFsAccessApi, autoFocus = _defaultProps$props.autoFocus, preventDropOnDocument = _defaultProps$props.preventDropOnDocument, noClick = _defaultProps$props.noClick, noKeyboard = _defaultProps$props.noKeyboard, noDrag = _defaultProps$props.noDrag, noDragEventsBubbling = _defaultProps$props.noDragEventsBubbling, onError = _defaultProps$props.onError, validator = _defaultProps$props.validator; + var acceptAttr = F2(function() { + return acceptPropAsAcceptAttr(accept); + }, [accept]); + var pickerTypes = F2(function() { + return pickerOptionsFromAccept(accept); + }, [accept]); + var onFileDialogOpenCb = F2(function() { + return typeof onFileDialogOpen === "function" ? onFileDialogOpen : noop2; + }, [onFileDialogOpen]); + var onFileDialogCancelCb = F2(function() { + return typeof onFileDialogCancel === "function" ? onFileDialogCancel : noop2; + }, [onFileDialogCancel]); + var rootRef = _2(null); + var inputRef = _2(null); + var _useReducer = s2(reducer2, initialState), _useReducer2 = _slicedToArray2(_useReducer, 2), state = _useReducer2[0], dispatch = _useReducer2[1]; + var isFocused = state.isFocused, isFileDialogActive = state.isFileDialogActive; + var fsAccessApiWorksRef = _2(typeof window !== "undefined" && window.isSecureContext && useFsAccessApi && canUseFileSystemAccessAPI()); + var onWindowFocus = function onWindowFocus2() { + if (!fsAccessApiWorksRef.current && isFileDialogActive) { + setTimeout(function() { + if (inputRef.current) { + var files = inputRef.current.files; + if (!files.length) { + dispatch({ + type: "closeDialog" + }); + onFileDialogCancelCb(); + } + } + }, 300); + } + }; + p2(function() { + window.addEventListener("focus", onWindowFocus, false); + return function() { + window.removeEventListener("focus", onWindowFocus, false); + }; + }, [inputRef, isFileDialogActive, onFileDialogCancelCb, fsAccessApiWorksRef]); + var dragTargetsRef = _2([]); + var onDocumentDrop = function onDocumentDrop2(event) { + if (rootRef.current && rootRef.current.contains(event.target)) { return; } - storeState.previousTree = storeState.currentTree; - storeState.currentTree = nextTree; - storeState.nextTree = null; - sendEndOfBatchNotifications(storeRef.current); - if (storeState.previousTree != null) { - storeState.graphsByVersion.delete(storeState.previousTree.version); - } else { - Recoil_recoverableViolation("Ended batch with no previous state, which is unexpected", "recoil"); + event.preventDefault(); + dragTargetsRef.current = []; + }; + p2(function() { + if (preventDropOnDocument) { + document.addEventListener("dragover", onDocumentDragOver, false); + document.addEventListener("drop", onDocumentDrop, false); } - storeState.previousTree = null; - if (Recoil_gkx_1("recoil_memory_managament_2020")) { - releaseScheduledRetainablesNow$1(storeRef.current); + return function() { + if (preventDropOnDocument) { + document.removeEventListener("dragover", onDocumentDragOver); + document.removeEventListener("drop", onDocumentDrop); + } + }; + }, [rootRef, preventDropOnDocument]); + p2(function() { + if (!disabled && autoFocus && rootRef.current) { + rootRef.current.focus(); } - } finally { - storeState.commitDepth--; - } -} -function Batcher({ - setNotifyBatcherOfChange -}) { - const storeRef = useStoreRef(); - const [_9, setState] = useState([]); - setNotifyBatcherOfChange(() => setState({})); - useEffect(() => { - Recoil_Queue.enqueueExecution("Batcher", () => { - endBatch(storeRef); - }); - }); - useEffect(() => { - return () => { - setNotifyBatcherOfChange(() => { - }); + return function() { }; - }, [setNotifyBatcherOfChange]); - return null; -} -if (true) { - if (typeof window !== "undefined" && !window.$recoilDebugStates) { - window.$recoilDebugStates = []; - } -} -function initialStoreState_DEPRECATED(store, initializeState) { - const initial = makeEmptyStoreState$2(); - initializeState({ - set: (atom2, value) => { - const state = initial.currentTree; - const writes = setNodeValue$2(store, state, atom2.key, value); - const writtenNodes = new Set(writes.keys()); - const nonvalidatedAtoms = state.nonvalidatedAtoms.clone(); - for (const n2 of writtenNodes) { - nonvalidatedAtoms.delete(n2); - } - initial.currentTree = { - ...state, - dirtyAtoms: Recoil_unionSets(state.dirtyAtoms, writtenNodes), - atomValues: applyAtomValueWrites$1(state.atomValues, writes), - nonvalidatedAtoms - }; - }, - setUnvalidatedAtomValues: (atomValues) => { - atomValues.forEach((v3, k5) => { - initial.currentTree = setUnvalidatedAtomValue_DEPRECATED$1(initial.currentTree, k5, v3); - }); + }, [rootRef, autoFocus, disabled]); + var onErrCb = T2(function(e4) { + if (onError) { + onError(e4); + } else { + console.error(e4); } - }); - return initial; -} -function initialStoreState(initializeState) { - const snapshot = freshSnapshot$1().map(initializeState); - return snapshot.getStore_INTERNAL().getState(); -} -var nextID = 0; -function RecoilRoot_INTERNAL({ - initializeState_DEPRECATED, - initializeState, - store_INTERNAL: storeProp, - children -}) { - var _createMutableSource; - let storeState; - const getGraph = (version) => { - const graphs = storeState.current.graphsByVersion; - if (graphs.has(version)) { - return Recoil_nullthrows(graphs.get(version)); - } - const newGraph = graph$3(); - graphs.set(version, newGraph); - return newGraph; - }; - const subscribeToTransactions = (callback, key2) => { - if (key2 == null) { - const { - transactionSubscriptions - } = storeRef.current.getState(); - const id2 = nextID++; - transactionSubscriptions.set(id2, callback); - return { - release: () => { - transactionSubscriptions.delete(id2); + }, [onError]); + var onDragEnterCb = T2(function(event) { + event.preventDefault(); + event.persist(); + stopPropagation2(event); + dragTargetsRef.current = [].concat(_toConsumableArray2(dragTargetsRef.current), [event.target]); + if (isEvtWithFiles(event)) { + Promise.resolve(getFilesFromEvent(event)).then(function(files) { + if (isPropagationStopped(event) && !noDragEventsBubbling) { + return; } - }; - } else { - const { - nodeTransactionSubscriptions - } = storeRef.current.getState(); - if (!nodeTransactionSubscriptions.has(key2)) { - nodeTransactionSubscriptions.set(key2, /* @__PURE__ */ new Map()); - } - const id2 = nextID++; - Recoil_nullthrows(nodeTransactionSubscriptions.get(key2)).set(id2, callback); - return { - release: () => { - const subs = nodeTransactionSubscriptions.get(key2); - if (subs) { - subs.delete(id2); - if (subs.size === 0) { - nodeTransactionSubscriptions.delete(key2); - } - } + var fileCount = files.length; + var isDragAccept = fileCount > 0 && allFilesAccepted({ + files, + accept: acceptAttr, + minSize, + maxSize, + multiple, + maxFiles, + validator + }); + var isDragReject = fileCount > 0 && !isDragAccept; + dispatch({ + isDragAccept, + isDragReject, + isDragActive: true, + type: "setDraggedFiles" + }); + if (onDragEnter) { + onDragEnter(event); } - }; + }).catch(function(e4) { + return onErrCb(e4); + }); } - }; - const addTransactionMetadata = (metadata) => { - startNextTreeIfNeeded(storeRef.current); - for (const k5 of Object.keys(metadata)) { - Recoil_nullthrows(storeRef.current.getState().nextTree).transactionMetadata[k5] = metadata[k5]; + }, [getFilesFromEvent, onDragEnter, onErrCb, noDragEventsBubbling, acceptAttr, minSize, maxSize, multiple, maxFiles, validator]); + var onDragOverCb = T2(function(event) { + event.preventDefault(); + event.persist(); + stopPropagation2(event); + var hasFiles = isEvtWithFiles(event); + if (hasFiles && event.dataTransfer) { + try { + event.dataTransfer.dropEffect = "copy"; + } catch (_unused) { + } } - }; - const replaceState = (replacer) => { - const storeState2 = storeRef.current.getState(); - startNextTreeIfNeeded(storeRef.current); - const nextTree = Recoil_nullthrows(storeState2.nextTree); - let replaced; - try { - stateReplacerIsBeingExecuted = true; - replaced = replacer(nextTree); - } finally { - stateReplacerIsBeingExecuted = false; + if (hasFiles && onDragOver) { + onDragOver(event); + } + return false; + }, [onDragOver, noDragEventsBubbling]); + var onDragLeaveCb = T2(function(event) { + event.preventDefault(); + event.persist(); + stopPropagation2(event); + var targets = dragTargetsRef.current.filter(function(target) { + return rootRef.current && rootRef.current.contains(target); + }); + var targetIdx = targets.indexOf(event.target); + if (targetIdx !== -1) { + targets.splice(targetIdx, 1); } - if (replaced === nextTree) { + dragTargetsRef.current = targets; + if (targets.length > 0) { return; } - if (true) { - if (typeof window !== "undefined") { - window.$recoilDebugStates.push(replaced); - } - } - storeState2.nextTree = replaced; - if (Recoil_gkx_1("recoil_early_rendering_2021")) { - notifyComponents(store, storeState2, replaced); - } - Recoil_nullthrows(notifyBatcherOfChange.current)(); - }; - const notifyBatcherOfChange = useRef(null); - const setNotifyBatcherOfChange = useCallback((x5) => { - notifyBatcherOfChange.current = x5; - }, [notifyBatcherOfChange]); - const createMutableSource = (_createMutableSource = Cn.createMutableSource) !== null && _createMutableSource !== void 0 ? _createMutableSource : Cn.unstable_createMutableSource; - const store = storeProp !== null && storeProp !== void 0 ? storeProp : { - getState: () => storeState.current, - replaceState, - getGraph, - subscribeToTransactions, - addTransactionMetadata - }; - const storeRef = useRef(store); - storeState = useRef(initializeState_DEPRECATED != null ? initialStoreState_DEPRECATED(store, initializeState_DEPRECATED) : initializeState != null ? initialStoreState(initializeState) : makeEmptyStoreState$2()); - const mutableSource = useMemo(() => createMutableSource ? createMutableSource(storeState, () => storeState.current.currentTree.version) : null, [createMutableSource, storeState]); - useEffect(() => () => { - for (const atomKey of storeRef.current.getState().knownAtoms) { - cleanUpNode$2(storeRef.current, atomKey); - } - }, []); - return /* @__PURE__ */ Cn.createElement(AppContext.Provider, { - value: storeRef - }, /* @__PURE__ */ Cn.createElement(MutableSourceContext.Provider, { - value: mutableSource - }, /* @__PURE__ */ Cn.createElement(Batcher, { - setNotifyBatcherOfChange - }), children)); -} -function RecoilRoot(props2) { - const { - override, - ...propsExceptOverride - } = props2; - const ancestorStoreRef = useStoreRef(); - if (override === false && ancestorStoreRef.current !== defaultStore) { - return props2.children; - } - return /* @__PURE__ */ Cn.createElement(RecoilRoot_INTERNAL, propsExceptOverride); -} -var Recoil_RecoilRoot_react = { - useStoreRef, - useRecoilMutableSource, - RecoilRoot, - notifyComponents_FOR_TESTING: notifyComponents, - sendEndOfBatchNotifications_FOR_TESTING: sendEndOfBatchNotifications -}; -var { - loadableWithValue: loadableWithValue$1 -} = Recoil_Loadable; -var { - DEFAULT_VALUE: DEFAULT_VALUE$2, - getNode: getNode$3 -} = Recoil_Node; -var { - copyTreeState: copyTreeState$1, - getRecoilValueAsLoadable: getRecoilValueAsLoadable$2, - invalidateDownstreams: invalidateDownstreams$1, - writeLoadableToTreeState: writeLoadableToTreeState$1 -} = Recoil_RecoilValueInterface; -function isAtom(recoilValue) { - return getNode$3(recoilValue.key).nodeType === "atom"; -} -var TransactionInterfaceImpl = class { - constructor(store, treeState) { - _defineProperty(this, "_store", void 0); - _defineProperty(this, "_treeState", void 0); - _defineProperty(this, "_changes", void 0); - _defineProperty(this, "get", (recoilValue) => { - if (this._changes.has(recoilValue.key)) { - return this._changes.get(recoilValue.key); - } - if (!isAtom(recoilValue)) { - throw new Error("Reading selectors within atomicUpdate is not supported"); - } - const loadable = getRecoilValueAsLoadable$2(this._store, recoilValue, this._treeState); - if (loadable.state === "hasValue") { - return loadable.contents; - } else if (loadable.state === "hasError") { - throw loadable.contents; - } else { - throw new Error(`Expected Recoil atom ${recoilValue.key} to have a value, but it is in a loading state.`); - } + dispatch({ + type: "setDraggedFiles", + isDragActive: false, + isDragAccept: false, + isDragReject: false }); - _defineProperty(this, "set", (recoilState, valueOrUpdater) => { - if (!isAtom(recoilState)) { - throw new Error("Setting selectors within atomicUpdate is not supported"); - } - if (typeof valueOrUpdater === "function") { - const current = this.get(recoilState); - this._changes.set(recoilState.key, valueOrUpdater(current)); + if (isEvtWithFiles(event) && onDragLeave) { + onDragLeave(event); + } + }, [rootRef, onDragLeave, noDragEventsBubbling]); + var setFiles = T2(function(files, event) { + var acceptedFiles = []; + var fileRejections = []; + files.forEach(function(file) { + var _fileAccepted = fileAccepted(file, acceptAttr), _fileAccepted2 = _slicedToArray2(_fileAccepted, 2), accepted = _fileAccepted2[0], acceptError = _fileAccepted2[1]; + var _fileMatchSize = fileMatchSize(file, minSize, maxSize), _fileMatchSize2 = _slicedToArray2(_fileMatchSize, 2), sizeMatch = _fileMatchSize2[0], sizeError = _fileMatchSize2[1]; + var customErrors = validator ? validator(file) : null; + if (accepted && sizeMatch && !customErrors) { + acceptedFiles.push(file); } else { - this._changes.set(recoilState.key, valueOrUpdater); + var errors = [acceptError, sizeError]; + if (customErrors) { + errors = errors.concat(customErrors); + } + fileRejections.push({ + file, + errors: errors.filter(function(e4) { + return e4; + }) + }); } }); - _defineProperty(this, "reset", (recoilState) => { - this.set(recoilState, DEFAULT_VALUE$2); + if (!multiple && acceptedFiles.length > 1 || multiple && maxFiles >= 1 && acceptedFiles.length > maxFiles) { + acceptedFiles.forEach(function(file) { + fileRejections.push({ + file, + errors: [TOO_MANY_FILES_REJECTION] + }); + }); + acceptedFiles.splice(0); + } + dispatch({ + acceptedFiles, + fileRejections, + type: "setFiles" }); - this._store = store; - this._treeState = treeState; - this._changes = /* @__PURE__ */ new Map(); - } - newTreeState_INTERNAL() { - if (this._changes.size === 0) { - return this._treeState; + if (onDrop) { + onDrop(acceptedFiles, fileRejections, event); } - const newState = copyTreeState$1(this._treeState); - for (const [k5, v3] of this._changes) { - writeLoadableToTreeState$1(newState, k5, loadableWithValue$1(v3)); + if (fileRejections.length > 0 && onDropRejected) { + onDropRejected(fileRejections, event); } - invalidateDownstreams$1(this._store, newState); - return newState; - } -}; -function atomicUpdater(store) { - return (fn2) => { - store.replaceState((treeState) => { - const changeset = new TransactionInterfaceImpl(store, treeState); - fn2(changeset); - return changeset.newTreeState_INTERNAL(); - }); - }; -} -var Recoil_AtomicUpdates = { - atomicUpdater -}; -var Recoil_AtomicUpdates_1 = Recoil_AtomicUpdates.atomicUpdater; -var Recoil_AtomicUpdates$1 = /* @__PURE__ */ Object.freeze({ - __proto__: null, - atomicUpdater: Recoil_AtomicUpdates_1 -}); -function filterMap(map, callback) { - const result = /* @__PURE__ */ new Map(); - for (const [key2, value] of map) { - if (callback(value, key2)) { - result.set(key2, value); + if (acceptedFiles.length > 0 && onDropAccepted) { + onDropAccepted(acceptedFiles, event); } - } - return result; -} -var Recoil_filterMap = filterMap; -function filterSet(set, callback) { - const result = /* @__PURE__ */ new Set(); - for (const value of set) { - if (callback(value)) { - result.add(value); + }, [dispatch, multiple, acceptAttr, minSize, maxSize, maxFiles, onDrop, onDropAccepted, onDropRejected, validator]); + var onDropCb = T2(function(event) { + event.preventDefault(); + event.persist(); + stopPropagation2(event); + dragTargetsRef.current = []; + if (isEvtWithFiles(event)) { + Promise.resolve(getFilesFromEvent(event)).then(function(files) { + if (isPropagationStopped(event) && !noDragEventsBubbling) { + return; + } + setFiles(files, event); + }).catch(function(e4) { + return onErrCb(e4); + }); } - } - return result; -} -var Recoil_filterSet = filterSet; -function invariant(condition, message) { - if (!condition) { - throw new Error(message); - } -} -var invariant_1 = invariant; -var Recoil_invariant = invariant_1; -function mergeMaps(...maps) { - const result = /* @__PURE__ */ new Map(); - for (let i4 = 0; i4 < maps.length; i4++) { - const iterator = maps[i4].keys(); - let nextKey; - while (!(nextKey = iterator.next()).done) { - result.set(nextKey.value, maps[i4].get(nextKey.value)); + dispatch({ + type: "reset" + }); + }, [getFilesFromEvent, setFiles, onErrCb, noDragEventsBubbling]); + var openFileDialog = T2(function() { + if (fsAccessApiWorksRef.current) { + dispatch({ + type: "openDialog" + }); + onFileDialogOpenCb(); + var opts = { + multiple, + types: pickerTypes + }; + window.showOpenFilePicker(opts).then(function(handles) { + return getFilesFromEvent(handles); + }).then(function(files) { + setFiles(files, null); + dispatch({ + type: "closeDialog" + }); + }).catch(function(e4) { + if (isAbort(e4)) { + onFileDialogCancelCb(e4); + dispatch({ + type: "closeDialog" + }); + } else if (isSecurityError(e4)) { + fsAccessApiWorksRef.current = false; + if (inputRef.current) { + inputRef.current.value = null; + inputRef.current.click(); + } else { + onErrCb(new Error("Cannot open the file picker because the https://developer.mozilla.org/en-US/docs/Web/API/File_System_Access_API is not supported and no was provided.")); + } + } else { + onErrCb(e4); + } + }); + return; } - } - return result; -} -var Recoil_mergeMaps = mergeMaps; -function shallowArrayEqual(a5, b4) { - if (a5 === b4) { - return true; - } - if (a5.length !== b4.length) { - return false; - } - for (let i4 = 0, l3 = a5.length; i4 < l3; i4++) { - if (a5[i4] !== b4[i4]) { - return false; + if (inputRef.current) { + dispatch({ + type: "openDialog" + }); + onFileDialogOpenCb(); + inputRef.current.value = null; + inputRef.current.click(); } - } - return true; -} -var Recoil_shallowArrayEqual = shallowArrayEqual; -var UNKNOWN_FUNCTION = ""; -function stackTraceParser(stackString) { - const lines = stackString.split("\n"); - return lines.reduce((stack, line) => { - const parseResult = parseChrome(line) || parseWinjs(line) || parseGecko(line) || parseNode(line) || parseJSC(line); - if (parseResult) { - stack.push(parseResult); + }, [dispatch, onFileDialogOpenCb, onFileDialogCancelCb, useFsAccessApi, setFiles, onErrCb, pickerTypes, multiple]); + var onKeyDownCb = T2(function(event) { + if (!rootRef.current || !rootRef.current.isEqualNode(event.target)) { + return; } - return stack; + if (event.key === " " || event.key === "Enter" || event.keyCode === 32 || event.keyCode === 13) { + event.preventDefault(); + openFileDialog(); + } + }, [rootRef, openFileDialog]); + var onFocusCb = T2(function() { + dispatch({ + type: "focus" + }); }, []); -} -var chromeRe = /^\s*at (.*?) ?\(((?:file|https?|blob|chrome-extension|native|eval|webpack||\/|[a-z]:\\|\\\\).*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i; -var chromeEvalRe = /\((\S*)(?::(\d+))(?::(\d+))\)/; -function parseChrome(line) { - const parts = chromeRe.exec(line); - if (!parts) { - return null; - } - const isNative = parts[2] && parts[2].indexOf("native") === 0; - const isEval = parts[2] && parts[2].indexOf("eval") === 0; - const submatch = chromeEvalRe.exec(parts[2]); - if (isEval && submatch != null) { - parts[2] = submatch[1]; - parts[3] = submatch[2]; - parts[4] = submatch[3]; - } - return { - file: !isNative ? parts[2] : null, - methodName: parts[1] || UNKNOWN_FUNCTION, - arguments: isNative ? [parts[2]] : [], - lineNumber: parts[3] ? +parts[3] : null, - column: parts[4] ? +parts[4] : null + var onBlurCb = T2(function() { + dispatch({ + type: "blur" + }); + }, []); + var onClickCb = T2(function() { + if (noClick) { + return; + } + if (isIeOrEdge()) { + setTimeout(openFileDialog, 0); + } else { + openFileDialog(); + } + }, [noClick, openFileDialog]); + var composeHandler = function composeHandler2(fn2) { + return disabled ? null : fn2; }; -} -var winjsRe = /^\s*at (?:((?:\[object object\])?.+) )?\(?((?:file|ms-appx|https?|webpack|blob):.*?):(\d+)(?::(\d+))?\)?\s*$/i; -function parseWinjs(line) { - const parts = winjsRe.exec(line); - if (!parts) { - return null; - } - return { - file: parts[2], - methodName: parts[1] || UNKNOWN_FUNCTION, - arguments: [], - lineNumber: +parts[3], - column: parts[4] ? +parts[4] : null - }; -} -var geckoRe = /^\s*(.*?)(?:\((.*?)\))?(?:^|@)((?:file|https?|blob|chrome|webpack|resource|\[native).*?|[^@]*bundle)(?::(\d+))?(?::(\d+))?\s*$/i; -var geckoEvalRe = /(\S+) line (\d+)(?: > eval line \d+)* > eval/i; -function parseGecko(line) { - const parts = geckoRe.exec(line); - if (!parts) { - return null; - } - const isEval = parts[3] && parts[3].indexOf(" > eval") > -1; - const submatch = geckoEvalRe.exec(parts[3]); - if (isEval && submatch != null) { - parts[3] = submatch[1]; - parts[4] = submatch[2]; - parts[5] = null; - } - return { - file: parts[3], - methodName: parts[1] || UNKNOWN_FUNCTION, - arguments: parts[2] ? parts[2].split(",") : [], - lineNumber: parts[4] ? +parts[4] : null, - column: parts[5] ? +parts[5] : null + var composeKeyboardHandler = function composeKeyboardHandler2(fn2) { + return noKeyboard ? null : composeHandler(fn2); }; -} -var javaScriptCoreRe = /^\s*(?:([^@]*)(?:\((.*?)\))?@)?(\S.*?):(\d+)(?::(\d+))?\s*$/i; -function parseJSC(line) { - const parts = javaScriptCoreRe.exec(line); - if (!parts) { - return null; - } - return { - file: parts[3], - methodName: parts[1] || UNKNOWN_FUNCTION, - arguments: [], - lineNumber: +parts[4], - column: parts[5] ? +parts[5] : null + var composeDragHandler = function composeDragHandler2(fn2) { + return noDrag ? null : composeHandler(fn2); + }; + var stopPropagation2 = function stopPropagation3(event) { + if (noDragEventsBubbling) { + event.stopPropagation(); + } }; + var getRootProps = F2(function() { + return function() { + var _ref2 = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {}, _ref2$refKey = _ref2.refKey, refKey = _ref2$refKey === void 0 ? "ref" : _ref2$refKey, role = _ref2.role, onKeyDown = _ref2.onKeyDown, onFocus = _ref2.onFocus, onBlur = _ref2.onBlur, onClick = _ref2.onClick, onDragEnter2 = _ref2.onDragEnter, onDragOver2 = _ref2.onDragOver, onDragLeave2 = _ref2.onDragLeave, onDrop2 = _ref2.onDrop, rest = _objectWithoutProperties(_ref2, _excluded3); + return _objectSpread2(_objectSpread2(_defineProperty2({ + onKeyDown: composeKeyboardHandler(composeEventHandlers(onKeyDown, onKeyDownCb)), + onFocus: composeKeyboardHandler(composeEventHandlers(onFocus, onFocusCb)), + onBlur: composeKeyboardHandler(composeEventHandlers(onBlur, onBlurCb)), + onClick: composeHandler(composeEventHandlers(onClick, onClickCb)), + onDragEnter: composeDragHandler(composeEventHandlers(onDragEnter2, onDragEnterCb)), + onDragOver: composeDragHandler(composeEventHandlers(onDragOver2, onDragOverCb)), + onDragLeave: composeDragHandler(composeEventHandlers(onDragLeave2, onDragLeaveCb)), + onDrop: composeDragHandler(composeEventHandlers(onDrop2, onDropCb)), + role: typeof role === "string" && role !== "" ? role : "presentation" + }, refKey, rootRef), !disabled && !noKeyboard ? { + tabIndex: 0 + } : {}), rest); + }; + }, [rootRef, onKeyDownCb, onFocusCb, onBlurCb, onClickCb, onDragEnterCb, onDragOverCb, onDragLeaveCb, onDropCb, noKeyboard, noDrag, disabled]); + var onInputElementClick = T2(function(event) { + event.stopPropagation(); + }, []); + var getInputProps = F2(function() { + return function() { + var _ref3 = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {}, _ref3$refKey = _ref3.refKey, refKey = _ref3$refKey === void 0 ? "ref" : _ref3$refKey, onChange = _ref3.onChange, onClick = _ref3.onClick, rest = _objectWithoutProperties(_ref3, _excluded4); + var inputProps = _defineProperty2({ + accept: acceptAttr, + multiple, + type: "file", + style: { + display: "none" + }, + onChange: composeHandler(composeEventHandlers(onChange, onDropCb)), + onClick: composeHandler(composeEventHandlers(onClick, onInputElementClick)), + tabIndex: -1 + }, refKey, inputRef); + return _objectSpread2(_objectSpread2({}, inputProps), rest); + }; + }, [inputRef, accept, multiple, onDropCb, disabled]); + return _objectSpread2(_objectSpread2({}, state), {}, { + isFocused: isFocused && !disabled, + getRootProps, + getInputProps, + rootRef, + inputRef, + open: composeHandler(openFileDialog) + }); } -var nodeRe = /^\s*at (?:((?:\[object object\])?[^\\/]+(?: \[as \S+\])?) )?\(?(.*?):(\d+)(?::(\d+))?\)?\s*$/i; -function parseNode(line) { - const parts = nodeRe.exec(line); - if (!parts) { - return null; +function reducer2(state, action) { + switch (action.type) { + case "focus": + return _objectSpread2(_objectSpread2({}, state), {}, { + isFocused: true + }); + case "blur": + return _objectSpread2(_objectSpread2({}, state), {}, { + isFocused: false + }); + case "openDialog": + return _objectSpread2(_objectSpread2({}, initialState), {}, { + isFileDialogActive: true + }); + case "closeDialog": + return _objectSpread2(_objectSpread2({}, state), {}, { + isFileDialogActive: false + }); + case "setDraggedFiles": + return _objectSpread2(_objectSpread2({}, state), {}, { + isDragActive: action.isDragActive, + isDragAccept: action.isDragAccept, + isDragReject: action.isDragReject + }); + case "setFiles": + return _objectSpread2(_objectSpread2({}, state), {}, { + acceptedFiles: action.acceptedFiles, + fileRejections: action.fileRejections + }); + case "reset": + return _objectSpread2({}, initialState); + default: + return state; } - return { - file: parts[2], - methodName: parts[1] || UNKNOWN_FUNCTION, - arguments: [], - lineNumber: +parts[3], - column: parts[4] ? +parts[4] : null - }; } -var Recoil_stackTraceParser = stackTraceParser; -var { - useRef: useRef$1 -} = Cn; -function useComponentName() { - const nameRef = useRef$1(); - if (true) { - if (Recoil_gkx_1("recoil_infer_component_names")) { - var _nameRef$current; - if (nameRef.current === void 0) { - const frames = Recoil_stackTraceParser(new Error().stack); - for (const { - methodName - } of frames) { - if (!methodName.match(/\buse[^\b]+$/)) { - return nameRef.current = methodName; - } +function noop2() { +} + +// src/components/Navigator/SpaceTree/SpaceTreeItem.tsx +var eventToModifier = (e4) => e4.altKey ? "copy" : e4.shiftKey ? "link" : "move"; +var TreeItem = k3( + ({ + childCount, + clone, + data: data2, + depth, + disableSelection, + dragActive, + disableInteraction, + ghost, + handleProps, + active, + indentationWidth, + indicator, + collapsed, + selected, + highlighted, + onCollapse, + onSelectRange, + wrapperRef, + style, + plugin, + disabled, + dragStarted, + dragOver, + dragEnded + }, ref2) => { + const { + activeFile, + setActiveFile, + selectedFiles, + setSelectedFiles, + setDragPaths + } = q2(NavigatorContext); + const [hoverTarget, setHoverTarget] = h2(null); + const innerRef = _2(null); + const [dropHighlighted, setDropHighlighted] = h2(false); + const [fileCache, setFileCache] = h2(data2.item); + const openFileAtTarget = (file, e4) => { + if (e4.shiftKey) { + onSelectRange(file.id); + return; + } + if (file.item.cacheType == "space") { + if (plugin.settings.expandFolderOnClick) { + onCollapse(data2, true); + } + openSpace( + file.item.path, + plugin, + e4.ctrlKey || e4.metaKey || e4.button == 1 ? e4.altKey ? "split" : "tab" : false + ); + setActiveFile(uriByString(plugin, file.item.path)); + setSelectedFiles([file]); + return; + } + if (!plugin.settings.contextEnabled) { + if (!file.item.isFolder) { + openAFile( + getAbstractFileAtPath(plugin, file.item.path), + plugin, + e4.ctrlKey || e4.metaKey || e4.button == 1 ? e4.altKey ? "split" : "tab" : false + ); + setActiveFile(uriByString(plugin, file.item.path)); + setSelectedFiles([file]); } - nameRef.current = null; + } else { + openAFile( + getAbstractFileAtPath(plugin, file.item.path), + plugin, + e4.ctrlKey || e4.metaKey ? e4.altKey ? "split" : "tab" : false + ); + setActiveFile(uriByString(plugin, file.item.path)); + setSelectedFiles([file]); } - return (_nameRef$current = nameRef.current) !== null && _nameRef$current !== void 0 ? _nameRef$current : ""; - } - } - return ""; -} -var Recoil_useComponentName = useComponentName; -var { - atomicUpdater: atomicUpdater$1 -} = Recoil_AtomicUpdates$1; -var { - batchUpdates: batchUpdates$2 -} = Recoil_Batching; -var { - DEFAULT_VALUE: DEFAULT_VALUE$3, - getNode: getNode$4, - nodes: nodes$1 -} = Recoil_Node; -var { - useRecoilMutableSource: useRecoilMutableSource$1, - useStoreRef: useStoreRef$1 -} = Recoil_RecoilRoot_react; -var { - isRecoilValue: isRecoilValue$2 -} = Recoil_RecoilValue$1; -var { - AbstractRecoilValue: AbstractRecoilValue$3, - getRecoilValueAsLoadable: getRecoilValueAsLoadable$3, - setRecoilValue: setRecoilValue$2, - setRecoilValueLoadable: setRecoilValueLoadable$1, - setUnvalidatedRecoilValue: setUnvalidatedRecoilValue$2, - subscribeToRecoilValue: subscribeToRecoilValue$1 -} = Recoil_RecoilValueInterface; -var { - updateRetainCount: updateRetainCount$2 -} = Recoil_Retention; -var { - RetentionZone: RetentionZone$3 -} = Recoil_RetentionZone; -var { - Snapshot: Snapshot$1, - cloneSnapshot: cloneSnapshot$1 -} = Recoil_Snapshot$1; -var { - setByAddingToSet: setByAddingToSet$2 -} = Recoil_CopyOnWrite; -var { - isSSR: isSSR$2 -} = Recoil_Environment; -var { - mutableSourceExists: mutableSourceExists$2, - useMutableSource: useMutableSource$1 -} = Recoil_mutableSource; -var { - useCallback: useCallback$1, - useEffect: useEffect$1, - useMemo: useMemo$1, - useRef: useRef$2, - useState: useState$1 -} = Cn; -var SUSPENSE_TIMEOUT_MS = 12e4; -function handleLoadable(loadable, recoilValue, storeRef) { - if (loadable.state === "hasValue") { - return loadable.contents; - } else if (loadable.state === "loading") { - const promise = new Promise((resolve) => { - storeRef.current.getState().suspendedComponentResolvers.add(resolve); - }); - throw promise; - } else if (loadable.state === "hasError") { - throw loadable.contents; - } else { - const err = new Error(`Invalid value of loadable atom "${recoilValue.key}"`); - throw err; - } -} -function validateRecoilValue(recoilValue, hookName) { - if (!isRecoilValue$2(recoilValue)) { - throw new Error(`Invalid argument to ${hookName}: expected an atom or selector but got ${String(recoilValue)}`); - } -} -function useRecoilInterface_DEPRECATED() { - const storeRef = useStoreRef$1(); - const [_9, forceUpdate] = useState$1([]); - const recoilValuesUsed = useRef$2(/* @__PURE__ */ new Set()); - recoilValuesUsed.current = /* @__PURE__ */ new Set(); - const previousSubscriptions = useRef$2(/* @__PURE__ */ new Set()); - const subscriptions = useRef$2(/* @__PURE__ */ new Map()); - const unsubscribeFrom = useCallback$1((key2) => { - const sub = subscriptions.current.get(key2); - if (sub) { - sub.release(); - subscriptions.current.delete(key2); - } - }, [subscriptions]); - const componentName = Recoil_useComponentName(); - useEffect$1(() => { - const store = storeRef.current; - function updateState(_state, key2) { - if (!subscriptions.current.has(key2)) { + }; + const onDragStarted = (e4) => { + if (selectedFiles.length > 1) { + setDragPaths(selectedFiles.map((f4) => f4.path)); + const files = selectedFiles.map((f4) => f4.file).filter((f4) => f4); + plugin.app.dragManager.onDragStart(e4, { + icon: "lucide-files", + source: void 0, + title: i18n_default.labels.filesCount.replace( + "{$1}", + files.length.toString() + ), + type: "files", + files + }); + plugin.app.dragManager.dragFiles(e4, files, true); return; } - forceUpdate([]); - } - Recoil_differenceSets(recoilValuesUsed.current, previousSubscriptions.current).forEach((key2) => { - if (subscriptions.current.has(key2)) { - Recoil_expectationViolation(`Double subscription to RecoilValue "${key2}"`); + dragStarted(data2.id); + setDragPaths([data2.path]); + if (data2.type == "space") { + const file = getAbstractFileAtPath(plugin, data2.path); + if (file) { + plugin.app.dragManager.onDragStart(e4, { + icon: "lucide-folder", + source: void 0, + title: file.name, + type: "folder", + file + }); + plugin.app.dragManager.dragFolder(e4, file, true); + } + } else if (data2.type == "file") { + const file = getAbstractFileAtPath(plugin, data2.path); + if (file) { + plugin.app.dragManager.onDragStart(e4, { + icon: "lucide-file", + source: void 0, + title: file.name, + type: "file", + file + }); + } + } + }; + const onDragOver = (e4) => { + e4.preventDefault(); + if (!innerRef.current) return; + const rect = innerRef.current.getBoundingClientRect(); + const x5 = e4.clientX - rect.left; + const y5 = e4.clientY - rect.top; + dragOver(e4, data2.id, { x: x5, y: y5 }); + }; + const onKeyDown = (e4) => { + if (e4.key === "Control" || e4.key === "Meta") { + if (e4.repeat) + return; + const el = hoverTarget; + if (el) + plugin.app.workspace.trigger( + "link-hover", + {}, + el, + data2.item.path, + data2.item.path + ); } - const sub = subscribeToRecoilValue$1(store, new AbstractRecoilValue$3(key2), (state2) => { - updateState(state2, key2); - }, componentName); - subscriptions.current.set(key2, sub); - const state = store.getState(); - if (state.nextTree) { - store.getState().queuedComponentCallbacks_DEPRECATED.push(() => { - updateState(store.getState(), key2); + }; + const onDrop = T2((files, g4, h5) => { + if (data2.item.cacheType == "space" && data2.item.type == "folder") { + files.map(async (file) => { + file.arrayBuffer().then((arrayBuffer) => { + plugin.app.vault.adapter.writeBinary( + data2.item.path + "/" + file.name, + arrayBuffer + ); + }); }); - } else { - updateState(store.getState(), key2); } + }, []); + const onDragEnter = T2(() => { + if (data2.item.cacheType == "space" && data2.item.type == "folder") + setDropHighlighted(true); + }, []); + const { getRootProps, getInputProps, isDragActive } = useDropzone({ + onDrop, + onDragEnter, + onDragLeave: () => setDropHighlighted(false), + onDropAccepted: () => setDropHighlighted(false), + onDropRejected: () => setDropHighlighted(false), + noClick: true }); - Recoil_differenceSets(previousSubscriptions.current, recoilValuesUsed.current).forEach((key2) => { - unsubscribeFrom(key2); - }); - previousSubscriptions.current = recoilValuesUsed.current; - }); - useEffect$1(() => { - const subs = subscriptions.current; - return () => subs.forEach((_10, key2) => unsubscribeFrom(key2)); - }, [unsubscribeFrom]); - return useMemo$1(() => { - function useSetRecoilState2(recoilState) { - if (true) { - validateRecoilValue(recoilState, "useSetRecoilState"); + const onDragEnded = (e4) => { + dragEnded(data2.id, eventToModifier(e4)); + }; + const mouseOut = (e4) => { + setHoverTarget(null); + }; + const newAction = (e4) => { + const space = data2.item; + newFileInSpace(plugin, space, space.space.uri); + }; + const handleRightClick = (e4) => { + selectedFiles.length > 1 && selectedFiles.some((f4) => f4.id == data2.id) ? triggerMultiFileMenu(plugin, selectedFiles, e4) : contextMenu(e4); + }; + const contextMenu = (e4) => { + if (data2.item.cacheType == "space") { + triggerSpaceMenu( + plugin, + data2.item, + e4, + activeFile, + data2.space + ); + return; + } + triggerFileMenu(plugin, data2.file, isFolder, e4, data2.space); + }; + const updateFileCache = (evt) => { + if (evt.detail.type == "file" && evt.detail.name == data2.item.path) { + const fileCache2 = plugin.index.filesIndex.get(data2.item.path); + if (fileCache2 && !fileCache2.isFolder) + setFileCache(fileCache2); + } else if (evt.detail.type == "space" && evt.detail.name == data2.item.path) { + const fileCache2 = plugin.index.spacesIndex.get(data2.item.path); + if (fileCache2) + setFileCache(fileCache2); } - return (newValueOrUpdater) => { - setRecoilValue$2(storeRef.current, recoilState, newValueOrUpdater); + }; + p2(() => { + window.addEventListener(eventTypes.spacesChange, updateFileCache); + return () => { + window.removeEventListener(eventTypes.spacesChange, updateFileCache); }; - } - function useResetRecoilState2(recoilState) { - if (true) { - validateRecoilValue(recoilState, "useResetRecoilState"); + }, []); + const hoverItem = (e4) => { + if (plugin.settings.filePreviewOnHover) { + setHoverTarget(e4.target); + if (e4.ctrlKey || e4.metaKey) { + plugin.app.workspace.trigger( + "link-hover", + {}, + e4.target, + data2.item.path, + data2.item.path + ); + } } - return () => setRecoilValue$2(storeRef.current, recoilState, DEFAULT_VALUE$3); - } - function useRecoilValueLoadable2(recoilValue) { - var _storeState$nextTree; - if (true) { - validateRecoilValue(recoilValue, "useRecoilValueLoadable"); + }; + p2(() => { + if (hoverTarget && plugin.settings.filePreviewOnHover) { + window.addEventListener("keydown", onKeyDown); + return () => { + window.removeEventListener("keydown", onKeyDown); + }; } - if (!recoilValuesUsed.current.has(recoilValue.key)) { - recoilValuesUsed.current = setByAddingToSet$2(recoilValuesUsed.current, recoilValue.key); + }, [hoverTarget]); + const dropProps = !platformIsMobile() ? { + onDragOver + } : {}; + const innerProps = !platformIsMobile() ? { + draggable: true, + onDragStart: onDragStarted, + onDrop: onDragEnded + } : handleProps; + const isFolder = data2.item.cacheType == "space" || data2.item.isFolder; + const extension = data2.item.cacheType == "file" && data2.item.extension; + const isLink = data2.item.parent != data2.space; + return /* @__PURE__ */ Cn.createElement(Cn.Fragment, null, /* @__PURE__ */ Cn.createElement("div", { + className: (0, import_classnames6.default)( + "mk-tree-wrapper", + clone && "mk-clone", + ghost && "mk-ghost", + disableSelection && "mk-disable-selection", + disableInteraction && "mk-disable-interaction", + highlighted ? "is-highlighted" : "" + ), + style: { position: "relative" }, + ref: innerRef, + onMouseLeave: mouseOut, + onMouseEnter: hoverItem, + onKeyDown, + onClick: (e4) => openFileAtTarget(data2, e4), + onContextMenu: (e4) => handleRightClick(e4), + ...dropProps, + ...innerProps + }, /* @__PURE__ */ Cn.createElement("div", { + className: (0, import_classnames6.default)( + data2.item.cacheType == "space" || isFolder ? "nav-folder" : "nav-file" + ), + ref: wrapperRef, + style: { + ...style, + ...dragActive && !platformIsMobile() ? { pointerEvents: "none" } : {} + }, + ...!platformIsMobile() ? getRootProps({ className: "dropzone" }) : {} + }, /* @__PURE__ */ Cn.createElement("input", { + ...getInputProps() + }), /* @__PURE__ */ Cn.createElement("div", { + className: (0, import_classnames6.default)( + "mk-tree-item", + "tree-item-self", + isFolder ? "nav-folder-title" : "nav-file-title", + active ? "is-active" : "", + selected ? "is-selected" : "", + indicator || dropHighlighted ? "mk-indicator-row" : "" + ), + ref: ref2, + style: { + "--spacing": `${indentationWidth * depth}px`, + "--childrenCount": `${childCount * spaceRowHeight(plugin) - 13}px` + }, + "data-path": fileCache.path + }, !data2.leaf ? /* @__PURE__ */ Cn.createElement("button", { + "aria-label": `${collapsed ? i18n_default.labels.expand : i18n_default.labels.collapse}`, + className: `mk-collapse mk-icon-xsmall ${collapsed ? "mk-collapsed" : ""}`, + onClick: (e4) => { + onCollapse(data2, false); + e4.stopPropagation(); + }, + dangerouslySetInnerHTML: { + __html: uiIconSet["mk-ui-collapse"] } - const storeState = storeRef.current.getState(); - return getRecoilValueAsLoadable$3(storeRef.current, recoilValue, Recoil_gkx_1("recoil_early_rendering_2021") ? (_storeState$nextTree = storeState.nextTree) !== null && _storeState$nextTree !== void 0 ? _storeState$nextTree : storeState.currentTree : storeState.currentTree); - } - function useRecoilValue2(recoilValue) { - if (true) { - validateRecoilValue(recoilValue, "useRecoilValue"); + }) : /* @__PURE__ */ Cn.createElement("div", { + className: `mk-collapse mk-icon-xsmall ${collapsed ? "mk-collapsed" : ""}` + }), plugin.settings.spacesStickers && fileCache && /* @__PURE__ */ Cn.createElement(FileSticker, { + plugin, + fileCache + }), /* @__PURE__ */ Cn.createElement("div", { + className: `mk-tree-text ${isFolder ? "nav-folder-title-content" : "nav-file-title-content"}` + }, plugin.settings.spacesUseAlias ? fileCache.alias : fileCache.name, isLink && /* @__PURE__ */ Cn.createElement("span", { + className: "mk-file-link", + dangerouslySetInnerHTML: { + __html: stickerFromString( + "lucide//arrow-up-right", + plugin + ) } - const loadable = useRecoilValueLoadable2(recoilValue); - return handleLoadable(loadable, recoilValue, storeRef); - } - function useRecoilState2(recoilState) { - if (true) { - validateRecoilValue(recoilState, "useRecoilState"); + })), !isFolder && extension != "md" && /* @__PURE__ */ Cn.createElement("span", { + className: "nav-file-tag" + }, extension), !clone ? /* @__PURE__ */ Cn.createElement("div", { + className: "mk-folder-buttons" + }, /* @__PURE__ */ Cn.createElement("button", { + "aria-label": i18n_default.buttons.moreOptions, + onClick: (e4) => { + contextMenu(e4); + e4.stopPropagation(); + }, + dangerouslySetInnerHTML: { + __html: uiIconSet["mk-ui-options"] } - return [useRecoilValue2(recoilState), useSetRecoilState2(recoilState)]; - } - function useRecoilStateLoadable2(recoilState) { - if (true) { - validateRecoilValue(recoilState, "useRecoilStateLoadable"); + }), isFolder && /* @__PURE__ */ Cn.createElement("button", { + "aria-label": i18n_default.buttons.newNote, + onClick: (e4) => { + newAction(e4); + e4.stopPropagation(); + }, + dangerouslySetInnerHTML: { + __html: uiIconSet["mk-ui-plus"] } - return [useRecoilValueLoadable2(recoilState), useSetRecoilState2(recoilState)]; - } - return { - getRecoilValue: useRecoilValue2, - getRecoilValueLoadable: useRecoilValueLoadable2, - getRecoilState: useRecoilState2, - getRecoilStateLoadable: useRecoilStateLoadable2, - getSetRecoilState: useSetRecoilState2, - getResetRecoilState: useResetRecoilState2 - }; - }, [recoilValuesUsed, storeRef]); -} -var recoilComponentGetRecoilValueCount_FOR_TESTING = { - current: 0 -}; -function useRecoilValueLoadable_MUTABLESOURCE(recoilValue) { - if (true) { - validateRecoilValue(recoilValue, "useRecoilValueLoadable"); - } - const storeRef = useStoreRef$1(); - const getLoadable = useCallback$1(() => { - var _storeState$nextTree2; - const store = storeRef.current; - const storeState = store.getState(); - const treeState = Recoil_gkx_1("recoil_early_rendering_2021") ? (_storeState$nextTree2 = storeState.nextTree) !== null && _storeState$nextTree2 !== void 0 ? _storeState$nextTree2 : storeState.currentTree : storeState.currentTree; - return getRecoilValueAsLoadable$3(store, recoilValue, treeState); - }, [storeRef, recoilValue]); - const getLoadableWithTesting = useCallback$1(() => { - if (true) { - recoilComponentGetRecoilValueCount_FOR_TESTING.current++; - } - return getLoadable(); - }, [getLoadable]); - const componentName = Recoil_useComponentName(); - const subscribe = useCallback$1((_storeState, callback) => { - const store = storeRef.current; - const subscription = subscribeToRecoilValue$1(store, recoilValue, () => { - if (!Recoil_gkx_1("recoil_suppress_rerender_in_callback")) { - return callback(); - } - const newLoadable = getLoadable(); - if (!prevLoadableRef.current.is(newLoadable)) { - callback(); - } - prevLoadableRef.current = newLoadable; - }, componentName); - return subscription.release; - }, [storeRef, recoilValue, componentName, getLoadable]); - const source = useRecoilMutableSource$1(); - const loadable = useMutableSource$1(source, getLoadableWithTesting, subscribe); - const prevLoadableRef = useRef$2(loadable); - useEffect$1(() => { - prevLoadableRef.current = loadable; + })) : /* @__PURE__ */ Cn.createElement(Cn.Fragment, null))))); + } +); +TreeItem.displayName = "TreeItem"; + +// src/components/Navigator/SpaceTree/SpaceTreeSectionItem.tsx +var TreeSectionItem = k3( + ({ + childCount, + clone, + data: data2, + depth, + disableSelection, + dragActive, + disableInteraction, + ghost, + handleProps, + active, + indentationWidth, + indicator, + collapsed, + selected, + highlighted, + onCollapse, + onSelectRange, + wrapperRef, + style, + plugin, + disabled, + dragStarted, + dragOver, + dragEnded + }, ref2) => { + return /* @__PURE__ */ Cn.createElement(Cn.Fragment, null, /* @__PURE__ */ Cn.createElement("div", { + className: "mk-tree-section" + }, data2.path)); + } +); +TreeSectionItem.displayName = "TreeSectionItem"; + +// src/components/Navigator/SpaceTree/SpaceTreeNodeView.tsx +var animateLayoutChanges2 = ({ + isSorting, + wasDragging +}) => isSorting || wasDragging ? false : true; +var SortableTreeItem = ({ + id: id2, + data: data2, + depth, + disabled, + style, + dragActive, + dragStarted, + dragOver, + dragEnded, + ...props2 +}) => { + const { + attributes, + isDragging, + isSorting, + listeners, + setDraggableNodeRef, + setDroppableNodeRef, + transform, + transition + } = useSortable({ + id: id2, + animateLayoutChanges: animateLayoutChanges2, + disabled, + data: data2 }); - return loadable; -} -function useRecoilValueLoadable_LEGACY(recoilValue) { - if (true) { - validateRecoilValue(recoilValue, "useRecoilValueLoadable"); - } - const storeRef = useStoreRef$1(); - const [_9, forceUpdate] = useState$1([]); - const componentName = Recoil_useComponentName(); - useEffect$1(() => { - const store = storeRef.current; - const storeState = store.getState(); - const subscription = subscribeToRecoilValue$1(store, recoilValue, (_state) => { - var _prevLoadableRef$curr; - if (!Recoil_gkx_1("recoil_suppress_rerender_in_callback")) { - return forceUpdate([]); - } - const newLoadable = getRecoilValueAsLoadable$3(store, recoilValue, store.getState().currentTree); - if (!((_prevLoadableRef$curr = prevLoadableRef.current) === null || _prevLoadableRef$curr === void 0 ? void 0 : _prevLoadableRef$curr.is(newLoadable))) { - forceUpdate(newLoadable); - } - prevLoadableRef.current = newLoadable; - }, componentName); - if (storeState.nextTree) { - store.getState().queuedComponentCallbacks_DEPRECATED.push(() => { - prevLoadableRef.current = null; - forceUpdate([]); - }); - } else { - var _prevLoadableRef$curr2; - if (!Recoil_gkx_1("recoil_suppress_rerender_in_callback")) { - return forceUpdate([]); - } - const newLoadable = getRecoilValueAsLoadable$3(store, recoilValue, store.getState().currentTree); - if (!((_prevLoadableRef$curr2 = prevLoadableRef.current) === null || _prevLoadableRef$curr2 === void 0 ? void 0 : _prevLoadableRef$curr2.is(newLoadable))) { - forceUpdate(newLoadable); - } - prevLoadableRef.current = newLoadable; - } - return subscription.release; - }, [componentName, recoilValue, storeRef]); - const loadable = getRecoilValueAsLoadable$3(storeRef.current, recoilValue); - const prevLoadableRef = useRef$2(loadable); - useEffect$1(() => { - prevLoadableRef.current = loadable; + const memoListeners = F2(() => { + return { + ...attributes, + ...listeners + }; + }, [isSorting]); + return data2.type == "group" ? /* @__PURE__ */ Cn.createElement(TreeSectionItem, { + ref: setDraggableNodeRef, + wrapperRef: setDroppableNodeRef, + data: data2, + depth, + ghost: isDragging, + disableInteraction: isSorting, + disabled, + dragActive, + style: platformIsMobile() ? { ...style, transform: CSS.Translate.toString(transform) } : style, + handleProps: memoListeners, + dragOver, + dragStarted, + dragEnded, + ...props2 + }) : /* @__PURE__ */ Cn.createElement(TreeItem, { + ref: setDraggableNodeRef, + wrapperRef: setDroppableNodeRef, + data: data2, + depth, + ghost: isDragging, + disableInteraction: isSorting, + disabled, + dragActive, + style: platformIsMobile() ? { ...style, transform: CSS.Translate.toString(transform) } : style, + handleProps: memoListeners, + dragOver, + dragStarted, + dragEnded, + ...props2 }); - return loadable; +}; + +// src/hooks/ForceUpdate.tsx +function useForceUpdate() { + const [value, setValue] = h2(0); + return () => setValue((value2) => value2 + 1); } -function useRecoilValueLoadable(recoilValue) { - if (Recoil_gkx_1("recoil_memory_managament_2020")) { - useRetain(recoilValue); + +// src/utils/dnd/dragFile.ts +function getMaxDepth(previousItem, dirDown) { + var _a2; + if (previousItem) { + if (((_a2 = previousItem.item) == null ? void 0 : _a2.cacheType) == "space" && !previousItem.collapsed && dirDown) + return previousItem.depth + 1; + return previousItem.depth; } - if (mutableSourceExists$2()) { - return useRecoilValueLoadable_MUTABLESOURCE(recoilValue); - } else { - return useRecoilValueLoadable_LEGACY(recoilValue); - } -} -function useRecoilValue(recoilValue) { - if (true) { - validateRecoilValue(recoilValue, "useRecoilValue"); - } - const storeRef = useStoreRef$1(); - const loadable = useRecoilValueLoadable(recoilValue); - return handleLoadable(loadable, recoilValue, storeRef); -} -function useSetRecoilState(recoilState) { - if (true) { - validateRecoilValue(recoilState, "useSetRecoilState"); - } - const storeRef = useStoreRef$1(); - return useCallback$1((newValueOrUpdater) => { - setRecoilValue$2(storeRef.current, recoilState, newValueOrUpdater); - }, [storeRef, recoilState]); -} -function useResetRecoilState(recoilState) { - if (true) { - validateRecoilValue(recoilState, "useResetRecoilState"); - } - const storeRef = useStoreRef$1(); - return useCallback$1(() => { - setRecoilValue$2(storeRef.current, recoilState, DEFAULT_VALUE$3); - }, [storeRef, recoilState]); -} -function useRecoilState(recoilState) { - if (true) { - validateRecoilValue(recoilState, "useRecoilState"); - } - return [useRecoilValue(recoilState), useSetRecoilState(recoilState)]; -} -function useRecoilStateLoadable(recoilState) { - if (true) { - validateRecoilValue(recoilState, "useRecoilStateLoadable"); - } - return [useRecoilValueLoadable(recoilState), useSetRecoilState(recoilState)]; -} -function useTransactionSubscription(callback) { - const storeRef = useStoreRef$1(); - useEffect$1(() => { - const sub = storeRef.current.subscribeToTransactions(callback); - return sub.release; - }, [callback, storeRef]); -} -function externallyVisibleAtomValuesInState(state) { - const atomValues = state.atomValues.toMap(); - const persistedAtomContentsValues = Recoil_mapMap(Recoil_filterMap(atomValues, (v3, k5) => { - const node = getNode$4(k5); - const persistence = node.persistence_UNSTABLE; - return persistence != null && persistence.type !== "none" && v3.state === "hasValue"; - }), (v3) => v3.contents); - return Recoil_mergeMaps(state.nonvalidatedAtoms.toMap(), persistedAtomContentsValues); -} -function useTransactionObservation_DEPRECATED(callback) { - useTransactionSubscription(useCallback$1((store) => { - let previousTree = store.getState().previousTree; - const currentTree = store.getState().currentTree; - if (!previousTree) { - Recoil_recoverableViolation("Transaction subscribers notified without a previous tree being present -- this is a bug in Recoil"); - previousTree = store.getState().currentTree; - } - const atomValues = externallyVisibleAtomValuesInState(currentTree); - const previousAtomValues = externallyVisibleAtomValuesInState(previousTree); - const atomInfo = Recoil_mapMap(nodes$1, (node) => { - var _node$persistence_UNS, _node$persistence_UNS2, _node$persistence_UNS3, _node$persistence_UNS4; - return { - persistence_UNSTABLE: { - type: (_node$persistence_UNS = (_node$persistence_UNS2 = node.persistence_UNSTABLE) === null || _node$persistence_UNS2 === void 0 ? void 0 : _node$persistence_UNS2.type) !== null && _node$persistence_UNS !== void 0 ? _node$persistence_UNS : "none", - backButton: (_node$persistence_UNS3 = (_node$persistence_UNS4 = node.persistence_UNSTABLE) === null || _node$persistence_UNS4 === void 0 ? void 0 : _node$persistence_UNS4.backButton) !== null && _node$persistence_UNS3 !== void 0 ? _node$persistence_UNS3 : false - } - }; - }); - const modifiedAtoms = Recoil_filterSet(currentTree.dirtyAtoms, (k5) => atomValues.has(k5) || previousAtomValues.has(k5)); - callback({ - atomValues, - previousAtomValues, - atomInfo, - modifiedAtoms, - transactionMetadata: { - ...currentTree.transactionMetadata - } - }); - }, [callback])); + return 0; } -function useRecoilTransactionObserver(callback) { - useTransactionSubscription(useCallback$1((store) => { - const snapshot = cloneSnapshot$1(store, "current"); - const previousSnapshot = cloneSnapshot$1(store, "previous"); - callback({ - snapshot, - previousSnapshot - }); - }, [callback])); +function getMinDepth(previousItem) { + if (previousItem) { + return Math.max(0, previousItem.depth - 1); + } + return 0; } -function usePrevious2(value) { - const ref = useRef$2(); - useEffect$1(() => { - ref.current = value; - }); - return ref.current; -} -function useRecoilSnapshot() { - const storeRef = useStoreRef$1(); - const [snapshot, setSnapshot] = useState$1(() => cloneSnapshot$1(storeRef.current)); - const previousSnapshot = usePrevious2(snapshot); - const timeoutID = useRef$2(); - useEffect$1(() => { - if (timeoutID.current && !isSSR$2) { - window.clearTimeout(timeoutID.current); - } - return snapshot.retain(); - }, [snapshot]); - useTransactionSubscription(useCallback$1((store) => setSnapshot(cloneSnapshot$1(store)), [])); - if (previousSnapshot !== snapshot && !isSSR$2) { - if (timeoutID.current) { - previousSnapshot === null || previousSnapshot === void 0 ? void 0 : previousSnapshot.release_INTERNAL(); - window.clearTimeout(timeoutID.current); - } - snapshot.retain(); - timeoutID.current = window.setTimeout(() => { - snapshot.release_INTERNAL(); - timeoutID.current = null; - }, SUSPENSE_TIMEOUT_MS); - } - return snapshot; -} -function useGotoRecoilSnapshot() { - const storeRef = useStoreRef$1(); - return useCallback$1((snapshot) => { - var _storeState$nextTree3; - const storeState = storeRef.current.getState(); - const prev = (_storeState$nextTree3 = storeState.nextTree) !== null && _storeState$nextTree3 !== void 0 ? _storeState$nextTree3 : storeState.currentTree; - const next = snapshot.getStore_INTERNAL().getState().currentTree; - batchUpdates$2(() => { - const keysToUpdate = /* @__PURE__ */ new Set(); - for (const keys of [prev.atomValues.keys(), next.atomValues.keys()]) { - for (const key2 of keys) { - var _prev$atomValues$get, _next$atomValues$get; - if (((_prev$atomValues$get = prev.atomValues.get(key2)) === null || _prev$atomValues$get === void 0 ? void 0 : _prev$atomValues$get.contents) !== ((_next$atomValues$get = next.atomValues.get(key2)) === null || _next$atomValues$get === void 0 ? void 0 : _next$atomValues$get.contents) && getNode$4(key2).shouldRestoreFromSnapshots) { - keysToUpdate.add(key2); - } - } - } - keysToUpdate.forEach((key2) => { - setRecoilValueLoadable$1(storeRef.current, new AbstractRecoilValue$3(key2), next.atomValues.has(key2) ? Recoil_nullthrows(next.atomValues.get(key2)) : DEFAULT_VALUE$3); - }); - storeRef.current.replaceState((state) => { - return { - ...state, - stateID: snapshot.getID_INTERNAL() - }; - }); - }); - }, [storeRef]); -} -function useSetUnvalidatedAtomValues() { - const storeRef = useStoreRef$1(); - return (values, transactionMetadata = {}) => { - batchUpdates$2(() => { - storeRef.current.addTransactionMetadata(transactionMetadata); - values.forEach((value, key2) => setUnvalidatedRecoilValue$2(storeRef.current, new AbstractRecoilValue$3(key2), value)); - }); - }; -} -var Sentinel = class { -}; -var SENTINEL = new Sentinel(); -function useRecoilCallback(fn2, deps) { - const storeRef = useStoreRef$1(); - const gotoSnapshot = useGotoRecoilSnapshot(); - return useCallback$1( - (...args) => { - function set(recoilState, newValueOrUpdater) { - setRecoilValue$2(storeRef.current, recoilState, newValueOrUpdater); - } - function reset(recoilState) { - setRecoilValue$2(storeRef.current, recoilState, DEFAULT_VALUE$3); - } - const snapshot = cloneSnapshot$1(storeRef.current); - const atomicUpdate = atomicUpdater$1(storeRef.current); - let ret = SENTINEL; - batchUpdates$2(() => { - const errMsg = "useRecoilCallback expects a function that returns a function: it accepts a function of the type (RecoilInterface) => T = R and returns a callback function T => R, where RecoilInterface is an object {snapshot, set, ...} and T and R are the argument and return types of the callback you want to create. Please see the docs at recoiljs.org for details."; - if (typeof fn2 !== "function") { - throw new Error(errMsg); - } - const cb = fn2({ - set, - reset, - snapshot, - gotoSnapshot, - transact_UNSTABLE: atomicUpdate - }); - if (typeof cb !== "function") { - throw new Error(errMsg); - } - ret = cb(...args); - }); - !!(ret instanceof Sentinel) ? true ? Recoil_invariant(false, "batchUpdates should return immediately") : Recoil_invariant(false) : void 0; - return ret; - }, - deps != null ? [...deps, storeRef] : void 0 - ); +function getDragDepth(offset2, indentationWidth) { + return Math.round(offset2 / indentationWidth); } -function useRetain(toRetain) { - if (!Recoil_gkx_1("recoil_memory_managament_2020")) { +var getMultiProjection = (flattenedTree, paths, overIndex, modifier) => { + const overItem = flattenedTree[overIndex]; + if (!overItem) return; - } - return useRetain_ACTUAL(toRetain); -} -function useRetain_ACTUAL(toRetain) { - const array = Array.isArray(toRetain) ? toRetain : [toRetain]; - const retainables = array.map((a5) => a5 instanceof RetentionZone$3 ? a5 : a5.key); - const storeRef = useStoreRef$1(); - useEffect$1(() => { - if (!Recoil_gkx_1("recoil_memory_managament_2020")) { - return; - } - const store = storeRef.current; - if (timeoutID.current && !isSSR$2) { - window.clearTimeout(timeoutID.current); - timeoutID.current = null; - } else { - for (const r3 of retainables) { - updateRetainCount$2(store, r3, 1); - } - } - return () => { - for (const r3 of retainables) { - updateRetainCount$2(store, r3, -1); - } + const dropTarget = overItem.type == "file" ? flattenedTree.find((f4) => f4.id == overItem.parentId) : overItem; + if ((dropTarget == null ? void 0 : dropTarget.type) != "file") { + const _projected = { + depth: overItem.depth, + overId: overItem.id, + parentId: dropTarget.id, + sortable: false, + insert: dropTarget.collapsed, + droppable: true, + copy: modifier == "link" || modifier == "copy", + reorder: false }; - }, [storeRef, ...retainables]); - const timeoutID = useRef$2(); - const previousRetainables = usePrevious2(retainables); - if (!isSSR$2 && (previousRetainables === void 0 || !Recoil_shallowArrayEqual(previousRetainables, retainables))) { - const store = storeRef.current; - for (const r3 of retainables) { - updateRetainCount$2(store, r3, 1); - } - if (previousRetainables) { - for (const r3 of previousRetainables) { - updateRetainCount$2(store, r3, -1); - } - } - if (timeoutID.current) { - window.clearTimeout(timeoutID.current); - } - timeoutID.current = window.setTimeout(() => { - timeoutID.current = null; - for (const r3 of retainables) { - updateRetainCount$2(store, r3, -1); - } - }, SUSPENSE_TIMEOUT_MS); + return _projected; } -} -function useRecoilTransaction(fn2, deps) { - const storeRef = useStoreRef$1(); - return useMemo$1( - () => (...args) => { - const atomicUpdate = atomicUpdater$1(storeRef.current); - atomicUpdate((transactionInterface) => { - fn2(transactionInterface)(...args); - }); - }, - deps != null ? [...deps, storeRef] : void 0 - ); -} -var Recoil_Hooks = { - recoilComponentGetRecoilValueCount_FOR_TESTING, - useGotoRecoilSnapshot, - useRecoilCallback, - useRecoilInterface: useRecoilInterface_DEPRECATED, - useRecoilSnapshot, - useRecoilState, - useRecoilStateLoadable, - useRecoilTransaction, - useRecoilTransactionObserver, - useRecoilValue, - useRecoilValueLoadable, - useRetain, - useResetRecoilState, - useSetRecoilState, - useSetUnvalidatedAtomValues, - useTransactionObservation_DEPRECATED, - useTransactionSubscription_DEPRECATED: useTransactionSubscription + return null; }; -var { - peekNodeInfo: peekNodeInfo$2 -} = Recoil_FunctionalCore; -var { - useStoreRef: useStoreRef$2 -} = Recoil_RecoilRoot_react; -function useGetRecoilValueInfo() { - const storeRef = useStoreRef$2(); - return ({ - key: key2 - }) => peekNodeInfo$2(storeRef.current, storeRef.current.getState().currentTree, key2); -} -var Recoil_useGetRecoilValueInfo = useGetRecoilValueInfo; -var { - RecoilRoot: RecoilRoot$1, - useStoreRef: useStoreRef$3 -} = Recoil_RecoilRoot_react; -var { - useMemo: useMemo$2 -} = Cn; -function useRecoilBridgeAcrossReactRoots() { - const store = useStoreRef$3().current; - return useMemo$2(() => { - function RecoilBridge({ - children - }) { - return /* @__PURE__ */ Cn.createElement(RecoilRoot$1, { - store_INTERNAL: store - }, children); - } - return RecoilBridge; - }, [store]); -} -var Recoil_useRecoilBridgeAcrossReactRoots = useRecoilBridgeAcrossReactRoots; -function isNode2(object) { - var _ownerDocument, _doc$defaultView; - if (typeof window === "undefined") { - return false; - } - const doc = object != null ? (_ownerDocument = object.ownerDocument) !== null && _ownerDocument !== void 0 ? _ownerDocument : object : document; - const defaultView = (_doc$defaultView = doc.defaultView) !== null && _doc$defaultView !== void 0 ? _doc$defaultView : window; - return !!(object != null && (typeof defaultView.Node === "function" ? object instanceof defaultView.Node : typeof object === "object" && typeof object.nodeType === "number" && typeof object.nodeName === "string")); -} -var Recoil_isNode = isNode2; -var { - isReactNative: isReactNative$1, - isSSR: isSSR$3 -} = Recoil_Environment; -function shouldNotBeFrozen(value) { - if (value === null || typeof value !== "object") { - return true; - } - switch (typeof value.$$typeof) { - case "symbol": - return true; - case "number": - return true; - } - if (value["@@__IMMUTABLE_ITERABLE__@@"] != null || value["@@__IMMUTABLE_KEYED__@@"] != null || value["@@__IMMUTABLE_INDEXED__@@"] != null || value["@@__IMMUTABLE_ORDERED__@@"] != null || value["@@__IMMUTABLE_RECORD__@@"] != null) { - return true; - } - if (Recoil_isNode(value)) { - return true; - } - if (Recoil_isPromise(value)) { - return true; - } - if (value instanceof Error) { - return true; - } - if (ArrayBuffer.isView(value)) { - return true; - } - if (!isSSR$3 && !isReactNative$1 && (value === window || value instanceof Window)) { - return true; - } - return false; -} -function deepFreezeValue(value) { - if (typeof value !== "object" || shouldNotBeFrozen(value)) { +function getProjection(activeItem, items, paths, overItemIndex, dragDepth, yOffset, dirDown, modifier) { + if (paths.length == 0) + return null; + if (paths.length > 1) + return getMultiProjection(items, paths, overItemIndex, modifier); + const overItem = items[overItemIndex]; + const previousItem = items[overItemIndex]; + const nextItem = items[overItemIndex + 1]; + if (!previousItem) return; + const previousItemDroppable = previousItem.type != "file"; + const insert2 = overItem.collapsed && previousItemDroppable && (!overItem.sortable || dirDown && yOffset <= 13 || !dirDown && yOffset >= 13); + const sortable = overItem.sortable || previousItemDroppable && !insert2 && nextItem.sortable; + const projectedDepth = dragDepth; + const maxDepth = getMaxDepth( + previousItem, + dirDown + ); + const minDepth = getMinDepth(previousItem); + let depth = projectedDepth; + if (projectedDepth >= maxDepth) { + depth = maxDepth; + } else if (projectedDepth < minDepth) { + depth = minDepth; } - Object.freeze(value); - for (const key2 in value) { - if (Object.prototype.hasOwnProperty.call(value, key2)) { - const prop = value[key2]; - if (typeof prop === "object" && prop != null && !Object.isFrozen(prop)) { - deepFreezeValue(prop); - } + const parentId = getParentId(); + const parent = items.find((f4) => f4.id == parentId); + return { + depth, + overId: previousItem.id, + parentId, + sortable, + insert: insert2, + droppable: (parent == null ? void 0 : parent.type) != "file", + copy: modifier == "link" || modifier == "copy", + reorder: insert2 ? (activeItem == null ? void 0 : activeItem.parentId) == (overItem == null ? void 0 : overItem.id) : (activeItem == null ? void 0 : activeItem.parentId) == (parent == null ? void 0 : parent.id) + }; + function getParentId() { + var _a2; + if (depth === 0) { + return null; + } + if (!previousItem) { + return null; + } + if (depth === previousItem.depth || depth > previousItem.depth && previousItem.item.cacheType != "space") { + return previousItem.parentId; + } + if (depth > previousItem.depth) { + return previousItem.id; } + const newParent = (_a2 = items.slice(0, overItemIndex).reverse().find((item) => item.depth === depth)) == null ? void 0 : _a2.parentId; + return newParent != null ? newParent : null; } - Object.seal(value); } -var Recoil_deepFreezeValue = deepFreezeValue; -var TIME_WARNING_THRESHOLD_MS = 15; -function stringify(x5, opt, key2) { - if (typeof x5 === "string" && !x5.includes('"') && !x5.includes("\\")) { - return `"${x5}"`; - } - switch (typeof x5) { - case "undefined": - return ""; - case "boolean": - return x5 ? "true" : "false"; - case "number": - case "symbol": - return String(x5); - case "string": - return JSON.stringify(x5); - case "function": - if ((opt === null || opt === void 0 ? void 0 : opt.allowFunctions) !== true) { - throw new Error("Attempt to serialize function in a Recoil cache key"); - } - return `__FUNCTION(${x5.name})__`; - } - if (x5 === null) { - return "null"; - } - if (typeof x5 !== "object") { - var _JSON$stringify; - return (_JSON$stringify = JSON.stringify(x5)) !== null && _JSON$stringify !== void 0 ? _JSON$stringify : ""; - } - if (Recoil_isPromise(x5)) { - return "__PROMISE__"; - } - if (Array.isArray(x5)) { - return `[${x5.map((v3, i4) => stringify(v3, opt, i4.toString()))}]`; + +// src/utils/dnd/dropFile.ts +var dropFilesInTree = async (plugin, paths, active, over, projected, flattenedTree, activeSpace, modifier) => { + var _a2, _b2, _c2, _d2; + if (paths.length == 1) { + dropFileInTree(plugin, paths[0], active, over, projected, flattenedTree, activeSpace, modifier); + return; } - if (typeof x5.toJSON === "function") { - return stringify(x5.toJSON(key2), opt, key2); + if (projected) { + const overIndex = flattenedTree.findIndex(({ id: id2 }) => id2 === over); + const overItem = flattenedTree[overIndex]; + const dropTarget = overItem.type == "file" ? overItem.depth == 0 ? activeSpace : (_a2 = flattenedTree.find((f4) => f4.id == overItem.parentId)) == null ? void 0 : _a2.item : overItem.item; + const droppable = paths.map((f4) => uriByString(plugin, f4)).filter( + (f4) => !nodeIsAncestorOfTarget(f4, dropTarget.space.uri) + ); + const parentId = projected.insert ? over : projected.parentId; + const newSpace = (_b2 = flattenedTree.find(({ id: id2 }) => id2 === parentId)) == null ? void 0 : _b2.item; + const newRank = parentId == overItem.id ? -1 : (_d2 = (_c2 = overItem.item) == null ? void 0 : _c2.rank) != null ? _d2 : -1; + if (!newSpace) + return; + movePathsToSpace(plugin, droppable.map((f4) => f4.path), newSpace, projected.sortable && newRank, modifier); } - if (x5 instanceof Map) { - const obj = {}; - for (const [k5, v3] of x5) { - obj[typeof k5 === "string" ? k5 : stringify(k5, opt)] = v3; +}; +var dropFileInTree = async (plugin, path, active, over, projected, flattenedTree, activeSpace, modifier) => { + var _a2, _b2, _c2, _d2; + if (projected) { + const clonedItems = flattenedTree; + const overIndex = clonedItems.findIndex(({ id: id2 }) => id2 === over); + const overItem = clonedItems[overIndex]; + const parentId = projected.insert ? over : projected.parentId; + const newSpace = projected.depth == 0 && !projected.insert ? activeSpace : (_a2 = clonedItems.find(({ id: id2 }) => id2 === parentId)) == null ? void 0 : _a2.item; + const newRank = parentId == overItem.id ? -1 : (_c2 = (_b2 = overItem.item) == null ? void 0 : _b2.rank) != null ? _c2 : -1; + if (!newSpace) + return; + if (!active) { + movePathToSpace(plugin, path, null, newSpace, projected.sortable && newRank, modifier); + return; } - return stringify(obj, opt, key2); - } - if (x5 instanceof Set) { - return stringify(Array.from(x5).sort((a5, b4) => stringify(a5, opt).localeCompare(stringify(b4, opt))), opt, key2); - } - if (Symbol !== void 0 && x5[Symbol.iterator] != null && typeof x5[Symbol.iterator] === "function") { - return stringify(Array.from(x5), opt, key2); + const activeIndex = clonedItems.findIndex(({ id: id2 }) => id2 === active); + const activeItem = clonedItems[activeIndex]; + const oldSpace = activeItem.parentId == activeSpace.path ? activeSpace : (_d2 = clonedItems.find(({ id: id2 }) => id2 === activeItem.parentId)) == null ? void 0 : _d2.item; + movePathToSpace(plugin, activeItem.item.path, oldSpace, newSpace, projected.sortable && newRank, modifier); } - return `{${Object.keys(x5).filter((key3) => x5[key3] !== void 0).sort().map((key3) => `${stringify(key3, opt)}:${stringify(x5[key3], opt, key3)}`).join(",")}}`; -} -function stableStringify(x5, opt = { - allowFunctions: false -}) { - if (true) { - if (typeof window !== "undefined") { - const startTime = window.performance ? window.performance.now() : 0; - const str = stringify(x5, opt); - const endTime = window.performance ? window.performance.now() : 0; - if (endTime - startTime > TIME_WARNING_THRESHOLD_MS) { - console.groupCollapsed(`Recoil: Spent ${endTime - startTime}ms computing a cache key`); - console.warn(x5, str); - console.groupEnd(); +}; + +// src/utils/keyboard.ts +var normalizedAltName = () => window.navigator.platform.startsWith("Mac") ? "\u2325" : "Alt"; + +// node_modules/@tanstack/react-virtual/build/esm/index.js +function _extends() { + _extends = Object.assign || function(target) { + for (var i4 = 1; i4 < arguments.length; i4++) { + var source = arguments[i4]; + for (var key2 in source) { + if (Object.prototype.hasOwnProperty.call(source, key2)) { + target[key2] = source[key2]; + } } - return str; } - } - return stringify(x5, opt); + return target; + }; + return _extends.apply(this, arguments); } -var Recoil_stableStringify = stableStringify; -var TreeCache = class { - constructor(options) { - var _options$onHit, _options$onSet, _options$mapNodeValue; - _defineProperty(this, "_numLeafs", void 0); - _defineProperty(this, "_root", void 0); - _defineProperty(this, "_onHit", void 0); - _defineProperty(this, "_onSet", void 0); - _defineProperty(this, "_mapNodeValue", void 0); - this._numLeafs = 0; - this._root = null; - this._onHit = (_options$onHit = options === null || options === void 0 ? void 0 : options.onHit) !== null && _options$onHit !== void 0 ? _options$onHit : () => { - }; - this._onSet = (_options$onSet = options === null || options === void 0 ? void 0 : options.onSet) !== null && _options$onSet !== void 0 ? _options$onSet : () => { - }; - this._mapNodeValue = (_options$mapNodeValue = options === null || options === void 0 ? void 0 : options.mapNodeValue) !== null && _options$mapNodeValue !== void 0 ? _options$mapNodeValue : (val) => val; - } - size() { - return this._numLeafs; +function _objectWithoutPropertiesLoose2(source, excluded) { + if (source == null) + return {}; + var target = {}; + var sourceKeys = Object.keys(source); + var key2, i4; + for (i4 = 0; i4 < sourceKeys.length; i4++) { + key2 = sourceKeys[i4]; + if (excluded.indexOf(key2) >= 0) + continue; + target[key2] = source[key2]; } - root() { - return this._root; + return target; +} +var props = ["bottom", "height", "left", "right", "top", "width"]; +var rectChanged = function rectChanged2(a5, b4) { + if (a5 === void 0) { + a5 = {}; } - get(getNodeValue, handlers) { - var _this$getLeafNode; - return (_this$getLeafNode = this.getLeafNode(getNodeValue, handlers)) === null || _this$getLeafNode === void 0 ? void 0 : _this$getLeafNode.value; + if (b4 === void 0) { + b4 = {}; } - getLeafNode(getNodeValue, handlers) { - return findLeaf(this.root(), (nodeKey) => this._mapNodeValue(getNodeValue(nodeKey)), { - onNodeVisit: (node) => { - handlers === null || handlers === void 0 ? void 0 : handlers.onNodeVisit(node); - if (node.type === "leaf") { - this._onHit(node); - } - } + return props.some(function(prop) { + return a5[prop] !== b4[prop]; + }); +}; +var observedNodes = /* @__PURE__ */ new Map(); +var rafId; +var run = function run2() { + var changedStates = []; + observedNodes.forEach(function(state, node) { + var newRect = node.getBoundingClientRect(); + if (rectChanged(newRect, state.rect)) { + state.rect = newRect; + changedStates.push(state); + } + }); + changedStates.forEach(function(state) { + state.callbacks.forEach(function(cb) { + return cb(state.rect); }); - } - set(route, value, handlers) { - let leafNode; - const newRoot = addLeaf(this.root(), route.map(([nodeKey, nodeValue]) => [nodeKey, this._mapNodeValue(nodeValue)]), null, value, null, { - onNodeVisit: (node) => { - handlers === null || handlers === void 0 ? void 0 : handlers.onNodeVisit(node); - if (node.type === "leaf") { - leafNode = node; - } + }); + rafId = window.requestAnimationFrame(run2); +}; +function observeRect(node, cb) { + return { + observe: function observe() { + var wasEmpty = observedNodes.size === 0; + if (observedNodes.has(node)) { + observedNodes.get(node).callbacks.push(cb); + } else { + observedNodes.set(node, { + rect: void 0, + hasRectChanged: false, + callbacks: [cb] + }); + } + if (wasEmpty) + run(); + }, + unobserve: function unobserve() { + var state = observedNodes.get(node); + if (state) { + var index = state.callbacks.indexOf(cb); + if (index >= 0) + state.callbacks.splice(index, 1); + if (!state.callbacks.length) + observedNodes["delete"](node); + if (!observedNodes.size) + cancelAnimationFrame(rafId); } - }); - if (!this.root()) { - this._root = newRoot; } - this._numLeafs++; - this._onSet(Recoil_nullthrows(leafNode)); + }; +} +var useIsomorphicLayoutEffect3 = typeof window !== "undefined" ? y2 : p2; +function rectReducer(state, action) { + var rect = action.rect; + if (state.height !== rect.height || state.width !== rect.width) { + return rect; } - delete(node) { - if (!this.root()) { - return false; + return state; +} +var useRect2 = function useRect3(nodeRef, initialRect) { + if (initialRect === void 0) { + initialRect = { + width: 0, + height: 0 + }; + } + var _React$useState = Cn.useState(nodeRef.current), element = _React$useState[0], setElement = _React$useState[1]; + var _React$useReducer = Cn.useReducer(rectReducer, initialRect), rect = _React$useReducer[0], dispatch = _React$useReducer[1]; + var initialRectSet = Cn.useRef(false); + useIsomorphicLayoutEffect3(function() { + if (nodeRef.current !== element) { + setElement(nodeRef.current); } - const root = Recoil_nullthrows(this.root()); - const existsInTree = pruneNodeFromTree(root, node, node.parent); - if (!existsInTree) { - return false; + }); + useIsomorphicLayoutEffect3(function() { + if (element && !initialRectSet.current) { + initialRectSet.current = true; + var _rect = element.getBoundingClientRect(); + dispatch({ + rect: _rect + }); } - if (node === root || root.type === "branch" && !root.branches.size) { - this._root = null; - this._numLeafs = 0; - return true; + }, [element]); + Cn.useEffect(function() { + if (!element) { + return; } - this._numLeafs -= countDownstreamLeaves(node); - return true; - } - clear() { - this._numLeafs = 0; - this._root = null; - } + var observer = observeRect(element, function(rect2) { + dispatch({ + rect: rect2 + }); + }); + observer.observe(); + return function() { + observer.unobserve(); + }; + }, [element]); + return rect; }; -var findLeaf = (root, getNodeValue, handlers) => { - var _handlers$onNodeVisit; - if (root == null) { - return void 0; - } - handlers === null || handlers === void 0 ? void 0 : (_handlers$onNodeVisit = handlers.onNodeVisit) === null || _handlers$onNodeVisit === void 0 ? void 0 : _handlers$onNodeVisit.call(handlers, root); - if (root.type === "leaf") { - return root; - } - const nodeValue = getNodeValue(root.nodeKey); - return findLeaf(root.branches.get(nodeValue), getNodeValue, handlers); +var _excluded5 = ["align"]; +var defaultEstimateSize = function defaultEstimateSize2() { + return 50; }; -var addLeaf = (root, route, parent, value, branchKey, handlers) => { - var _handlers$onNodeVisit2; - let node; - if (root == null) { - if (route.length === 0) { - node = { - type: "leaf", - value, - parent, - branchKey - }; - } else { - const [path, ...rest] = route; - const [nodeKey, nodeValue] = path; - node = { - type: "branch", - nodeKey, - parent, - branches: /* @__PURE__ */ new Map(), - branchKey - }; - node.branches.set(nodeValue, addLeaf(null, rest, node, value, nodeValue, handlers)); - } - } else { - node = root; - if (route.length) { - const [path, ...rest] = route; - const [nodeKey, nodeValue] = path; - !(root.type === "branch" && root.nodeKey === nodeKey) ? true ? Recoil_invariant(false, "Existing cache must have a branch midway through the route with matching node key") : Recoil_invariant(false) : void 0; - root.branches.set(nodeValue, addLeaf(root.branches.get(nodeValue), rest, root, value, nodeValue, handlers)); - } - } - handlers === null || handlers === void 0 ? void 0 : (_handlers$onNodeVisit2 = handlers.onNodeVisit) === null || _handlers$onNodeVisit2 === void 0 ? void 0 : _handlers$onNodeVisit2.call(handlers, node); - return node; +var defaultKeyExtractor = function defaultKeyExtractor2(index) { + return index; }; -var pruneNodeFromTree = (root, node, parent) => { - if (!parent) { - return root === node; - } - parent.branches.delete(node.branchKey); - return pruneUpstreamBranches(root, parent, parent.parent); +var defaultMeasureSize = function defaultMeasureSize2(el, horizontal) { + var key2 = horizontal ? "offsetWidth" : "offsetHeight"; + return el[key2]; }; -var pruneUpstreamBranches = (root, branchNode, parent) => { - if (!parent) { - return root === branchNode; - } - if (branchNode.branches.size === 0) { - parent.branches.delete(branchNode.branchKey); +var defaultRangeExtractor = function defaultRangeExtractor2(range) { + var start = Math.max(range.start - range.overscan, 0); + var end = Math.min(range.end + range.overscan, range.size - 1); + var arr = []; + for (var _i = start; _i <= end; _i++) { + arr.push(_i); } - return pruneUpstreamBranches(root, parent, parent.parent); -}; -var countDownstreamLeaves = (node) => node.type === "leaf" ? 1 : Array.from(node.branches.values()).reduce((sum2, currNode) => sum2 + countDownstreamLeaves(currNode), 0); -var Recoil_TreeCache = { - TreeCache + return arr; }; -var Recoil_TreeCache_1 = Recoil_TreeCache.TreeCache; -var Recoil_TreeCache$1 = /* @__PURE__ */ Object.freeze({ - __proto__: null, - TreeCache: Recoil_TreeCache_1 -}); -var LRUCache = class { - constructor(options) { - var _options$mapKey; - _defineProperty(this, "_maxSize", void 0); - _defineProperty(this, "_size", void 0); - _defineProperty(this, "_head", void 0); - _defineProperty(this, "_tail", void 0); - _defineProperty(this, "_map", void 0); - _defineProperty(this, "_keyMapper", void 0); - this._maxSize = options.maxSize; - this._size = 0; - this._head = null; - this._tail = null; - this._map = /* @__PURE__ */ new Map(); - this._keyMapper = (_options$mapKey = options.mapKey) !== null && _options$mapKey !== void 0 ? _options$mapKey : (v3) => v3; - } - head() { - return this._head; - } - tail() { - return this._tail; - } - size() { - return this._size; - } - maxSize() { - return this._maxSize; - } - has(key2) { - return this._map.has(this._keyMapper(key2)); - } - get(key2) { - const mappedKey = this._keyMapper(key2); - const node = this._map.get(mappedKey); - if (!node) { - return void 0; +var useVirtual = function useVirtual2(_ref) { + var _measurements; + var _ref$size = _ref.size, size = _ref$size === void 0 ? 0 : _ref$size, _ref$estimateSize = _ref.estimateSize, estimateSize = _ref$estimateSize === void 0 ? defaultEstimateSize : _ref$estimateSize, _ref$overscan = _ref.overscan, overscan = _ref$overscan === void 0 ? 1 : _ref$overscan, _ref$paddingStart = _ref.paddingStart, paddingStart = _ref$paddingStart === void 0 ? 0 : _ref$paddingStart, _ref$paddingEnd = _ref.paddingEnd, paddingEnd = _ref$paddingEnd === void 0 ? 0 : _ref$paddingEnd, parentRef = _ref.parentRef, _ref$horizontal = _ref.horizontal, horizontal = _ref$horizontal === void 0 ? false : _ref$horizontal, scrollToFn = _ref.scrollToFn, useObserver = _ref.useObserver, initialRect = _ref.initialRect, onScrollElement = _ref.onScrollElement, scrollOffsetFn = _ref.scrollOffsetFn, _ref$keyExtractor = _ref.keyExtractor, keyExtractor = _ref$keyExtractor === void 0 ? defaultKeyExtractor : _ref$keyExtractor, _ref$measureSize = _ref.measureSize, measureSize = _ref$measureSize === void 0 ? defaultMeasureSize : _ref$measureSize, _ref$rangeExtractor = _ref.rangeExtractor, rangeExtractor = _ref$rangeExtractor === void 0 ? defaultRangeExtractor : _ref$rangeExtractor; + var sizeKey = horizontal ? "width" : "height"; + var scrollKey = horizontal ? "scrollLeft" : "scrollTop"; + var latestRef = _2({ + outerSize: 0, + scrollOffset: 0, + measurements: [], + totalSize: 0 + }); + var _React$useState = h2(0), scrollOffset = _React$useState[0], setScrollOffset = _React$useState[1]; + latestRef.current.scrollOffset = scrollOffset; + var useMeasureParent = useObserver || useRect2; + var _useMeasureParent = useMeasureParent(parentRef, initialRect), outerSize = _useMeasureParent[sizeKey]; + latestRef.current.outerSize = outerSize; + var defaultScrollToFn = T2(function(offset2) { + if (parentRef.current) { + parentRef.current[scrollKey] = offset2; } - this.set(key2, node.value); - return node.value; - } - set(key2, val) { - const mappedKey = this._keyMapper(key2); - const existingNode = this._map.get(mappedKey); - if (existingNode) { - this.delete(key2); + }, [parentRef, scrollKey]); + var resolvedScrollToFn = scrollToFn || defaultScrollToFn; + var scrollTo = T2(function(offset2) { + resolvedScrollToFn(offset2, defaultScrollToFn); + }, [defaultScrollToFn, resolvedScrollToFn]); + var _React$useState2 = h2({}), measuredCache = _React$useState2[0], setMeasuredCache = _React$useState2[1]; + var measure = T2(function() { + return setMeasuredCache({}); + }, []); + var pendingMeasuredCacheIndexesRef = _2([]); + var measurements = F2(function() { + var min3 = pendingMeasuredCacheIndexesRef.current.length > 0 ? Math.min.apply(Math, pendingMeasuredCacheIndexesRef.current) : 0; + pendingMeasuredCacheIndexesRef.current = []; + var measurements2 = latestRef.current.measurements.slice(0, min3); + for (var _i2 = min3; _i2 < size; _i2++) { + var key2 = keyExtractor(_i2); + var measuredSize = measuredCache[key2]; + var _start = measurements2[_i2 - 1] ? measurements2[_i2 - 1].end : paddingStart; + var _size = typeof measuredSize === "number" ? measuredSize : estimateSize(_i2); + var _end = _start + _size; + measurements2[_i2] = { + index: _i2, + start: _start, + size: _size, + end: _end, + key: key2 + }; } - const head = this.head(); - const node = { - key: key2, - right: head, - left: null, - value: val - }; - if (head) { - head.left = node; - } else { - this._tail = node; + return measurements2; + }, [estimateSize, measuredCache, paddingStart, size, keyExtractor]); + var totalSize = (((_measurements = measurements[size - 1]) == null ? void 0 : _measurements.end) || paddingStart) + paddingEnd; + latestRef.current.measurements = measurements; + latestRef.current.totalSize = totalSize; + var element = onScrollElement ? onScrollElement.current : parentRef.current; + var scrollOffsetFnRef = _2(scrollOffsetFn); + scrollOffsetFnRef.current = scrollOffsetFn; + useIsomorphicLayoutEffect3(function() { + if (!element) { + setScrollOffset(0); + return; } - this._map.set(mappedKey, node); - this._head = node; - this._size++; - this._maybeDeleteLRU(); - } - _maybeDeleteLRU() { - if (this.size() > this.maxSize()) { - this.deleteLru(); + var onScroll = function onScroll2(event) { + var offset2 = scrollOffsetFnRef.current ? scrollOffsetFnRef.current(event) : element[scrollKey]; + setScrollOffset(offset2); + }; + onScroll(); + element.addEventListener("scroll", onScroll, { + capture: false, + passive: true + }); + return function() { + element.removeEventListener("scroll", onScroll); + }; + }, [element, scrollKey]); + var _calculateRange = calculateRange(latestRef.current), start = _calculateRange.start, end = _calculateRange.end; + var indexes = F2(function() { + return rangeExtractor({ + start, + end, + overscan, + size: measurements.length + }); + }, [start, end, overscan, measurements.length, rangeExtractor]); + var measureSizeRef = _2(measureSize); + measureSizeRef.current = measureSize; + var virtualItems = F2(function() { + var virtualItems2 = []; + var _loop = function _loop2(k6, len2) { + var i4 = indexes[k6]; + var measurement = measurements[i4]; + var item = _extends({}, measurement, { + measureRef: function measureRef(el) { + if (el) { + var measuredSize = measureSizeRef.current(el, horizontal); + if (measuredSize !== item.size) { + var _scrollOffset = latestRef.current.scrollOffset; + if (item.start < _scrollOffset) { + defaultScrollToFn(_scrollOffset + (measuredSize - item.size)); + } + pendingMeasuredCacheIndexesRef.current.push(i4); + setMeasuredCache(function(old) { + var _extends2; + return _extends({}, old, (_extends2 = {}, _extends2[item.key] = measuredSize, _extends2)); + }); + } + } + } + }); + virtualItems2.push(item); + }; + for (var k5 = 0, len = indexes.length; k5 < len; k5++) { + _loop(k5); } - } - deleteLru() { - const tail = this.tail(); - if (tail) { - this.delete(tail.key); + return virtualItems2; + }, [indexes, defaultScrollToFn, horizontal, measurements]); + var mountedRef = _2(false); + useIsomorphicLayoutEffect3(function() { + if (mountedRef.current) { + setMeasuredCache({}); } - } - delete(key2) { - const mappedKey = this._keyMapper(key2); - if (!this._size || !this._map.has(mappedKey)) { - return; + mountedRef.current = true; + }, [estimateSize]); + var scrollToOffset = T2(function(toOffset, _temp) { + var _ref2 = _temp === void 0 ? { + align: "start" + } : _temp, align = _ref2.align; + var _latestRef$current = latestRef.current, scrollOffset2 = _latestRef$current.scrollOffset, outerSize2 = _latestRef$current.outerSize; + if (align === "auto") { + if (toOffset <= scrollOffset2) { + align = "start"; + } else if (toOffset >= scrollOffset2 + outerSize2) { + align = "end"; + } else { + align = "start"; + } } - const node = Recoil_nullthrows(this._map.get(mappedKey)); - const right = node.right; - const left = node.left; - if (right) { - right.left = node.left; + if (align === "start") { + scrollTo(toOffset); + } else if (align === "end") { + scrollTo(toOffset - outerSize2); + } else if (align === "center") { + scrollTo(toOffset - outerSize2 / 2); } - if (left) { - left.right = node.right; + }, [scrollTo]); + var tryScrollToIndex = T2(function(index, _temp2) { + var _ref3 = _temp2 === void 0 ? { + align: "auto" + } : _temp2, align = _ref3.align, rest = _objectWithoutPropertiesLoose2(_ref3, _excluded5); + var _latestRef$current2 = latestRef.current, measurements2 = _latestRef$current2.measurements, scrollOffset2 = _latestRef$current2.scrollOffset, outerSize2 = _latestRef$current2.outerSize; + var measurement = measurements2[Math.max(0, Math.min(index, size - 1))]; + if (!measurement) { + return; } - if (node === this.head()) { - this._head = right; + if (align === "auto") { + if (measurement.end >= scrollOffset2 + outerSize2) { + align = "end"; + } else if (measurement.start <= scrollOffset2) { + align = "start"; + } else { + return; + } } - if (node === this.tail()) { - this._tail = left; + var toOffset = align === "center" ? measurement.start + measurement.size / 2 : align === "end" ? measurement.end : measurement.start; + scrollToOffset(toOffset, _extends({ + align + }, rest)); + }, [scrollToOffset, size]); + var scrollToIndex = T2(function(index, options) { + tryScrollToIndex(index, options); + requestAnimationFrame(function() { + tryScrollToIndex(index, options); + }); + }, [tryScrollToIndex]); + return { + virtualItems, + totalSize, + scrollToOffset, + scrollToIndex, + measure + }; +}; +var findNearestBinarySearch = function findNearestBinarySearch2(low, high, getCurrentValue, value) { + while (low <= high) { + var middle = (low + high) / 2 | 0; + var currentValue = getCurrentValue(middle); + if (currentValue < value) { + low = middle + 1; + } else if (currentValue > value) { + high = middle - 1; + } else { + return middle; } - this._map.delete(mappedKey); - this._size--; } - clear() { - this._size = 0; - this._head = null; - this._tail = null; - this._map = /* @__PURE__ */ new Map(); + if (low > 0) { + return low - 1; + } else { + return 0; } }; -var Recoil_LRUCache = { - LRUCache -}; -var Recoil_LRUCache_1 = Recoil_LRUCache.LRUCache; -var Recoil_LRUCache$1 = /* @__PURE__ */ Object.freeze({ - __proto__: null, - LRUCache: Recoil_LRUCache_1 -}); -var { - LRUCache: LRUCache$1 -} = Recoil_LRUCache$1; -var { - TreeCache: TreeCache$1 -} = Recoil_TreeCache$1; -function treeCacheLRU(maxSize, mapNodeValue = (v3) => v3) { - const lruCache = new LRUCache$1({ - maxSize - }); - const cache = new TreeCache$1({ - mapNodeValue, - onHit: (node) => { - lruCache.set(node, true); - }, - onSet: (node) => { - const lruNode = lruCache.tail(); - lruCache.set(node, true); - if (lruNode && cache.size() > maxSize) { - cache.delete(lruNode.key); - } - } - }); - return cache; -} -var Recoil_treeCacheLRU = treeCacheLRU; -var { - TreeCache: TreeCache$2 -} = Recoil_TreeCache$1; -var defaultPolicy = { - equality: "reference", - eviction: "keep-all", - maxSize: Infinity -}; -function treeCacheFromPolicy({ - equality = defaultPolicy.equality, - eviction = defaultPolicy.eviction, - maxSize = defaultPolicy.maxSize -} = defaultPolicy) { - const valueMapper = getValueMapper(equality); - const treeCache = getTreeCache(eviction, maxSize, valueMapper); - return treeCache; -} -function getValueMapper(equality) { - switch (equality) { - case "reference": - return (val) => val; - case "value": - return (val) => Recoil_stableStringify(val); - } - throw new Error(`Unrecognized equality policy ${equality}`); -} -function getTreeCache(eviction, maxSize, mapNodeValue) { - switch (eviction) { - case "keep-all": - return new TreeCache$2({ - mapNodeValue - }); - case "lru": - return Recoil_treeCacheLRU(Recoil_nullthrows(maxSize), mapNodeValue); - case "most-recent": - return Recoil_treeCacheLRU(1, mapNodeValue); +function calculateRange(_ref4) { + var measurements = _ref4.measurements, outerSize = _ref4.outerSize, scrollOffset = _ref4.scrollOffset; + var size = measurements.length - 1; + var getOffset = function getOffset2(index) { + return measurements[index].start; + }; + var start = findNearestBinarySearch(0, size, getOffset, scrollOffset); + var end = start; + while (end < size && measurements[end].end < scrollOffset + outerSize) { + end++; } - throw new Error(`Unrecognized eviction policy ${eviction}`); -} -var Recoil_treeCacheFromPolicy = treeCacheFromPolicy; -function startPerfBlock(_id) { - return () => null; -} -var Recoil_PerformanceTimings = { - startPerfBlock -}; -var { - CANCELED: CANCELED$2, - Canceled: Canceled$1, - loadableWithError: loadableWithError$1, - loadableWithPromise: loadableWithPromise$1, - loadableWithValue: loadableWithValue$2 -} = Recoil_Loadable; -var { - getNodeLoadable: getNodeLoadable$2, - peekNodeLoadable: peekNodeLoadable$1, - setNodeValue: setNodeValue$3 -} = Recoil_FunctionalCore; -var { - saveDependencyMapToStore: saveDependencyMapToStore$1 -} = Recoil_Graph; -var { - DEFAULT_VALUE: DEFAULT_VALUE$4, - RecoilValueNotReady: RecoilValueNotReady$2, - getConfigDeletionHandler: getConfigDeletionHandler$1, - registerNode: registerNode$1 -} = Recoil_Node; -var { - isRecoilValue: isRecoilValue$3 -} = Recoil_RecoilValue$1; -var { - AbstractRecoilValue: AbstractRecoilValue$4 -} = Recoil_RecoilValue$1; -var { - setRecoilValueLoadable: setRecoilValueLoadable$2 -} = Recoil_RecoilValueInterface; -var { - retainedByOptionWithDefault: retainedByOptionWithDefault$1 -} = Recoil_Retention; -var { - cloneSnapshot: cloneSnapshot$2 -} = Recoil_Snapshot$1; -var { - startPerfBlock: startPerfBlock$1 -} = Recoil_PerformanceTimings; -var dependencyStack = []; -var waitingStores = /* @__PURE__ */ new Map(); -var getNewExecutionId = (() => { - let executionId = 0; - return () => executionId++; -})(); -function getInitialExecutionInfo() { return { - depValuesDiscoveredSoFarDuringAsyncWork: null, - latestLoadable: null, - latestExecutionId: null, - stateVersion: null + start, + end }; } -function selector(options) { + +// src/components/Navigator/SpaceTree/SpaceTreeVirtualized.tsx +var VirtualizedList = Cn.memo(function VirtualizedList2(props2) { const { - key: key2, - get, - cachePolicy_UNSTABLE: cachePolicy - } = options; - const set = options.set != null ? options.set : void 0; - const cache = Recoil_treeCacheFromPolicy(cachePolicy !== null && cachePolicy !== void 0 ? cachePolicy : { - equality: "reference", - eviction: "keep-all" + flattenedTree, + projected, + vRef, + selectedFiles, + activeFile, + selectRange: selectRange2, + handleCollapse, + plugin, + overIndex, + activeIndex, + indentationWidth + } = props2; + const parentRef = Cn.useRef(null); + const rowHeight = (index) => flattenedTree[index].parentId == null ? spaceRowHeight(plugin) : spaceRowHeight(plugin); + const rowVirtualizer = useVirtual({ + size: flattenedTree.length, + paddingEnd: 24, + parentRef, + estimateSize: Cn.useCallback( + (index) => rowHeight(index), + [flattenedTree] + ), + overscan: plugin.settings.spacesPerformance ? 0 : 20 }); - const retainedBy = retainedByOptionWithDefault$1(options.retainedBy_UNSTABLE); - const executionInfoMap = /* @__PURE__ */ new Map(); - let liveStoresCount = 0; - function selectorIsLive() { - return !Recoil_gkx_1("recoil_memory_managament_2020") || liveStoresCount > 0; - } - function getExecutionInfo(store) { - if (!executionInfoMap.has(store)) { - executionInfoMap.set(store, getInitialExecutionInfo()); - } - return Recoil_nullthrows(executionInfoMap.get(store)); - } - function selectorInit(store) { - liveStoresCount++; - store.getState().knownSelectors.add(key2); - return () => { - liveStoresCount--; - store.getState().knownSelectors.delete(key2); - executionInfoMap.delete(store); - }; - } - function selectorShouldDeleteConfigOnRelease() { - return getConfigDeletionHandler$1(key2) !== void 0 && !selectorIsLive(); - } - function notifyStoreWhenAsyncSettles(store, loadable, executionId) { - if (loadable.state === "loading") { - let stores = waitingStores.get(executionId); - if (stores == null) { - waitingStores.set(executionId, stores = /* @__PURE__ */ new Set()); - } - stores.add(store); - } - } - function notifyStoresOfSettledAsync(newLoadable, executionId) { - const stores = waitingStores.get(executionId); - if (stores !== void 0) { - for (const store of stores) { - setRecoilValueLoadable$2(store, new AbstractRecoilValue$4(key2), newLoadable); - } - waitingStores.delete(executionId); - } - } - function getCachedNodeLoadable(store, state, key3) { - const isKeyPointingToSelector = store.getState().knownSelectors.has(key3); - if (isKeyPointingToSelector && state.atomValues.has(key3)) { - return Recoil_nullthrows(state.atomValues.get(key3)); - } - const loadable = getNodeLoadable$2(store, state, key3); - if (loadable.state !== "loading" && isKeyPointingToSelector) { - state.atomValues.set(key3, loadable); - } - return loadable; - } - function wrapPendingPromise(store, promise, state, depValues, executionId) { - return promise.then((value) => { - if (!selectorIsLive()) { - clearExecutionInfo(store, executionId); - return CANCELED$2; - } - const loadable = loadableWithValue$2(value); - maybeFreezeValue(value); - setCache(state, depValuesToDepRoute(depValues), loadable); - setDepsInStore(store, state, new Set(depValues.keys()), executionId); - setLoadableInStoreToNotifyDeps(store, loadable, executionId); - return { - __value: value, - __key: key2 - }; - }).catch((errorOrPromise) => { - if (!selectorIsLive()) { - clearExecutionInfo(store, executionId); - return CANCELED$2; - } - if (isLatestExecution(store, executionId)) { - updateExecutionInfoDepValues(depValues, store, executionId); - } - if (Recoil_isPromise(errorOrPromise)) { - return wrapPendingDependencyPromise(store, errorOrPromise, state, depValues, executionId); - } - const loadable = loadableWithError$1(errorOrPromise); - maybeFreezeValue(errorOrPromise); - setCache(state, depValuesToDepRoute(depValues), loadable); - setDepsInStore(store, state, new Set(depValues.keys()), executionId); - setLoadableInStoreToNotifyDeps(store, loadable, executionId); - throw errorOrPromise; - }); - } - function wrapPendingDependencyPromise(store, promise, state, existingDeps, executionId) { - return promise.then((resolvedDep) => { - if (!selectorIsLive()) { - clearExecutionInfo(store, executionId); - return CANCELED$2; - } - if (resolvedDep instanceof Canceled$1) { - Recoil_recoverableViolation("Selector was released while it had dependencies"); - return CANCELED$2; - } - const { - __key: resolvedDepKey, - __value: depValue - } = resolvedDep !== null && resolvedDep !== void 0 ? resolvedDep : {}; - let bypassSelectorDepCacheOnReevaluation = true; - if (resolvedDepKey != null) { - state.atomValues.set(resolvedDepKey, loadableWithValue$2(depValue)); - bypassSelectorDepCacheOnReevaluation = false; - } - const cachedLoadable = getValFromCacheAndUpdatedDownstreamDeps(store, state); - if (cachedLoadable && cachedLoadable.state === "hasValue") { - setExecutionInfo(cachedLoadable, store); - return { - __value: cachedLoadable.contents, - __key: key2 - }; - } - if (!isLatestExecution(store, executionId)) { - var _executionInfo$latest; - const executionInfo = getExecutionInfoOfInProgressExecution(state); - if ((executionInfo === null || executionInfo === void 0 ? void 0 : (_executionInfo$latest = executionInfo.latestLoadable) === null || _executionInfo$latest === void 0 ? void 0 : _executionInfo$latest.state) === "loading") { - return executionInfo.latestLoadable.contents; - } - } - const [loadable, depValues] = evaluateSelectorGetter(store, state, executionId, bypassSelectorDepCacheOnReevaluation); - if (isLatestExecution(store, executionId)) { - updateExecutionInfoDepValues(depValues, store, executionId); - } - maybeFreezeLoadableContents(loadable); - if (loadable.state !== "loading") { - setCache(state, depValuesToDepRoute(depValues), loadable); - setDepsInStore(store, state, new Set(depValues.keys()), executionId); - setLoadableInStoreToNotifyDeps(store, loadable, executionId); - } - if (loadable.state === "hasError") { - throw loadable.contents; - } - if (loadable.state === "hasValue") { - return { - __value: loadable.contents, - __key: key2 - }; - } - return loadable.contents; - }).catch((error) => { - if (!selectorIsLive()) { - clearExecutionInfo(store, executionId); - return CANCELED$2; - } - const loadable = loadableWithError$1(error); - maybeFreezeValue(error); - setCache(state, depValuesToDepRoute(existingDeps), loadableWithError$1(error)); - setDepsInStore(store, state, new Set(existingDeps.keys()), executionId); - setLoadableInStoreToNotifyDeps(store, loadable, executionId); - throw error; - }); - } - function setLoadableInStoreToNotifyDeps(store, loadable, executionId) { - if (isLatestExecution(store, executionId)) { - setExecutionInfo(loadable, store); - notifyStoresOfSettledAsync(loadable, executionId); - } - } - function setDepsInStore(store, state, deps, executionId) { - var _store$getState, _store$getState$curre, _store$getState2, _store$getState2$next; - if (isLatestExecution(store, executionId) || state.version === ((_store$getState = store.getState()) === null || _store$getState === void 0 ? void 0 : (_store$getState$curre = _store$getState.currentTree) === null || _store$getState$curre === void 0 ? void 0 : _store$getState$curre.version) || state.version === ((_store$getState2 = store.getState()) === null || _store$getState2 === void 0 ? void 0 : (_store$getState2$next = _store$getState2.nextTree) === null || _store$getState2$next === void 0 ? void 0 : _store$getState2$next.version)) { - var _store$getState$nextT, _store$getState3, _store$getState3$next; - saveDependencyMapToStore$1(/* @__PURE__ */ new Map([[key2, deps]]), store, (_store$getState$nextT = (_store$getState3 = store.getState()) === null || _store$getState3 === void 0 ? void 0 : (_store$getState3$next = _store$getState3.nextTree) === null || _store$getState3$next === void 0 ? void 0 : _store$getState3$next.version) !== null && _store$getState$nextT !== void 0 ? _store$getState$nextT : store.getState().currentTree.version); - } - } - function setNewDepInStore(store, state, deps, newDepKey, executionId) { - deps.add(newDepKey); - setDepsInStore(store, state, deps, executionId); - } - function evaluateSelectorGetter(store, state, executionId, bypassSelectorDepCache = false) { - const endPerfBlock = startPerfBlock$1(key2); - let result; - let resultIsError = false; - let loadable; - const depValues = /* @__PURE__ */ new Map(); - const deps = /* @__PURE__ */ new Set(); - setDepsInStore(store, state, deps, executionId); - function getRecoilValue(recoilValue) { - const { - key: depKey - } = recoilValue; - setNewDepInStore(store, state, deps, depKey, executionId); - const depLoadable = bypassSelectorDepCache ? getNodeLoadable$2(store, state, depKey) : getCachedNodeLoadable(store, state, depKey); - maybeFreezeLoadableContents(depLoadable); - depValues.set(depKey, depLoadable); - if (depLoadable.state === "hasValue") { - return depLoadable.contents; - } - throw depLoadable.contents; - } - let gateCallback = false; - const getCallback = (fn2) => { - return (...args) => { - if (!gateCallback) { - throw new Error("getCallback() should only be called asynchronously after the selector is evalutated. It can be used for selectors to return objects with callbacks that can obtain the current Recoil state without a subscription."); - } - const snapshot = cloneSnapshot$2(store); - const cb = fn2({ - snapshot - }); - if (typeof cb !== "function") { - throw new Error("getCallback() expects a function that returns a function."); - } - return cb(...args); - }; - }; - try { - result = get({ - get: getRecoilValue, - getCallback - }); - result = isRecoilValue$3(result) ? getRecoilValue(result) : result; - gateCallback = true; - if (Recoil_isPromise(result)) { - result = wrapPendingPromise(store, result, state, depValues, executionId).finally(endPerfBlock); + vRef.current = rowVirtualizer; + rowVirtualizer.scrollToIndex; + const dropIndicator = (index) => { + return overIndex == index && projected && projected.insert; + }; + const highlighted = (index) => { + if (!projected || !flattenedTree[index] || !(projected == null ? void 0 : projected.droppable)) + return false; + return !projected.sortable && !projected.insert && flattenedTree[index].parentId && flattenedTree[index].parentId.startsWith(projected.parentId) || flattenedTree[index].id == projected.parentId; + }; + const calcYOffset = (index) => { + if (!projected) + return 0; + if (projected.insert) { + if (projected.copy && !projected.reorder) + return 0; + if (index > activeIndex) { + return -spaceRowHeight(plugin); + } else if (index == activeIndex) { + return spaceRowHeight(plugin) * (overIndex - activeIndex); } else { - endPerfBlock(); + return 0; + } + } else if (projected.sortable) { + const targetIndex = overIndex < activeIndex ? overIndex : overIndex; + if (projected.copy && !projected.reorder) { + if (index == activeIndex) { + return spaceRowHeight(plugin) * (targetIndex - activeIndex); + } else if (index >= targetIndex) { + return spaceRowHeight(plugin); + } else { + return 0; + } } - } catch (errorOrDepPromise) { - result = errorOrDepPromise; - if (Recoil_isPromise(result)) { - result = wrapPendingDependencyPromise(store, result, state, depValues, executionId).finally(endPerfBlock); + if (index == activeIndex) { + return spaceRowHeight(plugin) * (targetIndex - activeIndex); + } else if (index > activeIndex && index <= targetIndex) { + return -spaceRowHeight(plugin); + } else if (index < activeIndex && index >= targetIndex) { + return spaceRowHeight(plugin); } else { - resultIsError = true; - endPerfBlock(); + return 0; } } - if (resultIsError) { - loadable = loadableWithError$1(result); - } else if (Recoil_isPromise(result)) { - loadable = loadableWithPromise$1(result); - } else { - loadable = loadableWithValue$2(result); - } - maybeFreezeLoadableContents(loadable); - return [loadable, depValues]; - } - function getValFromCacheAndUpdatedDownstreamDeps(store, state) { - const depsAfterCacheDone = /* @__PURE__ */ new Set(); - const executionInfo = getExecutionInfo(store); - const cachedVal = cache.get((nodeKey) => { - !(typeof nodeKey === "string") ? true ? Recoil_invariant(false, "Cache nodeKey is type string") : Recoil_invariant(false) : void 0; - const loadable = getCachedNodeLoadable(store, state, nodeKey); - return loadable.contents; - }, { - onNodeVisit: (node) => { - if (node.type === "branch" && node.nodeKey !== key2 && typeof node.nodeKey === "string") { - depsAfterCacheDone.add(node.nodeKey); - } - } - }); - if (cachedVal) { - setDepsInStore(store, state, depsAfterCacheDone, executionInfo.latestExecutionId); - } - return cachedVal; - } - function depValuesToDepRoute(depValues) { - return Array.from(depValues.entries()).map(([key3, valLoadable]) => [key3, valLoadable.contents]); - } - function getValFromRunningNewExecutionAndUpdatedDeps(store, state) { - const newExecutionId = getNewExecutionId(); - const [loadable, newDepValues] = evaluateSelectorGetter(store, state, newExecutionId); - setExecutionInfo(loadable, store, newDepValues, newExecutionId, state); - maybeSetCacheWithLoadable(state, depValuesToDepRoute(newDepValues), loadable); - notifyStoreWhenAsyncSettles(store, loadable, newExecutionId); - return loadable; - } - function getSelectorValAndUpdatedDeps(store, state) { - const cachedVal = getValFromCacheAndUpdatedDownstreamDeps(store, state); - if (cachedVal != null) { - setExecutionInfo(cachedVal, store); - return cachedVal; - } - const inProgressExecutionInfo = getExecutionInfoOfInProgressExecution(state); - if (inProgressExecutionInfo) { - const executionInfo = inProgressExecutionInfo; - notifyStoreWhenAsyncSettles(store, Recoil_nullthrows(executionInfo.latestLoadable), Recoil_nullthrows(executionInfo.latestExecutionId)); - return Recoil_nullthrows(executionInfo.latestLoadable); - } - return getValFromRunningNewExecutionAndUpdatedDeps(store, state); - } - function getExecutionInfoOfInProgressExecution(state) { - var _Array$from$find; - const [, executionInfo] = (_Array$from$find = Array.from(executionInfoMap.entries()).find(([store, executionInfo2]) => { - return executionInfo2.latestLoadable != null && executionInfo2.latestExecutionId != null && !haveAsyncDepsChanged(store, state); - })) !== null && _Array$from$find !== void 0 ? _Array$from$find : []; - return executionInfo; - } - const mapOfCheckedVersions = /* @__PURE__ */ new Map(); - function haveAsyncDepsChanged(store, state) { - var _executionInfo$depVal, _mapOfCheckedVersions; - const executionInfo = getExecutionInfo(store); - const oldDepValues = (_executionInfo$depVal = executionInfo.depValuesDiscoveredSoFarDuringAsyncWork) !== null && _executionInfo$depVal !== void 0 ? _executionInfo$depVal : /* @__PURE__ */ new Map(); - const cachedDepValuesCheckedForThisVersion = Array(((_mapOfCheckedVersions = mapOfCheckedVersions.get(state.version)) !== null && _mapOfCheckedVersions !== void 0 ? _mapOfCheckedVersions : /* @__PURE__ */ new Map()).entries()); - const isCachedVersionSame = mapOfCheckedVersions.has(state.version) && cachedDepValuesCheckedForThisVersion.length === oldDepValues.size && cachedDepValuesCheckedForThisVersion.every(([nodeKey, nodeVal]) => { - return oldDepValues.get(nodeKey) === nodeVal; - }); - if (oldDepValues == null || state.version === executionInfo.stateVersion || isCachedVersionSame) { - return false; - } - mapOfCheckedVersions.set(state.version, new Map(oldDepValues)); - return Array.from(oldDepValues).some(([nodeKey, oldVal]) => { - const loadable = getCachedNodeLoadable(store, state, nodeKey); - return loadable.contents !== oldVal.contents; - }); - } - function setExecutionInfo(loadable, store, depValues, newExecutionId, state) { - const executionInfo = getExecutionInfo(store); - if (loadable.state === "loading") { - executionInfo.depValuesDiscoveredSoFarDuringAsyncWork = depValues; - executionInfo.latestExecutionId = newExecutionId; - executionInfo.latestLoadable = loadable; - executionInfo.stateVersion = state === null || state === void 0 ? void 0 : state.version; - } else { - executionInfo.depValuesDiscoveredSoFarDuringAsyncWork = null; - executionInfo.latestExecutionId = null; - executionInfo.latestLoadable = null; - executionInfo.stateVersion = null; - } - } - function maybeSetCacheWithLoadable(state, depRoute, loadable) { - if (loadable.state !== "loading") { - setCache(state, depRoute, loadable); - } - } - function updateExecutionInfoDepValues(depValues, store, executionId) { - const executionInfo = getExecutionInfo(store); - if (isLatestExecution(store, executionId)) { - executionInfo.depValuesDiscoveredSoFarDuringAsyncWork = depValues; - } - } - function clearExecutionInfo(store, executionId) { - if (isLatestExecution(store, executionId)) { - executionInfoMap.delete(store); - } - } - function isLatestExecution(store, executionId) { - const executionInfo = getExecutionInfo(store); - return executionId === executionInfo.latestExecutionId; - } - function maybeFreezeLoadableContents(loadable) { - if (loadable.state !== "loading") { - maybeFreezeValue(loadable.contents); - } - } - function maybeFreezeValue(val) { - if (true) { - if (Boolean(options.dangerouslyAllowMutability) === false) { - Recoil_deepFreezeValue(val); - } + }; + return /* @__PURE__ */ Cn.createElement("div", { + ref: parentRef, + style: { + width: `100%`, + height: `100%`, + overflow: "auto", + "--spaceRowHeight": spaceRowHeight(plugin) + "px" } - } - function setCache(state, cacheRoute, loadable) { - state.atomValues.set(key2, loadable); - cache.set(cacheRoute, loadable); - } - function detectCircularDependencies(fn2) { - if (dependencyStack.includes(key2)) { - const message = `Recoil selector has circular dependencies: ${dependencyStack.slice(dependencyStack.indexOf(key2)).join(" \u2192 ")}`; - return loadableWithError$1(new Error(message)); + }, /* @__PURE__ */ Cn.createElement("div", { + style: { + height: `${rowVirtualizer.totalSize}px`, + width: "100%", + position: "relative" } - dependencyStack.push(key2); - try { - return fn2(); - } finally { - dependencyStack.pop(); - } - } - function selectorPeek(store, state) { - const cacheVal = cache.get((nodeKey) => { - !(typeof nodeKey === "string") ? true ? Recoil_invariant(false, "Cache nodeKey is type string") : Recoil_invariant(false) : void 0; - const peek = peekNodeLoadable$1(store, state, nodeKey); - return peek === null || peek === void 0 ? void 0 : peek.contents; - }); - return cacheVal; - } - function selectorGet(store, state) { - return detectCircularDependencies(() => getSelectorValAndUpdatedDeps(store, state)); - } - function invalidateSelector(state) { - state.atomValues.delete(key2); - } - if (set != null) { - const selectorSet = (store, state, newValue) => { - let syncSelectorSetFinished = false; - const writes = /* @__PURE__ */ new Map(); - function getRecoilValue({ - key: key3 - }) { - if (syncSelectorSetFinished) { - throw new Error("Recoil: Async selector sets are not currently supported."); - } - const loadable = getCachedNodeLoadable(store, state, key3); - maybeFreezeLoadableContents(loadable); - if (loadable.state === "hasValue") { - return loadable.contents; - } else if (loadable.state === "loading") { - throw new RecoilValueNotReady$2(key3); - } else { - throw loadable.contents; - } - } - function setRecoilState(recoilState, valueOrUpdater) { - if (syncSelectorSetFinished) { - throw new Error("Recoil: Async selector sets are not currently supported."); - } - const newValue2 = typeof valueOrUpdater === "function" ? valueOrUpdater(getRecoilValue(recoilState)) : valueOrUpdater; - const upstreamWrites = setNodeValue$3(store, state, recoilState.key, newValue2); - upstreamWrites.forEach((v3, k5) => writes.set(k5, v3)); - } - function resetRecoilState(recoilState) { - setRecoilState(recoilState, DEFAULT_VALUE$4); - } - const ret = set({ - set: setRecoilState, - get: getRecoilValue, - reset: resetRecoilState - }, newValue); - if (ret !== void 0) { - throw Recoil_isPromise(ret) ? new Error("Recoil: Async selector sets are not currently supported.") : new Error("Recoil: selector set should be a void function."); - } - syncSelectorSetFinished = true; - return writes; - }; - return registerNode$1({ - key: key2, - nodeType: "selector", - peek: selectorPeek, - get: selectorGet, - set: selectorSet, - init: selectorInit, - invalidate: invalidateSelector, - shouldDeleteConfigOnRelease: selectorShouldDeleteConfigOnRelease, - dangerouslyAllowMutability: options.dangerouslyAllowMutability, - shouldRestoreFromSnapshots: false, - retainedBy - }); - } else { - return registerNode$1({ - key: key2, - nodeType: "selector", - peek: selectorPeek, - get: selectorGet, - init: selectorInit, - invalidate: invalidateSelector, - shouldDeleteConfigOnRelease: selectorShouldDeleteConfigOnRelease, - dangerouslyAllowMutability: options.dangerouslyAllowMutability, - shouldRestoreFromSnapshots: false, - retainedBy - }); - } -} -var Recoil_selector = selector; -var { - loadableWithError: loadableWithError$2, - loadableWithPromise: loadableWithPromise$2, - loadableWithValue: loadableWithValue$3 -} = Recoil_Loadable; -var { - DEFAULT_VALUE: DEFAULT_VALUE$5, - DefaultValue: DefaultValue$2, - getConfigDeletionHandler: getConfigDeletionHandler$2, - registerNode: registerNode$2, - setConfigDeletionHandler: setConfigDeletionHandler$1 -} = Recoil_Node; -var { - isRecoilValue: isRecoilValue$4 -} = Recoil_RecoilValue$1; -var { - markRecoilValueModified: markRecoilValueModified$1, - setRecoilValue: setRecoilValue$3, - setRecoilValueLoadable: setRecoilValueLoadable$3 -} = Recoil_RecoilValueInterface; -var { - retainedByOptionWithDefault: retainedByOptionWithDefault$2 -} = Recoil_Retention; -function baseAtom(options) { + }, rowVirtualizer.virtualItems.map((virtualRow) => { + var _a2; + return /* @__PURE__ */ Cn.createElement("div", { + key: virtualRow.index, + ref: virtualRow.measureRef, + style: { + position: "absolute", + top: 0, + left: 0, + width: "100%", + height: `${rowHeight(virtualRow.index)}px`, + transform: `translateY(${virtualRow.start}px)` + } + }, /* @__PURE__ */ Cn.createElement(SortableTreeItem, { + key: flattenedTree[virtualRow.index].id, + id: flattenedTree[virtualRow.index].id, + data: flattenedTree[virtualRow.index], + disabled: false, + depth: flattenedTree[virtualRow.index].depth, + childCount: flattenedTree[virtualRow.index].childrenCount, + indentationWidth, + dragStarted: props2.dragStarted, + dragOver: props2.dragOver, + dragEnded: props2.dragEnded, + dragActive: activeIndex != -1, + indicator: dropIndicator(virtualRow.index), + plugin, + ghost: overIndex != -1 && activeIndex == virtualRow.index, + style: { + opacity: projected && projected.insert && !projected.copy && virtualRow.index == activeIndex ? 0 : 1, + transform: CSS.Translate.toString({ + x: projected && projected.sortable && virtualRow.index == activeIndex && projected ? (projected.depth - flattenedTree[virtualRow.index].depth) * indentationWidth : 0, + y: calcYOffset(virtualRow.index), + scaleX: 0, + scaleY: 0 + }) + }, + onSelectRange: selectRange2, + active: (activeFile == null ? void 0 : activeFile.fullPath) == ((_a2 = flattenedTree[virtualRow.index].item) == null ? void 0 : _a2.path), + highlighted: highlighted(virtualRow.index), + selected: selectedFiles.some( + (g4) => g4.id == flattenedTree[virtualRow.index].id + ), + collapsed: flattenedTree[virtualRow.index].collapsed, + onCollapse: handleCollapse + })); + }))); +}); + +// src/components/Navigator/SpaceTree/SpaceTreeView.tsx +var FileExplorerComponent = (props2) => { + const { plugin } = props2; + const indentationWidth = 16; + const [expandedSpaces, setExpandedSpaces] = h2( + plugin.settings.expandedSpaces + ); const { - key: key2, - persistence_UNSTABLE: persistence - } = options; - const retainedBy = retainedByOptionWithDefault$2(options.retainedBy_UNSTABLE); - let liveStoresCount = 0; - let defaultLoadable = Recoil_isPromise(options.default) ? loadableWithPromise$2(options.default.then((value) => { - defaultLoadable = loadableWithValue$3(value); - const promiseInfo = { - __key: key2, - __value: value - }; - return promiseInfo; - }).catch((error) => { - defaultLoadable = loadableWithError$2(error); - throw error; - })) : loadableWithValue$3(options.default); - let cachedAnswerForUnvalidatedValue = void 0; - const cleanupEffectsByStore = /* @__PURE__ */ new Map(); - function wrapPendingPromise(store, promise) { - const wrappedPromise = promise.then((value) => { - var _store$getState$nextT, _state$atomValues$get; - const state = (_store$getState$nextT = store.getState().nextTree) !== null && _store$getState$nextT !== void 0 ? _store$getState$nextT : store.getState().currentTree; - if (((_state$atomValues$get = state.atomValues.get(key2)) === null || _state$atomValues$get === void 0 ? void 0 : _state$atomValues$get.contents) === wrappedPromise) { - setRecoilValue$3(store, node, value); + activeFile, + activeViewSpace, + setActiveFile, + selectedFiles, + setSelectedFiles, + dragPaths, + setDragPaths, + queryResults, + spaces, + queryMode, + modifier, + setModifier + } = q2(NavigatorContext); + const [activeId, setActiveId] = h2(null); + const [overId, setOverId] = h2(null); + const nextTreeScrollPath = _2(null); + const [offset2, setOffset] = h2({ x: 0, y: 0 }); + const listRef = _2(null); + const forceUpdate = useForceUpdate(); + const treeForPaths = (paths) => { + const tree = []; + paths.map((f4) => { + const s5 = uriByString(props2.plugin, f4); + if (s5.type == "tag" || s5.type == "space" || s5.type == "folder" || s5.type == "vault") { + return props2.plugin.index.spacesIndex.get(f4); } + const fileCache = props2.plugin.index.filesIndex.get(f4); return { - __key: key2, - __value: value + ...fileCache }; - }).catch((error) => { - var _store$getState$nextT2, _state$atomValues$get2; - const state = (_store$getState$nextT2 = store.getState().nextTree) !== null && _store$getState$nextT2 !== void 0 ? _store$getState$nextT2 : store.getState().currentTree; - if (((_state$atomValues$get2 = state.atomValues.get(key2)) === null || _state$atomValues$get2 === void 0 ? void 0 : _state$atomValues$get2.contents) === wrappedPromise) { - setRecoilValueLoadable$3(store, node, loadableWithError$2(error)); - } - throw error; - }); - return wrappedPromise; - } - function initAtom(store, initState, trigger) { - liveStoresCount++; - const alreadyKnown = store.getState().knownAtoms.has(key2); - store.getState().knownAtoms.add(key2); - if (defaultLoadable.state === "loading") { - const notifyDefaultSubscribers = () => { - var _store$getState$nextT3; - const state = (_store$getState$nextT3 = store.getState().nextTree) !== null && _store$getState$nextT3 !== void 0 ? _store$getState$nextT3 : store.getState().currentTree; - if (!state.atomValues.has(key2)) { - markRecoilValueModified$1(store, node); + }).filter((f4) => f4).forEach((item) => { + if (item.cacheType == "file") { + item = item; + tree.push( + vaulItemToTreeNode( + plugin, + item, + item.parent, + item.path, + 0, + 0, + false, + false, + 0, + null + ) + ); + } else { + tree.push( + ...treeForSpace( + item, + 0, + null, + activeId, + false, + false, + null + ) + ); + } + }); + return tree; + }; + const treeForRoot = (space, activeId2) => { + var _a2, _b2, _c2; + const tree = []; + const spaceSort = (_b2 = (_a2 = space.metadata) == null ? void 0 : _a2.sort) != null ? _b2 : { + field: "rank", + asc: true, + group: true + }; + const children = (_c2 = plugin.index.getSpaceItems(space.path)) != null ? _c2 : []; + children.sort(spaceSortFn(spaceSort)).forEach((item) => { + var _a3; + const _parentId = space.path; + if (item.cacheType == "file") { + item = item; + const id2 = _parentId + "/" + item.filename; + const itemCollapsed = !expandedSpaces.includes(id2); + const items = []; + if (!itemCollapsed) { + const sortStrat = ((_a3 = item.sortBy) == null ? void 0 : _a3.length) > 0 ? parseSortStrat(item.sortBy) : spaceSort; + items.push( + ...flattenedTreeFromVaultItems( + plugin, + item.path, + expandedSpaces != null ? expandedSpaces : [], + 1, + sortStrat + ) + ); } - }; - defaultLoadable.contents.then(notifyDefaultSubscribers).catch(notifyDefaultSubscribers); - } - let initValue = DEFAULT_VALUE$5; - let pendingSetSelf = null; - if (options.effects_UNSTABLE != null && !alreadyKnown) { - let duringInit = true; - const setSelf = (effect) => (valueOrUpdater) => { - if (duringInit) { - const currentValue = initValue instanceof DefaultValue$2 || Recoil_isPromise(initValue) ? defaultLoadable.state === "hasValue" ? defaultLoadable.contents : DEFAULT_VALUE$5 : initValue; - initValue = typeof valueOrUpdater === "function" ? valueOrUpdater(currentValue) : valueOrUpdater; - if (Recoil_isPromise(initValue)) { - initValue = initValue.then((value) => { - pendingSetSelf = { - effect, - value - }; - return value; - }); + items.splice( + 0, + 0, + vaulItemToTreeNode( + plugin, + item, + space.path, + item.path, + 0, + 0, + itemCollapsed, + space.sortable, + items.length, + _parentId + ) + ); + tree.push(...items); + } else { + tree.push( + ...treeForSpace( + item, + 0, + _parentId, + activeId2, + space.sortable, + false, + space.path + ) + ); + } + }); + return tree; + }; + const treeForSpace = (space, depth, parentId, activeId2, sortable, root, parentPath) => { + var _a2, _b2, _c2; + const tree = []; + const id2 = parentId ? parentId + "/" + space.path : space.path; + const spaceCollapsed = !expandedSpaces.includes(id2) || activeId2 == id2; + const spaceSort = (_b2 = (_a2 = space.metadata) == null ? void 0 : _a2.sort) != null ? _b2 : { + field: "rank", + asc: true, + group: true + }; + const children = (_c2 = plugin.index.getSpaceItems(space.path)) != null ? _c2 : []; + const hasChildren = children.length > 0; + if (!spaceCollapsed || root) { + children.sort(spaceSortFn(spaceSort)).forEach((item) => { + var _a3; + const _parentId = parentId ? parentId + "/" + space.path : space.path; + if (item.cacheType == "file") { + item = item; + const id3 = _parentId + "/" + item.filename; + const itemCollapsed = !expandedSpaces.includes(id3); + const items = []; + if (!itemCollapsed) { + const sortStrat = ((_a3 = item.sortBy) == null ? void 0 : _a3.length) > 0 ? parseSortStrat(item.sortBy) : spaceSort; + items.push( + ...flattenedTreeFromVaultItems( + plugin, + item.path, + expandedSpaces != null ? expandedSpaces : [], + depth + 2, + sortStrat + ) + ); } + items.splice( + 0, + 0, + vaulItemToTreeNode( + plugin, + item, + space.path, + item.path, + depth + 1, + 0, + itemCollapsed, + space.sortable, + items.length, + _parentId + ) + ); + tree.push(...items); } else { - if (Recoil_isPromise(valueOrUpdater)) { - throw new Error("Setting atoms to async values is not implemented."); - } - if (typeof valueOrUpdater !== "function") { - pendingSetSelf = { - effect, - value: valueOrUpdater - }; - } - setRecoilValue$3(store, node, typeof valueOrUpdater === "function" ? (currentValue) => { - const newValue = valueOrUpdater(currentValue); - pendingSetSelf = { - effect, - value: newValue - }; - return newValue; - } : valueOrUpdater); + tree.push( + ...treeForSpace( + item, + depth + 1, + _parentId, + activeId2, + space.sortable, + false, + space.path + ) + ); } - }; - const resetSelf = (effect) => () => setSelf(effect)(DEFAULT_VALUE$5); - const onSet = (effect) => (handler) => { - store.subscribeToTransactions((currentStore) => { - var _currentTree$atomValu; - let { - currentTree, - previousTree - } = currentStore.getState(); - if (!previousTree) { - Recoil_recoverableViolation("Transaction subscribers notified without a next tree being present -- this is a bug in Recoil"); - previousTree = currentTree; - } - const newLoadable = (_currentTree$atomValu = currentTree.atomValues.get(key2)) !== null && _currentTree$atomValu !== void 0 ? _currentTree$atomValu : defaultLoadable; - if (newLoadable.state === "hasValue") { - var _previousTree$atomVal, _pendingSetSelf, _pendingSetSelf2, _pendingSetSelf3; - const newValue = newLoadable.contents; - const oldLoadable = (_previousTree$atomVal = previousTree.atomValues.get(key2)) !== null && _previousTree$atomVal !== void 0 ? _previousTree$atomVal : defaultLoadable; - const oldValue = oldLoadable.state === "hasValue" ? oldLoadable.contents : DEFAULT_VALUE$5; - if (((_pendingSetSelf = pendingSetSelf) === null || _pendingSetSelf === void 0 ? void 0 : _pendingSetSelf.effect) !== effect || ((_pendingSetSelf2 = pendingSetSelf) === null || _pendingSetSelf2 === void 0 ? void 0 : _pendingSetSelf2.value) !== newValue) { - handler(newValue, oldValue); - } else if (((_pendingSetSelf3 = pendingSetSelf) === null || _pendingSetSelf3 === void 0 ? void 0 : _pendingSetSelf3.effect) === effect) { - pendingSetSelf = null; - } - } - }, key2); - }; - for (const effect of (_options$effects_UNST = options.effects_UNSTABLE) !== null && _options$effects_UNST !== void 0 ? _options$effects_UNST : []) { - var _options$effects_UNST; - const cleanup = effect({ - node, - trigger, - setSelf: setSelf(effect), - resetSelf: resetSelf(effect), - onSet: onSet(effect) - }); - if (cleanup != null) { - var _cleanupEffectsByStor; - cleanupEffectsByStore.set(store, [...(_cleanupEffectsByStor = cleanupEffectsByStore.get(store)) !== null && _cleanupEffectsByStor !== void 0 ? _cleanupEffectsByStor : [], cleanup]); + }); + } + if (!root) + tree.splice( + 0, + 0, + spaceToTreeNode( + space, + spaceCollapsed, + sortable, + depth, + parentId, + parentPath, + tree.length, + hasChildren + ) + ); + return tree; + }; + const [flattenedTree, setFlattenedTree] = h2([]); + const retrieveData = () => { + if (queryMode) { + setFlattenedTree(treeForPaths(queryResults)); + return; + } + if (!activeViewSpace) + return setFlattenedTree([]); + const tree = []; + tree.push(...treeForRoot(activeViewSpace, activeId)); + if (nextTreeScrollPath.current) { + const index = tree.findIndex( + (f4) => { + var _a2; + return ((_a2 = f4.item) == null ? void 0 : _a2.path) == nextTreeScrollPath.current; } + ); + if (index != -1) { + listRef.current.scrollToIndex(index); + nextTreeScrollPath.current = null; } - duringInit = false; } - if (!(initValue instanceof DefaultValue$2)) { - var _store$getState$nextT4; - const initLoadable = Recoil_isPromise(initValue) ? loadableWithPromise$2(wrapPendingPromise(store, initValue)) : loadableWithValue$3(initValue); - initState.atomValues.set(key2, initLoadable); - (_store$getState$nextT4 = store.getState().nextTree) === null || _store$getState$nextT4 === void 0 ? void 0 : _store$getState$nextT4.atomValues.set(key2, initLoadable); + setFlattenedTree(tree); + }; + p2(() => { + if (selectedFiles.length <= 1) { + if (!selectedFiles[0] || selectedFiles[0].item.path != (activeFile == null ? void 0 : activeFile.fullPath)) + setSelectedFiles([]); + if (plugin.settings.revealActiveFile) + revealFile(activeFile); } + window.addEventListener(eventTypes.activePathChange, changeActiveFile); return () => { - var _cleanupEffectsByStor2; - liveStoresCount--; - (_cleanupEffectsByStor2 = cleanupEffectsByStore.get(store)) === null || _cleanupEffectsByStor2 === void 0 ? void 0 : _cleanupEffectsByStor2.forEach((cleanup) => cleanup()); - cleanupEffectsByStore.delete(store); - store.getState().knownAtoms.delete(key2); - }; - } - function peekAtom(_store, state) { - var _ref, _state$atomValues$get3, _cachedAnswerForUnval; - return (_ref = (_state$atomValues$get3 = state.atomValues.get(key2)) !== null && _state$atomValues$get3 !== void 0 ? _state$atomValues$get3 : (_cachedAnswerForUnval = cachedAnswerForUnvalidatedValue) === null || _cachedAnswerForUnval === void 0 ? void 0 : _cachedAnswerForUnval[1]) !== null && _ref !== void 0 ? _ref : defaultLoadable; - } - function getAtom(_store, state) { - if (state.atomValues.has(key2)) { - return Recoil_nullthrows(state.atomValues.get(key2)); - } else if (state.nonvalidatedAtoms.has(key2)) { - if (cachedAnswerForUnvalidatedValue != null) { - return cachedAnswerForUnvalidatedValue; - } - if (persistence == null) { - Recoil_expectationViolation(`Tried to restore a persisted value for atom ${key2} but it has no persistence settings.`); - return defaultLoadable; - } - const nonvalidatedValue = state.nonvalidatedAtoms.get(key2); - const validatorResult = persistence.validator(nonvalidatedValue, DEFAULT_VALUE$5); - const validatedValueLoadable = validatorResult instanceof DefaultValue$2 ? defaultLoadable : loadableWithValue$3(validatorResult); - cachedAnswerForUnvalidatedValue = validatedValueLoadable; - return cachedAnswerForUnvalidatedValue; - } else { - return defaultLoadable; + window.removeEventListener(eventTypes.activePathChange, changeActiveFile); + }; + }, [activeFile]); + p2(() => { + window.addEventListener("dragend", resetState); + return () => { + window.removeEventListener("dragend", resetState); + }; + }); + p2(() => { + window.addEventListener(eventTypes.refreshView, forceUpdate); + window.addEventListener(eventTypes.settingsChanged, settingsChanged); + return () => { + window.removeEventListener(eventTypes.refreshView, forceUpdate); + window.removeEventListener(eventTypes.settingsChanged, settingsChanged); + }; + }, [activeViewSpace]); + p2(() => { + window.addEventListener(eventTypes.revealFile, handleRevealFileEvent); + return () => { + window.removeEventListener(eventTypes.revealFile, handleRevealFileEvent); + }; + }, [activeViewSpace]); + const revealFile = (path) => { + var _a2; + const space = spaces.find((f4) => f4.path == "/"); + if (!space || !path || activeViewSpace.path != space.path) + return; + const file = getAbstractFileAtPath(props2.plugin, path.path); + const folders = file.path.split("/"); + const openPaths = folders.reduce( + (p3, c4, index) => [...p3, index == 0 ? c4 : `/${p3[index]}/${c4}`], + ["/"] + ).slice(0, -1); + const newOpenFolders = [ + ...(_a2 = expandedSpaces.filter((f4) => !openPaths.find((g4) => g4 == f4))) != null ? _a2 : [], + ...openPaths + ]; + plugin.settings.expandedSpaces = newOpenFolders; + nextTreeScrollPath.current = "/" + file.path; + plugin.saveSettings(); + }; + const handleRevealFileEvent = (evt) => { + if (evt.detail) + revealFile(uriByString(plugin, evt.detail.file.path)); + }; + p2(() => { + retrieveData(); + window.addEventListener(eventTypes.spacesChange, spaceChangeEvent); + return () => { + window.removeEventListener(eventTypes.spacesChange, spaceChangeEvent); + }; + }, [expandedSpaces, activeViewSpace, activeId, queryResults, queryMode]); + const spaceChangeEvent = (evt) => { + if (evt.detail.type == "vault" || evt.detail.type == "space") { + retrieveData(); } - } - function invalidateAtom() { - cachedAnswerForUnvalidatedValue = void 0; - } - function setAtom(_store, state, newValue) { - if (state.atomValues.has(key2)) { - const existing = Recoil_nullthrows(state.atomValues.get(key2)); - if (existing.state === "hasValue" && newValue === existing.contents) { - return /* @__PURE__ */ new Map(); + }; + const changeActiveFile = (evt) => { + const path = evt.detail.path; + setActiveFile(path); + }; + const settingsChanged = () => { + setExpandedSpaces(plugin.settings.expandedSpaces); + }; + const overIndex = F2( + () => flattenedTree.findIndex((f4) => f4.id == overId), + [overId, flattenedTree] + ); + const activeIndex = F2( + () => flattenedTree.findIndex((f4) => f4.id == activeId), + [activeId, flattenedTree] + ); + const [currentPosition, setCurrentPosition] = h2(null); + const sortedIds = F2( + () => flattenedTree.map(({ id: id2 }) => id2), + [flattenedTree] + ); + const selectRange2 = (fromId) => { + const startIndex = sortedIds.findIndex((f4) => f4 == fromId); + const selectedFilesStartIndex = sortedIds.findIndex( + (f4) => { + var _a2; + return f4 == ((_a2 = selectedFiles[0]) == null ? void 0 : _a2.id); } - } else if (!state.nonvalidatedAtoms.has(key2) && newValue instanceof DefaultValue$2) { - return /* @__PURE__ */ new Map(); - } - if (true) { - if (options.dangerouslyAllowMutability !== true) { - Recoil_deepFreezeValue(newValue); + ); + const selectedFilesEndIndex = sortedIds.findIndex( + (f4) => { + var _a2; + return f4 == ((_a2 = selectedFiles[selectedFiles.length - 1]) == null ? void 0 : _a2.id); } + ); + if (startIndex < selectedFilesStartIndex) { + setSelectedFiles( + flattenedTree.slice(startIndex, selectedFilesEndIndex + 1).filter((f4) => f4.item) + ); + } else { + setSelectedFiles( + flattenedTree.slice(selectedFilesStartIndex, startIndex + 1).filter((f4) => f4.item) + ); } - cachedAnswerForUnvalidatedValue = void 0; - return (/* @__PURE__ */ new Map()).set(key2, loadableWithValue$3(newValue)); - } - function shouldDeleteConfigOnReleaseAtom() { - return getConfigDeletionHandler$2(key2) !== void 0 && liveStoresCount <= 0; + }; + const [projected, setProjected] = h2(null); + p2(() => { + const dragDepth = getDragDepth(offset2.x, indentationWidth); + const activeItem = flattenedTree.find(({ id: id2 }) => id2 === activeId); + const _projected = overId ? getProjection( + activeItem, + flattenedTree, + dragPaths, + overIndex, + dragDepth, + offset2.y, + activeIndex < overIndex, + modifier + ) : null; + setProjected(_projected); + }, [ + activeId, + flattenedTree, + overId, + overIndex, + dragPaths, + offset2, + activeIndex, + modifier, + activeViewSpace + ]); + function handleDragStart(event) { + const { + active: { id: activeId2 } + } = event; + dragStarted(activeId2); } - const node = registerNode$2({ - key: key2, - nodeType: "atom", - peek: peekAtom, - get: getAtom, - set: setAtom, - init: initAtom, - invalidate: invalidateAtom, - shouldDeleteConfigOnRelease: shouldDeleteConfigOnReleaseAtom, - dangerouslyAllowMutability: options.dangerouslyAllowMutability, - persistence_UNSTABLE: options.persistence_UNSTABLE ? { - type: options.persistence_UNSTABLE.type, - backButton: options.persistence_UNSTABLE.backButton - } : void 0, - shouldRestoreFromSnapshots: true, - retainedBy - }); - return node; -} -function atom(options) { - const { - default: optionsDefault, - ...restOptions - } = options; - if (isRecoilValue$4(optionsDefault)) { - return atomWithFallback({ - ...restOptions, - default: optionsDefault - }); - } else { - return baseAtom({ - ...restOptions, - default: optionsDefault + const dragStarted = (activeId2) => { + const activeItem = flattenedTree.find(({ id: id2 }) => id2 === activeId2); + setActiveId(activeId2); + setOverId(activeId2); + if (activeItem) { + if (selectedFiles.length > 1) { + setDragPaths(selectedFiles.map((f4) => f4.path)); + } else { + setDragPaths([activeItem.path]); + } + setCurrentPosition({ + parentId: activeItem.parentId, + overId: activeId2 + }); + } + document.body.style.setProperty("cursor", "grabbing"); + }; + function handleDragMove({ delta }) { + setOffset({ + x: Math.max(1, delta.x), + y: delta.y }); } -} -function atomWithFallback(options) { - const base = atom({ - ...options, - default: DEFAULT_VALUE$5, - persistence_UNSTABLE: options.persistence_UNSTABLE === void 0 ? void 0 : { - ...options.persistence_UNSTABLE, - validator: (storedValue) => storedValue instanceof DefaultValue$2 ? storedValue : Recoil_nullthrows(options.persistence_UNSTABLE).validator(storedValue, DEFAULT_VALUE$5) - }, - effects_UNSTABLE: options.effects_UNSTABLE - }); - const sel = Recoil_selector({ - key: `${options.key}__withFallback`, - get: ({ - get - }) => { - const baseValue = get(base); - return baseValue instanceof DefaultValue$2 ? options.default : baseValue; - }, - set: ({ - set - }, newValue) => set(base, newValue), - dangerouslyAllowMutability: options.dangerouslyAllowMutability - }); - setConfigDeletionHandler$1(sel.key, getConfigDeletionHandler$2(options.key)); - return sel; -} -var Recoil_atom = atom; -var MapCache = class { - constructor(options) { - var _options$mapKey; - _defineProperty(this, "_map", void 0); - _defineProperty(this, "_keyMapper", void 0); - this._map = /* @__PURE__ */ new Map(); - this._keyMapper = (_options$mapKey = options === null || options === void 0 ? void 0 : options.mapKey) !== null && _options$mapKey !== void 0 ? _options$mapKey : (v3) => v3; - } - size() { - return this._map.size; - } - has(key2) { - return this._map.has(this._keyMapper(key2)); - } - get(key2) { - return this._map.get(this._keyMapper(key2)); - } - set(key2, val) { - this._map.set(this._keyMapper(key2), val); - } - delete(key2) { - this._map.delete(this._keyMapper(key2)); - } - clear() { - this._map.clear(); - } -}; -var Recoil_MapCache = { - MapCache -}; -var Recoil_MapCache_1 = Recoil_MapCache.MapCache; -var Recoil_MapCache$1 = /* @__PURE__ */ Object.freeze({ - __proto__: null, - MapCache: Recoil_MapCache_1 -}); -var { - LRUCache: LRUCache$2 -} = Recoil_LRUCache$1; -var { - MapCache: MapCache$1 -} = Recoil_MapCache$1; -var defaultPolicy$1 = { - equality: "reference", - eviction: "none", - maxSize: Infinity -}; -function cacheFromPolicy({ - equality = defaultPolicy$1.equality, - eviction = defaultPolicy$1.eviction, - maxSize = defaultPolicy$1.maxSize -} = defaultPolicy$1) { - const valueMapper = getValueMapper$1(equality); - const cache = getCache(eviction, maxSize, valueMapper); - return cache; -} -function getValueMapper$1(equality) { - switch (equality) { - case "reference": - return (val) => val; - case "value": - return (val) => Recoil_stableStringify(val); - } - throw new Error(`Unrecognized equality policy ${equality}`); -} -function getCache(eviction, maxSize, mapKey) { - switch (eviction) { - case "keep-all": - return new MapCache$1({ - mapKey - }); - case "lru": - return new LRUCache$2({ - mapKey, - maxSize: Recoil_nullthrows(maxSize) - }); - case "most-recent": - return new LRUCache$2({ - mapKey, - maxSize: 1 - }); + function handleDragOver({ over }) { + const overId2 = over == null ? void 0 : over.id; + if (overId2) { + setOverId(overId2); + } } - throw new Error(`Unrecognized eviction policy ${eviction}`); -} -var Recoil_cacheFromPolicy = cacheFromPolicy; -var { - setConfigDeletionHandler: setConfigDeletionHandler$2 -} = Recoil_Node; -function atomFamily(options) { - var _options$cachePolicyF, _options$cachePolicyF2; - const atomCache = Recoil_cacheFromPolicy({ - equality: (_options$cachePolicyF = (_options$cachePolicyF2 = options.cachePolicyForParams_UNSTABLE) === null || _options$cachePolicyF2 === void 0 ? void 0 : _options$cachePolicyF2.equality) !== null && _options$cachePolicyF !== void 0 ? _options$cachePolicyF : "value", - eviction: "keep-all" - }); - return (params) => { - var _stableStringify; - const cachedAtom = atomCache.get(params); - if (cachedAtom != null) { - return cachedAtom; + const parentName = F2( + () => { + var _a2, _b2, _c2; + return projected ? (_c2 = (_b2 = (_a2 = flattenedTree.find((f4) => f4.id == projected.parentId)) == null ? void 0 : _a2.item) == null ? void 0 : _b2.name) != null ? _c2 : activeViewSpace == null ? void 0 : activeViewSpace.name : null; + }, + [flattenedTree, projected, activeViewSpace] + ); + const overName = F2( + () => { + var _a2, _b2; + return projected && ((_b2 = (_a2 = flattenedTree.find((f4) => f4.id == projected.overId)) == null ? void 0 : _a2.item) == null ? void 0 : _b2.name); + }, + [flattenedTree, projected] + ); + const dragOver = (e4, _overId, position) => { + const modifier2 = eventToModifier(e4); + setModifier(modifier2); + e4.dataTransfer.dropEffect = modifier2; + if (projected) { + plugin.app.dragManager.setAction( + `${projected.reorder && !projected.insert ? "Reorder in" : modifier2 == "move" || !modifier2 ? `Move to` : modifier2 == "link" ? `Add to` : `Copy to`} ${projected.insert ? overName : parentName}` + ); } - const { - cachePolicyForParams_UNSTABLE, - ...atomOptions - } = options; - const newAtom = Recoil_atom({ - ...atomOptions, - key: `${options.key}__${(_stableStringify = Recoil_stableStringify(params)) !== null && _stableStringify !== void 0 ? _stableStringify : "void"}`, - default: typeof options.default === "function" ? options.default(params) : options.default, - retainedBy_UNSTABLE: typeof options.retainedBy_UNSTABLE === "function" ? options.retainedBy_UNSTABLE(params) : options.retainedBy_UNSTABLE, - effects_UNSTABLE: typeof options.effects_UNSTABLE === "function" ? options.effects_UNSTABLE(params) : options.effects_UNSTABLE - }); - atomCache.set(params, newAtom); - setConfigDeletionHandler$2(newAtom.key, () => { - atomCache.delete(params); - }); - return newAtom; - }; -} -var Recoil_atomFamily = atomFamily; -var { - setConfigDeletionHandler: setConfigDeletionHandler$3 -} = Recoil_Node; -var nextIndex = 0; -function selectorFamily(options) { - var _options$cachePolicyF, _options$cachePolicyF2; - const selectorCache = Recoil_cacheFromPolicy({ - equality: (_options$cachePolicyF = (_options$cachePolicyF2 = options.cachePolicyForParams_UNSTABLE) === null || _options$cachePolicyF2 === void 0 ? void 0 : _options$cachePolicyF2.equality) !== null && _options$cachePolicyF !== void 0 ? _options$cachePolicyF : "value", - eviction: "keep-all" - }); - return (params) => { - var _stableStringify; - const cachedSelector = selectorCache.get(params); - if (cachedSelector != null) { - return cachedSelector; - } - const myKey = `${options.key}__selectorFamily/${(_stableStringify = Recoil_stableStringify(params, { - allowFunctions: true - })) !== null && _stableStringify !== void 0 ? _stableStringify : "void"}/${nextIndex++}`; - const myGet = (callbacks) => options.get(params)(callbacks); - const myCachePolicy = options.cachePolicy_UNSTABLE; - const retainedBy = typeof options.retainedBy_UNSTABLE === "function" ? options.retainedBy_UNSTABLE(params) : options.retainedBy_UNSTABLE; - let newSelector; - if (options.set != null) { - const set = options.set; - const mySet = (callbacks, newValue) => set(params)(callbacks, newValue); - newSelector = Recoil_selector({ - key: myKey, - get: myGet, - set: mySet, - cachePolicy_UNSTABLE: myCachePolicy, - dangerouslyAllowMutability: options.dangerouslyAllowMutability, - retainedBy_UNSTABLE: retainedBy - }); - } else { - newSelector = Recoil_selector({ - key: myKey, - get: myGet, - cachePolicy_UNSTABLE: myCachePolicy, - dangerouslyAllowMutability: options.dangerouslyAllowMutability, - retainedBy_UNSTABLE: retainedBy + if (dragPaths.length > 1) { + if (_overId && _overId != overId) + setOverId(_overId); + return; + } + if (_overId && _overId != overId) + setOverId(_overId); + const x5 = offset2.x; + const y5 = offset2.y; + const newX = 2 * Math.round(Math.max(1, position.x - indentationWidth - 20)); + const newY = 2 * Math.round(position.y / 2); + if (x5 != newX || y5 != newY) { + setOffset({ + x: newX, + y: newY }); } - selectorCache.set(params, newSelector); - setConfigDeletionHandler$3(newSelector.key, () => { - selectorCache.delete(params); - }); - return newSelector; }; -} -var Recoil_selectorFamily = selectorFamily; -var constantSelector = Recoil_selectorFamily({ - key: "__constant", - get: (constant) => () => constant, - cachePolicyForParams_UNSTABLE: { - equality: "reference" - } -}); -function constSelector(constant) { - return constantSelector(constant); -} -var Recoil_constSelector = constSelector; -var throwingSelector = Recoil_selectorFamily({ - key: "__error", - get: (message) => () => { - throw new Error(message); - }, - cachePolicyForParams_UNSTABLE: { - equality: "reference" + p2(() => { + if (dragPaths.length == 0) { + setOverId(null); + setActiveId(null); + setOffset({ x: 0, y: 0 }); + setModifier(null); + setProjected(null); + dragCounter.current = 0; + document.body.style.setProperty("cursor", ""); + } + }, [dragPaths]); + function handleDragEnd({ active, over }) { + dropFilesInTree( + plugin, + dragPaths, + activeId, + over == null ? void 0 : over.id, + projected, + flattenedTree, + activeViewSpace + ); + resetState(); } -}); -function errorSelector(message) { - return throwingSelector(message); -} -var Recoil_errorSelector = errorSelector; -function readOnlySelector(atom2) { - return atom2; -} -var Recoil_readOnlySelector = readOnlySelector; -var { - loadableWithError: loadableWithError$3, - loadableWithPromise: loadableWithPromise$3, - loadableWithValue: loadableWithValue$4 -} = Recoil_Loadable; -function concurrentRequests(getRecoilValue, deps) { - const results = Array(deps.length).fill(void 0); - const exceptions = Array(deps.length).fill(void 0); - for (const [i4, dep] of deps.entries()) { - try { - results[i4] = getRecoilValue(dep); - } catch (e4) { - exceptions[i4] = e4; - } + const dragEnded = (overId2, modifiers) => { + dropFilesInTree( + plugin, + dragPaths, + activeId, + overId2, + projected, + flattenedTree, + activeViewSpace, + modifiers + ); + resetState(); + }; + const adjustTranslate = ({ transform }) => { + return { + ...transform, + x: transform.x, + y: transform.y - 10 + }; + }; + function handleDragCancel() { + resetState(); } - return [results, exceptions]; -} -function isError(exp) { - return exp != null && !Recoil_isPromise(exp); -} -function unwrapDependencies(dependencies) { - return Array.isArray(dependencies) ? dependencies : Object.getOwnPropertyNames(dependencies).map((key2) => dependencies[key2]); -} -function getValueFromLoadablePromiseResult(result) { - if (result != null && typeof result === "object" && result.hasOwnProperty("__value")) { - return result.__value; + const handleCollapse = T2( + (folder, open) => { + const folderOpen = expandedSpaces == null ? void 0 : expandedSpaces.includes(folder.id); + const newOpenFolders = !folderOpen || open ? [...expandedSpaces, folder.id] : expandedSpaces.filter( + (openFolder) => folder.id !== openFolder + ); + plugin.settings.expandedSpaces = newOpenFolders; + plugin.saveSettings(); + }, + [plugin, expandedSpaces] + ); + function resetState() { + setDragPaths([]); + setOverId(null); + setActiveId(null); + setOffset({ x: 0, y: 0 }); + setModifier(null); + setProjected(null); + dragCounter.current = 0; + document.body.style.setProperty("cursor", ""); } - return result; -} -function wrapResults(dependencies, results) { - return Array.isArray(dependencies) ? results : Object.getOwnPropertyNames(dependencies).reduce((out, key2, idx) => ({ - ...out, - [key2]: results[idx] - }), {}); -} -function wrapLoadables(dependencies, results, exceptions) { - const output = exceptions.map((exception, idx) => exception == null ? loadableWithValue$4(results[idx]) : Recoil_isPromise(exception) ? loadableWithPromise$3(exception) : loadableWithError$3(exception)); - return wrapResults(dependencies, output); -} -function combineAsyncResultsWithSyncResults(syncResults, asyncResults) { - return asyncResults.map((result, idx) => result === void 0 ? syncResults[idx] : result); -} -var waitForNone = Recoil_selectorFamily({ - key: "__waitForNone", - get: (dependencies) => ({ - get - }) => { - const deps = unwrapDependencies(dependencies); - const [results, exceptions] = concurrentRequests(get, deps); - return wrapLoadables(dependencies, results, exceptions); - }, - dangerouslyAllowMutability: true -}); -var waitForAny = Recoil_selectorFamily({ - key: "__waitForAny", - get: (dependencies) => ({ - get - }) => { - const deps = unwrapDependencies(dependencies); - const [results, exceptions] = concurrentRequests(get, deps); - if (exceptions.some((exp) => !Recoil_isPromise(exp))) { - return wrapLoadables(dependencies, results, exceptions); + useDndMonitor({ + onDragStart: handleDragStart, + onDragMove: handleDragMove, + onDragOver: handleDragOver, + onDragEnd: handleDragEnd, + onDragCancel: handleDragCancel + }); + const dragCounter = _2(0); + const dragEnter = () => { + dragCounter.current++; + }; + const dragLeave = () => { + dragCounter.current--; + if (dragCounter.current == 0) { + setOverId(null); + setOffset({ x: 0, y: 0 }); + setProjected(null); + dragCounter.current = 0; } - return new Promise((resolve) => { - for (const [i4, exp] of exceptions.entries()) { - if (Recoil_isPromise(exp)) { - exp.then((result) => { - results[i4] = getValueFromLoadablePromiseResult(result); - exceptions[i4] = void 0; - resolve(wrapLoadables(dependencies, results, exceptions)); - }).catch((error) => { - exceptions[i4] = error; - resolve(wrapLoadables(dependencies, results, exceptions)); - }); - } + }; + return /* @__PURE__ */ Cn.createElement("div", { + className: "mk-file-tree", + onDragEnter: () => dragEnter(), + onDragLeave: () => dragLeave(), + onDragOver: (e4) => e4.preventDefault(), + onDrop: (e4) => { + if (overId) { + dragEnded(overId); + } else { + resetState(); } - }); - }, - dangerouslyAllowMutability: true -}); -var waitForAll = Recoil_selectorFamily({ - key: "__waitForAll", - get: (dependencies) => ({ - get - }) => { - const deps = unwrapDependencies(dependencies); - const [results, exceptions] = concurrentRequests(get, deps); - if (exceptions.every((exp) => exp == null)) { - return wrapResults(dependencies, results); - } - const error = exceptions.find(isError); - if (error != null) { - throw error; - } - return Promise.all(exceptions).then((exceptionResults) => wrapResults(dependencies, combineAsyncResultsWithSyncResults(results, exceptionResults).map(getValueFromLoadablePromiseResult))); - }, - dangerouslyAllowMutability: true -}); -var waitForAllSettled = Recoil_selectorFamily({ - key: "__waitForAllSettled", - get: (dependencies) => ({ - get - }) => { - const deps = unwrapDependencies(dependencies); - const [results, exceptions] = concurrentRequests(get, deps); - if (exceptions.every((exp) => !Recoil_isPromise(exp))) { - return wrapLoadables(dependencies, results, exceptions); - } - return Promise.all(exceptions.map((exp, i4) => Recoil_isPromise(exp) ? exp.then((result) => { - results[i4] = getValueFromLoadablePromiseResult(result); - exceptions[i4] = void 0; - }).catch((error) => { - results[i4] = void 0; - exceptions[i4] = error; - }) : null)).then(() => wrapLoadables(dependencies, results, exceptions)); - }, - dangerouslyAllowMutability: true -}); -var noWait = Recoil_selectorFamily({ - key: "__noWait", - get: (dependency) => ({ - get - }) => { - try { - return loadableWithValue$4(get(dependency)); - } catch (exception) { - return Recoil_isPromise(exception) ? loadableWithPromise$3(exception) : loadableWithError$3(exception); } - }, - dangerouslyAllowMutability: true -}); -var Recoil_WaitFor = { - waitForNone, - waitForAny, - waitForAll, - waitForAllSettled, - noWait + }, /* @__PURE__ */ Cn.createElement("style", null, `${[...props2.plugin.index.fontsCache.values()].join(", ")} + `), /* @__PURE__ */ Cn.createElement(SortableContext, { + items: flattenedTree, + strategy: verticalListSortingStrategy + }, /* @__PURE__ */ Cn.createElement(VirtualizedList, { + vRef: listRef, + flattenedTree, + projected, + handleCollapse, + activeFile, + plugin, + selectedFiles, + selectRange: selectRange2, + indentationWidth, + dragStarted, + dragOver, + dragEnded, + overIndex, + activeIndex + }), z3( + /* @__PURE__ */ Cn.createElement(DragOverlay, { + dropAnimation: null, + modifiers: [adjustTranslate], + zIndex: 1600 + }, activeId && flattenedTree.some((f4) => f4.id == activeId) ? /* @__PURE__ */ Cn.createElement(SortableTreeItem, { + id: activeId, + data: flattenedTree.find((f4) => f4.id == activeId), + indicator: null, + depth: 0, + disabled: false, + plugin, + selected: false, + highlighted: false, + active: false, + clone: true, + childCount: 0, + style: {}, + indentationWidth, + dragStarted, + dragOver, + dragEnded, + dragActive: false + }) : null), + document.body + )), modifier && !platformIsMobile() && /* @__PURE__ */ Cn.createElement("div", { + className: "mk-hint-dnd", + style: { + position: "absolute", + bottom: "10px", + left: "10px", + background: "var(--interactive-accent)", + boxShadow: "var(--background-modifier-box-shadow)", + padding: "4px 8px", + borderRadius: "4px", + color: "var(--text-on-accent)", + fontSize: "var(--font-ui-smaller)" + } + }, /* @__PURE__ */ Cn.createElement("div", null, "Hold", " ", /* @__PURE__ */ Cn.createElement("span", { + style: { fontFamily: "var(--font-monospace)" } + }, "shift"), " ", "to Add and ", normalizedAltName(), " to Copy"))); }; -var { - batchUpdates: batchUpdates$3, - setBatcher: setBatcher$1 -} = Recoil_Batching; -var { - DefaultValue: DefaultValue$3 -} = Recoil_Node; -var { - RecoilRoot: RecoilRoot$2 -} = Recoil_RecoilRoot_react; -var { - isRecoilValue: isRecoilValue$5 -} = Recoil_RecoilValue$1; -var { - retentionZone: retentionZone$1 -} = Recoil_RetentionZone; -var { - freshSnapshot: freshSnapshot$2 -} = Recoil_Snapshot$1; -var { - useGotoRecoilSnapshot: useGotoRecoilSnapshot$1, - useRecoilCallback: useRecoilCallback$1, - useRecoilSnapshot: useRecoilSnapshot$1, - useRecoilState: useRecoilState$1, - useRecoilStateLoadable: useRecoilStateLoadable$1, - useRecoilTransaction: useRecoilTransaction$1, - useRecoilTransactionObserver: useRecoilTransactionObserver$1, - useRecoilValue: useRecoilValue$1, - useRecoilValueLoadable: useRecoilValueLoadable$1, - useResetRecoilState: useResetRecoilState$1, - useRetain: useRetain$1, - useSetRecoilState: useSetRecoilState$1, - useSetUnvalidatedAtomValues: useSetUnvalidatedAtomValues$1, - useTransactionObservation_DEPRECATED: useTransactionObservation_DEPRECATED$1 -} = Recoil_Hooks; -var { - noWait: noWait$1, - waitForAll: waitForAll$1, - waitForAllSettled: waitForAllSettled$1, - waitForAny: waitForAny$1, - waitForNone: waitForNone$1 -} = Recoil_WaitFor; -var Recoil_index = { - DefaultValue: DefaultValue$3, - RecoilRoot: RecoilRoot$2, - useRecoilBridgeAcrossReactRoots_UNSTABLE: Recoil_useRecoilBridgeAcrossReactRoots, - atom: Recoil_atom, - selector: Recoil_selector, - retentionZone: retentionZone$1, - atomFamily: Recoil_atomFamily, - selectorFamily: Recoil_selectorFamily, - constSelector: Recoil_constSelector, - errorSelector: Recoil_errorSelector, - readOnlySelector: Recoil_readOnlySelector, - useRecoilValue: useRecoilValue$1, - useRecoilValueLoadable: useRecoilValueLoadable$1, - useRecoilState: useRecoilState$1, - useRecoilStateLoadable: useRecoilStateLoadable$1, - useSetRecoilState: useSetRecoilState$1, - useResetRecoilState: useResetRecoilState$1, - useGetRecoilValueInfo_UNSTABLE: Recoil_useGetRecoilValueInfo, - useRetain: useRetain$1, - useRecoilCallback: useRecoilCallback$1, - useRecoilTransaction_UNSTABLE: useRecoilTransaction$1, - useGotoRecoilSnapshot: useGotoRecoilSnapshot$1, - useRecoilSnapshot: useRecoilSnapshot$1, - useRecoilTransactionObserver_UNSTABLE: useRecoilTransactionObserver$1, - useTransactionObservation_UNSTABLE: useTransactionObservation_DEPRECATED$1, - useSetUnvalidatedAtomValues_UNSTABLE: useSetUnvalidatedAtomValues$1, - noWait: noWait$1, - waitForNone: waitForNone$1, - waitForAny: waitForAny$1, - waitForAll: waitForAll$1, - waitForAllSettled: waitForAllSettled$1, - isRecoilValue: isRecoilValue$5, - batchUpdates: batchUpdates$3, - setBatcher: setBatcher$1, - snapshot_UNSTABLE: freshSnapshot$2 -}; -var Recoil_index_1 = Recoil_index.DefaultValue; -var Recoil_index_2 = Recoil_index.RecoilRoot; -var Recoil_index_3 = Recoil_index.useRecoilBridgeAcrossReactRoots_UNSTABLE; -var Recoil_index_4 = Recoil_index.atom; -var Recoil_index_5 = Recoil_index.selector; -var Recoil_index_6 = Recoil_index.retentionZone; -var Recoil_index_7 = Recoil_index.atomFamily; -var Recoil_index_8 = Recoil_index.selectorFamily; -var Recoil_index_9 = Recoil_index.constSelector; -var Recoil_index_10 = Recoil_index.errorSelector; -var Recoil_index_11 = Recoil_index.readOnlySelector; -var Recoil_index_12 = Recoil_index.useRecoilValue; -var Recoil_index_13 = Recoil_index.useRecoilValueLoadable; -var Recoil_index_14 = Recoil_index.useRecoilState; -var Recoil_index_15 = Recoil_index.useRecoilStateLoadable; -var Recoil_index_16 = Recoil_index.useSetRecoilState; -var Recoil_index_17 = Recoil_index.useResetRecoilState; -var Recoil_index_18 = Recoil_index.useGetRecoilValueInfo_UNSTABLE; -var Recoil_index_19 = Recoil_index.useRetain; -var Recoil_index_20 = Recoil_index.useRecoilCallback; -var Recoil_index_21 = Recoil_index.useRecoilTransaction_UNSTABLE; -var Recoil_index_22 = Recoil_index.useGotoRecoilSnapshot; -var Recoil_index_23 = Recoil_index.useRecoilSnapshot; -var Recoil_index_24 = Recoil_index.useRecoilTransactionObserver_UNSTABLE; -var Recoil_index_25 = Recoil_index.useTransactionObservation_UNSTABLE; -var Recoil_index_26 = Recoil_index.useSetUnvalidatedAtomValues_UNSTABLE; -var Recoil_index_27 = Recoil_index.noWait; -var Recoil_index_28 = Recoil_index.waitForNone; -var Recoil_index_29 = Recoil_index.waitForAny; -var Recoil_index_30 = Recoil_index.waitForAll; -var Recoil_index_31 = Recoil_index.waitForAllSettled; -var Recoil_index_32 = Recoil_index.isRecoilValue; -var Recoil_index_33 = Recoil_index.batchUpdates; -var Recoil_index_34 = Recoil_index.setBatcher; -var Recoil_index_35 = Recoil_index.snapshot_UNSTABLE; - -// src/components/ui/modals/hiddenFilesModal.tsx -var import_obsidian49 = require("obsidian"); -var HiddenItemsModal = class extends import_obsidian49.Modal { + +// src/components/Navigator/MainMenu.tsx +var import_classnames7 = __toESM(require_classnames()); + +// src/components/UI/modals/hiddenFilesModal.tsx +var import_obsidian54 = require("obsidian"); +var HiddenItemsModal = class extends import_obsidian54.Modal { constructor(plugin) { super(plugin.app); this.plugin = plugin; } onOpen() { - let { contentEl } = this; - let myModal = this; + const { contentEl } = this; + const myModal = this; let headerText; const headerEl = contentEl.createEl("div", { text: headerText }); headerEl.addClass("modal-title"); @@ -51383,13 +62322,13 @@ var HiddenItemsModal = class extends import_obsidian49.Modal { }; } onClose() { - let { contentEl } = this; + const { contentEl } = this; contentEl.empty(); } }; var HiddenFiles = (props2) => { const { plugin } = props2; - const ref = _2(null); + const ref2 = _2(null); const [hiddenFiles, setHiddenFiles] = h2(plugin.settings.hiddenFiles); const [hiddenExtensions, setHiddenExtensions] = h2( plugin.settings.hiddenExtensions @@ -51401,7 +62340,7 @@ var HiddenFiles = (props2) => { ]; plugin.saveSettings(); }; - const saveFile = (_9, value) => { + const saveFile = (_12, value) => { plugin.settings.hiddenFiles = [...plugin.settings.hiddenFiles, ...value]; plugin.saveSettings(); }; @@ -51418,9 +62357,9 @@ var HiddenFiles = (props2) => { plugin.saveSettings(); }; const addExtension = () => { - if ((ref == null ? void 0 : ref.current.value.length) > 0) { - saveExtension(ref.current.value); - ref.current.empty(); + if ((ref2 == null ? void 0 : ref2.current.value.length) > 0) { + saveExtension(ref2.current.value); + ref2.current.empty(); } }; const settingsChanged = () => { @@ -51434,14 +62373,15 @@ var HiddenFiles = (props2) => { }; }, []); const addMenu = (e4) => { - const offset = e4.target.getBoundingClientRect(); - const options = getAllAbstractFilesInVault(props2.plugin, app).map((f4) => ({ + const offset2 = e4.target.getBoundingClientRect(); + const options = getAllAbstractFilesInVault(props2.plugin).map((f4) => ({ name: fileNameToString(f4.name), value: f4.path })); showSelectMenu( - { x: offset.left, y: offset.top + 30 }, + { x: offset2.left, y: offset2.top + 30 }, { + plugin: props2.plugin, multi: false, editable: false, value: [], @@ -51460,6 +62400,7 @@ var HiddenFiles = (props2) => { }, "Name, Suffixes and Extension"), /* @__PURE__ */ Cn.createElement("div", { className: "setting-item-description" }, "Exclude any files and folders by name, suffix or extension."), /* @__PURE__ */ Cn.createElement("div", null, hiddenExtensions.map((f4, index) => /* @__PURE__ */ Cn.createElement("div", { + key: index, className: "mobile-option-setting-item" }, /* @__PURE__ */ Cn.createElement("span", { className: "mobile-option-setting-item-name" @@ -51473,7 +62414,7 @@ var HiddenFiles = (props2) => { }, /* @__PURE__ */ Cn.createElement("input", { placeholder: i18n_default.labels.addExtension, type: "text", - ref + ref: ref2 }), /* @__PURE__ */ Cn.createElement("button", { onClick: (e4) => addExtension() }, "+ Add")), /* @__PURE__ */ Cn.createElement("div", { @@ -51481,6 +62422,7 @@ var HiddenFiles = (props2) => { }, "Files and Folders"), /* @__PURE__ */ Cn.createElement("div", { className: "setting-item-description" }, "Exclude specific files and folders"), /* @__PURE__ */ Cn.createElement("div", null, hiddenFiles.map((f4, index) => /* @__PURE__ */ Cn.createElement("div", { + key: index, className: "mobile-option-setting-item" }, /* @__PURE__ */ Cn.createElement("span", { className: "mobile-option-setting-item-name" @@ -51496,41 +62438,8 @@ var HiddenFiles = (props2) => { }, "+ ", i18n_default.buttons.addFile))); }; -// src/components/Spaces/MainMenu.tsx -var import_obsidian50 = require("obsidian"); - -// src/recoil/pluginState.ts -var activeFile = Recoil_index_4({ - key: "spacesActivePath", - default: null, - dangerouslyAllowMutability: true -}); -var selectedFiles = Recoil_index_4({ - key: "spacesSelectedFiles", - default: [], - dangerouslyAllowMutability: true -}); -var activeView = Recoil_index_4({ - key: "spacesActiveView", - default: "root", - dangerouslyAllowMutability: true -}); -var activeViewSpace = Recoil_index_4({ - key: "spacesActiveSpace", - default: "", - dangerouslyAllowMutability: true -}); -var spaces = Recoil_index_4({ - key: "spaces", - default: [], - dangerouslyAllowMutability: true -}); -var expandedFolders = Recoil_index_4({ - key: "expandedFolders", - default: {} -}); - -// src/components/Spaces/MainMenu.tsx +// src/components/Navigator/MainMenu.tsx +var import_obsidian55 = require("obsidian"); var replaceMobileMainMenu = (plugin) => { if (platformIsMobile()) { const header = app.workspace.containerEl.querySelector( @@ -51539,9 +62448,10 @@ var replaceMobileMainMenu = (plugin) => { header.empty(); const reactEl = createRoot(header); reactEl.render( - /* @__PURE__ */ Cn.createElement(Recoil_index_2, null, /* @__PURE__ */ Cn.createElement(MainMenu, { - plugin, - compactMode: plugin.settings.spacesCompactMode + /* @__PURE__ */ Cn.createElement(SidebarProvider, { + plugin + }, /* @__PURE__ */ Cn.createElement(MainMenu, { + plugin })) ); } @@ -51549,32 +62459,55 @@ var replaceMobileMainMenu = (plugin) => { var MainMenu = (props2) => { var _a2; const { plugin } = props2; - const [activeView2, setActiveView] = Recoil_index_14(activeView); - const [spaces2, setSpaces] = h2(props2.plugin.index.allSpaces()); - const [activeFile2, setActiveFile] = Recoil_index_14(activeFile); - const folder = defaultNoteFolder(props2.plugin, activeFile2); - const [activeViewSpace2, setActiveViewSpace] = Recoil_index_14( - activeViewSpace - ); - const activeSpace = spaces2.find((f4) => f4.name == activeViewSpace2); - const ref = _2(); + const { + activeFile, + activeViewSpace, + spaces, + setDragPaths, + saveActiveSpace: setActiveViewSpaceByPath, + waypoints: pinnedSpaces, + activeQuery, + queryMode, + setQueryMode, + setActiveQuery + } = q2(NavigatorContext); + const folder = defaultNoteFolder(props2.plugin, activeFile); + const ref2 = _2(); + const inputRef = _2(); + const [queryString, setQueryString] = h2(""); + const [filters, setFilters] = h2([]); + const [hover, setHover] = h2(false); + p2(() => { + if (queryMode && inputRef.current) + inputRef.current.focus(); + }, [queryMode]); + const queries = F2(() => { + return queryString.length > 0 ? [ + { + type: "any", + trueFalse: true, + filters: [ + { + type: "fileprop", + fType: "text", + field: "name", + fn: "include", + value: queryString + } + ] + }, + ...filters + ] : filters; + }, [queryString, filters]); + p2(() => { + setActiveQuery(queries); + }, [queries]); const toggleSections = (collapse) => { - const newSections = collapse ? [] : spaces2.map((f4) => f4.name); + const spaces2 = [...props2.plugin.index.getSpaceItems(activeViewSpace.path)]; + const newSections = collapse ? [] : spaces2.map((f4) => activeViewSpace.path + "/" + f4.path); plugin.settings.expandedSpaces = newSections; plugin.saveSettings(); - }; - const newFile = async () => { - await createNewMarkdownFile(props2.plugin, folder, "", ""); - }; - const loadCachedSpaces = () => { - setSpaces([...plugin.index.allSpaces()]); - }; - p2(() => { - window.addEventListener(eventTypes.spacesChange, loadCachedSpaces); - return () => { - window.removeEventListener(eventTypes.spacesChange, loadCachedSpaces); - }; - }, [loadCachedSpaces]); + }; p2(() => { refreshLeafs(); }, []); @@ -51592,96 +62525,42 @@ var MainMenu = (props2) => { } return { leafs, spaceActive }; }; - const showMenu = (e4) => { + const showMenu = () => { const { spaceActive, leafs } = refreshLeafs(); - const menu = new import_obsidian50.Menu(); + const menu = new import_obsidian55.Menu(); !spaceActive && menu.addItem((menuItem) => { menuItem.setIcon("lucide-arrow-left"); menuItem.setTitle(i18n_default.menu.backToSpace); - menuItem.onClick((ev) => { + menuItem.onClick(() => { const leaves = plugin.app.workspace.getLeavesOfType(FILE_TREE_VIEW_TYPE); if (leaves.length > 0) { plugin.app.workspace.revealLeaf(leaves[0]); } }); }); - if (plugin.settings.spacesCompactMode) { - menu.addItem((menuItem) => { - menuItem.setTitle(i18n_default.menu.home); - menuItem.onClick((ev) => { - setActiveView("root"); - }); - }); - menu.addItem((menuItem) => { - menuItem.setTitle(i18n_default.menu.tags); - menuItem.onClick((ev) => { - setActiveView("tags"); - }); - }); - menu.addItem((menuItem) => { - menuItem.setTitle("All Spaces"); - menuItem.onClick((ev) => { - setActiveView("all"); - }); - }); - menu.addSeparator(); - spaces2.filter((f4) => f4.pinned == "true" || f4.pinned == "pinned").forEach((space) => { - menu.addItem((menuItem) => { - menuItem.setTitle(space.name); - menuItem.onClick((ev) => { - setActiveView("space"); - setActiveViewSpace(space.name); - }); - }); - }); - menu.addSeparator(); - } menu.addItem((menuItem) => { - menuItem.setIcon("plus"); - menuItem.setTitle(i18n_default.buttons.createSection); + menuItem.setTitle("Open Space"); + menuItem.setIcon("layout"); menuItem.onClick((ev) => { - const vaultChangeModal = new EditSpaceModal( - plugin, - { - name: "", - def: { - type: "focus", - folder: "", - filters: [] - } - }, - "create" - ); - vaultChangeModal.open(); + openSpace(activeViewSpace.path, props2.plugin, false); }); }); + menu.addSeparator(); menu.addItem((menuItem) => { - menuItem.setIcon("plus"); - menuItem.setTitle(i18n_default.buttons.createSectionSmart); + menuItem.setTitle("Vault"); + menuItem.setIcon("vault"); menuItem.onClick((ev) => { - const vaultChangeModal = new EditSpaceModal( - plugin, - { - name: "", - def: { - type: "smart", - folder: "", - filters: [] - } - }, - "create" - ); - vaultChangeModal.open(); + setActiveViewSpaceByPath("/"); }); }); - menu.addSeparator(); menu.addItem((menuItem) => { - menuItem.setIcon("sync"); - menuItem.setTitle("Reload Spaces"); + menuItem.setTitle(i18n_default.menu.tags); + menuItem.setIcon("tags"); menuItem.onClick((ev) => { - plugin.index.loadSpacesDatabaseFromDisk(); + setActiveViewSpaceByPath("spaces://$tags"); }); }); + menu.addSeparator(); menu.addItem((menuItem) => { menuItem.setIcon("lucide-chevrons-down-up"); menuItem.setTitle(i18n_default.menu.collapseAllSections); @@ -51710,7 +62589,7 @@ var MainMenu = (props2) => { (l3) => menu.addItem((menuItem) => { menuItem.setIcon(l3.view.icon); menuItem.setTitle(l3.getDisplayText()); - menuItem.onClick((ev) => { + menuItem.onClick(() => { plugin.app.workspace.revealLeaf(l3); }); }) @@ -51718,14 +62597,14 @@ var MainMenu = (props2) => { menu.addItem((menuItem) => { menuItem.setIcon("lucide-settings"); menuItem.setTitle(i18n_default.menu.obSettings); - menuItem.onClick((ev) => { + menuItem.onClick(() => { plugin.app.commands.commands["app:open-settings"].callback(); }); }); menu.addItem((menuItem) => { menuItem.setIcon("vault"); menuItem.setTitle(i18n_default.menu.openVault); - menuItem.onClick((ev) => { + menuItem.onClick(() => { plugin.app.commands.commands["app:open-vault"].callback(); }); }); @@ -51733,551 +62612,142 @@ var MainMenu = (props2) => { menu.addItem((menuItem) => { menuItem.setIcon("mk-logo"); menuItem.setTitle(i18n_default.menu.getHelp); - menuItem.onClick((ev) => { + menuItem.onClick(() => { window.open("https://make.md/community"); }); }); - const offset = ref.current.getBoundingClientRect(); - menu.showAtPosition({ x: offset.left, y: offset.top + 30 }); - }; - const currentViewName = activeView2 == "root" ? "Home" : activeView2 == "all" ? "All Spaces" : activeView2 == "tags" ? "Tags" : activeViewSpace2; - const currentViewIcon = activeView2 == "root" ? uiIconSet["mk-ui-home"] : activeView2 == "all" ? uiIconSet["mk-ui-spaces"] : activeView2 == "tags" ? uiIconSet["mk-ui-tags"] : ((_a2 = activeSpace == null ? void 0 : activeSpace.sticker) == null ? void 0 : _a2.length) > 0 ? stickerFromString(activeSpace.sticker, props2.plugin) : activeSpace == null ? void 0 : activeSpace.name.charAt(0); - const menuComponent = () => /* @__PURE__ */ Cn.createElement("div", { - className: "mk-main-menu-container" - }, /* @__PURE__ */ Cn.createElement("div", { - className: "mk-main-menu-button", - ref, - onClick: (e4) => showMenu(e4) - }, plugin.settings.spacesCompactMode ? /* @__PURE__ */ Cn.createElement(Cn.Fragment, null, /* @__PURE__ */ Cn.createElement("div", { - className: "mk-main-menu-icon", - dangerouslySetInnerHTML: { __html: currentViewIcon } - }), currentViewName) : plugin.app.vault.getName(), /* @__PURE__ */ Cn.createElement("div", { - dangerouslySetInnerHTML: { __html: uiIconSet["mk-ui-expand"] } - }))); - return props2.compactMode ? /* @__PURE__ */ Cn.createElement("div", { - className: "mk-flow-bar-compact" - }, " ", menuComponent(), /* @__PURE__ */ Cn.createElement("button", { - "aria-label": i18n_default.buttons.newNote, - className: "mk-inline-button", - onClick: () => newFile() - }, /* @__PURE__ */ Cn.createElement("div", { - className: "mk-icon-small", - dangerouslySetInnerHTML: { __html: uiIconSet["mk-ui-new-note"] } - })), props2.plugin.settings.blinkEnabled && /* @__PURE__ */ Cn.createElement("button", { - "aria-label": i18n_default.buttons.blink, - className: "mk-inline-button", - onClick: () => props2.plugin.quickOpen() - }, /* @__PURE__ */ Cn.createElement("div", { - className: "mk-icon-small", - dangerouslySetInnerHTML: { __html: uiIconSet["mk-ui-blink"] } - }))) : menuComponent(); -}; - -// node_modules/@tanstack/react-virtual/build/esm/index.js -function _extends() { - _extends = Object.assign || function(target) { - for (var i4 = 1; i4 < arguments.length; i4++) { - var source = arguments[i4]; - for (var key2 in source) { - if (Object.prototype.hasOwnProperty.call(source, key2)) { - target[key2] = source[key2]; - } - } - } - return target; + const offset2 = ref2.current.getBoundingClientRect(); + menu.showAtPosition({ x: offset2.left, y: offset2.top + 30 }); }; - return _extends.apply(this, arguments); -} -function _objectWithoutPropertiesLoose(source, excluded) { - if (source == null) - return {}; - var target = {}; - var sourceKeys = Object.keys(source); - var key2, i4; - for (i4 = 0; i4 < sourceKeys.length; i4++) { - key2 = sourceKeys[i4]; - if (excluded.indexOf(key2) >= 0) - continue; - target[key2] = source[key2]; - } - return target; -} -var props = ["bottom", "height", "left", "right", "top", "width"]; -var rectChanged = function rectChanged2(a5, b4) { - if (a5 === void 0) { - a5 = {}; - } - if (b4 === void 0) { - b4 = {}; - } - return props.some(function(prop) { - return a5[prop] !== b4[prop]; - }); -}; -var observedNodes = /* @__PURE__ */ new Map(); -var rafId; -var run = function run2() { - var changedStates = []; - observedNodes.forEach(function(state, node) { - var newRect = node.getBoundingClientRect(); - if (rectChanged(newRect, state.rect)) { - state.rect = newRect; - changedStates.push(state); - } - }); - changedStates.forEach(function(state) { - state.callbacks.forEach(function(cb) { - return cb(state.rect); - }); - }); - rafId = window.requestAnimationFrame(run2); -}; -function observeRect(node, cb) { - return { - observe: function observe() { - var wasEmpty = observedNodes.size === 0; - if (observedNodes.has(node)) { - observedNodes.get(node).callbacks.push(cb); - } else { - observedNodes.set(node, { - rect: void 0, - hasRectChanged: false, - callbacks: [cb] - }); - } - if (wasEmpty) - run(); - }, - unobserve: function unobserve() { - var state = observedNodes.get(node); - if (state) { - var index = state.callbacks.indexOf(cb); - if (index >= 0) - state.callbacks.splice(index, 1); - if (!state.callbacks.length) - observedNodes["delete"](node); - if (!observedNodes.size) - cancelAnimationFrame(rafId); - } + const { dragPaths, saveActiveSpace } = q2(NavigatorContext); + const onDragOver = (e4) => { + e4.preventDefault(); + e4.dataTransfer.dropEffect = "none"; + if (dragPaths.length == 1) { + plugin.app.dragManager.setAction("Open Space"); + setHover(true); } }; -} -var useIsomorphicLayoutEffect3 = typeof window !== "undefined" ? y2 : p2; -function rectReducer(state, action) { - var rect = action.rect; - if (state.height !== rect.height || state.width !== rect.width) { - return rect; - } - return state; -} -var useRect2 = function useRect3(nodeRef, initialRect) { - if (initialRect === void 0) { - initialRect = { - width: 0, - height: 0 - }; - } - var _React$useState = Cn.useState(nodeRef.current), element = _React$useState[0], setElement = _React$useState[1]; - var _React$useReducer = Cn.useReducer(rectReducer, initialRect), rect = _React$useReducer[0], dispatch = _React$useReducer[1]; - var initialRectSet = Cn.useRef(false); - useIsomorphicLayoutEffect3(function() { - if (nodeRef.current !== element) { - setElement(nodeRef.current); - } - }); - useIsomorphicLayoutEffect3(function() { - if (element && !initialRectSet.current) { - initialRectSet.current = true; - var _rect = element.getBoundingClientRect(); - dispatch({ - rect: _rect - }); - } - }, [element]); - Cn.useEffect(function() { - if (!element) { - return; - } - var observer = observeRect(element, function(rect2) { - dispatch({ - rect: rect2 - }); - }); - observer.observe(); - return function() { - observer.unobserve(); - }; - }, [element]); - return rect; -}; -var _excluded = ["align"]; -var defaultEstimateSize = function defaultEstimateSize2() { - return 50; -}; -var defaultKeyExtractor = function defaultKeyExtractor2(index) { - return index; -}; -var defaultMeasureSize = function defaultMeasureSize2(el, horizontal) { - var key2 = horizontal ? "offsetWidth" : "offsetHeight"; - return el[key2]; -}; -var defaultRangeExtractor = function defaultRangeExtractor2(range) { - var start = Math.max(range.start - range.overscan, 0); - var end = Math.min(range.end + range.overscan, range.size - 1); - var arr = []; - for (var _i = start; _i <= end; _i++) { - arr.push(_i); - } - return arr; -}; -var useVirtual = function useVirtual2(_ref) { - var _measurements; - var _ref$size = _ref.size, size = _ref$size === void 0 ? 0 : _ref$size, _ref$estimateSize = _ref.estimateSize, estimateSize = _ref$estimateSize === void 0 ? defaultEstimateSize : _ref$estimateSize, _ref$overscan = _ref.overscan, overscan = _ref$overscan === void 0 ? 1 : _ref$overscan, _ref$paddingStart = _ref.paddingStart, paddingStart = _ref$paddingStart === void 0 ? 0 : _ref$paddingStart, _ref$paddingEnd = _ref.paddingEnd, paddingEnd = _ref$paddingEnd === void 0 ? 0 : _ref$paddingEnd, parentRef = _ref.parentRef, _ref$horizontal = _ref.horizontal, horizontal = _ref$horizontal === void 0 ? false : _ref$horizontal, scrollToFn = _ref.scrollToFn, useObserver = _ref.useObserver, initialRect = _ref.initialRect, onScrollElement = _ref.onScrollElement, scrollOffsetFn = _ref.scrollOffsetFn, _ref$keyExtractor = _ref.keyExtractor, keyExtractor = _ref$keyExtractor === void 0 ? defaultKeyExtractor : _ref$keyExtractor, _ref$measureSize = _ref.measureSize, measureSize = _ref$measureSize === void 0 ? defaultMeasureSize : _ref$measureSize, _ref$rangeExtractor = _ref.rangeExtractor, rangeExtractor = _ref$rangeExtractor === void 0 ? defaultRangeExtractor : _ref$rangeExtractor; - var sizeKey = horizontal ? "width" : "height"; - var scrollKey = horizontal ? "scrollLeft" : "scrollTop"; - var latestRef = _2({ - outerSize: 0, - scrollOffset: 0, - measurements: [], - totalSize: 0 - }); - var _React$useState = h2(0), scrollOffset = _React$useState[0], setScrollOffset = _React$useState[1]; - latestRef.current.scrollOffset = scrollOffset; - var useMeasureParent = useObserver || useRect2; - var _useMeasureParent = useMeasureParent(parentRef, initialRect), outerSize = _useMeasureParent[sizeKey]; - latestRef.current.outerSize = outerSize; - var defaultScrollToFn = T2(function(offset) { - if (parentRef.current) { - parentRef.current[scrollKey] = offset; - } - }, [parentRef, scrollKey]); - var resolvedScrollToFn = scrollToFn || defaultScrollToFn; - var scrollTo = T2(function(offset) { - resolvedScrollToFn(offset, defaultScrollToFn); - }, [defaultScrollToFn, resolvedScrollToFn]); - var _React$useState2 = h2({}), measuredCache = _React$useState2[0], setMeasuredCache = _React$useState2[1]; - var measure = T2(function() { - return setMeasuredCache({}); - }, []); - var pendingMeasuredCacheIndexesRef = _2([]); - var measurements = F2(function() { - var min3 = pendingMeasuredCacheIndexesRef.current.length > 0 ? Math.min.apply(Math, pendingMeasuredCacheIndexesRef.current) : 0; - pendingMeasuredCacheIndexesRef.current = []; - var measurements2 = latestRef.current.measurements.slice(0, min3); - for (var _i2 = min3; _i2 < size; _i2++) { - var key2 = keyExtractor(_i2); - var measuredSize = measuredCache[key2]; - var _start = measurements2[_i2 - 1] ? measurements2[_i2 - 1].end : paddingStart; - var _size = typeof measuredSize === "number" ? measuredSize : estimateSize(_i2); - var _end = _start + _size; - measurements2[_i2] = { - index: _i2, - start: _start, - size: _size, - end: _end, - key: key2 - }; - } - return measurements2; - }, [estimateSize, measuredCache, paddingStart, size, keyExtractor]); - var totalSize = (((_measurements = measurements[size - 1]) == null ? void 0 : _measurements.end) || paddingStart) + paddingEnd; - latestRef.current.measurements = measurements; - latestRef.current.totalSize = totalSize; - var element = onScrollElement ? onScrollElement.current : parentRef.current; - var scrollOffsetFnRef = _2(scrollOffsetFn); - scrollOffsetFnRef.current = scrollOffsetFn; - useIsomorphicLayoutEffect3(function() { - if (!element) { - setScrollOffset(0); - return; - } - var onScroll = function onScroll2(event) { - var offset = scrollOffsetFnRef.current ? scrollOffsetFnRef.current(event) : element[scrollKey]; - setScrollOffset(offset); - }; - onScroll(); - element.addEventListener("scroll", onScroll, { - capture: false, - passive: true - }); - return function() { - element.removeEventListener("scroll", onScroll); - }; - }, [element, scrollKey]); - var _calculateRange = calculateRange(latestRef.current), start = _calculateRange.start, end = _calculateRange.end; - var indexes = F2(function() { - return rangeExtractor({ - start, - end, - overscan, - size: measurements.length - }); - }, [start, end, overscan, measurements.length, rangeExtractor]); - var measureSizeRef = _2(measureSize); - measureSizeRef.current = measureSize; - var virtualItems = F2(function() { - var virtualItems2 = []; - var _loop = function _loop2(k6, len2) { - var i4 = indexes[k6]; - var measurement = measurements[i4]; - var item = _extends({}, measurement, { - measureRef: function measureRef(el) { - if (el) { - var measuredSize = measureSizeRef.current(el, horizontal); - if (measuredSize !== item.size) { - var _scrollOffset = latestRef.current.scrollOffset; - if (item.start < _scrollOffset) { - defaultScrollToFn(_scrollOffset + (measuredSize - item.size)); - } - pendingMeasuredCacheIndexesRef.current.push(i4); - setMeasuredCache(function(old) { - var _extends2; - return _extends({}, old, (_extends2 = {}, _extends2[item.key] = measuredSize, _extends2)); - }); - } - } - } - }); - virtualItems2.push(item); - }; - for (var k5 = 0, len = indexes.length; k5 < len; k5++) { - _loop(k5); - } - return virtualItems2; - }, [indexes, defaultScrollToFn, horizontal, measurements]); - var mountedRef = _2(false); - useIsomorphicLayoutEffect3(function() { - if (mountedRef.current) { - setMeasuredCache({}); - } - mountedRef.current = true; - }, [estimateSize]); - var scrollToOffset = T2(function(toOffset, _temp) { - var _ref2 = _temp === void 0 ? { - align: "start" - } : _temp, align = _ref2.align; - var _latestRef$current = latestRef.current, scrollOffset2 = _latestRef$current.scrollOffset, outerSize2 = _latestRef$current.outerSize; - if (align === "auto") { - if (toOffset <= scrollOffset2) { - align = "start"; - } else if (toOffset >= scrollOffset2 + outerSize2) { - align = "end"; - } else { - align = "start"; - } - } - if (align === "start") { - scrollTo(toOffset); - } else if (align === "end") { - scrollTo(toOffset - outerSize2); - } else if (align === "center") { - scrollTo(toOffset - outerSize2 / 2); - } - }, [scrollTo]); - var tryScrollToIndex = T2(function(index, _temp2) { - var _ref3 = _temp2 === void 0 ? { - align: "auto" - } : _temp2, align = _ref3.align, rest = _objectWithoutPropertiesLoose(_ref3, _excluded); - var _latestRef$current2 = latestRef.current, measurements2 = _latestRef$current2.measurements, scrollOffset2 = _latestRef$current2.scrollOffset, outerSize2 = _latestRef$current2.outerSize; - var measurement = measurements2[Math.max(0, Math.min(index, size - 1))]; - if (!measurement) { - return; - } - if (align === "auto") { - if (measurement.end >= scrollOffset2 + outerSize2) { - align = "end"; - } else if (measurement.start <= scrollOffset2) { - align = "start"; - } else { - return; - } - } - var toOffset = align === "center" ? measurement.start + measurement.size / 2 : align === "end" ? measurement.end : measurement.start; - scrollToOffset(toOffset, _extends({ - align - }, rest)); - }, [scrollToOffset, size]); - var scrollToIndex = T2(function(index, options) { - tryScrollToIndex(index, options); - requestAnimationFrame(function() { - tryScrollToIndex(index, options); - }); - }, [tryScrollToIndex]); - return { - virtualItems, - totalSize, - scrollToOffset, - scrollToIndex, - measure + const dragLeave = () => { + setHover(false); }; -}; -var findNearestBinarySearch = function findNearestBinarySearch2(low, high, getCurrentValue, value) { - while (low <= high) { - var middle = (low + high) / 2 | 0; - var currentValue = getCurrentValue(middle); - if (currentValue < value) { - low = middle + 1; - } else if (currentValue > value) { - high = middle - 1; - } else { - return middle; + const onDrop = () => { + if (dragPaths.length == 1 && props2.plugin.index.spacesIndex.has(dragPaths[0])) { + saveActiveSpace(dragPaths[0]); } - } - if (low > 0) { - return low - 1; - } else { - return 0; - } -}; -function calculateRange(_ref4) { - var measurements = _ref4.measurements, outerSize = _ref4.outerSize, scrollOffset = _ref4.scrollOffset; - var size = measurements.length - 1; - var getOffset = function getOffset2(index) { - return measurements[index].start; - }; - var start = findNearestBinarySearch(0, size, getOffset, scrollOffset); - var end = start; - while (end < size && measurements[end].end < scrollOffset + outerSize) { - end++; - } - return { - start, - end + setHover(false); }; -} - -// src/components/Spaces/TreeView/FolderTreeView.tsx -var import_obsidian51 = require("obsidian"); -var import_classnames7 = __toESM(require_classnames()); - -// src/components/Spaces/TreeView/SectionView.tsx -var import_classnames6 = __toESM(require_classnames()); -var SectionItem = k3( - ({ - childCount, - clone, - data, - depth, - disableSelection, - disableInteraction, - ghost, - handleProps, - indentationWidth, - indicator, - collapsed, - style, - onCollapse, - wrapperRef, - plugin, - disabled, - active - }, ref) => { - var _a2, _b2; - const [activeFile2, setActiveFile] = Recoil_index_14(activeFile); - const space = (_a2 = plugin.index.spacesIndex.get(data.space)) == null ? void 0 : _a2.space; - const triggerMenu = (e4) => { - triggerSectionMenu( - plugin, - space, - [...plugin.index.allSpaces()], - e4, - activeFile2 - ); - }; - return /* @__PURE__ */ Cn.createElement(Cn.Fragment, null, /* @__PURE__ */ Cn.createElement("div", { - className: (0, import_classnames6.default)( - "mk-tree-wrapper", - "mk-section-wrapper", - clone && "mk-clone", - ghost && "mk-ghost", - disableSelection && "mk-disable-selection", - disableInteraction && "mk-disable-interaction" - ), - ref: wrapperRef, - style: { - ...style, - ...indicator ? { "--spacing": `${indentationWidth * depth}px` } : {} - } - }, /* @__PURE__ */ Cn.createElement("div", { - onContextMenu: (e4) => triggerMenu(e4), - className: (0, import_classnames6.default)( - "mk-section", - indicator ? indicator.state == 2 /* Bottom */ ? "mk-indicator-bottom" : indicator.state == 1 /* Top */ ? "mk-indicator-top" : indicator.state == 3 /* Row */ ? "mk-indicator-row" : "" : "" - ) - }, /* @__PURE__ */ Cn.createElement("div", { - className: `mk-collapse ${collapsed ? "mk-collapsed" : ""}`, - dangerouslySetInnerHTML: { - __html: uiIconSet["mk-ui-collapse-sm"] - }, - onClick: (e4) => onCollapse(data, false) - }), /* @__PURE__ */ Cn.createElement("div", { - className: (0, import_classnames6.default)( - "mk-tree-item", - "tree-item-self", - "nav-folder-title", - active && "is-selected" - ), - "data-path": data.space, - ref, - ...handleProps - }, /* @__PURE__ */ Cn.createElement("div", { - className: "mk-file-icon" - }, /* @__PURE__ */ Cn.createElement("button", { - dangerouslySetInnerHTML: { - __html: (space == null ? void 0 : space.sticker) ? stickerFromString(space == null ? void 0 : space.sticker, plugin) : uiIconSet["mk-ui-spaces"] - }, - onClick: () => { - if (!space) - return; - const vaultChangeModal = new stickerModal( - plugin.app, - plugin, - (emoji) => saveSpaceIcon(plugin, space.name, emoji) - ); - vaultChangeModal.open(); - } - })), /* @__PURE__ */ Cn.createElement("div", { - className: "mk-tree-text", - onClick: (e4) => space ? openSpace( - space.name, - plugin, - e4.ctrlKey || e4.metaKey ? e4.altKey ? "split" : "tab" : false - ) : {} - }, data.space), /* @__PURE__ */ Cn.createElement("div", { - className: "mk-folder-buttons" - }, /* @__PURE__ */ Cn.createElement("button", { - "aria-label": i18n_default.buttons.moreOptions, - onClick: (e4) => { - triggerMenu(e4); - e4.stopPropagation(); - }, - dangerouslySetInnerHTML: { - __html: uiIconSet["mk-ui-options"] - } - }), ((_b2 = space == null ? void 0 : space.def) == null ? void 0 : _b2.type) == "focus" ? /* @__PURE__ */ Cn.createElement("button", { - "aria-label": i18n_default.buttons.newNote, - onClick: () => { - newFileInSpace(plugin, space, activeFile2); + const saveQuerySpace = (e4) => { + showSpacesMenu( + e4, + props2.plugin, + (link, isNew) => { + if (!isNew) { + saveSpaceMetadataValue( + props2.plugin, + link, + props2.plugin.settings.fmKeyFilter, + activeQuery + ); + } else { + insertSpaceAtIndex(props2.plugin, link, { + filters: activeQuery + }).then((f4) => openSpace(link, props2.plugin, false)); + } }, - dangerouslySetInnerHTML: { - __html: uiIconSet["mk-ui-plus"] - } - }) : /* @__PURE__ */ Cn.createElement(Cn.Fragment, null)))))); - } -); -SectionItem.displayName = "SectionItem"; + false, + true + ); + }; + return /* @__PURE__ */ Cn.createElement("div", { + className: "mk-main-menu-container" + }, /* @__PURE__ */ Cn.createElement("div", { + className: "mk-main-menu-inner" + }, /* @__PURE__ */ Cn.createElement("div", { + className: (0, import_classnames7.default)("mk-main-menu", queryMode && "mk-hidden") + }, /* @__PURE__ */ Cn.createElement("div", { + className: `mk-main-menu-button mk-main-menu-button-primary ${hover && "is-active"}`, + ref: ref2, + onClick: (e4) => showMenu(), + onContextMenu: (e4) => triggerSpaceMenu(props2.plugin, activeViewSpace, e4, null, null), + onDragLeave: () => dragLeave(), + onDragOver: (e4) => onDragOver(e4), + onDrop: () => onDrop() + }, activeViewSpace ? /* @__PURE__ */ Cn.createElement(Cn.Fragment, null, /* @__PURE__ */ Cn.createElement("div", { + className: (0, import_classnames7.default)("mk-main-menu-sticker"), + dangerouslySetInnerHTML: { + __html: stickerFromString( + ((_a2 = activeViewSpace == null ? void 0 : activeViewSpace.sticker) == null ? void 0 : _a2.length) > 0 ? activeViewSpace.sticker : iconForSpaceType( + activeViewSpace.type, + activeViewSpace.path, + true + ), + props2.plugin + ) + }, + draggable: true, + onDragStart: () => setDragPaths([activeViewSpace.path]) + }), activeViewSpace.alias) : /* @__PURE__ */ Cn.createElement(Cn.Fragment, null), /* @__PURE__ */ Cn.createElement("div", { + className: "mk-icon-xsmall", + dangerouslySetInnerHTML: { __html: uiIconSet["mk-ui-collapse"] } + })), /* @__PURE__ */ Cn.createElement("div", { + className: "mk-main-menu-button", + onClick: (e4) => e4.metaKey ? props2.plugin.quickOpen() : setQueryMode((p3) => !p3) + }, /* @__PURE__ */ Cn.createElement("div", { + className: "mk-icon-small", + dangerouslySetInnerHTML: { __html: uiIconSet["mk-ui-search"] } + }))), /* @__PURE__ */ Cn.createElement("div", { + className: (0, import_classnames7.default)( + "mk-main-menu-search", + !queryMode && "mk-hidden" + ) + }, /* @__PURE__ */ Cn.createElement("div", { + className: "mk-main-menu-button", + onClick: (e4) => setQueryMode((p3) => !p3) + }, /* @__PURE__ */ Cn.createElement("div", { + className: "mk-icon-small", + dangerouslySetInnerHTML: { __html: lucideIcon("arrow-left") } + })), /* @__PURE__ */ Cn.createElement("input", { + onClick: (e4) => e4.stopPropagation(), + className: "mk-cell-text", + placeholder: "Search by Text or Filters", + ref: inputRef, + type: "text", + value: queryString, + tabIndex: -1, + onChange: (e4) => setQueryString(e4.target.value) + }), /* @__PURE__ */ Cn.createElement("div", { + "aria-label": i18n_default.buttons.addToSpace, + className: "mk-main-menu-button", + onClick: (e4) => saveQuerySpace(e4) + }, /* @__PURE__ */ Cn.createElement("div", { + className: "mk-icon-small", + dangerouslySetInnerHTML: { + __html: stickerFromString("lucide//plus-square", props2.plugin) + } + }))), /* @__PURE__ */ Cn.createElement("button", { + "aria-label": i18n_default.buttons.newNote, + className: "mk-main-menu-button", + onClick: (e4) => e4.metaKey ? showSpaceAddMenu(props2.plugin, e4, activeViewSpace) : newFileInSpace(plugin, activeViewSpace, null, false) + }, /* @__PURE__ */ Cn.createElement("div", { + className: "mk-icon-small", + dangerouslySetInnerHTML: { __html: uiIconSet["mk-ui-new-note"] } + }))), queryMode && /* @__PURE__ */ Cn.createElement(SpaceQuery, { + plugin, + filters, + setFilters + })); +}; -// src/components/Spaces/TreeView/FolderTreeView.tsx -var animateLayoutChanges2 = ({ +// src/components/Navigator/Waypoints/Waypoint.tsx +var import_classnames8 = __toESM(require_classnames()); +var animateLayoutChanges3 = ({ isSorting, wasDragging }) => isSorting || wasDragging ? false : true; -var SortableTreeItem = ({ +var SortablePinnedSpaceItem = ({ id: id2, - data, - depth, - disabled, - style, + index, ...props2 }) => { const { @@ -52285,15 +62755,13 @@ var SortableTreeItem = ({ isDragging, isSorting, listeners, - setDraggableNodeRef, - setDroppableNodeRef, + setNodeRef, transform, transition } = useSortable({ id: id2, - animateLayoutChanges: animateLayoutChanges2, - disabled, - data + animateLayoutChanges: animateLayoutChanges3, + disabled: !platformIsMobile() }); const memoListeners = F2(() => { return { @@ -52301,801 +62769,208 @@ var SortableTreeItem = ({ ...listeners }; }, [isSorting]); - if (data.parentId == null) { - return /* @__PURE__ */ Cn.createElement(SectionItem, { - ref: setDraggableNodeRef, - wrapperRef: setDroppableNodeRef, - data, - depth, - ghost: isDragging, - disableInteraction: isSorting, - disabled, - style, - handleProps: memoListeners, - ...props2 - }); - } else { - return /* @__PURE__ */ Cn.createElement(TreeItem, { - ref: setDraggableNodeRef, - wrapperRef: setDroppableNodeRef, - data, - depth, - ghost: isDragging, - disableInteraction: isSorting, - disabled, - style, - handleProps: memoListeners, - ...props2 - }); - } + return /* @__PURE__ */ Cn.createElement(PinnedSpace, { + index, + ref: setNodeRef, + handleProps: memoListeners, + ...props2 + }); }; -var TreeItem = k3( +var PinnedSpace = k3( ({ - childCount, - clone, - data, - depth, - disableSelection, - disableInteraction, - ghost, + pin, handleProps, - active, - indentationWidth, indicator, - collapsed, - selected, highlighted, - onCollapse, - onSelectRange, - wrapperRef, - style, plugin, - disabled - }, ref) => { - const [activeFile2, setActiveFile] = Recoil_index_14(activeFile); - const [hoverTarget, setHoverTarget] = h2(null); - const [selectedFiles2, setSelectedFiles] = Recoil_index_14( - selectedFiles - ); - const [fileCache, setFileCache] = h2(data.item); - const openFileAtTarget = (file, e4) => { - if (e4.shiftKey) { - onSelectRange(file.id); - return; - } - if (file.item.isFolder && plugin.settings.expandFolderOnClick) { - onCollapse(data, true); - } - openAFile( - getAbstractFileAtPath(app, file.item.path), - plugin, - e4.ctrlKey || e4.metaKey ? e4.altKey ? "split" : "tab" : false - ); - setActiveFile(pathByString(file.item.path)); - setSelectedFiles([file]); - }; - const dragStarted = (e4) => { - if (selectedFiles2.length > 1) { - const files = selectedFiles2.map((f4) => f4.file).filter((f4) => f4); - app.dragManager.onDragStart(e4, { - icon: "lucide-files", - source: void 0, - title: i18n_default.labels.filesCount.replace( - "{$1}", - files.length.toString() - ), - type: "files", - files - }); - app.dragManager.dragFiles(e4, files, true); - return; - } - const file = getAbstractFileAtPath(app, data.item.path); - if (file instanceof import_obsidian51.TFolder) { - app.dragManager.onDragStart(e4, { - icon: "lucide-folder", - source: void 0, - title: file.name, - type: "folder", - file - }); - app.dragManager.dragFolder(e4, file, true); - return; - } - app.dragManager.onDragStart(e4, { - icon: "lucide-file", - source: void 0, - title: file.name, - type: "file", - file - }); - app.dragManager.dragFile(e4, file, true); - }; - const onKeyDown = (e4) => { - if (e4.key === "Control" || e4.key === "Meta") { - if (e4.repeat) - return; - const el = hoverTarget; - if (el) - plugin.app.workspace.trigger( - "link-hover", - {}, - el, - data.item.path, - data.item.path - ); + style, + clone, + ghost, + dragStart, + dragOver, + dragEnded, + index + }, ref2) => { + var _a2, _b2; + const innerRef = _2(null); + const { + setDragPaths, + activeViewSpace, + activeFile, + saveActiveSpace, + setModifier + } = q2(NavigatorContext); + const onDragStarted = (e4) => { + if (dragStart && pin) { + dragStart(pin.path); + setDragPaths([pin.path]); } }; - const mouseOut = (e4) => { - setHoverTarget(null); - }; - const updateFileCache = (evt) => { - if (evt.detail.type == "file" && evt.detail.name == data.item.path) - setFileCache(plugin.index.filesIndex.get(data.item.path)); - }; - p2(() => { - window.addEventListener(eventTypes.spacesChange, updateFileCache); - return () => { - window.removeEventListener(eventTypes.refreshView, updateFileCache); - }; - }, []); - const hoverItem = (e4) => { - if (plugin.settings.filePreviewOnHover) { - setHoverTarget(e4.target); - if (e4.ctrlKey || e4.metaKey) { - plugin.app.workspace.trigger( - "link-hover", - {}, - e4.target, - data.item.path, - data.item.path - ); - } + const onDragEnded = (e4) => { + if (dragEnded) { + dragEnded(); } }; - p2(() => { - if (hoverTarget && plugin.settings.filePreviewOnHover) { - window.addEventListener("keydown", onKeyDown); - return () => { - window.removeEventListener("keydown", onKeyDown); - }; - } - }, [hoverTarget]); const innerProps = !platformIsMobile() ? { draggable: true, - onDragStart: dragStarted + onDragStart: onDragStarted, + onDragEnded, + onDrop: onDragEnded } : handleProps; - return /* @__PURE__ */ Cn.createElement(Cn.Fragment, null, /* @__PURE__ */ Cn.createElement("div", { - className: (0, import_classnames7.default)( - "mk-tree-wrapper", - clone && "mk-clone", - ghost && "mk-ghost", - disableSelection && "mk-disable-selection", - disableInteraction && "mk-disable-interaction" - ), - ref: wrapperRef, - style - }, /* @__PURE__ */ Cn.createElement("div", { - className: (0, import_classnames7.default)( - data.item.isFolder ? "nav-folder" : "nav-file", - indicator ? indicator.state == 2 /* Bottom */ ? "mk-indicator-bottom" : indicator.state == 1 /* Top */ ? "mk-indicator-top" : indicator.state == 3 /* Row */ ? "mk-indicator-row" : "" : "" - ), - style: indicator ? { - "--spacing": `${indentationWidth * indicator.depth}px` - } : {} - }, !platformIsMobile() && /* @__PURE__ */ Cn.createElement("div", { - className: "mk-drag-handle", - dangerouslySetInnerHTML: { __html: uiIconSet["mk-ui-handle"] }, - ...handleProps - }), /* @__PURE__ */ Cn.createElement("div", { - className: (0, import_classnames7.default)( - "mk-tree-item", - "tree-item-self", - fileCache.isFolder ? "nav-folder-title" : "nav-file-title", - fileCache.folderNote ? "mk-folder-is-folder-note" : "", - active ? "is-active" : "", - selected ? "is-selected" : "", - highlighted ? "is-highlighted" : "" - ), - ref, - style: { - "--spacing": `${indentationWidth * depth - 28}px`, - "--childrenCount": `${childCount * spaceRowHeight(plugin) - 13}px` - }, - onMouseLeave: mouseOut, - onMouseEnter: hoverItem, - onKeyDown, - onClick: (e4) => openFileAtTarget(data, e4), - "data-path": fileCache.path, - onContextMenu: (e4) => selectedFiles2.length > 1 && selectedFiles2.some((f4) => f4.id == data.id) ? triggerMultiFileMenu(plugin, selectedFiles2, e4) : triggerFileMenu(plugin, data.file, fileCache.isFolder, e4), - ...innerProps - }, data.item.isFolder && /* @__PURE__ */ Cn.createElement("button", { - "aria-label": `${collapsed ? i18n_default.labels.expand : i18n_default.labels.collapse}`, - className: `mk-collapse ${collapsed ? "mk-collapsed" : ""}`, + return pin ? /* @__PURE__ */ Cn.createElement("div", { + ref: innerRef, + className: "mk-waypoint", onClick: (e4) => { - onCollapse(data, false); - e4.stopPropagation(); + if (e4.metaKey) + openSpace(pin.path, plugin, false); + saveActiveSpace(pin.path); }, - dangerouslySetInnerHTML: { - __html: uiIconSet["mk-ui-collapse"] - } - }), plugin.settings.spacesStickers && /* @__PURE__ */ Cn.createElement(FileSticker, { - plugin, - fileCache - }), /* @__PURE__ */ Cn.createElement("div", { - className: `mk-tree-text ${fileCache.isFolder ? "nav-folder-title-content" : "nav-file-title-content"}` - }, fileCache.name), !fileCache.isFolder && fileCache.extension != "md" && /* @__PURE__ */ Cn.createElement("span", { - className: "nav-file-tag" - }, fileCache.extension), !clone ? /* @__PURE__ */ Cn.createElement("div", { - className: "mk-folder-buttons" - }, /* @__PURE__ */ Cn.createElement("button", { - "aria-label": i18n_default.buttons.moreOptions, - onClick: (e4) => { - triggerFileMenu(plugin, data.file, fileCache.isFolder, e4); - e4.stopPropagation(); + onContextMenu: (e4) => triggerSpaceMenu(plugin, pin, e4, activeFile, null), + onDragOver: (e4) => { + e4.preventDefault(); + setModifier(eventToModifier(e4)); + if (!innerRef.current) + return; + const rect = innerRef.current.getBoundingClientRect(); + const x5 = e4.clientX - rect.left; + if (dragOver && pin) + dragOver(pin.path, x5); }, + ...innerProps + }, /* @__PURE__ */ Cn.createElement("div", { + ref: ref2, + className: (0, import_classnames8.default)( + "mk-waypoints-item", + "clickable-icon", + "nav-action-button", + ((activeViewSpace == null ? void 0 : activeViewSpace.path) == (pin == null ? void 0 : pin.path) || highlighted) && "mk-active", + indicator && "mk-indicator", + clone && "mk-clone", + ghost && "mk-ghost" + ), dangerouslySetInnerHTML: { - __html: uiIconSet["mk-ui-options"] - } - }), fileCache.isFolder && /* @__PURE__ */ Cn.createElement("button", { - "aria-label": i18n_default.buttons.newNote, - onClick: (e4) => { - newFileInFolder(plugin, data.file); - e4.stopPropagation(); + __html: stickerFromString( + ((_a2 = pin == null ? void 0 : pin.sticker) == null ? void 0 : _a2.length) > 0 ? pin.sticker : iconForSpaceType(pin.type, pin.path, true), + plugin + ) }, - dangerouslySetInnerHTML: { - __html: uiIconSet["mk-ui-plus"] - } - })) : /* @__PURE__ */ Cn.createElement(Cn.Fragment, null))))); - } -); -TreeItem.displayName = "TreeItem"; - -// src/hooks/ForceUpdate.tsx -function useForceUpdate() { - const [value, setValue] = h2(0); - return () => setValue((value2) => value2 + 1); -} - -// src/utils/dnd/dragFile.ts -function getMaxDepth({ previousItem }) { - var _a2; - if (previousItem) { - if ((_a2 = previousItem.item) == null ? void 0 : _a2.isFolder) - return previousItem.depth + 1; - return previousItem.depth; - } - return 0; -} -function getMinDepth({ nextItem }) { - if (nextItem) { - return nextItem.depth; - } - return 0; -} -function getDragDepth(offset, indentationWidth) { - return Math.round(offset / indentationWidth) + 1; -} -function getProjection(items, activeItem, overItemIndex, previousItem, nextItem, dragDepth) { - const activeIsSection = activeItem.parentId == null; - const overIsSection = previousItem.parentId == null; - if (activeIsSection) { - if (overIsSection) { - return { - depth: 0, - overId: previousItem.id, - parentId: null, - sortable: true - }; - } - return null; - } - if (nodeIsAncestorOfTarget(activeItem, previousItem)) { - return null; - } - const projectedDepth = dragDepth; - const maxDepth = getMaxDepth({ - previousItem - }); - const minDepth = getMinDepth({ nextItem }); - let depth = projectedDepth; - if (projectedDepth >= maxDepth) { - depth = maxDepth; - } else if (projectedDepth < minDepth) { - depth = minDepth; - } - if (depth == activeItem.depth && activeItem.space == previousItem.space) { - if (!activeItem.sortable || !previousItem.sortable) { - return null; - } - } - const parentId = getParentId(); - return { - depth, - overId: previousItem.id, - parentId, - sortable: previousItem.sortable - }; - function getParentId() { - var _a2; - if (depth === 0) { - return previousItem.space + "//"; - } - if (!previousItem) { - return null; - } - if (depth === previousItem.depth || depth > previousItem.depth && !previousItem.item.isFolder) { - return previousItem.parentId; - } - if (depth > previousItem.depth) { - return previousItem.id; - } - const newParent = (_a2 = items.slice(0, overItemIndex).reverse().find((item) => item.depth === depth)) == null ? void 0 : _a2.parentId; - return newParent != null ? newParent : null; - } -} - -// src/utils/dnd/dropFile.ts -var import_obsidian52 = require("obsidian"); -var dropFileInTree = async (plugin, active, over, projected, flattenedTree, activeSpaces) => { - var _a2, _b2, _c2, _d2, _e2, _f, _g, _h; - if (projected) { - const clonedItems = flattenedTree; - const overIndex = clonedItems.findIndex(({ id: id2 }) => id2 === over.id); - const overItem = clonedItems[overIndex]; - const activeIndex = clonedItems.findIndex(({ id: id2 }) => id2 === active.id); - const activeItem = clonedItems[activeIndex]; - const activeIsSection = activeItem.parentId == null; - const overIsSection = overItem.parentId == null; - const overSpace = activeSpaces.find( - (f4) => f4.name == overItem.space - ); - const activeSpace = activeSpaces.find( - (f4) => f4.name == activeItem.space - ); - const overIsFolderSpace = ((_b2 = (_a2 = overSpace == null ? void 0 : overSpace.def) == null ? void 0 : _a2.folder) == null ? void 0 : _b2.length) > 0; - const overIsSmartSpace = ((_c2 = overSpace == null ? void 0 : overSpace.def) == null ? void 0 : _c2.type) == "smart"; - const activeIsFolderSpace = ((_e2 = (_d2 = activeSpace == null ? void 0 : activeSpace.def) == null ? void 0 : _d2.folder) == null ? void 0 : _e2.length) > 0; - const activeIsSmartSpace = ((_f = activeSpace == null ? void 0 : activeSpace.def) == null ? void 0 : _f.type) == "smart"; - const { depth, overId, parentId } = projected; - const parentItem = clonedItems.find(({ id: id2 }) => id2 === parentId); - const parentIsSpace = (parentItem == null ? void 0 : parentItem.item) ? false : true; - const newRank = (_h = (_g = overItem.item) == null ? void 0 : _g.rank) != null ? _h : "-1"; - if (activeIsSection) { - if (overIsSection) { - const activeSpace2 = activeSpaces.find( - (f4) => f4.name == activeItem.space - ); - insertSpaceAtIndex( - plugin, - activeSpace2, - overSpace ? parseInt(overSpace.rank) : activeSpaces.length - ); - } - return; - } - let newParent = activeItem.item.parent; - if (parentIsSpace) { - if (overIsSmartSpace) { - return; - } - if (overIsFolderSpace) { - newParent = overSpace.def.folder; - } else { - insertSpaceItemAtIndex( - plugin, - overItem.space, - activeItem.item.path, - parseInt(newRank) - ); - return; - } - } else { - newParent = parentItem.item.isFolder ? parentItem.item.path : parentItem.item.parent; - } - const newPath = newParent == "/" ? activeItem.file.name : `${newParent}/${activeItem.file.name}`; - if (newPath == activeItem.item.path) { - if (!activeIsFolderSpace && activeItem.depth == 1) { - removePathsFromSpace(plugin, activeItem.space, [ - activeItem.item.path - ]); - } - if (activeItem.parentId == overItem.id) { - updateFileRank(plugin, activeItem.item, -1); - return; - } else { - updateFileRank(plugin, activeItem.item, parseInt(newRank)); - return; + style: { + ...style, + ...((_b2 = pin.color) == null ? void 0 : _b2.length) > 0 ? { + "--label-color": `${pin.color}`, + "--icon-color": `var(--text-normal)` + } : { + "--icon-color": `var(--text-muted)` + }, + ...{ pointerEvents: "none" } } - } else { - if (plugin.app.vault.getAbstractFileByPath(newPath)) { - new import_obsidian52.Notice(i18n_default.notice.duplicateFile); - return; + })) : /* @__PURE__ */ Cn.createElement("div", { + ref: innerRef, + className: "mk-waypoint" + }, /* @__PURE__ */ Cn.createElement("div", { + ref: ref2, + className: (0, import_classnames8.default)( + "mk-waypoints-item", + "clickable-icon", + "nav-action-button", + highlighted && "mk-active", + indicator && "mk-indicator", + clone && "mk-clone", + ghost && "mk-ghost" + ), + style: { + ...style, + ...{ pointerEvents: "none" } } - removePathsFromSpace(plugin, activeItem.space, [ - activeItem.item.path - ]); - moveAFileToNewParentAtIndex( - plugin, - activeItem.item, - newParent, - parseInt(newRank) - ); - return; - } + })); } -}; +); +PinnedSpace.displayName = "PinnedSpace"; -// src/components/Spaces/TreeView/FileExplorerVirtualized.tsx -var VirtualizedList = Cn.memo(function VirtualizedList2(props2) { +// src/components/Navigator/Waypoints/Waypoints.tsx +var SpaceSwitcher = (props2) => { const { - flattenedTree, - projected, - vRef, - selectedFiles: selectedFiles2, - activeFile: activeFile2, - selectRange: selectRange2, - handleCollapse, - plugin, - indentationWidth - } = props2; - const parentRef = Cn.useRef(null); - const rowHeight = (index) => flattenedTree[index].parentId == null ? spaceRowHeight(plugin) + 8 : spaceRowHeight(plugin); - const rowVirtualizer = useVirtual({ - size: flattenedTree.length, - paddingEnd: 24, - parentRef, - estimateSize: Cn.useCallback( - (index) => rowHeight(index), - [flattenedTree] - ), - overscan: plugin.settings.spacesPerformance ? 0 : 20 - }); - vRef.current = rowVirtualizer; - rowVirtualizer.scrollToIndex; - return /* @__PURE__ */ Cn.createElement("div", { - ref: parentRef, - style: { - width: `100%`, - height: `100%`, - overflow: "auto", - "--spaceRowHeight": spaceRowHeight(plugin) - } - }, /* @__PURE__ */ Cn.createElement("div", { - style: { - height: `${rowVirtualizer.totalSize}px`, - width: "100%", - position: "relative" - } - }, rowVirtualizer.virtualItems.map((virtualRow) => /* @__PURE__ */ Cn.createElement("div", { - key: virtualRow.index, - ref: virtualRow.measureRef, - style: { - position: "absolute", - top: 0, - left: 0, - width: "100%", - height: `${rowHeight(virtualRow.index)}px`, - transform: `translateY(${virtualRow.start}px)` - } - }, /* @__PURE__ */ Cn.createElement(SortableTreeItem, { - key: flattenedTree[virtualRow.index].id, - id: flattenedTree[virtualRow.index].id, - data: flattenedTree[virtualRow.index], - disabled: false, - depth: flattenedTree[virtualRow.index].depth, - childCount: flattenedTree[virtualRow.index].childrenCount, - indentationWidth, - indicator: (projected == null ? void 0 : projected.sortable) && (projected == null ? void 0 : projected.overId) == flattenedTree[virtualRow.index].id ? flattenedTree[virtualRow.index].parentId == null && projected.parentId == null ? { state: 1 /* Top */, depth: projected.depth } : { state: 2 /* Bottom */, depth: projected.depth } : null, - plugin, - style: {}, - onSelectRange: selectRange2, - active: (activeFile2 == null ? void 0 : activeFile2.path) == (flattenedTree[virtualRow.index].item ? flattenedTree[virtualRow.index].item.path : flattenedTree[virtualRow.index].space + "//"), - highlighted: projected && !projected.sortable && (projected.parentId == flattenedTree[virtualRow.index].parentId || projected.parentId == flattenedTree[virtualRow.index].id), - selected: selectedFiles2.some( - (g4) => g4.id == flattenedTree[virtualRow.index].id - ), - collapsed: flattenedTree[virtualRow.index].collapsed, - onCollapse: handleCollapse - }))))); -}); -var FileExplorerComponent = (props2) => { + activeFile, + waypoints, + modifier, + setModifier + } = q2(NavigatorContext); + const folder = defaultNoteFolder(props2.plugin, activeFile); const { plugin } = props2; - const indentationWidth = 24; - const [vaultItems, setVaultItems] = h2({}); - const [expandedFolders2, setExpandedFolders] = h2(plugin.settings.expandedFolders); - const [expandedSpaces, setExpandedSpaces] = h2( - plugin.settings.expandedSpaces - ); - const [activeFile2, setActiveFile] = Recoil_index_14(activeFile); - const [spaces2, setSpaces] = h2([]); - const [selectedFiles2, setSelectedFiles] = Recoil_index_14( - selectedFiles - ); - const nextTreeScrollPath = _2(null); - const activeSpaces = F2( - () => props2.viewType == "root" ? spaces2.filter((f4) => f4.pinned == "false" || f4.pinned == "home") : props2.viewType == "space" ? spaces2.filter((f4) => f4.name == props2.activeSpace) : spaces2.sort((a5, b4) => { - var _a2, _b2; - return ((_a2 = a5.name) != null ? _a2 : "").localeCompare((_b2 = b4.name) != null ? _b2 : ""); - }), - [spaces2, props2.activeSpace, props2.viewType] - ); - const [offsetLeft, setOffsetLeft] = h2(0); - const listRef = _2(null); - const forceUpdate = useForceUpdate(); - const treeForSpace = (space) => { - var _a2, _b2; - const tree = []; - const spaceCollapsed = !expandedSpaces.includes(space.name); - const spaceSort = (_a2 = safelyParseJSON(space.sort)) != null ? _a2 : ["rank", true]; - tree.push(spaceToTreeNode(space, spaceCollapsed, true)); - if (!spaceCollapsed) - ((_b2 = vaultItems[space.name + "/"]) != null ? _b2 : []).sort(folderSortFn(spaceSort[0], spaceSort[1])).forEach((item) => { - var _a3, _b3, _c2; - const itemCollapsed = !((_a3 = expandedFolders2[space.name]) == null ? void 0 : _a3.includes( - item.path - )); - const items = []; - if (!itemCollapsed) { - const [sortStrat, dir] = ((_b3 = item.folderSort) == null ? void 0 : _b3.length) > 0 ? parseSortStrat(item.folderSort) : spaceSort; - items.push( - ...flattenedTreeFromVaultItems( - item.path, - space.name, - vaultItems, - (_c2 = expandedFolders2[space.name]) != null ? _c2 : [], - 2, - sortStrat, - dir - ) - ); - } - items.splice( - 0, - 0, - vaulItemToTreeNode( - item, - space.name, - "", - 1, - 0, - itemCollapsed, - space.def.type == "focus" && (spaceSort[0] == "rank" || spaceSort[0] == ""), - items.length - ) - ); - tree.push(...items); - }); - return tree; - }; - const flattenedTree = F2(() => { - const tree = []; - activeSpaces.forEach((space) => { - tree.push(...treeForSpace(space)); - }); - if (nextTreeScrollPath.current) { - const index = tree.findIndex( - (f4) => { - var _a2; - return ((_a2 = f4.item) == null ? void 0 : _a2.path) == nextTreeScrollPath.current; - } - ); - if (index != -1) { - listRef.current.scrollToIndex(index); - nextTreeScrollPath.current = null; - } - } - return tree; - }, [ - vaultItems, - activeSpaces, - expandedSpaces, - expandedFolders2, - props2.activeSpace - ]); - p2(() => { - if (selectedFiles2.length <= 1) { - if (!selectedFiles2[0] || selectedFiles2[0].item.path != (activeFile2 == null ? void 0 : activeFile2.path)) - setSelectedFiles([]); - if (plugin.settings.revealActiveFile) - revealFile(activeFile2); - } - window.addEventListener(eventTypes.activePathChange, changeActiveFile); - return () => { - window.removeEventListener(eventTypes.activePathChange, changeActiveFile); - }; - }, [activeFile2]); - p2(() => { - window.addEventListener(eventTypes.refreshView, forceUpdate); - window.addEventListener(eventTypes.settingsChanged, settingsChanged); - return () => { - window.removeEventListener(eventTypes.refreshView, forceUpdate); - window.removeEventListener(eventTypes.settingsChanged, settingsChanged); - }; - }, []); - p2(() => { - window.addEventListener(eventTypes.revealFile, handleRevealFileEvent); - return () => { - window.removeEventListener(eventTypes.revealFile, handleRevealFileEvent); - }; - }, [activeSpaces]); - const revealFile = (path) => { - var _a2, _b2; - const space = activeSpaces.find((f4) => f4.def.folder == "/"); - if (!space || !path || path.type != "file" && path.type != "folder") - return; - const file = getAbstractFileAtPath(app, path.path); - const folders = file.path.split("/"); - const openPaths = folders.reduce( - (p3, c4, index) => [...p3, index == 0 ? c4 : `${p3[index]}/${c4}`], - ["/"] - ).slice(0, -1); - const newOpenFolders = [ - ...(_b2 = (_a2 = expandedFolders2[space.name]) == null ? void 0 : _a2.filter( - (f4) => !openPaths.find((g4) => g4 == f4) - )) != null ? _b2 : [], - ...openPaths - ]; - plugin.settings.expandedFolders = { - ...expandedFolders2, - [space.name]: newOpenFolders - }; - nextTreeScrollPath.current = file.path; - plugin.saveSettings(); - }; - const handleRevealFileEvent = (evt) => { - if (evt.detail) - revealFile(pathByString(evt.detail.file.path)); - }; - const retrieveData = async (folders) => { - setSpaces(plugin.index.allSpaces()); - const spaceItems = plugin.index.spacesMap; - setVaultItems((g4) => ({ - ...g4, - ...[...plugin.index.spacesIndex.keys()].reduce( - (p3, c4) => { - var _a2; - return { - ...p3, - [c4 + "/"]: [...(_a2 = spaceItems.getInverse(c4)) != null ? _a2 : []].map((f4) => { - var _a3; - const fileCache = plugin.index.filesIndex.get(f4); - return { ...fileCache, rank: (_a3 = fileCache == null ? void 0 : fileCache.spaceRanks) == null ? void 0 : _a3[c4] }; - }).filter((f4) => f4) - }; - }, - {} - ) - })); - retrieveFolders(plugin, folders).then( - (f4) => setVaultItems((g4) => ({ ...g4, ...f4 })) - ); - }; - const flatFolders = F2(() => { - const allFolders = []; - expandedSpaces.forEach((space) => { - var _a2; - allFolders.push(...(_a2 = expandedFolders2[space]) != null ? _a2 : []); - }); - return allFolders; - }, [expandedSpaces, expandedFolders2]); - p2(() => { - const newFolders = flatFolders; - retrieveData(newFolders); - window.addEventListener(eventTypes.spacesChange, spaceChangeEvent); - return () => { - window.removeEventListener(eventTypes.spacesChange, spaceChangeEvent); - }; - }, [flatFolders]); - const spaceChangeEvent = (evt) => { - if (evt.detail.type == "vault" || evt.detail.type == "space" || evt.detail.type == "sync") { - retrieveData(flatFolders); - } - }; - const changeActiveFile = (evt) => { - const path = evt.detail.path; - setActiveFile(path); - }; - const settingsChanged = () => { - setExpandedFolders(plugin.settings.expandedFolders); - setExpandedSpaces(plugin.settings.expandedSpaces); + const newFile = async () => { + await createNewMarkdownFile(props2.plugin, folder, "", ""); }; - p2(() => { - settingsChanged(); - }, []); + const { dragPaths, setDragPaths } = q2(NavigatorContext); const [activeId, setActiveId] = h2(null); const [overId, setOverId] = h2(null); - const [currentPosition, setCurrentPosition] = h2(null); + const dragCounter = _2(0); + const [offset2, setOffset] = h2(0); + const [projected, setProjected] = h2(null); + const [dropPlaceholder, setDragPlaceholder] = h2(null); p2(() => { - if (!expandedSpaces.includes(props2.activeSpace)) { - plugin.settings.expandedSpaces = uniq([ - ...plugin.settings.expandedSpaces, - props2.activeSpace - ]); - plugin.saveSettings(); + if (overId === null || dragPaths.length == 0) { + setProjected(null); + return; } - }, [props2.activeSpace]); - const sortedIds = F2( - () => flattenedTree.map(({ id: id2 }) => id2), - [flattenedTree] - ); - const selectRange2 = (fromId) => { - const startIndex = sortedIds.findIndex((f4) => f4 == fromId); - const selectedFilesStartIndex = sortedIds.findIndex( - (f4) => { - var _a2; - return f4 == ((_a2 = selectedFiles2[0]) == null ? void 0 : _a2.id); - } - ); - const selectedFilesEndIndex = sortedIds.findIndex( - (f4) => { - var _a2; - return f4 == ((_a2 = selectedFiles2[selectedFiles2.length - 1]) == null ? void 0 : _a2.id); + const waypoint = waypoints.find((f4) => f4.path == overId); + if (!waypoint) + return; + if (dragPaths.length > 1) { + if (waypoint.cacheType != "file") { + const _projected = { + depth: 0, + overId, + parentId: null, + sortable: false, + insert: true, + droppable: true, + copy: false, + reorder: false + }; + setProjected(_projected); + return; + } else { + return null; } - ); - if (startIndex < selectedFilesStartIndex) { - setSelectedFiles( - flattenedTree.slice(startIndex, selectedFilesEndIndex + 1).filter((f4) => f4.item) - ); } else { - setSelectedFiles( - flattenedTree.slice(selectedFilesStartIndex, startIndex + 1).filter((f4) => f4.item) - ); + const insert2 = !activeId && (!pathIsSpace(props2.plugin, dragPaths[0]) || modifier == "copy" || modifier == "link"); + const _projected = { + depth: 0, + overId, + parentId: null, + sortable: false, + insert: insert2, + droppable: waypoint.cacheType != "file", + copy: modifier == "copy" || modifier == "link", + reorder: false + }; + setProjected(_projected); } + }, [overId, dragPaths, offset2, modifier, waypoints, activeId]); + const resetState = () => { + setModifier(null); + setOverId(null); + setDragPaths([]); + setActiveId(null); + setProjected(null); + setOffset(0); + dragCounter.current = 0; }; - const activeItem = activeId ? flattenedTree.find(({ id: id2 }) => id2 === activeId) : null; - const overIndex = overId ? flattenedTree.findIndex(({ id: id2 }) => id2 === overId) : null; - const overItem = flattenedTree[overIndex]; - const nextItem = flattenedTree[overIndex + 1]; - const dragDepth = F2(() => { - return getDragDepth(offsetLeft, indentationWidth); - }, [offsetLeft]); - const projected = F2(() => { - return activeId && overId ? getProjection( - flattenedTree, - activeItem, - overIndex, - overItem, - nextItem, - dragDepth - ) : null; - }, [flattenedTree, activeItem, overItem, nextItem, overIndex, dragDepth]); - function handleDragStart(event) { - const { - active: { id: activeId2 } - } = event; - const activeItem2 = flattenedTree.find(({ id: id2 }) => id2 === activeId2); - setActiveId(activeId2); - setOverId(activeId2); - if (activeItem2) { - setCurrentPosition({ - parentId: activeItem2.parentId, - overId: activeId2 - }); - } - document.body.style.setProperty("cursor", "grabbing"); - } - function handleDragMove({ delta }) { - setOffsetLeft(Math.max(1, delta.x)); - } - function handleDragOver({ over }) { - var _a2; - const overId2 = over == null ? void 0 : over.id; - if (overId2) { - setOverId((_a2 = over == null ? void 0 : over.id) != null ? _a2 : null); - } - } - function handleDragEnd({ active, over }) { + const handleDragCancel = () => { resetState(); - dropFileInTree( - plugin, - active, - over, - projected, - flattenedTree, - activeSpaces - ); - } + }; + const dragEnter = () => { + dragCounter.current++; + }; + const dragLeave = () => { + dragCounter.current--; + if (dragCounter.current == 0) { + setOverId(null); + setProjected(null); + setOffset(0); + dragCounter.current = 0; + } + }; const adjustTranslate = ({ transform }) => { return { ...transform, @@ -53103,42 +62978,39 @@ var FileExplorerComponent = (props2) => { y: transform.y - 10 }; }; - function handleDragCancel() { - resetState(); - } - const handleCollapse = T2( - (folder, open) => { - var _a2; - if (folder.parentId == null) { - if (plugin.settings.expandedSpaces.includes(folder.space) && !open) - plugin.settings.expandedSpaces = plugin.settings.expandedSpaces.filter((f4) => f4 != folder.space); - else - plugin.settings.expandedSpaces = [ - ...plugin.settings.expandedSpaces, - folder.space - ]; + const dragStarted = (id2) => { + setActiveId(id2); + }; + const dragOver = (id2, x5) => { + setOffset(x5); + setOverId(id2); + }; + const dragEnded = () => { + if (projected && projected.insert) { + const space = props2.plugin.index.spacesIndex.get(overId); + if (space) + movePathsToSpace(props2.plugin, dragPaths, space, 0, "link"); + } else if (dragPaths.length == 1) { + const toIndex = waypoints.findIndex((f4) => f4.path == overId); + if (activeId !== null) { + const fromIndex = waypoints.findIndex((f4) => f4.path == activeId); + plugin.settings.waypoints = arrayMove( + waypoints.map((f4) => f4.path), + fromIndex, + toIndex + ); plugin.saveSettings(); } else { - const openFolders = (_a2 = expandedFolders2[folder.space]) != null ? _a2 : []; - const folderOpen = openFolders == null ? void 0 : openFolders.includes(folder.item.path); - const newOpenFolders = !folderOpen || open ? [...openFolders, folder.item.path] : openFolders.filter( - (openFolder) => folder.item.path !== openFolder + plugin.settings.waypoints = insert( + waypoints.map((f4) => f4.path).filter((f4) => f4 != dragPaths[0]), + toIndex, + dragPaths[0] ); - plugin.settings.expandedFolders = { - ...expandedFolders2, - [folder.space]: newOpenFolders - }; plugin.saveSettings(); } - }, - [plugin, expandedFolders2, expandedSpaces] - ); - function resetState() { - setOverId(null); - setActiveId(null); - setOffsetLeft(0); - document.body.style.setProperty("cursor", ""); - } + } + resetState(); + }; useDndMonitor({ onDragStart: handleDragStart, onDragMove: handleDragMove, @@ -53146,368 +63018,111 @@ var FileExplorerComponent = (props2) => { onDragEnd: handleDragEnd, onDragCancel: handleDragCancel }); - return /* @__PURE__ */ Cn.createElement("div", { - className: "mk-file-tree" - }, /* @__PURE__ */ Cn.createElement(SortableContext, { - items: sortedIds, - strategy: verticalListSortingStrategy - }, /* @__PURE__ */ Cn.createElement(VirtualizedList, { - vRef: listRef, - flattenedTree, - projected, - handleCollapse, - activeFile: activeFile2, - plugin, - selectedFiles: selectedFiles2, - selectRange: selectRange2, - indentationWidth - }), z3( - /* @__PURE__ */ Cn.createElement(DragOverlay, { - dropAnimation: null, - modifiers: [adjustTranslate], - zIndex: 1600 - }, activeId ? /* @__PURE__ */ Cn.createElement(SortableTreeItem, { - id: activeId, - data: flattenedTree.find((f4) => f4.id == activeId), - indicator: null, - depth: 0, - disabled: false, - plugin, - selected: false, - highlighted: false, - active: false, - clone: true, - childCount: 0, - style: {}, - indentationWidth - }) : null), - document.body - ))); -}; - -// src/components/Spaces/SpaceSwitcher/SpaceSwitcher.tsx -var import_classnames8 = __toESM(require_classnames()); -var SpaceSwitcher = (props2) => { - const [activeView2, setActiveView] = Recoil_index_14(activeView); - const [spaces2, setSpaces] = h2([]); - const [activeFile2, setActiveFile] = Recoil_index_14(activeFile); - const folder = defaultNoteFolder(props2.plugin, activeFile2); - const { plugin } = props2; - const newFile = async () => { - await createNewMarkdownFile(props2.plugin, folder, "", ""); - }; - const pinnedSpaces = F2( - () => spaces2.filter((f4) => f4.pinned == "true" || f4.pinned == "pinned"), - [spaces2] - ); - const [activeViewSpace2, setActiveViewSpace] = Recoil_index_14( - activeViewSpace - ); - p2(() => { - loadCachedSpaces(); - }, []); - const loadCachedSpaces = () => { - setSpaces([...plugin.index.allSpaces()]); - setActiveView(plugin.settings.activeView); - setActiveViewSpace(plugin.settings.activeSpace); - }; - p2(() => { - window.addEventListener(eventTypes.spacesChange, loadCachedSpaces); - return () => { - window.removeEventListener(eventTypes.spacesChange, loadCachedSpaces); - }; - }, [loadCachedSpaces]); - p2(() => { - plugin.settings.activeSpace = activeViewSpace2; - plugin.settings.activeView = activeView2; - plugin.saveSettings(); - }, [activeView2, activeViewSpace2]); - return /* @__PURE__ */ Cn.createElement(Cn.Fragment, null, /* @__PURE__ */ Cn.createElement("div", { - className: "mk-flow-bar" - }, /* @__PURE__ */ Cn.createElement("button", { - "aria-label": i18n_default.buttons.newNote, - className: "mk-new-note", - onClick: () => newFile() - }, /* @__PURE__ */ Cn.createElement("div", { - dangerouslySetInnerHTML: { __html: uiIconSet["mk-ui-new-note"] } - }), /* @__PURE__ */ Cn.createElement("p", null, i18n_default.buttons.newNote)), props2.plugin.settings.blinkEnabled && /* @__PURE__ */ Cn.createElement("button", { - "aria-label": i18n_default.buttons.blink, - className: "mk-button-blink", - onClick: () => props2.plugin.quickOpen() - }, /* @__PURE__ */ Cn.createElement("div", { - dangerouslySetInnerHTML: { __html: uiIconSet["mk-ui-blink"] } - }))), /* @__PURE__ */ Cn.createElement("div", { - className: "mk-sidebar-switcher" - }, /* @__PURE__ */ Cn.createElement("div", { - className: (0, import_classnames8.default)( - "mk-sidebar-item", - activeView2 == "root" && "mk-sidebar-item-active" - ), - onClick: () => setActiveView("root") - }, /* @__PURE__ */ Cn.createElement("div", { - className: "mk-icon-small", - dangerouslySetInnerHTML: { __html: uiIconSet["mk-ui-home"] } - })), /* @__PURE__ */ Cn.createElement("div", { - className: (0, import_classnames8.default)( - "mk-sidebar-item", - activeView2 == "tags" && "mk-sidebar-item-active" - ), - onClick: () => setActiveView("tags") - }, /* @__PURE__ */ Cn.createElement("div", { - className: "mk-icon-small", - dangerouslySetInnerHTML: { __html: uiIconSet["mk-ui-tags"] } - })), /* @__PURE__ */ Cn.createElement("div", { - className: (0, import_classnames8.default)( - "mk-sidebar-item", - activeView2 == "all" && "mk-sidebar-item-active" - ), - onClick: () => setActiveView("all") - }, /* @__PURE__ */ Cn.createElement("div", { - className: "mk-icon-small", - dangerouslySetInnerHTML: { __html: uiIconSet["mk-ui-spaces"] } - })), /* @__PURE__ */ Cn.createElement("div", { - className: "mk-sidebar-spaces" - }, pinnedSpaces.map((pin, i4) => { - var _a2; - return /* @__PURE__ */ Cn.createElement("div", { - key: i4, - onContextMenu: (e4) => triggerSectionMenu(props2.plugin, pin, spaces2, e4, activeFile2), - className: (0, import_classnames8.default)( - "mk-sidebar-item mk-sidebar-space", - activeView2 == "space" && activeViewSpace2 == pin.name && "mk-sidebar-item-active" - ), - onClick: () => (setActiveView("space"), setActiveViewSpace(pin.name)), - dangerouslySetInnerHTML: ((_a2 = pin.sticker) == null ? void 0 : _a2.length) > 0 ? { __html: stickerFromString(pin.sticker, props2.plugin) } : null - }, pin.name.substring(0, 1)); - })), /* @__PURE__ */ Cn.createElement("div", { - className: (0, import_classnames8.default)("mk-sidebar-item"), - onClick: (e4) => triggerSectionAddMenu(plugin, e4) - }, /* @__PURE__ */ Cn.createElement("div", { - className: "mk-icon-small", - dangerouslySetInnerHTML: { __html: uiIconSet["mk-ui-new-space"] } - }, " ")))); -}; - -// src/components/ui/modals/tagChangeModal.ts -var import_obsidian53 = require("obsidian"); -var TagChangeModal = class extends import_obsidian53.Modal { - constructor(plugin, action, tag) { - super(plugin.app); - this.action = action; - this.plugin = plugin; - this.tag = tag; - } - onOpen() { - let { contentEl } = this; - let myModal = this; - let headerText; - if (this.action === "rename") { - headerText = "Rename Tag"; - } else if (this.action === "create tag") { - headerText = "New Tag"; - } - const headerEl = contentEl.createEl("div", { text: headerText }); - headerEl.addClass("modal-title"); - const inputEl = contentEl.createEl("input"); - inputEl.style.cssText = "width: 100%; height: 2.5em; margin-bottom: 15px;"; - if (this.action === "rename") { - inputEl.value = this.tag; - } - inputEl.focus(); - let changeButtonText; - if (this.action === "rename") { - changeButtonText = "Rename Tag"; - } else if (this.action === "create tag") { - changeButtonText = "Create Tag"; + function handleDragStart(event) { + const { + active: { id: activeId2 } + } = event; + const waypoint = waypoints.find((f4) => f4.path == activeId2); + if (waypoint) { + setDragPaths([waypoint.path]); } - const changeButton = contentEl.createEl("button", { - text: changeButtonText - }); - const cancelButton = contentEl.createEl("button", { - text: i18n_default.buttons.cancel - }); - cancelButton.style.cssText = "float: right;"; - cancelButton.addEventListener("click", () => { - myModal.close(); - }); - const onClickAction = async () => { - let newName = inputEl.value; - if (this.action === "rename") { - renameTag(this.plugin, this.tag, newName); - } else if (this.action === "create tag") { - addTag(this.plugin, newName); - } - myModal.close(); - }; - changeButton.addEventListener("click", onClickAction); - inputEl.addEventListener("keydown", (e4) => { - if (e4.key === "Enter") { - e4.preventDefault(); - onClickAction(); - } - }); + dragStarted(activeId2); } - onClose() { - let { contentEl } = this; - contentEl.empty(); + function handleDragMove({ delta }) { } -}; - -// src/components/Spaces/TagContextList/TagContextList.tsx -var import_lodash9 = __toESM(require_lodash()); -var import_obsidian54 = require("obsidian"); -var TagContextList = (props2) => { - const [allTags, setAllTags] = h2([]); - const [allQueries, setAllQueries] = h2([]); - const openContextMenu = async (e4, tag) => { - const fileMenu = new import_obsidian54.Menu(); - fileMenu.addItem((menuItem) => { - menuItem.setTitle("Rename Tag"); - menuItem.setIcon("edit"); - menuItem.onClick((ev) => { - const vaultChangeModal = new TagChangeModal( - props2.plugin, - "rename", - tag - ); - vaultChangeModal.open(); - }); - }); - fileMenu.addItem((menuItem) => { - menuItem.setTitle("Delete Tag"); - menuItem.setIcon("trash"); - menuItem.onClick((ev) => { - deleteTag(props2.plugin, tag, true); - }); - }); - if (isMouseEvent(e4)) { - fileMenu.showAtPosition({ x: e4.pageX, y: e4.pageY }); - } else { - fileMenu.showAtPosition({ - x: e4.nativeEvent.locationX, - y: e4.nativeEvent.locationY - }); + function handleDragOver({ over }) { + const overId2 = over == null ? void 0 : over.id; + if (overId2 !== null) { + setOverId(overId2); } - }; - const openContextView = async (tag) => { - openTagContext(tag, props2.plugin, false); - }; + } + function handleDragEnd({ active, over }) { + dragEnded(); + } p2(() => { - window.addEventListener(eventTypes.spacesChange, refreshData); + window.addEventListener("dragend", resetState); return () => { - window.removeEventListener(eventTypes.spacesChange, refreshData); + window.removeEventListener("dragend", resetState); }; - }, []); - const refreshData = () => { - refreshTags(); - }; - const refreshTags = () => { - var _a2; - const folder = props2.plugin.settings.tagContextFolder == "" ? app.vault.getRoot() : getAbstractFileAtPath( - app, - getFolderPathFromString(props2.plugin.settings.tagContextFolder) - ); - const f4 = (_a2 = folder == null ? void 0 : folder.children.filter( - (f5) => f5 instanceof import_obsidian54.TFile && f5.extension == "mdb" && f5.name.charAt(0) == "#" - ).map((f5) => tagPathToTag(fileNameToString(f5.name)))) != null ? _a2 : []; - setAllTags( - (0, import_lodash9.uniq)([...f4.filter((g4) => g4), ...Object.keys(app.metadataCache.getTags())]) - ); - }; - p2(() => { - refreshData(); - }, []); - const tags = F2(() => { - return (0, import_lodash9.uniq)( - allTags.reduce((p3, c4) => { - const r3 = c4.split("/"); - const allSubTags = r3.reduce((a5, b4, i4, array) => { - return [...a5, array.slice(0, i4 + 1).join("/")]; - }, []); - return [...p3, ...allSubTags]; - }, []) - ).map((f4) => { - const r3 = f4.split("/"); - return { - tag: f4, - name: stringFromTag(r3[r3.length - 1]), - parent: r3.length > 1 ? r3.slice(0, r3.length - 1).join("/") : null, - depth: r3.length - 1 - }; - }).sort(compareByFieldCaseInsensitive("tag", true)); - }, [allTags]); - const indentationWidth = 24; - return /* @__PURE__ */ Cn.createElement("div", { - className: "tag-container mk-context-tree" - }, /* @__PURE__ */ Cn.createElement("div", { - className: "mk-tree-wrapper" - }, /* @__PURE__ */ Cn.createElement("div", { - className: "mk-section" - }, /* @__PURE__ */ Cn.createElement("div", { - className: "mk-section-title" - }, /* @__PURE__ */ Cn.createElement("div", { - className: "mk-tree-text" - }, "Tags")), /* @__PURE__ */ Cn.createElement("div", null, /* @__PURE__ */ Cn.createElement("button", { - "aria-label": "New Tag", - className: "mk-inline-button", - onClick: () => { - const vaultChangeModal = new TagChangeModal( - props2.plugin, - "create tag" - ); - vaultChangeModal.open(); - }, - dangerouslySetInnerHTML: { - __html: uiIconSet["mk-ui-plus"] + }); + const width = platformIsMobile() ? 48 : 32; + const calcXOffset = (index) => { + if (!projected || projected.insert) + return 0; + const fromIndex = waypoints.findIndex((f4) => f4.path == activeId); + const targetIndex = waypoints.findIndex((f4) => f4.path == overId); + if (activeId === null) { + if (index >= targetIndex) + return width; + return 0; } - })))), /* @__PURE__ */ Cn.createElement("div", { - className: "tree-item" - }, tags.map((f4, i4) => /* @__PURE__ */ Cn.createElement("div", { - key: i4, - className: "tree-item-self is-clickable mk-context-item", - onContextMenu: (e4) => openContextMenu(e4, f4.tag), - onClick: () => openContextView(f4.tag), - style: { - "--spacing": `${indentationWidth * f4.depth}px` + if (index == fromIndex) { + return width * (targetIndex - fromIndex); + } else if (index > fromIndex && index <= targetIndex) { + return -width; + } else if (index < fromIndex && index >= targetIndex) { + return width; + } else { + return 0; } + }; + return /* @__PURE__ */ Cn.createElement(Cn.Fragment, null, /* @__PURE__ */ Cn.createElement("div", { + className: "mk-waypoints nav-header", + onDragEnter: () => dragEnter(), + onDragLeave: () => dragLeave(), + onDragOver: (e4) => e4.preventDefault() }, /* @__PURE__ */ Cn.createElement("div", { - className: "mk-file-icon" - }, /* @__PURE__ */ Cn.createElement("button", { - dangerouslySetInnerHTML: { - __html: uiIconSet["mk-ui-tags"] - } - })), f4.name)))); + className: "nav-buttons-container" + }, waypoints.map((pin, i4) => /* @__PURE__ */ Cn.createElement(SortablePinnedSpaceItem, { + id: pin.path, + plugin: props2.plugin, + highlighted: overId == pin.path && projected && projected.insert && projected.droppable, + style: { + transform: CSS.Translate.toString({ + x: calcXOffset(i4), + y: 0, + scaleX: 0, + scaleY: 0 + }) + }, + index: i4, + pin, + key: pin.path, + dragStart: dragStarted, + dragOver, + dragEnded, + dragActive: activeId !== null, + ghost: activeId === pin.path + })), overId != null && activeId === null && /* @__PURE__ */ Cn.createElement(SortablePinnedSpaceItem, { + id: waypoints.length, + plugin: props2.plugin, + highlighted: false, + index: waypoints.length, + pin: null + })), z3( + /* @__PURE__ */ Cn.createElement(DragOverlay, { + dropAnimation: null, + modifiers: [adjustTranslate], + zIndex: 1600 + }, activeId !== null ? /* @__PURE__ */ Cn.createElement(SortablePinnedSpaceItem, { + id: -1, + plugin: props2.plugin, + highlighted: false, + clone: true, + index: waypoints.findIndex((f4) => f4.path == activeId), + indicator: false, + pin: waypoints.find((f4) => f4.path == activeId) + }) : null), + document.body + ))); }; -// src/components/Spaces/MainList.tsx +// src/components/Navigator/MainList.tsx var MainList = (props2) => { - const [activeView2, setActiveView] = Recoil_index_14(activeView); - const [spaces2, setSpaces] = h2(props2.plugin.index.allSpaces()); - const [activeViewSpace2, setActiveViewSpace] = Recoil_index_14( - activeViewSpace - ); - const [syncState, setSyncState] = h2(props2.plugin.index.syncStatus); + const { activeViewSpace } = q2(NavigatorContext); const [error, resetError] = P2(); if (error) console.log(error); - p2(() => { - if (activeView2 == "space" && !spaces2.some( - (f4) => f4.name == activeViewSpace2 && (f4.pinned == "true" || f4.pinned == "pinned") - )) { - setActiveView("root"); - } - }, [spaces2]); - const reloadSync = (evt) => { - if (evt.detail.type == "sync") { - setSyncState(props2.plugin.index.syncStatus); - } - }; - p2(() => { - window.addEventListener(eventTypes.spacesChange, reloadSync); - return () => { - window.removeEventListener(eventTypes.spacesChange, reloadSync); - }; - }, [reloadSync]); const sensors = useSensors( useSensor(MouseSensor, { activationConstraint: { @@ -53526,73 +63141,38 @@ var MainList = (props2) => { strategy: MeasuringStrategy.Always } }; - const viewForState = (viewType, space) => { - if (viewType == "root") { - return /* @__PURE__ */ Cn.createElement(FileExplorerComponent, { - viewType, - plugin: props2.plugin - }); - } else if (viewType == "tags") { - return /* @__PURE__ */ Cn.createElement(TagContextList, { - plugin: props2.plugin - }); - } else if (viewType == "space") { - return /* @__PURE__ */ Cn.createElement(FileExplorerComponent, { - plugin: props2.plugin, - viewType, - activeSpace: space - }); - } else if (viewType == "all") { - return /* @__PURE__ */ Cn.createElement(FileExplorerComponent, { - plugin: props2.plugin, - viewType - }); - } - return /* @__PURE__ */ Cn.createElement(FileExplorerComponent, { - plugin: props2.plugin, - viewType: "root" - }); - }; return /* @__PURE__ */ Cn.createElement(DndContext, { sensors, collisionDetection: closestCenter, measuring - }, !platformIsMobile() ? props2.plugin.settings.spacesCompactMode ? /* @__PURE__ */ Cn.createElement(MainMenu, { - plugin: props2.plugin, - compactMode: true - }) : /* @__PURE__ */ Cn.createElement(SpaceSwitcher, { + }, /* @__PURE__ */ Cn.createElement(SpaceSwitcher, { plugin: props2.plugin - }) : /* @__PURE__ */ Cn.createElement(SpaceSwitcher, { + }), !platformIsMobile() && /* @__PURE__ */ Cn.createElement(MainMenu, { plugin: props2.plugin - }), syncState == 1 && /* @__PURE__ */ Cn.createElement("div", { - className: "mk-sync-status" - }, /* @__PURE__ */ Cn.createElement("div", { - className: `mk-icon-xsmall`, - dangerouslySetInnerHTML: { - __html: uiIconSet["mk-ui-sync"] - } - }), "Waiting for Spaces to Sync..."), viewForState(activeView2, activeViewSpace2)); + }), /* @__PURE__ */ Cn.createElement(FileExplorerComponent, { + plugin: props2.plugin + })); }; -// src/components/Spaces/FileTreeView.tsx +// src/components/Navigator/FileTreeView.tsx var FILE_TREE_VIEW_TYPE = "mk-file-view"; var VIEW_DISPLAY_TEXT = "Spaces"; var ICON = "layout-grid"; -var FileTreeView = class extends import_obsidian55.ItemView { +var FileTreeView = class extends import_obsidian56.ItemView { constructor(leaf, plugin) { super(leaf); this.navigation = false; this.plugin = plugin; } revealInFolder(file) { - if (file instanceof import_obsidian55.TFolder) { + if (file instanceof import_obsidian56.TFolder) { this.plugin.app.workspace.activeLeaf.setViewState({ - type: CONTEXT_VIEW_TYPE, - state: { contextPath: file.path } + type: SPACE_VIEW_TYPE, + state: { path: file.path } }); this.plugin.app.workspace.requestSaveLayout(); } else { - let evt = new CustomEvent(eventTypes.revealFile, { + const evt = new CustomEvent(eventTypes.revealFile, { detail: { file } }); window.dispatchEvent(evt); @@ -53608,9 +63188,9 @@ var FileTreeView = class extends import_obsidian55.ItemView { return ICON; } async onClose() { - let leafs = this.app.workspace.getLeavesOfType(FILE_TREE_VIEW_TYPE); + const leafs = this.app.workspace.getLeavesOfType(FILE_TREE_VIEW_TYPE); if (leafs.length == 0) { - let leaf = this.app.workspace.getLeftLeaf(false); + const leaf = this.app.workspace.getLeftLeaf(false); await leaf.setViewState({ type: FILE_TREE_VIEW_TYPE }); } this.destroy(); @@ -53629,10 +63209,9 @@ var FileTreeView = class extends import_obsidian55.ItemView { this.root.render( /* @__PURE__ */ Cn.createElement("div", { className: "mk-sidebar" - }, /* @__PURE__ */ Cn.createElement(Recoil_index_2, null, !platformIsMobile() && !this.plugin.settings.spacesCompactMode ? /* @__PURE__ */ Cn.createElement(MainMenu, { - plugin: this.plugin, - compactMode: false - }) : null, /* @__PURE__ */ Cn.createElement(MainList, { + }, /* @__PURE__ */ Cn.createElement(SidebarProvider, { + plugin: this.plugin + }, /* @__PURE__ */ Cn.createElement(MainList, { plugin: this.plugin }))) ); @@ -53640,7 +63219,7 @@ var FileTreeView = class extends import_obsidian55.ItemView { }; // src/settings/settings.ts -var import_obsidian56 = require("obsidian"); +var import_obsidian57 = require("obsidian"); var DEFAULT_SETTINGS = { defaultInitialization: false, filePreviewOnHover: false, @@ -53651,6 +63230,7 @@ var DEFAULT_SETTINGS = { mobileMakeBar: true, inlineStyler: true, makerMode: true, + spacesMDBInHidden: true, inlineStylerColors: false, editorFlow: true, internalLinkClickFlow: true, @@ -53658,14 +63238,12 @@ var DEFAULT_SETTINGS = { saveAllContextToFrontmatter: true, editorFlowStyle: "seamless", autoOpenFileContext: false, - activeView: "root", + activeView: "/", hideFrontmatter: true, activeSpace: "", - spacesCompactMode: false, defaultDateFormat: "MMM dd yyyy", spacesEnabled: true, spacesPerformance: false, - collapsedTags: [], enableFolderNote: true, folderIndentationLines: true, revealActiveFile: false, @@ -53673,22 +63251,19 @@ var DEFAULT_SETTINGS = { spaceRowHeight: 29, spacesDisablePatch: false, folderNoteInsideFolder: true, - folderNoteDefaultView: true, sidebarTabs: true, showRibbon: true, deleteFileOption: "trash", - expandedFolders: {}, expandedSpaces: ["/"], expandFolderOnClick: true, - openFolders: [], - fileIcons: [], cachedSpaces: [], menuTriggerChar: "/", inlineStickerMenu: true, emojiTriggerChar: ":", folderContextFile: "context", - tagContextFolder: "Context", - hiddenFiles: ["Context"], + folderFrameFile: "frames", + spacesFolder: "Spaces", + hiddenFiles: [], lineNumbers: false, hiddenExtensions: [".mdb"], newFileLocation: "root", @@ -53700,22 +63275,26 @@ var DEFAULT_SETTINGS = { inlineContextSectionsExpanded: true, dataviewInlineContext: false, inlineContextNameLayout: "vertical", - spacesSyncLastUpdated: "Context/spacesLastSync.log", - spacesSyncTimeoutSeconds: 10, - spacesAutoBackup: true, - spacesAutoBackupInterval: 10, - spacesAutoBackupLast: 0, + waypoints: [], + rootSpaces: [], spacesUseAlias: false, - precreateVaultSpace: false, fmKeyAlias: "aliases", fmKeyBanner: "banner", fmKeyColor: "color", fmKeySticker: "sticker", + fmKeyContexts: "_contexts", + fmKeySort: "_sort", + fmKeyFilter: "_filters", + fmKeyLinks: "_links", openSpacesOnLaunch: true, indexSVG: false, - readableLineWidth: true + quickFrames: [], + readableLineWidth: true, + autoAddContextsToSubtags: true, + autoMigration08: false, + releaseNotesPrompt: 0.8 }; -var MakeMDPluginSettingsTab = class extends import_obsidian56.PluginSettingTab { +var MakeMDPluginSettingsTab = class extends import_obsidian57.PluginSettingTab { constructor(app2, plugin) { super(app2, plugin); this.plugin = plugin; @@ -53727,7 +63306,7 @@ var MakeMDPluginSettingsTab = class extends import_obsidian56.PluginSettingTab { const { containerEl } = this; containerEl.empty(); containerEl.createEl("h1", { text: i18n_default.settings.sectionSidebar }); - new import_obsidian56.Setting(containerEl).setName(i18n_default.settings.spaces.name).setDesc(i18n_default.settings.spaces.desc).addToggle( + new import_obsidian57.Setting(containerEl).setName(i18n_default.settings.spaces.name).setDesc(i18n_default.settings.spaces.desc).addToggle( (toggle) => toggle.setValue(this.plugin.settings.spacesEnabled).onChange((value) => { this.plugin.settings.spacesEnabled = value; this.plugin.saveSettings(); @@ -53742,145 +63321,98 @@ var MakeMDPluginSettingsTab = class extends import_obsidian56.PluginSettingTab { if (this.plugin.settings.spacesEnabled) { containerEl.createEl("h3", { text: i18n_default.settings.sectionAppearance }); const spaceAppearances = containerEl.createEl("div"); - new import_obsidian56.Setting(spaceAppearances).setName(i18n_default.settings.sidebarTabs.name).setDesc(i18n_default.settings.sidebarTabs.desc).addToggle( + new import_obsidian57.Setting(spaceAppearances).setName(i18n_default.settings.sidebarTabs.name).setDesc(i18n_default.settings.sidebarTabs.desc).addToggle( (toggle) => toggle.setValue(this.plugin.settings.sidebarTabs).onChange((value) => { this.plugin.settings.sidebarTabs = value; this.plugin.saveSettings(); document.body.classList.toggle("mk-hide-tabs", !value); }) ); - new import_obsidian56.Setting(spaceAppearances).setName(i18n_default.settings.hideRibbon.name).setDesc(i18n_default.settings.hideRibbon.desc).addToggle( + new import_obsidian57.Setting(spaceAppearances).setName(i18n_default.settings.hideRibbon.name).setDesc(i18n_default.settings.hideRibbon.desc).addToggle( (toggle) => toggle.setValue(this.plugin.settings.showRibbon).onChange((value) => { this.plugin.settings.showRibbon = value; this.plugin.saveSettings(); document.body.classList.toggle("mk-hide-ribbon", !value); }) ); - new import_obsidian56.Setting(spaceAppearances).setName(i18n_default.settings.compactMode.name).setDesc(i18n_default.settings.compactMode.desc).addToggle( - (toggle) => toggle.setValue(this.plugin.settings.spacesCompactMode).onChange((value) => { - this.plugin.settings.spacesCompactMode = value; - this.plugin.detachFileTreeLeafs(); - this.plugin.saveSettings(); - }) - ); - new import_obsidian56.Setting(spaceAppearances).setName(i18n_default.settings.folderIndentationLines.name).setDesc(i18n_default.settings.folderIndentationLines.desc).addToggle( + new import_obsidian57.Setting(spaceAppearances).setName(i18n_default.settings.folderIndentationLines.name).setDesc(i18n_default.settings.folderIndentationLines.desc).addToggle( (toggle) => toggle.setValue(this.plugin.settings.folderIndentationLines).onChange((value) => { this.plugin.settings.folderIndentationLines = value; this.plugin.saveSettings(); document.body.classList.toggle("mk-folder-lines", value); }) ); - new import_obsidian56.Setting(spaceAppearances).setName(i18n_default.settings.spacesStickers.name).setDesc(i18n_default.settings.spacesStickers.desc).addToggle( + new import_obsidian57.Setting(spaceAppearances).setName(i18n_default.settings.spacesStickers.name).setDesc(i18n_default.settings.spacesStickers.desc).addToggle( (toggle) => toggle.setValue(this.plugin.settings.spacesStickers).onChange((value) => { this.plugin.settings.spacesStickers = value; this.plugin.saveSettings(); this.refreshView(); }) ); - new import_obsidian56.Setting(spaceAppearances).setName(i18n_default.settings.spacesAlias.name).setDesc(i18n_default.settings.spacesAlias.desc).addToggle( + new import_obsidian57.Setting(spaceAppearances).setName(i18n_default.settings.spacesAlias.name).setDesc(i18n_default.settings.spacesAlias.desc).addToggle( (toggle) => toggle.setValue(this.plugin.settings.spacesUseAlias).onChange((value) => { this.plugin.settings.spacesUseAlias = value; this.plugin.saveSettings(); this.refreshView(); }) ); - new import_obsidian56.Setting(spaceAppearances).setName(i18n_default.settings.readableLineWidth.name).setDesc(i18n_default.settings.readableLineWidth.desc).addToggle( + new import_obsidian57.Setting(spaceAppearances).setName(i18n_default.settings.readableLineWidth.name).setDesc(i18n_default.settings.readableLineWidth.desc).addToggle( (toggle) => toggle.setValue(this.plugin.settings.readableLineWidth).onChange((value) => { this.plugin.settings.readableLineWidth = value; this.plugin.saveSettings(); }) ); - new import_obsidian56.Setting(spaceAppearances).setName(i18n_default.settings.openSpacesOnLaunch.name).setDesc(i18n_default.settings.openSpacesOnLaunch.desc).addToggle( + new import_obsidian57.Setting(spaceAppearances).setName(i18n_default.settings.openSpacesOnLaunch.name).setDesc(i18n_default.settings.openSpacesOnLaunch.desc).addToggle( (toggle) => toggle.setValue(this.plugin.settings.openSpacesOnLaunch).onChange((value) => { this.plugin.settings.openSpacesOnLaunch = value; this.plugin.saveSettings(); }) ); - new import_obsidian56.Setting(spaceAppearances).setName(i18n_default.settings.spaceRowHeight.name).setDesc(i18n_default.settings.spaceRowHeight.desc).addText((text2) => { + new import_obsidian57.Setting(spaceAppearances).setName(i18n_default.settings.spaceRowHeight.name).setDesc(i18n_default.settings.spaceRowHeight.desc).addText((text2) => { text2.setValue(this.plugin.settings.spaceRowHeight.toString()).onChange(async (value) => { text2.setValue(parseInt(value).toString()); this.plugin.settings.spaceRowHeight = parseInt(value); await this.plugin.saveSettings(); }); }); - containerEl.createEl("h3", { text: "Folder Note" }); - new import_obsidian56.Setting(containerEl).setName(i18n_default.settings.folderNote.name).setDesc(i18n_default.settings.folderNote.desc).addToggle( - (toggle) => toggle.setValue(this.plugin.settings.enableFolderNote).onChange((value) => { - this.plugin.settings.enableFolderNote = value; - this.plugin.saveSettings(); - }) - ); - new import_obsidian56.Setting(containerEl).setName(i18n_default.settings.folderNoteLocation.name).setDesc(i18n_default.settings.folderNoteLocation.desc).addToggle( - (toggle) => toggle.setValue(this.plugin.settings.folderNoteInsideFolder).onChange((value) => { - this.plugin.settings.folderNoteInsideFolder = value; - this.plugin.saveSettings(); - }) - ); - new import_obsidian56.Setting(containerEl).setName(i18n_default.settings.folderViewDefault.name).setDesc(i18n_default.settings.folderViewDefault.desc).addToggle( - (toggle) => toggle.setValue(this.plugin.settings.folderNoteDefaultView).onChange((value) => { - this.plugin.settings.folderNoteDefaultView = value; - this.plugin.saveSettings(); - }) - ); - containerEl.createEl("h3", { text: "Sync and Backup" }); - new import_obsidian56.Setting(containerEl).setName(i18n_default.settings.syncTimeout.name).setDesc(i18n_default.settings.syncTimeout.desc).addText((text2) => { - text2.setValue(this.plugin.settings.spacesSyncTimeoutSeconds.toString()).onChange(async (value) => { - text2.setValue(parseInt(value).toString()); - this.plugin.settings.spacesSyncTimeoutSeconds = parseInt(value); - await this.plugin.saveSettings(); - }); - }); - new import_obsidian56.Setting(containerEl).setName(i18n_default.settings.spaceAutoBackup.name).setDesc(i18n_default.settings.spaceAutoBackup.desc).addToggle( - (toggle) => toggle.setValue(this.plugin.settings.spacesAutoBackup).onChange((value) => { - this.plugin.settings.spacesAutoBackup = value; - this.plugin.saveSettings(); - }) - ); - new import_obsidian56.Setting(containerEl).setName(i18n_default.settings.spaceAutoBackupInterval.name).setDesc(i18n_default.settings.spaceAutoBackupInterval.desc).addText((text2) => { - text2.setValue(this.plugin.settings.spacesAutoBackupInterval.toString()).onChange(async (value) => { - text2.setValue(parseInt(value).toString()); - this.plugin.settings.spacesAutoBackupInterval = parseInt(value); - await this.plugin.saveSettings(); - }); - }); containerEl.createEl("h3", { text: "Advanced" }); - new import_obsidian56.Setting(containerEl).setName(i18n_default.settings.expandFolder.name).setDesc(i18n_default.settings.expandFolder.desc).addToggle( + new import_obsidian57.Setting(containerEl).setName(i18n_default.settings.expandFolder.name).setDesc(i18n_default.settings.expandFolder.desc).addToggle( (toggle) => toggle.setValue(this.plugin.settings.expandFolderOnClick).onChange((value) => { this.plugin.settings.expandFolderOnClick = value; this.plugin.saveSettings(); }) ); - new import_obsidian56.Setting(containerEl).setName(i18n_default.settings.hoverPreview.name).setDesc(i18n_default.settings.hoverPreview.desc).addToggle( + new import_obsidian57.Setting(containerEl).setName(i18n_default.settings.hoverPreview.name).setDesc(i18n_default.settings.hoverPreview.desc).addToggle( (toggle) => toggle.setValue(this.plugin.settings.filePreviewOnHover).onChange((value) => { this.plugin.settings.filePreviewOnHover = value; this.plugin.saveSettings(); }) ); - new import_obsidian56.Setting(containerEl).setName(i18n_default.settings.activeFile.name).setDesc(i18n_default.settings.activeFile.desc).addToggle( + new import_obsidian57.Setting(containerEl).setName(i18n_default.settings.activeFile.name).setDesc(i18n_default.settings.activeFile.desc).addToggle( (toggle) => toggle.setValue(this.plugin.settings.revealActiveFile).onChange((value) => { this.plugin.settings.revealActiveFile = value; this.plugin.saveSettings(); }) ); - new import_obsidian56.Setting(containerEl).setName(i18n_default.settings.spacesFileExplorerDual.name).setDesc(i18n_default.settings.spacesFileExplorerDual.desc).addToggle( + new import_obsidian57.Setting(containerEl).setName(i18n_default.settings.spacesFileExplorerDual.name).setDesc(i18n_default.settings.spacesFileExplorerDual.desc).addToggle( (toggle) => toggle.setValue(this.plugin.settings.spacesDisablePatch).onChange((value) => { this.plugin.settings.spacesDisablePatch = value; this.plugin.saveSettings(); }) ); - new import_obsidian56.Setting(containerEl).setName(i18n_default.settings.spacesPerformance.name).setDesc(i18n_default.settings.spacesPerformance.desc).addToggle( + new import_obsidian57.Setting(containerEl).setName(i18n_default.settings.spacesPerformance.name).setDesc(i18n_default.settings.spacesPerformance.desc).addToggle( (toggle) => toggle.setValue(this.plugin.settings.spacesPerformance).onChange((value) => { this.plugin.settings.spacesPerformance = value; this.plugin.saveSettings(); }) ); - new import_obsidian56.Setting(containerEl).setName(i18n_default.settings.indexSVG.name).setDesc(i18n_default.settings.indexSVG.desc).addToggle( + new import_obsidian57.Setting(containerEl).setName(i18n_default.settings.indexSVG.name).setDesc(i18n_default.settings.indexSVG.desc).addToggle( (toggle) => toggle.setValue(this.plugin.settings.indexSVG).onChange((value) => { this.plugin.settings.indexSVG = value; this.plugin.saveSettings(); }) ); - new import_obsidian56.Setting(containerEl).setName(i18n_default.settings.spacesDeleteOption.name).setDesc(i18n_default.settings.spacesDeleteOption.desc).addDropdown((dropdown) => { + new import_obsidian57.Setting(containerEl).setName(i18n_default.settings.spacesDeleteOption.name).setDesc(i18n_default.settings.spacesDeleteOption.desc).addDropdown((dropdown) => { dropdown.addOption( "permanent", i18n_default.settings.spacesDeleteOptions.permanant @@ -53898,7 +63430,7 @@ var MakeMDPluginSettingsTab = class extends import_obsidian56.PluginSettingTab { }); } containerEl.createEl("h1", { text: "Context" }); - new import_obsidian56.Setting(containerEl).setName(i18n_default.settings.contexts.name).setDesc(i18n_default.settings.contexts.desc).addToggle( + new import_obsidian57.Setting(containerEl).setName(i18n_default.settings.contexts.name).setDesc(i18n_default.settings.contexts.desc).addToggle( (toggle) => toggle.setValue(this.plugin.settings.contextEnabled).onChange((value) => { this.plugin.settings.contextEnabled = value; this.plugin.saveSettings(); @@ -53906,27 +63438,27 @@ var MakeMDPluginSettingsTab = class extends import_obsidian56.PluginSettingTab { }) ); containerEl.createEl("h3", { text: i18n_default.settings.sectionAppearance }); - new import_obsidian56.Setting(containerEl).setName(i18n_default.settings.defaultDateFormat.name).setDesc(i18n_default.settings.defaultDateFormat.desc).addText((text2) => { + new import_obsidian57.Setting(containerEl).setName(i18n_default.settings.defaultDateFormat.name).setDesc(i18n_default.settings.defaultDateFormat.desc).addText((text2) => { text2.setValue(this.plugin.settings.defaultDateFormat).onChange(async (value) => { this.plugin.settings.defaultDateFormat = value; await this.plugin.saveSettings(); }); }); containerEl.createEl("h3", { text: i18n_default.settings.sectionAdvanced }); - new import_obsidian56.Setting(containerEl).setName(i18n_default.settings.openFileContext.name).setDesc(i18n_default.settings.openFileContext.desc).addToggle( + new import_obsidian57.Setting(containerEl).setName(i18n_default.settings.openFileContext.name).setDesc(i18n_default.settings.openFileContext.desc).addToggle( (toggle) => toggle.setValue(this.plugin.settings.autoOpenFileContext).onChange((value) => { this.plugin.settings.autoOpenFileContext = value; this.plugin.saveSettings(); }) ); - new import_obsidian56.Setting(containerEl).setName(i18n_default.settings.syncContextToFrontmatter.name).setDesc(i18n_default.settings.syncContextToFrontmatter.desc).addToggle( + new import_obsidian57.Setting(containerEl).setName(i18n_default.settings.syncContextToFrontmatter.name).setDesc(i18n_default.settings.syncContextToFrontmatter.desc).addToggle( (toggle) => toggle.setValue(this.plugin.settings.saveAllContextToFrontmatter).onChange((value) => { this.plugin.settings.saveAllContextToFrontmatter = value; this.plugin.saveSettings(); }) ); containerEl.createEl("h1", { text: "Blink" }); - new import_obsidian56.Setting(containerEl).setName(i18n_default.settings.blink.name).setDesc(i18n_default.settings.blink.desc).addToggle( + new import_obsidian57.Setting(containerEl).setName(i18n_default.settings.blink.name).setDesc(i18n_default.settings.blink.desc).addToggle( (toggle) => toggle.setValue(this.plugin.settings.blinkEnabled).onChange(async (value) => { this.plugin.settings.blinkEnabled = value; await this.plugin.saveSettings(); @@ -53934,7 +63466,7 @@ var MakeMDPluginSettingsTab = class extends import_obsidian56.PluginSettingTab { }) ); containerEl.createEl("h1", { text: i18n_default.settings.sectionFlow }); - new import_obsidian56.Setting(containerEl).setName(i18n_default.settings.editorMakerMode.name).setDesc(i18n_default.settings.editorMakerMode.desc).addToggle( + new import_obsidian57.Setting(containerEl).setName(i18n_default.settings.editorMakerMode.name).setDesc(i18n_default.settings.editorMakerMode.desc).addToggle( (toggle) => toggle.setValue(this.plugin.settings.makerMode).onChange((value) => { this.plugin.settings.makerMode = value; this.plugin.saveSettings(); @@ -53943,27 +63475,27 @@ var MakeMDPluginSettingsTab = class extends import_obsidian56.PluginSettingTab { ); if (this.plugin.settings.makerMode) { containerEl.createEl("h3", { text: "Inline Context" }); - new import_obsidian56.Setting(containerEl).setName(i18n_default.settings.inlineContextExplorer.name).setDesc(i18n_default.settings.inlineContextExplorer.desc).addToggle( + new import_obsidian57.Setting(containerEl).setName(i18n_default.settings.inlineContextExplorer.name).setDesc(i18n_default.settings.inlineContextExplorer.desc).addToggle( (toggle) => toggle.setValue(this.plugin.settings.inlineContext).onChange((value) => { this.plugin.settings.inlineContext = value; this.plugin.saveSettings(); this.plugin.reloadExtensions(false); }) ); - new import_obsidian56.Setting(containerEl).setName(i18n_default.settings.lineNumbers.name).setDesc(i18n_default.settings.lineNumbers.desc).addToggle( + new import_obsidian57.Setting(containerEl).setName(i18n_default.settings.lineNumbers.name).setDesc(i18n_default.settings.lineNumbers.desc).addToggle( (toggle) => toggle.setValue(this.plugin.settings.lineNumbers).onChange(async (value) => { this.plugin.settings.lineNumbers = value; await this.plugin.saveSettings(); this.plugin.reloadExtensions(false); }) ); - new import_obsidian56.Setting(containerEl).setName(i18n_default.settings.inlineContextExpanded.name).setDesc(i18n_default.settings.inlineContextExpanded.desc).addToggle( + new import_obsidian57.Setting(containerEl).setName(i18n_default.settings.inlineContextExpanded.name).setDesc(i18n_default.settings.inlineContextExpanded.desc).addToggle( (toggle) => toggle.setValue(this.plugin.settings.inlineContextSectionsExpanded).onChange((value) => { this.plugin.settings.inlineContextSectionsExpanded = value; this.plugin.saveSettings(); }) ); - new import_obsidian56.Setting(containerEl).setName(i18n_default.settings.inlineContextHorizontal.name).setDesc(i18n_default.settings.inlineContextHorizontal.desc).addDropdown((dropdown) => { + new import_obsidian57.Setting(containerEl).setName(i18n_default.settings.inlineContextHorizontal.name).setDesc(i18n_default.settings.inlineContextHorizontal.desc).addDropdown((dropdown) => { dropdown.addOption("vertical", i18n_default.settings.layoutVertical); dropdown.addOption("horizontal", i18n_default.settings.layoutHorizontal); dropdown.setValue(this.plugin.settings.inlineContextNameLayout); @@ -53972,20 +63504,20 @@ var MakeMDPluginSettingsTab = class extends import_obsidian56.PluginSettingTab { this.plugin.saveSettings(); }); }); - new import_obsidian56.Setting(containerEl).setName(i18n_default.settings.hideFrontmatter.name).setDesc(i18n_default.settings.hideFrontmatter.desc).addToggle( + new import_obsidian57.Setting(containerEl).setName(i18n_default.settings.hideFrontmatter.name).setDesc(i18n_default.settings.hideFrontmatter.desc).addToggle( (toggle) => toggle.setValue(this.plugin.settings.hideFrontmatter).onChange(async (value) => { this.plugin.settings.hideFrontmatter = value; await this.plugin.saveSettings(); this.plugin.reloadExtensions(false); }) ); - new import_obsidian56.Setting(containerEl).setName(i18n_default.settings.dataviewInlineContext.name).setDesc(i18n_default.settings.dataviewInlineContext.desc).addToggle( + new import_obsidian57.Setting(containerEl).setName(i18n_default.settings.dataviewInlineContext.name).setDesc(i18n_default.settings.dataviewInlineContext.desc).addToggle( (toggle) => toggle.setValue(this.plugin.settings.dataviewInlineContext).onChange((value) => { this.plugin.settings.dataviewInlineContext = value; this.plugin.saveSettings(); }) ); - new import_obsidian56.Setting(containerEl).setName(i18n_default.settings.inlineBacklinks.name).setDesc(i18n_default.settings.inlineBacklinks.desc).addToggle( + new import_obsidian57.Setting(containerEl).setName(i18n_default.settings.inlineBacklinks.name).setDesc(i18n_default.settings.inlineBacklinks.desc).addToggle( (toggle) => toggle.setValue(this.plugin.settings.inlineBacklinks).onChange(async (value) => { this.plugin.settings.inlineBacklinks = value; await this.plugin.saveSettings(); @@ -53993,21 +63525,21 @@ var MakeMDPluginSettingsTab = class extends import_obsidian56.PluginSettingTab { }) ); containerEl.createEl("h3", { text: "Flow Block" }); - new import_obsidian56.Setting(containerEl).setName(i18n_default.settings.editorFlowReplace.name).setDesc(i18n_default.settings.editorFlowReplace.desc).addToggle( + new import_obsidian57.Setting(containerEl).setName(i18n_default.settings.editorFlowReplace.name).setDesc(i18n_default.settings.editorFlowReplace.desc).addToggle( (toggle) => toggle.setValue(this.plugin.settings.editorFlow).onChange((value) => { this.plugin.settings.editorFlow = value; this.plugin.saveSettings(); this.refreshView(); }) ); - new import_obsidian56.Setting(containerEl).setName(i18n_default.settings.internalLinkFlowEditor.name).setDesc(i18n_default.settings.internalLinkFlowEditor.desc).addToggle( + new import_obsidian57.Setting(containerEl).setName(i18n_default.settings.internalLinkFlowEditor.name).setDesc(i18n_default.settings.internalLinkFlowEditor.desc).addToggle( (toggle) => toggle.setValue(this.plugin.settings.internalLinkClickFlow).onChange(async (value) => { this.plugin.settings.internalLinkClickFlow = value; await this.plugin.saveSettings(); this.plugin.reloadExtensions(false); }) ); - new import_obsidian56.Setting(containerEl).setName(i18n_default.settings.editorFlowStyle.name).setDesc(i18n_default.settings.editorFlowStyle.desc).addDropdown((dropdown) => { + new import_obsidian57.Setting(containerEl).setName(i18n_default.settings.editorFlowStyle.name).setDesc(i18n_default.settings.editorFlowStyle.desc).addDropdown((dropdown) => { dropdown.addOption("classic", i18n_default.settings.editorFlowStyle.classic); dropdown.addOption("seamless", i18n_default.settings.editorFlowStyle.seamless); dropdown.addOption("minimal", i18n_default.settings.editorFlowStyle.minimal); @@ -54025,14 +63557,14 @@ var MakeMDPluginSettingsTab = class extends import_obsidian56.PluginSettingTab { }); }); containerEl.createEl("h3", { text: "Flow Menu" }); - new import_obsidian56.Setting(containerEl).setName(i18n_default.settings.editorMakeMenu.name).setDesc(i18n_default.settings.editorMakeMenu.desc).addToggle( + new import_obsidian57.Setting(containerEl).setName(i18n_default.settings.editorMakeMenu.name).setDesc(i18n_default.settings.editorMakeMenu.desc).addToggle( (toggle) => toggle.setValue(this.plugin.settings.flowMenuEnabled).onChange(async (value) => { this.plugin.settings.flowMenuEnabled = value; await this.plugin.saveSettings(); this.plugin.reloadExtensions(false); }) ); - new import_obsidian56.Setting(containerEl).setName(i18n_default.settings.makeChar.name).setDesc(i18n_default.settings.makeChar.desc).addText((text2) => { + new import_obsidian57.Setting(containerEl).setName(i18n_default.settings.makeChar.name).setDesc(i18n_default.settings.makeChar.desc).addText((text2) => { text2.setValue(this.plugin.settings.menuTriggerChar).onChange(async (value) => { if (value.length < 1) { text2.setValue(this.plugin.settings.menuTriggerChar); @@ -54047,7 +63579,7 @@ var MakeMDPluginSettingsTab = class extends import_obsidian56.PluginSettingTab { await this.plugin.saveSettings(); }); }); - new import_obsidian56.Setting(containerEl).setName(i18n_default.settings.editorMakePlacholder.name).setDesc(i18n_default.settings.editorMakePlacholder.desc).addToggle( + new import_obsidian57.Setting(containerEl).setName(i18n_default.settings.editorMakePlacholder.name).setDesc(i18n_default.settings.editorMakePlacholder.desc).addToggle( (toggle) => toggle.setValue(this.plugin.settings.makeMenuPlaceholder).onChange(async (value) => { this.plugin.settings.makeMenuPlaceholder = value; await this.plugin.saveSettings(); @@ -54055,28 +63587,28 @@ var MakeMDPluginSettingsTab = class extends import_obsidian56.PluginSettingTab { }) ); containerEl.createEl("h3", { text: "Flow Styler" }); - new import_obsidian56.Setting(containerEl).setName(i18n_default.settings.inlineStyler.name).setDesc(i18n_default.settings.inlineStyler.desc).addToggle( + new import_obsidian57.Setting(containerEl).setName(i18n_default.settings.inlineStyler.name).setDesc(i18n_default.settings.inlineStyler.desc).addToggle( (toggle) => toggle.setValue(this.plugin.settings.inlineStyler).onChange(async (value) => { this.plugin.settings.inlineStyler = value; await this.plugin.saveSettings(); this.plugin.reloadExtensions(false); }) ); - new import_obsidian56.Setting(containerEl).setName(i18n_default.settings.inlineStickerMenu.name).setDesc(i18n_default.settings.inlineStickerMenu.desc).addToggle( + new import_obsidian57.Setting(containerEl).setName(i18n_default.settings.inlineStickerMenu.name).setDesc(i18n_default.settings.inlineStickerMenu.desc).addToggle( (toggle) => toggle.setValue(this.plugin.settings.inlineStickerMenu).onChange(async (value) => { this.plugin.settings.inlineStickerMenu = value; await this.plugin.saveSettings(); this.plugin.reloadExtensions(false); }) ); - new import_obsidian56.Setting(containerEl).setName(i18n_default.settings.inlineStylerColor.name).setDesc(i18n_default.settings.inlineStylerColor.desc).addToggle( + new import_obsidian57.Setting(containerEl).setName(i18n_default.settings.inlineStylerColor.name).setDesc(i18n_default.settings.inlineStylerColor.desc).addToggle( (toggle) => toggle.setValue(this.plugin.settings.inlineStylerColors).onChange((value) => { this.plugin.settings.inlineStylerColors = value; this.plugin.saveSettings(); this.refreshView(); }) ); - new import_obsidian56.Setting(containerEl).setName(i18n_default.settings.mobileMakeBar.name).setDesc(i18n_default.settings.mobileMakeBar.desc).addToggle( + new import_obsidian57.Setting(containerEl).setName(i18n_default.settings.mobileMakeBar.name).setDesc(i18n_default.settings.mobileMakeBar.desc).addToggle( (toggle) => toggle.setValue(this.plugin.settings.mobileMakeBar).onChange((value) => { this.plugin.settings.mobileMakeBar = value; this.plugin.saveSettings(); @@ -54088,15 +63620,15 @@ var MakeMDPluginSettingsTab = class extends import_obsidian56.PluginSettingTab { }; // src/components/Blink/Blink.tsx -var import_obsidian57 = require("obsidian"); +var import_obsidian58 = require("obsidian"); // src/components/Blink/BlinkComponent.tsx var BlinkComponent = Cn.forwardRef( - (props2, ref) => { + (props2, ref2) => { const [previewPath, setPreviewPath] = h2(null); const [allItems, setAllItems] = h2([]); - const defaultOptions3 = F2( - () => app.workspace.getLastOpenFiles().filter((f4) => getAbstractFileAtPath(app, f4)).map((f4) => ({ + const defaultOptions4 = F2( + () => props2.plugin.app.workspace.getLastOpenFiles().filter((f4) => getAbstractFileAtPath(props2.plugin, f4)).map((f4) => ({ description: f4, value: f4, name: filePathToString(f4) @@ -54109,8 +63641,7 @@ var BlinkComponent = Cn.forwardRef( name: f4 })); const allNotes = getAllAbstractFilesInVault( - props2.plugin, - app + props2.plugin ).map((f4) => ({ name: fileNameToString(f4.name), description: f4.path, @@ -54119,7 +63650,7 @@ var BlinkComponent = Cn.forwardRef( setAllItems([...allNotes, ...allTags]); }, []); const loadPreview = (path) => { - if (previewPath != path && getAbstractFileAtPath(app, path)) { + if (previewPath != path && getAbstractFileAtPath(props2.plugin, path)) { setPreviewPath(path); } }; @@ -54129,16 +63660,17 @@ var BlinkComponent = Cn.forwardRef( const selectItem = (item, modifiers) => { if (!item) return; - openPath(props2.plugin, pathByString(item), modifiers); + openPath(props2.plugin, uriByString(props2.plugin, item), modifiers); }; const optionProps = { multi: false, editable: true, + plugin: props2.plugin, onHover: hoverItem, value: [], options: allItems, - defaultOptions: defaultOptions3, - saveOptions: (_9, items, modifiers) => { + defaultOptions: defaultOptions4, + saveOptions: (_12, items, modifiers) => { selectItem(items[0], modifiers); }, placeholder: i18n_default.labels.blinkPlaceholder, @@ -54146,7 +63678,8 @@ var BlinkComponent = Cn.forwardRef( showAll: true }; return /* @__PURE__ */ Cn.createElement(Cn.Fragment, null, /* @__PURE__ */ Cn.createElement(selectMenu_default, { - ref, + ref: ref2, + plugin: props2.plugin, ...optionProps, hide: props2.hide, previewComponent: previewPath && /* @__PURE__ */ Cn.createElement("div", { @@ -54163,7 +63696,7 @@ BlinkComponent.displayName = "BlinkComponent"; var BlinkComponent_default = BlinkComponent; // src/components/Blink/Blink.tsx -var Blink = class extends import_obsidian57.Modal { +var Blink = class extends import_obsidian58.Modal { constructor(app2, plugin) { super(app2); this.ref = Cn.createRef(); @@ -54195,190 +63728,12 @@ var Blink = class extends import_obsidian57.Modal { } }; -// src/components/ContextView/MDBFileViewer.tsx -var import_obsidian58 = require("obsidian"); -var MDB_FILE_VIEWER_TYPE = "make-mdb-viewer"; -var MDBFileViewer = class extends import_obsidian58.FileView { - constructor(leaf, plugin) { - super(leaf); - this.navigation = true; - this.plugin = plugin; - } - getViewType() { - return MDB_FILE_VIEWER_TYPE; - } - getDisplayText() { - var _a2; - return (_a2 = this.file) == null ? void 0 : _a2.name; - } - async onClose() { - this.destroy(); - } - destroy() { - if (this.root) - this.root.unmount(); - } - async onOpen() { - this.destroy(); - } - async setState(state, result) { - this.file = getAbstractFileAtPath(app, state.file); - this.constructInlineContext(); - await super.setState(state, result); - this.leaf.tabHeaderInnerTitleEl.innerText = this.file.name; - this.leaf.view.titleEl = this.file.name; - const headerEl = this.leaf.view.headerEl; - if (headerEl) { - headerEl.querySelector(".view-header-title").innerText = this.file.name; - } - return; - } - getState() { - let state = super.getState(); - state.file = this.file.path; - return state; - } - constructInlineContext() { - const context = mdbContextByDBPath(this.plugin, this.file.path); - this.destroy(); - this.root = createRoot(this.contentEl); - this.root.render( - /* @__PURE__ */ Cn.createElement("div", { - className: "mk-folder-view" - }, /* @__PURE__ */ Cn.createElement(ContextViewComponent, { - context, - plugin: this.plugin - })) - ); - } -}; - -// src/components/FileContextView/FileContextView.tsx +// src/components/Explorer/Explorer.tsx var import_obsidian59 = require("obsidian"); - -// src/components/FileContextView/Backlinks.tsx -var BacklinkItem = (props2) => { - const file = F2( - () => getAbstractFileAtPath(app, props2.path), - [props2.path] - ); - const [block, setBlock] = h2([null, null]); - const refreshBlock = (path) => { - var _a2, _b2; - const fCache = app.metadataCache.getCache(path); - const link = [...(_a2 = fCache.links) != null ? _a2 : [], ...(_b2 = fCache.embeds) != null ? _b2 : []].find( - (f4) => props2.source.includes(f4.displayText) - ); - if (link) { - const block2 = fCache.sections.find( - (f4) => f4.position.start.offset <= link.position.start.offset && f4.position.end.offset >= link.position.end.offset - ); - setBlock([ - Math.max(1, block2.position.start.line), - Math.max(block2.position.start.line + 1, block2.position.end.line + 1) - ]); - } else { - setBlock([null, null]); - } - }; - p2(() => { - refreshBlock(props2.path); - }, []); - p2(() => { - refreshBlock(props2.path); - }, [props2.path]); - const [collapsed, setCollapsed] = h2(false); - return /* @__PURE__ */ Cn.createElement(Cn.Fragment, null, /* @__PURE__ */ Cn.createElement("div", { - className: "mk-file-context-title" - }, /* @__PURE__ */ Cn.createElement("button", { - className: `mk-collapse mk-inline-button mk-icon-xsmall ${collapsed ? "mk-collapsed" : ""}`, - onClick: (e4) => { - setCollapsed(!collapsed); - e4.stopPropagation(); - }, - dangerouslySetInnerHTML: { - __html: uiIconSet["mk-ui-collapse"] - } - }), /* @__PURE__ */ Cn.createElement("div", { - onClick: (e4) => { - openAFile(file, props2.plugin, false); - e4.stopPropagation(); - } - }, fileNameToString(file.name))), !collapsed ? /* @__PURE__ */ Cn.createElement("div", { - className: "mk-file-context-backlink" - }, /* @__PURE__ */ Cn.createElement(FlowView, { - plugin: props2.plugin, - load: true, - path: props2.path, - from: block[0], - to: block[1] - })) : /* @__PURE__ */ Cn.createElement(Cn.Fragment, null)); -}; -var Backlinks = (props2) => { - const [collapsed, setCollapsed] = h2( - !props2.plugin.settings.inlineBacklinksExpanded - ); - const [backlinks, setBacklinks] = h2([]); - p2(() => { - if (!props2.file) - return; - const bls = uniq([ - ...props2.plugin.index.linksMap.getInverse(props2.file.path), - ...Object.keys(app.metadataCache.resolvedLinks).filter( - (f4) => props2.file.path in app.metadataCache.resolvedLinks[f4] - ) - ]).filter((f4) => abstractFileAtPathExists(app, f4)); - setBacklinks(bls); - }, [props2.file]); - p2(() => { - props2.plugin.settings.inlineBacklinksExpanded = !collapsed; - props2.plugin.saveSettings(); - }, [collapsed]); - const toggleBacklinks = () => { - setCollapsed(!collapsed); - }; - p2(() => { - window.addEventListener(eventTypes.toggleBacklinks, toggleBacklinks); - return () => { - window.removeEventListener(eventTypes.toggleBacklinks, toggleBacklinks); - }; - }, [collapsed]); - return backlinks.length > 0 && props2.file ? /* @__PURE__ */ Cn.createElement("div", { - className: "mk-file-context-component mk-note-footer" - }, /* @__PURE__ */ Cn.createElement("div", { - className: "mk-file-context-section" - }, /* @__PURE__ */ Cn.createElement("div", { - onClick: (e4) => { - setCollapsed(!collapsed); - e4.stopPropagation(); - }, - className: "mk-file-context-title" - }, /* @__PURE__ */ Cn.createElement("div", { - className: `mk-icon-xsmall`, - dangerouslySetInnerHTML: { - __html: uiIconSet["mk-ui-backlink"] - } - }), i18n_default.labels.backlinks, /* @__PURE__ */ Cn.createElement("button", { - className: `mk-collapse mk-inline-button mk-icon-xsmall ${collapsed ? "mk-collapsed" : ""}`, - dangerouslySetInnerHTML: { - __html: uiIconSet["mk-ui-collapse-sm"] - } - })), /* @__PURE__ */ Cn.createElement("div", null, !collapsed && backlinks.map((f4, i4) => { - var _a2; - return /* @__PURE__ */ Cn.createElement(BacklinkItem, { - path: f4, - key: i4, - plugin: props2.plugin, - source: (_a2 = props2.file) == null ? void 0 : _a2.path - }); - })))) : /* @__PURE__ */ Cn.createElement(Cn.Fragment, null); -}; - -// src/components/FileContextView/FileContextView.tsx var FILE_CONTEXT_VIEW_TYPE = "make-context-view"; var ICON2 = "component"; -var VIEW_DISPLAY_TEXT2 = "Context Explorer"; -var FileContextLeafView = class extends import_obsidian59.ItemView { +var VIEW_DISPLAY_TEXT2 = "Explorer"; +var ContextExplorerLeafView = class extends import_obsidian59.ItemView { constructor(leaf, plugin) { super(leaf); this.navigation = false; @@ -54410,7 +63765,7 @@ var FileContextLeafView = class extends import_obsidian59.ItemView { return; } getState() { - let state = super.getState(); + const state = super.getState(); return state; } constructFileContext() { @@ -54421,92 +63776,371 @@ var FileContextLeafView = class extends import_obsidian59.ItemView { })); } }; +var isLeafNode = (node) => { + if (node.type == "metadata" && (node.subType == "properties" || node.subType == "flow")) + return true; + return false; +}; +var childrenForNode = (plugin, node, index, depth) => { + var _a2, _b2; + let i4 = index; + const items = []; + if (node.type == "path") { + const isSpace = pathIsSpace(plugin, node.path); + const metadataTypes = []; + metadataTypes.push({ + type: "properties", + label: "Properties", + sticker: "ui//mk-ui-note" + }); + if (depth != 0) { + metadataTypes.push({ + type: "flow", + label: "Content", + sticker: "ui//mk-ui-note" + }); + } + metadataTypes.push( + ...[ + { type: "spaces", label: "Spaces", sticker: "ui//mk-ui-note" }, + { + type: "inlinks", + label: "Backlinks", + sticker: "lucide//links-coming-in" + }, + { + type: "outlinks", + label: "Outgoing Links", + sticker: "lucide//links-going-out" + } + ] + ); + items.push( + ...metadataTypes.map((f4, k5) => ({ + id: node.id + "/" + f4.type, + parentId: node.id, + type: "metadata", + subType: f4.type, + index: i4 + k5, + path: node.path, + label: f4.label, + sticker: f4.sticker, + value: f4.type, + depth, + parentPath: node.parentPath + })) + ); + } else if (node.type == "metadata") { + if (node.subType == "tables") { + items.push( + ...[ + ...((_b2 = (_a2 = plugin.index.contextsIndex.get(node.path)) == null ? void 0 : _a2.schemas) != null ? _b2 : []).filter( + (f4) => f4.name != "files" + ) + ].map((f4, k5) => ({ + id: node.id + "/" + f4.id, + parentId: node.id, + type: "schema", + path: node.path, + index: i4 + k5, + sticker: "", + label: f4.name, + value: f4.id, + depth, + parentPath: node.path + })) + ); + } + let paths = []; + if (node.subType == "inlinks") { + paths = [...plugin.index.linksMap.getInverse(node.path)]; + } else if (node.subType == "outlinks") { + paths = [...plugin.index.linksMap.get(node.path)]; + } + items.push( + ...paths.map((f4) => plugin.index.cacheForURI(uriByString(plugin, f4))).filter((f4) => f4).map((f4, k5) => ({ + id: node.id + "/" + node.value, + parentId: node.id, + type: "path", + path: f4.path, + index: i4 + k5, + sticker: f4.sticker, + label: f4.name, + value: f4.path, + depth, + parentPath: node.path + })) + ); + } + i4 += items.length; + return items; +}; +var flattenTree = (plugin, node, openNodes, depth, index) => { + const items = []; + let i4 = index; + const leafNode = isLeafNode(node); + if (!leafNode) { + const children = childrenForNode(plugin, node, i4, depth); + const newItems = []; + if (openNodes.some((f4) => f4 == node.id)) { + children.forEach((f4) => { + i4 = i4 + 1; + newItems.push(...flattenTree(plugin, f4, openNodes, depth + 1, i4)); + }); + } + if (node.type != "metadata" || children.length != 0) + items.push({ ...node, children: children.length, isLeafNode: leafNode }); + items.push(...newItems); + } else { + items.push({ ...node, isLeafNode: leafNode }); + } + return items; +}; var FileContextView = (props2) => { const [selectedPath, setSelectedPath] = h2(null); - const [selectedRow, setSelectedRow] = h2(null); - const selectedContext = F2(() => { - var _a2; - if (!selectedPath) - return null; - if (selectedPath.type == "folder" || selectedPath.type == "space" || selectedPath.type == "tag") { - return (_a2 = props2.plugin.index.contextsIndex.get(selectedPath.path)) == null ? void 0 : _a2.info; - } else { - return null; - } - }, [selectedPath]); - const file = F2(() => { - const afile = getAbstractFileAtPath(app, selectedPath == null ? void 0 : selectedPath.path); - return afile; - }, [selectedPath]); - const folderNoteFile = F2(() => { - if (file instanceof import_obsidian59.TFolder) { - const afile2 = getAbstractFileAtPath(app, file.path + ".md"); - return afile2; - } - return file; - }, [file]); - const changeSelectedFile = (evt) => { + const [selectedRoot, setSelectedRoot] = h2(null); + const [openNodes, setOpenNodes] = h2([]); + const [filters, setFilters] = h2([]); + const rootCache = F2( + () => selectedRoot ? props2.plugin.index.cacheForURI(selectedRoot) : null, + [selectedRoot] + ); + const flattenedTree = F2( + () => rootCache ? flattenTree( + props2.plugin, + { + id: rootCache.path, + parentId: null, + type: "path", + path: rootCache.path, + index: 0, + depth: 0, + sticker: rootCache.sticker, + label: rootCache.name, + value: rootCache.path + }, + openNodes, + 0, + 0 + ) : [], + [rootCache, openNodes] + ); + p2(() => { + rootCache && setOpenNodes([rootCache.path]); + }, [rootCache]); + const changeSelectedPath = (evt) => { const path = evt.detail.path; + setSelectedRoot(path); if (evt.detail.selection) { - setSelectedPath(pathByString(evt.detail.selection)); - } else { - setSelectedPath(path); + setSelectedPath(evt.detail.selection); } }; p2(() => { props2.plugin.activeFileChange(); }, []); p2(() => { - window.addEventListener(eventTypes.activePathChange, changeSelectedFile); + window.addEventListener(eventTypes.activePathChange, changeSelectedPath); return () => { window.removeEventListener( eventTypes.activePathChange, - changeSelectedFile + changeSelectedPath ); }; - }, [file]); + }, [rootCache]); return /* @__PURE__ */ Cn.createElement("div", { className: "mk-file-context" - }, file && /* @__PURE__ */ Cn.createElement(InlineFileContextView, { + }, rootCache ? /* @__PURE__ */ Cn.createElement(Cn.Fragment, null, flattenedTree.map((f4, i4) => /* @__PURE__ */ Cn.createElement("div", { + key: f4.id, + className: "mk-tree-wrapper", + style: { marginLeft: f4.depth * 8 } + }, !f4.isLeafNode ? /* @__PURE__ */ Cn.createElement("button", { + className: `mk-collapse mk-inline-button mk-icon-xsmall ${!openNodes.some((g4) => g4 == f4.id) ? "mk-collapsed" : ""}`, + dangerouslySetInnerHTML: { + __html: stickerFromString( + "ui//mk-ui-collapse", + props2.plugin + ) + }, + onClick: () => setOpenNodes( + (p3) => p3.some((g4) => g4 == f4.id) ? p3.filter((o3) => o3 != f4.id) : [...p3, f4.id] + ) + }) : /* @__PURE__ */ Cn.createElement("div", { + className: `mk-collapse mk-inline-button mk-icon-xsmall` + }), f4.type == "metadata" ? f4.subType == "flow" ? /* @__PURE__ */ Cn.createElement(ExplorerFlowRow, { + path: f4.path, + source: f4.parentPath, + plugin: props2.plugin + }) : f4.subType == "properties" ? /* @__PURE__ */ Cn.createElement(ExplorerContextRow, { plugin: props2.plugin, - file, - showHeader: true, - showBanner: false, - editable: true - }), selectedRow && /* @__PURE__ */ Cn.createElement(InlineFileContextView, { + node: f4 + }) : /* @__PURE__ */ Cn.createElement("div", { + className: "mk-file-context-row" + }, /* @__PURE__ */ Cn.createElement("div", { + className: "mk-file-context-field" + }, /* @__PURE__ */ Cn.createElement("div", { + className: "mk-file-context-field-icon", + dangerouslySetInnerHTML: { + __html: stickerFromString(f4.sticker, props2.plugin) + } + }), /* @__PURE__ */ Cn.createElement("div", { + className: "mk-file-context-field-key" + }, f4.label))) : /* @__PURE__ */ Cn.createElement("div", { + className: "mk-file-context-row" + }, /* @__PURE__ */ Cn.createElement("div", { + className: "mk-file-context-field" + }, /* @__PURE__ */ Cn.createElement("div", { + className: "mk-file-context-field-icon", + dangerouslySetInnerHTML: { + __html: stickerFromString(f4.sticker, props2.plugin) + } + }), /* @__PURE__ */ Cn.createElement("div", { + className: "mk-file-context-field-key" + }, f4.label)))))) : /* @__PURE__ */ Cn.createElement(Cn.Fragment, null)); +}; +var ExplorerFlowRow = (props2) => { + var _a2; + const path = F2(() => { + const spaceCache = props2.plugin.index.spacesIndex.get(props2.path); + if (spaceCache) + return spaceCache.space.defPath; + return props2.path; + }, [props2.path]); + const [collapsed, setCollapsed] = h2(true); + const [block, setBlock] = h2([null, null]); + const refreshBlock = (path2) => { + var _a3, _b2; + const fCache = props2.plugin.app.metadataCache.getCache(path2); + const link = [...(_a3 = fCache == null ? void 0 : fCache.links) != null ? _a3 : [], ...(_b2 = fCache == null ? void 0 : fCache.embeds) != null ? _b2 : []].find( + (f4) => props2.source && props2.source.includes(f4.displayText) + ); + if (link) { + const block2 = fCache.sections.find( + (f4) => f4.position.start.offset <= link.position.start.offset && f4.position.end.offset >= link.position.end.offset + ); + if (!block2) + setBlock([null, null]); + setBlock([block2.position.start, block2.position.end]); + } else { + if (fCache.frontmatterPosition) { + setBlock([ + fCache.frontmatterPosition.end, + fCache.sections.last().position.end + ]); + } else { + setBlock([ + fCache.sections.first().position.start, + fCache.sections.last().position.end + ]); + } + } + }; + p2(() => { + refreshBlock(path); + }, []); + p2(() => { + refreshBlock(path); + }, [path]); + return /* @__PURE__ */ Cn.createElement(Cn.Fragment, null, /* @__PURE__ */ Cn.createElement("div", { + className: "mk-file-context-backlink" + }, /* @__PURE__ */ Cn.createElement(FlowView, { plugin: props2.plugin, - file: selectedRow, - showHeader: true, - showBanner: false, - editable: true - }), file && /* @__PURE__ */ Cn.createElement(Backlinks, { + load: true, + leaf: props2.leaf, + path, + from: (_a2 = block[0]) == null ? void 0 : _a2.line, + to: block[1] ? block[1].line + 1 : null, + classname: "mk-file-context-flow" + }))); +}; +var ExplorerContextRow = (props2) => { + var _a2, _b2; + const { node, plugin } = props2; + const [spaceCache, setSpaceCache] = h2( + plugin.index.spacesIndex.get(node.path) + ); + const spaces = [...plugin.index.spacesMap.get(node.path)]; + return /* @__PURE__ */ Cn.createElement(ContextPropertiesView, { plugin: props2.plugin, - file: folderNoteFile - })); + spacePaths: spaces, + path: node.path, + metadataFilePath: (_b2 = (_a2 = spaceCache == null ? void 0 : spaceCache.space) == null ? void 0 : _a2.defPath) != null ? _b2 : node.path, + showMetadata: true, + hiddenFields: [...FMMetadataKeys(plugin), ...FMSpaceKeys(plugin)], + editable: true + }); }; -// src/components/ui/modals/loadSpaceBackupModal.tsx +// src/components/SpaceView/Contexts/MDBFileViewer.tsx var import_obsidian60 = require("obsidian"); -var LoadSpaceBackupModal = class extends import_obsidian60.FuzzySuggestModal { - constructor(plugin, files) { - super(app); +var MDB_FILE_VIEWER_TYPE = "make-mdb-viewer"; +var MDBFileViewer = class extends import_obsidian60.FileView { + constructor(leaf, plugin) { + super(leaf); + this.navigation = true; this.plugin = plugin; - this.files = files; } - getItemText(file) { - return file; + getViewType() { + return MDB_FILE_VIEWER_TYPE; } - getItems() { - return this.files; + getDisplayText() { + var _a2; + return (_a2 = this.file) == null ? void 0 : _a2.name; + } + async onClose() { + this.destroy(); } - onChooseItem(file, evt) { - this.plugin.index.loadSpaceDBFromBackup(file); + destroy() { + if (this.root) + this.root.unmount(); + } + async onOpen() { + this.destroy(); + } + async setState(state, result) { + this.file = getAbstractFileAtPath(this.plugin, state.file); + this.schema = state.schema; + this.constructInlineContext(state.file, state.schema); + await super.setState(state, result); + this.leaf.tabHeaderInnerTitleEl.innerText = this.file.name; + this.leaf.view.titleEl = this.file.name; + const headerEl = this.leaf.view.headerEl; + if (headerEl) { + headerEl.querySelector(".view-header-title").innerText = this.file.name; + } + return; + } + getState() { + const state = super.getState(); + state.file = this.file.path; + state.schema = this.schema; + return state; + } + constructInlineContext(path, schema) { + const space = spaceInfoByPath(this.plugin, getParentPathFromString(path)); + this.destroy(); + this.root = createRoot(this.contentEl); + if (space) + this.root.render( + /* @__PURE__ */ Cn.createElement(SpaceContextProvider, { + plugin: this.plugin, + space + }, /* @__PURE__ */ Cn.createElement(ContextMDBProvider, { + plugin: this.plugin, + schema + }, /* @__PURE__ */ Cn.createElement(FramesMDBProvider, { + plugin: this.plugin + }, /* @__PURE__ */ Cn.createElement(ContextEditorProvider, { + plugin: this.plugin + }, /* @__PURE__ */ Cn.createElement(ContextListView, { + plugin: this.plugin + }))))) + ); } }; // src/dispatch/spaces.ts var dispatchSpaceDatabaseFileChanged = (type, action, name, newName) => { - let evt = new CustomEvent(eventTypes.spacesChange, { + const evt = new CustomEvent(eventTypes.spacesChange, { detail: { type, action, @@ -54517,11 +64151,14 @@ var dispatchSpaceDatabaseFileChanged = (type, action, name, newName) => { window.dispatchEvent(evt); }; var onFileCreated = async (plugin, newPath, folder) => { - var _a2; - const parent = (_a2 = getAbstractFileAtPath(app, newPath).parent) == null ? void 0 : _a2.path; + const file = getAbstractFileAtPath(plugin, newPath); + const parent = file.parent; + if (!excludeFilePredicate(plugin)(file)) { + return; + } await plugin.index.saveSpacesDatabaseToDisk({ vault: { ...vaultSchema, rows: [...plugin.index.vaultDBCache, { path: newPath, - parent, + parent: parent == null ? void 0 : parent.path, created: Math.trunc(Date.now() / 1e3).toString(), folder: folder ? "true" : "false" }] } }); @@ -54529,26 +64166,21 @@ var onFileCreated = async (plugin, newPath, folder) => { }; var onFileDeleted = async (plugin, oldPath) => { const newVaultRows = plugin.index.vaultDBCache.filter((f4) => f4.path != oldPath); - const newSpaceItemsRows = plugin.index.spacesItemsDBCache.filter((f4) => f4.path != oldPath); - await plugin.index.saveSpacesDatabaseToDisk({ vault: { ...vaultSchema, rows: newVaultRows }, spaceItems: { ...spaceItemsSchema, rows: newSpaceItemsRows } }); + await plugin.index.saveSpacesDatabaseToDisk({ vault: { ...vaultSchema, rows: newVaultRows } }); plugin.index.deleteFile(oldPath); }; var onFileChanged = async (plugin, oldPath, newPath) => { - const newFolderPath = getFolderPathFromString(newPath); + const newFolderPath = getFolderPathFromString(plugin, newPath); const newVaultRows = plugin.index.vaultDBCache.map((f4) => f4.path == oldPath ? { ...f4, path: newPath, parent: newFolderPath } : f4); - const newSpaceItemsRows = plugin.index.spacesItemsDBCache.map((f4) => f4.path == oldPath ? { - ...f4, - path: newPath - } : f4); - await plugin.index.saveSpacesDatabaseToDisk({ vault: { ...vaultSchema, rows: newVaultRows }, spaceItems: { ...spaceItemsSchema, rows: newSpaceItemsRows } }); - plugin.index.renameFile(oldPath, newPath); + await plugin.index.saveSpacesDatabaseToDisk({ vault: { ...vaultSchema, rows: newVaultRows } }); + return plugin.index.renameFile(oldPath, newPath); }; var onFolderChanged = async (plugin, oldPath, newPath) => { - const newFolderPath = getFolderFromPath(app, newPath).parent.path; + const newFolderPath = getFolderFromPath(plugin, newPath).parent.path; const allChildren = retrieveAllRecursiveChildren(plugin.index.vaultDBCache, plugin.settings, oldPath); const newVaultRows = plugin.index.vaultDBCache.map((f4) => f4.path == oldPath ? { ...f4, @@ -54559,27 +64191,15 @@ var onFolderChanged = async (plugin, oldPath, newPath) => { path: f4.path.replace(oldPath, newPath), parent: f4.parent.replace(oldPath, newPath) } : f4); - const newSpaceItemsRows = plugin.index.spacesItemsDBCache.map((f4) => f4.path == oldPath ? { - ...f4, - path: newPath - } : f4.path.startsWith(oldPath) ? { - ...f4, - path: f4.path.replace(oldPath, newPath) - } : f4); - await plugin.index.saveSpacesDatabaseToDisk({ vault: { ...vaultSchema, rows: newVaultRows }, spaceItems: { ...spaceItemsSchema, rows: newSpaceItemsRows } }); - plugin.index.renameFile(oldPath, newPath); - if (plugin.settings.enableFolderNote && !plugin.settings.folderNoteInsideFolder) { - const file = getAbstractFileAtPath(app, oldPath + ".md"); - if (file) - renameFile(plugin, file, newPath + ".md"); - } + await plugin.index.saveSpacesDatabaseToDisk({ vault: { ...vaultSchema, rows: newVaultRows } }); + await plugin.index.renameFile(oldPath, newPath); + await folderRenamed(plugin, oldPath, newPath); allChildren.forEach((f4) => plugin.index.renameFile(f4.path, f4.path.replace(oldPath, newPath))); }; var onFolderDeleted = async (plugin, oldPath) => { const allChildren = retrieveAllRecursiveChildren(plugin.index.vaultDBCache, plugin.settings, oldPath); const newVaultRows = plugin.index.vaultDBCache.filter((f4) => f4.path != oldPath && !f4.parent.startsWith(oldPath)); - const newSpaceItemsRows = plugin.index.spacesItemsDBCache.filter((f4) => f4.path != oldPath && !f4.path.startsWith(oldPath)); - await plugin.index.saveSpacesDatabaseToDisk({ vault: { ...vaultSchema, rows: newVaultRows }, spaceItems: { ...spaceItemsSchema, rows: newSpaceItemsRows } }); + await plugin.index.saveSpacesDatabaseToDisk({ vault: { ...vaultSchema, rows: newVaultRows } }); allChildren.forEach((f4) => plugin.index.deleteFile(f4.path)); plugin.index.deleteFile(oldPath); }; @@ -54588,7 +64208,7 @@ var onFolderDeleted = async (plugin, oldPath) => { var import_obsidian_dataview = __toESM(require_lib()); // src/superstate/superstate.ts -var import_lodash10 = __toESM(require_lodash()); +var import_lodash13 = __toESM(require_lodash()); var import_obsidian62 = require("obsidian"); // src/types/indexMap.ts @@ -54598,7 +64218,7 @@ var _IndexMap = class { this.invMap = /* @__PURE__ */ new Map(); } get(key2) { - let result = this.map.get(key2); + const result = this.map.get(key2); if (result) { return new Set(result); } else { @@ -54614,15 +64234,15 @@ var _IndexMap = class { this.delete(key2); return this; } - let oldValues = this.map.get(key2); + const oldValues = this.map.get(key2); if (oldValues) { - for (let value of oldValues) { + for (const value of oldValues) { if (!values.has(key2)) (_a2 = this.invMap.get(value)) == null ? void 0 : _a2.delete(key2); } } this.map.set(key2, values); - for (let value of values) { + for (const value of values) { if (!this.invMap.has(value)) this.invMap.set(value, /* @__PURE__ */ new Set([key2])); else @@ -54636,15 +64256,15 @@ var _IndexMap = class { this.deleteInverse(key2); return this; } - let oldValues = this.invMap.get(key2); + const oldValues = this.invMap.get(key2); if (oldValues) { - for (let value of oldValues) { + for (const value of oldValues) { if (!values.has(key2)) (_a2 = this.map.get(value)) == null ? void 0 : _a2.delete(key2); } } this.invMap.set(key2, values); - for (let value of values) { + for (const value of values) { if (!this.map.has(value)) this.map.set(value, /* @__PURE__ */ new Set([key2])); else @@ -54654,28 +64274,28 @@ var _IndexMap = class { } delete(key2) { var _a2; - let oldValues = this.map.get(key2); + const oldValues = this.map.get(key2); if (!oldValues) return false; this.map.delete(key2); - for (let value of oldValues) { + for (const value of oldValues) { (_a2 = this.invMap.get(value)) == null ? void 0 : _a2.delete(key2); } return true; } deleteInverse(key2) { var _a2; - let oldValues = this.invMap.get(key2); + const oldValues = this.invMap.get(key2); if (!oldValues) return false; this.invMap.delete(key2); - for (let value of oldValues) { + for (const value of oldValues) { (_a2 = this.map.get(value)) == null ? void 0 : _a2.delete(key2); } return true; } rename(oldKey, newKey) { - let oldValues = this.map.get(oldKey); + const oldValues = this.map.get(oldKey); if (!oldValues) return false; this.delete(oldKey); @@ -54683,7 +64303,7 @@ var _IndexMap = class { return true; } renameInverse(oldKey, newKey) { - let oldValues = this.invMap.get(oldKey); + const oldValues = this.invMap.get(oldKey); if (!oldValues) return false; this.deleteInverse(oldKey); @@ -54699,13 +64319,16 @@ var IndexMap = _IndexMap; IndexMap.EMPTY_SET = Object.freeze(/* @__PURE__ */ new Set()); // src/utils/foldernote.ts -var isFolderNote = (settings, aFile) => { +var isFolderNote = (plugin, aFile) => { if (!aFile) return false; - const afolder = tFileToAFile(getAbstractFileAtPath(app, folderPathFromFolderNoteFile(settings, aFile))); + const folderPath = folderPathFromFolderNoteFile(plugin.settings, aFile); + if (!folderPath) + return false; + const afolder = tFileToAFile(getAbstractFileAtPath(plugin, folderPath)); if (!afolder) return false; - if (folderNotePathFromAFile(settings, afolder) == aFile.path) + if (folderNotePathFromAFile(plugin.settings, afolder) == aFile.path) return true; return false; }; @@ -54721,43 +64344,86 @@ var serializeFileCache = (fileCache) => { }; var stringifyJob = (job) => `${job.type}:${job.path}`; +// src/superstate/api.ts +var API = class { + constructor(plugin) { + this.buttonCommand = (action, actionValue) => { + if (action == "$commands") { + this.runObsidianCommand(actionValue); + } + if (action == "$links") { + this.openLink(actionValue, false); + } + }; + this.runObsidianCommand = (command) => { + if (this.plugin.app.commands.commands[command].callback) { + this.plugin.app.commands.commands[command].callback(); + } else if (this.plugin.app.commands.commands[command].checkCallback) { + this.plugin.app.commands.commands[command].checkCallback(false); + } + }; + this.formatDate = (date, format2) => { + return formatDate(this.plugin, date, format2); + }; + this.now = () => { + return new Date(); + }; + this.plugin = plugin; + } + openLink(path, target) { + openPath(this.plugin, uriByString(this.plugin, path), target); + } + getLocalFile(path) { + return this.plugin.app.vault.getResourcePath(getAbstractFileAtPath(this.plugin, path)); + } + getContext(path, table) { + var _a2; + return (_a2 = this.plugin.index.contextsIndex.get(path)) == null ? void 0 : _a2.tables[table]; + } + setContextValue(path, file, field, value) { + const space = this.plugin.index.spacesIndex.get(path); + if (space) + updateValueInContext(this.plugin, file, field, value, space.space); + } +}; + // src/superstate/localCache/localCache.ts var import_localforage = __toESM(require_localforage()); var LocalStorageCache = class { - constructor(appId, version) { + constructor(appId, version2) { this.appId = appId; - this.version = version; + this.version = version2; this.persister = import_localforage.default.createInstance({ - name: "superstate/" + appId, + name: "superstate/" + appId + this.version, driver: [import_localforage.default.INDEXEDDB], description: "Superstate Index" }); } async recreate() { - await import_localforage.default.dropInstance({ name: "superstate/" + this.appId }); + await import_localforage.default.dropInstance({ name: "superstate/" + this.appId + this.version }); this.persister = import_localforage.default.createInstance({ - name: "superstate/" + this.appId, + name: "superstate/" + this.appId + this.version, driver: [import_localforage.default.INDEXEDDB], description: "Superstate Index" }); } async load(path, type) { return this.persister.getItem(this.keyForType(path, type)).then((raw) => { - let result = raw; + const result = raw; return result; }); } - async store(path, data, type) { - await this.persister.setItem(this.keyForType(path, type), data); + async store(path, data2, type) { + await this.persister.setItem(this.keyForType(path, type), data2); } async remove(path, type) { await this.persister.removeItem(this.keyForType(path, type)); } async synchronize(existing) { - let keys = new Set(await this.allFiles()); - for (let exist of existing) + const keys = new Set(await this.allFiles()); + for (const exist of existing) keys.delete(exist); - for (let key2 of keys) + for (const key2 of keys) await this.persister.removeItem(this.keyForType(key2, "file")); return keys; } @@ -54765,7 +64431,7 @@ var LocalStorageCache = class { return this.persister.keys(); } async allFiles() { - let keys = await this.allKeys(); + const keys = await this.allKeys(); return keys.filter((k5) => k5.startsWith("file:")).map((k5) => k5.substring(5)); } keyForType(path, type) { @@ -54787,7 +64453,7 @@ function inlineWorker(scriptText) { // src/superstate/workers/entry.worker.ts function Worker2() { - return inlineWorker('var G_=Object.create;var Ji=Object.defineProperty,q_=Object.defineProperties,H_=Object.getOwnPropertyDescriptor,$_=Object.getOwnPropertyDescriptors,K_=Object.getOwnPropertyNames,Wo=Object.getOwnPropertySymbols,z_=Object.getPrototypeOf,Uo=Object.prototype.hasOwnProperty,k_=Object.prototype.propertyIsEnumerable;var Bo=(i,h,m)=>h in i?Ji(i,h,{enumerable:!0,configurable:!0,writable:!0,value:m}):i[h]=m,Pt=(i,h)=>{for(var m in h||(h={}))Uo.call(h,m)&&Bo(i,m,h[m]);if(Wo)for(var m of Wo(h))k_.call(h,m)&&Bo(i,m,h[m]);return i},Wt=(i,h)=>q_(i,$_(h));var Y_=(i,h)=>()=>(h||i((h={exports:{}}).exports,h),h.exports);var Z_=(i,h,m,A)=>{if(h&&typeof h=="object"||typeof h=="function")for(let y of K_(h))!Uo.call(i,y)&&y!==m&&Ji(i,y,{get:()=>h[y],enumerable:!(A=H_(h,y))||A.enumerable});return i};var J_=(i,h,m)=>(m=i!=null?G_(z_(i)):{},Z_(h||!i||!i.__esModule?Ji(m,"default",{value:i,enumerable:!0}):m,i));var No=Y_((jt,Se)=>{(function(){var i,h="4.17.21",m=200,A="Unsupported core-js use. Try https://npms.io/search?q=ponyfill.",y="Expected a function",E="Invalid `variable` option passed into `_.template`",V="__lodash_hash_undefined__",rn=500,un="__lodash_placeholder__",H=1,An=2,hn=4,pn=1,Sn=2,Y=1,K=2,X=4,gn=8,En=16,Q=32,jn=64,On=128,nt=256,qn=512,Fr=30,Fe="...",Bt=800,Ct=16,Ut=1,Ir=2,Ie=3,Jn=1/0,Hn=9007199254740991,Me=17976931348623157e292,Tt=0/0,Cn=4294967295,Re=Cn-1,Le=Cn>>>1,sn=[["ary",On],["bind",Y],["bindKey",K],["curry",gn],["curryRight",En],["flip",qn],["partial",Q],["partialRight",jn],["rearg",nt]],an="[object Arguments]",fn="[object Array]",pt="[object AsyncFunction]",te="[object Boolean]",ee="[object Date]",es="[object DOMException]",Ee="[object Error]",Oe="[object Function]",ru="[object GeneratorFunction]",$n="[object Map]",re="[object Number]",rs="[object Null]",tt="[object Object]",iu="[object Promise]",is="[object Proxy]",ie="[object RegExp]",Kn="[object Set]",ue="[object String]",be="[object Symbol]",us="[object Undefined]",fe="[object WeakMap]",fs="[object WeakSet]",oe="[object ArrayBuffer]",Nt="[object DataView]",Mr="[object Float32Array]",Rr="[object Float64Array]",Lr="[object Int8Array]",Er="[object Int16Array]",Or="[object Int32Array]",br="[object Uint8Array]",Dr="[object Uint8ClampedArray]",Pr="[object Uint16Array]",Wr="[object Uint32Array]",os=/\\b__p \\+= \'\';/g,ss=/\\b(__p \\+=) \'\' \\+/g,as=/(__e\\(.*?\\)|\\b__t\\)) \\+\\n\'\';/g,uu=/&(?:amp|lt|gt|quot|#39);/g,fu=/[&<>"\']/g,ls=RegExp(uu.source),cs=RegExp(fu.source),hs=/<%-([\\s\\S]+?)%>/g,ps=/<%([\\s\\S]+?)%>/g,ou=/<%=([\\s\\S]+?)%>/g,gs=/\\.|\\[(?:[^[\\]]*|(["\'])(?:(?!\\1)[^\\\\]|\\\\.)*?\\1)\\]/,_s=/^\\w*$/,ds=/[^.[\\]]+|\\[(?:(-?\\d+(?:\\.\\d+)?)|(["\'])((?:(?!\\2)[^\\\\]|\\\\.)*?)\\2)\\]|(?=(?:\\.|\\[\\])(?:\\.|\\[\\]|$))/g,Br=/[\\\\^$.*+?()[\\]{}|]/g,vs=RegExp(Br.source),Ur=/^\\s+/,xs=/\\s/,ms=/\\{(?:\\n\\/\\* \\[wrapped with .+\\] \\*\\/)?\\n?/,ys=/\\{\\n\\/\\* \\[wrapped with (.+)\\] \\*/,ws=/,? & /,As=/[^\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\x7f]+/g,Ss=/[()=,{}\\[\\]\\/\\s]/,Cs=/\\\\(\\\\)?/g,Ts=/\\$\\{([^\\\\}]*(?:\\\\.[^\\\\}]*)*)\\}/g,su=/\\w*$/,Fs=/^[-+]0x[0-9a-f]+$/i,Is=/^0b[01]+$/i,Ms=/^\\[object .+?Constructor\\]$/,Rs=/^0o[0-7]+$/i,Ls=/^(?:0|[1-9]\\d*)$/,Es=/[\\xc0-\\xd6\\xd8-\\xf6\\xf8-\\xff\\u0100-\\u017f]/g,De=/($^)/,Os=/[\'\\n\\r\\u2028\\u2029\\\\]/g,Pe="\\\\ud800-\\\\udfff",bs="\\\\u0300-\\\\u036f",Ds="\\\\ufe20-\\\\ufe2f",Ps="\\\\u20d0-\\\\u20ff",au=bs+Ds+Ps,lu="\\\\u2700-\\\\u27bf",cu="a-z\\\\xdf-\\\\xf6\\\\xf8-\\\\xff",Ws="\\\\xac\\\\xb1\\\\xd7\\\\xf7",Bs="\\\\x00-\\\\x2f\\\\x3a-\\\\x40\\\\x5b-\\\\x60\\\\x7b-\\\\xbf",Us="\\\\u2000-\\\\u206f",Ns=" \\\\t\\\\x0b\\\\f\\\\xa0\\\\ufeff\\\\n\\\\r\\\\u2028\\\\u2029\\\\u1680\\\\u180e\\\\u2000\\\\u2001\\\\u2002\\\\u2003\\\\u2004\\\\u2005\\\\u2006\\\\u2007\\\\u2008\\\\u2009\\\\u200a\\\\u202f\\\\u205f\\\\u3000",hu="A-Z\\\\xc0-\\\\xd6\\\\xd8-\\\\xde",pu="\\\\ufe0e\\\\ufe0f",gu=Ws+Bs+Us+Ns,Nr="[\'\\u2019]",Gs="["+Pe+"]",_u="["+gu+"]",We="["+au+"]",du="\\\\d+",qs="["+lu+"]",vu="["+cu+"]",xu="[^"+Pe+gu+du+lu+cu+hu+"]",Gr="\\\\ud83c[\\\\udffb-\\\\udfff]",Hs="(?:"+We+"|"+Gr+")",mu="[^"+Pe+"]",qr="(?:\\\\ud83c[\\\\udde6-\\\\uddff]){2}",Hr="[\\\\ud800-\\\\udbff][\\\\udc00-\\\\udfff]",Gt="["+hu+"]",yu="\\\\u200d",wu="(?:"+vu+"|"+xu+")",$s="(?:"+Gt+"|"+xu+")",Au="(?:"+Nr+"(?:d|ll|m|re|s|t|ve))?",Su="(?:"+Nr+"(?:D|LL|M|RE|S|T|VE))?",Cu=Hs+"?",Tu="["+pu+"]?",Ks="(?:"+yu+"(?:"+[mu,qr,Hr].join("|")+")"+Tu+Cu+")*",zs="\\\\d*(?:1st|2nd|3rd|(?![123])\\\\dth)(?=\\\\b|[A-Z_])",ks="\\\\d*(?:1ST|2ND|3RD|(?![123])\\\\dTH)(?=\\\\b|[a-z_])",Fu=Tu+Cu+Ks,Ys="(?:"+[qs,qr,Hr].join("|")+")"+Fu,Zs="(?:"+[mu+We+"?",We,qr,Hr,Gs].join("|")+")",Js=RegExp(Nr,"g"),Xs=RegExp(We,"g"),$r=RegExp(Gr+"(?="+Gr+")|"+Zs+Fu,"g"),Qs=RegExp([Gt+"?"+vu+"+"+Au+"(?="+[_u,Gt,"$"].join("|")+")",$s+"+"+Su+"(?="+[_u,Gt+wu,"$"].join("|")+")",Gt+"?"+wu+"+"+Au,Gt+"+"+Su,ks,zs,du,Ys].join("|"),"g"),Vs=RegExp("["+yu+Pe+au+pu+"]"),js=/[a-z][A-Z]|[A-Z]{2}[a-z]|[0-9][a-zA-Z]|[a-zA-Z][0-9]|[^a-zA-Z0-9 ]/,na=["Array","Buffer","DataView","Date","Error","Float32Array","Float64Array","Function","Int8Array","Int16Array","Int32Array","Map","Math","Object","Promise","RegExp","Set","String","Symbol","TypeError","Uint8Array","Uint8ClampedArray","Uint16Array","Uint32Array","WeakMap","_","clearTimeout","isFinite","parseInt","setTimeout"],ta=-1,q={};q[Mr]=q[Rr]=q[Lr]=q[Er]=q[Or]=q[br]=q[Dr]=q[Pr]=q[Wr]=!0,q[an]=q[fn]=q[oe]=q[te]=q[Nt]=q[ee]=q[Ee]=q[Oe]=q[$n]=q[re]=q[tt]=q[ie]=q[Kn]=q[ue]=q[fe]=!1;var G={};G[an]=G[fn]=G[oe]=G[Nt]=G[te]=G[ee]=G[Mr]=G[Rr]=G[Lr]=G[Er]=G[Or]=G[$n]=G[re]=G[tt]=G[ie]=G[Kn]=G[ue]=G[be]=G[br]=G[Dr]=G[Pr]=G[Wr]=!0,G[Ee]=G[Oe]=G[fe]=!1;var ea={\\u00C0:"A",\\u00C1:"A",\\u00C2:"A",\\u00C3:"A",\\u00C4:"A",\\u00C5:"A",\\u00E0:"a",\\u00E1:"a",\\u00E2:"a",\\u00E3:"a",\\u00E4:"a",\\u00E5:"a",\\u00C7:"C",\\u00E7:"c",\\u00D0:"D",\\u00F0:"d",\\u00C8:"E",\\u00C9:"E",\\u00CA:"E",\\u00CB:"E",\\u00E8:"e",\\u00E9:"e",\\u00EA:"e",\\u00EB:"e",\\u00CC:"I",\\u00CD:"I",\\u00CE:"I",\\u00CF:"I",\\u00EC:"i",\\u00ED:"i",\\u00EE:"i",\\u00EF:"i",\\u00D1:"N",\\u00F1:"n",\\u00D2:"O",\\u00D3:"O",\\u00D4:"O",\\u00D5:"O",\\u00D6:"O",\\u00D8:"O",\\u00F2:"o",\\u00F3:"o",\\u00F4:"o",\\u00F5:"o",\\u00F6:"o",\\u00F8:"o",\\u00D9:"U",\\u00DA:"U",\\u00DB:"U",\\u00DC:"U",\\u00F9:"u",\\u00FA:"u",\\u00FB:"u",\\u00FC:"u",\\u00DD:"Y",\\u00FD:"y",\\u00FF:"y",\\u00C6:"Ae",\\u00E6:"ae",\\u00DE:"Th",\\u00FE:"th",\\u00DF:"ss",\\u0100:"A",\\u0102:"A",\\u0104:"A",\\u0101:"a",\\u0103:"a",\\u0105:"a",\\u0106:"C",\\u0108:"C",\\u010A:"C",\\u010C:"C",\\u0107:"c",\\u0109:"c",\\u010B:"c",\\u010D:"c",\\u010E:"D",\\u0110:"D",\\u010F:"d",\\u0111:"d",\\u0112:"E",\\u0114:"E",\\u0116:"E",\\u0118:"E",\\u011A:"E",\\u0113:"e",\\u0115:"e",\\u0117:"e",\\u0119:"e",\\u011B:"e",\\u011C:"G",\\u011E:"G",\\u0120:"G",\\u0122:"G",\\u011D:"g",\\u011F:"g",\\u0121:"g",\\u0123:"g",\\u0124:"H",\\u0126:"H",\\u0125:"h",\\u0127:"h",\\u0128:"I",\\u012A:"I",\\u012C:"I",\\u012E:"I",\\u0130:"I",\\u0129:"i",\\u012B:"i",\\u012D:"i",\\u012F:"i",\\u0131:"i",\\u0134:"J",\\u0135:"j",\\u0136:"K",\\u0137:"k",\\u0138:"k",\\u0139:"L",\\u013B:"L",\\u013D:"L",\\u013F:"L",\\u0141:"L",\\u013A:"l",\\u013C:"l",\\u013E:"l",\\u0140:"l",\\u0142:"l",\\u0143:"N",\\u0145:"N",\\u0147:"N",\\u014A:"N",\\u0144:"n",\\u0146:"n",\\u0148:"n",\\u014B:"n",\\u014C:"O",\\u014E:"O",\\u0150:"O",\\u014D:"o",\\u014F:"o",\\u0151:"o",\\u0154:"R",\\u0156:"R",\\u0158:"R",\\u0155:"r",\\u0157:"r",\\u0159:"r",\\u015A:"S",\\u015C:"S",\\u015E:"S",\\u0160:"S",\\u015B:"s",\\u015D:"s",\\u015F:"s",\\u0161:"s",\\u0162:"T",\\u0164:"T",\\u0166:"T",\\u0163:"t",\\u0165:"t",\\u0167:"t",\\u0168:"U",\\u016A:"U",\\u016C:"U",\\u016E:"U",\\u0170:"U",\\u0172:"U",\\u0169:"u",\\u016B:"u",\\u016D:"u",\\u016F:"u",\\u0171:"u",\\u0173:"u",\\u0174:"W",\\u0175:"w",\\u0176:"Y",\\u0177:"y",\\u0178:"Y",\\u0179:"Z",\\u017B:"Z",\\u017D:"Z",\\u017A:"z",\\u017C:"z",\\u017E:"z",\\u0132:"IJ",\\u0133:"ij",\\u0152:"Oe",\\u0153:"oe",\\u0149:"\'n",\\u017F:"s"},ra={"&":"&","<":"<",">":">",\'"\':""","\'":"'"},ia={"&":"&","<":"<",">":">",""":\'"\',"'":"\'"},ua={"\\\\":"\\\\","\'":"\'","\\n":"n","\\r":"r","\\u2028":"u2028","\\u2029":"u2029"},fa=parseFloat,oa=parseInt,Iu=typeof global=="object"&&global&&global.Object===Object&&global,sa=typeof self=="object"&&self&&self.Object===Object&&self,tn=Iu||sa||Function("return this")(),Kr=typeof jt=="object"&&jt&&!jt.nodeType&&jt,Ft=Kr&&typeof Se=="object"&&Se&&!Se.nodeType&&Se,Mu=Ft&&Ft.exports===Kr,zr=Mu&&Iu.process,bn=function(){try{var l=Ft&&Ft.require&&Ft.require("util").types;return l||zr&&zr.binding&&zr.binding("util")}catch(g){}}(),Ru=bn&&bn.isArrayBuffer,Lu=bn&&bn.isDate,Eu=bn&&bn.isMap,Ou=bn&&bn.isRegExp,bu=bn&&bn.isSet,Du=bn&&bn.isTypedArray;function Tn(l,g,p){switch(p.length){case 0:return l.call(g);case 1:return l.call(g,p[0]);case 2:return l.call(g,p[0],p[1]);case 3:return l.call(g,p[0],p[1],p[2])}return l.apply(g,p)}function aa(l,g,p,w){for(var I=-1,W=l==null?0:l.length;++I-1}function kr(l,g,p){for(var w=-1,I=l==null?0:l.length;++w-1;);return p}function Hu(l,g){for(var p=l.length;p--&&qt(g,l[p],0)>-1;);return p}function xa(l,g){for(var p=l.length,w=0;p--;)l[p]===g&&++w;return w}var ma=Xr(ea),ya=Xr(ra);function wa(l){return"\\\\"+ua[l]}function Aa(l,g){return l==null?i:l[g]}function Ht(l){return Vs.test(l)}function Sa(l){return js.test(l)}function Ca(l){for(var g,p=[];!(g=l.next()).done;)p.push(g.value);return p}function ni(l){var g=-1,p=Array(l.size);return l.forEach(function(w,I){p[++g]=[I,w]}),p}function $u(l,g){return function(p){return l(g(p))}}function dt(l,g){for(var p=-1,w=l.length,I=0,W=[];++p-1}function cl(n,t){var e=this.__data__,r=nr(e,n);return r<0?(++this.size,e.push([n,t])):e[r][1]=t,this}et.prototype.clear=ol,et.prototype.delete=sl,et.prototype.get=al,et.prototype.has=ll,et.prototype.set=cl;function rt(n){var t=-1,e=n==null?0:n.length;for(this.clear();++t=t?n:t)),n}function Bn(n,t,e,r,u,o){var s,a=t&H,c=t&An,_=t&hn;if(e&&(s=u?e(n,r,u,o):e(n)),s!==i)return s;if(!z(n))return n;var d=M(n);if(d){if(s=_c(n),!a)return xn(n,s)}else{var v=cn(n),x=v==Oe||v==ru;if(St(n))return Ff(n,a);if(v==tt||v==an||x&&!u){if(s=c||x?{}:zf(n),!a)return c?ic(n,Il(s,n)):rc(n,tf(s,n))}else{if(!G[v])return u?n:{};s=dc(n,v,a)}}o||(o=new kn);var S=o.get(n);if(S)return S;o.set(n,s),wo(n)?n.forEach(function(F){s.add(Bn(F,t,e,F,n,o))}):mo(n)&&n.forEach(function(F,b){s.set(b,Bn(F,t,e,b,n,o))});var T=_?c?Fi:Ti:c?yn:en,L=d?i:T(n);return Dn(L||n,function(F,b){L&&(b=F,F=n[b]),ge(s,b,Bn(F,t,e,b,n,o))}),s}function Ml(n){var t=en(n);return function(e){return ef(e,n,t)}}function ef(n,t,e){var r=e.length;if(n==null)return!r;for(n=N(n);r--;){var u=e[r],o=t[u],s=n[u];if(s===i&&!(u in n)||!o(s))return!1}return!0}function rf(n,t,e){if(typeof n!="function")throw new Pn(y);return we(function(){n.apply(i,e)},t)}function _e(n,t,e,r){var u=-1,o=Be,s=!0,a=n.length,c=[],_=t.length;if(!a)return c;e&&(t=$(t,Fn(e))),r?(o=kr,s=!1):t.length>=m&&(o=se,s=!1,t=new Rt(t));n:for(;++uu?0:u+e),r=r===i||r>u?u:R(r),r<0&&(r+=u),r=e>r?0:So(r);e0&&e(a)?t>1?on(a,t-1,e,r,u):_t(u,a):r||(u[u.length]=a)}return u}var oi=Of(),of=Of(!0);function Xn(n,t){return n&&oi(n,t,en)}function si(n,t){return n&&of(n,t,en)}function er(n,t){return gt(t,function(e){return st(n[e])})}function Et(n,t){t=wt(t,n);for(var e=0,r=t.length;n!=null&&et}function El(n,t){return n!=null&&U.call(n,t)}function Ol(n,t){return n!=null&&t in N(n)}function bl(n,t,e){return n>=ln(t,e)&&n=120&&d.length>=120)?new Rt(s&&d):i}d=n[0];var v=-1,x=a[0];n:for(;++v-1;)a!==n&&Ye.call(a,c,1),Ye.call(n,c,1);return n}function xf(n,t){for(var e=n?t.length:0,r=e-1;e--;){var u=t[e];if(e==r||u!==o){var o=u;ot(u)?Ye.call(n,u,1):xi(n,u)}}return n}function _i(n,t){return n+Xe(Qu()*(t-n+1))}function kl(n,t,e,r){for(var u=-1,o=nn(Je((t-n)/(e||1)),0),s=p(o);o--;)s[r?o:++u]=n,n+=e;return s}function di(n,t){var e="";if(!n||t<1||t>Hn)return e;do t%2&&(e+=n),t=Xe(t/2),t&&(n+=n);while(t);return e}function O(n,t){return bi(Zf(n,t,wn),n+"")}function Yl(n){return nf(Vt(n))}function Zl(n,t){var e=Vt(n);return pr(e,Lt(t,0,e.length))}function xe(n,t,e,r){if(!z(n))return n;t=wt(t,n);for(var u=-1,o=t.length,s=o-1,a=n;a!=null&&++uu?0:u+t),e=e>u?u:e,e<0&&(e+=u),u=t>e?0:e-t>>>0,t>>>=0;for(var o=p(u);++r>>1,s=n[o];s!==null&&!Mn(s)&&(e?s<=t:s=m){var _=t?null:sc(n);if(_)return Ne(_);s=!1,u=se,c=new Rt}else c=t?[]:a;n:for(;++r=r?n:Un(n,t,e)}var Tf=Na||function(n){return tn.clearTimeout(n)};function Ff(n,t){if(t)return n.slice();var e=n.length,r=ku?ku(e):new n.constructor(e);return n.copy(r),r}function Ai(n){var t=new n.constructor(n.byteLength);return new ze(t).set(new ze(n)),t}function jl(n,t){var e=t?Ai(n.buffer):n.buffer;return new n.constructor(e,n.byteOffset,n.byteLength)}function nc(n){var t=new n.constructor(n.source,su.exec(n));return t.lastIndex=n.lastIndex,t}function tc(n){return pe?N(pe.call(n)):{}}function If(n,t){var e=t?Ai(n.buffer):n.buffer;return new n.constructor(e,n.byteOffset,n.length)}function Mf(n,t){if(n!==t){var e=n!==i,r=n===null,u=n===n,o=Mn(n),s=t!==i,a=t===null,c=t===t,_=Mn(t);if(!a&&!_&&!o&&n>t||o&&s&&c&&!a&&!_||r&&s&&c||!e&&c||!u)return 1;if(!r&&!o&&!_&&n=a)return c;var _=e[r];return c*(_=="desc"?-1:1)}}return n.index-t.index}function Rf(n,t,e,r){for(var u=-1,o=n.length,s=e.length,a=-1,c=t.length,_=nn(o-s,0),d=p(c+_),v=!r;++a1?e[u-1]:i,s=u>2?e[2]:i;for(o=n.length>3&&typeof o=="function"?(u--,o):i,s&&dn(e[0],e[1],s)&&(o=u<3?i:o,u=1),t=N(t);++r-1?u[o?t[s]:s]:i}}function Pf(n){return ft(function(t){var e=t.length,r=e,u=Wn.prototype.thru;for(n&&t.reverse();r--;){var o=t[r];if(typeof o!="function")throw new Pn(y);if(u&&!s&&cr(o)=="wrapper")var s=new Wn([],!0)}for(r=s?r:e;++r1&&P.reverse(),d&&ca))return!1;var _=o.get(n),d=o.get(t);if(_&&d)return _==t&&d==n;var v=-1,x=!0,S=e&Sn?new Rt:i;for(o.set(n,t),o.set(t,n);++v1?"& ":"")+t[r],t=t.join(e>2?", ":" "),n.replace(ms,`{\n/* [wrapped with `+t+`] */\n`)}function xc(n){return M(n)||Dt(n)||!!(Ju&&n&&n[Ju])}function ot(n,t){var e=typeof n;return t=t==null?Hn:t,!!t&&(e=="number"||e!="symbol"&&Ls.test(n))&&n>-1&&n%1==0&&n0){if(++t>=Bt)return arguments[0]}else t=0;return n.apply(i,arguments)}}function pr(n,t){var e=-1,r=n.length,u=r-1;for(t=t===i?r:t;++e1?n[t-1]:i;return e=typeof e=="function"?(n.pop(),e):i,fo(n,e)});function oo(n){var t=f(n);return t.__chain__=!0,t}function Rh(n,t){return t(n),n}function gr(n,t){return t(n)}var Lh=ft(function(n){var t=n.length,e=t?n[0]:0,r=this.__wrapped__,u=function(o){return fi(o,n)};return t>1||this.__actions__.length||!(r instanceof D)||!ot(e)?this.thru(u):(r=r.slice(e,+e+(t?1:0)),r.__actions__.push({func:gr,args:[u],thisArg:i}),new Wn(r,this.__chain__).thru(function(o){return t&&!o.length&&o.push(i),o}))});function Eh(){return oo(this)}function Oh(){return new Wn(this.value(),this.__chain__)}function bh(){this.__values__===i&&(this.__values__=Ao(this.value()));var n=this.__index__>=this.__values__.length,t=n?i:this.__values__[this.__index__++];return{done:n,value:t}}function Dh(){return this}function Ph(n){for(var t,e=this;e instanceof je;){var r=no(e);r.__index__=0,r.__values__=i,t?u.__wrapped__=r:t=r;var u=r;e=e.__wrapped__}return u.__wrapped__=n,t}function Wh(){var n=this.__wrapped__;if(n instanceof D){var t=n;return this.__actions__.length&&(t=new D(this)),t=t.reverse(),t.__actions__.push({func:gr,args:[Di],thisArg:i}),new Wn(t,this.__chain__)}return this.thru(Di)}function Bh(){return Sf(this.__wrapped__,this.__actions__)}var Uh=fr(function(n,t,e){U.call(n,e)?++n[e]:it(n,e,1)});function Nh(n,t,e){var r=M(n)?Pu:Rl;return e&&dn(n,t,e)&&(t=i),r(n,C(t,3))}function Gh(n,t){var e=M(n)?gt:ff;return e(n,C(t,3))}var qh=Df(to),Hh=Df(eo);function $h(n,t){return on(_r(n,t),1)}function Kh(n,t){return on(_r(n,t),Jn)}function zh(n,t,e){return e=e===i?1:R(e),on(_r(n,t),e)}function so(n,t){var e=M(n)?Dn:mt;return e(n,C(t,3))}function ao(n,t){var e=M(n)?la:uf;return e(n,C(t,3))}var kh=fr(function(n,t,e){U.call(n,e)?n[e].push(t):it(n,e,[t])});function Yh(n,t,e,r){n=mn(n)?n:Vt(n),e=e&&!r?R(e):0;var u=n.length;return e<0&&(e=nn(u+e,0)),yr(n)?e<=u&&n.indexOf(t,e)>-1:!!u&&qt(n,t,e)>-1}var Zh=O(function(n,t,e){var r=-1,u=typeof t=="function",o=mn(n)?p(n.length):[];return mt(n,function(s){o[++r]=u?Tn(t,s,e):de(s,t,e)}),o}),Jh=fr(function(n,t,e){it(n,e,t)});function _r(n,t){var e=M(n)?$:hf;return e(n,C(t,3))}function Xh(n,t,e,r){return n==null?[]:(M(t)||(t=t==null?[]:[t]),e=r?i:e,M(e)||(e=e==null?[]:[e]),df(n,t,e))}var Qh=fr(function(n,t,e){n[e?0:1].push(t)},function(){return[[],[]]});function Vh(n,t,e){var r=M(n)?Yr:Nu,u=arguments.length<3;return r(n,C(t,4),e,u,mt)}function jh(n,t,e){var r=M(n)?ca:Nu,u=arguments.length<3;return r(n,C(t,4),e,u,uf)}function np(n,t){var e=M(n)?gt:ff;return e(n,xr(C(t,3)))}function tp(n){var t=M(n)?nf:Yl;return t(n)}function ep(n,t,e){(e?dn(n,t,e):t===i)?t=1:t=R(t);var r=M(n)?Cl:Zl;return r(n,t)}function rp(n){var t=M(n)?Tl:Xl;return t(n)}function ip(n){if(n==null)return 0;if(mn(n))return yr(n)?$t(n):n.length;var t=cn(n);return t==$n||t==Kn?n.size:hi(n).length}function up(n,t,e){var r=M(n)?Zr:Ql;return e&&dn(n,t,e)&&(t=i),r(n,C(t,3))}var fp=O(function(n,t){if(n==null)return[];var e=t.length;return e>1&&dn(n,t[0],t[1])?t=[]:e>2&&dn(t[0],t[1],t[2])&&(t=[t[0]]),df(n,on(t,1),[])}),dr=Ga||function(){return tn.Date.now()};function op(n,t){if(typeof t!="function")throw new Pn(y);return n=R(n),function(){if(--n<1)return t.apply(this,arguments)}}function lo(n,t,e){return t=e?i:t,t=n&&t==null?n.length:t,ut(n,On,i,i,i,i,t)}function co(n,t){var e;if(typeof t!="function")throw new Pn(y);return n=R(n),function(){return--n>0&&(e=t.apply(this,arguments)),n<=1&&(t=i),e}}var Wi=O(function(n,t,e){var r=Y;if(e.length){var u=dt(e,Xt(Wi));r|=Q}return ut(n,r,t,e,u)}),ho=O(function(n,t,e){var r=Y|K;if(e.length){var u=dt(e,Xt(ho));r|=Q}return ut(t,r,n,e,u)});function po(n,t,e){t=e?i:t;var r=ut(n,gn,i,i,i,i,i,t);return r.placeholder=po.placeholder,r}function go(n,t,e){t=e?i:t;var r=ut(n,En,i,i,i,i,i,t);return r.placeholder=go.placeholder,r}function _o(n,t,e){var r,u,o,s,a,c,_=0,d=!1,v=!1,x=!0;if(typeof n!="function")throw new Pn(y);t=Gn(t)||0,z(e)&&(d=!!e.leading,v="maxWait"in e,o=v?nn(Gn(e.maxWait)||0,t):o,x="trailing"in e?!!e.trailing:x);function S(J){var Zn=r,lt=u;return r=u=i,_=J,s=n.apply(lt,Zn),s}function T(J){return _=J,a=we(b,t),d?S(J):s}function L(J){var Zn=J-c,lt=J-_,Po=t-Zn;return v?ln(Po,o-lt):Po}function F(J){var Zn=J-c,lt=J-_;return c===i||Zn>=t||Zn<0||v&<>=o}function b(){var J=dr();if(F(J))return P(J);a=we(b,L(J))}function P(J){return a=i,x&&r?S(J):(r=u=i,s)}function Rn(){a!==i&&Tf(a),_=0,r=c=u=a=i}function vn(){return a===i?s:P(dr())}function Ln(){var J=dr(),Zn=F(J);if(r=arguments,u=this,c=J,Zn){if(a===i)return T(c);if(v)return Tf(a),a=we(b,t),S(c)}return a===i&&(a=we(b,t)),s}return Ln.cancel=Rn,Ln.flush=vn,Ln}var sp=O(function(n,t){return rf(n,1,t)}),ap=O(function(n,t,e){return rf(n,Gn(t)||0,e)});function lp(n){return ut(n,qn)}function vr(n,t){if(typeof n!="function"||t!=null&&typeof t!="function")throw new Pn(y);var e=function(){var r=arguments,u=t?t.apply(this,r):r[0],o=e.cache;if(o.has(u))return o.get(u);var s=n.apply(this,r);return e.cache=o.set(u,s)||o,s};return e.cache=new(vr.Cache||rt),e}vr.Cache=rt;function xr(n){if(typeof n!="function")throw new Pn(y);return function(){var t=arguments;switch(t.length){case 0:return!n.call(this);case 1:return!n.call(this,t[0]);case 2:return!n.call(this,t[0],t[1]);case 3:return!n.call(this,t[0],t[1],t[2])}return!n.apply(this,t)}}function cp(n){return co(2,n)}var hp=Vl(function(n,t){t=t.length==1&&M(t[0])?$(t[0],Fn(C())):$(on(t,1),Fn(C()));var e=t.length;return O(function(r){for(var u=-1,o=ln(r.length,e);++u=t}),Dt=af(function(){return arguments}())?af:function(n){return k(n)&&U.call(n,"callee")&&!Zu.call(n,"callee")},M=p.isArray,Ip=Ru?Fn(Ru):Pl;function mn(n){return n!=null&&mr(n.length)&&!st(n)}function Z(n){return k(n)&&mn(n)}function Mp(n){return n===!0||n===!1||k(n)&&_n(n)==te}var St=Ha||Zi,Rp=Lu?Fn(Lu):Wl;function Lp(n){return k(n)&&n.nodeType===1&&!Ae(n)}function Ep(n){if(n==null)return!0;if(mn(n)&&(M(n)||typeof n=="string"||typeof n.splice=="function"||St(n)||Qt(n)||Dt(n)))return!n.length;var t=cn(n);if(t==$n||t==Kn)return!n.size;if(ye(n))return!hi(n).length;for(var e in n)if(U.call(n,e))return!1;return!0}function Op(n,t){return ve(n,t)}function bp(n,t,e){e=typeof e=="function"?e:i;var r=e?e(n,t):i;return r===i?ve(n,t,i,e):!!r}function Ui(n){if(!k(n))return!1;var t=_n(n);return t==Ee||t==es||typeof n.message=="string"&&typeof n.name=="string"&&!Ae(n)}function Dp(n){return typeof n=="number"&&Xu(n)}function st(n){if(!z(n))return!1;var t=_n(n);return t==Oe||t==ru||t==pt||t==is}function xo(n){return typeof n=="number"&&n==R(n)}function mr(n){return typeof n=="number"&&n>-1&&n%1==0&&n<=Hn}function z(n){var t=typeof n;return n!=null&&(t=="object"||t=="function")}function k(n){return n!=null&&typeof n=="object"}var mo=Eu?Fn(Eu):Ul;function Pp(n,t){return n===t||ci(n,t,Mi(t))}function Wp(n,t,e){return e=typeof e=="function"?e:i,ci(n,t,Mi(t),e)}function Bp(n){return yo(n)&&n!=+n}function Up(n){if(wc(n))throw new I(A);return lf(n)}function Np(n){return n===null}function Gp(n){return n==null}function yo(n){return typeof n=="number"||k(n)&&_n(n)==re}function Ae(n){if(!k(n)||_n(n)!=tt)return!1;var t=ke(n);if(t===null)return!0;var e=U.call(t,"constructor")&&t.constructor;return typeof e=="function"&&e instanceof e&&He.call(e)==Wa}var Ni=Ou?Fn(Ou):Nl;function qp(n){return xo(n)&&n>=-Hn&&n<=Hn}var wo=bu?Fn(bu):Gl;function yr(n){return typeof n=="string"||!M(n)&&k(n)&&_n(n)==ue}function Mn(n){return typeof n=="symbol"||k(n)&&_n(n)==be}var Qt=Du?Fn(Du):ql;function Hp(n){return n===i}function $p(n){return k(n)&&cn(n)==fe}function Kp(n){return k(n)&&_n(n)==fs}var zp=lr(pi),kp=lr(function(n,t){return n<=t});function Ao(n){if(!n)return[];if(mn(n))return yr(n)?zn(n):xn(n);if(ae&&n[ae])return Ca(n[ae]());var t=cn(n),e=t==$n?ni:t==Kn?Ne:Vt;return e(n)}function at(n){if(!n)return n===0?n:0;if(n=Gn(n),n===Jn||n===-Jn){var t=n<0?-1:1;return t*Me}return n===n?n:0}function R(n){var t=at(n),e=t%1;return t===t?e?t-e:t:0}function So(n){return n?Lt(R(n),0,Cn):0}function Gn(n){if(typeof n=="number")return n;if(Mn(n))return Tt;if(z(n)){var t=typeof n.valueOf=="function"?n.valueOf():n;n=z(t)?t+"":t}if(typeof n!="string")return n===0?n:+n;n=Gu(n);var e=Is.test(n);return e||Rs.test(n)?oa(n.slice(2),e?2:8):Fs.test(n)?Tt:+n}function Co(n){return Qn(n,yn(n))}function Yp(n){return n?Lt(R(n),-Hn,Hn):n===0?n:0}function B(n){return n==null?"":In(n)}var Zp=Zt(function(n,t){if(ye(t)||mn(t)){Qn(t,en(t),n);return}for(var e in t)U.call(t,e)&&ge(n,e,t[e])}),To=Zt(function(n,t){Qn(t,yn(t),n)}),wr=Zt(function(n,t,e,r){Qn(t,yn(t),n,r)}),Jp=Zt(function(n,t,e,r){Qn(t,en(t),n,r)}),Xp=ft(fi);function Qp(n,t){var e=Yt(n);return t==null?e:tf(e,t)}var Vp=O(function(n,t){n=N(n);var e=-1,r=t.length,u=r>2?t[2]:i;for(u&&dn(t[0],t[1],u)&&(r=1);++e1),o}),Qn(n,Fi(n),e),r&&(e=Bn(e,H|An|hn,ac));for(var u=t.length;u--;)xi(e,t[u]);return e});function dg(n,t){return Io(n,xr(C(t)))}var vg=ft(function(n,t){return n==null?{}:Kl(n,t)});function Io(n,t){if(n==null)return{};var e=$(Fi(n),function(r){return[r]});return t=C(t),vf(n,e,function(r,u){return t(r,u[0])})}function xg(n,t,e){t=wt(t,n);var r=-1,u=t.length;for(u||(u=1,n=i);++rt){var r=n;n=t,t=r}if(e||n%1||t%1){var u=Qu();return ln(n+u*(t-n+fa("1e-"+((u+"").length-1))),t)}return _i(n,t)}var Rg=Jt(function(n,t,e){return t=t.toLowerCase(),n+(e?Lo(t):t)});function Lo(n){return Hi(B(n).toLowerCase())}function Eo(n){return n=B(n),n&&n.replace(Es,ma).replace(Xs,"")}function Lg(n,t,e){n=B(n),t=In(t);var r=n.length;e=e===i?r:Lt(R(e),0,r);var u=e;return e-=t.length,e>=0&&n.slice(e,u)==t}function Eg(n){return n=B(n),n&&cs.test(n)?n.replace(fu,ya):n}function Og(n){return n=B(n),n&&vs.test(n)?n.replace(Br,"\\\\$&"):n}var bg=Jt(function(n,t,e){return n+(e?"-":"")+t.toLowerCase()}),Dg=Jt(function(n,t,e){return n+(e?" ":"")+t.toLowerCase()}),Pg=bf("toLowerCase");function Wg(n,t,e){n=B(n),t=R(t);var r=t?$t(n):0;if(!t||r>=t)return n;var u=(t-r)/2;return ar(Xe(u),e)+n+ar(Je(u),e)}function Bg(n,t,e){n=B(n),t=R(t);var r=t?$t(n):0;return t&&r>>0,e?(n=B(n),n&&(typeof t=="string"||t!=null&&!Ni(t))&&(t=In(t),!t&&Ht(n))?At(zn(n),0,e):n.split(t,e)):[]}var Kg=Jt(function(n,t,e){return n+(e?" ":"")+Hi(t)});function zg(n,t,e){return n=B(n),e=e==null?0:Lt(R(e),0,n.length),t=In(t),n.slice(e,e+t.length)==t}function kg(n,t,e){var r=f.templateSettings;e&&dn(n,t,e)&&(t=i),n=B(n),t=wr({},t,r,Gf);var u=wr({},t.imports,r.imports,Gf),o=en(u),s=jr(u,o),a,c,_=0,d=t.interpolate||De,v="__p += \'",x=ti((t.escape||De).source+"|"+d.source+"|"+(d===ou?Ts:De).source+"|"+(t.evaluate||De).source+"|$","g"),S="//# sourceURL="+(U.call(t,"sourceURL")?(t.sourceURL+"").replace(/\\s/g," "):"lodash.templateSources["+ ++ta+"]")+`\n`;n.replace(x,function(F,b,P,Rn,vn,Ln){return P||(P=Rn),v+=n.slice(_,Ln).replace(Os,wa),b&&(a=!0,v+=`\' +\n__e(`+b+`) +\n\'`),vn&&(c=!0,v+=`\';\n`+vn+`;\n__p += \'`),P&&(v+=`\' +\n((__t = (`+P+`)) == null ? \'\' : __t) +\n\'`),_=Ln+F.length,F}),v+=`\';\n`;var T=U.call(t,"variable")&&t.variable;if(!T)v=`with (obj) {\n`+v+`\n}\n`;else if(Ss.test(T))throw new I(E);v=(c?v.replace(os,""):v).replace(ss,"$1").replace(as,"$1;"),v="function("+(T||"obj")+`) {\n`+(T?"":`obj || (obj = {});\n`)+"var __t, __p = \'\'"+(a?", __e = _.escape":"")+(c?`, __j = Array.prototype.join;\nfunction print() { __p += __j.call(arguments, \'\') }\n`:`;\n`)+v+`return __p\n}`;var L=bo(function(){return W(o,S+"return "+v).apply(i,s)});if(L.source=v,Ui(L))throw L;return L}function Yg(n){return B(n).toLowerCase()}function Zg(n){return B(n).toUpperCase()}function Jg(n,t,e){if(n=B(n),n&&(e||t===i))return Gu(n);if(!n||!(t=In(t)))return n;var r=zn(n),u=zn(t),o=qu(r,u),s=Hu(r,u)+1;return At(r,o,s).join("")}function Xg(n,t,e){if(n=B(n),n&&(e||t===i))return n.slice(0,Ku(n)+1);if(!n||!(t=In(t)))return n;var r=zn(n),u=Hu(r,zn(t))+1;return At(r,0,u).join("")}function Qg(n,t,e){if(n=B(n),n&&(e||t===i))return n.replace(Ur,"");if(!n||!(t=In(t)))return n;var r=zn(n),u=qu(r,zn(t));return At(r,u).join("")}function Vg(n,t){var e=Fr,r=Fe;if(z(t)){var u="separator"in t?t.separator:u;e="length"in t?R(t.length):e,r="omission"in t?In(t.omission):r}n=B(n);var o=n.length;if(Ht(n)){var s=zn(n);o=s.length}if(e>=o)return n;var a=e-$t(r);if(a<1)return r;var c=s?At(s,0,a).join(""):n.slice(0,a);if(u===i)return c+r;if(s&&(a+=c.length-a),Ni(u)){if(n.slice(a).search(u)){var _,d=c;for(u.global||(u=ti(u.source,B(su.exec(u))+"g")),u.lastIndex=0;_=u.exec(d);)var v=_.index;c=c.slice(0,v===i?a:v)}}else if(n.indexOf(In(u),a)!=a){var x=c.lastIndexOf(u);x>-1&&(c=c.slice(0,x))}return c+r}function jg(n){return n=B(n),n&&ls.test(n)?n.replace(uu,Ma):n}var n_=Jt(function(n,t,e){return n+(e?" ":"")+t.toUpperCase()}),Hi=bf("toUpperCase");function Oo(n,t,e){return n=B(n),t=e?i:t,t===i?Sa(n)?Ea(n):ga(n):n.match(t)||[]}var bo=O(function(n,t){try{return Tn(n,i,t)}catch(e){return Ui(e)?e:new I(e)}}),t_=ft(function(n,t){return Dn(t,function(e){e=Vn(e),it(n,e,Wi(n[e],n))}),n});function e_(n){var t=n==null?0:n.length,e=C();return n=t?$(n,function(r){if(typeof r[1]!="function")throw new Pn(y);return[e(r[0]),r[1]]}):[],O(function(r){for(var u=-1;++uHn)return[];var e=Cn,r=ln(n,Cn);t=C(t),n-=Cn;for(var u=Vr(r,t);++e0||t<0)?new D(e):(n<0?e=e.takeRight(-n):n&&(e=e.drop(n)),t!==i&&(t=R(t),e=t<0?e.dropRight(-t):e.take(t-n)),e)},D.prototype.takeRightWhile=function(n){return this.reverse().takeWhile(n).reverse()},D.prototype.toArray=function(){return this.take(Cn)},Xn(D.prototype,function(n,t){var e=/^(?:filter|find|map|reject)|While$/.test(t),r=/^(?:head|last)$/.test(t),u=f[r?"take"+(t=="last"?"Right":""):t],o=r||/^find/.test(t);!u||(f.prototype[t]=function(){var s=this.__wrapped__,a=r?[1]:arguments,c=s instanceof D,_=a[0],d=c||M(s),v=function(b){var P=u.apply(f,_t([b],a));return r&&x?P[0]:P};d&&e&&typeof _=="function"&&_.length!=1&&(c=d=!1);var x=this.__chain__,S=!!this.__actions__.length,T=o&&!x,L=c&&!S;if(!o&&d){s=L?s:new D(this);var F=n.apply(s,a);return F.__actions__.push({func:gr,args:[v],thisArg:i}),new Wn(F,x)}return T&&L?n.apply(this,a):(F=this.thru(v),T?r?F.value()[0]:F.value():F)})}),Dn(["pop","push","shift","sort","splice","unshift"],function(n){var t=Ge[n],e=/^(?:push|sort|unshift)$/.test(n)?"tap":"thru",r=/^(?:pop|shift)$/.test(n);f.prototype[n]=function(){var u=arguments;if(r&&!this.__chain__){var o=this.value();return t.apply(M(o)?o:[],u)}return this[e](function(s){return t.apply(M(s)?s:[],u)})}}),Xn(D.prototype,function(n,t){var e=f[t];if(e){var r=e.name+"";U.call(kt,r)||(kt[r]=[]),kt[r].push({name:t,func:e})}}),kt[or(i,K).name]=[{name:"wrapper",func:i}],D.prototype.clone=ja,D.prototype.reverse=nl,D.prototype.value=tl,f.prototype.at=Lh,f.prototype.chain=Eh,f.prototype.commit=Oh,f.prototype.next=bh,f.prototype.plant=Ph,f.prototype.reverse=Wh,f.prototype.toJSON=f.prototype.valueOf=f.prototype.value=Bh,f.prototype.first=f.prototype.head,ae&&(f.prototype[ae]=Dh),f},vt=Oa();typeof define=="function"&&typeof define.amd=="object"&&define.amd?(tn._=vt,define(function(){return vt})):Ft?((Ft.exports=vt)._=vt,Kr._=vt):tn._=vt}).call(jt)});var eu=J_(No());var ct=i=>[...new Set(i)],Go=i=>[...new Map(i.map(h=>[h.toLowerCase(),h])).values()];var qo=i=>{var h;try{h=JSON.parse(i)}catch(m){}return h};var $o=(i,h)=>h.indexOf(i)>0?h.indexOf(i):h.length,X_=i=>i.substring(0,i.length-2),Xi=i=>i.replace(/\\//g,"+")+"//";var Q_=i=>i.charAt(0)=="#"?i.substring(1,i.length):i;var V_=i=>i.charAt(0)=="/"?i.substring(1):i;var Ho=i=>V_(i.substring(i.lastIndexOf("/")))||i,Qi=i=>i?(i==null?void 0:i.type)=="folder"?Ho(i.contextPath):(i==null?void 0:i.type)=="tag"?Q_(i.contextPath):(i==null?void 0:i.type)=="space"?X_(i.contextPath):i.isRemote?Ho(i.contextPath):i.contextPath:"";var ht=i=>{var h;return(h=i==null?void 0:i.match(/(\\\\.|[^,])+/g))!=null?h:[]},Vi=i=>{if(!i)return"";let h=/\\[\\[(.*?)\\]\\]/g.exec(i),m=(h==null?void 0:h.length)>1?h[1].substring(0,$o("|",h[1])):i;return m||i};var Ko=i=>{var h;return!i||i.length==0?[]:i.charAt(0)=="#"?i.split("&").map(m=>({type:"tag",value:m})):(h=qo(i))!=null?h:[]};var Ce=(i,h)=>{if(typeof i=="string"){if(/\\/\\/(\\S+?(?:jpe?g|png|gif|svg))/gi.test(i)||i.includes("unsplash"))return"image";if(/^\\d{4}-\\d{2}-\\d{2}$/.test(i))return"date";if(h=="tag"||h=="tags")return"tag";if(/\\[\\[.*?\\]\\]/.test(i))return"link"}else{if(typeof i=="number")return"number";if(typeof i=="boolean")return"boolean";if(i)if(Array.isArray(i)||typeof i=="string"&&i.indexOf(",")>-1){let m=Array.isArray(i)?i:[];if(typeof i=="string"&&i.indexOf(",")>-1&&(m=ht(i)),h=="tag"||h=="tags")return"tag-multi";if(m.length==1&&Array.isArray(m[0])&&m[0].length==1&&typeof m[0][0]=="string")return"link";let A=ct(m.map(y=>Ce(y,h)));return A.length==1&&A[0]=="link"?"link-multi":"option-multi"}else{if(i.isLuxonDateTime)return"date";if(i.isLuxonDuration)return"duration";if(i.type=="file")return"link";if(typeof i=="object"&&!Array.isArray(i)&&i!==null)return"object"}else return"unknown"}return"text"};var zo=i=>Object.keys(i!=null?i:{}).filter(h=>h!="position").filter(h=>h!="tag"&&h!="tags");var ne=i=>i.join(","),ko=i=>i.join(", ");var Ar=(i,h)=>{switch(Ce(h,i)){case"object":return JSON.stringify(h);case"number":return h.toString();case"boolean":return h?"true":"false";case"date":return h;case"duration":return ko(Object.keys(h.values).reduce((A,y)=>[...A,...h.values[y]>0?[h.values[y]+" "+y]:[]],[]));case"option-multi":case"link-multi":return typeof h=="string"?h:ne(h.map(A=>A?typeof A=="string"?A:A.path?A.path:Array.isArray(h)&&A.length==1&&Array.isArray(A[0])&&A[0].length==1&&typeof A[0][0]=="string"?A[0][0]:JSON.stringify(A):""));case"link":return Array.isArray(h)&&h.length==1&&Array.isArray(h[0])&&h[0].length==1&&typeof h[0][0]=="string"?h[0][0]:typeof h=="string"?h:h.path;case"text":case"tag":case"image":return h}return""};var Yo=i=>{switch(i){case"duration":return"text";case"unknown":return"text"}return i};var Sr=(i,h)=>i==h,ji=(i,h)=>(i!=null?i:"").length==0,nu=(i,h)=>(i!=null?i:"").toLowerCase().includes((h!=null?h:"").toLowerCase()),Cr=(i,h)=>parseFloat(i)>parseFloat(h),Tr=(i,h)=>parseInt(i)>parseInt(h),tu=(i,h)=>{let m=i?ht(i):[];return(h?ht(h):[]).some(y=>m.some(E=>E==y))};var Te={isNotEmpty:{type:["text","file","link","link-multi","fileprop","image"],fn:(i,h)=>!ji(i,""),valueType:"none"},isEmpty:{type:["text","file","link","link-multi","fileprop","image"],fn:(i,h)=>ji(i,""),valueType:"none"},include:{fn:(i,h)=>nu(i,h),type:["text","file","link","link-multi","fileprop","image"],valueType:"text"},notInclude:{type:["text","file","link","link-multi","fileprop","image"],fn:(i,h)=>!nu(i,h),valueType:"text"},is:{type:["text","file","link","context","fileprop"],fn:Sr,valueType:"text"},isNot:{type:["text","file","link","context","fileprop"],fn:(i,h)=>!Sr(i,h),valueType:"text"},equal:{type:["number"],fn:Sr,valueType:"number"},isGreatThan:{type:["number"],fn:Cr,valueType:"number"},isLessThan:{type:["number"],fn:Tr,valueType:"number"},isLessThanOrEqual:{type:["number"],fn:(i,h)=>!Cr(i,h),valueType:"number"},isGreatThanOrEqual:{type:["number"],fn:(i,h)=>!Tr(i,h),valueType:"number"},dateBefore:{type:["date","fileprop"],fn:Tr,valueType:"date"},dateAfter:{type:["date","fileprop"],fn:Cr,valueType:"date"},isAnyInList:{type:["option","context","option-multi","context-multi","tags-multi","tags"],fn:tu,valueType:"list"},isNoneInList:{type:["option","context","option-multi","context-multi","tags-multi","tags"],fn:(i,h)=>!tu(i,h),valueType:"list"},isTrue:{type:["boolean"],fn:(i,h)=>i=="true",valueType:"none"},isFalse:{type:["boolean"],fn:(i,h)=>i!="true",valueType:"none"}};var j_=(i,h)=>h.reduce((A,y)=>{let[E,V]=A,rn=y.type=="fileprop"?Xo(V,y):y.type=="filemeta"?Jo(V,y):y.type=="frontmatter"?Zo(V,y):[],un=V.filter(H=>!rn.includes(H));return[[...E,...rn],un]},[[],i])[0],n0=(i,h)=>h.reduce((m,A)=>A.type=="fileprop"?Xo(m,A):A.type=="filemeta"?Jo(m,A):A.type=="frontmatter"?Zo(m,A):[],i),Zo=(i,h)=>i.filter(m=>{let A=m.frontmatter;if(!A||!A[h.field])return!1;let y=Te[h.fn],E=!0;return y&&(E=y.fn(Ar(h.field,A[h.field]),h.value)),E}),Jo=(i,h)=>i.filter(m=>{let A="";h.field=="outlinks"?A=ne(m.outlinks):h.field=="inlinks"?A=ne(m.inlinks):h.field=="tags"&&(A=ne(m.tags));let y=Te[h.fn],E=!0;return y&&(E=y.fn(A,h.value)),E}),Xo=(i,h)=>i.filter(m=>{if(["path","sticker","color","isFolder","extension","ctime","mtime","size","parent"].includes(h.field)){let y=Te[h.fn],E=!0;return y&&(E=y.fn(m[h.field],h.value)),E}return!0}),Qo=(i,h)=>i.filters.reduce((y,E)=>y&&(E.type=="any"?j_([h],E.filters).length>0:n0([h],E.filters).length>0),!0);var Vo=(i,h,m)=>{var An,hn,pn,Sn,Y,K;if(!h)return{changed:!1,cache:{path:i.dbPath,info:i,name:Qi(i),sticker:"",banner:"",cols:[],files:[],rows:[],def:[],defContexts:[],outlinks:[],contexts:[]}};let A=(hn=(An=h.cols)==null?void 0:An.filter(X=>X.type.startsWith("context")))!=null?hn:[],y=(Sn=(pn=h.cols)==null?void 0:pn.filter(X=>X.type.startsWith("link")))!=null?Sn:[],E=ct(A.map(X=>X.value)),V=ct(h.rows.reduce((X,gn)=>ct([...X,...[...A,...y].flatMap(En=>ht(gn[En.name]).map(Q=>Vi(Q)))]),[])),rn=Ko(h.schema.def),un={path:i.dbPath,info:i,name:Qi(i),sticker:"",banner:"",cols:h.cols,files:(Y=h.rows.map(X=>X.File))!=null?Y:[],rows:(K=h.rows)!=null?K:[],defContexts:rn.filter(X=>X.type=="tag").map(X=>X.value),def:rn,contexts:E,outlinks:V},H=!0;return m&&eu.default.isEqual(un,m)&&(H=!0),{changed:H,cache:un}},t0=i=>{var m,A,y,E,V,rn,un,H,An,hn,pn,Sn,Y;let h=[];return i&&i.tags&&h.push(...(A=(m=i.tags)==null?void 0:m.map(K=>K.tag))!=null?A:[]),i&&((y=i.frontmatter)==null?void 0:y.tags)&&h.push(...(typeof((E=i.frontmatter)==null?void 0:E.tags)=="string"?ht(i.frontmatter.tags.replace(/ /g,"")):Array.isArray((V=i.frontmatter)==null?void 0:V.tags)?(un=(rn=i.frontmatter)==null?void 0:rn.tags)!=null?un:[]:[]).filter(K=>typeof K=="string").map(K=>"#"+K)),i&&((H=i.frontmatter)==null?void 0:H.tag)&&h.push(...(typeof((An=i.frontmatter)==null?void 0:An.tag)=="string"?ht(i.frontmatter.tag.replace(/ /g,"")):Array.isArray((hn=i.frontmatter)==null?void 0:hn.tag)?(Sn=(pn=i.frontmatter)==null?void 0:pn.tag)!=null?Sn:[]:[]).filter(K=>typeof K=="string").map(K=>"#"+K)),(Y=ct(h))!=null?Y:[]};var e0=(i,h,m,A)=>{let y=[];return y.push(...h.filter(E=>m.has(E))),i.parent!="/"&&y.push(i.parent),A.forEach(E=>{m.has(Xi(E))&&y.push(Xi(E))}),y},jo=(i,h,m,A,y,E,V,rn,un)=>{var Hn,Me,Tt,Cn,Re,Le;let H={path:i.path,name:i.name};i.stat&&(H.ctime=i.stat.ctime,H.mtime=i.stat.mtime,H.size=i.stat.size,H.extension=i.extension);let An=[],hn=t0(E);if(m.has(i.parent))for(let sn of m.get(i.parent).def)sn.type=="tag"&&An.push(sn.value);An.push(...hn);let pn=i.name,Sn=(Hn=y==null?void 0:y.sticker)!=null?Hn:"",Y=(Me=y==null?void 0:y.color)!=null?Me:"",K=(Tt=y==null?void 0:y.rank)!=null?Tt:"",X=(Cn=y==null?void 0:y.folder)!=null?Cn:"";X=="true"&&(X="");let gn=i.parent,En=i.isFolder,Q={},jn={},On=[],nt=[],qn=E==null?void 0:E.frontmatter;E!=null&&E.links&&nt.push(...E.links.map(sn=>sn.link));let Fr=rn&&En?rn.folderNotePath:i.path;for(let sn of Object.keys(V))Fr in V[sn]&&On.push(sn);let Fe="";if(qn){let an=Go(zo(qn)).reduce((fn,pt)=>Wt(Pt({},fn),{[pt]:{name:pt,type:Yo(Ce(qn[pt],pt))}}),{});Object.keys(an).forEach(fn=>{Q[fn]=Ar(fn,qn[fn]),jn[fn]=an[fn].type,an[fn].type.startsWith("link")&&nt.push(Vi(Q[fn]))}),Fe=(Re=Q[h.fmKeyBanner])!=null?Re:"",Q[h.fmKeySticker]&&(Sn=qn[h.fmKeySticker]),Q[h.fmKeyColor]&&(Y=qn[h.fmKeyColor]),Q[h.fmKeyAlias]&&h.spacesUseAlias&&(pn=qn[h.fmKeyAlias])}let Bt=Wt(Pt({},H),{name:pn,tags:ct(An),fileTags:hn,folderNote:rn,sticker:Sn,color:Y,rank:K,parent:gn,banner:Fe,isFolder:En,folderSort:X,frontmatter:Q,frontmatterTypes:jn,inlinks:On,outlinks:nt}),Ct=[],Ut={};for(let[sn,an]of A)if(an.space.def.type=="smart")Qo(an.space.def,Bt)&&Ct.push(sn);else if(((Le=an.space.def.folder)==null?void 0:Le.length)>0)an.space.def.folder==gn&&(Ct.push(sn),Ut[sn]=K);else{let fn=an.spaceItems.find(pt=>pt.path==Bt.path);fn&&(Ct.push(sn),Ut[sn]=fn.rank)}let Ir=e0(i,An,m,Ct),Ie=rn&&!En?Wt(Pt({},Bt),{spaces:[],contexts:[]}):Wt(Pt({},Bt),{spaces:Ct,contexts:ct(Ir),spaceRanks:Ut}),Jn=!0;return un&&eu.default.isEqual(Ie,un)&&(Jn=!1),{changed:Jn,cache:Ie}};function ns(i){let{file:h,settings:m,contextsCache:A,spacesCache:y,vaultItem:E,metadataCache:V,resolvedLinks:rn,folderNote:un,oldMetadata:H}=i;return jo(h,m,A,y,E,V,rn,un,H)}function ts(i){let{context:h,mdbTable:m,oldCache:A}=i;return Vo(h,m,A)}var r0=self;r0.onmessage=async i=>{let{payload:h,job:m}=i.data,A;m.type=="file"?A=ns(h):m.type=="context"&&(A=ts(h));try{postMessage({job:m,result:A})}catch(y){console.log(y),postMessage({job:m,result:{$error:`Failed to index ${m.type} ${m.path}: ${y}`}})}};\n/**\n * @license\n * Lodash \n * Copyright OpenJS Foundation and other contributors \n * Released under MIT license \n * Based on Underscore.js 1.8.3 \n * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors\n */\n'); + return inlineWorker('var qd=Object.create;var ru=Object.defineProperty,$d=Object.defineProperties,kd=Object.getOwnPropertyDescriptor,Hd=Object.getOwnPropertyDescriptors,Kd=Object.getOwnPropertyNames,Uo=Object.getOwnPropertySymbols,zd=Object.getPrototypeOf,Go=Object.prototype.hasOwnProperty,Yd=Object.prototype.propertyIsEnumerable;var No=(i,l,m)=>l in i?ru(i,l,{enumerable:!0,configurable:!0,writable:!0,value:m}):i[l]=m,Rt=(i,l)=>{for(var m in l||(l={}))Go.call(l,m)&&No(i,m,l[m]);if(Uo)for(var m of Uo(l))Yd.call(l,m)&&No(i,m,l[m]);return i},Lt=(i,l)=>$d(i,Hd(l));var Zd=(i,l)=>()=>(l||i((l={exports:{}}).exports,l),l.exports);var Xd=(i,l,m,w)=>{if(l&&typeof l=="object"||typeof l=="function")for(let y of Kd(l))!Go.call(i,y)&&y!==m&&ru(i,y,{get:()=>l[y],enumerable:!(w=kd(l,y))||w.enumerable});return i};var Jd=(i,l,m)=>(m=i!=null?qd(zd(i)):{},Xd(l||!i||!i.__esModule?ru(m,"default",{value:i,enumerable:!0}):m,i));var qo=Zd((oe,Me)=>{(function(){var i,l="4.17.21",m=200,w="Unsupported core-js use. Try https://npms.io/search?q=ponyfill.",y="Expected a function",O="Invalid `variable` option passed into `_.template`",J="__lodash_hash_undefined__",V=500,Y="__lodash_placeholder__",B=1,an=2,j=4,fn=1,Pn=2,nn=1,q=2,vt=4,hn=8,Bn=16,pn=32,gn=64,yn=128,W=256,dn=512,_n=30,Kn="...",Kt=800,Et=16,zn=1,Le=2,Ee=3,nt=1/0,Yn=9007199254740991,Oe=17976931348623157e292,Ot=0/0,Mn=4294967295,De=Mn-1,Pe=Mn>>>1,Be=[["ary",yn],["bind",nn],["bindKey",q],["curry",hn],["curryRight",Bn],["flip",dn],["partial",pn],["partialRight",gn],["rearg",W]],ft="[object Arguments]",Dt="[object Array]",We="[object AsyncFunction]",mt="[object Boolean]",xt="[object Date]",Ue="[object DOMException]",k="[object Error]",tn="[object Function]",un="[object GeneratorFunction]",K="[object Map]",tt="[object Number]",Ne="[object Null]",Zn="[object Object]",Ge="[object Promise]",zt="[object Proxy]",ae="[object RegExp]",Xn="[object Set]",le="[object String]",qe="[object Symbol]",fs="[object Undefined]",ce="[object WeakMap]",os="[object WeakSet]",he="[object ArrayBuffer]",Yt="[object DataView]",Br="[object Float32Array]",Wr="[object Float64Array]",Ur="[object Int8Array]",Nr="[object Int16Array]",Gr="[object Int32Array]",qr="[object Uint8Array]",$r="[object Uint8ClampedArray]",kr="[object Uint16Array]",Hr="[object Uint32Array]",ss=/\\b__p \\+= \'\';/g,as=/\\b(__p \\+=) \'\' \\+/g,ls=/(__e\\(.*?\\)|\\b__t\\)) \\+\\n\'\';/g,ou=/&(?:amp|lt|gt|quot|#39);/g,su=/[&<>"\']/g,cs=RegExp(ou.source),hs=RegExp(su.source),ps=/<%-([\\s\\S]+?)%>/g,gs=/<%([\\s\\S]+?)%>/g,au=/<%=([\\s\\S]+?)%>/g,ds=/\\.|\\[(?:[^[\\]]*|(["\'])(?:(?!\\1)[^\\\\]|\\\\.)*?\\1)\\]/,_s=/^\\w*$/,vs=/[^.[\\]]+|\\[(?:(-?\\d+(?:\\.\\d+)?)|(["\'])((?:(?!\\2)[^\\\\]|\\\\.)*?)\\2)\\]|(?=(?:\\.|\\[\\])(?:\\.|\\[\\]|$))/g,Kr=/[\\\\^$.*+?()[\\]{}|]/g,ms=RegExp(Kr.source),zr=/^\\s+/,xs=/\\s/,ys=/\\{(?:\\n\\/\\* \\[wrapped with .+\\] \\*\\/)?\\n?/,ws=/\\{\\n\\/\\* \\[wrapped with (.+)\\] \\*/,As=/,? & /,Ss=/[^\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\x7f]+/g,Ts=/[()=,{}\\[\\]\\/\\s]/,Fs=/\\\\(\\\\)?/g,Cs=/\\$\\{([^\\\\}]*(?:\\\\.[^\\\\}]*)*)\\}/g,lu=/\\w*$/,Is=/^[-+]0x[0-9a-f]+$/i,Ms=/^0b[01]+$/i,bs=/^\\[object .+?Constructor\\]$/,Rs=/^0o[0-7]+$/i,Ls=/^(?:0|[1-9]\\d*)$/,Es=/[\\xc0-\\xd6\\xd8-\\xf6\\xf8-\\xff\\u0100-\\u017f]/g,$e=/($^)/,Os=/[\'\\n\\r\\u2028\\u2029\\\\]/g,ke="\\\\ud800-\\\\udfff",Ds="\\\\u0300-\\\\u036f",Ps="\\\\ufe20-\\\\ufe2f",Bs="\\\\u20d0-\\\\u20ff",cu=Ds+Ps+Bs,hu="\\\\u2700-\\\\u27bf",pu="a-z\\\\xdf-\\\\xf6\\\\xf8-\\\\xff",Ws="\\\\xac\\\\xb1\\\\xd7\\\\xf7",Us="\\\\x00-\\\\x2f\\\\x3a-\\\\x40\\\\x5b-\\\\x60\\\\x7b-\\\\xbf",Ns="\\\\u2000-\\\\u206f",Gs=" \\\\t\\\\x0b\\\\f\\\\xa0\\\\ufeff\\\\n\\\\r\\\\u2028\\\\u2029\\\\u1680\\\\u180e\\\\u2000\\\\u2001\\\\u2002\\\\u2003\\\\u2004\\\\u2005\\\\u2006\\\\u2007\\\\u2008\\\\u2009\\\\u200a\\\\u202f\\\\u205f\\\\u3000",gu="A-Z\\\\xc0-\\\\xd6\\\\xd8-\\\\xde",du="\\\\ufe0e\\\\ufe0f",_u=Ws+Us+Ns+Gs,Yr="[\'\\u2019]",qs="["+ke+"]",vu="["+_u+"]",He="["+cu+"]",mu="\\\\d+",$s="["+hu+"]",xu="["+pu+"]",yu="[^"+ke+_u+mu+hu+pu+gu+"]",Zr="\\\\ud83c[\\\\udffb-\\\\udfff]",ks="(?:"+He+"|"+Zr+")",wu="[^"+ke+"]",Xr="(?:\\\\ud83c[\\\\udde6-\\\\uddff]){2}",Jr="[\\\\ud800-\\\\udbff][\\\\udc00-\\\\udfff]",Zt="["+gu+"]",Au="\\\\u200d",Su="(?:"+xu+"|"+yu+")",Hs="(?:"+Zt+"|"+yu+")",Tu="(?:"+Yr+"(?:d|ll|m|re|s|t|ve))?",Fu="(?:"+Yr+"(?:D|LL|M|RE|S|T|VE))?",Cu=ks+"?",Iu="["+du+"]?",Ks="(?:"+Au+"(?:"+[wu,Xr,Jr].join("|")+")"+Iu+Cu+")*",zs="\\\\d*(?:1st|2nd|3rd|(?![123])\\\\dth)(?=\\\\b|[A-Z_])",Ys="\\\\d*(?:1ST|2ND|3RD|(?![123])\\\\dTH)(?=\\\\b|[a-z_])",Mu=Iu+Cu+Ks,Zs="(?:"+[$s,Xr,Jr].join("|")+")"+Mu,Xs="(?:"+[wu+He+"?",He,Xr,Jr,qs].join("|")+")",Js=RegExp(Yr,"g"),Qs=RegExp(He,"g"),Qr=RegExp(Zr+"(?="+Zr+")|"+Xs+Mu,"g"),Vs=RegExp([Zt+"?"+xu+"+"+Tu+"(?="+[vu,Zt,"$"].join("|")+")",Hs+"+"+Fu+"(?="+[vu,Zt+Su,"$"].join("|")+")",Zt+"?"+Su+"+"+Tu,Zt+"+"+Fu,Ys,zs,mu,Zs].join("|"),"g"),js=RegExp("["+Au+ke+cu+du+"]"),na=/[a-z][A-Z]|[A-Z]{2}[a-z]|[0-9][a-zA-Z]|[a-zA-Z][0-9]|[^a-zA-Z0-9 ]/,ta=["Array","Buffer","DataView","Date","Error","Float32Array","Float64Array","Function","Int8Array","Int16Array","Int32Array","Map","Math","Object","Promise","RegExp","Set","String","Symbol","TypeError","Uint8Array","Uint8ClampedArray","Uint16Array","Uint32Array","WeakMap","_","clearTimeout","isFinite","parseInt","setTimeout"],ea=-1,z={};z[Br]=z[Wr]=z[Ur]=z[Nr]=z[Gr]=z[qr]=z[$r]=z[kr]=z[Hr]=!0,z[ft]=z[Dt]=z[he]=z[mt]=z[Yt]=z[xt]=z[k]=z[tn]=z[K]=z[tt]=z[Zn]=z[ae]=z[Xn]=z[le]=z[ce]=!1;var H={};H[ft]=H[Dt]=H[he]=H[Yt]=H[mt]=H[xt]=H[Br]=H[Wr]=H[Ur]=H[Nr]=H[Gr]=H[K]=H[tt]=H[Zn]=H[ae]=H[Xn]=H[le]=H[qe]=H[qr]=H[$r]=H[kr]=H[Hr]=!0,H[k]=H[tn]=H[ce]=!1;var ra={\\u00C0:"A",\\u00C1:"A",\\u00C2:"A",\\u00C3:"A",\\u00C4:"A",\\u00C5:"A",\\u00E0:"a",\\u00E1:"a",\\u00E2:"a",\\u00E3:"a",\\u00E4:"a",\\u00E5:"a",\\u00C7:"C",\\u00E7:"c",\\u00D0:"D",\\u00F0:"d",\\u00C8:"E",\\u00C9:"E",\\u00CA:"E",\\u00CB:"E",\\u00E8:"e",\\u00E9:"e",\\u00EA:"e",\\u00EB:"e",\\u00CC:"I",\\u00CD:"I",\\u00CE:"I",\\u00CF:"I",\\u00EC:"i",\\u00ED:"i",\\u00EE:"i",\\u00EF:"i",\\u00D1:"N",\\u00F1:"n",\\u00D2:"O",\\u00D3:"O",\\u00D4:"O",\\u00D5:"O",\\u00D6:"O",\\u00D8:"O",\\u00F2:"o",\\u00F3:"o",\\u00F4:"o",\\u00F5:"o",\\u00F6:"o",\\u00F8:"o",\\u00D9:"U",\\u00DA:"U",\\u00DB:"U",\\u00DC:"U",\\u00F9:"u",\\u00FA:"u",\\u00FB:"u",\\u00FC:"u",\\u00DD:"Y",\\u00FD:"y",\\u00FF:"y",\\u00C6:"Ae",\\u00E6:"ae",\\u00DE:"Th",\\u00FE:"th",\\u00DF:"ss",\\u0100:"A",\\u0102:"A",\\u0104:"A",\\u0101:"a",\\u0103:"a",\\u0105:"a",\\u0106:"C",\\u0108:"C",\\u010A:"C",\\u010C:"C",\\u0107:"c",\\u0109:"c",\\u010B:"c",\\u010D:"c",\\u010E:"D",\\u0110:"D",\\u010F:"d",\\u0111:"d",\\u0112:"E",\\u0114:"E",\\u0116:"E",\\u0118:"E",\\u011A:"E",\\u0113:"e",\\u0115:"e",\\u0117:"e",\\u0119:"e",\\u011B:"e",\\u011C:"G",\\u011E:"G",\\u0120:"G",\\u0122:"G",\\u011D:"g",\\u011F:"g",\\u0121:"g",\\u0123:"g",\\u0124:"H",\\u0126:"H",\\u0125:"h",\\u0127:"h",\\u0128:"I",\\u012A:"I",\\u012C:"I",\\u012E:"I",\\u0130:"I",\\u0129:"i",\\u012B:"i",\\u012D:"i",\\u012F:"i",\\u0131:"i",\\u0134:"J",\\u0135:"j",\\u0136:"K",\\u0137:"k",\\u0138:"k",\\u0139:"L",\\u013B:"L",\\u013D:"L",\\u013F:"L",\\u0141:"L",\\u013A:"l",\\u013C:"l",\\u013E:"l",\\u0140:"l",\\u0142:"l",\\u0143:"N",\\u0145:"N",\\u0147:"N",\\u014A:"N",\\u0144:"n",\\u0146:"n",\\u0148:"n",\\u014B:"n",\\u014C:"O",\\u014E:"O",\\u0150:"O",\\u014D:"o",\\u014F:"o",\\u0151:"o",\\u0154:"R",\\u0156:"R",\\u0158:"R",\\u0155:"r",\\u0157:"r",\\u0159:"r",\\u015A:"S",\\u015C:"S",\\u015E:"S",\\u0160:"S",\\u015B:"s",\\u015D:"s",\\u015F:"s",\\u0161:"s",\\u0162:"T",\\u0164:"T",\\u0166:"T",\\u0163:"t",\\u0165:"t",\\u0167:"t",\\u0168:"U",\\u016A:"U",\\u016C:"U",\\u016E:"U",\\u0170:"U",\\u0172:"U",\\u0169:"u",\\u016B:"u",\\u016D:"u",\\u016F:"u",\\u0171:"u",\\u0173:"u",\\u0174:"W",\\u0175:"w",\\u0176:"Y",\\u0177:"y",\\u0178:"Y",\\u0179:"Z",\\u017B:"Z",\\u017D:"Z",\\u017A:"z",\\u017C:"z",\\u017E:"z",\\u0132:"IJ",\\u0133:"ij",\\u0152:"Oe",\\u0153:"oe",\\u0149:"\'n",\\u017F:"s"},ia={"&":"&","<":"<",">":">",\'"\':""","\'":"'"},ua={"&":"&","<":"<",">":">",""":\'"\',"'":"\'"},fa={"\\\\":"\\\\","\'":"\'","\\n":"n","\\r":"r","\\u2028":"u2028","\\u2029":"u2029"},oa=parseFloat,sa=parseInt,bu=typeof global=="object"&&global&&global.Object===Object&&global,aa=typeof self=="object"&&self&&self.Object===Object&&self,ln=bu||aa||Function("return this")(),Vr=typeof oe=="object"&&oe&&!oe.nodeType&&oe,Pt=Vr&&typeof Me=="object"&&Me&&!Me.nodeType&&Me,Ru=Pt&&Pt.exports===Vr,jr=Ru&&bu.process,Wn=function(){try{var c=Pt&&Pt.require&&Pt.require("util").types;return c||jr&&jr.binding&&jr.binding("util")}catch(g){}}(),Lu=Wn&&Wn.isArrayBuffer,Eu=Wn&&Wn.isDate,Ou=Wn&&Wn.isMap,Du=Wn&&Wn.isRegExp,Pu=Wn&&Wn.isSet,Bu=Wn&&Wn.isTypedArray;function bn(c,g,p){switch(p.length){case 0:return c.call(g);case 1:return c.call(g,p[0]);case 2:return c.call(g,p[0],p[1]);case 3:return c.call(g,p[0],p[1],p[2])}return c.apply(g,p)}function la(c,g,p,A){for(var I=-1,U=c==null?0:c.length;++I-1}function ni(c,g,p){for(var A=-1,I=c==null?0:c.length;++A-1;);return p}function Hu(c,g){for(var p=c.length;p--&&Xt(g,c[p],0)>-1;);return p}function xa(c,g){for(var p=c.length,A=0;p--;)c[p]===g&&++A;return A}var ya=ii(ra),wa=ii(ia);function Aa(c){return"\\\\"+fa[c]}function Sa(c,g){return c==null?i:c[g]}function Jt(c){return js.test(c)}function Ta(c){return na.test(c)}function Fa(c){for(var g,p=[];!(g=c.next()).done;)p.push(g.value);return p}function si(c){var g=-1,p=Array(c.size);return c.forEach(function(A,I){p[++g]=[I,A]}),p}function Ku(c,g){return function(p){return c(g(p))}}function At(c,g){for(var p=-1,A=c.length,I=0,U=[];++p-1}function hl(n,t){var e=this.__data__,r=sr(e,n);return r<0?(++this.size,e.push([n,t])):e[r][1]=t,this}ot.prototype.clear=sl,ot.prototype.delete=al,ot.prototype.get=ll,ot.prototype.has=cl,ot.prototype.set=hl;function st(n){var t=-1,e=n==null?0:n.length;for(this.clear();++t=t?n:t)),n}function qn(n,t,e,r,u,o){var s,a=t&B,h=t&an,d=t&j;if(e&&(s=u?e(n,r,u,o):e(n)),s!==i)return s;if(!X(n))return n;var _=M(n);if(_){if(s=_c(n),!a)return Tn(n,s)}else{var v=xn(n),x=v==tn||v==un;if(bt(n))return Mf(n,a);if(v==Zn||v==ft||x&&!u){if(s=h||x?{}:Yf(n),!a)return h?uc(n,Ml(s,n)):ic(n,rf(s,n))}else{if(!H[v])return u?n:{};s=vc(n,v,a)}}o||(o=new Qn);var S=o.get(n);if(S)return S;o.set(n,s),So(n)?n.forEach(function(C){s.add(qn(C,t,e,C,n,o))}):wo(n)&&n.forEach(function(C,E){s.set(E,qn(C,t,e,E,n,o))});var F=d?h?Di:Oi:h?Cn:cn,R=_?i:F(n);return Un(R||n,function(C,E){R&&(E=C,C=n[E]),xe(s,E,qn(C,t,e,E,n,o))}),s}function bl(n){var t=cn(n);return function(e){return uf(e,n,t)}}function uf(n,t,e){var r=e.length;if(n==null)return!r;for(n=$(n);r--;){var u=e[r],o=t[u],s=n[u];if(s===i&&!(u in n)||!o(s))return!1}return!0}function ff(n,t,e){if(typeof n!="function")throw new Nn(y);return Ce(function(){n.apply(i,e)},t)}function ye(n,t,e,r){var u=-1,o=Ke,s=!0,a=n.length,h=[],d=t.length;if(!a)return h;e&&(t=Z(t,Rn(e))),r?(o=ni,s=!1):t.length>=m&&(o=pe,s=!1,t=new Ut(t));n:for(;++uu?0:u+e),r=r===i||r>u?u:b(r),r<0&&(r+=u),r=e>r?0:Fo(r);e0&&e(a)?t>1?vn(a,t-1,e,r,u):wt(u,a):r||(u[u.length]=a)}return u}var di=Df(),af=Df(!0);function et(n,t){return n&&di(n,t,cn)}function _i(n,t){return n&&af(n,t,cn)}function lr(n,t){return yt(t,function(e){return pt(n[e])})}function Gt(n,t){t=It(t,n);for(var e=0,r=t.length;n!=null&&et}function El(n,t){return n!=null&&G.call(n,t)}function Ol(n,t){return n!=null&&t in $(n)}function Dl(n,t,e){return n>=mn(t,e)&&n=120&&_.length>=120)?new Ut(s&&_):i}_=n[0];var v=-1,x=a[0];n:for(;++v-1;)a!==n&&tr.call(a,h,1),tr.call(n,h,1);return n}function yf(n,t){for(var e=n?t.length:0,r=e-1;e--;){var u=t[e];if(e==r||u!==o){var o=u;ht(u)?tr.call(n,u,1):Ci(n,u)}}return n}function Si(n,t){return n+ir(ju()*(t-n+1))}function Yl(n,t,e,r){for(var u=-1,o=sn(rr((t-n)/(e||1)),0),s=p(o);o--;)s[r?o:++u]=n,n+=e;return s}function Ti(n,t){var e="";if(!n||t<1||t>Yn)return e;do t%2&&(e+=n),t=ir(t/2),t&&(n+=n);while(t);return e}function L(n,t){return qi(Jf(n,t,In),n+"")}function Zl(n){return ef(fe(n))}function Xl(n,t){var e=fe(n);return wr(e,Nt(t,0,e.length))}function Se(n,t,e,r){if(!X(n))return n;t=It(t,n);for(var u=-1,o=t.length,s=o-1,a=n;a!=null&&++uu?0:u+t),e=e>u?u:e,e<0&&(e+=u),u=t>e?0:e-t>>>0,t>>>=0;for(var o=p(u);++r>>1,s=n[o];s!==null&&!En(s)&&(e?s<=t:s=m){var d=t?null:ac(n);if(d)return Ye(d);s=!1,u=pe,h=new Ut}else h=t?[]:a;n:for(;++r=r?n:$n(n,t,e)}var If=Ga||function(n){return ln.clearTimeout(n)};function Mf(n,t){if(t)return n.slice();var e=n.length,r=Zu?Zu(e):new n.constructor(e);return n.copy(r),r}function Ri(n){var t=new n.constructor(n.byteLength);return new je(t).set(new je(n)),t}function nc(n,t){var e=t?Ri(n.buffer):n.buffer;return new n.constructor(e,n.byteOffset,n.byteLength)}function tc(n){var t=new n.constructor(n.source,lu.exec(n));return t.lastIndex=n.lastIndex,t}function ec(n){return me?$(me.call(n)):{}}function bf(n,t){var e=t?Ri(n.buffer):n.buffer;return new n.constructor(e,n.byteOffset,n.length)}function Rf(n,t){if(n!==t){var e=n!==i,r=n===null,u=n===n,o=En(n),s=t!==i,a=t===null,h=t===t,d=En(t);if(!a&&!d&&!o&&n>t||o&&s&&h&&!a&&!d||r&&s&&h||!e&&h||!u)return 1;if(!r&&!o&&!d&&n=a)return h;var d=e[r];return h*(d=="desc"?-1:1)}}return n.index-t.index}function Lf(n,t,e,r){for(var u=-1,o=n.length,s=e.length,a=-1,h=t.length,d=sn(o-s,0),_=p(h+d),v=!r;++a1?e[u-1]:i,s=u>2?e[2]:i;for(o=n.length>3&&typeof o=="function"?(u--,o):i,s&&An(e[0],e[1],s)&&(o=u<3?i:o,u=1),t=$(t);++r-1?u[o?t[s]:s]:i}}function Wf(n){return ct(function(t){var e=t.length,r=e,u=Gn.prototype.thru;for(n&&t.reverse();r--;){var o=t[r];if(typeof o!="function")throw new Nn(y);if(u&&!s&&xr(o)=="wrapper")var s=new Gn([],!0)}for(r=s?r:e;++r1&&P.reverse(),_&&ha))return!1;var d=o.get(n),_=o.get(t);if(d&&_)return d==t&&_==n;var v=-1,x=!0,S=e&Pn?new Ut:i;for(o.set(n,t),o.set(t,n);++v1?"& ":"")+t[r],t=t.join(e>2?", ":" "),n.replace(ys,`{\n/* [wrapped with `+t+`] */\n`)}function xc(n){return M(n)||kt(n)||!!(Qu&&n&&n[Qu])}function ht(n,t){var e=typeof n;return t=t==null?Yn:t,!!t&&(e=="number"||e!="symbol"&&Ls.test(n))&&n>-1&&n%1==0&&n0){if(++t>=Kt)return arguments[0]}else t=0;return n.apply(i,arguments)}}function wr(n,t){var e=-1,r=n.length,u=r-1;for(t=t===i?r:t;++e1?n[t-1]:i;return e=typeof e=="function"?(n.pop(),e):i,so(n,e)});function ao(n){var t=f(n);return t.__chain__=!0,t}function Rh(n,t){return t(n),n}function Ar(n,t){return t(n)}var Lh=ct(function(n){var t=n.length,e=t?n[0]:0,r=this.__wrapped__,u=function(o){return gi(o,n)};return t>1||this.__actions__.length||!(r instanceof D)||!ht(e)?this.thru(u):(r=r.slice(e,+e+(t?1:0)),r.__actions__.push({func:Ar,args:[u],thisArg:i}),new Gn(r,this.__chain__).thru(function(o){return t&&!o.length&&o.push(i),o}))});function Eh(){return ao(this)}function Oh(){return new Gn(this.value(),this.__chain__)}function Dh(){this.__values__===i&&(this.__values__=To(this.value()));var n=this.__index__>=this.__values__.length,t=n?i:this.__values__[this.__index__++];return{done:n,value:t}}function Ph(){return this}function Bh(n){for(var t,e=this;e instanceof or;){var r=eo(e);r.__index__=0,r.__values__=i,t?u.__wrapped__=r:t=r;var u=r;e=e.__wrapped__}return u.__wrapped__=n,t}function Wh(){var n=this.__wrapped__;if(n instanceof D){var t=n;return this.__actions__.length&&(t=new D(this)),t=t.reverse(),t.__actions__.push({func:Ar,args:[$i],thisArg:i}),new Gn(t,this.__chain__)}return this.thru($i)}function Uh(){return Ff(this.__wrapped__,this.__actions__)}var Nh=gr(function(n,t,e){G.call(n,e)?++n[e]:at(n,e,1)});function Gh(n,t,e){var r=M(n)?Wu:Rl;return e&&An(n,t,e)&&(t=i),r(n,T(t,3))}function qh(n,t){var e=M(n)?yt:sf;return e(n,T(t,3))}var $h=Bf(ro),kh=Bf(io);function Hh(n,t){return vn(Sr(n,t),1)}function Kh(n,t){return vn(Sr(n,t),nt)}function zh(n,t,e){return e=e===i?1:b(e),vn(Sr(n,t),e)}function lo(n,t){var e=M(n)?Un:Ft;return e(n,T(t,3))}function co(n,t){var e=M(n)?ca:of;return e(n,T(t,3))}var Yh=gr(function(n,t,e){G.call(n,e)?n[e].push(t):at(n,e,[t])});function Zh(n,t,e,r){n=Fn(n)?n:fe(n),e=e&&!r?b(e):0;var u=n.length;return e<0&&(e=sn(u+e,0)),Mr(n)?e<=u&&n.indexOf(t,e)>-1:!!u&&Xt(n,t,e)>-1}var Xh=L(function(n,t,e){var r=-1,u=typeof t=="function",o=Fn(n)?p(n.length):[];return Ft(n,function(s){o[++r]=u?bn(t,s,e):we(s,t,e)}),o}),Jh=gr(function(n,t,e){at(n,e,t)});function Sr(n,t){var e=M(n)?Z:gf;return e(n,T(t,3))}function Qh(n,t,e,r){return n==null?[]:(M(t)||(t=t==null?[]:[t]),e=r?i:e,M(e)||(e=e==null?[]:[e]),mf(n,t,e))}var Vh=gr(function(n,t,e){n[e?0:1].push(t)},function(){return[[],[]]});function jh(n,t,e){var r=M(n)?ti:qu,u=arguments.length<3;return r(n,T(t,4),e,u,Ft)}function np(n,t,e){var r=M(n)?ha:qu,u=arguments.length<3;return r(n,T(t,4),e,u,of)}function tp(n,t){var e=M(n)?yt:sf;return e(n,Cr(T(t,3)))}function ep(n){var t=M(n)?ef:Zl;return t(n)}function rp(n,t,e){(e?An(n,t,e):t===i)?t=1:t=b(t);var r=M(n)?Fl:Xl;return r(n,t)}function ip(n){var t=M(n)?Cl:Ql;return t(n)}function up(n){if(n==null)return 0;if(Fn(n))return Mr(n)?Qt(n):n.length;var t=xn(n);return t==K||t==Xn?n.size:yi(n).length}function fp(n,t,e){var r=M(n)?ei:Vl;return e&&An(n,t,e)&&(t=i),r(n,T(t,3))}var op=L(function(n,t){if(n==null)return[];var e=t.length;return e>1&&An(n,t[0],t[1])?t=[]:e>2&&An(t[0],t[1],t[2])&&(t=[t[0]]),mf(n,vn(t,1),[])}),Tr=qa||function(){return ln.Date.now()};function sp(n,t){if(typeof t!="function")throw new Nn(y);return n=b(n),function(){if(--n<1)return t.apply(this,arguments)}}function ho(n,t,e){return t=e?i:t,t=n&&t==null?n.length:t,lt(n,yn,i,i,i,i,t)}function po(n,t){var e;if(typeof t!="function")throw new Nn(y);return n=b(n),function(){return--n>0&&(e=t.apply(this,arguments)),n<=1&&(t=i),e}}var Hi=L(function(n,t,e){var r=nn;if(e.length){var u=At(e,ie(Hi));r|=pn}return lt(n,r,t,e,u)}),go=L(function(n,t,e){var r=nn|q;if(e.length){var u=At(e,ie(go));r|=pn}return lt(t,r,n,e,u)});function _o(n,t,e){t=e?i:t;var r=lt(n,hn,i,i,i,i,i,t);return r.placeholder=_o.placeholder,r}function vo(n,t,e){t=e?i:t;var r=lt(n,Bn,i,i,i,i,i,t);return r.placeholder=vo.placeholder,r}function mo(n,t,e){var r,u,o,s,a,h,d=0,_=!1,v=!1,x=!0;if(typeof n!="function")throw new Nn(y);t=Hn(t)||0,X(e)&&(_=!!e.leading,v="maxWait"in e,o=v?sn(Hn(e.maxWait)||0,t):o,x="trailing"in e?!!e.trailing:x);function S(rn){var jn=r,dt=u;return r=u=i,d=rn,s=n.apply(dt,jn),s}function F(rn){return d=rn,a=Ce(E,t),_?S(rn):s}function R(rn){var jn=rn-h,dt=rn-d,Wo=t-jn;return v?mn(Wo,o-dt):Wo}function C(rn){var jn=rn-h,dt=rn-d;return h===i||jn>=t||jn<0||v&&dt>=o}function E(){var rn=Tr();if(C(rn))return P(rn);a=Ce(E,R(rn))}function P(rn){return a=i,x&&r?S(rn):(r=u=i,s)}function On(){a!==i&&If(a),d=0,r=h=u=a=i}function Sn(){return a===i?s:P(Tr())}function Dn(){var rn=Tr(),jn=C(rn);if(r=arguments,u=this,h=rn,jn){if(a===i)return F(h);if(v)return If(a),a=Ce(E,t),S(h)}return a===i&&(a=Ce(E,t)),s}return Dn.cancel=On,Dn.flush=Sn,Dn}var ap=L(function(n,t){return ff(n,1,t)}),lp=L(function(n,t,e){return ff(n,Hn(t)||0,e)});function cp(n){return lt(n,dn)}function Fr(n,t){if(typeof n!="function"||t!=null&&typeof t!="function")throw new Nn(y);var e=function(){var r=arguments,u=t?t.apply(this,r):r[0],o=e.cache;if(o.has(u))return o.get(u);var s=n.apply(this,r);return e.cache=o.set(u,s)||o,s};return e.cache=new(Fr.Cache||st),e}Fr.Cache=st;function Cr(n){if(typeof n!="function")throw new Nn(y);return function(){var t=arguments;switch(t.length){case 0:return!n.call(this);case 1:return!n.call(this,t[0]);case 2:return!n.call(this,t[0],t[1]);case 3:return!n.call(this,t[0],t[1],t[2])}return!n.apply(this,t)}}function hp(n){return po(2,n)}var pp=jl(function(n,t){t=t.length==1&&M(t[0])?Z(t[0],Rn(T())):Z(vn(t,1),Rn(T()));var e=t.length;return L(function(r){for(var u=-1,o=mn(r.length,e);++u=t}),kt=cf(function(){return arguments}())?cf:function(n){return Q(n)&&G.call(n,"callee")&&!Ju.call(n,"callee")},M=p.isArray,Mp=Lu?Rn(Lu):Bl;function Fn(n){return n!=null&&Ir(n.length)&&!pt(n)}function en(n){return Q(n)&&Fn(n)}function bp(n){return n===!0||n===!1||Q(n)&&wn(n)==mt}var bt=ka||eu,Rp=Eu?Rn(Eu):Wl;function Lp(n){return Q(n)&&n.nodeType===1&&!Ie(n)}function Ep(n){if(n==null)return!0;if(Fn(n)&&(M(n)||typeof n=="string"||typeof n.splice=="function"||bt(n)||ue(n)||kt(n)))return!n.length;var t=xn(n);if(t==K||t==Xn)return!n.size;if(Fe(n))return!yi(n).length;for(var e in n)if(G.call(n,e))return!1;return!0}function Op(n,t){return Ae(n,t)}function Dp(n,t,e){e=typeof e=="function"?e:i;var r=e?e(n,t):i;return r===i?Ae(n,t,i,e):!!r}function zi(n){if(!Q(n))return!1;var t=wn(n);return t==k||t==Ue||typeof n.message=="string"&&typeof n.name=="string"&&!Ie(n)}function Pp(n){return typeof n=="number"&&Vu(n)}function pt(n){if(!X(n))return!1;var t=wn(n);return t==tn||t==un||t==We||t==zt}function yo(n){return typeof n=="number"&&n==b(n)}function Ir(n){return typeof n=="number"&&n>-1&&n%1==0&&n<=Yn}function X(n){var t=typeof n;return n!=null&&(t=="object"||t=="function")}function Q(n){return n!=null&&typeof n=="object"}var wo=Ou?Rn(Ou):Nl;function Bp(n,t){return n===t||xi(n,t,Bi(t))}function Wp(n,t,e){return e=typeof e=="function"?e:i,xi(n,t,Bi(t),e)}function Up(n){return Ao(n)&&n!=+n}function Np(n){if(Ac(n))throw new I(w);return hf(n)}function Gp(n){return n===null}function qp(n){return n==null}function Ao(n){return typeof n=="number"||Q(n)&&wn(n)==tt}function Ie(n){if(!Q(n)||wn(n)!=Zn)return!1;var t=nr(n);if(t===null)return!0;var e=G.call(t,"constructor")&&t.constructor;return typeof e=="function"&&e instanceof e&&Je.call(e)==Wa}var Yi=Du?Rn(Du):Gl;function $p(n){return yo(n)&&n>=-Yn&&n<=Yn}var So=Pu?Rn(Pu):ql;function Mr(n){return typeof n=="string"||!M(n)&&Q(n)&&wn(n)==le}function En(n){return typeof n=="symbol"||Q(n)&&wn(n)==qe}var ue=Bu?Rn(Bu):$l;function kp(n){return n===i}function Hp(n){return Q(n)&&xn(n)==ce}function Kp(n){return Q(n)&&wn(n)==os}var zp=mr(wi),Yp=mr(function(n,t){return n<=t});function To(n){if(!n)return[];if(Fn(n))return Mr(n)?Jn(n):Tn(n);if(ge&&n[ge])return Fa(n[ge]());var t=xn(n),e=t==K?si:t==Xn?Ye:fe;return e(n)}function gt(n){if(!n)return n===0?n:0;if(n=Hn(n),n===nt||n===-nt){var t=n<0?-1:1;return t*Oe}return n===n?n:0}function b(n){var t=gt(n),e=t%1;return t===t?e?t-e:t:0}function Fo(n){return n?Nt(b(n),0,Mn):0}function Hn(n){if(typeof n=="number")return n;if(En(n))return Ot;if(X(n)){var t=typeof n.valueOf=="function"?n.valueOf():n;n=X(t)?t+"":t}if(typeof n!="string")return n===0?n:+n;n=$u(n);var e=Ms.test(n);return e||Rs.test(n)?sa(n.slice(2),e?2:8):Is.test(n)?Ot:+n}function Co(n){return rt(n,Cn(n))}function Zp(n){return n?Nt(b(n),-Yn,Yn):n===0?n:0}function N(n){return n==null?"":Ln(n)}var Xp=ee(function(n,t){if(Fe(t)||Fn(t)){rt(t,cn(t),n);return}for(var e in t)G.call(t,e)&&xe(n,e,t[e])}),Io=ee(function(n,t){rt(t,Cn(t),n)}),br=ee(function(n,t,e,r){rt(t,Cn(t),n,r)}),Jp=ee(function(n,t,e,r){rt(t,cn(t),n,r)}),Qp=ct(gi);function Vp(n,t){var e=te(n);return t==null?e:rf(e,t)}var jp=L(function(n,t){n=$(n);var e=-1,r=t.length,u=r>2?t[2]:i;for(u&&An(t[0],t[1],u)&&(r=1);++e1),o}),rt(n,Di(n),e),r&&(e=qn(e,B|an|j,lc));for(var u=t.length;u--;)Ci(e,t[u]);return e});function vg(n,t){return bo(n,Cr(T(t)))}var mg=ct(function(n,t){return n==null?{}:Kl(n,t)});function bo(n,t){if(n==null)return{};var e=Z(Di(n),function(r){return[r]});return t=T(t),xf(n,e,function(r,u){return t(r,u[0])})}function xg(n,t,e){t=It(t,n);var r=-1,u=t.length;for(u||(u=1,n=i);++rt){var r=n;n=t,t=r}if(e||n%1||t%1){var u=ju();return mn(n+u*(t-n+oa("1e-"+((u+"").length-1))),t)}return Si(n,t)}var Rg=re(function(n,t,e){return t=t.toLowerCase(),n+(e?Eo(t):t)});function Eo(n){return Ji(N(n).toLowerCase())}function Oo(n){return n=N(n),n&&n.replace(Es,ya).replace(Qs,"")}function Lg(n,t,e){n=N(n),t=Ln(t);var r=n.length;e=e===i?r:Nt(b(e),0,r);var u=e;return e-=t.length,e>=0&&n.slice(e,u)==t}function Eg(n){return n=N(n),n&&hs.test(n)?n.replace(su,wa):n}function Og(n){return n=N(n),n&&ms.test(n)?n.replace(Kr,"\\\\$&"):n}var Dg=re(function(n,t,e){return n+(e?"-":"")+t.toLowerCase()}),Pg=re(function(n,t,e){return n+(e?" ":"")+t.toLowerCase()}),Bg=Pf("toLowerCase");function Wg(n,t,e){n=N(n),t=b(t);var r=t?Qt(n):0;if(!t||r>=t)return n;var u=(t-r)/2;return vr(ir(u),e)+n+vr(rr(u),e)}function Ug(n,t,e){n=N(n),t=b(t);var r=t?Qt(n):0;return t&&r>>0,e?(n=N(n),n&&(typeof t=="string"||t!=null&&!Yi(t))&&(t=Ln(t),!t&&Jt(n))?Mt(Jn(n),0,e):n.split(t,e)):[]}var Kg=re(function(n,t,e){return n+(e?" ":"")+Ji(t)});function zg(n,t,e){return n=N(n),e=e==null?0:Nt(b(e),0,n.length),t=Ln(t),n.slice(e,e+t.length)==t}function Yg(n,t,e){var r=f.templateSettings;e&&An(n,t,e)&&(t=i),n=N(n),t=br({},t,r,$f);var u=br({},t.imports,r.imports,$f),o=cn(u),s=oi(u,o),a,h,d=0,_=t.interpolate||$e,v="__p += \'",x=ai((t.escape||$e).source+"|"+_.source+"|"+(_===au?Cs:$e).source+"|"+(t.evaluate||$e).source+"|$","g"),S="//# sourceURL="+(G.call(t,"sourceURL")?(t.sourceURL+"").replace(/\\s/g," "):"lodash.templateSources["+ ++ea+"]")+`\n`;n.replace(x,function(C,E,P,On,Sn,Dn){return P||(P=On),v+=n.slice(d,Dn).replace(Os,Aa),E&&(a=!0,v+=`\' +\n__e(`+E+`) +\n\'`),Sn&&(h=!0,v+=`\';\n`+Sn+`;\n__p += \'`),P&&(v+=`\' +\n((__t = (`+P+`)) == null ? \'\' : __t) +\n\'`),d=Dn+C.length,C}),v+=`\';\n`;var F=G.call(t,"variable")&&t.variable;if(!F)v=`with (obj) {\n`+v+`\n}\n`;else if(Ts.test(F))throw new I(O);v=(h?v.replace(ss,""):v).replace(as,"$1").replace(ls,"$1;"),v="function("+(F||"obj")+`) {\n`+(F?"":`obj || (obj = {});\n`)+"var __t, __p = \'\'"+(a?", __e = _.escape":"")+(h?`, __j = Array.prototype.join;\nfunction print() { __p += __j.call(arguments, \'\') }\n`:`;\n`)+v+`return __p\n}`;var R=Po(function(){return U(o,S+"return "+v).apply(i,s)});if(R.source=v,zi(R))throw R;return R}function Zg(n){return N(n).toLowerCase()}function Xg(n){return N(n).toUpperCase()}function Jg(n,t,e){if(n=N(n),n&&(e||t===i))return $u(n);if(!n||!(t=Ln(t)))return n;var r=Jn(n),u=Jn(t),o=ku(r,u),s=Hu(r,u)+1;return Mt(r,o,s).join("")}function Qg(n,t,e){if(n=N(n),n&&(e||t===i))return n.slice(0,zu(n)+1);if(!n||!(t=Ln(t)))return n;var r=Jn(n),u=Hu(r,Jn(t))+1;return Mt(r,0,u).join("")}function Vg(n,t,e){if(n=N(n),n&&(e||t===i))return n.replace(zr,"");if(!n||!(t=Ln(t)))return n;var r=Jn(n),u=ku(r,Jn(t));return Mt(r,u).join("")}function jg(n,t){var e=_n,r=Kn;if(X(t)){var u="separator"in t?t.separator:u;e="length"in t?b(t.length):e,r="omission"in t?Ln(t.omission):r}n=N(n);var o=n.length;if(Jt(n)){var s=Jn(n);o=s.length}if(e>=o)return n;var a=e-Qt(r);if(a<1)return r;var h=s?Mt(s,0,a).join(""):n.slice(0,a);if(u===i)return h+r;if(s&&(a+=h.length-a),Yi(u)){if(n.slice(a).search(u)){var d,_=h;for(u.global||(u=ai(u.source,N(lu.exec(u))+"g")),u.lastIndex=0;d=u.exec(_);)var v=d.index;h=h.slice(0,v===i?a:v)}}else if(n.indexOf(Ln(u),a)!=a){var x=h.lastIndexOf(u);x>-1&&(h=h.slice(0,x))}return h+r}function nd(n){return n=N(n),n&&cs.test(n)?n.replace(ou,ba):n}var td=re(function(n,t,e){return n+(e?" ":"")+t.toUpperCase()}),Ji=Pf("toUpperCase");function Do(n,t,e){return n=N(n),t=e?i:t,t===i?Ta(n)?Ea(n):da(n):n.match(t)||[]}var Po=L(function(n,t){try{return bn(n,i,t)}catch(e){return zi(e)?e:new I(e)}}),ed=ct(function(n,t){return Un(t,function(e){e=it(e),at(n,e,Hi(n[e],n))}),n});function rd(n){var t=n==null?0:n.length,e=T();return n=t?Z(n,function(r){if(typeof r[1]!="function")throw new Nn(y);return[e(r[0]),r[1]]}):[],L(function(r){for(var u=-1;++uYn)return[];var e=Mn,r=mn(n,Mn);t=T(t),n-=Mn;for(var u=fi(r,t);++e0||t<0)?new D(e):(n<0?e=e.takeRight(-n):n&&(e=e.drop(n)),t!==i&&(t=b(t),e=t<0?e.dropRight(-t):e.take(t-n)),e)},D.prototype.takeRightWhile=function(n){return this.reverse().takeWhile(n).reverse()},D.prototype.toArray=function(){return this.take(Mn)},et(D.prototype,function(n,t){var e=/^(?:filter|find|map|reject)|While$/.test(t),r=/^(?:head|last)$/.test(t),u=f[r?"take"+(t=="last"?"Right":""):t],o=r||/^find/.test(t);!u||(f.prototype[t]=function(){var s=this.__wrapped__,a=r?[1]:arguments,h=s instanceof D,d=a[0],_=h||M(s),v=function(E){var P=u.apply(f,wt([E],a));return r&&x?P[0]:P};_&&e&&typeof d=="function"&&d.length!=1&&(h=_=!1);var x=this.__chain__,S=!!this.__actions__.length,F=o&&!x,R=h&&!S;if(!o&&_){s=R?s:new D(this);var C=n.apply(s,a);return C.__actions__.push({func:Ar,args:[v],thisArg:i}),new Gn(C,x)}return F&&R?n.apply(this,a):(C=this.thru(v),F?r?C.value()[0]:C.value():C)})}),Un(["pop","push","shift","sort","splice","unshift"],function(n){var t=Ze[n],e=/^(?:push|sort|unshift)$/.test(n)?"tap":"thru",r=/^(?:pop|shift)$/.test(n);f.prototype[n]=function(){var u=arguments;if(r&&!this.__chain__){var o=this.value();return t.apply(M(o)?o:[],u)}return this[e](function(s){return t.apply(M(s)?s:[],u)})}}),et(D.prototype,function(n,t){var e=f[t];if(e){var r=e.name+"";G.call(ne,r)||(ne[r]=[]),ne[r].push({name:t,func:e})}}),ne[dr(i,q).name]=[{name:"wrapper",func:i}],D.prototype.clone=nl,D.prototype.reverse=tl,D.prototype.value=el,f.prototype.at=Lh,f.prototype.chain=Eh,f.prototype.commit=Oh,f.prototype.next=Dh,f.prototype.plant=Bh,f.prototype.reverse=Wh,f.prototype.toJSON=f.prototype.valueOf=f.prototype.value=Uh,f.prototype.first=f.prototype.head,ge&&(f.prototype[ge]=Ph),f},St=Oa();typeof define=="function"&&typeof define.amd=="object"&&define.amd?(ln._=St,define(function(){return St})):Pt?((Pt.exports=St)._=St,Vr._=St):ln._=St}).call(oe)});var Pr=Jd(qo());var _t=i=>[...new Set(i)],$o=i=>[...new Map(i.map(l=>[l.toLowerCase(),l])).values()];var ko=(i,l)=>{if(!i)return l?"ui//mk-ui-folder-solid":"ui//mk-ui-folder";switch(i){case"png":case"jpg":case"jpeg":case"svg":return"ui//mk-make-image";case"mov":case"webm":return"ui//mk-ui-video";case"canvas":return"ui//mk-ui-canvas";default:return l?"ui//mk-ui-file-solid":"ui//mk-ui-file"}};function Ho(i){return Array.isArray(i)?i:[]}var Ko=(i,l)=>l.indexOf(i)>0?l.indexOf(i):l.length;var Rr=i=>"spaces://"+i;var ut=i=>{var l;return(l=i==null?void 0:i.match(/(\\\\.|[^,])+/g))!=null?l:[]},Ht=i=>{if(!i)return"";let l=/\\[\\[(.*?)\\]\\]/g.exec(i),m=(l==null?void 0:l.length)>1?l[1].substring(0,Ko("|",l[1])):i;return m||i};var be=(i,l)=>{if(typeof i=="string"){if(/\\/\\/(\\S+?(?:jpe?g|png|gif|svg))/gi.test(i)||i.includes("unsplash"))return"image";if(/^\\d{4}-\\d{2}-\\d{2}$/.test(i))return"date";if(l=="tag"||l=="tags")return"tag";if(/\\[\\[.*?\\]\\]/.test(i))return"link"}else{if(typeof i=="number")return"number";if(typeof i=="boolean")return"boolean";if(i)if(Array.isArray(i)||typeof i=="string"&&i.indexOf(",")>-1){let m=Array.isArray(i)?i:[];if(typeof i=="string"&&i.indexOf(",")>-1&&(m=ut(i)),l=="tag"||l=="tags")return"tag-multi";if(m.length==1&&Array.isArray(m[0])&&m[0].length==1&&typeof m[0][0]=="string")return"link";let w=_t(m.map(y=>be(y,l)));return w.length==1&&w[0]=="link"?"link-multi":"option-multi"}else{if(i.isLuxonDateTime)return"date";if(i.isLuxonDuration)return"duration";if(i.type=="file")return"link";if(typeof i=="object"&&!Array.isArray(i)&&i!==null)return"object"}else return"unknown"}return"text"};var zo=i=>Object.keys(i!=null?i:{}).filter(l=>l!="position").filter(l=>l!="tag"&&l!="tags");var se=i=>i.join(","),Yo=i=>i.join(", ");var Lr=(i,l)=>{switch(be(l,i)){case"object":return JSON.stringify(l);case"number":return l.toString();case"boolean":return l?"true":"false";case"date":return l;case"duration":return Yo(Object.keys(l.values).reduce((w,y)=>[...w,...l.values[y]>0?[l.values[y]+" "+y]:[]],[]));case"option-multi":case"link-multi":return typeof l=="string"?Ht(l):se(l.map(w=>w?typeof w=="string"?Ht(w):w.path?w.path:Array.isArray(l)&&w.length==1&&Array.isArray(w[0])&&w[0].length==1&&typeof w[0][0]=="string"?w[0][0]:JSON.stringify(w):""));case"link":return Array.isArray(l)&&l.length==1&&Array.isArray(l[0])&&l[0].length==1&&typeof l[0][0]=="string"?l[0][0]:typeof l=="string"?Ht(l):l.path;case"text":case"tag":case"image":return l}return""};var Zo=i=>{switch(i){case"duration":return"text";case"unknown":return"text"}return i};var Er=(i,l)=>i==l,iu=(i,l)=>(i!=null?i:"").length==0,uu=(i,l)=>(i!=null?i:"").toLowerCase().includes((l!=null?l:"").toLowerCase()),Or=(i,l)=>parseFloat(i)>parseFloat(l),Dr=(i,l)=>parseInt(i)>parseInt(l),fu=(i,l)=>{let m=i?ut(i):[];return(l?ut(l):[]).some(y=>m.some(O=>O==y))},Xo=i=>{let l=new Date(`${i}T00:00`),m=new Date;return l.getMonth()===m.getMonth()&&l.getDate()===m.getDate()};var Re={isNotEmpty:{type:["text","file","link","link-multi","fileprop","image"],fn:(i,l)=>!iu(i,""),valueType:"none"},isEmpty:{type:["text","file","link","link-multi","fileprop","image"],fn:(i,l)=>iu(i,""),valueType:"none"},include:{fn:(i,l)=>uu(i,l),type:["text","file","link","link-multi","fileprop","image"],valueType:"text"},notInclude:{type:["text","file","link","link-multi","fileprop","image"],fn:(i,l)=>!uu(i,l),valueType:"text"},is:{type:["text","file","link","context","fileprop"],fn:(i,l)=>Er(i,l),valueType:"text"},isNot:{type:["text","file","link","context","fileprop"],fn:(i,l)=>!Er(i,l),valueType:"text"},equal:{type:["number"],fn:(i,l)=>Er(i,l),valueType:"number"},isGreatThan:{type:["number"],fn:(i,l)=>Or(i,l),valueType:"number"},isLessThan:{type:["number"],fn:(i,l)=>Dr(i,l),valueType:"number"},isLessThanOrEqual:{type:["number"],fn:(i,l)=>!Or(i,l),valueType:"number"},isGreatThanOrEqual:{type:["number"],fn:(i,l)=>!Dr(i,l),valueType:"number"},dateBefore:{type:["date","fileprop"],fn:(i,l)=>Dr(i,l),valueType:"date"},dateAfter:{type:["date","fileprop"],fn:(i,l)=>Or(i,l),valueType:"date"},isSameDateAsToday:{type:["date"],fn:(i,l)=>Xo(i,l),valueType:"none"},isAnyInList:{type:["option","context","option-multi","context-multi","tags-multi","tags"],fn:(i,l)=>fu(i,l),valueType:"list"},isNoneInList:{type:["option","context","option-multi","context-multi","tags-multi","tags"],fn:(i,l)=>!fu(i,l),valueType:"list"},isTrue:{type:["boolean"],fn:(i,l)=>i=="true",valueType:"none"},isFalse:{type:["boolean"],fn:(i,l)=>i!="true",valueType:"none"}};var Qd=(i,l)=>l.reduce((w,y)=>{let[O,J]=w,V=y.type=="fileprop"?Vo(J,y):y.type=="filemeta"?Qo(J,y):y.type=="frontmatter"?Jo(J,y):[],Y=J.filter(B=>!V.includes(B));return[[...O,...V],Y]},[[],i])[0],Vd=(i,l)=>l.reduce((m,w)=>w.type=="fileprop"?Vo(m,w):w.type=="filemeta"?Qo(m,w):w.type=="frontmatter"?Jo(m,w):[],i),Jo=(i,l)=>i.filter(m=>{let w=m.frontmatter;if(!w||!w[l.field])return!1;let y=Re[l.fn],O=!0;return y&&(O=y.fn(Lr(l.field,w[l.field]),l.value)),O}),Qo=(i,l)=>i.filter(m=>{let w="";l.field=="outlinks"?w=se(m.outlinks):l.field=="inlinks"?w=se(m.inlinks):l.field=="tags"&&(w=se(m.tags));let y=Re[l.fn],O=!0;return y&&(O=y.fn(w,l.value)),O}),Vo=(i,l)=>i.filter(m=>{if(["name","path","sticker","color","isFolder","extension","ctime","mtime","size","parent"].includes(l.field)){let y=Re[l.fn],O=!0;return y&&(O=y.fn(m[l.field],l.value)),O}return!0}),jo=(i,l)=>i.reduce((w,y)=>!w||y.filters.length==0?w:y.type=="any"?Qd([l],y.filters).length>0:Vd([l],y.filters).length>0,!0);var ns=(i,l,m)=>{if(!l)return{changed:!1,cache:{path:i.path,frames:{},schemas:[],listitems:{}}};let w=l.schemas,y=w.filter(Y=>Y.type=="frame").reduce((Y,B)=>{var an,j;return Lt(Rt({},Y),{[B.id]:{schema:B,cols:l.fields.filter(fn=>fn.schemaId==B.id),rows:(j=(an=l.tables[B.id])==null?void 0:an.rows)!=null?j:[]}})},{}),O=w.filter(Y=>Y.type=="listitem").reduce((Y,B)=>{var an,j;return Lt(Rt({},Y),{[B.id]:{schema:B,cols:l.fields.filter(fn=>fn.schemaId==B.id),rows:(j=(an=l.tables[B.id])==null?void 0:an.rows)!=null?j:[]}})},{}),J={path:i.path,frames:y,schemas:w,listitems:O},V=!0;return m&&Pr.default.isEqual(J,m)&&(V=!1),{changed:V,cache:J}},ts=(i,l,m)=>{var Pn,nn,q,vt,hn,Bn,pn,gn,yn;let w={};if(!l)return{changed:!1,cache:{cols:[],path:i.path,schemas:[],outlinks:[],contexts:[],files:[],tables:{},space:i,spaceMap:w}};let y=l.schemas.find(W=>W.primary=="true"),O={schema:y,cols:l.fields.filter(W=>W.schemaId==y.id),rows:(nn=(Pn=l.tables[y.id])==null?void 0:Pn.rows)!=null?nn:[]},J=l.schemas.filter(W=>W.type=="db").reduce((W,dn)=>{var _n,Kn;return Lt(Rt({},W),{[dn.id]:{schema:dn,cols:l.fields.filter(Kt=>Kt.schemaId==dn.id),rows:(Kn=(_n=l.tables[dn.id])==null?void 0:_n.rows)!=null?Kn:[]}})},{}),V=(vt=(q=O.cols)==null?void 0:q.filter(W=>W.type.startsWith("context")))!=null?vt:[],Y=(Bn=(hn=O.cols)==null?void 0:hn.filter(W=>W.type.startsWith("link")))!=null?Bn:[],B=_t(V.map(W=>W.value));V.forEach(W=>{w[W.name]={},O.rows.forEach(dn=>{ut(dn[W.name]).forEach(_n=>{var Kn;return w[W.name][_n]=[...(Kn=w[W.name][_n])!=null?Kn:[],dn.File]})})});let an=_t(O.rows.reduce((W,dn)=>_t([...W,...[...V,...Y].flatMap(_n=>ut(dn[_n.name]).map(Kn=>Ht(Kn)))]),[])),j={cols:l.fields.filter(W=>W.schemaId==y.id),path:i.path,contexts:B,outlinks:an,files:(yn=(gn=(pn=J.files)==null?void 0:pn.rows)==null?void 0:gn.map(W=>W.File))!=null?yn:[],tables:J,schemas:l.schemas,space:i,spaceMap:w},fn=!0;return m&&Pr.default.isEqual(j,m)&&(fn=!0),{changed:fn,cache:j}},jd=i=>{var m,w,y,O,J,V,Y,B,an,j,fn,Pn,nn;let l=[];return i&&i.tags&&l.push(...(w=(m=i.tags)==null?void 0:m.map(q=>q.tag))!=null?w:[]),i&&((y=i.frontmatter)==null?void 0:y.tags)&&l.push(...(typeof((O=i.frontmatter)==null?void 0:O.tags)=="string"?ut(i.frontmatter.tags.replace(/ /g,"")):Array.isArray((J=i.frontmatter)==null?void 0:J.tags)?(Y=(V=i.frontmatter)==null?void 0:V.tags)!=null?Y:[]:[]).filter(q=>typeof q=="string").map(q=>"#"+q)),i&&((B=i.frontmatter)==null?void 0:B.tag)&&l.push(...(typeof((an=i.frontmatter)==null?void 0:an.tag)=="string"?ut(i.frontmatter.tag.replace(/ /g,"")):Array.isArray((j=i.frontmatter)==null?void 0:j.tag)?(Pn=(fn=i.frontmatter)==null?void 0:fn.tag)!=null?Pn:[]:[]).filter(q=>typeof q=="string").map(q=>"#"+q)),(nn=_t(l))!=null?nn:[]};var es=(i,l,m,w,y,O,J,V,Y)=>{var Oe,Ot,Mn,De,Pe,Be,ft,Dt,We,mt,xt,Ue;let B={cacheType:"file",path:i.path,name:i.name,filename:i.filename};i.stat&&(B.ctime=i.stat.ctime,B.mtime=i.stat.mtime,B.size=i.stat.size,B.extension=i.extension);let an=[],j=jd(O),fn=(k,tn,un=new Set)=>{var tt,Ne;let K=[];for(let Zn of tn){let Ge=(Ne=(tt=k.get(Zn))==null?void 0:tt.contexts)!=null?Ne:[];for(let zt of Ge)un.has(zt)||(K.push(zt),un.add(zt),K.push(...fn(k,[Rr(zt)],un)))}return K};if(m.has(i.parent))for(let k of(Oe=m.get(i.parent).contexts)!=null?Oe:[])an.push(k);an.push(...j);let Pn=i.name,nn=i.name,q=(Ot=y==null?void 0:y.sticker)!=null?Ot:"",vt=(Mn=y==null?void 0:y.color)!=null?Mn:"",hn=(De=y==null?void 0:y.folder)!=null?De:"";hn=="true"&&(hn="");let Bn=i.parent,pn=i.isFolder,gn={},yn={},W=[],dn=[],_n=O==null?void 0:O.frontmatter;O!=null&&O.links&&dn.push(...O.links.map(k=>k.link));let Kn=V&&pn?V.folderNotePath:i.path;for(let k of Object.keys(J))Kn in J[k]&&W.push(k);let Kt="";if(_n){let tn=$o(zo(_n)).reduce((un,K)=>Lt(Rt({},un),{[K]:{name:K,type:Zo(be(_n[K],K))}}),{});Object.keys(tn).forEach(un=>{gn[un]=Lr(un,_n[un]),yn[un]=tn[un].type,tn[un].type.startsWith("link")&&dn.push(Ht(gn[un]))}),Kt=(Pe=gn[l.fmKeyBanner])!=null?Pe:"",gn[l.fmKeySticker]&&(q=_n[l.fmKeySticker]),gn[l.fmKeyColor]&&(vt=_n[l.fmKeyColor]),gn[l.fmKeyAlias]&&(nn=(Be=Ho(_n[l.fmKeyAlias]))==null?void 0:Be[0])}q=(q==null?void 0:q.length)>0?q:ko(B.extension,!1);let Et=Lt(Rt({},B),{name:Pn,tags:_t(an),alias:nn,fileTags:j,folderNote:V,sticker:q,color:vt,parent:Bn,banner:Kt,isFolder:pn,sortBy:hn,frontmatter:gn,frontmatterTypes:yn,inlinks:W,outlinks:dn}),zn=[],Le={};for(let k of an)zn.push(Rr(k));for(let[k,tn]of m){if(tn.space&&tn.space.folderPath==Bn&&tn.space.defPath!=i.path){zn.push(k);continue}if(((Dt=(ft=tn.metadata)==null?void 0:ft.filters)==null?void 0:Dt.length)>0&&jo(tn.metadata.filters,Et)){zn.push(k);continue}if(((mt=(We=tn.metadata)==null?void 0:We.links)==null?void 0:mt.length)>0&&((Ue=(xt=tn.metadata)==null?void 0:xt.links)!=null?Ue:[]).find(K=>K==Et.path)){zn.push(k);continue}}let Ee=fn(m,zn);zn.push(...Ee.map(k=>Rr(k))),zn.forEach(k=>{var tn,un,K;Le[k]=(K=(un=(tn=w.get(k))==null?void 0:tn.tables)==null?void 0:un.files)==null?void 0:K.rows.findIndex(tt=>tt.File==i.path)}),Et.tags.push(...Ee);let nt=V&&!pn?Lt(Rt({},Et),{spaces:[],contexts:[]}):Lt(Rt({},Et),{spaces:_t(zn),spaceRanks:Le}),Yn=!0;return Y&&Pr.default.isEqual(nt,Y)&&(Yn=!1),{changed:Yn,cache:nt}};function rs(i){let{file:l,settings:m,spacesCache:w,vaultItem:y,metadataCache:O,contextsCache:J,resolvedLinks:V,folderNote:Y,oldMetadata:B}=i;return es(l,m,w,J,y,O,V,Y,B)}function is(i){let{space:l,mdb:m,oldCache:w}=i;return ts(l,m,w)}function us(i){let{space:l,mdb:m,oldCache:w}=i;return ns(l,m,w)}var n_=self;n_.onmessage=async i=>{let{payload:l,job:m}=i.data,w;m.type=="file"?w=rs(l):m.type=="context"?w=is(l):m.type=="frames"&&(w=us(l));try{postMessage({job:m,result:w})}catch(y){console.log(y),postMessage({job:m,result:{$error:`Failed to index ${m.type} ${m.path}: ${y}`}})}};\n/**\n * @license\n * Lodash \n * Copyright OpenJS Foundation and other contributors \n * Released under MIT license \n * Based on Underscore.js 1.8.3 \n * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors\n */\n'); } // src/superstate/workers/manager.ts @@ -54802,7 +64468,7 @@ var Manager = class extends import_obsidian61.Component { this.reloadSet = /* @__PURE__ */ new Set(); this.callbacks = /* @__PURE__ */ new Map(); for (let index = 0; index < numWorkers; index++) { - let worker = new Worker2({ name: "Make.md Superstate Indexer " + (index + 1) }); + const worker = new Worker2({ name: "Make.md Superstate Indexer " + (index + 1) }); worker.onmessage = (evt) => this.finish(evt.data.job, evt.data.result, index); this.workers.push(worker); this.register(() => worker.terminate()); @@ -54811,7 +64477,7 @@ var Manager = class extends import_obsidian61.Component { } reload(jerb) { const jobKey = stringifyJob(jerb); - let promise = new Promise((resolve, reject) => { + const promise = new Promise((resolve, reject) => { var _a2; if (this.callbacks.has(jobKey)) (_a2 = this.callbacks.get(jobKey)) == null ? void 0 : _a2.push([resolve, reject]); @@ -54821,7 +64487,7 @@ var Manager = class extends import_obsidian61.Component { if (this.reloadSet.has(jobKey)) return promise; this.reloadSet.add(jobKey); - let workerId = this.nextAvailableWorker(); + const workerId = this.nextAvailableWorker(); if (workerId !== void 0) { this.send(jerb, workerId); } else { @@ -54829,27 +64495,27 @@ var Manager = class extends import_obsidian61.Component { } return promise; } - finish(jerb, data, index) { + finish(jerb, data2, index) { var _a2; const jobKey = stringifyJob(jerb); - let calls = [].concat((_a2 = this.callbacks.get(jobKey)) != null ? _a2 : []); + const calls = [].concat((_a2 = this.callbacks.get(jobKey)) != null ? _a2 : []); this.reloadSet.delete(jobKey); this.callbacks.delete(jobKey); this.busy[index] = false; - let job = this.reloadQueue.shift(); + const job = this.reloadQueue.shift(); if (job !== void 0) this.send(job, index); - if ("$error" in data) { - for (let [_9, reject] of calls) - reject(data["$error"]); + if ("$error" in data2) { + for (const [_12, reject] of calls) + reject(data2["$error"]); } else { - for (let [callback, _9] of calls) - callback(data); + for (const [callback, _12] of calls) + callback(data2); } } send(job, workerId) { if (job.type == "file") { - const file = tFileToAFile(getAbstractFileAtPath(app, job.path)); + const file = tFileToAFile(getAbstractFileAtPath(this.cache.plugin, job.path)); if (!file) return; const folderNote = this.cache.plugin.settings.enableFolderNote ? folderNoteCache(this.cache.plugin, file) : null; @@ -54859,11 +64525,11 @@ var Manager = class extends import_obsidian61.Component { payload: { file, settings: this.cache.plugin.settings, - contextsCache: this.cache.contextsIndex, spacesCache: this.cache.spacesIndex, + contextsCache: this.cache.contextsIndex, vaultItem: vaultItemForPath(this.cache.plugin, job.path), - metadataCache: app.metadataCache.getCache(metadataPath), - resolvedLinks: app.metadataCache.resolvedLinks, + metadataCache: this.cache.plugin.app.metadataCache.getCache(metadataPath), + resolvedLinks: this.cache.plugin.app.metadataCache.resolvedLinks, folderNote, oldMetadata: this.cache.filesIndex.get(job.path) } @@ -54871,71 +64537,80 @@ var Manager = class extends import_obsidian61.Component { this.busy[workerId] = true; } if (job.type == "context") { - const context = mdbContextByPath(this.cache.plugin, job.path); - if (!context) { + const space = spaceInfoByPath(this.cache.plugin, job.path); + if (!space || !space.path) { return; } - getMDBTable(this.cache.plugin, context, "files").then((mdbTable) => { + getContextMDB(this.cache.plugin, space).then((mdb) => { this.workers[workerId].postMessage({ job, payload: { - context, - mdbTable, + space, + mdb, oldCache: this.cache.contextsIndex.get(job.path) } }); this.busy[workerId] = true; }); } + if (job.type == "frames") { + const space = spaceInfoByPath(this.cache.plugin, job.path); + if (!space) { + return; + } + getFramesMDB(this.cache.plugin, space).then((mdb) => { + this.workers[workerId].postMessage({ + job, + payload: { + space, + mdb, + oldCache: this.cache.framesIndex.get(job.path) + } + }); + this.busy[workerId] = true; + }); + } } nextAvailableWorker() { - let index = this.busy.indexOf(false); + const index = this.busy.indexOf(false); return index == -1 ? void 0 : index; } }; // src/superstate/superstate.ts -var loadContexts = (plugin, spaces2) => { +var loadSpaces = (plugin) => { const getAllTagContextFiles = (plugin2) => { - var _a2; - const folder = plugin2.settings.tagContextFolder == "" ? app.vault.getRoot() : getAbstractFileAtPath( - app, - getFolderPathFromString(plugin2.settings.tagContextFolder) - ); - const allcontexts = (_a2 = folder == null ? void 0 : folder.children.filter( - (f4) => f4 instanceof import_obsidian62.TFile && f4.extension == "mdb" && f4.name.charAt(0) == "#" - ).map((f4) => tagContextFromTag(plugin2, tagPathToTag(f4.name)))) != null ? _a2 : []; - return allcontexts; - }; - const getAllSpaceContextFiles = (plugin2, spaces3) => { - var _a2; - const folder = plugin2.settings.tagContextFolder == "" ? app.vault.getRoot() : getAbstractFileAtPath( - app, - getFolderPathFromString(plugin2.settings.tagContextFolder) + var _a2, _b2; + const folder = plugin2.settings.spacesFolder == "" ? plugin2.app.vault.getRoot() : getAbstractFileAtPath( + plugin2, + getFolderPathFromString(plugin2, plugin2.settings.spacesFolder) ); - const allcontexts = (_a2 = folder == null ? void 0 : folder.children.filter( - (f4) => f4 instanceof import_obsidian62.TFile && f4.extension == "mdb" && spaces3.some((s5) => s5.name == f4.basename) - ).map((f4) => spaceContextFromSpace(plugin2, spaceContextPathFromName(f4.basename)))) != null ? _a2 : []; + const allcontexts = (_b2 = uniq([...Object.keys(plugin2.app.metadataCache.getTags()), ...(_a2 = folder == null ? void 0 : folder.children.filter( + (f4) => f4 instanceof import_obsidian62.TFolder && f4.name.charAt(0) == "#" + ).map((g4) => g4.name)) != null ? _a2 : []]).map((f4) => spaceFromTag(plugin2, tagPathToTag(f4)))) != null ? _b2 : []; return allcontexts; }; const getAllFolderContextFiles = (plugin2) => { - let files = []; - let rootFolder = app.vault.getRoot(); + const folders = [plugin2.app.vault.getRoot()]; + const rootFolder = plugin2.app.vault.getRoot(); function recursiveFx(folder) { - for (let child of folder.children) { + for (const child of folder.children) { if (child instanceof import_obsidian62.TFolder) { - let childFolder = child; - if (childFolder.children) - recursiveFx(childFolder); + if (!child.path.startsWith(plugin2.settings.spacesFolder + "/#")) { + const childFolder = child; + folders.push(child); + if (childFolder.children) + recursiveFx(childFolder); + } } - if (child instanceof import_obsidian62.TFile && child.basename == plugin2.settings.folderContextFile && child.path != "/") - files.push(child); } } recursiveFx(rootFolder); - return files.map((f4) => folderContextFromFolder(plugin2, f4.parent.path)); + return folders.map((f4) => spaceFromFolder(plugin2, f4.path)); }; - return [...getAllTagContextFiles(plugin), ...getAllFolderContextFiles(plugin), ...getAllSpaceContextFiles(plugin, spaces2)]; + const allTagSpaces = getAllTagContextFiles(plugin); + const allFolders = getAllFolderContextFiles(plugin); + return [...allTagSpaces, ...allFolders]; }; var Superstate = class extends import_obsidian62.Component { constructor(app2, indexVersion, onChange, plugin) { @@ -54943,12 +64618,9 @@ var Superstate = class extends import_obsidian62.Component { this.app = app2; this.indexVersion = indexVersion; this.onChange = onChange; - this.debounceSaveSpaceDatabase = (0, import_lodash10.debounce)( + this.debounceSaveSpaceDatabase = (0, import_lodash13.debounce)( (tables) => { - saveDBToPath(this.plugin, this.plugin.spacesDBPath, tables).then((f4) => { - this.updateSpaceLastUpdated(); - this.backupSpaceDB(true); - }); + saveDBToPath(this.plugin, this.plugin.spacesDBPath, tables); }, 1e3, { @@ -54958,131 +64630,178 @@ var Superstate = class extends import_obsidian62.Component { this.initialized = false; this.plugin = plugin; this.metadataCache = app2.metadataCache; + this.api = new API(plugin); this.filesIndex = /* @__PURE__ */ new Map(); this.spacesIndex = /* @__PURE__ */ new Map(); this.contextsIndex = /* @__PURE__ */ new Map(); + this.framesIndex = /* @__PURE__ */ new Map(); this.spacesMap = new IndexMap(); this.linksMap = new IndexMap(); this.tagsMap = new IndexMap(); - this.contextsMap = new IndexMap(); + this.superProperties = /* @__PURE__ */ new Map(); this.iconsCache = /* @__PURE__ */ new Map(); + this.fontsCache = /* @__PURE__ */ new Map(); this.contextStoreQueue = Promise.resolve(); + this.vaultQueue = Promise.resolve(); this.vaultDBCache = []; - this.spacesItemsDBCache = []; - this.spacesDBCache = []; - this.syncStatus = 0; this.persister = new LocalStorageCache(app2.appId || "shared", indexVersion); this.addChild(this.indexer = new Manager(2, this)); + this.loadSuperProperties(); } static create(app2, indexVersion, onChange, plugin) { return new Superstate(app2, indexVersion, onChange, plugin); } + loadSuperProperties() { + this.superProperties.set("$commands", { name: "Obsidian Commands", schemaId: "$super", type: "option" }); + this.superProperties.set("$links", { name: "Links", schemaId: "$super", type: "option" }); + } + valueForSuperproperty(superProperty, property) { + if (superProperty == "$commands") { + return { options: Object.values(this.plugin.app.commands.commands).map((f4) => ({ name: f4.name, value: f4.id })) }; + } else if (superProperty == "$links") { + return { options: getAllAbstractFilesInVault(this.plugin).map((f4) => ({ name: f4.name, value: f4.path })) }; + } else { + return parseFieldValue(property.value, property.type); + } + } async initializeIndex() { await Promise.race([new Promise((resolve) => setTimeout(resolve, 1e3)), this.loadFromCache()]); this.loadSpacesDatabaseFromDisk(); } + addToVaultQueue(operation) { + this.vaultQueue = this.vaultQueue.then(operation).catch(() => { + }); + } addToContextStoreQueue(operation) { this.contextStoreQueue = this.contextStoreQueue.then(operation).catch(() => { }); } - async resolveSpacesDatabaseSync() { - if (this.plugin.settings.spacesSyncLastUpdated.length > 0) { - const waitIfSpacesFileStillSyncing = async (timeout) => { - var _a2; - const incomingSpaceTime = parseInt(await app.vault.read(getAbstractFileAtPath(app, this.plugin.settings.spacesSyncLastUpdated))); - const currentSpaceTime = this.plugin.spacesDBLastModify; - const spaceFileTime = (_a2 = await app.vault.adapter.stat(this.plugin.spacesDBPath)) == null ? void 0 : _a2.mtime; - if (Math.floor(incomingSpaceTime / 1e3) != Math.floor(spaceFileTime / 1e3)) { - await sleep(timeout); - return false; - } - return true; + async migrate08(db) { + var _a2, _b2, _c2, _d2; + const currentSpaces = (_b2 = (_a2 = selectDB(db, "spaces")) == null ? void 0 : _a2.rows) != null ? _b2 : []; + const currentSpaceItems = (_d2 = (_c2 = selectDB(db, "spaceItems")) == null ? void 0 : _c2.rows) != null ? _d2 : []; + const oldSpaceDefToSpaceMetadata = (name, oldDef) => { + return { + links: currentSpaceItems.filter((s5) => s5.space == name).map((s5) => s5.path), + path: oldDef.type == "focus" && oldDef.folder.length > 0 ? oldDef.folder : null, + filters: oldDef.filters }; - const resolverFile = getAbstractFileAtPath(app, this.plugin.settings.spacesSyncLastUpdated); - if (!resolverFile) { - await this.updateSpaceLastUpdated(); - } else { - let counter = 0; - let spacesReady = await waitIfSpacesFileStillSyncing(500); - if (!spacesReady) { - this.syncStatus = 1; - this.broadcast("sync"); + }; + const homeSpaces = []; + const pinnedSpaces = this.plugin.settings.waypoints; + const promises = currentSpaces.map((f4) => { + const spaceIntermediary = oldSpaceDefToSpaceMetadata(f4.name, safelyParseJSON(f4.def)); + if (spaceIntermediary.path) { + const path = spaceIntermediary.path; + if (f4.pinned == "home") { + homeSpaces.push(path); + } else if (f4.pinned == "pinned") { + pinnedSpaces.push(path); } - while (!spacesReady && counter++ <= this.plugin.settings.spacesSyncTimeoutSeconds * 2) { - spacesReady = await waitIfSpacesFileStillSyncing(500); + return; + } else { + const path = `${this.plugin.settings.spacesFolder}/${f4.name}`; + if (f4.pinned == "home" && homeSpaces.some((g4) => g4 != path)) { + homeSpaces.push(path); + } else if (f4.pinned == "pinned" && pinnedSpaces.some((g4) => g4 != path)) { + pinnedSpaces.push(path); } - this.syncStatus = 0; - this.broadcast("sync"); - } - } - } - async loadSpacesDatabaseFromDisk() { - var _a2, _b2, _c2, _d2, _e2, _f; - if (this.plugin.settings.spacesEnabled) { - await this.resolveSpacesDatabaseSync(); - const db = await getDB(await this.plugin.sqlJS(), this.plugin.spacesDBPath); - const tables = dbResultsToDBTables( - db.exec( - "SELECT name FROM sqlite_schema WHERE type ='table' AND name NOT LIKE 'sqlite_%';" - ) - ); - if (tables.length == 0) { - initiateDB(db); - await saveDBToPath(this.plugin, this.plugin.spacesDBPath, { - vault: vaultSchema, - spaces: spaceSchema, - spaceItems: spaceItemsSchema - }).then((f4) => this.updateSpaceLastUpdated()); - } - this.vaultDBCache = (_b2 = (_a2 = selectDB(db, "vault")) == null ? void 0 : _a2.rows) != null ? _b2 : []; - this.spacesItemsDBCache = (_d2 = (_c2 = selectDB(db, "spaceItems")) == null ? void 0 : _c2.rows) != null ? _d2 : []; - this.spacesDBCache = (_f = (_e2 = selectDB(db, "spaces")) == null ? void 0 : _e2.rows) != null ? _f : []; - db.close(); - this.spacesDBLoaded = true; - this.spacesDBCache.forEach((f4) => this.reloadSpace(f4.name, false)); - if (!this.plugin.settings.precreateVaultSpace || this.spacesDBCache.length == 0) { - insertSpaceAtIndex( + if (this.spacesIndex.has(path)) + return; + return insertSpaceAtIndex( this.plugin, + this.plugin.settings.spacesFolder + "/" + f4.name, { - name: this.plugin.app.vault.getName(), - pinned: "home", - def: { type: "focus", folder: "/", filters: [] } - }, - this.spacesDBCache.length - ); - this.plugin.settings.precreateVaultSpace = true; - this.plugin.saveSettings(); + sort: parseSortStrat(f4.sort), + color: f4.color, + sticker: f4.sticker, + contexts: [], + filters: spaceIntermediary.filters, + links: ensureArray(spaceIntermediary.links).filter((f5) => f5) + } + ).then((f5) => { + }); } + }); + const spaceFolder = getAbstractFileAtPath(this.plugin, "Context"); + if (spaceFolder instanceof import_obsidian62.TFolder) { + promises.push(...spaceFolder.children.map((f4) => { + if (f4 instanceof import_obsidian62.TFile && f4.extension == "mdb") { + const folderPath = `${this.plugin.settings.spacesFolder}/${f4.basename}/.space`; + return this.plugin.app.vault.adapter.exists(folderPath).then((g4) => { + if (!g4) + return this.plugin.app.vault.createFolder(folderPath); + }).then((g4) => this.plugin.app.vault.rename(f4, folderPath + "/context.mdb")); + } + })); } - rebuildIndex(this.plugin, true); - } - async updateSpaceLastUpdated() { - if (this.plugin.settings.spacesSyncLastUpdated.length > 0) { - return app.vault.adapter.stat(this.plugin.spacesDBPath).then((f4) => { - if (f4) { - this.plugin.spacesDBLastModify = f4.mtime; - const resolverFile = getAbstractFileAtPath(app, this.plugin.settings.spacesSyncLastUpdated); - if (!resolverFile) { - return app.vault.create(this.plugin.settings.spacesSyncLastUpdated, f4.mtime.toString()).then((f5) => { - }); + const getAllFolders = (plugin) => { + const folders = [plugin.app.vault.getRoot()]; + const rootFolder = plugin.app.vault.getRoot(); + function recursiveFx(folder) { + for (const child of folder.children) { + if (!folder.path.startsWith(plugin.settings.spacesFolder)) { + if (child instanceof import_obsidian62.TFolder) { + const childFolder = child; + folders.push(child); + if (childFolder.children) + recursiveFx(childFolder); + } } - return app.vault.modify(getAbstractFileAtPath(app, this.plugin.settings.spacesSyncLastUpdated), f4.mtime.toString()); } + } + recursiveFx(rootFolder); + return folders.filter((f4) => f4.children.some((g4) => g4.name == "context.mdb")); + }; + promises.push(...getAllFolders(this.plugin).map((f4) => { + const folderPath = f4.path == "/" ? ".space" : `${f4.path}/.space`; + return this.plugin.app.vault.adapter.exists(folderPath).then((f5) => { + if (!f5) + return this.plugin.app.vault.createFolder(folderPath); + }).then((g4) => this.plugin.app.vault.rename(getAbstractFileAtPath(this.plugin, f4.path == "/" ? "context.mdb" : `${f4.path}/context.mdb`), folderPath + "/context.mdb")); + })); + await Promise.all(promises); + await insertSpaceAtIndex(this.plugin, this.plugin.settings.spacesFolder + "/Home", { + links: homeSpaces, + sticker: "lucide//home" + }); + this.plugin.settings.waypoints = [this.plugin.settings.spacesFolder + "/Home", "/", "spaces://$tags", ...pinnedSpaces]; + this.plugin.settings.activeView = "/"; + this.plugin.settings.autoMigration08 = true; + this.plugin.saveSettings(); + return; + } + async loadSpacesDatabaseFromDisk() { + var _a2, _b2; + const db = await getDB(this.plugin, await this.plugin.sqlJS(), this.plugin.spacesDBPath); + const tables = dbResultsToDBTables( + db.exec( + "SELECT name FROM sqlite_schema WHERE type ='table' AND name NOT LIKE 'sqlite_%';" + ) + ); + if (tables.length == 0) { + initiateDB(db); + await saveDBToPath(this.plugin, this.plugin.spacesDBPath, { + vault: vaultSchema }); + } else { + if (!this.plugin.settings.autoMigration08) { + await this.migrate08(db); + } } + this.vaultDBCache = (_b2 = (_a2 = selectDB(db, "vault")) == null ? void 0 : _a2.rows) != null ? _b2 : []; + db.close(); + this.spacesDBLoaded = true; + rebuildIndex(this.plugin, true); } async saveSpacesDatabaseToDisk(tables, save = true) { - if (await app.vault.adapter.exists((0, import_obsidian62.normalizePath)(this.plugin.spacesDBPath)) && !this.spacesDBLoaded) { + if (await this.plugin.app.vault.adapter.exists((0, import_obsidian62.normalizePath)(this.plugin.spacesDBPath)) && !this.spacesDBLoaded) { return; } this.spacesDBLoaded = true; if (tables.vault) this.vaultDBCache = tables.vault.rows; - if (tables.spaceItems) - this.spacesItemsDBCache = tables.spaceItems.rows; - if (tables.spaces) - this.spacesDBCache = tables.spaces.rows; - if (save && this.plugin.settings.spacesEnabled && this.syncStatus == 0) { + if (save && this.plugin.settings.spacesEnabled) { this.debounceSaveSpaceDatabase(tables); } } @@ -55091,33 +64810,74 @@ var Superstate = class extends import_obsidian62.Component { if (this.plugin.settings.spacesEnabled) await this.initializeSpaces(); await this.initializeContexts(); + await this.initializeFrames(); await this.initalizeFiles(); this.cleanContexts(); console.log(`Make.md Superstate: ${Date.now() - start} ms`); } async initializeSpaces() { this.spacesIndex = /* @__PURE__ */ new Map(); - const promises = this.spacesDBCache.map((f4) => this.reloadSpace(f4.name, true)); + this.spacesIndex.set(tagsSpace.path, tagsSpace); + const promises = loadSpaces(this.plugin).map((f4) => this.reloadSpace(f4, null, true)); + await Promise.all(promises); + } + getSpaceItems(spacePath, filesOnly) { + let items = []; + if (spacePath == "spaces://$tags") { + items = this.allSpaces().filter((f4) => f4.type == "tag").map((f4) => f4.path); + } else { + items = [...this.spacesMap.getInverse(spacePath)]; + } + return items.map((f4, i4) => { + var _a2, _b2, _c2, _d2; + const s5 = uriByString(this.plugin, f4); + const fileCache = this.filesIndex.get(f4); + if (filesOnly) { + if (s5.type != "folder" && s5.type != "file") + return null; + } + if (s5.type == "tag" || s5.type == "space" || s5.type == "folder" || s5.type == "vault") { + if (fileCache) { + return { + ...this.spacesIndex.get(f4), + rank: (_b2 = (_a2 = fileCache == null ? void 0 : fileCache.spaceRanks) == null ? void 0 : _a2[spacePath]) != null ? _b2 : i4 + }; + } + return this.spacesIndex.get(f4); + } + return { + ...fileCache, + rank: (_d2 = (_c2 = fileCache == null ? void 0 : fileCache.spaceRanks) == null ? void 0 : _c2[spacePath]) != null ? _d2 : i4 + }; + }).filter((f4) => f4); + } + async initializeFrames() { + const promises = this.allSpaces().filter((f4) => f4.type != "default").map((f4) => f4.space).map( + (l3) => this.reloadFrames(l3) + ); await Promise.all(promises); } async initializeContexts() { - const allContexts = loadContexts(this.plugin, this.allSpaces()); - const promises = allContexts.map((l3) => this.reloadContext(l3)); + const promises = this.allSpaces().filter((f4) => f4.type != "default").map((f4) => f4.space).map( + (l3) => this.reloadContext(l3) + ); await Promise.all(promises); } async cleanContexts() { this.contextsIndex.forEach((context) => { - const contextFiles = [...this.contextsMap.getInverse(context.info.contextPath)]; - const removeFiles = context.files.filter((f4) => !contextFiles.includes(f4)); - if (removeFiles.length > 0) - this.addToContextStoreQueue(() => removeFilesInContext(this.plugin, removeFiles, context.info).then((f4) => this.reloadContext(context.info))); + var _a2, _b2, _c2; + const contextFiles = [...this.spacesMap.getInverse(context.path)]; + const removeFiles = (_c2 = (_b2 = (_a2 = context.tables) == null ? void 0 : _a2["files"]) == null ? void 0 : _b2.rows.filter((f4) => !contextFiles.includes(f4.File))) != null ? _c2 : []; + if (removeFiles.length > 0) { + this.addToContextStoreQueue(() => removeFilesInContext(this.plugin, removeFiles.map((f4) => f4.File), this.spacesIndex.get(context.path).space).then((f4) => this.reloadSpaceByPath(context.path))); + } }); this.spacesIndex.forEach((space) => { - const removeFiles = [...this.spacesMap.getInverse(space.name)]; + const removeFiles = [...this.spacesMap.getInverse(space.path)]; }); } async loadFromCache() { - const allFiles = getAllAbstractFilesInVault(this.plugin, app); + const allFiles = getAllAbstractFilesInVault(this.plugin); if (this.plugin.settings.indexSVG) { const cacheIcons = allFiles.filter((f4) => f4 instanceof import_obsidian62.TFile && f4.extension == "svg").map((s5) => this.persister.load(s5.path, "icon").then((string) => { if ((string == null ? void 0 : string.length) > 0) @@ -55128,10 +64888,12 @@ var Superstate = class extends import_obsidian62.Component { const cachePromises = allFiles.map((file) => this.persister.load(file.path, "file").then((f4) => { if (!f4) return; + if (!excludeFilePredicate(this.plugin)(file)) { + return; + } const cache = parseFileCache(f4); this.filesIndex.set(file.path, cache); this.tagsMap.set(file.path, new Set(cache.tags)); - this.contextsMap.set(file.path, new Set(cache.contexts)); this.spacesMap.set(file.path, new Set(cache.spaces)); this.linksMap.set(file.path, new Set(cache.outlinks)); this.broadcast("file", "change", file.path); @@ -55140,7 +64902,7 @@ var Superstate = class extends import_obsidian62.Component { const allSpaces = this.plugin.settings.cachedSpaces; const cacheSpacePromises = allSpaces.map((s5) => this.persister.load(s5, "space").then((serializedSpace) => { const space = safelyParseJSON(serializedSpace); - if (space) { + if (space && space.type) { this.spacesIndex.set(s5, space); this.broadcast("space", "change", s5); } @@ -55149,29 +64911,27 @@ var Superstate = class extends import_obsidian62.Component { this.broadcast("vault"); } async initalizeFiles() { - const allFiles = getAllAbstractFilesInVault(this.plugin, app); + const allFiles = getAllAbstractFilesInVault(this.plugin); const promises = allFiles.map((l3) => this.reloadFile(l3, true)); await Promise.all(promises); this.broadcast("vault"); } async renameTag(tag, newTag) { - const contextCache = this.contextsIndex.get(tag); - const existingContext = this.contextsIndex.get(newTag); - if (existingContext) { - await this.reloadContext(existingContext.info); - this.tagsMap.getInverse(tag).forEach((file) => this.renameTagInFile(tag, newTag, getAbstractFileAtPath(app, file))); - } else { - this.contextsIndex.set(newTag, contextCache); - this.contextsIndex.delete(tag); - this.tagsMap.getInverse(tag).forEach((file) => this.renameTagInFile(tag, newTag, getAbstractFileAtPath(app, file))); - } - let allContextsWithTag = []; - for (let [contextPath, contextCache2] of this.contextsIndex) { - if (contextCache2.contexts.includes(tag) || contextCache2.defContexts.includes(tag)) { - allContextsWithTag.push(contextCache2.info); + await renameSpaceFolder(this.plugin, tag, newTag); + const oldPath = spacePathFromName(tag); + const newSpaceInfo = spaceFromTag(this.plugin, newTag); + await this.spaceRenamed(oldPath, newSpaceInfo); + this.broadcast("space", "rename", oldPath); + const allContextsWithTag = []; + for (const [contextPath, spaceCache] of this.spacesIndex) { + const contextCache = this.contextsIndex.get(contextPath); + if (contextCache == null ? void 0 : contextCache.contexts.includes(tag)) { + this.addToContextStoreQueue(() => renameTagInContexts(this.plugin, tag, newTag, allContextsWithTag)); + } + if (spaceCache.metadata.contexts.includes(tag)) { + saveSpaceCache(this.plugin, spaceCache.space, { ...spaceCache.metadata, contexts: spaceCache.metadata.contexts.map((f4) => f4 == tag ? newTag : f4) }); } } - this.addToContextStoreQueue(() => renameTagInContexts(this.plugin, tag, newTag, allContextsWithTag)); } renameTagInFile(tag, newTag, file) { let oldMetadata; @@ -55183,11 +64943,11 @@ var Superstate = class extends import_obsidian62.Component { ...oldMetadata, tags: oldMetadata.tags.map((f4) => f4 == tag ? newTag : f4), fileTags: oldMetadata.fileTags.map((f4) => f4 == tag ? newTag : f4), - contexts: oldMetadata.contexts.map((f4) => f4 == tag ? newTag : f4) + spaces: oldMetadata.spaces.map((f4) => f4 == tagPathToTag(tag) ? tagPathToTag(newTag) : f4) }; this.filesIndex.set(file.path, newMetadata); this.tagsMap.set(file.path, new Set(newMetadata.tags)); - this.contextsMap.set(file.path, new Set(newMetadata.contexts)); + this.spacesMap.set(file.path, new Set(newMetadata.spaces)); } else { this.reloadFile(file); } @@ -55195,15 +64955,22 @@ var Superstate = class extends import_obsidian62.Component { this.broadcast("file", "change", file.path); } deleteTag(tag) { - const contextCache = this.contextsIndex.get(tag); - this.contextsIndex.delete(tag); this.tagsMap.getInverse(tag).forEach((file) => { - this.deleteTagInFile(tag, getAbstractFileAtPath(app, file)); + const tFile = getAbstractFileAtPath(this.plugin, file); + if (tFile) + this.deleteTagInFile(tag, tFile); }); - let allContextsWithTag = []; - for (let [contextPath, contextCache2] of this.contextsIndex) { - if (contextCache2.contexts.includes(tag) || contextCache2.defContexts.includes(tag)) { - allContextsWithTag.push(contextCache2.info); + deleteSpaceFolder(this.plugin, tag); + this.plugin.index.deleteSpace(tagSpacePathFromTag(tag)); + for (const [contextPath, spaceCache] of this.spacesIndex) { + if (spaceCache.metadata.contexts.includes(tag)) { + saveSpaceCache(this.plugin, spaceCache.space, { ...spaceCache.metadata, contexts: spaceCache.metadata.contexts.filter((f4) => f4 != tag) }); + } + } + const allContextsWithTag = []; + for (const [contextPath, contextCache] of this.contextsIndex) { + if (contextCache.contexts.includes(tag)) { + allContextsWithTag.push(spaceInfoByPath(this.plugin, contextCache.path)); } } this.addToContextStoreQueue(() => removeTagInContexts(this.plugin, tag, allContextsWithTag)); @@ -55218,11 +64985,11 @@ var Superstate = class extends import_obsidian62.Component { ...oldMetadata, tags: oldMetadata.tags.filter((f4) => f4 != tag), fileTags: oldMetadata.fileTags.filter((f4) => f4 != tag), - contexts: oldMetadata.contexts.filter((f4) => f4 != tag) + spaces: oldMetadata.spaces.filter((f4) => f4 != tagSpacePathFromTag(tag)) }; this.filesIndex.set(file.path, newMetadata); this.tagsMap.set(file.path, new Set(newMetadata.tags)); - this.contextsMap.set(file.path, new Set(newMetadata.contexts)); + this.spacesMap.set(file.path, new Set(newMetadata.spaces)); } else { this.reloadFile(file); } @@ -55230,35 +64997,55 @@ var Superstate = class extends import_obsidian62.Component { this.broadcast("file", "change", file.path); } metadataChange(file) { + var _a2; let fileCache = this.filesIndex.get(file.path); let afile = file; + let spaceCache = this.spacesIndex.get(file.path); if (!fileCache) { - const folderNotePath = folderPathFromFolderNoteFile(this.plugin.settings, tFileToAFile(file)); - fileCache = this.filesIndex.get(folderNotePath); - if (fileCache) - afile = getAbstractFileAtPath(app, fileCache.path); + const aFile = tFileToAFile(file); + if (isFolderNote(this.plugin, aFile)) { + const folderNotePath = folderPathFromFolderNoteFile(this.plugin.settings, aFile); + fileCache = this.filesIndex.get(folderNotePath); + if (fileCache || folderNotePath == "/") { + spaceCache = this.spacesIndex.get(folderNotePath); + afile = getAbstractFileAtPath(this.plugin, folderNotePath); + } else { + const spacePath = spacePathFromSpaceDefFile(aFile); + spaceCache = this.spacesIndex.get(spacePath); + } + } } if (fileCache) { - const allContextsWithFile = fileCache.contexts.map((f4) => { - var _a2; - return (_a2 = this.contextsIndex.get(f4)) == null ? void 0 : _a2.info; + if (fileCache.isFolder) { + } + const allContextsWithFile = fileCache.spaces.map((f4) => { + var _a3; + return (_a3 = this.spacesIndex.get(f4)) == null ? void 0 : _a3.space; }).filter((f4) => f4); this.addToContextStoreQueue(() => onMetadataChange(this.plugin, afile, allContextsWithFile)); this.reloadFile(afile); } + if (spaceCache) { + const metaCache = this.metadataCache.getFileCache(file); + const spaceDef = (_a2 = metaCache == null ? void 0 : metaCache.frontmatter) != null ? _a2 : {}; + this.updateSpaceMetadata(spaceCache.path, parseSpaceMetadata(spaceDef, spaceCache.space, this.plugin)); + } + } + reloadSpaceByPath(path, metadata) { + return this.reloadSpace(spaceInfoByPath(this.plugin, path), metadata); } - renameFile(oldPath, newPath) { + async renameFile(oldPath, newPath) { var _a2, _b2; const oldParentPath = getParentPathFromString(oldPath); const newParentPath = getParentPathFromString(newPath); let newFilePath = newPath; - const newTFile = getAbstractFileAtPath(app, newPath); + const newTFile = getAbstractFileAtPath(this.plugin, newPath); const oldFileCache = this.filesIndex.get(oldPath); if (!oldFileCache) { this.spacesMap.rename(oldPath, newPath); this.linksMap.rename(oldPath, newPath); this.linksMap.renameInverse(oldPath, newPath); - this.spacesMap.get(newPath).forEach((f4) => this.reloadSpace(f4)); + this.spacesMap.get(newPath).forEach((f4) => this.reloadSpaceByPath(f4)); this.reloadFile(newTFile).then((f4) => this.broadcast("space")); return; } @@ -55266,108 +65053,151 @@ var Superstate = class extends import_obsidian62.Component { this.filesIndex.set(newPath, fileCache); this.filesIndex.delete(oldPath); if (this.plugin.settings.enableFolderNote) { - if (isFolderNote(this.plugin.settings, tFileToAFile(getAbstractFileAtPath(app, newPath)))) { - newFilePath = folderPathFromFolderNoteFile(this.plugin.settings, tFileToAFile(getAbstractFileAtPath(app, newPath))); + if (isFolderNote(this.plugin, tFileToAFile(getAbstractFileAtPath(this.plugin, newPath)))) { + const newFolderPath = folderPathFromFolderNoteFile(this.plugin.settings, tFileToAFile(getAbstractFileAtPath(this.plugin, newPath))); + if (newFolderPath) + newFilePath = newPath; this.filesIndex.delete(newPath); } } this.spacesMap.rename(oldPath, newFilePath); - const allContextsWithFile = ((_a2 = oldFileCache.contexts) != null ? _a2 : []).map((f4) => { + if (oldFileCache.isFolder) { + await this.spaceRenamed(oldPath, spaceFromFolder(this.plugin, newPath)); + } + const allContextsWithFile = ((_a2 = oldFileCache.spaces) != null ? _a2 : []).map((f4) => { var _a3; - return (_a3 = this.contextsIndex.get(f4)) == null ? void 0 : _a3.info; + return (_a3 = this.spacesIndex.get(f4)) == null ? void 0 : _a3.space; }).filter((f4) => f4); if (oldParentPath != newParentPath) { - const newFolderPath = getFolderPathFromString(newFilePath); - const newFolderContext = this.contextsIndex.get(newFolderPath); - const newTags = uniq([...oldFileCache.fileTags, ...(_b2 = newFolderContext == null ? void 0 : newFolderContext.contexts) != null ? _b2 : []]); - const sameContexts = allContextsWithFile.filter((f4) => newTags.includes(f4)); + const newFolderPath = getFolderPathFromString(this.plugin, newFilePath); + const newFolderContext = this.spacesIndex.get(newFolderPath); + const newTags = uniq([...oldFileCache.fileTags, ...(_b2 = newFolderContext == null ? void 0 : newFolderContext.contexts) != null ? _b2 : []]).map((f4) => tagSpacePathFromTag(f4)); + const sameContexts = allContextsWithFile.filter((f4) => newTags.includes(f4.path)); if (sameContexts.length > 0) - this.addToContextStoreQueue(() => renameFileInContexts(this.plugin, oldPath, newFilePath, sameContexts).then((f4) => sameContexts.forEach((c4) => this.reloadContext(c4)))); - const newContexts = newTags.filter((f4) => !sameContexts.includes(f4)).map((f4) => { + this.addToContextStoreQueue(() => renameFileInContexts(this.plugin, oldPath, newFilePath, sameContexts).then((f4) => sameContexts.forEach((c4) => this.reloadSpace(c4)))); + const newContexts = newTags.filter((f4) => !sameContexts.some((g4) => g4.path == f4)).map((f4) => { var _a3; - return (_a3 = this.contextsIndex.get(f4)) == null ? void 0 : _a3.info; + return (_a3 = this.spacesIndex.get(f4)) == null ? void 0 : _a3.space; }); if (newContexts.length > 0) - this.addToContextStoreQueue(() => addFileInContexts(this.plugin, newFilePath, newContexts).then((f4) => newContexts.forEach((c4) => this.reloadContext(c4)))); + this.addToContextStoreQueue(() => addFileInContexts(this.plugin, newFilePath, newContexts).then((f4) => newContexts.forEach((c4) => this.reloadSpace(c4)))); const removedContexts = allContextsWithFile.filter((f4) => !sameContexts.includes(f4)); if (removedContexts.length > 0) - this.addToContextStoreQueue(() => removeFileInContexts(this.plugin, oldPath, removedContexts).then((f4) => removedContexts.forEach((c4) => this.reloadContext(c4)))); + this.addToContextStoreQueue(() => removeFileInContexts(this.plugin, oldPath, removedContexts).then((f4) => removedContexts.forEach((c4) => this.reloadSpace(c4)))); } else { this.addToContextStoreQueue(() => renameFileInContexts(this.plugin, oldPath, newFilePath, allContextsWithFile).then((f4) => { allContextsWithFile.forEach((c4) => this.reloadContext(c4)); })); } - let allContextsWithLink = []; - for (let [contextPath, contextCache] of this.contextsIndex) { + const allContextsWithLink = []; + for (const [contextPath, contextCache] of this.contextsIndex) { if (contextCache.outlinks.includes(oldPath)) { - allContextsWithLink.push(contextCache.info); + allContextsWithLink.push(this.spacesIndex.get(contextCache.path).space); } } - this.spacesMap.get(newFilePath).forEach((f4) => this.reloadSpace(f4)); - this.reloadFile(getAbstractFileAtPath(app, newFilePath)).then((f4) => this.broadcast("space")); - this.addToContextStoreQueue(() => renameLinkInContexts(this.plugin, oldPath, newFilePath, allContextsWithLink).then((f4) => allContextsWithFile.forEach((c4) => this.reloadContext(c4)))); + this.spacesMap.get(newFilePath).forEach((f4) => this.reloadSpaceByPath(f4)); + this.reloadFile(getAbstractFileAtPath(this.plugin, newFilePath)).then((f4) => this.broadcast("space")); + this.addToContextStoreQueue(() => renameLinkInContexts(this.plugin, oldPath, newFilePath, allContextsWithLink).then((f4) => allContextsWithFile.forEach((c4) => this.reloadSpace(c4)))); } async createFile(path) { - await this.reloadFile(getAbstractFileAtPath(app, path)); + const file = getAbstractFileAtPath(this.plugin, path); + if (file instanceof import_obsidian62.TFolder) { + await this.reloadSpace(spaceFromFolder(this.plugin, path)); + } + await this.reloadFile(file); this.broadcast("space"); } + async updateValue(contextPath, row, field, value) { + const context = this.spacesIndex.get(contextPath).space; + this.addToContextStoreQueue(() => updateContextValue(this.plugin, context, row, field, value).then((f4) => this.reloadContext(context))); + } deleteFile(path) { + var _a2; const fileCache = this.filesIndex.get(path); - if (!fileCache) + if (!fileCache) { + if (path.startsWith(this.plugin.settings.spacesFolder)) { + for (const [contextPath, spaceCache] of this.spacesIndex) { + if (((_a2 = spaceCache.space) == null ? void 0 : _a2.folderPath) == path) { + this.deleteSpace(spaceCache.path); + break; + } + } + } return; + } + if (fileCache.isFolder) { + this.deleteSpace(fileCache.path); + } this.filesIndex.delete(path); this.spacesMap.delete(path); this.linksMap.delete(path); this.linksMap.deleteInverse(path); - const allContextsWithFile = fileCache.contexts.map((f4) => { - var _a2; - return (_a2 = this.contextsIndex.get(f4)) == null ? void 0 : _a2.info; - }).filter((f4) => f4); + const allContextsWithFile = fileCache.spaces.map((f4) => this.spacesIndex.get(f4).space).filter((f4) => f4); this.addToContextStoreQueue(() => removeFileInContexts(this.plugin, path, allContextsWithFile).then((f4) => allContextsWithFile.forEach((c4) => this.reloadContext(c4)))); - let allContextsWithLink = []; - for (let [contextPath, contextCache] of this.contextsIndex) { + const allContextsWithLink = []; + for (const [contextPath, contextCache] of this.contextsIndex) { if (contextCache.outlinks.includes(path)) { - allContextsWithLink.push(contextCache.info); + allContextsWithLink.push(this.spacesIndex.get(contextCache.path).space); } } this.addToContextStoreQueue(() => removeLinkInContexts(this.plugin, path, allContextsWithLink).then((f4) => allContextsWithFile.forEach((c4) => this.reloadContext(c4)))); this.broadcast("space"); } - async renameSpace(oldSpace, newSpace) { - if (this.spacesIndex.has(oldSpace)) { - this.spacesIndex.delete(oldSpace); - await this.reloadSpace(newSpace); + async spaceRenamed(oldPath, newSpaceInfo) { + if (this.spacesIndex.has(oldPath)) { + this.spacesIndex.delete(oldPath); + this.contextsIndex.delete(oldPath); + this.framesIndex.delete(oldPath); + await this.reloadSpace(newSpaceInfo); + await this.reloadContext(newSpaceInfo); + await this.reloadFrames(newSpaceInfo); } - this.spacesMap.renameInverse(oldSpace, newSpace); - this.broadcast("space", "rename", oldSpace); + this.spacesMap.renameInverse(oldPath, newSpaceInfo.path); + this.plugin.app.workspace.iterateLeaves((leaf) => { + if (leaf.view.getViewType() == SPACE_VIEW_TYPE && leaf.view.getState().path == oldPath) { + leaf.setViewState({ + type: SPACE_VIEW_TYPE, + state: { path: newSpaceInfo.path } + }); + } + }, this.plugin.app.workspace["rootSplit"]); } deleteSpace(space) { if (this.spacesIndex.has(space)) { this.spacesIndex.delete(space); + this.contextsIndex.delete(space); + this.framesIndex.delete(space); } this.spacesMap.deleteInverse(space); this.persister.remove(space, "space"); this.plugin.settings.cachedSpaces = this.allSpaces().map((f4) => f4.name); this.plugin.saveSettings(); + spaceFolderDelete(space); this.broadcast("space"); } - async spacesSynced() { - const incomingSpaceTime = parseInt(await app.vault.read(getAbstractFileAtPath(app, this.plugin.settings.spacesSyncLastUpdated))); - const currentSpaceTime = this.plugin.spacesDBLastModify; - if (incomingSpaceTime != currentSpaceTime) { - this.loadSpacesDatabaseFromDisk(); - } + async reloadFrames(space) { + if (!space) + return false; + return this.indexer.reload({ type: "frames", path: space.path }).then((r3) => { + const { changed, cache } = r3; + if (!changed) { + return false; + } + this.framesIndex.set(space.path, cache); + this.broadcast("frames", "change", space.path); + return true; + }); } - async reloadContext(context) { - if (!context) + async reloadContext(space) { + if (!space) return false; - return this.indexer.reload({ type: "context", path: context.contextPath }).then((r3) => { + return this.indexer.reload({ type: "context", path: space.path }).then((r3) => { const { changed, cache } = r3; if (!changed) { return false; } - this.contextsIndex.set(context.contextPath, cache); - this.broadcast("context", "change", context.contextPath); + this.contextsIndex.set(space.path, cache); + this.broadcast("context", "change", space.path); return true; }); } @@ -55377,68 +65207,123 @@ var Superstate = class extends import_obsidian62.Component { async reloadVault() { this.broadcast("vault"); } - allSpaces() { - return [...this.spacesIndex.values()].filter((f4) => f4).map((f4) => f4.space).sort( - (a5, b4) => { - var _a2, _b2; - return ((_a2 = a5.rank) != null ? _a2 : "").localeCompare((_b2 = b4.rank) != null ? _b2 : "", void 0, { numeric: true }); - } - ); + allSpaces(ordered) { + if (ordered) { + return orderArrayByArray([...this.spacesIndex.values()], this.spaceOrder(), "path"); + } + return [...this.spacesIndex.values()]; } - async backupSpaceDB(auto) { - if (auto) { - if (!this.plugin.settings.spacesAutoBackup) { - return; - } - if (Date.now() - this.plugin.settings.spacesAutoBackupLast > this.plugin.settings.spacesAutoBackupInterval * 60 * 24) { - this.plugin.settings.spacesAutoBackupLast = Date.now(); - this.plugin.saveSettings(); - } else { - return; - } + spaceOrder() { + return [...this.plugin.settings.waypoints]; + } + allFrames() { + return [...this.framesIndex.values()].filter((f4) => f4).flatMap((f4) => f4.schemas.filter((f5) => f5.type == "frame").map((s5) => ({ schema: s5, path: f4.path }))); + } + allListItems() { + return [...this.framesIndex.values()].filter((f4) => f4).flatMap((f4) => f4.schemas.filter((f5) => f5.type == "listitem").map((s5) => ({ schema: s5, path: f4.path }))); + } + async updateSpaceMetadata(spacePath, metadata) { + var _a2, _b2, _c2; + const space = this.spacesIndex.get(spacePath); + if (!space) { + return this.reloadSpaceByPath(spacePath); } - const spaceBackupFolder = (0, import_obsidian62.normalizePath)( - `${app.vault.configDir}/plugins/make-md/backups` - ); - if (!await this.app.vault.adapter.exists( - spaceBackupFolder - )) { - await this.app.vault.createFolder(spaceBackupFolder); + let reinit = false; + const spaceSort = (_a2 = metadata == null ? void 0 : metadata.sort) != null ? _a2 : { field: "rank", asc: true, group: true }; + const sortable = spaceSort.field == "rank"; + if (!import_lodash13.default.isEqual(space.metadata.links, metadata.links) || !import_lodash13.default.isEqual(space.metadata.filters, metadata.filters)) { + reinit = true; } - const backupPath = (0, import_obsidian62.normalizePath)( - `${spaceBackupFolder}/Spaces ${format(Date.now(), "yyyy-MM-dd HH-mm")}.mdb` - ); - const dbPathExists = await this.app.vault.adapter.exists(this.plugin.spacesDBPath); - const backupPathExists = await this.app.vault.adapter.exists(backupPath); - if (dbPathExists && !backupPathExists) - app.vault.adapter.copy(this.plugin.spacesDBPath, backupPath); - } - async loadSpaceDBFromBackup(fileName) { - const filePath = (0, import_obsidian62.normalizePath)( - `${app.vault.configDir}/plugins/make-md/backups/${fileName}.mdb` - ); - if (this.app.vault.adapter.exists( - filePath - )) { - await app.vault.adapter.remove(this.plugin.spacesDBPath); - await app.vault.adapter.copy(filePath, this.plugin.spacesDBPath); - await this.updateSpaceLastUpdated(); - this.loadSpacesDatabaseFromDisk(); - } - } - reloadSpace(spaceName, initialized = true) { - const spaceDB = this.spacesDBCache.find((f4) => f4.name == spaceName); - if (spaceDB) { - const space = parseSpace(spaceDB); - const spaceItems = this.spacesItemsDBCache.filter((f4) => f4.space == spaceName); - const cache = parseSpaceCache(space, spaceItems); - this.spacesIndex.set(spaceName, cache); - this.persister.store(spaceName, JSON.stringify(cache), "space"); - if (initialized) { - this.plugin.settings.cachedSpaces = this.allSpaces().map((f4) => f4.name); - this.plugin.saveSettings(); - this.broadcast("space", "change", spaceName); + const newSpaceCache = { + ...space, + metadata, + contexts: (_b2 = metadata == null ? void 0 : metadata.contexts) != null ? _b2 : [], + sticker: (_c2 = metadata.sticker) != null ? _c2 : iconForSpaceType(space.type, space.path, true), + banner: metadata.banner, + color: metadata.color, + sortable + }; + this.spacesIndex.set(spacePath, newSpaceCache); + this.broadcast("space", "change", spacePath); + if (reinit) + await this.initalizeFiles(); + return newSpaceCache; + } + cacheForURI(uri) { + if (!uri) + return null; + if (uri.type == "file" || uri.type == "folder") { + const fileCache = this.filesIndex.get(uri.path); + if (!fileCache) { + const folderPath = folderPathFromFolderNoteFile( + this.plugin.settings, + tFileToAFile(getAbstractFileAtPath(this.plugin, uri.path)) + ); + if (!folderPath) + return null; + const space = this.spacesIndex.get(folderPath); + return space; + } else if (uri.type == "folder") { + const space = this.spacesIndex.get(uri.path); + if (space) + return space; + } + return fileCache; + } else if (uri.type == "space" || uri.type == "tag" || uri.type == "vault") { + const space = this.spacesIndex.get(uri.basePath); + return space; + } + return null; + } + async reloadSpace(space, spaceMetadata, initialized = true) { + var _a2, _b2, _c2, _d2, _e2, _f, _g, _h; + if (!space) + return; + const defFile = getAbstractFileAtPath(this.plugin, space.defPath); + const folder = getAbstractFileAtPath(this.plugin, space.folderPath); + const metaCache = defFile ? this.metadataCache.getFileCache(defFile) : null; + const spaceDef = (_a2 = metaCache == null ? void 0 : metaCache.frontmatter) != null ? _a2 : {}; + const metadata = spaceMetadata != null ? spaceMetadata : parseSpaceMetadata(spaceDef, space, this.plugin); + const frontmatter = metaCache == null ? void 0 : metaCache.frontmatter; + const type = space.uri.type == "tag" ? "tag" : space.uri.type == "folder" ? "folder" : space.uri.type == "vault" ? "vault" : "unknown"; + const spaceSort = (_b2 = metadata == null ? void 0 : metadata.sort) != null ? _b2 : { field: "rank", asc: true, group: true }; + const sortable = spaceSort.field == "rank" || !spaceSort; + const contexts = (_c2 = metadata.contexts) != null ? _c2 : []; + const banner = metadata.banner; + const sticker = ((_d2 = metadata.sticker) == null ? void 0 : _d2.length) > 0 ? metadata.sticker : iconForSpaceType(type, space.path, true); + const color = metadata.color; + if (type == "tag" && this.plugin.settings.autoAddContextsToSubtags) { + const parentTags = getAllParentTags(space.name); + contexts.push(...parentTags); + } + const cache = { + name: space.name, + space, + alias: (_f = (_e2 = ensureArray(metadata.aliases)) == null ? void 0 : _e2[0]) != null ? _f : space.name, + cacheType: "space", + path: space.path, + frontmatter, + type, + parent: (_g = folder == null ? void 0 : folder.parent) == null ? void 0 : _g.path, + contexts: contexts.map((f4) => tagToTagPath(f4)), + metadata, + sortable, + sticker, + banner, + color + }; + this.spacesIndex.set(space.path, cache); + this.persister.store(space.path, JSON.stringify(cache), "space"); + (_h = cache.metadata.links) == null ? void 0 : _h.forEach((f4) => { + if (pathIsSpace(this.plugin, f4)) { + this.spacesMap.set(f4, /* @__PURE__ */ new Set([...this.spacesMap.get(f4), space.path])); } + }); + if (initialized) { + this.plugin.settings.cachedSpaces = this.allSpaces().map((f4) => f4.path); + this.plugin.saveSettings(); + this.broadcast("space", "change", space.path); + return cache; } } async reloadFile(file, force) { @@ -55446,26 +65331,35 @@ var Superstate = class extends import_obsidian62.Component { return false; return this.indexer.reload({ type: "file", path: file.path }).then((r3) => { const { changed, cache } = r3; + if (cache.extension == "otf" || cache.extension == "ttf") { + this.fontsCache.set(cache.name, `@font-face { + font-family: '${cache.name}'; + src: url('${this.api.getLocalFile(cache.path)}'); + }`); + } if (!changed && !force) { return false; } this.filesIndex.set(file.path, cache); this.tagsMap.set(file.path, new Set(cache.tags)); - this.contextsMap.set(file.path, new Set(cache.contexts)); - this.linksMap.set(file.path, new Set(cache.outlinks)); - if (!import_lodash10.default.isEqual(cache.spaces, Array.from(this.spacesMap.get(file.path)))) { + this.linksMap.set(file.path, new Set(cache.outlinks.map((f4) => { + var _a2; + return (_a2 = this.plugin.app.metadataCache.getFirstLinkpathDest(f4, file.path)) == null ? void 0 : _a2.path; + }).filter((f4) => f4))); + if (!import_lodash13.default.isEqual(cache.spaces, Array.from(this.spacesMap.get(file.path)))) { this.spacesMap.set(file.path, new Set(cache.spaces)); + cache.tags.map((f4) => this.spacesIndex.has(tagSpacePathFromTag(f4)) ? null : spaceFromTag(this.plugin, f4)).filter((f4) => f4).forEach((f4) => this.reloadSpace(f4).then((f5) => this.broadcast("file", "change", file.path))); this.broadcast("space"); } if (force) { - const allContextsWithFile = cache.contexts.map((f4) => { + const allContextsWithFile = cache.spaces.map((f4) => { var _a2; - return (_a2 = this.contextsIndex.get(f4)) == null ? void 0 : _a2.info; + return (_a2 = this.spacesIndex.get(f4)) == null ? void 0 : _a2.space; }).filter((f4) => f4); this.addToContextStoreQueue(() => onMetadataChange(this.plugin, file, allContextsWithFile)); } if (cache.extension == "svg" && this.plugin.settings.indexSVG) { - app.vault.read(file).then((f4) => { + this.plugin.app.vault.read(file).then((f4) => { this.iconsCache.set(file.path, f4); this.persister.store(file.path, f4, "icon"); }); @@ -55483,13 +65377,13 @@ var Superstate = class extends import_obsidian62.Component { if (!metadata) { return false; } - let missingContexts = []; - let removedContexts = []; + const missingContexts = []; + const removedContexts = []; this.contextsIndex.forEach((contextCache) => { - if (metadata.contexts.includes(contextCache.info.contextPath) && !contextCache.files.includes(path)) { - missingContexts.push(contextCache.info); - } else if (contextCache.files.includes(path) && !metadata.contexts.includes(contextCache.info.contextPath)) { - removedContexts.push(contextCache.info); + if (metadata.spaces.includes(contextCache.path) && !contextCache.files.includes(path)) { + missingContexts.push(contextCache.space); + } else if (!metadata.spaces.includes(contextCache.path) && contextCache.files.includes(path)) { + removedContexts.push(contextCache.space); } }); if (missingContexts.length > 0) { @@ -55502,16 +65396,18 @@ var Superstate = class extends import_obsidian62.Component { } }; -// src/components/FileContextView/FileHeaderContextView.tsx +// src/components/InlineFileContext/FileHeaderContextView.tsx var FileHeaderContextView = (props2) => { + var _a2; const { name, fm } = props2; + const file = getAbstractFileAtPath(props2.plugin, name); const [collapsed, setCollapsed] = h2(false); - const tags = fm.tags; + const tags = (_a2 = fm.tags) != null ? _a2 : []; const [values, setValues] = h2({}); const [columns, setColumns] = h2([]); p2(() => { - let newCols = []; - let newValues = {}; + const newCols = []; + const newValues = {}; const fmKeys = uniqCaseInsensitive(frontMatterKeys(fm)); const cols = fmKeys.map((f4) => ({ table: "", @@ -55536,7 +65432,7 @@ var FileHeaderContextView = (props2) => { }, /* @__PURE__ */ Cn.createElement("div", { className: `mk-spacer`, style: { - "--header-height": fm && fm[props2.plugin.settings.fmKeyBanner] ? ((platformIsMobile() ? 1 : 0) * 26 + 138 + (!fm.icon || props2.plugin.settings.inlineContextNameLayout == "horizontal" ? 1 : 0) * 50).toString() + "px" : 0 + "--mk-header-height": fm && fm[props2.plugin.settings.fmKeyBanner] ? ((platformIsMobile() ? 1 : 0) * 26 + 138 + (!fm.icon || props2.plugin.settings.inlineContextNameLayout == "horizontal" ? 1 : 0) * 50).toString() + "px" : 0 }, onContextMenu: (e4) => e4.preventDefault() }), /* @__PURE__ */ Cn.createElement("div", { @@ -55549,11 +65445,10 @@ var FileHeaderContextView = (props2) => { } })) : /* @__PURE__ */ Cn.createElement(Cn.Fragment, null), /* @__PURE__ */ Cn.createElement("div", { className: "mk-inline-title inline-title" - }, fileNameToString(name)), (tags == null ? void 0 : tags.length) > 0 ? /* @__PURE__ */ Cn.createElement(TagsView, { - canOpen: true, - plugin: props2.plugin, - tags - }) : /* @__PURE__ */ Cn.createElement(Cn.Fragment, null)))), !collapsed ? /* @__PURE__ */ Cn.createElement("div", { + }, fileNameToString(name)), /* @__PURE__ */ Cn.createElement(NoteSpacesBar, { + path: file.path, + plugin: props2.plugin + })))), !collapsed ? /* @__PURE__ */ Cn.createElement("div", { className: "mk-file-context-component" }, /* @__PURE__ */ Cn.createElement(Cn.Fragment, null, /* @__PURE__ */ Cn.createElement("div", { className: "mk-file-context-section" @@ -55567,8 +65462,7 @@ var FileHeaderContextView = (props2) => { }, /* @__PURE__ */ Cn.createElement(DataTypeView, { plugin: props2.plugin, initialValue: values[f4.name], - index: 0, - file: null, + row: {}, column: { ...f4, table: "" }, editable: false, updateValue: () => { @@ -55579,15 +65473,15 @@ var FileHeaderContextView = (props2) => { })))))))) : /* @__PURE__ */ Cn.createElement(Cn.Fragment, null)); }; -// src/components/FileContextView/ReadingModeHeader.tsx +// src/components/InlineFileContext/ReadingModeHeader.tsx var ReadingModeHeader = (props2) => { const [path, setPath] = h2(props2.filePath); - const ref = _2(null); + const ref2 = _2(null); p2(() => { setPath(props2.filePath); }, [props2.filePath]); const changeActiveFile = (evt) => { - if (ref.current.closest(".mod-active") && evt.detail.path.type == "file") + if (ref2.current.closest(".mod-active") && evt.detail.path.type == "file") setPath(evt.detail.path.path); }; p2(() => { @@ -55597,12 +65491,13 @@ var ReadingModeHeader = (props2) => { }; }, [path]); return /* @__PURE__ */ Cn.createElement("div", { - ref + ref: ref2 }, /* @__PURE__ */ Cn.createElement(InlineFileContextView, { plugin: props2.plugin, - file: getAbstractFileAtPath(app, path), + path, showHeader: true, showBanner: true, + showFolder: true, editable: false })); }; @@ -55666,51 +65561,93 @@ var loadSQL = async () => { return sql; }; -// src/utils/flow/flow.tsx -var modifyFlowDom = (plugin) => { - if (!plugin.settings.makerMode || !plugin.settings.inlineContext || !app.workspace.activeEditor) - return; - const contentEl = app.workspace.activeEditor.contentEl; - const editorView = app.workspace.activeEditor.editor; - const sizerEl = contentEl.querySelector(".cm-sizer"); - const file = app.workspace.getActiveFile(); - if (sizerEl && file) { - let inlineContext = contentEl.querySelector(".mk-inline-context"); - if (!inlineContext) { - inlineContext = document.createElement("div"); - inlineContext.classList.add("mk-inline-context"); - inlineContext.classList.add("embedded-backlinks"); - sizerEl.prepend(inlineContext); +// src/middleware/filesystem.ts +var import_obsidian64 = require("obsidian"); +var FilesystemMiddleware = class { + constructor(type, plugin) { + this.type = type; + this.plugin = plugin; + } + static create(plugin, type) { + return new FilesystemMiddleware(type, plugin); + } + getRoot() { + if (this.type == 0 /* Obsidian */) { } - const inlineContextReactEl = createRoot(inlineContext); - inlineContextReactEl.render( - /* @__PURE__ */ Cn.createElement(InlineFileContextView, { - plugin, - file, - editorView: editorView.cm, - showHeader: true, - showBanner: true, - isFolderNote: false, - editable: true - }) - ); - if (plugin.settings.inlineBacklinks) { - let backlinksEl = contentEl.querySelector(".mk-backlinks"); - if (!backlinksEl) { - backlinksEl = document.createElement("div"); - backlinksEl.classList.add("mk-backlinks"); - backlinksEl.classList.add("embedded-backlinks"); - sizerEl.appendChild(backlinksEl); - } - const backlinksReactEl = createRoot(backlinksEl); - backlinksReactEl.render( - /* @__PURE__ */ Cn.createElement(Backlinks, { - plugin, - file - }) + } + copyFile() { + if (this.type == 0 /* Obsidian */) { + } + } + async renameFile(path, newPath) { + if (this.type == 0 /* Obsidian */) { + return this.plugin.app.fileManager.renameFile( + getAbstractFileAtPath(this.plugin, path), + newPath ); } } + async newFile(parent, name, type) { + if (this.type == 0 /* Obsidian */) { + if (type == "md") { + const parentFolder = getAbstractFileAtPath(this.plugin, parent); + return this.plugin.app.fileManager.createNewMarkdownFile( + parentFolder instanceof import_obsidian64.TFolder ? parentFolder : parentFolder.parent, + name + ); + } else if (type == "canvas") { + const newFile = await this.newFile(parent, name, "md"); + await this.plugin.app.vault.modify(newFile, "{}"); + await this.renameFile( + newFile.path, + newFile.path.substring(0, newFile.name.lastIndexOf(".")) + ".canvas" + ); + } + } + } + fileExists() { + if (this.type == 0 /* Obsidian */) { + } + } + getFile() { + if (this.type == 0 /* Obsidian */) { + } + } + deleteFile() { + if (this.type == 0 /* Obsidian */) { + } + } +}; + +// src/middleware/metadata.ts +var import_obsidian65 = require("obsidian"); +var MetadataMiddleware = class { + constructor(type, plugin) { + this.type = type; + this.plugin = plugin; + } + static create(plugin, type) { + return new MetadataMiddleware(type, plugin); + } + canProcessFrontmatter() { + if (this.type == 0 /* Obsidian */) { + return this.plugin.app.fileManager.processFrontMatter ? true : false; + } + return false; + } + async processFrontMatter(path, fn2) { + if (this.type == 0 /* Obsidian */) { + const afile = getAbstractFileAtPath(this.plugin, path); + if (afile && afile instanceof import_obsidian65.TFile) { + if (this.plugin.app.fileManager.processFrontMatter) { + return this.plugin.app.fileManager.processFrontMatter(afile, fn2); + } + } + } + } + canProcessMarkdown() { + return false; + } }; // node_modules/monkey-around/mjs/index.js @@ -55722,16 +65659,16 @@ function around(obj, factories) { } function around1(obj, method, createWrapper) { const original = obj[method], hadOwn = obj.hasOwnProperty(method); - let current = createWrapper(original); + let current2 = createWrapper(original); if (original) - Object.setPrototypeOf(current, original); - Object.setPrototypeOf(wrapper, current); + Object.setPrototypeOf(current2, original); + Object.setPrototypeOf(wrapper, current2); obj[method] = wrapper; return remove; function wrapper(...args) { - if (current === original && obj[method] === wrapper) + if (current2 === original && obj[method] === wrapper) remove(); - return current.apply(this, args); + return current2.apply(this, args); } function remove() { if (obj[method] === wrapper) { @@ -55740,18 +65677,18 @@ function around1(obj, method, createWrapper) { else delete obj[method]; } - if (current === original) + if (current2 === original) return; - current = original; + current2 = original; Object.setPrototypeOf(wrapper, original || Function); } } // src/utils/spaces/patches.ts -var import_obsidian64 = require("obsidian"); -var patchFileExplorer = (plugin) => { +var import_obsidian66 = require("obsidian"); +var patchFilesPlugin = (plugin) => { plugin.register( - around(import_obsidian64.Workspace.prototype, { + around(import_obsidian66.Workspace.prototype, { getLeavesOfType(old) { return function(type) { if (type == "file-explorer") { @@ -55765,7 +65702,7 @@ var patchFileExplorer = (plugin) => { }; var patchWorkspace = (plugin) => { let layoutChanging = false; - const uninstaller = around(import_obsidian64.Workspace.prototype, { + const uninstaller = around(import_obsidian66.Workspace.prototype, { changeLayout(old) { return async function(workspace) { layoutChanging = true; @@ -55780,13 +65717,13 @@ var patchWorkspace = (plugin) => { return function(arg1, arg2) { if (old.call(this, arg1, arg2)) return true; - let cb = typeof arg1 === "function" ? arg1 : arg2; - let parent = typeof arg1 === "function" ? arg2 : arg1; + const cb = typeof arg1 === "function" ? arg1 : arg2; + const parent = typeof arg1 === "function" ? arg2 : arg1; if (!parent) return false; if (layoutChanging) return false; - if (parent === app.workspace.rootSplit || import_obsidian64.WorkspaceContainer && parent instanceof import_obsidian64.WorkspaceContainer) { + if (parent === plugin.app.workspace.rootSplit || import_obsidian66.WorkspaceContainer && parent instanceof import_obsidian66.WorkspaceContainer) { for (const popover of FlowEditor.popoversForWindow( parent.win )) { @@ -55838,52 +65775,204 @@ var patchWorkspace = (plugin) => { plugin.register(uninstaller); }; +// src/components/FileContextView/Backlinks.tsx +var BacklinkItem = (props2) => { + const file = F2( + () => getAbstractFileAtPath(props2.plugin, props2.path), + [props2.path] + ); + const [block, setBlock] = h2([null, null]); + const refreshBlock = (path) => { + var _a2, _b2; + const fCache = props2.plugin.app.metadataCache.getCache(path); + const link = [...(_a2 = fCache.links) != null ? _a2 : [], ...(_b2 = fCache.embeds) != null ? _b2 : []].find( + (f4) => props2.source.includes(f4.displayText) + ); + if (link) { + const block2 = fCache.sections.find( + (f4) => f4.position.start.offset <= link.position.start.offset && f4.position.end.offset >= link.position.end.offset + ); + setBlock([ + Math.max(1, block2.position.start.line), + Math.max(block2.position.start.line + 1, block2.position.end.line + 1) + ]); + } else { + setBlock([null, null]); + } + }; + p2(() => { + refreshBlock(props2.path); + }, []); + p2(() => { + refreshBlock(props2.path); + }, [props2.path]); + const [collapsed, setCollapsed] = h2(false); + return /* @__PURE__ */ Cn.createElement(Cn.Fragment, null, /* @__PURE__ */ Cn.createElement("div", { + className: "mk-file-context-title" + }, /* @__PURE__ */ Cn.createElement("button", { + className: `mk-collapse mk-inline-button mk-icon-xsmall ${collapsed ? "mk-collapsed" : ""}`, + onClick: (e4) => { + setCollapsed(!collapsed); + e4.stopPropagation(); + }, + dangerouslySetInnerHTML: { + __html: uiIconSet["mk-ui-collapse"] + } + }), /* @__PURE__ */ Cn.createElement("div", { + onClick: (e4) => { + openAFile(file, props2.plugin, false); + e4.stopPropagation(); + } + }, fileNameToString(file.name))), !collapsed ? /* @__PURE__ */ Cn.createElement("div", { + className: "mk-file-context-backlink" + }, /* @__PURE__ */ Cn.createElement(FlowView, { + plugin: props2.plugin, + load: true, + leaf: props2.leaf, + path: props2.path, + from: block[0], + to: block[1], + classname: "mk-file-context-flow" + })) : /* @__PURE__ */ Cn.createElement(Cn.Fragment, null)); +}; +var Backlinks = (props2) => { + const [collapsed, setCollapsed] = h2( + !props2.plugin.settings.inlineBacklinksExpanded + ); + const [backlinks, setBacklinks] = h2([]); + p2(() => { + if (!props2.file) + return; + const bls = uniq([ + ...props2.plugin.index.linksMap.getInverse(props2.file.path), + ...Object.keys(props2.plugin.app.metadataCache.resolvedLinks).filter( + (f4) => props2.file.path in props2.plugin.app.metadataCache.resolvedLinks[f4] + ) + ]).filter((f4) => abstractFileAtPathExists(props2.plugin, f4)); + setBacklinks(bls); + }, [props2.file]); + p2(() => { + props2.plugin.settings.inlineBacklinksExpanded = !collapsed; + props2.plugin.saveSettings(); + }, [collapsed]); + const toggleBacklinks = () => { + setCollapsed(!collapsed); + }; + p2(() => { + window.addEventListener(eventTypes.toggleBacklinks, toggleBacklinks); + return () => { + window.removeEventListener(eventTypes.toggleBacklinks, toggleBacklinks); + }; + }, [collapsed]); + return backlinks.length > 0 && props2.file ? /* @__PURE__ */ Cn.createElement("div", { + className: "mk-file-context-component mk-note-footer" + }, /* @__PURE__ */ Cn.createElement("div", { + className: "mk-file-context-section" + }, /* @__PURE__ */ Cn.createElement("div", { + onClick: (e4) => { + setCollapsed(!collapsed); + e4.stopPropagation(); + }, + className: "mk-file-context-title" + }, /* @__PURE__ */ Cn.createElement("div", { + className: `mk-icon-xsmall`, + dangerouslySetInnerHTML: { + __html: uiIconSet["mk-ui-backlink"] + } + }), i18n_default.labels.backlinks, /* @__PURE__ */ Cn.createElement("button", { + className: `mk-collapse mk-inline-button mk-icon-xsmall ${collapsed ? "mk-collapsed" : ""}`, + dangerouslySetInnerHTML: { + __html: uiIconSet["mk-ui-collapse-sm"] + } + })), /* @__PURE__ */ Cn.createElement("div", null, !collapsed && backlinks.map((f4, i4) => { + var _a2; + return /* @__PURE__ */ Cn.createElement(BacklinkItem, { + path: f4, + key: i4, + leaf: props2.leaf, + plugin: props2.plugin, + source: (_a2 = props2.file) == null ? void 0 : _a2.path + }); + })))) : /* @__PURE__ */ Cn.createElement(Cn.Fragment, null); +}; + +// src/utils/flow/flow.tsx +var modifyFlowDom = (plugin) => { + if (!plugin.settings.makerMode || !plugin.settings.inlineContext || !plugin.app.workspace.activeEditor) + return; + const contentEl = plugin.app.workspace.activeEditor.contentEl; + const editorView = plugin.app.workspace.activeEditor.editor; + const sizerEl = contentEl.querySelector(".cm-sizer"); + const file = plugin.app.workspace.getActiveFile(); + if (sizerEl && file) { + let inlineContext = contentEl.querySelector(".mk-inline-context"); + if (!inlineContext) { + inlineContext = document.createElement("div"); + inlineContext.classList.add("mk-inline-context"); + inlineContext.classList.add("embedded-backlinks"); + sizerEl.prepend(inlineContext); + } + const inlineContextReactEl = createRoot(inlineContext); + inlineContextReactEl.render( + /* @__PURE__ */ Cn.createElement(Cn.Fragment, null, /* @__PURE__ */ Cn.createElement(InlineFileContextView, { + plugin, + path: file.path, + editorView: editorView.cm, + showHeader: true, + showBanner: true, + showFolder: true, + editable: true, + hiddenFields: [...FMMetadataKeys(plugin)] + })) + ); + if (plugin.settings.inlineBacklinks) { + let backlinksEl = contentEl.querySelector(".mk-backlinks"); + if (!backlinksEl) { + backlinksEl = document.createElement("div"); + backlinksEl.classList.add("mk-backlinks"); + backlinksEl.classList.add("embedded-backlinks"); + sizerEl.appendChild(backlinksEl); + } + const backlinksReactEl = createRoot(backlinksEl); + backlinksReactEl.render( + /* @__PURE__ */ Cn.createElement(Backlinks, { + plugin, + file + }) + ); + } + } +}; + // src/main.ts -var MakeMDPlugin = class extends import_obsidian65.Plugin { +var makeMDVersion = 0.804; +var MakeMDPlugin = class extends import_obsidian67.Plugin { constructor() { super(...arguments); this.dataViewAPI = () => (0, import_obsidian_dataview.getAPI)(); this.spacesDBLastModify = 0; this.debouncedRefresh = () => null; - this.createInlineTable = async (path) => { - const context = folderContextFromFolder(this, path); - const schemas = await getMDBTableSchemas(this, context); - if (schemas) - return uniqueNameFromString( - "Table", - schemas.map((f4) => f4.id) - ); - return "Table"; - }; this.metadataChange = (file) => { this.index.metadataChange(file); }; this.onCreate = async (file) => { if (!file) return; - onFileCreated(this, file.path, file instanceof import_obsidian65.TFolder); + this.index.addToVaultQueue(() => onFileCreated(this, file.path, file instanceof import_obsidian67.TFolder)); }; this.onDelete = async (file) => { - if (file instanceof import_obsidian65.TFile && file.extension != "mdb") { - onFileDeleted(this, file.path); - } else if (file instanceof import_obsidian65.TFolder) { - onFolderDeleted(this, file.path); + if (file instanceof import_obsidian67.TFile && file.extension != "mdb") { + this.index.addToVaultQueue(() => onFileDeleted(this, file.path)); + } else if (file instanceof import_obsidian67.TFolder) { + this.index.addToVaultQueue(() => onFolderDeleted(this, file.path)); } this.activeFileChange(); }; - this.onModify = async (file) => { - if (file.path == this.settings.spacesSyncLastUpdated) { - this.index.spacesSynced(); - } - if (file instanceof import_obsidian65.TFile && file.extension == "mdb") { - this.index.reloadContext(mdbContextByDBPath(this, file.path)); - } - }; this.onRename = async (file, oldPath) => { - if (file instanceof import_obsidian65.TFile && file.extension != "mdb") { - await onFileChanged(this, oldPath, file.path); - } else if (file instanceof import_obsidian65.TFolder) { - await onFolderChanged(this, oldPath, file.path); + if (file instanceof import_obsidian67.TFile && file.extension != "mdb") { + this.index.addToVaultQueue(() => onFileChanged(this, oldPath, file.path)); + } else if (file instanceof import_obsidian67.TFolder) { + this.index.addToVaultQueue(() => onFolderChanged(this, oldPath, file.path)); } this.activeFileChange(); }; @@ -55892,14 +65981,14 @@ var MakeMDPlugin = class extends import_obsidian65.Plugin { if (leafs.length == 0) { const leaf = this.app.workspace.getLeftLeaf(false); await leaf.setViewState({ type: FILE_TREE_VIEW_TYPE }); - if (showAfterAttach && !app.workspace.leftSplit.collapsed) + if (showAfterAttach && !this.app.workspace.leftSplit.collapsed) this.app.workspace.revealLeaf(leaf); } else { if (!app.workspace.leftSplit.collapsed && showAfterAttach) leafs.forEach((leaf) => this.app.workspace.revealLeaf(leaf)); } if (platformIsMobile()) { - app.workspace.leftSplit.collapse(); + this.app.workspace.leftSplit.collapse(); } replaceMobileMainMenu(this); }; @@ -55914,7 +66003,7 @@ var MakeMDPlugin = class extends import_obsidian65.Plugin { this.detachFileContextLeafs = () => { const leafs = this.app.workspace.getLeavesOfType(FILE_CONTEXT_VIEW_TYPE); for (const leaf of leafs) { - if (leaf.view instanceof FileContextLeafView) + if (leaf.view instanceof ContextExplorerLeafView) leaf.view.destroy(); leaf.detach(); } @@ -55929,7 +66018,7 @@ var MakeMDPlugin = class extends import_obsidian65.Plugin { leafs.forEach((leaf) => this.app.workspace.revealLeaf(leaf)); } if (platformIsMobile() && !reveal) { - app.workspace.rightSplit.collapse(); + this.app.workspace.rightSplit.collapse(); } }; this.refreshFileContextLeafs = () => { @@ -55942,7 +66031,7 @@ var MakeMDPlugin = class extends import_obsidian65.Plugin { return sqljs; } openFlow() { - const cm = getActiveCM(); + const cm = getActiveCM(this); if (cm) { const value = cm.state.field(flowEditorInfo, false); const currPosition = cm.state.selection.main; @@ -55956,7 +66045,7 @@ var MakeMDPlugin = class extends import_obsidian65.Plugin { } } closeFlow() { - const cm = getActiveCM(); + const cm = getActiveCM(this); if (cm) { const value = cm.state.field(flowEditorInfo, false); const currPosition = cm.state.selection.main; @@ -55969,12 +66058,15 @@ var MakeMDPlugin = class extends import_obsidian65.Plugin { } } } + systemName() { + return this.app.vault.getName(); + } reloadExtensions(firstLoad) { this.extensions = cmExtensions(this, platformIsMobile()); if (firstLoad) { this.registerEditorExtension(this.extensions); } else { - app.workspace.updateOptions(); + this.app.workspace.updateOptions(); } } quickOpen() { @@ -55982,7 +66074,7 @@ var MakeMDPlugin = class extends import_obsidian65.Plugin { quickOpenModal.open(); } toggleBold() { - const cm = getActiveCM(); + const cm = getActiveCM(this); if (cm) { cm.dispatch({ annotations: toggleMark.of("strong") @@ -55990,7 +66082,7 @@ var MakeMDPlugin = class extends import_obsidian65.Plugin { } } toggleEm() { - const cm = getActiveCM(); + const cm = getActiveCM(this); if (cm) { cm.dispatch({ annotations: toggleMark.of("em") @@ -56009,8 +66101,12 @@ var MakeMDPlugin = class extends import_obsidian65.Plugin { this.registerEvent(this.app.vault.on("create", this.onCreate)); this.registerEvent(this.app.vault.on("delete", this.onDelete)); this.registerEvent(this.app.vault.on("rename", this.onRename)); - this.registerEvent(this.app.vault.on("modify", this.onModify)); this.app.metadataCache.on("changed", this.metadataChange); + if (makeMDVersion > this.settings.releaseNotesPrompt) { + this.releaseTheNotes(); + this.settings.releaseNotesPrompt = makeMDVersion; + this.saveSettings(); + } if (this.dataViewAPI()) { this.registerEvent( this.app.metadataCache.on("dataview:index-ready", () => { @@ -56022,7 +66118,7 @@ var MakeMDPlugin = class extends import_obsidian65.Plugin { "dataview:metadata-change", (type, file, oldPath) => { if (type === "update" && this.app.metadataCache.fileCache[file.path].mtime >= this.loadTime && this.dataViewAPI().index.revision !== this.dataViewLastIndex && this.dataViewReady) { - if (file instanceof import_obsidian65.TFile) { + if (file instanceof import_obsidian67.TFile) { this.metadataChange(file); } this.dataViewLastIndex = this.dataViewAPI().index.revision; @@ -56046,104 +66142,83 @@ var MakeMDPlugin = class extends import_obsidian65.Plugin { this.settings.spacesEnabled ); if (!this.settings.spacesDisablePatch) - patchFileExplorer(this); + patchFilesPlugin(this); this.registerView(FILE_TREE_VIEW_TYPE, (leaf) => { return new FileTreeView(leaf, this); }); } this.registerEvent( - app.workspace.on("active-leaf-change", () => this.activeFileChange()) + this.app.workspace.on("active-leaf-change", () => this.activeFileChange()) ); } convertFolderNote() { - const activeLeaf = app.workspace.activeLeaf; + const activeLeaf = this.app.workspace.activeLeaf; if ((activeLeaf == null ? void 0 : activeLeaf.view.getViewType()) == "markdown") { - const view = app.workspace.getActiveViewOfType(import_obsidian65.MarkdownView); - if (view instanceof import_obsidian65.MarkdownView && view.file instanceof import_obsidian65.TFile) { + const view = this.app.workspace.getActiveViewOfType(import_obsidian67.MarkdownView); + if (view instanceof import_obsidian67.MarkdownView && view.file instanceof import_obsidian67.TFile) { noteToFolderNote(this, view.file, true); } } else { - new import_obsidian65.Notice("The view is not a note"); + new import_obsidian67.Notice("The view is not a note"); } } getActiveFile() { + var _a2, _b2, _c2; let filePath = null; - const leaf = app.workspace.activeLeaf; - const activeView2 = leaf == null ? void 0 : leaf.view; - if (!activeView2 || leaf.isFlowBlock) + let leaf = (_a2 = this.app.workspace.getActiveViewOfType(import_obsidian67.MarkdownView)) == null ? void 0 : _a2.leaf; + if (!leaf) { + leaf = (_b2 = this.app.workspace.getActiveViewOfType(SpaceView)) == null ? void 0 : _b2.leaf; + } + if (!leaf) { + leaf = (_c2 = this.app.workspace.getActiveViewOfType(FrameEditorView)) == null ? void 0 : _c2.leaf; + } + const activeView = leaf == null ? void 0 : leaf.view; + if (!activeView || leaf.isFlowBlock) return null; - if (activeView2.getViewType() == CONTEXT_VIEW_TYPE) { - const context = mdbContextByPath( - this, - activeView2.getState().contextPath - ); - if ((context == null ? void 0 : context.type) == "folder") { - const file = getAbstractFileAtPath(app, context.contextPath); - if (file) - filePath = file.path; - } - } else if (activeView2.getViewType() == "markdown") { - filePath = activeView2.file.path; + if (activeView.getViewType() == SPACE_VIEW_TYPE || activeView.getViewType() == FRAME_EDITOR_TYPE) { + return activeView.getState().path; + } else if (activeView.getViewType() == "markdown") { + filePath = activeView.file.path; modifyFlowDom(this); } return filePath; } activeFileChange() { + var _a2; const path = this.getActiveFile(); if (path) { const evt = new CustomEvent(eventTypes.activePathChange, { - detail: { path: pathByString(path) } + detail: { path: uriByString(this, path) } }); window.dispatchEvent(evt); + const leaf = (_a2 = this.app.workspace.getActiveViewOfType(FrameEditorView)) == null ? void 0 : _a2.leaf; + if (leaf == null ? void 0 : leaf.view) { + const view = leaf.view; + const evt2 = new CustomEvent(eventTypes.frameSelected, { + detail: { path: uriByString(this, `${view.getState().path}#*${view.getState().schema}`) } + }); + window.dispatchEvent(evt2); + } } } + releaseTheNotes() { + openURL("https://www.make.md/static/latest.md", this, true); + } loadCommands() { if (this.settings.spacesEnabled) { - this.addCommand({ - id: "mk-log", - name: "log", - callback: () => { - console.log(app.workspace.getActiveViewOfType(import_obsidian65.MarkdownView)); - } - }); this.addCommand({ id: "mk-collapse-folders", name: i18n_default.commandPalette.collapseAllFolders, callback: () => { - this.settings.expandedFolders = {}; + this.settings.expandedSpaces = []; this.saveSettings(); } }); this.addCommand({ - id: "mk-reveal-file", - name: i18n_default.commandPalette.revealFile, + id: "mk-release-notes", + name: i18n_default.commandPalette.releaseNotes, callback: () => { - const file = getAbstractFileAtPath(app, this.getActiveFile()); - const evt = new CustomEvent(eventTypes.revealFile, { - detail: { file } - }); - window.dispatchEvent(evt); - } - }); - this.addCommand({ - id: "mk-spaces-add-file", - name: i18n_default.commandPalette.addFileSpace, - callback: () => { - const vaultChangeModal = new AddToSpaceModal(this, [ - this.getActiveFile() - ]); - vaultChangeModal.open(); - } - }); - this.addCommand({ - id: "mk-spaces-remove-file", - name: i18n_default.commandPalette.removeFileSpace, - callback: () => { - const vaultChangeModal = new RemoveFromSpaceModal( - this, - this.getActiveFile() - ); - vaultChangeModal.open(); + this.releaseTheNotes(); } }); this.addCommand({ @@ -56151,25 +66226,6 @@ var MakeMDPlugin = class extends import_obsidian65.Plugin { name: i18n_default.commandPalette.reloadSpaces, callback: () => this.index.loadSpacesDatabaseFromDisk() }); - this.addCommand({ - id: "mk-spaces-load-backup", - name: i18n_default.commandPalette.loadBackupSpace, - callback: () => { - this.app.vault.adapter.list( - (0, import_obsidian65.normalizePath)(`${app.vault.configDir}/plugins/make-md/backups`) - ).then( - (f4) => { - const vaultChangeModal = new LoadSpaceBackupModal(this, f4.files.map((f5) => filePathToString(f5))); - vaultChangeModal.open(); - } - ); - } - }); - this.addCommand({ - id: "mk-spaces-save-backup", - name: i18n_default.commandPalette.backupSpace, - callback: () => this.index.backupSpaceDB(false) - }); this.addCommand({ id: "mk-spaces", name: i18n_default.commandPalette.openSpaces, @@ -56227,26 +66283,29 @@ var MakeMDPlugin = class extends import_obsidian65.Plugin { } } loadContext() { - this.registerView(CONTEXT_VIEW_TYPE, (leaf) => { - return new ContextView(leaf, this, CONTEXT_VIEW_TYPE); + this.registerView(SPACE_VIEW_TYPE, (leaf) => { + return new SpaceView(leaf, this, SPACE_VIEW_TYPE); + }); + this.registerView(EMBED_CONTEXT_VIEW_TYPE, (leaf) => { + return new EmbedContextView2(leaf, this); }); if (this.settings.contextEnabled) { this.registerView(FILE_VIEW_TYPE, (leaf) => { return new FileLinkView(leaf, this, FILE_VIEW_TYPE); }); + this.registerView(FRAME_EDITOR_TYPE, (leaf) => { + return new FrameEditorView(leaf, this, FRAME_EDITOR_TYPE); + }); this.app.workspace.onLayoutReady(async () => { if (!getAbstractFileAtPath( - this.app, - getFolderPathFromString(this.settings.tagContextFolder) + this, + getFolderPathFromString(this, this.settings.spacesFolder) )) { - this.app.vault.createFolder(this.settings.tagContextFolder); + this.app.vault.createFolder(this.settings.spacesFolder); } }); this.registerView(FILE_CONTEXT_VIEW_TYPE, (leaf) => { - return new FileContextLeafView(leaf, this); - }); - this.registerView(EMBED_CONTEXT_VIEW_TYPE, (leaf) => { - return new EmbedContextView(leaf, this); + return new ContextExplorerLeafView(leaf, this); }); this.registerView(MDB_FILE_VIEWER_TYPE, (leaf) => { return new MDBFileViewer(leaf, this); @@ -56278,7 +66337,7 @@ var MakeMDPlugin = class extends import_obsidian65.Plugin { }; removeAllFlowMarks(element); replaceAllTables(this, element, context); - replaceAllEmbed(element, context); + replaceAllEmbed(element, context, this); }); window.addEventListener( eventTypes.spawnPortal, @@ -56318,21 +66377,23 @@ var MakeMDPlugin = class extends import_obsidian65.Plugin { this.registerEditorSuggest(new StickerMenu(this.app, this)); } if (platformIsMobile() && this.settings.mobileMakeBar && this.settings.inlineStyler) - loadStylerIntoContainer(app.mobileToolbar.containerEl, this); + loadStylerIntoContainer(this.app.mobileToolbar.containerEl, this); } } async onload() { console.time("Loading Make.md"); this.loadTime = Date.now(); - (0, import_obsidian65.addIcon)("mk-logo", mkLogo); + this.metadata = MetadataMiddleware.create(this, 0 /* Obsidian */); + this.files = FilesystemMiddleware.create(this, 0 /* Obsidian */); + (0, import_obsidian67.addIcon)("mk-logo", mkLogo); await this.loadSettings(); this.index = this.addChild( - Superstate.create(this.app, "0.8", () => { + Superstate.create(this.app, "0.9", () => { this.debouncedRefresh(); }, this) ); - this.spacesDBPath = (0, import_obsidian65.normalizePath)( - app.vault.configDir + "/plugins/make-md/Spaces.mdb" + this.spacesDBPath = (0, import_obsidian67.normalizePath)( + this.app.vault.configDir + "/plugins/make-md/Spaces.mdb" ); this.loadSuperState(); this.addSettingTab(new MakeMDPluginSettingsTab(this.app, this)); @@ -56357,7 +66418,7 @@ var MakeMDPlugin = class extends import_obsidian65.Plugin { } async loadSettings() { this.settings = Object.assign({}, DEFAULT_SETTINGS, await this.loadData()); - const userConfig = safelyParseJSON(await defaultConfigFile(this.app)); + const userConfig = safelyParseJSON(await defaultConfigFile(this)); this.settings.newFileFolderPath = userConfig.newFileFolderPath; this.settings.newFileLocation = userConfig.newFileLocation; this.saveSettings(); @@ -56381,6 +66442,11 @@ var MakeMDPlugin = class extends import_obsidian65.Plugin { this.detachFileTreeLeafs(); } }; +/* +object-assign +(c) Sindre Sorhus +@license MIT +*/ /*! Copyright (c) 2018 Jed Watson. Licensed under the MIT License (MIT), see @@ -56431,3 +66497,11 @@ var MakeMDPlugin = class extends import_obsidian65.Plugin { * * @license MIT */ +/** @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. + */ diff --git a/manifest.json b/manifest.json index 1f350a6..94a23f6 100755 --- a/manifest.json +++ b/manifest.json @@ -1,7 +1,7 @@ { "id": "make-md", "name": "MAKE.md", - "version": "0.7.31", + "version": "0.8.4", "minAppVersion": "0.16.0", "description": "Make.md brings you features that supercharges Obsidian. Sort your files in custom order and add file icons using Spaces. Edit inline embeds with Flow Editor. And style your text and add new markdown blocks without writing markdown using Maker Mode.", "author": "MAKE.md", diff --git a/styles.css b/styles.css index 06cb0fc..ac38aff 100644 --- a/styles.css +++ b/styles.css @@ -11,9 +11,6 @@ background-color: unset !important; gap: 0; } -.mk-space-settings { - margin-bottom: 12px; -} .menu-item-title { display: flex; justify-content: space-between; @@ -39,13 +36,28 @@ } .mk-options-menu { position: relative; - width: 180px; + width: 240px; font-size: 1em; line-height: 1.2; display: flex; flex-wrap: wrap; cursor: text; } +.mk-options-menu-sections { + display: flex; + padding: 6px 8px; + width: 100%; + gap: 8px; +} +.mk-options-menu-section { + background: var(--background-primary); + padding: 4px 6px; + border-radius: 4px; +} +.mk-options-menu-section.is-active { + background: var(--interactive-accent); + color: var(--text-on-accent); +} .mk-options-menu__selected-tag { display: inline-block; box-sizing: border-box; @@ -102,11 +114,6 @@ max-height: 200px; overflow: auto; } -@media screen and (min-width: 30em) { - .mk-options-menu__suggestions { - width: 240px; - } -} .mk-options-menu__suggestions ul { margin: 4px -1px; padding: 0; @@ -121,6 +128,8 @@ border-radius: var(--radius-s); display: flex; flex-direction: row; + align-items: center; + gap: 6px; } .mk-options-menu__suggestions li .mk-options-menu-inner { flex: 1; @@ -444,1044 +453,1004 @@ border-radius: 0; } -/* src/css/Table.css */ -.mk-folder-view { - height: 100%; -} -body { - --context-padding: var(--size-4-6); +/* src/css/SpaceEditor.css */ +.mk-space-editor { + display: flex; + flex-direction: column; + margin-bottom: 20px; + gap: 24px; + flex: 1; + overflow-y: scroll; } -.mk-th { - position: relative; +.mk-space-editor-appearance .mk-file-icon, +.mk-space-editor-appearance .mk-file-icon button, +.mk-space-editor-appearance .mk-file-icon svg { + width: 48px; + height: 48px; + font-size: 36px; } -.is-mobile .mk-resizer { - width: 8px; - opacity: 0.05; +.mk-space-editor-appearance .mk-file-icon svg { + padding: 6px; } -.mk-resizer { - position: absolute; - right: 0; - top: 0; +.mk-space-query { + display: flex; + flex-direction: column; height: 100%; - width: 2px; - background: var(--divider-color); - cursor: col-resize; - user-select: none; - touch-action: none; - opacity: 0; } -.mk-resizer.mk-resizer-active { - opacity: 1; +.mk-space-editor-title { + font-size: var(--font-ui-large); + font-weight: var(--font-semibold); + line-height: var(--line-height-tight); + padding: var(--size-4-2) var(--size-4-1); + display: flex; + gap: 8px; } -.mk-resizer.isResizing { - background: var(--interactive-hover); - opacity: 1; +.mk-space-editor-title span { + flex: 1; } -.mk-resizer:hover { - opacity: 1; +.mk-space-editor-contents { + display: flex; + flex-direction: column; + gap: 4px; } -.mk-col-header { - overflow-x: hidden; - text-overflow: ellipsis; - padding: 0.5rem 0.75rem; +.mk-space-editor-controls { display: flex; - align-items: center; - font-size: var(--font-smaller); - font-weight: var(--font-normal); - color: var(--text-muted); - text-transform: capitalize; + justify-content: space-between; } -.mk-col-header-context { - margin-left: 4px; - color: var(--text-faint); +.mk-space-editor-link { + display: flex; + padding: 8px; + font-size: var(--font-ui-small); + color: var(--text-muted); + gap: 6px; + align-items: center; + background: var(--background-modifier-cover); + border-radius: 6px; } -.mk-td { - padding: 0.5rem; - vertical-align: top; +.mk-space-editor-link span { + flex: 1; } -.mk-td > div { - min-height: 28px; +.mk-space-editor-contents .mk-query { + background: var(--background-modifier-cover); + margin-left: 8px; } -.mk-td-group { - background-color: var(--background-primary); - padding: 0.5rem; - border-top: 0.5px solid var(--divider-color) !important; - font-size: var(--font-ui-small); - font-weight: var(--bold-weight); +.mk-space-editor-contents .mk-query-group-type { + width: 24px; + padding: 4px; } -.mk-td-group .mk-cell-option { - width: unset; +.mk-space-editor-appearance { + display: flex; + width: 100%; + gap: 16px; + align-items: center; } -.mk-td-group .mk-cell-option-item { +.mk-space-editor-input input { + font-weight: var(--inline-title-weight); + font-size: var(--inline-title-size); + line-height: var(--inline-title-line-height); + font-style: var(--inline-title-style); + font-variant: var(--inline-title-variant); + font-family: var(--inline-title-font); + color: var(--inline-title-color); background: none; + outline: none; + border: none; } -.mk-td-group .mk-cell-option-item div:hover { - background: none; + +/* src/css/FrameProps.css */ +body:not(.is-mobile) .mk-frame-props-editor { } -.mk-td-empty { - padding: 0 !important; +.mk-frame-props-editor { + display: flex; + position: absolute; + top: -40px; + padding: 0; + z-index: var(--layer-popover); + background: var(--background-primary); + max-height: unset; } -.mk-td input[type=text], -.mk-td input[type=number] { - display: table-cell; - width: 100%; - border: 0; - outline: 0; +.is-mobile .mk-frame-props-editor svg { + width: 32px; + height: 32px; } -.mk-table { +.is-mobile .mk-frame-props-editor { + --mobile-toolbar-height: 48px; + border-radius: 0; width: 100%; - overflow-x: scroll; - padding-bottom: 60px; + margin-top: 0; + overflow-x: auto; + justify-content: center; + height: var(--mobile-toolbar-height); + border-top: var(--divider-width) solid var(--divider-color); } -.mk-table table { - border-spacing: 0; - border-bottom: 0.5px solid var(--divider-color) !important; +.mk-frame-props-editor .mk-mark { + margin: 4px; + padding: 4px; + border-radius: 4px; + display: flex; + font-size: var(--font-ui-small); + align-items: center; + gap: 4px; } -.mk-table table th:last-child { - width: 100%; +.mk-frame-props-editor .mk-mark:hover { + background: var(--background-modifier-hover); } -.mk-table th:hover { - background: var(--interactive-hover); +.mk-frame-props-editor .mk-mark-active { + background: var(--background-modifier-hover); } -.mk-table tr th:first-child .mk-col-header, -.mk-table tr td:first-child { - padding-left: calc(var(--context-padding) - 0.75rem); +.mk-frame-props-editor svg { + color: var(--text-muted); + width: 16px; + height: 16px; } -.mk-cell-empty { - color: var(--text-faint); +.mk-divider { + border-left: thin solid var(--background-modifier-hover); + width: 1px; } -.mk-td img { - max-height: 45px; +mark { + color: unset; + border-radius: 2px; + margin: 0px 2px; + padding: 0px 2px; } -.mk-table tr td:first-child.mk-td-empty { - padding-left: calc(var(--context-padding) - 0.75rem) !important; + +/* src/css/SpaceView.css */ +.mk-space-scroller { + display: flex !important; + flex-direction: column; + align-items: flex-start !important; + line-height: 1.4; + height: 100%; + overflow-x: auto; + position: relative; + z-index: 0; + padding-bottom: 0; } -.mk-table td { - border-top: 0.5px solid var(--background-modifier-border) !important; +.mk-context-selector { font-size: var(--font-ui-small); + --tag-background: var(--background-secondary); + position: relative; + display: flex; } -.mk-table .mk-td:not(:last-child) { - border-right: 0.5px solid var(--background-modifier-border) !important; +.mk-context-selector-menu { } -.mk-cell-object { - display: flex; - flex-direction: column; +.mk-context-header { + margin: var(--file-margins); + margin-bottom: 0; } -.mk-cell-object-row { +.mk-title-container { display: flex; + align-items: center; + gap: 4px; } -.mk-cell-text { - padding: 4px; +.mk-title-container .mk-title-prefix { + display: flex; + font-size: var(--inline-title-size); + font-weight: var(--inline-title-weight); } -.mk-cell-number { - padding: 4px; - text-align: right; +.mk-title-container span { + flex: 1; } -.mk-cell-text:not(:focus) { - background: unset !important; +.mk-context-header { + display: flex; + flex-direction: column; + max-width: var(--file-line-width); + width: 100%; } -.mk-cell-image:hover > .mk-image-selector { - visibility: visible; +.markdown-source-view.mod-cm6.is-readable-line-width .mk-space-outer { + padding: var(--file-margins); + max-width: 100%; + width: 100%; + margin-left: auto; + margin-right: auto; } -.mk-cell-image { +.mk-space-title { position: relative; } -.mk-button-new { - background: var(--interactive-accent) !important; - color: var(--text-normal) !important; +.mk-space-header { + margin-left: auto; + margin-right: auto; + margin-bottom: 16px; + width: 100%; + max-width: var(--file-line-width); } -.mk-image-selector { - position: absolute; - visibility: hidden; - top: 0px; - left: 0px; - z-index: var(--layer-popover); - padding-right: 8px; - height: 30px; +body:not(.is-mobile) .markdown-source-view.mod-cm6.is-readable-line-width .mk-space-header .inline-title { + flex-grow: 1; + margin-bottom: 0; + margin-left: 0 !important; + margin-right: 0; + width: inherit; + max-width: inherit; +} +.mk-space-sizer { display: flex; - gap: 6px; + flex-direction: column; + align-items: stretch; + margin-left: auto; + margin-right: auto; } -.mk-cell-image img { - max-height: 100px; - overflow: hidden; - border-radius: 4px; +.mk-file-table-header { + margin-top: 24px; + color: var(--text-faint); } -.mk-cell-date { +.mk-file-table { + border-collapse: collapse; + table-layout: fixed; width: 100%; - min-height: 30px; - display: flex; - align-items: center; } -.mk-cell-date-value { - border-radius: 4px; - padding: 2px 4px; +.mk-space-body { + padding-bottom: 100px; } -.mk-cell-date-value:hover { - background: var(--interactive-hover); +.mk-space-body > .mk-f { + max-width: var(--file-line-width); + margin: 0 auto; } -.mk-cell-link, -.mk-cell-context, -.mk-cell-option { - width: 100%; - min-height: 24px; - padding: 4px 0px; - gap: 4px; - display: flex; - flex-wrap: wrap; +.mk-f-main > div { + max-width: var(--file-line-width); + margin: 0 auto; + padding-bottom: 8px; } -.mk-cell-boolean { - padding: 4px; - display: flex; - align-items: center; - gap: 2px; +.mk-space-body .cm-content { + padding-bottom: 0px !important; } -.mk-cell-option-item { - background: rgba(var(--mono-rgb-100), 0.025); - border-radius: 4px; - overflow: hidden; +.mk-space-body > .mk-frame { + align-items: flex-start; display: flex; - align-items: center; - gap: 2px; + flex-direction: column; + gap: 8px; } -.mk-cell-option-item.mk-is-active { - background: var(--interactive-accent) !important; +.mk-file-row { } -.mk-cell-option-item input { - margin: 0; +.mk-file-row:hover { + background: var(--background-modifier-hover) !important; } -.mk-cell-option-item div { - padding: 2px 4px; - height: 100%; - display: -webkit-box; - -webkit-line-clamp: 1; - line-clamp: 1; - -webkit-box-orient: vertical; +.mk-file-table tr:nth-child(even) { + background: var(--color-base-10); } -.mk-cell-option-item div:hover { - background: var(--interactive-hover); +.mk-file-row td { + padding: 10px 10px; } -.mk-cell-fileprop { - padding: 4px; - color: var(--text-muted); +.mk-file-row .mk-column-file { + width: 99%; } -.mk-cell-file { - display: flex; - align-items: center; +.mk-file-row p { + text-overflow: ellipsis; + overflow: hidden; + font-size: var(--font-ui-smaller); + color: var(--text-faint); + margin: 0; + -webkit-line-clamp: 2; + -webkit-box-orient: vertical; + display: -webkit-box; } -.mk-cell-file-title { - font-size: var(--font-ui-medium); - margin-bottom: 8px; +.mk-file-row .mk-file-name { + font-weight: var(--font-medium); } -.mk-cell-file-new { - display: flex; - align-items: center; +.mk-file-date { + font-size: var(--font-ui-smaller); + color: var(--text-muted); + width: 100px; } -.mk-cell-file-new .mk-file-icon svg { - color: var(--text-faint); +.mk-column-icon { + width: 40px; } -.mk-table:focus .mk-is-active { - background: var(--background-modifier-active-hover) !important; +.mk-column-icon svg { + width: 16px; + height: 16px; + color: var(--text-muted); } -.mk-floweditor .mk-table:not(:focus) .mk-is-active { - background: none !important; +.mk-flowspace-title svg { + width: 16px; + height: 16px; + color: var(--text-muted); } -.mk-table:focus .mk-is-active .mk-selected-cell { - outline: solid 2px var(--interactive-accent); +.mk-flowspace-title p { + margin: 0; + padding: 0; + margin-left: 8px; } -.mk-cell-file-new .mk-file-icon:hover { - background: var(--interactive-hover); +.mk-flowspace-title .mk-flowspace-date { + font-size: var(--font-ui-smaller); + color: var(--text-muted); } -.mk-cell-file-item { +.mk-flowspace-title { display: flex; align-items: center; + padding: 8px 12px; + border-top: 1px solid var(--divider-color); } -.mk-cell-file-item .mk-file-icon:hover { - background: var(--interactive-hover); -} -.mk-cell-file-item .mk-cell-file-name { - padding: 2px 4px; - border-radius: 4px; -} -.mk-cell-file-item .mk-cell-file-name:hover { - background: var(--interactive-hover); +.mk-flowspace-editor { + padding: 0px 12px; + width: 100%; } -.mk-cell-file .mk-file-icon { - margin-right: 4px; - align-items: center; - display: flex; - width: 24px; - border-radius: 4px; +.mk-flowspace-editor:not(.mk-flow-node, .mk-file-context-flow) .mk-floweditor { + padding: 12px 0px; } -.mk-cell-file-new .mk-cell-file-name { - padding: 4px !important; - background: none !important; +.mk-frame-view .mk-flowspace-editor:not(.mk-flow-node, .mk-file-context-flow) .mk-floweditor { + padding: 0; } -.is-phone .mk-cell-file-flow { - display: none; +.mk-flowspace-editor.mk-foldernote { + width: var(--file-line-width); + max-width: 100%; + margin-left: auto; + margin-right: auto; } -.mk-list-item .mk-cell-file-flow { - visibility: hidden; - margin-left: 4px; - padding: 2px 4px; +.mk-foldernote .mk-floweditor { + height: 100% !important; } -.mk-list-item:hover .mk-cell-file-flow { - visibility: visible; +.mk-flowspace-title span { + flex-grow: 1; } -.is-phone .mk-list-item .mk-cell-file-flow { +.mk-flowspace-title button { + padding: 8px; + margin-left: 8px; width: unset; - visibility: unset; -} -.mk-list-item .mk-cell-file-flow:hover { - border-radius: 4px; - background: var(--interactive-hover); -} -.mk-row-new { - text-align: left; - border-top: 0.5px solid var(--divider-color) !important; - padding: 8px var(--context-padding) !important; - font-weight: normal !important; - color: var(--text-faint) !important; - font-size: var(--font-ui-small) !important; -} -.markdown-rendered .mk-table td, -.markdown-rendered .mk-table th { - border: unset; } -.mk-row-new:hover { - background: var(--background-modifier-hover); +.mk-flowspace-title button.mk-open { + background: var(--icon-color-active); } -.mk-icon-small svg { - width: 16px; - height: 16px; - color: var(--text-muted); +.mk-flowspace-title:hover { + background: var(--color-base-10); } -.mk-icon-small, -.mk-icon-xsmall { +.mk-space-empty { + width: 100%; + height: 100%; display: flex; align-items: center; + justify-content: center; + font-size: var(--font-ui-small); + font-style: italic; } -.mk-icon-xxsmall svg { - width: 10px; - height: 10px; - color: var(--text-muted); -} -.mk-icon-xsmall svg { - width: 12px; - height: 12px; - color: var(--text-muted); +.mk-flow-container { + width: 100%; } -.mk-icon-rotated svg { - transform: rotate(90deg); +.mk-flow-container > div { + border-bottom: thin dotted var(--divider-color); } -.mk-cell-link-item { - color: var(--link-color); - display: flex; +.mk-flow-container > div > span { + font-size: var(--font-smallest); + padding: var(--size-4-1) var(--context-padding); + color: var(--text-faint); } -.mk-cell-option span { - flex-grow: 1; +.mk-space-scroller .mk-flowspace-editor { + padding: 0; } -.mk-cell-option-select { - display: flex; - align-items: center; +.mk-space-scroller .cm-sizer { } -.mk-cell-option-new { - visibility: hidden; - background: rgba(var(--mono-rgb-100), 0.025); - padding: 2px; +.mk-smart-note-view { display: flex; - border-radius: 4px; } -.mk-cell-link:hover .mk-cell-option-new, -.mk-cell-context:hover .mk-cell-option-new, -.mk-cell-option:hover .mk-cell-option-new { - visibility: visible; +.mk-smart-note-view div { + padding: 4px; } -.mk-cell-link-unresolved { - color: var(--link-unresolved-color); - opacity: var(--link-unresolved-opacity); - filter: var(--link-unresolved-filter); +.mk-context-type-selector { + max-width: 100%; + width: 100%; + padding-top: 4px; + margin-left: auto; + margin-right: auto; } -.mk-cell-link-unresolved:hover { - color: var(--link-unresolved-color); - opacity: var(--link-unresolved-opacity); - filter: var(--link-unresolved-filter); +.mk-context-type-selector button { + background: rgba(var(--nav-item-background-active), 0.3); + border: none; + box-shadow: none; + color: var(--text-faint); } -/* src/css/ContextBuilder.css */ -.is-phone .mk-context-maker { - max-height: 100vh; +/* src/css/CardsView.css */ +.mk-space-scroller > .mk-cards-container { + padding-bottom: 60px; } -.mk-context-maker-container { +.mk-cards-container { + width: 100%; height: 100%; - display: flex; - flex-direction: column; + overflow-x: auto; + overflow-y: visible; } -.mk-context-maker .modal-content { - height: var(--dialog-max-height); +.mk-cards-container .mk-list-content > .mk-flowspace-editor { + padding-left: 12px !important; + padding-right: 12px !important; } -.mk-context-maker-preview { - display: flex; - flex-wrap: wrap; - gap: 4px; - margin-bottom: 16px; - padding: var(--size-4-4); - flex-grow: 1; - overflow: scroll; - padding-bottom: 0; +.mk-cards-container .mk-list-view { + display: inline-grid; + grid-auto-flow: column; + gap: 20px; } -.mk-context-maker-item { - background: rgba(var(--mono-rgb-100), 0.025); +.mk-space-scroller > .mk-cards-container .mk-list-view { + padding: 20px; +} +.mk-cards-container .mk-list-item { border-radius: 4px; + list-style: none; + background: var(--background-secondary); overflow: hidden; - display: flex; - align-items: center; - gap: 2px; - padding: 8px; -} -.mk-context-maker-selector { font-size: var(--font-ui-small); - height: 240px; - overflow-y: scroll; - background: rgba(var(--mono-rgb-100), 0.025); - padding: var(--size-4-4); - border-radius: 4px; + color: var(--text-muted); + box-shadow: + 0px 1px 2px rgba(0, 0, 0, 0.06), + 0px 3.4px 6.7px rgba(0, 0, 0, 0.06), + 0px 15px 30px rgba(0, 0, 0, 0.15); } -.mk-context-maker-selector .mk-cell-option { - margin-bottom: 8px; +.mk-cards-container .mk-list-group { + width: 200px; } -.mk-context-maker-builder { - min-height: 60px; - display: flex; - flex-wrap: wrap; - padding: 8px; - gap: 4px; +.mk-cards-grid .mk-list-item { + width: 250px; } -.mk-context-maker { - padding: 0; +.mk-cards-container .mk-file-icon svg { + display: none; } -.mk-context-maker-layout > div > div { - border-bottom: thin solid var(--divider-color); - padding: 4px; +.mk-cards-grid .mk-list-group { + width: 100% !important; +} +.mk-cards-grid .mk-list-group ul { + flex-direction: row !important; + flex-wrap: wrap; } -.mk-context-maker-layout > div { +.mk-cards-container .mk-list-group ul { + list-style: none; + padding-inline-start: 0px; display: flex; flex-direction: column; - gap: 8px; + gap: 10px; } - -/* src/css/FilterBar.css */ -.mk-view-selector, -.mk-table-selector { - margin-right: 0; +.mk-list-container .mk-list-group-header { display: flex; - align-items: center; - gap: 16px; - min-height: 48px; - max-width: 100%; - overflow-x: auto; + padding: 12px 24px 4px 24px; + background-color: var(--titlebar-background); } -.mk-view-selector-spacer { - min-width: var(--context-padding); - width: var(--file-margins); +.mk-list-container .mk-list-group-header > div { + background: none !important; } -.mk-view-selector::-webkit-scrollbar { - display: none; +.mk-floweditor > .workspace-leaf > .workspace-leaf-content > .view-content > div > .mk-list-container { + padding-bottom: 0; } -.mk-view-selector > div > .mk-collapse { - padding-right: 8px; - padding-left: 0px; +.mk-floweditor > .workspace-leaf > .workspace-leaf-content > .view-content > div > .mk-list-container .mk-list-item { + padding: 8px; } -.mk-view-selector .mk-collapse.mk-icon-xsmall svg { - color: unset; +.mk-space-scroller > .mk-list-container { + padding-bottom: 100px; } -.mk-view-selector > div > button:not(:last-child) { - padding-right: 0px; +.mk-list-container { + width: 100%; + height: 100%; + overflow-y: auto; } -.mk-view-selector > div, -.mk-view-selector > button { - border-radius: 0; - margin: 4px -8px; +.mk-list-container .mk-list-view { + display: flex; + flex-direction: column; +} +.mk-cards-container .mk-list-item.mk-is-active, +.mk-list-container .mk-list-item.mk-is-active { + background: var(--background-modifier-active-hover); +} +.mk-list-container .mk-list-item { + display: flex; + padding: 8px; + list-style: none; + font-size: var(--font-ui-small); + color: var(--text-muted); + align-items: flex-start; +} +.mk-list-container .mk-list-content { + flex-grow: 1; + display: flex; + flex-direction: column; + border-bottom: thin solid var(--divider-color); + min-height: 69px; +} +.mk-list-container .mk-list-fields { display: flex; + flex-wrap: wrap; align-items: center; - border-bottom: thin solid transparent; - height: 100%; + gap: 8px; + padding-bottom: 8px; } -.mk-view-config .mk-is-active button { - color: var(--text-normal); +.mk-list-container .mk-list-fields > div { + margin-bottom: -8px; } -.mk-view-config .mk-is-active { - border-bottom: thin solid var(--text-normal); - color: var(--text-normal); - background: none !important; +.mk-list-container .mk-list-fields > div:not(.mk-cell-file):not(.mk-cell-image) { + width: unset !important; } -.mk-table-selector button, -.mk-view-config button { - background: rgba(var(--nav-item-background-active), 0.3); - border: none; - box-shadow: none; - color: var(--text-faint); +.mk-list-container .mk-list-fields > .mk-cell-image { + width: 100%; } -.mk-view-config button:hover { +.mk-list-container .mk-list-group { + width: 100%; +} +.mk-cards-container .mk-cell-file-title, +.mk-list-container .mk-cell-file-title { + padding: 4px; color: var(--text-normal); + margin-bottom: 0; } -.mk-view-config { +.mk-list-container .mk-list-fields .mk-cell-file { width: 100%; + font-weight: var(--bold-weight); +} +.mk-cards-container .mk-list-fields { + padding: 12px; + align-items: flex-start; display: flex; - color: var(--text-faint); - align-items: stretch; - border-bottom: 1px solid var(--divider-color); - flex-wrap: wrap; + flex-direction: column; } -.mk-view-config input { - background: none; - border: none; - flex-grow: 1; +.mk-list-fields .mk-cell-file-preview { + width: 100%; + color: var(--text-normal); + margin-bottom: -8px; + color: var(--text-faint); + text-overflow: ellipsis; + overflow: hidden; + -webkit-line-clamp: 1; + -webkit-box-orient: vertical; + display: -webkit-box; } -.is-phone .mk-view-config { - flex-wrap: wrap; +.mk-list-container .mk-list-group ul { + list-style: none; + padding-inline-start: 0px; + display: flex; + flex-direction: column; + margin-top: 0; + margin-bottom: 0; } -.is-phone .mk-view-config button { - width: unset; +.mk-file-preview { + background: var(--label-color); } -.mk-view-search { - background: var(--background-modifier-form-field); - border: var(--input-border-width) solid var(--background-modifier-border); - display: flex; +.mk-list-container .mk-file-preview { + min-width: 48px; + height: 48px; border-radius: 8px; + margin-right: 8px; + margin-top: 8px; + display: flex; align-items: center; - flex-grow: 1; + justify-content: center; } -.mk-view-search button:hover { - background: unset !important; +.mk-list-group-header .mk-cell-option-item { + background: none !important; } -.mk-view-search button { - margin: 0 !important; - padding: var(--size-4-1) var(--size-4-2) !important; +.mk-cards-container .mk-file-preview { + position: relative; + margin-bottom: 4px; + height: 80px; } -.is-phone .mk-view-options { - margin-top: 8px; - margin-bottom: 8px; +.mk-cards-container .mk-file-icon { + position: absolute; + bottom: -6px; + font-size: 24px; + left: 14px; } -.mk-view-options { +.mk-list-container .mk-file-icon { + font-size: 20px; display: flex; align-items: center; - color: var(--text-normal) !important; - min-height: 48px; - padding-left: var(--context-padding); - padding-right: var(--size-4-3); - flex-grow: 1; + justify-content: center; } -.mk-view-config span { - flex-grow: 10; +.mk-context-view-editor { + flex: 1; + padding: 40px; } -.mk-view-config svg { - width: 14px; - height: 14px; +.mk-context-view-editor .mk-td { + white-space: nowrap; } -.mk-filter-bar { +.mk-context-view-selector { display: flex; - padding: 8px var(--context-padding); + padding: 12px 24px; gap: 8px; - width: 100%; - border-bottom: 1px solid var(--divider-color); + border-top: thin solid var(--divider-color); } -.mk-filter-bar span { - flex-grow: 1; +.mk-context-view-selector > div { + width: 50px; + overflow: hidden; + display: -webkit-box; + -webkit-line-clamp: 2; + line-clamp: 2; + -webkit-box-orient: vertical; + text-align: center; } -.mk-view-config .mk-is-active, -.mk-table-selector .mk-is-active { - color: var(--text-normal) !important; + +/* src/css/Table.css */ +.mk-space-view { + height: 100%; } -.mk-filter { - display: flex; - font-size: var(--font-ui-small); - color: var(--text-muted); - padding: 0px; +body { + --context-padding: var(--size-4-6); } -.mk-filter > span, -.mk-filter > div { - background: var(--interactive-normal); +.mk-th { + position: relative; } -.mk-filter > span:hover, -.mk-filter > div:hover { - background: var(--interactive-hover); +.is-mobile .mk-resizer { + width: 8px; + opacity: 0.05; } -.mk-filter > *:first-child { - border-top-left-radius: 4px; - border-bottom-left-radius: 4px; - padding-left: 10px; +.mk-resizer { + position: absolute; + right: 0; + top: 0; + height: 100%; + width: 2px; + background: var(--divider-color); + cursor: col-resize; + user-select: none; + touch-action: none; + opacity: 0; } -.mk-filter > *:last-child { - border-top-right-radius: 4px; - border-bottom-right-radius: 4px; - padding-right: 6px; +.mk-resizer.mk-resizer-active { + opacity: 1; } -.mk-filter > span { - border-right: thin solid var(--background-primary); - padding: 4px 8px; - display: flex; - align-items: center; +.mk-resizer.isResizing { + background: var(--interactive-hover); + opacity: 1; } -.mk-filter div { +.mk-resizer:hover { + opacity: 1; +} +.mk-col-header { + overflow-x: hidden; + text-overflow: ellipsis; + padding: 0.5rem 0.75rem; display: flex; align-items: center; - padding-left: 4px; -} -.mk-filter div svg { - width: 14px; - height: 14px; + font-size: var(--font-ui-small); + font-weight: var(--font-normal); + color: var(--text-muted); + text-transform: capitalize; } -.mk-query { +.mk-col-header > div { display: flex; - flex-direction: column; - gap: 16px; - margin-bottom: 16px; + gap: 4px; } -.mk-query-filters { - flex-direction: column; - padding: 0; - border-bottom: none; +.mk-col-header-context { + margin-left: 4px; + color: var(--text-faint); } -.mk-query-filter, -.mk-query-group-type { - display: flex; - width: 100%; +.mk-td { + padding: 0.5rem; + vertical-align: top; } -.mk-query-group-type { - padding-bottom: 4px; +.mk-td > div { + min-height: 28px; } -.mk-query-group-type .mk-filter { - align-items: center; +.mk-td-group { + background-color: var(--background-primary); + padding: 0.5rem; + border-top: 0.5px solid var(--divider-color) !important; + font-size: var(--font-ui-small); + font-weight: var(--bold-weight); } -.mk-query-group button { - background-color: unset; - box-shadow: none; +.mk-td-group .mk-cell-option { width: unset; } -.is-phone .mk-query-group button { - background-color: var(--interative-normal); +.mk-td-group .mk-cell-option-item { + background: none; } -.mk-query-group-type > span, -.mk-query-filter > span { - flex-grow: 1; +.mk-td-group .mk-cell-option-item div:hover { + background: none; } -.mk-folder-note { - display: flex; - align-items: center; - gap: 4px; +.mk-td-empty { + padding: 0 !important; } -.mk-filter-add { - border: thin solid var(--divider-color) !important; - border-radius: 4px; - box-shadow: none !important; - background: none !important; - display: flex; - align-items: center; - padding: 4px; - font-size: var(--font-ui-small); - color: var(--text-muted); - gap: 4px; +.mk-td input[type=text], +.mk-td input[type=number] { + display: table-cell; + width: 100%; + border: 0; + outline: 0; } -.mk-filter-add div { - display: flex; +.mk-table { + width: 100%; + overflow-x: scroll; } -.mk-search-bar { +.mk-table table { + border-spacing: 0; + border-bottom: 0.5px solid var(--divider-color) !important; } -.mk-tag-selector { - display: flex; - gap: 8px; - margin-top: 8px; - margin-bottom: 8px; - flex-wrap: wrap; +.mk-table table th:last-child { + width: 100%; } -.mk-tag-selector svg { - color: var(--tag-color) !important; +.mk-table th:hover { + background: var(--interactive-hover); } -.mk-tag-selector div { - cursor: var(--cursor-link); - font-size: var(--font-ui-medium); - display: flex; +.mk-table tr th:first-child .mk-col-header, +.mk-table tr td:first-child { + padding-left: calc(var(--context-padding) - 0.75rem); } -.mk-tag-selector button { - height: auto; - border-radius: var(--tag-radius); - color: var(--tag-color); - background-color: var(--tag-background); - border: var(--tag-border-width) solid var(--tag-border-color); - box-shadow: none !important; - font-size: var(--tag-size); - vertical-align: baseline; - border-left: none; - border-right: none; - padding-top: var(--tag-padding-y) !important; - padding-bottom: var(--tag-padding-y) !important; +.mk-cell-empty { + color: var(--text-faint); } - -/* src/css/FlowComponent.css */ -.mk-folder-scroller { - display: flex !important; - flex-direction: column; - align-items: flex-start !important; - line-height: 1.4; - height: 100%; - overflow-x: auto; - position: relative; - padding: var(--file-margins); - z-index: 0; - padding-bottom: 0; +.mk-td img { + max-height: 45px; } -.mk-context-header { - margin-bottom: 0; +.mk-table tr td:first-child.mk-td-empty { + padding-left: calc(var(--context-padding) - 0.75rem) !important; } -.mk-context-header { - display: flex; - flex-direction: column; - max-width: var(--file-line-width); - width: 100%; +.mk-table td { + border-top: 0.5px solid var(--background-modifier-border) !important; + font-size: var(--font-ui-small); } -.mk-sizer-override { - min-height: auto !important; +.mk-table .mk-td:not(:last-child) { + border-right: 0.5px solid var(--background-modifier-border) !important; } -.mk-backlinks.embedded-backlinks, -.mk-sizer-override > .embedded-backlinks { - border-top: none; +.mk-cell-object { + display: flex; + flex-direction: column; + margin-left: 10px; + padding-left: 10px; + border-left: thin solid var(--divider-color); } -.markdown-source-view.mod-cm6 .mk-folder-outer { - padding: 0 var(--file-margins); - max-width: 100%; +.mk-cell-object .mk-file-context-field-key { width: 100%; - margin-left: auto; - margin-right: auto; + border: none; + border-radius: 0px; + height: 24px; } -.mk-folder-header { - margin-left: auto; - margin-right: auto; - width: 100%; +.mk-cell-object .mk-file-context-field-key:not(:focus) { + background: unset !important; } -.mk-folder-header .inline-title { - flex-grow: 1; - margin-bottom: 0; +.mk-cell-object-row { + display: flex; } -.mk-folder-sizer { +.mk-cell-radio-group { display: flex; - flex-direction: column; - align-items: stretch; - margin-left: auto; - margin-right: auto; + background-color: var(--interactive-normal); + box-shadow: var(--input-shadow); + -webkit-app-region: no-drag; + display: inline-flex; + align-items: center; + justify-content: center; + color: var(--text-normal); + font-size: var(--font-ui-small); + border-radius: var(--button-radius); + border: 0; + padding: var(--size-4-1) var(--size-4-3); + height: var(--input-height); + font-weight: var(--input-font-weight); + cursor: var(--cursor); + font-family: inherit; + outline: none; + user-select: none; + white-space: nowrap; } -.mk-file-table-header { - margin-top: 24px; - color: var(--text-faint); +.mk-cell-radio-group > div { + width: 30px; } -.mk-file-table { - border-collapse: collapse; - table-layout: fixed; - width: 100%; +.mk-cell-text { + padding: 4px; } -.mk-file-row { +.mk-cell-number { + padding: 4px; + text-align: right; } -.mk-file-row:hover { - background: var(--background-modifier-hover) !important; +.mk-cell-text:not(:focus) { + background: unset !important; } -.mk-file-table tr:nth-child(even) { - background: var(--color-base-10); -} -.mk-file-row td { - padding: 10px 10px; -} -.mk-file-row .mk-column-file { - width: 99%; +.mk-cell-image:hover > .mk-image-selector { + visibility: visible; } -.mk-file-row p { - text-overflow: ellipsis; - overflow: hidden; - font-size: var(--font-ui-smaller); - color: var(--text-faint); - margin: 0; - -webkit-line-clamp: 2; - -webkit-box-orient: vertical; - display: -webkit-box; +.mk-cell-image { + position: relative; + min-width: 40px; + min-height: 40px; } -.mk-file-row .mk-file-name { - font-weight: var(--font-medium); +.mk-button-new { + background: var(--interactive-accent) !important; + color: var(--text-on-accent) !important; } -.mk-file-date { - font-size: var(--font-ui-smaller); - color: var(--text-muted); - width: 100px; +.mk-image-selector { + position: absolute; + visibility: hidden; + top: 0px; + left: 0px; + z-index: var(--layer-popover); + padding-right: 8px; + height: 30px; + display: flex; + gap: 6px; } -.mk-column-icon { - width: 40px; +.mk-cell-image img { + max-height: 100px; + overflow: hidden; + border-radius: 4px; } -.mk-column-icon svg { - width: 16px; - height: 16px; - color: var(--text-muted); +.mk-cell-date { + width: 100%; + min-height: 30px; + display: flex; + align-items: center; } -.mk-flowspace-title svg { - width: 16px; - height: 16px; - color: var(--text-muted); +.mk-cell-date-value { + border-radius: 4px; + padding: 2px 4px; } -.mk-flowspace-title p { - margin: 0; - padding: 0; - margin-left: 8px; +.mk-cell-date-value:hover { + background: var(--interactive-hover); } -.mk-flowspace-title .mk-flowspace-date { - font-size: var(--font-ui-smaller); - color: var(--text-muted); +.mk-cell-link, +.mk-cell-context, +.mk-cell-option { + width: 100%; + min-height: 24px; + padding: 4px 0px; + gap: 4px; + display: flex; + flex-wrap: wrap; } -.mk-flowspace-title { +.mk-cell-boolean { + padding: 4px; display: flex; align-items: center; - padding: 8px 12px; - border-top: 1px solid var(--divider-color); -} -.mk-flowspace-editor { - padding: 0px 12px; - width: 100%; -} -.mk-flowspace-editor:not(.mk-foldernote) .mk-floweditor { - padding: 12px 0px; + gap: 2px; } -.mk-flowspace-editor.mk-foldernote { - max-width: 100%; - margin-left: auto; - margin-right: auto; +.mk-cell-option-item { + background: rgba(var(--mono-rgb-100), 0.025); + border-radius: 4px; + overflow: hidden; + display: flex; + align-items: center; + gap: 2px; } -.mk-foldernote .mk-floweditor { - height: 100% !important; +.mk-cell-option-item.mk-is-active { + background: var(--interactive-accent) !important; } -.mk-flowspace-title span { - flex-grow: 1; +.mk-cell-option-item input { + margin: 0; } -.mk-flowspace-title button { - padding: 8px; - margin-left: 8px; - width: unset; +.mk-cell-option-item div { + padding: 2px 4px; + height: 100%; + display: -webkit-box; + -webkit-line-clamp: 1; + line-clamp: 1; + -webkit-box-orient: vertical; } -.mk-flowspace-title button.mk-open { - background: var(--icon-color-active); +.mk-cell-option-item div:hover { + background: var(--interactive-hover); } -.mk-flowspace-title:hover { - background: var(--color-base-10); +.mk-cell-fileprop { + padding: 4px; + color: var(--text-muted); } -.mk-folder-empty { - width: 100%; - height: 100%; +.mk-cell-file { display: flex; align-items: center; - justify-content: center; - font-size: var(--font-ui-small); - font-style: italic; } -.mk-flow-container { - width: 100%; +.mk-cell-file-title { + font-size: var(--font-ui-medium); + margin-bottom: 8px; } -.mk-flow-container > div { - border-bottom: thin dotted var(--divider-color); +.mk-cell-file-new { + display: flex; + align-items: center; } -.mk-flow-container > div > span { - font-size: var(--font-smallest); - padding: var(--size-4-1) var(--context-padding); +.mk-cell-file-new .mk-file-icon svg { color: var(--text-faint); } -.mk-folder-scroller .mk-flowspace-editor { - padding: 0; +.mk-table:focus .mk-is-active { + background: var(--background-modifier-active-hover) !important; } -.mk-folder-scroller .cm-sizer { +.mk-floweditor .mk-table:not(:focus) .mk-is-active { + background: none !important; } - -/* src/css/CardsView.css */ -.mk-folder-view .mk-cards-container { - padding-bottom: 60px; +.mk-table:focus .mk-is-active .mk-selected-cell { + outline: solid 2px var(--interactive-accent); } -.mk-cards-container { - width: 100%; - height: 100%; - overflow-x: auto; - overflow-y: visible; +.mk-cell-file-new .mk-file-icon:hover { + background: var(--interactive-hover); } -.mk-cards-container .mk-list-content > .mk-flowspace-editor { - padding-left: 12px !important; - padding-right: 12px !important; +.mk-cell-file-item { + display: flex; + align-items: center; } -.mk-cards-container .mk-list-view { - display: inline-grid; - grid-auto-flow: column; - padding: 20px; - gap: 20px; +.mk-cell-file-item .mk-file-icon:hover { + background: var(--interactive-hover); } -.mk-cards-container .mk-list-item { +.mk-cell-file-item .mk-cell-file-name { + padding: 2px 4px; border-radius: 4px; - list-style: none; - background: var(--background-secondary); - overflow: hidden; - font-size: var(--font-ui-small); - color: var(--text-muted); - box-shadow: - 0px 1px 2px rgba(0, 0, 0, 0.06), - 0px 3.4px 6.7px rgba(0, 0, 0, 0.06), - 0px 15px 30px rgba(0, 0, 0, 0.15); } -.mk-cards-container .mk-list-group { - width: 200px; +.mk-cell-file-item .mk-cell-file-name:hover { + background: var(--interactive-hover); } -.mk-cards-grid .mk-list-item { - width: 250px; +.mk-cell-file .mk-file-icon { + margin-right: 4px; + align-items: center; + display: flex; + width: 24px; + border-radius: 4px; } -.mk-cards-container .mk-file-icon svg { +.mk-cell-file-new .mk-cell-file-name { + padding: 4px !important; + background: none !important; +} +.is-phone .mk-cell-file-flow { display: none; } -.mk-cards-grid .mk-list-group { - width: 100% !important; +.mk-list-item .mk-cell-file-flow { + visibility: hidden; + margin-left: 4px; + padding: 2px 4px; } -.mk-cards-grid .mk-list-group ul { - flex-direction: row !important; - flex-wrap: wrap; +.mk-list-item:hover .mk-cell-file-flow { + visibility: visible; } -.mk-cards-container .mk-list-group ul { - list-style: none; - padding-inline-start: 0px; - display: flex; - flex-direction: column; - gap: 10px; +.is-phone .mk-list-item .mk-cell-file-flow { + width: unset; + visibility: unset; } -.mk-list-container .mk-list-group-header { - display: flex; - padding: 12px 24px 4px 24px; - background-color: var(--titlebar-background); +.mk-list-item .mk-cell-file-flow:hover { + border-radius: 4px; + background: var(--interactive-hover); } -.mk-list-container .mk-list-group-header > div { - background: none !important; +.mk-row-new { + text-align: left; + border-top: 0.5px solid var(--divider-color) !important; + padding: 8px var(--context-padding) !important; + font-weight: normal !important; + color: var(--text-faint) !important; + font-size: var(--font-ui-small) !important; } -.mk-floweditor > .workspace-leaf > .workspace-leaf-content > .view-content > div > .mk-list-container { - padding-bottom: 0; +.markdown-rendered .mk-table td, +.markdown-rendered .mk-table th { + border: unset; } -.mk-floweditor > .workspace-leaf > .workspace-leaf-content > .view-content > div > .mk-list-container .mk-list-item { - padding: 8px; +.mk-row-new:hover { + background: var(--background-modifier-hover); } -.mk-folder-view .mk-list-container { - padding-bottom: 100px; -} -.mk-list-container { - width: 100%; - height: 100%; - overflow-y: auto; -} -.mk-list-container .mk-list-view { - display: flex; - flex-direction: column; -} -.mk-cards-container .mk-list-item.mk-is-active, -.mk-list-container .mk-list-item.mk-is-active { - background: var(--background-modifier-active-hover); -} -.mk-folder-view .mk-list-container .mk-list-item { - padding: 8px var(--context-padding) 0 var(--context-padding); -} -.mk-list-container .mk-list-item { - display: flex; - padding: 8px; - list-style: none; - font-size: var(--font-ui-small); +.mk-icon-small svg { + width: 16px; + height: 16px; color: var(--text-muted); - align-items: flex-start; } -.mk-list-container .mk-list-content { - flex-grow: 1; - display: flex; - flex-direction: column; - border-bottom: thin solid var(--divider-color); - min-height: 69px; -} -.mk-list-container .mk-list-fields { +.mk-icon-small, +.mk-icon-xsmall { display: flex; - flex-wrap: wrap; align-items: center; - gap: 8px; - padding-bottom: 8px; -} -.mk-list-container .mk-list-fields > div { - margin-bottom: -8px; -} -.mk-list-container .mk-list-fields > div:not(.mk-cell-file):not(.mk-cell-image) { - width: unset !important; -} -.mk-list-container .mk-list-fields > .mk-cell-image { - width: 100%; -} -.mk-list-container .mk-list-group { - width: 100%; -} -.mk-cards-container .mk-cell-file-title, -.mk-list-container .mk-cell-file-title { - padding: 4px; - color: var(--text-normal); - margin-bottom: 0; } -.mk-list-container .mk-list-fields .mk-cell-file { - width: 100%; - font-weight: var(--bold-weight); +.mk-icon-xxsmall svg { + width: 10px; + height: 10px; + color: var(--text-muted); } -.mk-cards-container .mk-list-fields { - padding: 12px; - align-items: flex-start; - display: flex; - flex-direction: column; +.mk-icon-xsmall svg { + width: 12px !important; + height: 12px !important; + color: var(--text-muted); } -.mk-list-fields .mk-cell-file-preview { - width: 100%; - color: var(--text-normal); - margin-bottom: -8px; - color: var(--text-faint); - text-overflow: ellipsis; - overflow: hidden; - -webkit-line-clamp: 1; - -webkit-box-orient: vertical; - display: -webkit-box; +.mk-icon-rotated svg { + transform: rotate(90deg); } -.mk-list-container .mk-list-group ul { - list-style: none; - padding-inline-start: 0px; +.mk-cell-link-item { + color: var(--link-color); display: flex; - flex-direction: column; - margin-top: 0; - margin-bottom: 0; } -.mk-file-preview { - background: var(--label-color); +.mk-cell-option span { + flex-grow: 1; } -.mk-list-container .mk-file-preview { - min-width: 48px; - height: 48px; - border-radius: 8px; - margin-right: 8px; - margin-top: 8px; +.mk-cell-option-select { display: flex; align-items: center; - justify-content: center; } -.mk-list-group-header .mk-cell-option-item { - background: none !important; +.mk-cell-option-new { + visibility: hidden; + background: rgba(var(--mono-rgb-100), 0.025); + padding: 2px; + display: flex; + border-radius: 4px; } -.mk-cards-container .mk-file-preview { - position: relative; - margin-bottom: 4px; - height: 80px; +.mk-cell-link:hover .mk-cell-option-new, +.mk-cell-context:hover .mk-cell-option-new, +.mk-cell-option:hover .mk-cell-option-new { + visibility: visible; } -.mk-cards-container .mk-file-icon { - position: absolute; - bottom: -6px; - font-size: 24px; - left: 14px; +.mk-cell-link-unresolved { + color: var(--link-unresolved-color); + opacity: var(--link-unresolved-opacity); + filter: var(--link-unresolved-filter); } -.mk-list-container .mk-file-icon { - font-size: 20px; - display: flex; - align-items: center; - justify-content: center; +.mk-cell-link-unresolved:hover { + color: var(--link-unresolved-color); + opacity: var(--link-unresolved-opacity); + filter: var(--link-unresolved-filter); } /* src/css/FlowEditor.css */ @@ -1504,8 +1473,9 @@ body { .mk-floweditor .markdown-source-view.mod-cm6 .cm-editor { min-height: auto; } -.mk-floweditor .embedded-backlinks { - display: none; +.mk-floweditor .embedded-backlinks, +.mk-floweditor .metadata-container { + display: none !important; } .mk-floweditor .workspace-leaf-content[data-type=canvas] .view-content { min-height: 600px; @@ -1530,9 +1500,6 @@ div:not(.mk-flowspace-editor) > .mk-floweditor .cm-content { .mk-floweditor .mk-floweditor-title-container { display: flex; } -.mk-hidden { - display: none !important; -} .mk-floweditor-title { padding: 8px 0px; margin: 0; @@ -1567,7 +1534,7 @@ div:not(.mk-flowspace-editor) > .mk-floweditor .cm-content { .mk-flow-minimal .mk-floweditor-container:not(.mk-floweditor-fix) > .mk-floweditor { padding: 8px; border-radius: 4px; - border: thin solid var(--divider-color); + border-left: thin solid var(--divider-color); } .mk-flow-minimal .markdown-embed-title, .mk-flow-seamless .markdown-embed-title { @@ -1641,12 +1608,16 @@ div:not(.mk-flowspace-editor) > .mk-floweditor .cm-content { .mk-floweditor-container { min-height: var(--flow-height); } +.workspace-leaf > .workspace-leaf-content, +.workspace-leaf > .workspace-leaf-content > .view-content, +.workspace-leaf > .workspace-leaf-content > .view-content > .mod-cm6 > .cm-editor > .cm-scroller { +} .mk-floweditor-container > .mk-floweditor { border: thin solid transparent; } .mk-floweditor-container > .mk-floweditor:hover { background: rgba(0, 0, 0, 0.04) !important; - border: thin solid var(--divider-color); + border-left: thin solid var(--divider-color); } .mk-flow-minimal .mk-floweditor-container > .mk-floweditor:hover { box-shadow: @@ -1683,59 +1654,900 @@ div:not(.mk-flowspace-editor) > .mk-floweditor .cm-content { .mk-flow-seamless .internal-embed > .markdown-embed > .mk-floweditor-selector, .mk-flow-seamless .internal-embed.markdown-embed > .mk-floweditor-selector { top: 8px; - right: 8px; + right: -16px; } .mk-flow-minimal .cm-line > .mk-floweditor-selector, .mk-flow-seamless .cm-line > .mk-floweditor-selector { top: 8px; - right: 8px; + right: -16px; } .mk-floweditor-selector { position: absolute; right: 0px; top: 8px; z-index: var(--layer-popover); - visibility: hidden; - height: 32px; display: flex; } .mk-flowblock-menu { border-radius: var(--radius-s); display: flex; - font-size: var(--font-ui-smaller); - border: 1px solid var(--background-modifier-border); - background: var(--interactive-normal); - box-shadow: var(--input-shadow); + font-size: var(--font-ui-smaller); + border: 1px solid var(--background-modifier-border); + background: var(--interactive-normal); + box-shadow: var(--input-shadow); +} +.mk-hover-button { + padding: var(--size-4-1); + color: var(--text-muted); +} +.mk-flowblock-menu .mk-hover-button { + padding: var(--size-4-2); + color: var(--text-muted); + border: none; + border-right: 1px solid var(--background-modifier-border); +} +.mk-flowblock-menu .mk-hover-button:last-child { + border-right: none; +} +.mk-flowblock-menu .mk-hover-button:hover { + background: var(--background-secondary-alt); +} +.mk-floweditor > .workspace-leaf > .workspace-leaf-content > .view-content > .markdown-source-view.mod-cm6 > .cm-editor > .cm-scroller { + padding: 0; +} +.mk-floweditor > .workspace-leaf > .workspace-leaf-content > .view-content > div > .mk-table { + padding-bottom: 10px !important; +} + +/* src/css/Frame.css */ +.mk-frame-view > div { +} +.mk-setter-code { + display: flex; + border: var(--input-border-width) solid var(--background-modifier-border); + width: 120px; + overflow: hidden; + align-items: center; + border-radius: var(--input-radius); +} +.mk-setter-code .mk-setter-code-value { + padding: 2px 4px; + background-color: var(--background-modifier-form-field); + height: 100%; +} +.mk-frame-code-block .cm-gutters { + padding-inline-end: 0 !important; +} +.mk-frame-code-add { + margin-left: 10px; +} +.mk-frame-code-section > span { + margin-left: 10px; +} +.mk-frame-view p { + margin-block-start: 0; + margin-block-end: 0; +} +.mk-frame-row-placeholder:hover > .mk-frame-hover-menu-container, +.mk-f:hover > .mk-frame-hover-menu-container, +.mk-frame-hover-menu-container:hover { + display: flex; +} +.mk-image-node { + width: 100%; +} +.mk-f { + position: relative; + width: 100%; +} +.mk-f.is-selected { + background: var(--background-modifier-active-hover); + border-radius: 4px; +} +.mk-frame-hover-menu-container { + position: absolute; + display: none; + left: -36px; + top: -6px; + padding: 6px; + z-index: var(--layer-popover); +} +.mk-frame-hover-menu-container .mk-hover-button:hover { + background: var(--nav-item-background-hover); + border-radius: 4px; +} +.mk-frame-hover-props-editor { +} +.mk-frame-hover-menu { + border-radius: var(--radius-s); + display: flex; + flex-direction: column; + font-size: var(--font-ui-smaller); + background: var(--background-primary); +} +.mk-frame-bounds { + position: absolute !important; + width: 100%; + height: 100%; + z-index: var(--layer-popover); +} +.mk-frame-bounds.is-selected { + border: 2px solid var(--color-accent); +} +.mk-frame-sidebar .mk-frame-selector { + flex-direction: column; + height: 200px; + overflow: scroll; +} +.mk-frame-selector { + display: flex; +} +.mk-space-scroller .mk-frame-selector { + flex-wrap: wrap; + margin-left: auto; + margin-right: auto; + margin-top: var(--file-margins); + width: 100%; + max-width: var(--file-line-width); +} +.mk-space-scroller .mk-frame-selector > div { + width: 100px; + height: 80px; +} +.mk-frame-editor { + display: flex; + flex-direction: row; + width: 100%; + height: 100%; + flex: 1; +} +.mk-frame-main { + flex: 1; + display: flex; + flex-direction: column; + align-items: flex-start; +} +.mk-frame-main-tabs { + border-bottom: thin solid var(--divider-color); + width: 100%; +} +.mk-frame-main-tabs button { + background: rgba(var(--nav-item-background-active), 0.3); + border: none; + box-shadow: none; + color: var(--text-faint); +} +.mk-frame-builder { + display: flex; + flex-direction: row; + flex-wrap: wrap; + gap: 2px; +} +.mk-frame-builder > div { + width: 74px; + display: flex; + flex-direction: column; + align-items: center; + background: var(--background-primary); + padding: 8px; +} +.mk-frame-builder-icon svg { + width: 24px; + height: 24px; + color: var(--text-muted); +} +.mk-frame-canvas { + background: var(--background-secondary); + display: flex; + flex-direction: column; + flex: 1; + padding: 12px; + width: 100%; + gap: 16px; +} +.mk-cell-code.markdown-source-view.mod-cm6 .cm-content { + white-space: pre-wrap; +} +.mk-cell-code .cm-editor { + min-height: inherit !important; +} +.mk-frame-props { + display: flex; + flex-direction: column; +} +.mk-frame-canvas-editor { + background: var(--background-primary); + max-width: var(--file-line-width); + min-height: 100px; + box-shadow: var(--shadow-s); +} +.mk-frame-canvas-editor p { + margin-block-start: 0; + margin-block-end: 0; + margin-inline-start: 0px; + margin-inline-end: 0px; +} +.mk-frame-container { + flex: 1; + height: 100%; + display: flex; + justify-content: center; + position: relative; + border-top: 1px solid var(--divider-color); +} +.mk-cell-code { + font-family: var(--font-monospace); +} +.mk-frame-code-editor { + width: 100%; + height: 100%; + background: var(--code-background); +} +.mk-frame-code-section { + display: flex; + flex-direction: column; + align-items: flex-start; + padding: 8px; + font-size: 12px; + border-left: var(--nav-indentation-guide-width) solid var(--nav-indentation-guide-color); +} +.mk-frame-code-editor .\37c e { + color: var(--code-string); +} +.mk-frame-code-section > span { + background: var(--background-modifier-active); + padding: 2px 4px; + border-radius: 4px; + font-size: 12px; +} +.mk-frame-code-block { + width: 100%; + border-left: var(--nav-indentation-guide-width) solid var(--nav-indentation-guide-color); +} +.mk-frame-code-block-prop { + display: flex; + margin-left: 40px; + border-left: var(--nav-indentation-guide-width) solid var(--nav-indentation-guide-color); +} +.mk-frame-menu-container { + display: flex; + align-items: flex-start; + overflow: scroll; +} +.mk-frame-sidebar { + position: relative; + display: flex; + flex-direction: column; + padding: 0 var(--size-4-3); + border-bottom: 1px solid var(--divider-color); +} +.mk-frame-node-info { + padding: 8px; +} +.mk-frame-inspector { + display: flex; + overflow: scroll; + flex-direction: column; + flex: 1; + border-left: 1px solid var(--divider-color); +} +.mk-frame-row-placeholder { + width: 100%; + position: relative; + height: 40px; +} +.mk-frame-row-placeholder > div:before { + content: attr(data-ph); + color: var(--text-faint); + position: absolute; +} +.mk-frame-drop-placeholder { + position: absolute; + top: 0; + left: 0; +} +.mk-frame-column { + display: none; + position: absolute !important; + width: 100%; + height: 100%; + z-index: var(--layer-popover); + border-left: var(--nav-indentation-guide-width) solid var(--nav-indentation-guide-color); +} +.mk-frame-column-placeholder { + position: absolute; + right: -16px; + width: 16px; + bottom: 0; +} +.mk-frame-layers { + position: relative; + max-height: 200px; + overflow: scroll; +} +.mk-frame-layer > span { + flex: 1; +} +.mk-frame-row-placeholder.mk-indicator-bottom::before, +.mk-frame-drop-placeholder .mk-indicator-bottom::before { + position: absolute; + content: " "; + display: block; + width: 100%; + height: 2px; + bottom: 0; + border-radius: 1px; + background: var(--interactive-accent); +} +.mk-frame-column-placeholder.mk-indicator-right::before { + content: " "; + display: block; + height: 100%; + width: 2px; + border-radius: 1px; + background: var(--interactive-accent); +} +.mk-frame-menu-bar { + display: flex; + flex-direction: column; + position: absolute; + overflow: scroll; + left: 40px; + height: 100px; + margin: 0 !important; +} +.mk-frame-menu-bar > div { + display: flex; +} +.mk-frame-placeholder { + color: var(--text-faint); +} +.mk-frame-text { + display: inline; + color: inherit; + font-size: var(--font-text-size); + font-weight: var(--font-normal); + color: var(--text-normal); + font-family: var(--font-text); +} +.mk-frame-text p { + display: inline; +} +.mk-frame-menu-bar div { + padding: 8px; +} +.mk-frame-menu { + display: flex; + overflow: scroll; + flex-direction: column; + position: relative; +} +.mk-setter-group { + display: flex; + flex-wrap: wrap; + align-items: center; +} +.mk-setter-color { + border-radius: var(--input-radius); + border: var(--input-border-width) solid var(--background-modifier-border); +} +.mk-setter-group .mk-setter-slider { + flex: 1; +} +.mk-setter-step input { + width: 40px; + padding-right: 0px; +} +.mk-setter-step input[type=number]::-webkit-outer-spin-button, +.mk-setter-step input[type=number]::-webkit-inner-spin-button { + -webkit-appearance: inner-spin-button !important; +} +.mk-setter-text span, +.mk-setter-step span { + font-size: var(--font-ui-smaller); + padding: 4px; +} +.mk-frame-label { + position: absolute; + font-size: 9px; + background-color: var(--color-accent); + top: -10px; + left: 0; +} +.mk-frame-schema { + display: flex; + padding: 4px 8px; + font-size: var(--font-ui-small); +} +.mk-frame-layer { + margin-left: var(--spacing); + padding: 4px 8px; + font-size: var(--font-ui-small); + display: flex; +} +.mk-frame-layer.is-selected { + background-color: var(--nav-item-background-active); +} +.mk-frame-schema.is-selected { + background-color: var(--nav-item-background-active); +} +.mk-frame-sidebar-title { + display: flex; + padding: 4px 8px; + font-size: var(--font-ui-small); + font-weight: var(--bold-weight); + background: var(--background-primary-alt); +} +.mk-frame-text { + min-height: 40px; +} +.mk-frame-text[placeholder]:empty::before { + content: attr(placeholder); + color: var(--text-faint); +} +.mk-frame-text[placeholder]:empty:focus::before { + content: ""; +} +.mk-button { + -webkit-app-region: no-drag; + display: inline-flex; + align-items: center; + justify-content: center; + color: var(--text-normal); + font-size: var(--font-ui-small); + border-radius: var(--button-radius); + border: 0; + padding: var(--size-4-1) var(--size-4-3); + height: var(--input-height); + font-weight: var(--input-font-weight); + cursor: var(--cursor); + font-family: inherit; + outline: none; + user-select: none; + white-space: nowrap; + background-color: var(--interactive-normal); + box-shadow: var(--input-shadow); +} +.mk-a { + color: var(--link-color); + outline: none; + text-decoration-line: var(--link-decoration); + text-decoration-thickness: var(--link-decoration-thickness); + cursor: var(--cursor-link); +} +.mk-t-h1 { + --font-text-size: var(--h1-size); + --text-normal: var(--h1-color); + --font-normal: var(--h1-weight); +} +.mk-t-h2 { + --font-text-size: var(--h2-size); + --text-normal: var(--h2-color); + --font-normal: var(--h2-weight); +} +.mk-t-h3 { + --font-text-size: var(--h3-size); + --text-normal: var(--h3-color); + --font-normal: var(--h3-weight); +} +.mk-t-h4 { + --font-text-size: var(--h4-size); + --text-normal: var(--h4-color); + --font-normal: var(--h4-weight); +} +.mk-t-h5 { + --font-text-size: var(--h5-size); + --text-normal: var(--h5-color); + --font-normal: var(--h5-weight); +} +.mk-t-p { +} + +/* src/css/ContextBuilder.css */ +.is-phone .mk-context-maker { + max-height: 100vh; +} +.mk-context-maker-container { + height: 100%; + display: flex; + flex-direction: column; +} +.mk-context-maker .modal-content { + height: var(--dialog-max-height); + overflow-y: scroll; +} +.mk-context-maker-preview { + display: flex; + flex-wrap: wrap; + gap: 4px; + margin-bottom: 16px; + padding: var(--size-4-4); + flex-grow: 1; + overflow: scroll; + padding-bottom: 0; +} +.mk-context-maker-item { + background: rgba(var(--mono-rgb-100), 0.025); + border-radius: 4px; + overflow: hidden; + display: flex; + align-items: center; + gap: 2px; + padding: 8px; +} +.mk-context-maker-selector { + font-size: var(--font-ui-small); + height: 240px; + overflow-y: scroll; + background: rgba(var(--mono-rgb-100), 0.025); + padding: var(--size-4-4); + border-radius: 4px; +} +.mk-context-maker-selector .mk-cell-option { + margin-bottom: 8px; +} +.mk-context-maker-builder { + min-height: 60px; + display: flex; + flex-wrap: wrap; + padding: 8px; + gap: 4px; +} +.mk-property-editor-context-title { + display: flex; + font-size: var(--font-ui-small); + font-weight: var(--font-normal); + padding: var(--size-4-2) var(--size-4-1); +} +.mk-property-editor-context-title span { + flex: 1; +} +.mk-property-editor-context-tag { + display: flex; + gap: 4px; + align-items: center; +} +.mk-property-editor { + padding: 0; + display: flex; + flex-direction: column; + height: 100%; + gap: 8px; +} +.mk-property-editor-property { + display: flex; + padding: 8px; + font-size: var(--font-ui-small); + color: var(--text-muted); + gap: 6px; + align-items: center; + background: var(--background-modifier-cover); + border-radius: 6px; +} +.mk-property-editor-new:hover { + color: var(--text-normal); +} +.mk-property-editor-new span { + font-size: var(--font-ui-smaller); +} +.mk-property-editor-new { + color: var(--text-faint); + display: flex; + flex-direction: column; + padding: var(--size-4-2) var(--size-4-2); + border: thin solid var(--divider-color); + border-radius: 8px; +} +.mk-property-editor-context-title { + font-size: var(--font-ui-medium); + font-weight: var(--font-semibold); + line-height: var(--line-height-tight); + padding: var(--size-4-2) var(--size-4-1); + display: flex; + align-items: center; + gap: 8px; +} +.mk-property-editor-list { + display: flex; + flex-direction: column; + gap: 4px; +} +.mk-property-editor-context-title span, +.mk-property-editor-list span { + font-size: var(--font-ui-smaller); + color: var(--text-faint); + flex: 1; +} +.mk-context-properties-new { +} + +/* src/css/FilterBar.css */ +.mk-view-selector { + margin-right: 0; + display: flex; + align-items: center; + gap: 16px; + min-height: 48px; + max-width: 100%; + overflow-x: auto; + font-size: var(--font-ui-medium); +} +.mk-view-selector-spacer { + min-width: var(--context-padding); + width: var(--file-margins); +} +.mk-table-selector, +.mk-frame-selector { + display: flex; + flex-direction: column; +} +.mk-view-selector::-webkit-scrollbar { + display: none; +} +.mk-view-selector > div > .mk-collapse { + padding-right: 8px; + padding-left: 0px; +} +.mk-view-selector .mk-collapse.mk-icon-xsmall svg { + color: unset; +} +.mk-view-selector > div > button:not(:last-child) { + padding-right: 0px; +} +.mk-view-selector > div, +.mk-view-selector > button { + border-radius: 0; + margin: 4px -8px; + display: flex; + align-items: center; + border-bottom: thin solid transparent; + height: 100%; +} +.mk-view-config .mk-is-active button { + color: var(--text-normal); +} +.mk-view-config .mk-is-active { + color: var(--text-normal); + background: none !important; +} +.mk-table-selector button, +.mk-view-config button { + font-size: max(var(--font-ui-small), 1em); + font-weight: var(--font-medium); + background: rgba(var(--nav-item-background-active), 0.3); + border: none; + box-shadow: none; + color: var(--text-faint); +} +body:not(.is-mobile) .mk-view-config .mk-view-options, +body:not(.is-mobile) .mk-view-config .mk-view-selector > *:not(.mk-is-active) { + opacity: 0; +} +body:not(.is-mobile) .mk-view-config:hover .mk-view-options, +body:not(.is-mobile) .mk-view-config:hover .mk-view-selector > *:not(.mk-is-active) { + opacity: 1; +} +.mk-view-config button:hover { + color: var(--text-normal); +} +.mk-view-config { + width: 100%; + display: flex; + color: var(--text-faint); + align-items: center; + border-bottom: thin solid var(--divider-color); + flex-wrap: wrap; +} +.mk-view-config input { + background: none; + border: none; + flex-grow: 1; +} +.is-phone .mk-view-config { + flex-wrap: wrap; +} +.is-phone .mk-view-config button { + width: unset; +} +.mk-view-search { + background: var(--background-modifier-form-field); + border: var(--input-border-width) solid var(--background-modifier-border); + display: flex; + border-radius: 8px; + align-items: center; + flex-grow: 1; +} +.mk-view-search button:hover { + background: unset !important; +} +.mk-view-search button { + margin: 0 !important; + padding: var(--size-4-1) var(--size-4-2) !important; +} +.is-phone .mk-view-options { + margin-top: 8px; + margin-bottom: 8px; +} +.mk-view-options { + display: flex; + align-items: center; + color: var(--text-normal) !important; + min-height: 48px; + padding-left: var(--context-padding); +} +.mk-view-config span { + flex-grow: 10; +} +.mk-view-config svg { + width: 14px; + height: 14px; +} +.mk-filter-bar { + display: flex; + padding: 8px 4px; + gap: 8px; + width: 100%; + border-bottom: 1px solid var(--divider-color); +} +.mk-filter-bar span { + flex-grow: 1; +} +.mk-view-config .mk-is-active, +.mk-table-selector .mk-is-active { + color: var(--text-normal) !important; +} +.mk-filter { + display: flex; + font-size: var(--font-ui-smaller); + color: var(--text-muted); + padding: 0px; +} +.mk-query .mk-filter > span { + background: var(--background-primary); +} +.mk-filter > span, +.mk-filter > div { + background: var(--interactive-normal); +} +.mk-filter > span:hover, +.mk-filter > div:hover { + background: var(--interactive-hover); +} +.mk-filter > *:first-child { + border-top-left-radius: 4px; + border-bottom-left-radius: 4px; + padding-left: 10px; +} +.mk-filter > *:last-child { + border-top-right-radius: 4px; + border-bottom-right-radius: 4px; + padding-right: 6px; +} +.mk-filter > span { + border-right: thin solid var(--background-primary); + padding: 4px 8px; + display: flex; + align-items: center; +} +.mk-filter div { + display: flex; + align-items: center; +} +.mk-filter div svg { + width: 14px; + height: 14px; +} +.mk-query { + display: flex; + flex-direction: column; + gap: 16px; + padding: 8px; + border-radius: 6px; +} +.mk-query-filters { + flex-wrap: wrap; + padding: 0; + border-bottom: none; +} +.mk-query-filter, +.mk-query-group-type { + display: flex; +} +.mk-query-group { + display: flex; +} +.mk-query-group-type { + width: 32px; + padding-bottom: 4px; +} +.mk-query-group button { + background-color: unset; + box-shadow: none; + width: unset; +} +.is-phone .mk-query-group button { + background-color: var(--interative-normal); +} +.mk-query-group-type > span, +.mk-query-filter > span { + display: flex; + flex-grow: 1; +} +.mk-filter-add { + border: thin solid var(--divider-color) !important; + border-radius: 4px; + box-shadow: none !important; + background: none !important; + display: flex; + align-items: center; + padding: 4px; + font-size: var(--font-ui-small); + color: var(--text-muted); + gap: 4px; +} +.mk-filter-add div { + display: flex; } -.mk-flowblock-menu .mk-hover-button { - padding: var(--size-4-2); - color: var(--text-muted); - border: none; - border-right: 1px solid var(--background-modifier-border); +.mk-search-bar { } -.mk-flowblock-menu .mk-hover-button:last-child { - border-right: none; +.mk-tag-selector { + display: flex; + gap: 4px; + margin-top: 8px; + margin-bottom: 8px; + flex-wrap: wrap; } -.mk-flowblock-menu .mk-hover-button:hover { - background: var(--background-secondary-alt); +.mk-tag-selector svg { + color: var(--tag-color) !important; } -.mk-floweditor > .workspace-leaf > .workspace-leaf-content > .view-content > .markdown-source-view.mod-cm6 > .cm-editor > .cm-scroller { - padding: 0; +.mk-tag-selector div { + cursor: var(--cursor-link); + font-size: var(--font-ui-smaller); + display: flex; } -.mk-floweditor > .workspace-leaf > .workspace-leaf-content > .view-content > div > .mk-table { - padding-bottom: 10px !important; +.mk-tag-selector span { + display: flex; + align-items: center; +} +.mk-tag-selector button { + height: auto; + border-radius: var(--tag-radius); + color: var(--tag-color); + background-color: var(--tag-background); + border: var(--tag-border-width) solid var(--tag-border-color); + box-shadow: none !important; + font-size: var(--tag-size); + vertical-align: baseline; + border-left: none; + border-right: none; + padding-top: var(--tag-padding-y) !important; + padding-bottom: var(--tag-padding-y) !important; } /* src/css/FileContext.css */ .mk-file-context { - margin-bottom: 12px; - gap: 12px; display: flex; flex-direction: column; --file-context-spacing: 4px; + height: 100%; + padding: var(--size-4-2) var(--size-4-1); + gap: 4px; +} +.mk-file-context-header { + height: var(--mk-header-height); + border-bottom: var(--divider-color); + background-color: var(--background-primary); + z-index: 1; + position: relative; + gap: var(--size-4-2); + padding: 0 var(--size-4-3); +} +.mk-file-context-file .mk-file-icon button { + --label-color:var(--background-secondary) ; } .mk-file-context-file { display: flex; + width: 100%; flex-direction: column; align-items: flex-start; gap: 8px; @@ -1752,7 +2564,7 @@ div:not(.mk-flowspace-editor) > .mk-floweditor .cm-content { padding-inline-start: 0 !important; text-indent: 0 !important; } -.mk-folder-header .mk-file-icon-placeholder button, +.mk-space-header .mk-file-icon-placeholder button, .mk-inline-context .mk-file-context-component .mk-file-icon-placeholder button { background: var(--label-color); border-radius: 8px; @@ -1765,28 +2577,52 @@ div:not(.mk-flowspace-editor) > .mk-floweditor .cm-content { display: none; } .markdown-reading-view .mk-file-context-file > .mk-inline-title.inline-title, -.markdown-source-view.mod-cm6 .mk-file-context-file > .mk-inline-title.inline-title { +.markdown-source-view.mod-cm6.mod-cm6.is-readable-line-width .mk-file-context-file > .mk-inline-title.inline-title { padding-bottom: 0; margin-left: 0 !important; margin-top: 0; padding-top: 0 !important; margin-bottom: 0; + width: auto; +} +.mk-inline-title { + margin-bottom: 0; } .mk-file-context-component .mk-tag-selector { - margin-top: 4px; + margin-top: 0px; margin-bottom: 0; padding: 0; } .mk-file-context-component { display: flex; flex-direction: column; - padding: 0.15rem var(--file-context-spacing); gap: 8px; + align-items: flex-start; +} +.mk-file-context-properties { + display: flex; + flex-direction: column; + align-items: flex-start; + gap: 4px; + margin-bottom: 12px; } .mk-file-context-section { display: flex; flex-direction: column; - padding: 0.15rem var(--file-context-spacing); + gap: 4px; +} +.mk-file-context-section button { + background: none; + border: none; + padding: 0; + margin: 0; + color: var(--text-faint); + font-size: var(--font-ui-small); + font-weight: 500; + text-align: left; + cursor: pointer; + display: flex; + align-items: center; gap: 4px; } .mk-file-context-row { @@ -1794,6 +2630,10 @@ div:not(.mk-flowspace-editor) > .mk-floweditor .cm-content { align-items: flex-start; gap: 2px; } +.mk-file-context-row .mk-collapse { + width: 24px !important; + height: 24px !important; +} .mk-file-context-row .mk-cell-option { width: unset; align-items: flex-start; @@ -1805,8 +2645,36 @@ div:not(.mk-flowspace-editor) > .mk-floweditor .cm-content { align-items: center; gap: 10px; } -.mk-file-context-field-new:hover { - color: var(--text-normal); +.mk-file-context-field-key { + padding: var(--size-4-1) var(--size-4-2); + min-width: 122px; + display: flex; + gap: 6px; +} +.mk-file-context-field-space { + display: flex; + justify-content: center; + min-width: 18px; + height: 18px; + color: var(--tag-color); + border-radius: var(--tag-radius); + border: var(--tag-border-width) solid var(--tag-border-color); + opacity: 0.4; +} +.mk-file-context-field-space:hover { + opacity: 1; +} +.mk-file-context-field-icon { + min-width: 18px; + height: 18px; + display: flex; + align-items: center; + text-align: center; + justify-content: center; +} +.mk-file-context-field-new:hover, +.mk-file-context-field-new button:hover svg { + color: var(--text-normal) !important; } .mk-file-context-field-new button { background: none !important; @@ -1826,7 +2694,6 @@ div:not(.mk-flowspace-editor) > .mk-floweditor .cm-content { } .mk-file-context-field { min-width: 100px; - width: 100px; font-size: var(--font-ui-small); color: var(--text-faint); min-height: 24px; @@ -1849,6 +2716,12 @@ div:not(.mk-flowspace-editor) > .mk-floweditor .cm-content { background-color: var(--bullet-color); transition: transform 75ms ease-out; } +.mk-file-context .mk-cell-text { + background: var(--interactive-hover) !important; +} +.mk-file-context .mk-file-context-row { + flex-wrap: wrap; +} .mk-file-context-value { font-size: var(--font-ui-small); flex-grow: 1; @@ -1868,7 +2741,7 @@ div:not(.mk-flowspace-editor) > .mk-floweditor .cm-content { } .mk-file-context-value input[type=text], .mk-file-context-value input[type=number] { - width: 100%; + width: 130px; border: none; border-radius: 0px; height: 24px; @@ -1878,7 +2751,8 @@ div:not(.mk-flowspace-editor) > .mk-floweditor .cm-content { box-shadow: none !important; } c .mk-section-title, -.mk-file-context-title { +.mk-file-context-title, +.mk-file-context-subtitle { font-size: var(--font-ui-small); font-weight: var(--bold-weight); color: var(--text-muted); @@ -1886,8 +2760,9 @@ c .mk-section-title, .mk-file-context-title { display: flex; align-items: center; - height: 24px; + height: 32px; gap: 4px; + position: relative; } .mk-file-context-title:hover { color: var(--text-normal); @@ -1899,6 +2774,8 @@ c .mk-section-title, background: none !important; } .mk-file-context-title .mk-collapse { + position: absolute; + left: -25px; width: 10px; height: 10px; } @@ -1915,13 +2792,57 @@ c .mk-section-title, .mk-file-context .mk-tag-selector { padding: 0 !important; } +.mk-space-icon { + display: flex; + padding-right: 2px; +} .mk-file-context-backlink { - border: thin solid var(--divider-color); - padding: 0px 8px; + background: var(--background-primary); + padding: 8px; } .mk-file-context-backlink .cm-content { padding-bottom: 0 !important; } +.mk-space-gallery-container { + width: 100%; + height: 100vh; + position: relative; +} +.mk-space-gallery-controls { + font-size: var(--font-ui-small); + position: absolute; + display: flex; + align-items: center; + gap: 10px; + z-index: 100; +} +.mk-space-gallery-controls:hover { + color: var(--text-normal); +} +.mk-space-scroller > .mk-spacer { + min-height: var(--mk-header-height); +} +.mk-space-gallery-controls button { + background: none !important; + box-shadow: none !important; + color: var(--text-faint) !important; + padding: 0 4px !important; + display: flex; + gap: 4px; + height: 20px; + border: none !important; +} +.mk-space-gallery-controls button svg { + color: var(--text-faint) !important; +} +.mk-space-gallery-controls button:hover { + color: var(--text-normal) !important; +} +.mk-space-gallery { + position: fixed; + width: 100%; + height: 100%; +} .mk-note-header { position: absolute; top: 0; @@ -1929,6 +2850,7 @@ c .mk-section-title, right: 0; width: 100%; user-select: none; + height: 200px; } .mk-note-header img { height: 200px; @@ -1936,14 +2858,20 @@ c .mk-section-title, object-fit: cover; opacity: 1 !important; } -.mk-file-context-collapse { +.mk-fold { opacity: 1; position: absolute; left: -24px; - bottom: 0px; + bottom: 4px; opacity: 0; } -.mk-file-context-file-horizontal .mk-file-context-collapse { +.mk-smart-note-title { + width: 100%; + display: flex; + flex-direction: column; + justify-content: space-between; +} +.mk-file-context-file-horizontal .mk-fold { bottom: 8px; } .markdown-source-view:not(.is-live-preview) > .cm-editor > .cm-scroller > .cm-sizer > .mk-inline-context { @@ -1955,18 +2883,17 @@ c .mk-section-title, flex-direction: column; border-top: none !important; } -.mk-inline-context .mk-file-context-collapse.mk-collapsed { +.mk-inline-context .mk-fold.mk-collapsed { opacity: 1; color: var(--collapse-icon-color-collapsed); } -.mk-inline-context .mk-file-context-collapse.mk-collapsed svg { +.mk-inline-context .mk-fold.mk-collapsed svg { color: var(--collapse-icon-color-collapsed); } -.mk-inline-context:hover .mk-file-context-collapse { +.mk-inline-context:hover .mk-fold { opacity: 1 !important; } .markdown-source-view.mod-cm6 .cm-content > .cm-line.mk-has-banner { - position: inherit !important; } .markdown-source-view.mod-cm6 .mk-has-backlinks img.cm-widgetBuffer { display: none !important; @@ -1987,6 +2914,7 @@ c .mk-section-title, } .mk-note-header .inline-title { display: flex !important; + margin-bottom: 0; } .mk-header-title { max-width: var(--file-line-width); @@ -1998,12 +2926,14 @@ c .mk-section-title, .mk-header-title.mk-header-has-banner { margin-top: -34px; } -.workspace-leaf-content[data-type=make-folder-view] .view-content, +.workspace-leaf-content[data-type=mk-frame-editor] .view-content, +.workspace-leaf-content[data-type=mk-space] .view-content, +.workspace-leaf-content[data-type=make-context-view] .view-content, .workspace-leaf-content[data-type=make-file-view] .view-content { padding: 0; } .markdown-source-view.mod-cm6 .cm-content > .mk-header { - --header-height: 0px; + --mk-header-height: 0px; gap: 16px; display: flex; flex-direction: column; @@ -2018,12 +2948,13 @@ c .mk-section-title, } .mk-inline-context .mk-file-context-component .mk-spacer, .markdown-source-view.mod-cm6 .cm-content > .mk-header .mk-spacer, -.mk-folder-view .mk-folder-header .mk-spacer { - height: var(--header-height) !important; +.mk-space-view .mk-space-header .mk-spacer { + height: var(--mk-header-height) !important; pointer-events: none; } .mk-file-context .inline-title { font-size: 18px; + margin-bottom: 0; } .mk-file-context-component .mk-file-context-field-new { opacity: 0.5; @@ -2032,34 +2963,39 @@ c .mk-section-title, .mk-file-context-component .mk-file-context-field-new:hover { opacity: 1; } -.mk-folder-header .mk-file-context-file .mk-file-icon, +.mk-space-header .mk-file-context-file .mk-file-icon, .mk-inline-context .mk-file-context-file .mk-file-icon { width: 48px; height: 48px; margin-bottom: 8px; } -.mk-folder-header .mk-file-context-file.mk-file-context-file-horizontal .mk-file-icon, +.mk-space-header .mk-file-context-file.mk-file-context-file-horizontal .mk-file-icon, .mk-header .mk-file-context-file.mk-file-context-file-horizontal .mk-file-icon { width: 32px; height: 32px; margin-bottom: 0px; } -.mk-folder-header .mk-file-context-file-horizontal .mk-file-icon svg, -.mk-folder-header .mk-file-context-file-horizontal .mk-file-icon button, +.mk-space-header .mk-file-context-file-horizontal .mk-file-icon svg, +.mk-space-header .mk-file-context-file-horizontal .mk-file-icon button, .mk-header .mk-file-context-file-horizontal .mk-file-icon svg, .mk-header .mk-file-context-file-horizontal .mk-file-icon button { width: 32px; height: 32px; font-size: 28px; } -.mk-folder-header .mk-file-icon svg, -.mk-folder-header .mk-file-icon button, +.mk-space-header .mk-file-icon svg, +.mk-space-header .mk-file-icon button, .mk-inline-context .mk-file-icon svg, .mk-inline-context .mk-file-icon button { width: 48px; height: 48px; + padding: 6px; font-size: 40px; } +.mk-space-header .mk-file-icon svg.svg-icon, +.mk-inline-context .mk-file-icon svg.svg-icon { + padding: 6px; +} /* src/css/InlineMenu.css */ body:not(.is-mobile) .mk-style-menu { @@ -2090,6 +3026,9 @@ body:not(.is-mobile) .mk-style-menu { border-radius: 4px; display: flex; } +.mk-mark div { + display: flex; +} .mk-style-menu .mk-mark:hover { background: var(--background-modifier-hover); } @@ -2108,6 +3047,7 @@ body:not(.is-mobile) .mk-style-menu { height: 24px; border-radius: 12px; margin: 8px; + border: thin solid var(--background-modifier-hover); } .mk-color:hover { opacity: 0.8; @@ -2190,6 +3130,14 @@ mark { display: flex; flex-wrap: wrap; } +.mk-sticker { + display: flex; +} +.mk-sticker svg { + height: var(--icon-size); + width: var(--icon-size); + stroke-width: var(--icon-stroke); +} /* src/css/makerMode.css */ .mk-mark-sans .cm-s-obsidian span.cm-hmd-escape-backslash, @@ -2254,13 +3202,6 @@ mark { .mk-hide-tabs .mod-left-split .mod-top-left-space .workspace-tab-header-container-inner { visibility: hidden; } -.mk-sync-status { - display: flex; - font-size: var(--font-ui-small); - color: var(--nav-item-color); - gap: 4px; - margin: 8px 12px; -} .mk-spaces-enabled.is-mobile.mk-hide-ribbon .workspace-drawer.mod-left .workspace-drawer-inner { padding-left: 0 !important; } @@ -2276,196 +3217,73 @@ mark { .mk-spaces-enabled.is-mobile.mk-hide-ribbon .workspace-drawer-ribbon { display: none; } -.mk-spaces-enabled.is-mobile .workspace-drawer.mod-left .workspace-drawer-inner .workspace-drawer-header { - padding-left: 0 !important; -} -.mk-spaces-enabled.is-mobile .workspace-drawer.mod-left .workspace-drawer-active-tab-header { - display: none; -} -.mk-spaces-enabled.is-mobile .workspace-drawer.mod-left .workspace-drawer-inner .mod-settings { - display: none; -} -.is-mobile .workspace-drawer.mod-left .workspace-drawer-header-left { -} -.is-mobile .mk-sidebar button:not(.clickable-icon) { - padding: unset; -} -.is-mobile .mk-sidebar .mk-file-icon button { - font-size: 16px; - margin: 0; - height: 24px; - width: 24px; -} -body.is-mobile .sidebar-toggle-button { - display: flex !important; -} -.is-mobile .workspace-drawer.mod-left .workspace-drawer-header-icon { - position: absolute; - right: 20px; - top: 12px; - z-index: 100; -} -.is-phone .workspace-drawer.mod-left .workspace-drawer-header-icon { - top: 20px; -} -.is-mobile .workspace-drawer.mod-left { - border-top-right-radius: 0; - border-bottom-right-radius: 0; -} -.mk-sidebar { - display: flex; - flex-direction: column; - height: 100%; -} -.is-mobile .mk-sidebar { -} -.mk-file-tree { - flex: 1; - overflow: hidden; -} -.mk-context-tree .tree-item { - padding: 4px; -} -.mk-context-tree .tree-item-self { - margin-left: var(--spacing); - align-items: center; - padding: 2px 2px; -} -.mk-context-tree .mk-tree-wrapper { - padding: 0px !important; -} -.mk-context-tree .mk-section-title .mk-tree-text { - padding: 0.25rem 0.3rem; -} -.mk-context-tree .mk-section-title { - padding-left: 4px; - padding-right: 4px; -} - -/* src/css/MainMenu.css */ -.mk-main-menu-container { - display: flex; - padding: 12px 8px 0px 8px; -} -.mk-main-menu-button { - text-align: left; - padding: 8px 8px; - border-radius: 4px; - align-items: center; - display: flex; - width: calc(100% - 50px); -} -.mk-main-menu-icon { - background: var(--nav-item-background-hover); - padding: 2px; - border-radius: 2px; - text-transform: uppercase; - width: 20px; - height: 20px; - font-size: 12px; - justify-content: center; - margin-right: 4px; -} -.mk-flow-bar-compact .mk-main-menu-container { - flex-grow: 1; - padding: 0; -} -.mk-flow-bar-compact .mk-main-menu-button { - width: 100%; - padding: 4px; - gap: 4px; -} -.is-mobile .mk-main-menu-button { - font-size: var(--font-ui-medium); - font-weight: var(--font-medium); - gap: 4px; +.mk-spaces-enabled.is-mobile .workspace-drawer.mod-left .workspace-drawer-inner .workspace-drawer-header { + padding-left: 0 !important; } -.mk-main-menu-button > div { - display: flex; +.mk-spaces-enabled.is-mobile .workspace-drawer.mod-left .workspace-drawer-active-tab-header { + display: none; } -.mk-main-menu-button svg { - height: 16px; - width: 16px; +.mk-spaces-enabled.is-mobile .workspace-drawer.mod-left .workspace-drawer-inner .mod-settings { + display: none; } -body:not(.is-mobile) .mk-main-menu-button:hover { - background: var(--nav-item-background-hover); +.is-mobile .workspace-drawer.mod-left .workspace-drawer-header-left .mk-main-menu-container { + margin-right: 34px; } -.mk-main-menu { - position: absolute; - left: 8px; - z-index: var(--layer-menu); - margin-top: 2.25rem; - margin-left: 2px; - background-color: var(--background-secondary); - transform-origin: top left; - border-radius: var(--radius-m); - border: 1px solid var(--background-modifier-border-hover); - box-shadow: var(--shadow-s); +.is-mobile .mk-sidebar button:not(.clickable-icon) { } -.mk-menu-button { - display: flex; - padding-top: 0.5rem; - padding-bottom: 0.5rem; - padding-left: 0.5rem; - padding-right: 0.5rem; - font-size: 0.75rem; - line-height: 1.25rem; - align-items: center; - width: 100%; - border-radius: 0.375rem; +.is-mobile .mk-sidebar .mk-file-icon button { + font-size: 16px; + margin: 0; + height: 24px; + width: 24px; } -.mk-menu-button:hover { - background: var(--nav-item-background-hover); +body.is-mobile .sidebar-toggle-button { + display: flex !important; } - -/* src/css/SectionView.css */ -.mk-section { - display: flex; - color: var(--text-muted); - font-size: var(--font-ui-smaller); - width: 100%; - justify-content: space-between; - margin-left: 0; +.is-mobile .workspace-drawer.mod-left .workspace-drawer-header-icon { + position: absolute; + right: 20px; + top: 12px; + z-index: 100; +} +.is-phone .workspace-drawer.mod-left .workspace-drawer-header-icon { + top: 20px; } -.mk-section-wrapper { - padding-top: 8px !important; +.is-mobile .workspace-drawer.mod-left { + border-top-right-radius: 0; + border-bottom-right-radius: 0; } -.mk-section-tabs { +.mk-sidebar { display: flex; - border-bottom: 1px solid var(--divider-color); + flex-direction: column; + height: 100%; } -.mk-section-tabs .mk-is-active { - background: none; - font-weight: var(--bold-weight); - color: var(--text-normal); +.is-mobile .mk-sidebar { } -.mk-section-tabs .mk-section-title { - font-weight: var(--normal-weight); - background: none; +.mk-file-tree { flex: 1; - display: flex; - justify-content: center; - padding: 12px; - gap: 8px; - height: unset; - flex-direction: column; + overflow: hidden; } -.mk-section-title { - height: 24px; - display: flex; - min-width: 0; +.mk-context-tree .tree-item { + padding: 4px; +} +.mk-context-tree .tree-item-self { + margin-left: var(--spacing); align-items: center; + padding: 2px 2px; +} +.mk-context-tree .mk-tree-wrapper { + padding: 0px !important; } -.mk-section-title .mk-tree-text { +.mk-context-tree .mk-section-title .mk-tree-text { padding: 0.25rem 0.3rem; } -.mk-section .mk-collapse svg { - margin: 4px; - width: 8px; - height: 8px; +.mk-context-tree .mk-section-title { + padding-left: 4px; + padding-right: 4px; } -/* src/css/FolderTreeView.css */ +/* src/css/Sidebar.css */ .workspace .mod-root .workspace-tab-header[data-type=markdown] .workspace-tab-header-inner-icon { display: flex; } @@ -2476,6 +3294,8 @@ body:not(.is-mobile) .mk-main-menu-button:hover { align-items: center !important; padding: 0 6px; position: relative; + height: var(--spaceRowHeight); + gap: 4px; } .nav-file { overflow-y: inherit !important; @@ -2485,26 +3305,24 @@ body:not(.is-mobile) .mk-main-menu-button:hover { padding-bottom: 6px; } .is-mobile .mk-tree-wrapper > div { - padding-left: 24px; } .is-mobile .mk-tree-wrapper > .mk-section { padding-left: 4px; } .mk-tree-wrapper > div { display: flex; - align-items: center; width: 100%; + transition: transform .2s ease; } -.mk-tree-wrapper > .mk-indicator-bottom::after { - content: " "; - display: block; - position: absolute; - height: 2px; - border-radius: 1px; - background: var(--interactive-accent); - width: calc(100% - var(--spacing)); - left: var(--spacing); - top: 100%; +.mk-waypoints { + position: relative; +} +.mk-waypoints > .mk-indicator { + border-radius: 8px; + outline: 2px solid var(--interactive-accent); +} +.mk-waypoints > .mk-waypoints-item { + transition: transform .2s ease; } .mk-tree-wrapper > .mk-indicator-top::before { content: " "; @@ -2517,7 +3335,7 @@ body:not(.is-mobile) .mk-main-menu-button:hover { left: var(--spacing); top: 0%; } -.mk-folder-lines .mk-tree-item.nav-folder-title::before { +.mk-folder-lines .mk-tree-item::before { display: block; content: " "; width: 1px; @@ -2528,7 +3346,8 @@ body:not(.is-mobile) .mk-main-menu-button:hover { left: 13px; } .mk-tree-wrapper .mk-indicator-row { - background: #dde8f6; + border-radius: 8px; + outline: 2px solid var(--interactive-accent); } .mk-tree-wrapper.mk-clone { display: inline-block; @@ -2545,6 +3364,8 @@ body:not(.is-mobile) .mk-main-menu-button:hover { .mk-tree-wrapper.mk-ghost { opacity: 0.5; } +.mk-nav-button { +} .mk-tree-item { margin-left: var(--spacing) !important; flex-direction: row !important; @@ -2556,7 +3377,6 @@ body:not(.is-mobile) .mk-main-menu-button:hover { padding: var(--vertical-padding) 2px; min-width: 0; margin-right: 4px; - height: var(--spaceRowHeight); } .is-mobile .mk-tree-item { height: 38px; @@ -2577,11 +3397,15 @@ body:not(.is-mobile) .mk-main-menu-button:hover { padding: unset !important; } .mk-inline-button { - background: unset !important; + display: inline-flex; + align-items: center; + justify-content: center; + padding: 4px; + border-radius: var(--clickable-icon-radius); box-shadow: unset !important; } -.is-mobile .mk-tree-wrapper button:hover { - background: none !important; +.mk-inline-button:not(:hover) { + background: unset !important; } .mk-inline-button, .mk-tree-wrapper button { @@ -2591,7 +3415,7 @@ body:not(.is-mobile) .mk-main-menu-button:hover { margin: 0; height: 24px; width: 24px; - padding: 0; + padding: 0 !important; } .is-mobile .mk-tree-wrapper .mk-folder-buttons button { margin-left: 8px; @@ -2631,13 +3455,22 @@ body:not(.is-mobile) .mk-tree-wrapper:hover .mk-drag-handle { .is-mobile .mk-folder-buttons { display: flex; } -body:not(.is-mobile) .mk-tree-wrapper .mk-folder-buttons { +body:not(.is-mobile) .mk-tree-wrapper .mk-file-link { + opacity: 0; +} +body:not(.is-mobile) .mk-tree-wrapper:hover .mk-file-link { + opacity: 1; +} +body:not(.is-mobile) .mk-tree-wrapper .mk-folder-buttons button { display: none; } -body:not(.is-mobile) .mk-tree-wrapper:hover .mk-folder-buttons { +body:not(.is-mobile) .mk-tree-wrapper:hover .mk-folder-buttons button { + display: flex; +} +body:not(.is-mobile) .mk-tree-wrapper .mk-folder-buttons { display: flex; } -.mk-tree-wrapper svg { +.mk-tree-item svg { width: 16px; height: 16px; color: var(--text-muted); @@ -2658,6 +3491,13 @@ body:not(.is-mobile) .mk-tree-wrapper:hover .mk-folder-buttons { font-size: var(--font-ui-small); flex-grow: 1 !important; } +.mk-file-link { + vertical-align: middle; +} +.mk-file-link svg { + width: 12px; + height: 10px; +} .mk-disable-interaction { pointer-events: none; } @@ -2669,16 +3509,29 @@ body:not(.is-mobile) .mk-tree-wrapper:hover .mk-folder-buttons { .workspace-leaf-content[data-type=mk-file-view] > .view-content { padding: 0 !important; } +.mk-collapse { + min-width: 16px !important; + width: 16px !important; + height: 16px !important; + opacity: 0.4; +} +.mk-collapse:hover { + background: none !important; + opacity: 1; +} .mk-collapse svg { transform: rotate(90deg); transition: transform 250ms ease; - width: 14px; - height: 14px; - margin: 5px; + width: 12px; + height: 12px; + margin: 2px; } .mk-collapse.mk-collapsed svg { transform: rotate(0deg); } +.mk-collapse.mk-collapsed-plus svg { + transform: rotate(45deg); +} .mk-is-active:not(.clone) { color: var(--nav-item-color-active); background: var(--nav-item-background-active); @@ -2701,28 +3554,113 @@ body:not(.is-mobile) .mk-tree-wrapper:not(.mk-section-wrapper):not(.mk-disable-i color: var(--text-faint); } -/* src/css/NewNote.css */ -.mk-flow-bar { +/* src/css/MainMenu.css */ +.mk-main-menu-container { display: flex; - margin: 8px 12px; - gap: 12px; + flex-direction: column; + margin: 6px; + gap: 4px; align-items: center; + margin-right: 10px; } -.mk-flow-bar-compact { +.mk-main-menu-inner { display: flex; - gap: 12px; + width: 100%; align-items: center; - padding: 8px; + gap: 8px; } -.is-tablet .mk-flow-bar-compact { - margin-right: 50px; - margin-top: 5px; - gap: 24px; +.mk-main-menu { + display: flex; + transition: all 0.2s ease; + align-items: center; + gap: 8px; + flex: 1; } -.is-phone .mk-flow-bar-compact { - margin-top: 5px; - gap: 24px; +.mk-main-menu.mk-hidden { + transform: translateX(-100%); + opacity: 0; + pointer-events: none; +} +.mk-main-menu-search { + transition: all 0.2s ease; + align-items: center; + gap: 8px; +} +.mk-main-menu-search.mk-hidden { + opacity: 0; + pointer-events: none; +} +.mk-main-menu-button { + padding: 8px 10px; + text-align: left; + border-radius: 4px; + align-items: center; + display: flex; + gap: 4px; + justify-content: center; +} +.mk-main-menu-search { + position: absolute; + display: flex; + width: calc(100% - 60px); +} +.mk-main-menu-search input { + width: 100%; +} +.mk-main-menu-icon { + background: var(--nav-item-background-hover); + padding: 2px; + border-radius: 2px; + text-transform: uppercase; + width: 20px; + height: 20px; + font-size: 12px; + justify-content: center; + margin-right: 4px; +} +.is-mobile .mk-main-menu-button { + font-size: var(--font-ui-medium); + font-weight: var(--font-medium); + gap: 4px; +} +.mk-main-menu-button > div { + display: flex; +} +.mk-main-menu-button.mk-main-menu-button-primary { + flex-grow: 1; + line-height: 1; + justify-content: flex-start; +} +.mk-main-menu .mk-main-menu-sticker { + margin-right: 8px; +} +.mk-main-menu-button svg { + height: 16px; + width: 16px; +} +body:not(.is-mobile) .mk-main-menu-button:hover { + background: var(--nav-item-background-hover); +} +.mk-menu-button { + display: flex; + padding-top: 0.5rem; + padding-bottom: 0.5rem; + padding-left: 0.5rem; + padding-right: 0.5rem; + font-size: 0.75rem; + line-height: 1.25rem; + align-items: center; + width: 100%; + border-radius: 0.375rem; +} +.mk-menu-button:hover { + background: var(--nav-item-background-hover); } +.mk-main-menu-container .mk-query { + width: 100%; +} + +/* src/css/NewNote.css */ .mk-new-note { flex-grow: 1; padding: 8px 12px; @@ -2755,44 +3693,56 @@ body:not(.is-mobile) .mk-tree-wrapper:not(.mk-section-wrapper):not(.mk-disable-i width: 16px; height: 16px; } -.mk-sidebar-switcher { +.mk-waypoint { display: flex; - margin: 8px 12px; - gap: 4px; } -.mk-sidebar-spaces .mk-sidebar-item { +.mk-waypoint .mk-waypoints-item { display: flex; justify-content: center; } -.mk-sidebar-spaces { +.is-mobile .mk-waypoints { + background: var(--background-primary); + border-top: thin solid var(--divider-color); + box-shadow: var(--input-shadow); +} +.is-mobile .mk-waypoints > div { + gap: 8px; +} +.mk-waypoints { display: flex; overflow: auto; - flex-grow: 1; - padding-left: 4px; + padding: var(--size-4-3) var(--size-4-3) var(--size-4-1) var(--size-4-3); } .mk-sidebar-expanded { flex-grow: 1; } -.mk-sidebar-item { - height: 32px; - min-width: 32px; - padding: 8px; - margin: 2px; - border-radius: 4px; +.mk-waypoint:hover .mk-waypoints-item:not(.mk-active) { + background: var(--nav-item-background-hover); +} +.mk-waypoints-item { + color: var(--text-muted); + height: 30px; + min-width: 30px; + padding: 6px; + border-radius: 15px; display: flex; align-items: center; gap: 4px; text-align: center; - font-size: var(--font-ui-smaller); - color: var(--tab-text-color); + font-size: var(--font-ui-normal); + color: var(--icon-color); transition: transform 250ms ease; } -.mk-sidebar-item-active { - background: var(--background-primary); - color: var(--text-normal) !important; +.is-mobile .mk-waypoints-item { + width: 40px; + height: 40px; + border-radius: 20px; } -.mk-sidebar-item-active svg { - color: var(--text-normal) !important; +.mk-waypoints-item.mk-active { + --label-color: var(--background-modifier-active-hover); + color: var(--text-n); + background-color: var(--label-color); + opacity: 1; } /* src/css/Blink.css */