From d19f9bb6ffb73be33ad800129587966bd44033ce Mon Sep 17 00:00:00 2001 From: JP Cen Date: Tue, 4 Apr 2023 17:11:25 -0400 Subject: [PATCH] 0.7 Release See release notes --- README.md | 6 +- main.js | 38330 ++++++++++++++++++++++++++---------------------- manifest.json | 2 +- styles.css | 638 +- 4 files changed, 21553 insertions(+), 17423 deletions(-) diff --git a/README.md b/README.md index 4032f6c..651b5d1 100644 --- a/README.md +++ b/README.md @@ -18,11 +18,7 @@ Make edits to your notes in the blink of your eye, quickly open and directly edi ### ⌛ Flow -Stay in the flow while writing, edit your notes, canvas or context directly inline. - -### 🧠 Maker Mode - -Create without learning markdown, just type slash to create a new block or select some text to style. +An editor experience that helps you stay in the flow while writing, editing your notes, canvas or context directly inline. --- diff --git a/main.js b/main.js index b99457c..927de31 100644 --- a/main.js +++ b/main.js @@ -46,6 +46,564 @@ var __toBinary = /* @__PURE__ */ (() => { }; })(); +// 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)); + } + function createExporter(exports2, previous) { + if (exports2 !== root) { + if (typeof Object.create === "function") { + Object.defineProperty(exports2, "__esModule", { value: true }); + } else { + exports2.__esModule = true; + } + } + 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]; + }; + __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]; + } + 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 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 _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; + } + } + 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 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 new (P4 || (P4 = Promise))(function(resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e4) { + reject(e4); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e4) { + reject(e4); + } + } + function step(result) { + result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); + } + 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; + } + 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 }; + } + }; + __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]; + } }; + } + 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; + } + } + 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 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); + }); + }; + } + 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]); + } + }; + __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; + } + }; + __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); + } + }; + __makeTemplateObject2 = function(cooked, raw) { + if (Object.defineProperty) { + Object.defineProperty(cooked, "raw", { value: raw }); + } else { + cooked.raw = raw; + } + 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); + } + __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); + }); + } +}); + +// 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); + } + } + } else if (argType === "object") { + if (arg.toString !== Object.prototype.toString && !arg.toString.toString().includes("[native code]")) { + classes.push(arg.toString()); + continue; + } + for (var key2 in arg) { + if (hasOwn.call(arg, key2) && arg[key2]) { + classes.push(key2); + } + } + } + } + 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/lodash/lodash.js var require_lodash = __commonJS({ "node_modules/lodash/lodash.js"(exports, module2) { @@ -734,7 +1292,7 @@ var require_lodash = __commonJS({ return string.match(reUnicodeWord) || []; } var runInContext = function runInContext2(context) { - context = context == null ? root : _7.defaults(root.Object(), context, _7.pick(root, contextProps)); + context = context == null ? root : _9.defaults(root.Object(), context, _9.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__"]; @@ -3460,7 +4018,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) { @@ -5122,7 +5680,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; @@ -5468,529 +6026,2175 @@ var require_lodash = __commonJS({ } return lodash; }; - var _7 = runInContext(); + var _9 = runInContext(); if (typeof define == "function" && typeof define.amd == "object" && define.amd) { - root._ = _7; + root._ = _9; define(function() { - return _7; + return _9; }); } else if (freeModule) { - (freeModule.exports = _7)._ = _7; - freeExports._ = _7; + (freeModule.exports = _9)._ = _9; + freeExports._ = _9; } else { - root._ = _7; + root._ = _9; } }).call(exports); } }); -// 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 __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))); +// node_modules/obsidian-dataview/lib/index.js +var require_lib = __commonJS({ + "node_modules/obsidian-dataview/lib/index.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + require("obsidian"); + var getAPI2 = (app2) => { + var _a2; + if (app2) + return (_a2 = app2.plugins.plugins.dataview) === null || _a2 === void 0 ? void 0 : _a2.api; + else + return window["DataviewAPI"]; + }; + var isPluginEnabled = (app2) => app2.plugins.enabledPlugins.has("dataview"); + exports.getAPI = getAPI2; + exports.isPluginEnabled = isPluginEnabled; + } +}); + +// node_modules/localforage/dist/localforage.js +var require_localforage = __commonJS({ + "node_modules/localforage/dist/localforage.js"(exports, module2) { + (function(f4) { + if (typeof exports === "object" && typeof module2 !== "undefined") { + module2.exports = f4(); + } else if (typeof define === "function" && define.amd) { + define([], f4); } else { - factory(createExporter(root)); - } - function createExporter(exports2, previous) { - if (exports2 !== root) { - if (typeof Object.create === "function") { - Object.defineProperty(exports2, "__esModule", { value: true }); + var g4; + if (typeof window !== "undefined") { + g4 = window; + } else if (typeof global !== "undefined") { + g4 = global; + } else if (typeof self !== "undefined") { + g4 = self; + } else { + g4 = this; + } + g4.localforage = f4(); + } + })(function() { + var define2, module3, exports2; + return function e4(t4, n2, r3) { + function s5(o4, u4) { + if (!n2[o4]) { + if (!t4[o4]) { + var a5 = typeof require == "function" && require; + if (!u4 && a5) + return a5(o4, true); + if (i4) + return i4(o4, true); + var f4 = new Error("Cannot find module '" + o4 + "'"); + throw f4.code = "MODULE_NOT_FOUND", f4; + } + var l3 = n2[o4] = { exports: {} }; + t4[o4][0].call(l3.exports, function(e5) { + var n3 = t4[o4][1][e5]; + return s5(n3 ? n3 : e5); + }, l3, l3.exports, e4, t4, n2, r3); + } + return n2[o4].exports; + } + var i4 = typeof require == "function" && require; + for (var o3 = 0; o3 < r3.length; o3++) + s5(r3[o3]); + return s5; + }({ 1: [function(_dereq_, module4, exports3) { + (function(global2) { + "use strict"; + var Mutation = global2.MutationObserver || global2.WebKitMutationObserver; + var scheduleDrain; + { + if (Mutation) { + var called = 0; + var observer = new Mutation(nextTick); + var element = global2.document.createTextNode(""); + observer.observe(element, { + characterData: true + }); + scheduleDrain = function() { + element.data = called = ++called % 2; + }; + } else if (!global2.setImmediate && typeof global2.MessageChannel !== "undefined") { + var channel = new global2.MessageChannel(); + channel.port1.onmessage = nextTick; + scheduleDrain = function() { + channel.port2.postMessage(0); + }; + } else if ("document" in global2 && "onreadystatechange" in global2.document.createElement("script")) { + scheduleDrain = function() { + var scriptEl = global2.document.createElement("script"); + scriptEl.onreadystatechange = function() { + nextTick(); + scriptEl.onreadystatechange = null; + scriptEl.parentNode.removeChild(scriptEl); + scriptEl = null; + }; + global2.document.documentElement.appendChild(scriptEl); + }; + } else { + scheduleDrain = function() { + setTimeout(nextTick, 0); + }; + } + } + var draining; + var queue = []; + function nextTick() { + draining = true; + var i4, oldQueue; + var len = queue.length; + while (len) { + oldQueue = queue; + queue = []; + i4 = -1; + while (++i4 < len) { + oldQueue[i4](); + } + len = queue.length; + } + draining = false; + } + module4.exports = immediate; + function immediate(task) { + if (queue.push(task) === 1 && !draining) { + scheduleDrain(); + } + } + }).call(this, typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}); + }, {}], 2: [function(_dereq_, module4, exports3) { + "use strict"; + var immediate = _dereq_(1); + function INTERNAL() { + } + var handlers = {}; + var REJECTED = ["REJECTED"]; + var FULFILLED = ["FULFILLED"]; + var PENDING = ["PENDING"]; + module4.exports = Promise2; + function Promise2(resolver) { + if (typeof resolver !== "function") { + throw new TypeError("resolver must be a function"); + } + this.state = PENDING; + this.queue = []; + this.outcome = void 0; + if (resolver !== INTERNAL) { + safelyResolveThenable(this, resolver); + } + } + Promise2.prototype["catch"] = function(onRejected) { + return this.then(null, onRejected); + }; + Promise2.prototype.then = function(onFulfilled, onRejected) { + if (typeof onFulfilled !== "function" && this.state === FULFILLED || typeof onRejected !== "function" && this.state === REJECTED) { + return this; + } + var promise = new this.constructor(INTERNAL); + if (this.state !== PENDING) { + var resolver = this.state === FULFILLED ? onFulfilled : onRejected; + unwrap(promise, resolver, this.outcome); } else { - exports2.__esModule = true; + this.queue.push(new QueueItem(promise, onFulfilled, onRejected)); } - } - return function(id2, v3) { - return exports2[id2] = previous ? previous(id2, v3) : v3; + return promise; }; - } - })(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; + function QueueItem(promise, onFulfilled, onRejected) { + this.promise = promise; + if (typeof onFulfilled === "function") { + this.onFulfilled = onFulfilled; + this.callFulfilled = this.otherCallFulfilled; + } + if (typeof onRejected === "function") { + this.onRejected = onRejected; + this.callRejected = this.otherCallRejected; + } } - 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]; + QueueItem.prototype.callFulfilled = function(value) { + handlers.resolve(this.promise, value); + }; + QueueItem.prototype.otherCallFulfilled = function(value) { + unwrap(this.promise, this.onFulfilled, value); + }; + QueueItem.prototype.callRejected = function(value) { + handlers.reject(this.promise, value); + }; + QueueItem.prototype.otherCallRejected = function(value) { + unwrap(this.promise, this.onRejected, value); + }; + function unwrap(promise, func, value) { + immediate(function() { + var returnValue; + try { + returnValue = func(value); + } catch (e4) { + return handlers.reject(promise, e4); + } + if (returnValue === promise) { + handlers.reject(promise, new TypeError("Cannot resolve promise with itself")); + } else { + handlers.resolve(promise, returnValue); + } + }); } - 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]]; + handlers.resolve = function(self2, value) { + var result = tryCatch(getThen, value); + if (result.status === "error") { + return handlers.reject(self2, result.value); } - 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); + var thenable = result.value; + if (thenable) { + safelyResolveThenable(self2, thenable); + } else { + self2.state = FULFILLED; + self2.outcome = value; + var i4 = -1; + var len = self2.queue.length; + while (++i4 < len) { + self2.queue[i4].callFulfilled(value); + } + } + return self2; }; - }; - __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); - }); + handlers.reject = function(self2, error) { + self2.state = REJECTED; + self2.outcome = error; + var i4 = -1; + var len = self2.queue.length; + while (++i4 < len) { + self2.queue[i4].callRejected(error); + } + return self2; + }; + function getThen(obj) { + var then = obj && obj.then; + if (obj && (typeof obj === "object" || typeof obj === "function") && typeof then === "function") { + return function appyThen() { + then.apply(obj, arguments); + }; + } } - return new (P4 || (P4 = Promise))(function(resolve, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e4) { - reject(e4); + function safelyResolveThenable(self2, thenable) { + var called = false; + function onError(value) { + if (called) { + return; } + called = true; + handlers.reject(self2, value); } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e4) { - reject(e4); + function onSuccess(value) { + if (called) { + return; } + called = true; + handlers.resolve(self2, value); } - function step(result) { - result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); + function tryToUnwrap() { + thenable(onSuccess, onError); + } + var result = tryCatch(tryToUnwrap); + if (result.status === "error") { + onError(result.value); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; - __generator2 = function(thisArg, body) { - var _7 = { 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] && (_7 = 0)), _7) - 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: - _7.label++; - return { value: op[1], done: false }; - case 5: - _7.label++; - y5 = op[1]; - op = [0]; - continue; - case 7: - op = _7.ops.pop(); - _7.trys.pop(); - continue; - default: - if (!(t4 = _7.trys, t4 = t4.length > 0 && t4[t4.length - 1]) && (op[0] === 6 || op[0] === 2)) { - _7 = 0; - continue; - } - if (op[0] === 3 && (!t4 || op[1] > t4[0] && op[1] < t4[3])) { - _7.label = op[1]; - break; - } - if (op[0] === 6 && _7.label < t4[1]) { - _7.label = t4[1]; - t4 = op; - break; - } - if (t4 && _7.label < t4[2]) { - _7.label = t4[2]; - _7.ops.push(op); - break; - } - if (t4[2]) - _7.ops.pop(); - _7.trys.pop(); - continue; + function tryCatch(func, value) { + var out = {}; + try { + out.value = func(value); + out.status = "success"; + } catch (e4) { + out.status = "error"; + out.value = e4; + } + return out; + } + Promise2.resolve = resolve; + function resolve(value) { + if (value instanceof this) { + return value; + } + return handlers.resolve(new this(INTERNAL), value); + } + Promise2.reject = reject; + function reject(reason) { + var promise = new this(INTERNAL); + return handlers.reject(promise, reason); + } + Promise2.all = all; + function all(iterable) { + var self2 = this; + if (Object.prototype.toString.call(iterable) !== "[object Array]") { + return this.reject(new TypeError("must be an array")); + } + var len = iterable.length; + var called = false; + if (!len) { + return this.resolve([]); + } + var values = new Array(len); + var resolved = 0; + var i4 = -1; + var promise = new this(INTERNAL); + while (++i4 < len) { + allResolver(iterable[i4], i4); + } + return promise; + function allResolver(value, i5) { + self2.resolve(value).then(resolveFromAll, function(error) { + if (!called) { + called = true; + handlers.reject(promise, error); + } + }); + function resolveFromAll(outValue) { + values[i5] = outValue; + if (++resolved === len && !called) { + called = true; + handlers.resolve(promise, values); } - op = body.call(thisArg, _7); - } 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 }; + } } - }; - __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]; - } }; + Promise2.race = race; + function race(iterable) { + var self2 = this; + if (Object.prototype.toString.call(iterable) !== "[object Array]") { + return this.reject(new TypeError("must be an array")); + } + var len = iterable.length; + var called = false; + if (!len) { + return this.resolve([]); + } + var i4 = -1; + var promise = new this(INTERNAL); + while (++i4 < len) { + resolver(iterable[i4]); + } + return promise; + function resolver(value) { + self2.resolve(value).then(function(response) { + if (!called) { + called = true; + handlers.resolve(promise, response); + } + }, function(error) { + if (!called) { + called = true; + handlers.reject(promise, error); + } + }); + } } - 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 { + }, { "1": 1 }], 3: [function(_dereq_, module4, exports3) { + (function(global2) { + "use strict"; + if (typeof global2.Promise !== "function") { + global2.Promise = _dereq_(2); + } + }).call(this, typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}); + }, { "2": 2 }], 4: [function(_dereq_, module4, exports3) { + "use strict"; + 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; + }; + function _classCallCheck(instance, Constructor) { + if (!(instance instanceof Constructor)) { + throw new TypeError("Cannot call a class as a function"); + } + } + function getIDB() { try { - if (r3 && !r3.done && (m5 = i4["return"])) - m5.call(i4); - } finally { - if (e4) - throw e4.error; + if (typeof indexedDB !== "undefined") { + return indexedDB; + } + if (typeof webkitIndexedDB !== "undefined") { + return webkitIndexedDB; + } + if (typeof mozIndexedDB !== "undefined") { + return mozIndexedDB; + } + if (typeof OIndexedDB !== "undefined") { + return OIndexedDB; + } + if (typeof msIndexedDB !== "undefined") { + return msIndexedDB; + } + } catch (e4) { + return; } } - 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]; + var idb = getIDB(); + function isIndexedDBValid() { + try { + if (!idb || !idb.open) { + return false; } + var isSafari = typeof openDatabase !== "undefined" && /(Safari|iPhone|iPad|iPod)/.test(navigator.userAgent) && !/Chrome/.test(navigator.userAgent) && !/BlackBerry/.test(navigator.platform); + var hasFetch = typeof fetch === "function" && fetch.toString().indexOf("[native code") !== -1; + return (!isSafari || hasFetch) && typeof indexedDB !== "undefined" && typeof IDBKeyRange !== "undefined"; + } catch (e4) { + return false; } - 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); - }); - }; } - function resume(n2, v3) { + function createBlob(parts, properties2) { + parts = parts || []; + properties2 = properties2 || {}; try { - step(g4[n2](v3)); + return new Blob(parts, properties2); } catch (e4) { - settle(q5[0][3], e4); + if (e4.name !== "TypeError") { + throw e4; + } + var Builder = typeof BlobBuilder !== "undefined" ? BlobBuilder : typeof MSBlobBuilder !== "undefined" ? MSBlobBuilder : typeof MozBlobBuilder !== "undefined" ? MozBlobBuilder : WebKitBlobBuilder; + var builder = new Builder(); + for (var i4 = 0; i4 < parts.length; i4 += 1) { + builder.append(parts[i4]); + } + return builder.getBlob(properties2.type); } } - function step(r3) { - r3.value instanceof __await2 ? Promise.resolve(r3.value.v).then(fulfill, reject) : settle(q5[0][2], r3); + if (typeof Promise === "undefined") { + _dereq_(3); } - function fulfill(value) { - resume("next", value); + var Promise$1 = Promise; + function executeCallback(promise, callback) { + if (callback) { + promise.then(function(result) { + callback(null, result); + }, function(error) { + callback(error); + }); + } } - function reject(value) { - resume("throw", value); + function executeTwoCallbacks(promise, callback, errorCallback) { + if (typeof callback === "function") { + promise.then(callback); + } + if (typeof errorCallback === "function") { + promise["catch"](errorCallback); + } } - function settle(f4, v3) { - if (f4(v3), q5.shift(), q5.length) - resume(q5[0][0], q5[0][1]); + function normalizeKey(key3) { + if (typeof key3 !== "string") { + console.warn(key3 + " used as a key, but it is not a string."); + key3 = String(key3); + } + return key3; } - }; - __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: n2 === "return" } : f4 ? f4(v3) : v3; - } : f4; + function getCallback() { + if (arguments.length && typeof arguments[arguments.length - 1] === "function") { + return arguments[arguments.length - 1]; + } } - }; - __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); + var DETECT_BLOB_SUPPORT_STORE = "local-forage-detect-blob-support"; + var supportsBlobs = void 0; + var dbContexts = {}; + var toString2 = Object.prototype.toString; + var READ_ONLY = "readonly"; + var READ_WRITE = "readwrite"; + function _binStringToArrayBuffer(bin) { + var length2 = bin.length; + var buf = new ArrayBuffer(length2); + var arr = new Uint8Array(buf); + for (var i4 = 0; i4 < length2; i4++) { + arr[i4] = bin.charCodeAt(i4); + } + return buf; + } + function _checkBlobSupportWithoutCaching(idb2) { + return new Promise$1(function(resolve) { + var txn = idb2.transaction(DETECT_BLOB_SUPPORT_STORE, READ_WRITE); + var blob = createBlob([""]); + txn.objectStore(DETECT_BLOB_SUPPORT_STORE).put(blob, "key"); + txn.onabort = function(e4) { + e4.preventDefault(); + e4.stopPropagation(); + resolve(false); + }; + txn.oncomplete = function() { + var matchedChrome = navigator.userAgent.match(/Chrome\/(\d+)/); + var matchedEdge = navigator.userAgent.match(/Edge\//); + resolve(matchedEdge || !matchedChrome || parseInt(matchedChrome[1], 10) >= 43); + }; + })["catch"](function() { + return false; + }); + } + function _checkBlobSupport(idb2) { + if (typeof supportsBlobs === "boolean") { + return Promise$1.resolve(supportsBlobs); + } + return _checkBlobSupportWithoutCaching(idb2).then(function(value) { + supportsBlobs = value; + return supportsBlobs; + }); + } + function _deferReadiness(dbInfo) { + var dbContext = dbContexts[dbInfo.name]; + var deferredOperation = {}; + deferredOperation.promise = new Promise$1(function(resolve, reject) { + deferredOperation.resolve = resolve; + deferredOperation.reject = reject; + }); + dbContext.deferredOperations.push(deferredOperation); + if (!dbContext.dbReady) { + dbContext.dbReady = deferredOperation.promise; + } else { + dbContext.dbReady = dbContext.dbReady.then(function() { + return deferredOperation.promise; }); - }; + } } - function settle(resolve, reject, d5, v3) { - Promise.resolve(v3).then(function(v4) { - resolve({ value: v4, done: d5 }); - }, reject); + function _advanceReadiness(dbInfo) { + var dbContext = dbContexts[dbInfo.name]; + var deferredOperation = dbContext.deferredOperations.pop(); + if (deferredOperation) { + deferredOperation.resolve(); + return deferredOperation.promise; + } } - }; - __makeTemplateObject2 = function(cooked, raw) { - if (Object.defineProperty) { - Object.defineProperty(cooked, "raw", { value: raw }); - } else { - cooked.raw = raw; + function _rejectReadiness(dbInfo, err) { + var dbContext = dbContexts[dbInfo.name]; + var deferredOperation = dbContext.deferredOperations.pop(); + if (deferredOperation) { + deferredOperation.reject(err); + return deferredOperation.promise; + } } - 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); + function _getConnection(dbInfo, upgradeNeeded) { + return new Promise$1(function(resolve, reject) { + dbContexts[dbInfo.name] = dbContexts[dbInfo.name] || createDbContext(); + if (dbInfo.db) { + if (upgradeNeeded) { + _deferReadiness(dbInfo); + dbInfo.db.close(); + } else { + return resolve(dbInfo.db); + } + } + var dbArgs = [dbInfo.name]; + if (upgradeNeeded) { + dbArgs.push(dbInfo.version); + } + var openreq = idb.open.apply(idb, dbArgs); + if (upgradeNeeded) { + openreq.onupgradeneeded = function(e4) { + var db = openreq.result; + try { + db.createObjectStore(dbInfo.storeName); + if (e4.oldVersion <= 1) { + db.createObjectStore(DETECT_BLOB_SUPPORT_STORE); + } + } catch (ex) { + if (ex.name === "ConstraintError") { + console.warn('The database "' + dbInfo.name + '" has been upgraded from version ' + e4.oldVersion + " to version " + e4.newVersion + ', but the storage "' + dbInfo.storeName + '" already exists.'); + } else { + throw ex; + } + } + }; + } + openreq.onerror = function(e4) { + e4.preventDefault(); + reject(openreq.error); + }; + openreq.onsuccess = function() { + var db = openreq.result; + db.onversionchange = function(e4) { + e4.target.close(); + }; + resolve(db); + _advanceReadiness(dbInfo); + }; + }); } - __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("__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); - }); - } -}); - -// 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 classNames8() { - 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 = classNames8.apply(null, arg); - if (inner) { - classes.push(inner); + function _getOriginalConnection(dbInfo) { + return _getConnection(dbInfo, false); + } + function _getUpgradedConnection(dbInfo) { + return _getConnection(dbInfo, true); + } + function _isUpgradeNeeded(dbInfo, defaultVersion) { + if (!dbInfo.db) { + return true; + } + var isNewStore = !dbInfo.db.objectStoreNames.contains(dbInfo.storeName); + var isDowngrade = dbInfo.version < dbInfo.db.version; + var isUpgrade = dbInfo.version > dbInfo.db.version; + if (isDowngrade) { + if (dbInfo.version !== defaultVersion) { + console.warn('The database "' + dbInfo.name + `" can't be downgraded from version ` + dbInfo.db.version + " to version " + dbInfo.version + "."); + } + dbInfo.version = dbInfo.db.version; + } + if (isUpgrade || isNewStore) { + if (isNewStore) { + var incVersion = dbInfo.db.version + 1; + if (incVersion > dbInfo.version) { + dbInfo.version = incVersion; } } - } else if (argType === "object") { - if (arg.toString !== Object.prototype.toString && !arg.toString.toString().includes("[native code]")) { - classes.push(arg.toString()); - continue; + return true; + } + return false; + } + function _encodeBlob(blob) { + return new Promise$1(function(resolve, reject) { + var reader = new FileReader(); + reader.onerror = reject; + reader.onloadend = function(e4) { + var base64 = btoa(e4.target.result || ""); + resolve({ + __local_forage_encoded_blob: true, + data: base64, + type: blob.type + }); + }; + reader.readAsBinaryString(blob); + }); + } + function _decodeBlob(encodedBlob) { + var arrayBuff = _binStringToArrayBuffer(atob(encodedBlob.data)); + return createBlob([arrayBuff], { type: encodedBlob.type }); + } + function _isEncodedBlob(value) { + return value && value.__local_forage_encoded_blob; + } + function _fullyReady(callback) { + var self2 = this; + var promise = self2._initReady().then(function() { + var dbContext = dbContexts[self2._dbInfo.name]; + if (dbContext && dbContext.dbReady) { + return dbContext.dbReady; } - for (var key2 in arg) { - if (hasOwn.call(arg, key2) && arg[key2]) { - classes.push(key2); + }); + executeTwoCallbacks(promise, callback, callback); + return promise; + } + function _tryReconnect(dbInfo) { + _deferReadiness(dbInfo); + var dbContext = dbContexts[dbInfo.name]; + var forages = dbContext.forages; + for (var i4 = 0; i4 < forages.length; i4++) { + var forage = forages[i4]; + if (forage._dbInfo.db) { + forage._dbInfo.db.close(); + forage._dbInfo.db = null; + } + } + dbInfo.db = null; + return _getOriginalConnection(dbInfo).then(function(db) { + dbInfo.db = db; + if (_isUpgradeNeeded(dbInfo)) { + return _getUpgradedConnection(dbInfo); + } + return db; + }).then(function(db) { + dbInfo.db = dbContext.db = db; + for (var i5 = 0; i5 < forages.length; i5++) { + forages[i5]._dbInfo.db = db; + } + })["catch"](function(err) { + _rejectReadiness(dbInfo, err); + throw err; + }); + } + function createTransaction(dbInfo, mode, callback, retries) { + if (retries === void 0) { + retries = 1; + } + try { + var tx = dbInfo.db.transaction(dbInfo.storeName, mode); + callback(null, tx); + } catch (err) { + if (retries > 0 && (!dbInfo.db || err.name === "InvalidStateError" || err.name === "NotFoundError")) { + return Promise$1.resolve().then(function() { + if (!dbInfo.db || err.name === "NotFoundError" && !dbInfo.db.objectStoreNames.contains(dbInfo.storeName) && dbInfo.version <= dbInfo.db.version) { + if (dbInfo.db) { + dbInfo.version = dbInfo.db.version + 1; + } + return _getUpgradedConnection(dbInfo); + } + }).then(function() { + return _tryReconnect(dbInfo).then(function() { + createTransaction(dbInfo, mode, callback, retries - 1); + }); + })["catch"](callback); + } + callback(err); + } + } + function createDbContext() { + return { + forages: [], + db: null, + dbReady: null, + deferredOperations: [] + }; + } + function _initStorage(options) { + var self2 = this; + var dbInfo = { + db: null + }; + if (options) { + for (var i4 in options) { + dbInfo[i4] = options[i4]; + } + } + var dbContext = dbContexts[dbInfo.name]; + if (!dbContext) { + dbContext = createDbContext(); + dbContexts[dbInfo.name] = dbContext; + } + dbContext.forages.push(self2); + if (!self2._initReady) { + self2._initReady = self2.ready; + self2.ready = _fullyReady; + } + var initPromises = []; + function ignoreErrors() { + return Promise$1.resolve(); + } + for (var j4 = 0; j4 < dbContext.forages.length; j4++) { + var forage = dbContext.forages[j4]; + if (forage !== self2) { + initPromises.push(forage._initReady()["catch"](ignoreErrors)); + } + } + var forages = dbContext.forages.slice(0); + return Promise$1.all(initPromises).then(function() { + dbInfo.db = dbContext.db; + return _getOriginalConnection(dbInfo); + }).then(function(db) { + dbInfo.db = db; + if (_isUpgradeNeeded(dbInfo, self2._defaultConfig.version)) { + return _getUpgradedConnection(dbInfo); + } + return db; + }).then(function(db) { + dbInfo.db = dbContext.db = db; + self2._dbInfo = dbInfo; + for (var k5 = 0; k5 < forages.length; k5++) { + var forage2 = forages[k5]; + if (forage2 !== self2) { + forage2._dbInfo.db = dbInfo.db; + forage2._dbInfo.version = dbInfo.version; + } + } + }); + } + function getItem(key3, callback) { + var self2 = this; + key3 = normalizeKey(key3); + var promise = new Promise$1(function(resolve, reject) { + self2.ready().then(function() { + createTransaction(self2._dbInfo, READ_ONLY, function(err, transaction) { + if (err) { + return reject(err); + } + try { + var store = transaction.objectStore(self2._dbInfo.storeName); + var req = store.get(key3); + req.onsuccess = function() { + var value = req.result; + if (value === void 0) { + value = null; + } + if (_isEncodedBlob(value)) { + value = _decodeBlob(value); + } + resolve(value); + }; + req.onerror = function() { + reject(req.error); + }; + } catch (e4) { + reject(e4); + } + }); + })["catch"](reject); + }); + executeCallback(promise, callback); + return promise; + } + function iterate(iterator, callback) { + var self2 = this; + var promise = new Promise$1(function(resolve, reject) { + self2.ready().then(function() { + createTransaction(self2._dbInfo, READ_ONLY, function(err, transaction) { + if (err) { + return reject(err); + } + try { + var store = transaction.objectStore(self2._dbInfo.storeName); + var req = store.openCursor(); + var iterationNumber = 1; + req.onsuccess = function() { + var cursor = req.result; + if (cursor) { + var value = cursor.value; + if (_isEncodedBlob(value)) { + value = _decodeBlob(value); + } + var result = iterator(value, cursor.key, iterationNumber++); + if (result !== void 0) { + resolve(result); + } else { + cursor["continue"](); + } + } else { + resolve(); + } + }; + req.onerror = function() { + reject(req.error); + }; + } catch (e4) { + reject(e4); + } + }); + })["catch"](reject); + }); + executeCallback(promise, callback); + return promise; + } + function setItem(key3, value, callback) { + var self2 = this; + key3 = normalizeKey(key3); + var promise = new Promise$1(function(resolve, reject) { + var dbInfo; + self2.ready().then(function() { + dbInfo = self2._dbInfo; + if (toString2.call(value) === "[object Blob]") { + return _checkBlobSupport(dbInfo.db).then(function(blobSupport) { + if (blobSupport) { + return value; + } + return _encodeBlob(value); + }); + } + return value; + }).then(function(value2) { + createTransaction(self2._dbInfo, READ_WRITE, function(err, transaction) { + if (err) { + return reject(err); + } + try { + var store = transaction.objectStore(self2._dbInfo.storeName); + if (value2 === null) { + value2 = void 0; + } + var req = store.put(value2, key3); + transaction.oncomplete = function() { + if (value2 === void 0) { + value2 = null; + } + resolve(value2); + }; + transaction.onabort = transaction.onerror = function() { + var err2 = req.error ? req.error : req.transaction.error; + reject(err2); + }; + } catch (e4) { + reject(e4); + } + }); + })["catch"](reject); + }); + executeCallback(promise, callback); + return promise; + } + function removeItem(key3, callback) { + var self2 = this; + key3 = normalizeKey(key3); + var promise = new Promise$1(function(resolve, reject) { + self2.ready().then(function() { + createTransaction(self2._dbInfo, READ_WRITE, function(err, transaction) { + if (err) { + return reject(err); + } + try { + var store = transaction.objectStore(self2._dbInfo.storeName); + var req = store["delete"](key3); + transaction.oncomplete = function() { + resolve(); + }; + transaction.onerror = function() { + reject(req.error); + }; + transaction.onabort = function() { + var err2 = req.error ? req.error : req.transaction.error; + reject(err2); + }; + } catch (e4) { + reject(e4); + } + }); + })["catch"](reject); + }); + executeCallback(promise, callback); + return promise; + } + function clear(callback) { + var self2 = this; + var promise = new Promise$1(function(resolve, reject) { + self2.ready().then(function() { + createTransaction(self2._dbInfo, READ_WRITE, function(err, transaction) { + if (err) { + return reject(err); + } + try { + var store = transaction.objectStore(self2._dbInfo.storeName); + var req = store.clear(); + transaction.oncomplete = function() { + resolve(); + }; + transaction.onabort = transaction.onerror = function() { + var err2 = req.error ? req.error : req.transaction.error; + reject(err2); + }; + } catch (e4) { + reject(e4); + } + }); + })["catch"](reject); + }); + executeCallback(promise, callback); + return promise; + } + function length(callback) { + var self2 = this; + var promise = new Promise$1(function(resolve, reject) { + self2.ready().then(function() { + createTransaction(self2._dbInfo, READ_ONLY, function(err, transaction) { + if (err) { + return reject(err); + } + try { + var store = transaction.objectStore(self2._dbInfo.storeName); + var req = store.count(); + req.onsuccess = function() { + resolve(req.result); + }; + req.onerror = function() { + reject(req.error); + }; + } catch (e4) { + reject(e4); + } + }); + })["catch"](reject); + }); + executeCallback(promise, callback); + return promise; + } + function key2(n2, callback) { + var self2 = this; + var promise = new Promise$1(function(resolve, reject) { + if (n2 < 0) { + resolve(null); + return; + } + self2.ready().then(function() { + createTransaction(self2._dbInfo, READ_ONLY, function(err, transaction) { + if (err) { + return reject(err); + } + try { + var store = transaction.objectStore(self2._dbInfo.storeName); + var advanced = false; + var req = store.openKeyCursor(); + req.onsuccess = function() { + var cursor = req.result; + if (!cursor) { + resolve(null); + return; + } + if (n2 === 0) { + resolve(cursor.key); + } else { + if (!advanced) { + advanced = true; + cursor.advance(n2); + } else { + resolve(cursor.key); + } + } + }; + req.onerror = function() { + reject(req.error); + }; + } catch (e4) { + reject(e4); + } + }); + })["catch"](reject); + }); + executeCallback(promise, callback); + return promise; + } + function keys(callback) { + var self2 = this; + var promise = new Promise$1(function(resolve, reject) { + self2.ready().then(function() { + createTransaction(self2._dbInfo, READ_ONLY, function(err, transaction) { + if (err) { + return reject(err); + } + try { + var store = transaction.objectStore(self2._dbInfo.storeName); + var req = store.openKeyCursor(); + var keys2 = []; + req.onsuccess = function() { + var cursor = req.result; + if (!cursor) { + resolve(keys2); + return; + } + keys2.push(cursor.key); + cursor["continue"](); + }; + req.onerror = function() { + reject(req.error); + }; + } catch (e4) { + reject(e4); + } + }); + })["catch"](reject); + }); + executeCallback(promise, callback); + return promise; + } + function dropInstance(options, callback) { + callback = getCallback.apply(this, arguments); + var currentConfig = this.config(); + options = typeof options !== "function" && options || {}; + if (!options.name) { + options.name = options.name || currentConfig.name; + options.storeName = options.storeName || currentConfig.storeName; + } + var self2 = this; + var promise; + if (!options.name) { + promise = Promise$1.reject("Invalid arguments"); + } else { + var isCurrentDb = options.name === currentConfig.name && self2._dbInfo.db; + var dbPromise = isCurrentDb ? Promise$1.resolve(self2._dbInfo.db) : _getOriginalConnection(options).then(function(db) { + var dbContext = dbContexts[options.name]; + var forages = dbContext.forages; + dbContext.db = db; + for (var i4 = 0; i4 < forages.length; i4++) { + forages[i4]._dbInfo.db = db; + } + return db; + }); + if (!options.storeName) { + promise = dbPromise.then(function(db) { + _deferReadiness(options); + var dbContext = dbContexts[options.name]; + var forages = dbContext.forages; + db.close(); + for (var i4 = 0; i4 < forages.length; i4++) { + var forage = forages[i4]; + forage._dbInfo.db = null; + } + var dropDBPromise = new Promise$1(function(resolve, reject) { + var req = idb.deleteDatabase(options.name); + req.onerror = function() { + var db2 = req.result; + if (db2) { + db2.close(); + } + reject(req.error); + }; + req.onblocked = function() { + console.warn('dropInstance blocked for database "' + options.name + '" until all open connections are closed'); + }; + req.onsuccess = function() { + var db2 = req.result; + if (db2) { + db2.close(); + } + resolve(db2); + }; + }); + return dropDBPromise.then(function(db2) { + dbContext.db = db2; + for (var i5 = 0; i5 < forages.length; i5++) { + var _forage = forages[i5]; + _advanceReadiness(_forage._dbInfo); + } + })["catch"](function(err) { + (_rejectReadiness(options, err) || Promise$1.resolve())["catch"](function() { + }); + throw err; + }); + }); + } else { + promise = dbPromise.then(function(db) { + if (!db.objectStoreNames.contains(options.storeName)) { + return; + } + var newVersion = db.version + 1; + _deferReadiness(options); + var dbContext = dbContexts[options.name]; + var forages = dbContext.forages; + db.close(); + for (var i4 = 0; i4 < forages.length; i4++) { + var forage = forages[i4]; + forage._dbInfo.db = null; + forage._dbInfo.version = newVersion; + } + var dropObjectPromise = new Promise$1(function(resolve, reject) { + var req = idb.open(options.name, newVersion); + req.onerror = function(err) { + var db2 = req.result; + db2.close(); + reject(err); + }; + req.onupgradeneeded = function() { + var db2 = req.result; + db2.deleteObjectStore(options.storeName); + }; + req.onsuccess = function() { + var db2 = req.result; + db2.close(); + resolve(db2); + }; + }); + return dropObjectPromise.then(function(db2) { + dbContext.db = db2; + for (var j4 = 0; j4 < forages.length; j4++) { + var _forage2 = forages[j4]; + _forage2._dbInfo.db = db2; + _advanceReadiness(_forage2._dbInfo); + } + })["catch"](function(err) { + (_rejectReadiness(options, err) || Promise$1.resolve())["catch"](function() { + }); + throw err; + }); + }); + } + } + executeCallback(promise, callback); + return promise; + } + var asyncStorage = { + _driver: "asyncStorage", + _initStorage, + _support: isIndexedDBValid(), + iterate, + getItem, + setItem, + removeItem, + clear, + length, + key: key2, + keys, + dropInstance + }; + function isWebSQLValid() { + return typeof openDatabase === "function"; + } + var BASE_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; + var BLOB_TYPE_PREFIX = "~~local_forage_type~"; + var BLOB_TYPE_PREFIX_REGEX = /^~~local_forage_type~([^~]+)~/; + var SERIALIZED_MARKER = "__lfsc__:"; + var SERIALIZED_MARKER_LENGTH = SERIALIZED_MARKER.length; + var TYPE_ARRAYBUFFER = "arbf"; + var TYPE_BLOB = "blob"; + var TYPE_INT8ARRAY = "si08"; + var TYPE_UINT8ARRAY = "ui08"; + var TYPE_UINT8CLAMPEDARRAY = "uic8"; + var TYPE_INT16ARRAY = "si16"; + var TYPE_INT32ARRAY = "si32"; + var TYPE_UINT16ARRAY = "ur16"; + var TYPE_UINT32ARRAY = "ui32"; + var TYPE_FLOAT32ARRAY = "fl32"; + var TYPE_FLOAT64ARRAY = "fl64"; + var TYPE_SERIALIZED_MARKER_LENGTH = SERIALIZED_MARKER_LENGTH + TYPE_ARRAYBUFFER.length; + var toString$1 = Object.prototype.toString; + function stringToBuffer(serializedString) { + var bufferLength = serializedString.length * 0.75; + var len = serializedString.length; + var i4; + var p3 = 0; + var encoded1, encoded2, encoded3, encoded4; + if (serializedString[serializedString.length - 1] === "=") { + bufferLength--; + if (serializedString[serializedString.length - 2] === "=") { + bufferLength--; + } + } + var buffer = new ArrayBuffer(bufferLength); + var bytes = new Uint8Array(buffer); + for (i4 = 0; i4 < len; i4 += 4) { + encoded1 = BASE_CHARS.indexOf(serializedString[i4]); + encoded2 = BASE_CHARS.indexOf(serializedString[i4 + 1]); + encoded3 = BASE_CHARS.indexOf(serializedString[i4 + 2]); + encoded4 = BASE_CHARS.indexOf(serializedString[i4 + 3]); + bytes[p3++] = encoded1 << 2 | encoded2 >> 4; + bytes[p3++] = (encoded2 & 15) << 4 | encoded3 >> 2; + bytes[p3++] = (encoded3 & 3) << 6 | encoded4 & 63; + } + return buffer; + } + function bufferToString(buffer) { + var bytes = new Uint8Array(buffer); + var base64String = ""; + var i4; + for (i4 = 0; i4 < bytes.length; i4 += 3) { + base64String += BASE_CHARS[bytes[i4] >> 2]; + base64String += BASE_CHARS[(bytes[i4] & 3) << 4 | bytes[i4 + 1] >> 4]; + base64String += BASE_CHARS[(bytes[i4 + 1] & 15) << 2 | bytes[i4 + 2] >> 6]; + base64String += BASE_CHARS[bytes[i4 + 2] & 63]; + } + if (bytes.length % 3 === 2) { + base64String = base64String.substring(0, base64String.length - 1) + "="; + } else if (bytes.length % 3 === 1) { + base64String = base64String.substring(0, base64String.length - 2) + "=="; + } + return base64String; + } + function serialize(value, callback) { + var valueType = ""; + if (value) { + valueType = toString$1.call(value); + } + if (value && (valueType === "[object ArrayBuffer]" || value.buffer && toString$1.call(value.buffer) === "[object ArrayBuffer]")) { + var buffer; + var marker = SERIALIZED_MARKER; + if (value instanceof ArrayBuffer) { + buffer = value; + marker += TYPE_ARRAYBUFFER; + } else { + buffer = value.buffer; + if (valueType === "[object Int8Array]") { + marker += TYPE_INT8ARRAY; + } else if (valueType === "[object Uint8Array]") { + marker += TYPE_UINT8ARRAY; + } else if (valueType === "[object Uint8ClampedArray]") { + marker += TYPE_UINT8CLAMPEDARRAY; + } else if (valueType === "[object Int16Array]") { + marker += TYPE_INT16ARRAY; + } else if (valueType === "[object Uint16Array]") { + marker += TYPE_UINT16ARRAY; + } else if (valueType === "[object Int32Array]") { + marker += TYPE_INT32ARRAY; + } else if (valueType === "[object Uint32Array]") { + marker += TYPE_UINT32ARRAY; + } else if (valueType === "[object Float32Array]") { + marker += TYPE_FLOAT32ARRAY; + } else if (valueType === "[object Float64Array]") { + marker += TYPE_FLOAT64ARRAY; + } else { + callback(new Error("Failed to get type for BinaryArray")); } } + callback(marker + bufferToString(buffer)); + } else if (valueType === "[object Blob]") { + var fileReader = new FileReader(); + fileReader.onload = function() { + var str = BLOB_TYPE_PREFIX + value.type + "~" + bufferToString(this.result); + callback(SERIALIZED_MARKER + TYPE_BLOB + str); + }; + fileReader.readAsArrayBuffer(value); + } else { + try { + callback(JSON.stringify(value)); + } catch (e4) { + console.error("Couldn't convert value into a JSON string: ", value); + callback(null, e4); + } } } - return classes.join(" "); - } - if (typeof module2 !== "undefined" && module2.exports) { - classNames8.default = classNames8; - module2.exports = classNames8; - } else if (typeof define === "function" && typeof define.amd === "object" && define.amd) { - define("classnames", [], function() { - return classNames8; - }); - } else { - window.classNames = classNames8; - } - })(); - } -}); - -// node_modules/obsidian-dataview/lib/index.js -var require_lib = __commonJS({ - "node_modules/obsidian-dataview/lib/index.js"(exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - require("obsidian"); - var getAPI2 = (app2) => { - var _a2; - if (app2) - return (_a2 = app2.plugins.plugins.dataview) === null || _a2 === void 0 ? void 0 : _a2.api; - else - return window["DataviewAPI"]; - }; - var isPluginEnabled = (app2) => app2.plugins.enabledPlugins.has("dataview"); - exports.getAPI = getAPI2; - exports.isPluginEnabled = isPluginEnabled; + function deserialize(value) { + if (value.substring(0, SERIALIZED_MARKER_LENGTH) !== SERIALIZED_MARKER) { + return JSON.parse(value); + } + var serializedString = value.substring(TYPE_SERIALIZED_MARKER_LENGTH); + var type = value.substring(SERIALIZED_MARKER_LENGTH, TYPE_SERIALIZED_MARKER_LENGTH); + var blobType; + if (type === TYPE_BLOB && BLOB_TYPE_PREFIX_REGEX.test(serializedString)) { + var matcher = serializedString.match(BLOB_TYPE_PREFIX_REGEX); + blobType = matcher[1]; + serializedString = serializedString.substring(matcher[0].length); + } + var buffer = stringToBuffer(serializedString); + switch (type) { + case TYPE_ARRAYBUFFER: + return buffer; + case TYPE_BLOB: + return createBlob([buffer], { type: blobType }); + case TYPE_INT8ARRAY: + return new Int8Array(buffer); + case TYPE_UINT8ARRAY: + return new Uint8Array(buffer); + case TYPE_UINT8CLAMPEDARRAY: + return new Uint8ClampedArray(buffer); + case TYPE_INT16ARRAY: + return new Int16Array(buffer); + case TYPE_UINT16ARRAY: + return new Uint16Array(buffer); + case TYPE_INT32ARRAY: + return new Int32Array(buffer); + case TYPE_UINT32ARRAY: + return new Uint32Array(buffer); + case TYPE_FLOAT32ARRAY: + return new Float32Array(buffer); + case TYPE_FLOAT64ARRAY: + return new Float64Array(buffer); + default: + throw new Error("Unkown type: " + type); + } + } + var localforageSerializer = { + serialize, + deserialize, + stringToBuffer, + bufferToString + }; + function createDbTable(t4, dbInfo, callback, errorCallback) { + t4.executeSql("CREATE TABLE IF NOT EXISTS " + dbInfo.storeName + " (id INTEGER PRIMARY KEY, key unique, value)", [], callback, errorCallback); + } + function _initStorage$1(options) { + var self2 = this; + var dbInfo = { + db: null + }; + if (options) { + for (var i4 in options) { + dbInfo[i4] = typeof options[i4] !== "string" ? options[i4].toString() : options[i4]; + } + } + var dbInfoPromise = new Promise$1(function(resolve, reject) { + try { + dbInfo.db = openDatabase(dbInfo.name, String(dbInfo.version), dbInfo.description, dbInfo.size); + } catch (e4) { + return reject(e4); + } + dbInfo.db.transaction(function(t4) { + createDbTable(t4, dbInfo, function() { + self2._dbInfo = dbInfo; + resolve(); + }, function(t5, error) { + reject(error); + }); + }, reject); + }); + dbInfo.serializer = localforageSerializer; + return dbInfoPromise; + } + function tryExecuteSql(t4, dbInfo, sqlStatement, args, callback, errorCallback) { + t4.executeSql(sqlStatement, args, callback, function(t5, error) { + if (error.code === error.SYNTAX_ERR) { + t5.executeSql("SELECT name FROM sqlite_master WHERE type='table' AND name = ?", [dbInfo.storeName], function(t6, results) { + if (!results.rows.length) { + createDbTable(t6, dbInfo, function() { + t6.executeSql(sqlStatement, args, callback, errorCallback); + }, errorCallback); + } else { + errorCallback(t6, error); + } + }, errorCallback); + } else { + errorCallback(t5, error); + } + }, errorCallback); + } + function getItem$1(key3, callback) { + var self2 = this; + key3 = normalizeKey(key3); + var promise = new Promise$1(function(resolve, reject) { + self2.ready().then(function() { + var dbInfo = self2._dbInfo; + dbInfo.db.transaction(function(t4) { + tryExecuteSql(t4, dbInfo, "SELECT * FROM " + dbInfo.storeName + " WHERE key = ? LIMIT 1", [key3], function(t5, results) { + var result = results.rows.length ? results.rows.item(0).value : null; + if (result) { + result = dbInfo.serializer.deserialize(result); + } + resolve(result); + }, function(t5, error) { + reject(error); + }); + }); + })["catch"](reject); + }); + executeCallback(promise, callback); + return promise; + } + function iterate$1(iterator, callback) { + var self2 = this; + var promise = new Promise$1(function(resolve, reject) { + self2.ready().then(function() { + var dbInfo = self2._dbInfo; + dbInfo.db.transaction(function(t4) { + tryExecuteSql(t4, dbInfo, "SELECT * FROM " + dbInfo.storeName, [], function(t5, results) { + var rows = results.rows; + var length2 = rows.length; + for (var i4 = 0; i4 < length2; i4++) { + var item = rows.item(i4); + var result = item.value; + if (result) { + result = dbInfo.serializer.deserialize(result); + } + result = iterator(result, item.key, i4 + 1); + if (result !== void 0) { + resolve(result); + return; + } + } + resolve(); + }, function(t5, error) { + reject(error); + }); + }); + })["catch"](reject); + }); + executeCallback(promise, callback); + return promise; + } + function _setItem(key3, value, callback, retriesLeft) { + var self2 = this; + key3 = normalizeKey(key3); + var promise = new Promise$1(function(resolve, reject) { + self2.ready().then(function() { + if (value === void 0) { + value = null; + } + var originalValue = value; + var dbInfo = self2._dbInfo; + dbInfo.serializer.serialize(value, function(value2, error) { + if (error) { + reject(error); + } else { + dbInfo.db.transaction(function(t4) { + tryExecuteSql(t4, dbInfo, "INSERT OR REPLACE INTO " + dbInfo.storeName + " (key, value) VALUES (?, ?)", [key3, value2], function() { + resolve(originalValue); + }, function(t5, error2) { + reject(error2); + }); + }, function(sqlError) { + if (sqlError.code === sqlError.QUOTA_ERR) { + if (retriesLeft > 0) { + resolve(_setItem.apply(self2, [key3, originalValue, callback, retriesLeft - 1])); + return; + } + reject(sqlError); + } + }); + } + }); + })["catch"](reject); + }); + executeCallback(promise, callback); + return promise; + } + function setItem$1(key3, value, callback) { + return _setItem.apply(this, [key3, value, callback, 1]); + } + function removeItem$1(key3, callback) { + var self2 = this; + key3 = normalizeKey(key3); + var promise = new Promise$1(function(resolve, reject) { + self2.ready().then(function() { + var dbInfo = self2._dbInfo; + dbInfo.db.transaction(function(t4) { + tryExecuteSql(t4, dbInfo, "DELETE FROM " + dbInfo.storeName + " WHERE key = ?", [key3], function() { + resolve(); + }, function(t5, error) { + reject(error); + }); + }); + })["catch"](reject); + }); + executeCallback(promise, callback); + return promise; + } + function clear$1(callback) { + var self2 = this; + var promise = new Promise$1(function(resolve, reject) { + self2.ready().then(function() { + var dbInfo = self2._dbInfo; + dbInfo.db.transaction(function(t4) { + tryExecuteSql(t4, dbInfo, "DELETE FROM " + dbInfo.storeName, [], function() { + resolve(); + }, function(t5, error) { + reject(error); + }); + }); + })["catch"](reject); + }); + executeCallback(promise, callback); + return promise; + } + function length$1(callback) { + var self2 = this; + var promise = new Promise$1(function(resolve, reject) { + self2.ready().then(function() { + var dbInfo = self2._dbInfo; + dbInfo.db.transaction(function(t4) { + tryExecuteSql(t4, dbInfo, "SELECT COUNT(key) as c FROM " + dbInfo.storeName, [], function(t5, results) { + var result = results.rows.item(0).c; + resolve(result); + }, function(t5, error) { + reject(error); + }); + }); + })["catch"](reject); + }); + executeCallback(promise, callback); + return promise; + } + function key$1(n2, callback) { + var self2 = this; + var promise = new Promise$1(function(resolve, reject) { + self2.ready().then(function() { + var dbInfo = self2._dbInfo; + dbInfo.db.transaction(function(t4) { + tryExecuteSql(t4, dbInfo, "SELECT key FROM " + dbInfo.storeName + " WHERE id = ? LIMIT 1", [n2 + 1], function(t5, results) { + var result = results.rows.length ? results.rows.item(0).key : null; + resolve(result); + }, function(t5, error) { + reject(error); + }); + }); + })["catch"](reject); + }); + executeCallback(promise, callback); + return promise; + } + function keys$1(callback) { + var self2 = this; + var promise = new Promise$1(function(resolve, reject) { + self2.ready().then(function() { + var dbInfo = self2._dbInfo; + dbInfo.db.transaction(function(t4) { + tryExecuteSql(t4, dbInfo, "SELECT key FROM " + dbInfo.storeName, [], function(t5, results) { + var keys2 = []; + for (var i4 = 0; i4 < results.rows.length; i4++) { + keys2.push(results.rows.item(i4).key); + } + resolve(keys2); + }, function(t5, error) { + reject(error); + }); + }); + })["catch"](reject); + }); + executeCallback(promise, callback); + return promise; + } + function getAllStoreNames(db) { + return new Promise$1(function(resolve, reject) { + db.transaction(function(t4) { + t4.executeSql("SELECT name FROM sqlite_master WHERE type='table' AND name <> '__WebKitDatabaseInfoTable__'", [], function(t5, results) { + var storeNames = []; + for (var i4 = 0; i4 < results.rows.length; i4++) { + storeNames.push(results.rows.item(i4).name); + } + resolve({ + db, + storeNames + }); + }, function(t5, error) { + reject(error); + }); + }, function(sqlError) { + reject(sqlError); + }); + }); + } + function dropInstance$1(options, callback) { + callback = getCallback.apply(this, arguments); + var currentConfig = this.config(); + options = typeof options !== "function" && options || {}; + if (!options.name) { + options.name = options.name || currentConfig.name; + options.storeName = options.storeName || currentConfig.storeName; + } + var self2 = this; + var promise; + if (!options.name) { + promise = Promise$1.reject("Invalid arguments"); + } else { + promise = new Promise$1(function(resolve) { + var db; + if (options.name === currentConfig.name) { + db = self2._dbInfo.db; + } else { + db = openDatabase(options.name, "", "", 0); + } + if (!options.storeName) { + resolve(getAllStoreNames(db)); + } else { + resolve({ + db, + storeNames: [options.storeName] + }); + } + }).then(function(operationInfo) { + return new Promise$1(function(resolve, reject) { + operationInfo.db.transaction(function(t4) { + function dropTable2(storeName) { + return new Promise$1(function(resolve2, reject2) { + t4.executeSql("DROP TABLE IF EXISTS " + storeName, [], function() { + resolve2(); + }, function(t5, error) { + reject2(error); + }); + }); + } + var operations = []; + for (var i4 = 0, len = operationInfo.storeNames.length; i4 < len; i4++) { + operations.push(dropTable2(operationInfo.storeNames[i4])); + } + Promise$1.all(operations).then(function() { + resolve(); + })["catch"](function(e4) { + reject(e4); + }); + }, function(sqlError) { + reject(sqlError); + }); + }); + }); + } + executeCallback(promise, callback); + return promise; + } + var webSQLStorage = { + _driver: "webSQLStorage", + _initStorage: _initStorage$1, + _support: isWebSQLValid(), + iterate: iterate$1, + getItem: getItem$1, + setItem: setItem$1, + removeItem: removeItem$1, + clear: clear$1, + length: length$1, + key: key$1, + keys: keys$1, + dropInstance: dropInstance$1 + }; + function isLocalStorageValid() { + try { + return typeof localStorage !== "undefined" && "setItem" in localStorage && !!localStorage.setItem; + } catch (e4) { + return false; + } + } + function _getKeyPrefix(options, defaultConfig) { + var keyPrefix = options.name + "/"; + if (options.storeName !== defaultConfig.storeName) { + keyPrefix += options.storeName + "/"; + } + return keyPrefix; + } + function checkIfLocalStorageThrows() { + var localStorageTestKey = "_localforage_support_test"; + try { + localStorage.setItem(localStorageTestKey, true); + localStorage.removeItem(localStorageTestKey); + return false; + } catch (e4) { + return true; + } + } + function _isLocalStorageUsable() { + return !checkIfLocalStorageThrows() || localStorage.length > 0; + } + function _initStorage$2(options) { + var self2 = this; + var dbInfo = {}; + if (options) { + for (var i4 in options) { + dbInfo[i4] = options[i4]; + } + } + dbInfo.keyPrefix = _getKeyPrefix(options, self2._defaultConfig); + if (!_isLocalStorageUsable()) { + return Promise$1.reject(); + } + self2._dbInfo = dbInfo; + dbInfo.serializer = localforageSerializer; + return Promise$1.resolve(); + } + function clear$2(callback) { + var self2 = this; + var promise = self2.ready().then(function() { + var keyPrefix = self2._dbInfo.keyPrefix; + for (var i4 = localStorage.length - 1; i4 >= 0; i4--) { + var key3 = localStorage.key(i4); + if (key3.indexOf(keyPrefix) === 0) { + localStorage.removeItem(key3); + } + } + }); + executeCallback(promise, callback); + return promise; + } + function getItem$2(key3, callback) { + var self2 = this; + key3 = normalizeKey(key3); + var promise = self2.ready().then(function() { + var dbInfo = self2._dbInfo; + var result = localStorage.getItem(dbInfo.keyPrefix + key3); + if (result) { + result = dbInfo.serializer.deserialize(result); + } + return result; + }); + executeCallback(promise, callback); + return promise; + } + function iterate$2(iterator, callback) { + var self2 = this; + var promise = self2.ready().then(function() { + var dbInfo = self2._dbInfo; + var keyPrefix = dbInfo.keyPrefix; + var keyPrefixLength = keyPrefix.length; + var length2 = localStorage.length; + var iterationNumber = 1; + for (var i4 = 0; i4 < length2; i4++) { + var key3 = localStorage.key(i4); + if (key3.indexOf(keyPrefix) !== 0) { + continue; + } + var value = localStorage.getItem(key3); + if (value) { + value = dbInfo.serializer.deserialize(value); + } + value = iterator(value, key3.substring(keyPrefixLength), iterationNumber++); + if (value !== void 0) { + return value; + } + } + }); + executeCallback(promise, callback); + return promise; + } + function key$2(n2, callback) { + var self2 = this; + var promise = self2.ready().then(function() { + var dbInfo = self2._dbInfo; + var result; + try { + result = localStorage.key(n2); + } catch (error) { + result = null; + } + if (result) { + result = result.substring(dbInfo.keyPrefix.length); + } + return result; + }); + executeCallback(promise, callback); + return promise; + } + function keys$2(callback) { + var self2 = this; + var promise = self2.ready().then(function() { + var dbInfo = self2._dbInfo; + var length2 = localStorage.length; + var keys2 = []; + for (var i4 = 0; i4 < length2; i4++) { + var itemKey = localStorage.key(i4); + if (itemKey.indexOf(dbInfo.keyPrefix) === 0) { + keys2.push(itemKey.substring(dbInfo.keyPrefix.length)); + } + } + return keys2; + }); + executeCallback(promise, callback); + return promise; + } + function length$2(callback) { + var self2 = this; + var promise = self2.keys().then(function(keys2) { + return keys2.length; + }); + executeCallback(promise, callback); + return promise; + } + function removeItem$2(key3, callback) { + var self2 = this; + key3 = normalizeKey(key3); + var promise = self2.ready().then(function() { + var dbInfo = self2._dbInfo; + localStorage.removeItem(dbInfo.keyPrefix + key3); + }); + executeCallback(promise, callback); + return promise; + } + function setItem$2(key3, value, callback) { + var self2 = this; + key3 = normalizeKey(key3); + var promise = self2.ready().then(function() { + if (value === void 0) { + value = null; + } + var originalValue = value; + return new Promise$1(function(resolve, reject) { + var dbInfo = self2._dbInfo; + dbInfo.serializer.serialize(value, function(value2, error) { + if (error) { + reject(error); + } else { + try { + localStorage.setItem(dbInfo.keyPrefix + key3, value2); + resolve(originalValue); + } catch (e4) { + if (e4.name === "QuotaExceededError" || e4.name === "NS_ERROR_DOM_QUOTA_REACHED") { + reject(e4); + } + reject(e4); + } + } + }); + }); + }); + executeCallback(promise, callback); + return promise; + } + function dropInstance$2(options, callback) { + callback = getCallback.apply(this, arguments); + options = typeof options !== "function" && options || {}; + if (!options.name) { + var currentConfig = this.config(); + options.name = options.name || currentConfig.name; + options.storeName = options.storeName || currentConfig.storeName; + } + var self2 = this; + var promise; + if (!options.name) { + promise = Promise$1.reject("Invalid arguments"); + } else { + promise = new Promise$1(function(resolve) { + if (!options.storeName) { + resolve(options.name + "/"); + } else { + resolve(_getKeyPrefix(options, self2._defaultConfig)); + } + }).then(function(keyPrefix) { + for (var i4 = localStorage.length - 1; i4 >= 0; i4--) { + var key3 = localStorage.key(i4); + if (key3.indexOf(keyPrefix) === 0) { + localStorage.removeItem(key3); + } + } + }); + } + executeCallback(promise, callback); + return promise; + } + var localStorageWrapper = { + _driver: "localStorageWrapper", + _initStorage: _initStorage$2, + _support: isLocalStorageValid(), + iterate: iterate$2, + getItem: getItem$2, + setItem: setItem$2, + removeItem: removeItem$2, + clear: clear$2, + length: length$2, + key: key$2, + keys: keys$2, + dropInstance: dropInstance$2 + }; + var sameValue = function sameValue2(x5, y5) { + return x5 === y5 || typeof x5 === "number" && typeof y5 === "number" && isNaN(x5) && isNaN(y5); + }; + var includes = function includes2(array, searchElement) { + var len = array.length; + var i4 = 0; + while (i4 < len) { + if (sameValue(array[i4], searchElement)) { + return true; + } + i4++; + } + return false; + }; + var isArray = Array.isArray || function(arg) { + return Object.prototype.toString.call(arg) === "[object Array]"; + }; + var DefinedDrivers = {}; + var DriverSupport = {}; + var DefaultDrivers = { + INDEXEDDB: asyncStorage, + WEBSQL: webSQLStorage, + LOCALSTORAGE: localStorageWrapper + }; + var DefaultDriverOrder = [DefaultDrivers.INDEXEDDB._driver, DefaultDrivers.WEBSQL._driver, DefaultDrivers.LOCALSTORAGE._driver]; + var OptionalDriverMethods = ["dropInstance"]; + var LibraryMethods = ["clear", "getItem", "iterate", "key", "keys", "length", "removeItem", "setItem"].concat(OptionalDriverMethods); + var DefaultConfig = { + description: "", + driver: DefaultDriverOrder.slice(), + name: "localforage", + size: 4980736, + storeName: "keyvaluepairs", + version: 1 + }; + function callWhenReady(localForageInstance, libraryMethod) { + localForageInstance[libraryMethod] = function() { + var _args = arguments; + return localForageInstance.ready().then(function() { + return localForageInstance[libraryMethod].apply(localForageInstance, _args); + }); + }; + } + function extend() { + 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])) { + arguments[0][_key] = arg[_key].slice(); + } else { + arguments[0][_key] = arg[_key]; + } + } + } + } + } + return arguments[0]; + } + var LocalForage = function() { + function LocalForage2(options) { + _classCallCheck(this, LocalForage2); + for (var driverTypeKey in DefaultDrivers) { + if (DefaultDrivers.hasOwnProperty(driverTypeKey)) { + var driver = DefaultDrivers[driverTypeKey]; + var driverName = driver._driver; + this[driverTypeKey] = driverName; + if (!DefinedDrivers[driverName]) { + this.defineDriver(driver); + } + } + } + this._defaultConfig = extend({}, DefaultConfig); + this._config = extend({}, this._defaultConfig, options); + this._driverSet = null; + this._initDriver = null; + this._ready = false; + this._dbInfo = null; + this._wrapLibraryMethodsWithReady(); + this.setDriver(this._config.driver)["catch"](function() { + }); + } + LocalForage2.prototype.config = function config(options) { + if ((typeof options === "undefined" ? "undefined" : _typeof5(options)) === "object") { + if (this._ready) { + return new Error("Can't call config() after localforage has been used."); + } + for (var i4 in options) { + if (i4 === "storeName") { + options[i4] = options[i4].replace(/\W/g, "_"); + } + if (i4 === "version" && typeof options[i4] !== "number") { + return new Error("Database version must be a number."); + } + this._config[i4] = options[i4]; + } + if ("driver" in options && options.driver) { + return this.setDriver(this._config.driver); + } + return true; + } else if (typeof options === "string") { + return this._config[options]; + } else { + return this._config; + } + }; + LocalForage2.prototype.defineDriver = function defineDriver(driverObject, callback, errorCallback) { + var promise = new Promise$1(function(resolve, reject) { + try { + var driverName = driverObject._driver; + var complianceError = new Error("Custom driver not compliant; see https://mozilla.github.io/localForage/#definedriver"); + if (!driverObject._driver) { + reject(complianceError); + return; + } + var driverMethods = LibraryMethods.concat("_initStorage"); + for (var i4 = 0, len = driverMethods.length; i4 < len; i4++) { + var driverMethodName = driverMethods[i4]; + var isRequired = !includes(OptionalDriverMethods, driverMethodName); + if ((isRequired || driverObject[driverMethodName]) && typeof driverObject[driverMethodName] !== "function") { + reject(complianceError); + return; + } + } + var configureMissingMethods = function configureMissingMethods2() { + var methodNotImplementedFactory = function methodNotImplementedFactory2(methodName) { + return function() { + var error = new Error("Method " + methodName + " is not implemented by the current driver"); + var promise2 = Promise$1.reject(error); + executeCallback(promise2, arguments[arguments.length - 1]); + return promise2; + }; + }; + for (var _i = 0, _len = OptionalDriverMethods.length; _i < _len; _i++) { + var optionalDriverMethod = OptionalDriverMethods[_i]; + if (!driverObject[optionalDriverMethod]) { + driverObject[optionalDriverMethod] = methodNotImplementedFactory(optionalDriverMethod); + } + } + }; + configureMissingMethods(); + var setDriverSupport = function setDriverSupport2(support) { + if (DefinedDrivers[driverName]) { + console.info("Redefining LocalForage driver: " + driverName); + } + DefinedDrivers[driverName] = driverObject; + DriverSupport[driverName] = support; + resolve(); + }; + if ("_support" in driverObject) { + if (driverObject._support && typeof driverObject._support === "function") { + driverObject._support().then(setDriverSupport, reject); + } else { + setDriverSupport(!!driverObject._support); + } + } else { + setDriverSupport(true); + } + } catch (e4) { + reject(e4); + } + }); + executeTwoCallbacks(promise, callback, errorCallback); + return promise; + }; + LocalForage2.prototype.driver = function driver() { + return this._driver || null; + }; + LocalForage2.prototype.getDriver = function getDriver(driverName, callback, errorCallback) { + var getDriverPromise = DefinedDrivers[driverName] ? Promise$1.resolve(DefinedDrivers[driverName]) : Promise$1.reject(new Error("Driver not found.")); + executeTwoCallbacks(getDriverPromise, callback, errorCallback); + return getDriverPromise; + }; + LocalForage2.prototype.getSerializer = function getSerializer(callback) { + var serializerPromise = Promise$1.resolve(localforageSerializer); + executeTwoCallbacks(serializerPromise, callback); + return serializerPromise; + }; + LocalForage2.prototype.ready = function ready(callback) { + var self2 = this; + var promise = self2._driverSet.then(function() { + if (self2._ready === null) { + self2._ready = self2._initDriver(); + } + return self2._ready; + }); + executeTwoCallbacks(promise, callback, callback); + return promise; + }; + LocalForage2.prototype.setDriver = function setDriver(drivers, callback, errorCallback) { + var self2 = this; + if (!isArray(drivers)) { + drivers = [drivers]; + } + var supportedDrivers = this._getSupportedDrivers(drivers); + function setDriverToConfig() { + self2._config.driver = self2.driver(); + } + function extendSelfWithDriver(driver) { + self2._extend(driver); + setDriverToConfig(); + self2._ready = self2._initStorage(self2._config); + return self2._ready; + } + function initDriver(supportedDrivers2) { + return function() { + var currentDriverIndex = 0; + function driverPromiseLoop() { + while (currentDriverIndex < supportedDrivers2.length) { + var driverName = supportedDrivers2[currentDriverIndex]; + currentDriverIndex++; + self2._dbInfo = null; + self2._ready = null; + return self2.getDriver(driverName).then(extendSelfWithDriver)["catch"](driverPromiseLoop); + } + setDriverToConfig(); + var error = new Error("No available storage method found."); + self2._driverSet = Promise$1.reject(error); + return self2._driverSet; + } + return driverPromiseLoop(); + }; + } + var oldDriverSetDone = this._driverSet !== null ? this._driverSet["catch"](function() { + return Promise$1.resolve(); + }) : Promise$1.resolve(); + this._driverSet = oldDriverSetDone.then(function() { + var driverName = supportedDrivers[0]; + self2._dbInfo = null; + self2._ready = null; + return self2.getDriver(driverName).then(function(driver) { + self2._driver = driver._driver; + setDriverToConfig(); + self2._wrapLibraryMethodsWithReady(); + self2._initDriver = initDriver(supportedDrivers); + }); + })["catch"](function() { + setDriverToConfig(); + var error = new Error("No available storage method found."); + self2._driverSet = Promise$1.reject(error); + return self2._driverSet; + }); + executeTwoCallbacks(this._driverSet, callback, errorCallback); + return this._driverSet; + }; + LocalForage2.prototype.supports = function supports(driverName) { + return !!DriverSupport[driverName]; + }; + LocalForage2.prototype._extend = function _extend(libraryMethodsAndProperties) { + extend(this, libraryMethodsAndProperties); + }; + LocalForage2.prototype._getSupportedDrivers = function _getSupportedDrivers(drivers) { + var supportedDrivers = []; + for (var i4 = 0, len = drivers.length; i4 < len; i4++) { + var driverName = drivers[i4]; + if (this.supports(driverName)) { + supportedDrivers.push(driverName); + } + } + return supportedDrivers; + }; + LocalForage2.prototype._wrapLibraryMethodsWithReady = function _wrapLibraryMethodsWithReady() { + for (var i4 = 0, len = LibraryMethods.length; i4 < len; i4++) { + callWhenReady(this, LibraryMethods[i4]); + } + }; + LocalForage2.prototype.createInstance = function createInstance(options) { + return new LocalForage2(options); + }; + return LocalForage2; + }(); + var localforage_js = new LocalForage(); + module4.exports = localforage_js; + }, { "3": 3 }] }, {}, [4])(4); + }); } }); @@ -6480,9 +8684,9 @@ var require_sql_wasm = __commonJS({ }; e4.Database = f4; }; - var va = Object.assign({}, e4), wa = "./this.program", ya = "object" == typeof window, za = "function" == typeof importScripts, Aa = "object" == typeof process && "object" == typeof process.versions && "string" == typeof process.versions.node, D3 = "", Ba, Ca, Da, fs, Ea, Fa; + var va = Object.assign({}, e4), wa = "./this.program", ya = "object" == typeof window, za = "function" == typeof importScripts, Aa = "object" == typeof process && "object" == typeof process.versions && "string" == typeof process.versions.node, D4 = "", Ba, Ca, Da, fs, Ea, Fa; if (Aa) - D3 = za ? require("path").dirname(D3) + "/" : __dirname + "/", Fa = () => { + D4 = za ? require("path").dirname(D4) + "/" : __dirname + "/", Fa = () => { Ea || (fs = require("fs"), Ea = require("path")); }, Ba = function(a5, b4) { Fa(); @@ -6502,7 +8706,7 @@ var require_sql_wasm = __commonJS({ return "[Emscripten Module object]"; }; else if (ya || za) - za ? D3 = self.location.href : "undefined" != typeof document && document.currentScript && (D3 = document.currentScript.src), D3 = 0 !== D3.indexOf("blob:") ? D3.substr(0, D3.replace(/[?#].*/, "").lastIndexOf("/") + 1) : "", Ba = (a5) => { + za ? D4 = self.location.href : "undefined" != typeof document && document.currentScript && (D4 = document.currentScript.src), D4 = 0 !== D4.indexOf("blob:") ? D4.substr(0, D4.replace(/[?#].*/, "").lastIndexOf("/") + 1) : "", Ba = (a5) => { var b4 = new XMLHttpRequest(); b4.open("GET", a5, false); b4.send(null); @@ -6530,7 +8734,7 @@ var require_sql_wasm = __commonJS({ var Ia; e4.wasmBinary && (Ia = e4.wasmBinary); var noExitRuntime = e4.noExitRuntime || true; - "object" != typeof WebAssembly && E3("no native wasm support detected"); + "object" != typeof WebAssembly && E4("no native wasm support detected"); var Ja, Ka = false, La = "undefined" != typeof TextDecoder ? new TextDecoder("utf8") : void 0; function Ma(a5, b4, c4) { var d5 = b4 + c4; @@ -6603,13 +8807,13 @@ var require_sql_wasm = __commonJS({ } return b4; } - var Na, r3, u4, Oa, F3, J2, Pa, Qa; + var Na, r3, u4, Oa, F4, J2, Pa, Qa; function Ra() { var a5 = Ja.buffer; Na = a5; e4.HEAP8 = r3 = new Int8Array(a5); e4.HEAP16 = Oa = new Int16Array(a5); - e4.HEAP32 = F3 = new Int32Array(a5); + e4.HEAP32 = F4 = new Int32Array(a5); e4.HEAPU8 = u4 = new Uint8Array(a5); e4.HEAPU16 = new Uint16Array(a5); e4.HEAPU32 = J2 = new Uint32Array(a5); @@ -6622,7 +8826,7 @@ var require_sql_wasm = __commonJS({ Sa.unshift(a5); } var Wa = 0, Xa = null, Ya = null; - function E3(a5) { + function E4(a5) { if (e4.onAbort) e4.onAbort(a5); a5 = "Aborted(" + a5 + ")"; @@ -6637,7 +8841,7 @@ var require_sql_wasm = __commonJS({ M5 = "sql-wasm.wasm"; if (!Za()) { var $a = M5; - M5 = e4.locateFile ? e4.locateFile($a, D3) : D3 + $a; + M5 = e4.locateFile ? e4.locateFile($a, D4) : D4 + $a; } function ab() { var a5 = M5; @@ -6648,7 +8852,7 @@ var require_sql_wasm = __commonJS({ return Da(a5); throw "both async and sync fetching of the wasm failed"; } catch (b4) { - E3(b4); + E4(b4); } } function bb() { @@ -6687,9 +8891,9 @@ var require_sql_wasm = __commonJS({ case "i16": return Oa[a5 >> 1]; case "i32": - return F3[a5 >> 2]; + return F4[a5 >> 2]; case "i64": - return F3[a5 >> 2]; + return F4[a5 >> 2]; case "float": return Pa[a5 >> 2]; case "double": @@ -6697,7 +8901,7 @@ var require_sql_wasm = __commonJS({ case "*": return J2[a5 >> 2]; default: - E3("invalid type for getValue: " + b4); + E4("invalid type for getValue: " + b4); } return null; } @@ -6715,12 +8919,12 @@ var require_sql_wasm = __commonJS({ Oa[a5 >> 1] = 0; break; case "i32": - F3[a5 >> 2] = 0; + F4[a5 >> 2] = 0; break; case "i64": O4 = [0, (N3 = 0, 1 <= +Math.abs(N3) ? 0 < N3 ? (Math.min(+Math.floor(N3 / 4294967296), 4294967295) | 0) >>> 0 : ~~+Math.ceil((N3 - +(~~N3 >>> 0)) / 4294967296) >>> 0 : 0)]; - F3[a5 >> 2] = O4[0]; - F3[a5 + 4 >> 2] = O4[1]; + F4[a5 >> 2] = O4[0]; + F4[a5 + 4 >> 2] = O4[1]; break; case "float": Pa[a5 >> 2] = 0; @@ -6732,7 +8936,7 @@ var require_sql_wasm = __commonJS({ J2[a5 >> 2] = 0; break; default: - E3("invalid type for setValue: " + b4); + E4("invalid type for setValue: " + b4); } } var db = (a5, b4) => { @@ -6779,7 +8983,7 @@ var require_sql_wasm = __commonJS({ return () => b4.randomBytes(1)[0]; } catch (c4) { } - return () => E3("randomDevice"); + return () => E4("randomDevice"); } function hb() { for (var a5 = "", b4 = false, c4 = arguments.length - 1; -1 <= c4 && !b4; c4--) { @@ -7452,39 +9656,39 @@ var require_sql_wasm = __commonJS({ return -54; throw f4; } - F3[c4 >> 2] = d5.dev; - F3[c4 + 8 >> 2] = d5.ino; - F3[c4 + 12 >> 2] = d5.mode; + F4[c4 >> 2] = d5.dev; + F4[c4 + 8 >> 2] = d5.ino; + F4[c4 + 12 >> 2] = d5.mode; J2[c4 + 16 >> 2] = d5.nlink; - F3[c4 + 20 >> 2] = d5.uid; - F3[c4 + 24 >> 2] = d5.gid; - F3[c4 + 28 >> 2] = d5.rdev; + F4[c4 + 20 >> 2] = d5.uid; + F4[c4 + 24 >> 2] = d5.gid; + F4[c4 + 28 >> 2] = d5.rdev; O4 = [d5.size >>> 0, (N3 = d5.size, 1 <= +Math.abs(N3) ? 0 < N3 ? (Math.min(+Math.floor(N3 / 4294967296), 4294967295) | 0) >>> 0 : ~~+Math.ceil((N3 - +(~~N3 >>> 0)) / 4294967296) >>> 0 : 0)]; - F3[c4 + 40 >> 2] = O4[0]; - F3[c4 + 44 >> 2] = O4[1]; - F3[c4 + 48 >> 2] = 4096; - F3[c4 + 52 >> 2] = d5.blocks; + F4[c4 + 40 >> 2] = O4[0]; + F4[c4 + 44 >> 2] = O4[1]; + F4[c4 + 48 >> 2] = 4096; + F4[c4 + 52 >> 2] = d5.blocks; O4 = [Math.floor(d5.atime.getTime() / 1e3) >>> 0, (N3 = Math.floor(d5.atime.getTime() / 1e3), 1 <= +Math.abs(N3) ? 0 < N3 ? (Math.min(+Math.floor(N3 / 4294967296), 4294967295) | 0) >>> 0 : ~~+Math.ceil((N3 - +(~~N3 >>> 0)) / 4294967296) >>> 0 : 0)]; - F3[c4 + 56 >> 2] = O4[0]; - F3[c4 + 60 >> 2] = O4[1]; + F4[c4 + 56 >> 2] = O4[0]; + F4[c4 + 60 >> 2] = O4[1]; J2[c4 + 64 >> 2] = 0; O4 = [Math.floor(d5.mtime.getTime() / 1e3) >>> 0, (N3 = Math.floor(d5.mtime.getTime() / 1e3), 1 <= +Math.abs(N3) ? 0 < N3 ? (Math.min(+Math.floor(N3 / 4294967296), 4294967295) | 0) >>> 0 : ~~+Math.ceil((N3 - +(~~N3 >>> 0)) / 4294967296) >>> 0 : 0)]; - F3[c4 + 72 >> 2] = O4[0]; - F3[c4 + 76 >> 2] = O4[1]; + F4[c4 + 72 >> 2] = O4[0]; + F4[c4 + 76 >> 2] = O4[1]; J2[c4 + 80 >> 2] = 0; O4 = [Math.floor(d5.ctime.getTime() / 1e3) >>> 0, (N3 = Math.floor(d5.ctime.getTime() / 1e3), 1 <= +Math.abs(N3) ? 0 < N3 ? (Math.min(+Math.floor(N3 / 4294967296), 4294967295) | 0) >>> 0 : ~~+Math.ceil((N3 - +(~~N3 >>> 0)) / 4294967296) >>> 0 : 0)]; - F3[c4 + 88 >> 2] = O4[0]; - F3[c4 + 92 >> 2] = O4[1]; + F4[c4 + 88 >> 2] = O4[0]; + F4[c4 + 92 >> 2] = O4[1]; J2[c4 + 96 >> 2] = 0; O4 = [d5.ino >>> 0, (N3 = d5.ino, 1 <= +Math.abs(N3) ? 0 < N3 ? (Math.min(+Math.floor(N3 / 4294967296), 4294967295) | 0) >>> 0 : ~~+Math.ceil((N3 - +(~~N3 >>> 0)) / 4294967296) >>> 0 : 0)]; - F3[c4 + 104 >> 2] = O4[0]; - F3[c4 + 108 >> 2] = O4[1]; + F4[c4 + 104 >> 2] = O4[0]; + F4[c4 + 108 >> 2] = O4[1]; return 0; } var fc = void 0; function Hc() { fc += 4; - return F3[fc - 4 >> 2]; + return F4[fc - 4 >> 2]; } function X3(a5) { a5 = R3[a5]; @@ -7493,7 +9697,7 @@ var require_sql_wasm = __commonJS({ return a5; } function Jc(a5) { - return J2[a5 >> 2] + 4294967296 * F3[a5 + 4 >> 2]; + return J2[a5 >> 2] + 4294967296 * F4[a5 + 4 >> 2]; } function Kc(a5) { var b4 = ca(a5) + 1, c4 = da(b4); @@ -7507,8 +9711,8 @@ var require_sql_wasm = __commonJS({ var f4 = new Date().getFullYear(), h5 = new Date(f4, 0, 1), k5 = new Date(f4, 6, 1); f4 = h5.getTimezoneOffset(); var q5 = k5.getTimezoneOffset(); - F3[a5 >> 2] = 60 * Math.max(f4, q5); - F3[b4 >> 2] = Number(f4 != q5); + F4[a5 >> 2] = 60 * Math.max(f4, q5); + F4[b4 >> 2] = Number(f4 != q5); a5 = d5(h5); b4 = d5(k5); a5 = Kc(a5); @@ -7694,7 +9898,7 @@ var require_sql_wasm = __commonJS({ } }, "/proc/self/fd"); })(); var Wc = { a: function(a5, b4, c4, d5) { - E3("Assertion failed: " + C3(a5) + ", at: " + [b4 ? C3(b4) : "unknown filename", c4, d5 ? C3(d5) : "unknown function"]); + E4("Assertion failed: " + C3(a5) + ", at: " + [b4 ? C3(b4) : "unknown filename", c4, d5 ? C3(d5) : "unknown function"]); }, h: function(a5, b4) { try { return a5 = C3(a5), ia(a5, b4), 0; @@ -7774,7 +9978,7 @@ var require_sql_wasm = __commonJS({ case 8: return -28; case 9: - return F3[Vc() >> 2] = 28, -1; + return F4[Vc() >> 2] = 28, -1; default: return -28; } @@ -7898,7 +10102,7 @@ var require_sql_wasm = __commonJS({ } }, p: function(a5, b4, c4) { try { - return b4 = C3(b4), b4 = dc(a5, b4), 0 === c4 ? ta(b4) : 512 === c4 ? Tb(b4) : E3("Invalid flags passed to unlinkat"), 0; + return b4 = C3(b4), b4 = dc(a5, b4), 0 === c4 ? ta(b4) : 512 === c4 ? Tb(b4) : E4("Invalid flags passed to unlinkat"), 0; } catch (d5) { if ("undefined" == typeof W2 || !(d5 instanceof P4)) throw d5; @@ -7909,11 +10113,11 @@ var require_sql_wasm = __commonJS({ b4 = C3(b4); b4 = dc(a5, b4, true); if (c4) { - var d5 = Jc(c4), f4 = F3[c4 + 8 >> 2]; + var d5 = Jc(c4), f4 = F4[c4 + 8 >> 2]; h5 = 1e3 * d5 + f4 / 1e6; c4 += 16; d5 = Jc(c4); - f4 = F3[c4 + 8 >> 2]; + f4 = F4[c4 + 8 >> 2]; k5 = 1e3 * d5 + f4 / 1e6; } else var h5 = Date.now(), k5 = h5; @@ -7930,19 +10134,19 @@ var require_sql_wasm = __commonJS({ return Date.now(); }, j: function(a5, b4) { a5 = new Date(1e3 * Jc(a5)); - F3[b4 >> 2] = a5.getSeconds(); - F3[b4 + 4 >> 2] = a5.getMinutes(); - F3[b4 + 8 >> 2] = a5.getHours(); - F3[b4 + 12 >> 2] = a5.getDate(); - F3[b4 + 16 >> 2] = a5.getMonth(); - F3[b4 + 20 >> 2] = a5.getFullYear() - 1900; - F3[b4 + 24 >> 2] = a5.getDay(); + F4[b4 >> 2] = a5.getSeconds(); + F4[b4 + 4 >> 2] = a5.getMinutes(); + F4[b4 + 8 >> 2] = a5.getHours(); + F4[b4 + 12 >> 2] = a5.getDate(); + F4[b4 + 16 >> 2] = a5.getMonth(); + F4[b4 + 20 >> 2] = a5.getFullYear() - 1900; + F4[b4 + 24 >> 2] = a5.getDay(); var c4 = new Date(a5.getFullYear(), 0, 1); - F3[b4 + 28 >> 2] = (a5.getTime() - c4.getTime()) / 864e5 | 0; - F3[b4 + 36 >> 2] = -(60 * a5.getTimezoneOffset()); + F4[b4 + 28 >> 2] = (a5.getTime() - c4.getTime()) / 864e5 | 0; + F4[b4 + 36 >> 2] = -(60 * a5.getTimezoneOffset()); var d5 = new Date(a5.getFullYear(), 6, 1).getTimezoneOffset(); c4 = c4.getTimezoneOffset(); - F3[b4 + 32 >> 2] = (d5 != c4 && a5.getTimezoneOffset() == Math.min(c4, d5)) | 0; + F4[b4 + 32 >> 2] = (d5 != c4 && a5.getTimezoneOffset() == Math.min(c4, d5)) | 0; }, w: function(a5, b4, c4, d5, f4, h5) { try { var k5 = X3(d5); @@ -7954,7 +10158,7 @@ var require_sql_wasm = __commonJS({ throw new P4(43); var q5 = k5.Ha.bb(k5, a5, f4, b4, c4); var x5 = q5.Fb; - F3[h5 >> 2] = q5.vb; + F4[h5 >> 2] = q5.vb; return x5; } catch (w5) { if ("undefined" == typeof W2 || !(w5 instanceof P4)) @@ -8077,8 +10281,8 @@ var require_sql_wasm = __commonJS({ var h5 = X3(a5); Yb(h5, b4, d5); O4 = [h5.position >>> 0, (N3 = h5.position, 1 <= +Math.abs(N3) ? 0 < N3 ? (Math.min(+Math.floor(N3 / 4294967296), 4294967295) | 0) >>> 0 : ~~+Math.ceil((N3 - +(~~N3 >>> 0)) / 4294967296) >>> 0 : 0)]; - F3[f4 >> 2] = O4[0]; - F3[f4 + 4 >> 2] = O4[1]; + F4[f4 >> 2] = O4[0]; + F4[f4 + 4 >> 2] = O4[1]; h5.hb && 0 === b4 && 0 === d5 && (h5.hb = null); return 0; } catch (k5) { @@ -8141,7 +10345,7 @@ var require_sql_wasm = __commonJS({ return h5; }).then(f4, function(h5) { Ha("failed to asynchronously prepare wasm: " + h5); - E3(h5); + E4(h5); }); } var d5 = { a: Wc }; @@ -8964,51 +11168,53 @@ var l; var u; var i; var t; -var o; var r; -var f = {}; -var e = []; -var c = /acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i; -function s(n2, l3) { +var o; +var f; +var e; +var c = {}; +var s = []; +var a = /acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i; +function h(n2, l3) { for (var u4 in l3) n2[u4] = l3[u4]; return n2; } -function a(n2) { +function v(n2) { var l3 = n2.parentNode; l3 && l3.removeChild(n2); } -function h(l3, u4, i4) { - var t4, o3, r3, f4 = {}; - for (r3 in u4) - "key" == r3 ? t4 = u4[r3] : "ref" == r3 ? o3 = u4[r3] : f4[r3] = u4[r3]; +function y(l3, u4, i4) { + var t4, r3, o3, f4 = {}; + for (o3 in u4) + "key" == o3 ? t4 = u4[o3] : "ref" == o3 ? r3 = u4[o3] : f4[o3] = u4[o3]; if (arguments.length > 2 && (f4.children = arguments.length > 3 ? n.call(arguments, 2) : i4), "function" == typeof l3 && null != l3.defaultProps) - for (r3 in l3.defaultProps) - void 0 === f4[r3] && (f4[r3] = l3.defaultProps[r3]); - return v(l3, f4, t4, o3, null); + for (o3 in l3.defaultProps) + void 0 === f4[o3] && (f4[o3] = l3.defaultProps[o3]); + return p(l3, f4, t4, r3, null); } -function v(n2, i4, t4, o3, r3) { - var f4 = { type: n2, props: i4, key: t4, ref: o3, __k: null, __: null, __b: 0, __e: null, __d: void 0, __c: null, __h: null, constructor: void 0, __v: null == r3 ? ++u : r3 }; - return null == r3 && null != l.vnode && l.vnode(f4), f4; +function p(n2, i4, t4, r3, o3) { + var f4 = { type: n2, props: i4, key: t4, ref: r3, __k: null, __: null, __b: 0, __e: null, __d: void 0, __c: null, __h: null, constructor: void 0, __v: null == o3 ? ++u : o3 }; + return null == o3 && null != l.vnode && l.vnode(f4), f4; } -function y() { +function d() { return { current: null }; } -function p(n2) { +function _(n2) { return n2.children; } -function d(n2, l3) { +function k(n2, l3) { this.props = n2, this.context = l3; } -function _(n2, l3) { +function b(n2, l3) { if (null == l3) - return n2.__ ? _(n2.__, n2.__.__k.indexOf(n2) + 1) : null; + return n2.__ ? b(n2.__, n2.__.__k.indexOf(n2) + 1) : null; for (var u4; l3 < n2.__k.length; l3++) if (null != (u4 = n2.__k[l3]) && null != u4.__e) return u4.__e; - return "function" == typeof n2.type ? _(n2) : null; + return "function" == typeof n2.type ? b(n2) : null; } -function k(n2) { +function g(n2) { var l3, u4; if (null != (n2 = n2.__) && null != n2.__c) { for (n2.__e = n2.__c.base = null, l3 = 0; l3 < n2.__k.length; l3++) @@ -9016,81 +11222,89 @@ function k(n2) { n2.__e = n2.__c.base = u4.__e; break; } - return k(n2); + return g(n2); } } -function b(n2) { - (!n2.__d && (n2.__d = true) && t.push(n2) && !g.__r++ || o !== l.debounceRendering) && ((o = l.debounceRendering) || setTimeout)(g); +function m(n2) { + (!n2.__d && (n2.__d = true) && t.push(n2) && !w.__r++ || r !== l.debounceRendering) && ((r = l.debounceRendering) || o)(w); } -function g() { - for (var n2; g.__r = t.length; ) - n2 = t.sort(function(n3, l3) { - return n3.__v.__b - l3.__v.__b; - }), t = [], n2.some(function(n3) { - var l3, u4, i4, t4, o3, r3; - n3.__d && (o3 = (t4 = (l3 = n3).__v).__e, (r3 = l3.__P) && (u4 = [], (i4 = s({}, t4)).__v = t4.__v + 1, j(r3, t4, i4, l3.__n, void 0 !== r3.ownerSVGElement, null != t4.__h ? [o3] : null, u4, null == o3 ? _(t4) : o3, t4.__h), z(u4, t4), t4.__e != o3 && k(t4))); - }); +function w() { + var n2, l3, u4, i4, r3, o3, e4, c4; + for (t.sort(f); n2 = t.shift(); ) + n2.__d && (l3 = t.length, i4 = void 0, r3 = void 0, e4 = (o3 = (u4 = n2).__v).__e, (c4 = u4.__P) && (i4 = [], (r3 = h({}, o3)).__v = o3.__v + 1, L(c4, o3, r3, u4.__n, void 0 !== c4.ownerSVGElement, null != o3.__h ? [e4] : null, i4, null == e4 ? b(o3) : e4, o3.__h), M(i4, o3), o3.__e != e4 && g(o3)), t.length > l3 && t.sort(f)); + w.__r = 0; } -function w(n2, l3, u4, i4, t4, o3, r3, c4, s5, a5) { - var h5, y5, d5, k5, b4, g4, w5, x5 = i4 && i4.__k || e, C3 = x5.length; +function x(n2, l3, u4, i4, t4, r3, o3, f4, e4, a5) { + var h5, v3, y5, d5, k5, g4, m5, w5 = i4 && i4.__k || s, x5 = w5.length; for (u4.__k = [], h5 = 0; h5 < l3.length; h5++) - if (null != (k5 = u4.__k[h5] = null == (k5 = l3[h5]) || "boolean" == typeof k5 ? null : "string" == typeof k5 || "number" == typeof k5 || "bigint" == typeof k5 ? v(null, k5, null, null, k5) : Array.isArray(k5) ? v(p, { children: k5 }, null, null, null) : k5.__b > 0 ? v(k5.type, k5.props, k5.key, k5.ref ? k5.ref : null, k5.__v) : k5)) { - if (k5.__ = u4, k5.__b = u4.__b + 1, null === (d5 = x5[h5]) || d5 && k5.key == d5.key && k5.type === d5.type) - x5[h5] = void 0; + if (null != (d5 = u4.__k[h5] = null == (d5 = l3[h5]) || "boolean" == typeof d5 || "function" == typeof d5 ? null : "string" == typeof d5 || "number" == typeof d5 || "bigint" == typeof d5 ? p(null, d5, null, null, d5) : Array.isArray(d5) ? p(_, { children: d5 }, null, null, null) : d5.__b > 0 ? p(d5.type, d5.props, d5.key, d5.ref ? d5.ref : null, d5.__v) : d5)) { + if (d5.__ = u4, d5.__b = u4.__b + 1, null === (y5 = w5[h5]) || y5 && d5.key == y5.key && d5.type === y5.type) + w5[h5] = void 0; else - for (y5 = 0; y5 < C3; y5++) { - if ((d5 = x5[y5]) && k5.key == d5.key && k5.type === d5.type) { - x5[y5] = void 0; + for (v3 = 0; v3 < x5; v3++) { + if ((y5 = w5[v3]) && d5.key == y5.key && d5.type === y5.type) { + w5[v3] = void 0; break; } - d5 = null; + y5 = null; } - j(n2, k5, d5 = d5 || f, t4, o3, r3, c4, s5, a5), b4 = k5.__e, (y5 = k5.ref) && d5.ref != y5 && (w5 || (w5 = []), d5.ref && w5.push(d5.ref, null, k5), w5.push(y5, k5.__c || b4, k5)), null != b4 ? (null == g4 && (g4 = b4), "function" == typeof k5.type && k5.__k === d5.__k ? k5.__d = s5 = m(k5, s5, n2) : s5 = A(n2, k5, d5, x5, b4, s5), "function" == typeof u4.type && (u4.__d = s5)) : s5 && d5.__e == s5 && s5.parentNode != n2 && (s5 = _(d5)); + L(n2, d5, y5 = y5 || c, t4, r3, o3, f4, e4, a5), k5 = d5.__e, (v3 = d5.ref) && y5.ref != v3 && (m5 || (m5 = []), y5.ref && m5.push(y5.ref, null, d5), m5.push(v3, d5.__c || k5, d5)), null != k5 ? (null == g4 && (g4 = k5), "function" == typeof d5.type && d5.__k === y5.__k ? d5.__d = e4 = A(d5, e4, n2) : e4 = C(n2, d5, y5, w5, k5, e4), "function" == typeof u4.type && (u4.__d = e4)) : e4 && y5.__e == e4 && e4.parentNode != n2 && (e4 = b(y5)); } - for (u4.__e = g4, h5 = C3; h5--; ) - null != x5[h5] && N(x5[h5], x5[h5]); - if (w5) - for (h5 = 0; h5 < w5.length; h5++) - M(w5[h5], w5[++h5], w5[++h5]); + for (u4.__e = g4, h5 = x5; h5--; ) + null != w5[h5] && ("function" == typeof u4.type && null != w5[h5].__e && w5[h5].__e == u4.__d && (u4.__d = $(i4).nextSibling), S(w5[h5], w5[h5])); + if (m5) + for (h5 = 0; h5 < m5.length; h5++) + O(m5[h5], m5[++h5], m5[++h5]); } -function m(n2, l3, u4) { - for (var i4, t4 = n2.__k, o3 = 0; t4 && o3 < t4.length; o3++) - (i4 = t4[o3]) && (i4.__ = n2, l3 = "function" == typeof i4.type ? m(i4, l3, u4) : A(u4, i4, i4, t4, i4.__e, l3)); +function A(n2, l3, u4) { + for (var i4, t4 = n2.__k, r3 = 0; t4 && r3 < t4.length; r3++) + (i4 = t4[r3]) && (i4.__ = n2, l3 = "function" == typeof i4.type ? A(i4, l3, u4) : C(u4, i4, i4, t4, i4.__e, l3)); return l3; } -function x(n2, l3) { +function P(n2, l3) { return l3 = l3 || [], null == n2 || "boolean" == typeof n2 || (Array.isArray(n2) ? n2.some(function(n3) { - x(n3, l3); + P(n3, l3); }) : l3.push(n2)), l3; } -function A(n2, l3, u4, i4, t4, o3) { - var r3, f4, e4; +function C(n2, l3, u4, i4, t4, r3) { + var o3, f4, e4; if (void 0 !== l3.__d) - r3 = l3.__d, l3.__d = void 0; - else if (null == u4 || t4 != o3 || null == t4.parentNode) + o3 = l3.__d, l3.__d = void 0; + else if (null == u4 || t4 != r3 || null == t4.parentNode) n: - if (null == o3 || o3.parentNode !== n2) - n2.appendChild(t4), r3 = null; + if (null == r3 || r3.parentNode !== n2) + n2.appendChild(t4), o3 = null; else { - for (f4 = o3, e4 = 0; (f4 = f4.nextSibling) && e4 < i4.length; e4 += 1) + for (f4 = r3, e4 = 0; (f4 = f4.nextSibling) && e4 < i4.length; e4 += 1) if (f4 == t4) break n; - n2.insertBefore(t4, o3), r3 = o3; + n2.insertBefore(t4, r3), o3 = r3; } - return void 0 !== r3 ? r3 : t4.nextSibling; -} -function C(n2, l3, u4, i4, t4) { - var o3; - for (o3 in u4) - "children" === o3 || "key" === o3 || o3 in l3 || H(n2, o3, null, u4[o3], i4); - for (o3 in l3) - t4 && "function" != typeof l3[o3] || "children" === o3 || "key" === o3 || "value" === o3 || "checked" === o3 || u4[o3] === l3[o3] || H(n2, o3, l3[o3], u4[o3], i4); + return void 0 !== o3 ? o3 : t4.nextSibling; } -function $(n2, l3, u4) { - "-" === l3[0] ? n2.setProperty(l3, u4) : n2[l3] = null == u4 ? "" : "number" != typeof u4 || c.test(l3) ? u4 : u4 + "px"; +function $(n2) { + var l3, u4, i4; + if (null == n2.type || "string" == typeof n2.type) + return n2.__e; + if (n2.__k) { + for (l3 = n2.__k.length - 1; l3 >= 0; l3--) + if ((u4 = n2.__k[l3]) && (i4 = $(u4))) + return i4; + } + return null; } function H(n2, l3, u4, i4, t4) { - var o3; + var r3; + for (r3 in u4) + "children" === r3 || "key" === r3 || r3 in l3 || T(n2, r3, null, u4[r3], i4); + for (r3 in l3) + t4 && "function" != typeof l3[r3] || "children" === r3 || "key" === r3 || "value" === r3 || "checked" === r3 || u4[r3] === l3[r3] || T(n2, r3, l3[r3], u4[r3], i4); +} +function I(n2, l3, u4) { + "-" === l3[0] ? n2.setProperty(l3, null == u4 ? "" : u4) : n2[l3] = null == u4 ? "" : "number" != typeof u4 || a.test(l3) ? u4 : u4 + "px"; +} +function T(n2, l3, u4, i4, t4) { + var r3; n: if ("style" === l3) if ("string" == typeof u4) @@ -9098,17 +11312,17 @@ function H(n2, l3, u4, i4, t4) { else { if ("string" == typeof i4 && (n2.style.cssText = i4 = ""), i4) for (l3 in i4) - u4 && l3 in u4 || $(n2.style, l3, ""); + u4 && l3 in u4 || I(n2.style, l3, ""); if (u4) for (l3 in u4) - i4 && u4[l3] === i4[l3] || $(n2.style, l3, u4[l3]); + i4 && u4[l3] === i4[l3] || I(n2.style, l3, u4[l3]); } else if ("o" === l3[0] && "n" === l3[1]) - o3 = l3 !== (l3 = l3.replace(/Capture$/, "")), l3 = l3.toLowerCase() in n2 ? l3.toLowerCase().slice(2) : l3.slice(2), n2.l || (n2.l = {}), n2.l[l3 + o3] = u4, u4 ? i4 || n2.addEventListener(l3, o3 ? T : I, o3) : n2.removeEventListener(l3, o3 ? T : I, o3); + r3 = l3 !== (l3 = l3.replace(/Capture$/, "")), l3 = l3.toLowerCase() in n2 ? l3.toLowerCase().slice(2) : l3.slice(2), n2.l || (n2.l = {}), n2.l[l3 + r3] = u4, u4 ? i4 || n2.addEventListener(l3, r3 ? z : j, r3) : n2.removeEventListener(l3, r3 ? z : j, r3); else if ("dangerouslySetInnerHTML" !== l3) { if (t4) l3 = l3.replace(/xlink(H|:h)/, "h").replace(/sName$/, "s"); - else if ("href" !== l3 && "list" !== l3 && "form" !== l3 && "tabIndex" !== l3 && "download" !== l3 && l3 in n2) + else if ("width" !== l3 && "height" !== l3 && "href" !== l3 && "list" !== l3 && "form" !== l3 && "tabIndex" !== l3 && "download" !== l3 && l3 in n2) try { n2[l3] = null == u4 ? "" : u4; break n; @@ -9117,52 +11331,52 @@ function H(n2, l3, u4, i4, t4) { "function" == typeof u4 || (null == u4 || false === u4 && -1 == l3.indexOf("-") ? n2.removeAttribute(l3) : n2.setAttribute(l3, u4)); } } -function I(n2) { - this.l[n2.type + false](l.event ? l.event(n2) : n2); +function j(n2) { + return this.l[n2.type + false](l.event ? l.event(n2) : n2); } -function T(n2) { - this.l[n2.type + true](l.event ? l.event(n2) : n2); +function z(n2) { + return this.l[n2.type + true](l.event ? l.event(n2) : n2); } -function j(n2, u4, i4, t4, o3, r3, f4, e4, c4) { - var a5, h5, v3, y5, _7, k5, b4, g4, m5, x5, A4, C3, $3, H5, I4, T6 = u4.type; +function L(n2, u4, i4, t4, r3, o3, f4, e4, c4) { + var s5, a5, v3, y5, p3, d5, b4, g4, m5, w5, A4, P4, C3, $3, H5, I4 = u4.type; if (void 0 !== u4.constructor) return null; - null != i4.__h && (c4 = i4.__h, e4 = u4.__e = i4.__e, u4.__h = null, r3 = [e4]), (a5 = l.__b) && a5(u4); + null != i4.__h && (c4 = i4.__h, e4 = u4.__e = i4.__e, u4.__h = null, o3 = [e4]), (s5 = l.__b) && s5(u4); try { n: - if ("function" == typeof T6) { - if (g4 = u4.props, m5 = (a5 = T6.contextType) && t4[a5.__c], x5 = a5 ? m5 ? m5.props.value : a5.__ : t4, i4.__c ? b4 = (h5 = u4.__c = i4.__c).__ = h5.__E : ("prototype" in T6 && T6.prototype.render ? u4.__c = h5 = new T6(g4, x5) : (u4.__c = h5 = new d(g4, x5), h5.constructor = T6, h5.render = O), m5 && m5.sub(h5), h5.props = g4, h5.state || (h5.state = {}), h5.context = x5, h5.__n = t4, v3 = h5.__d = true, h5.__h = [], h5._sb = []), null == h5.__s && (h5.__s = h5.state), null != T6.getDerivedStateFromProps && (h5.__s == h5.state && (h5.__s = s({}, h5.__s)), s(h5.__s, T6.getDerivedStateFromProps(g4, h5.__s))), y5 = h5.props, _7 = h5.state, v3) - null == T6.getDerivedStateFromProps && null != h5.componentWillMount && h5.componentWillMount(), null != h5.componentDidMount && h5.__h.push(h5.componentDidMount); + if ("function" == typeof I4) { + if (g4 = u4.props, m5 = (s5 = I4.contextType) && t4[s5.__c], w5 = s5 ? m5 ? m5.props.value : s5.__ : t4, i4.__c ? b4 = (a5 = u4.__c = i4.__c).__ = a5.__E : ("prototype" in I4 && I4.prototype.render ? u4.__c = a5 = new I4(g4, w5) : (u4.__c = a5 = new k(g4, w5), a5.constructor = I4, a5.render = q), m5 && m5.sub(a5), a5.props = g4, a5.state || (a5.state = {}), a5.context = w5, a5.__n = t4, v3 = a5.__d = true, a5.__h = [], a5._sb = []), null == a5.__s && (a5.__s = a5.state), null != I4.getDerivedStateFromProps && (a5.__s == a5.state && (a5.__s = h({}, a5.__s)), h(a5.__s, I4.getDerivedStateFromProps(g4, a5.__s))), y5 = a5.props, p3 = a5.state, a5.__v = u4, v3) + null == I4.getDerivedStateFromProps && null != a5.componentWillMount && a5.componentWillMount(), null != a5.componentDidMount && a5.__h.push(a5.componentDidMount); else { - if (null == T6.getDerivedStateFromProps && g4 !== y5 && null != h5.componentWillReceiveProps && h5.componentWillReceiveProps(g4, x5), !h5.__e && null != h5.shouldComponentUpdate && false === h5.shouldComponentUpdate(g4, h5.__s, x5) || u4.__v === i4.__v) { - for (h5.props = g4, h5.state = h5.__s, u4.__v !== i4.__v && (h5.__d = false), h5.__v = u4, u4.__e = i4.__e, u4.__k = i4.__k, u4.__k.forEach(function(n3) { + if (null == I4.getDerivedStateFromProps && g4 !== y5 && null != a5.componentWillReceiveProps && a5.componentWillReceiveProps(g4, w5), !a5.__e && null != a5.shouldComponentUpdate && false === a5.shouldComponentUpdate(g4, a5.__s, w5) || u4.__v === i4.__v) { + for (u4.__v !== i4.__v && (a5.props = g4, a5.state = a5.__s, a5.__d = false), a5.__e = false, u4.__e = i4.__e, u4.__k = i4.__k, u4.__k.forEach(function(n3) { n3 && (n3.__ = u4); - }), A4 = 0; A4 < h5._sb.length; A4++) - h5.__h.push(h5._sb[A4]); - h5._sb = [], h5.__h.length && f4.push(h5); + }), A4 = 0; A4 < a5._sb.length; A4++) + a5.__h.push(a5._sb[A4]); + a5._sb = [], a5.__h.length && f4.push(a5); break n; } - null != h5.componentWillUpdate && h5.componentWillUpdate(g4, h5.__s, x5), null != h5.componentDidUpdate && h5.__h.push(function() { - h5.componentDidUpdate(y5, _7, k5); + null != a5.componentWillUpdate && a5.componentWillUpdate(g4, a5.__s, w5), null != a5.componentDidUpdate && a5.__h.push(function() { + a5.componentDidUpdate(y5, p3, d5); }); } - if (h5.context = x5, h5.props = g4, h5.__v = u4, h5.__P = n2, C3 = l.__r, $3 = 0, "prototype" in T6 && T6.prototype.render) { - for (h5.state = h5.__s, h5.__d = false, C3 && C3(u4), a5 = h5.render(h5.props, h5.state, h5.context), H5 = 0; H5 < h5._sb.length; H5++) - h5.__h.push(h5._sb[H5]); - h5._sb = []; + if (a5.context = w5, a5.props = g4, a5.__P = n2, P4 = l.__r, C3 = 0, "prototype" in I4 && I4.prototype.render) { + for (a5.state = a5.__s, a5.__d = false, P4 && P4(u4), s5 = a5.render(a5.props, a5.state, a5.context), $3 = 0; $3 < a5._sb.length; $3++) + a5.__h.push(a5._sb[$3]); + a5._sb = []; } else do { - h5.__d = false, C3 && C3(u4), a5 = h5.render(h5.props, h5.state, h5.context), h5.state = h5.__s; - } while (h5.__d && ++$3 < 25); - h5.state = h5.__s, null != h5.getChildContext && (t4 = s(s({}, t4), h5.getChildContext())), v3 || null == h5.getSnapshotBeforeUpdate || (k5 = h5.getSnapshotBeforeUpdate(y5, _7)), I4 = null != a5 && a5.type === p && null == a5.key ? a5.props.children : a5, w(n2, Array.isArray(I4) ? I4 : [I4], u4, i4, t4, o3, r3, f4, e4, c4), h5.base = u4.__e, u4.__h = null, h5.__h.length && f4.push(h5), b4 && (h5.__E = h5.__ = null), h5.__e = false; + a5.__d = false, P4 && P4(u4), s5 = a5.render(a5.props, a5.state, a5.context), a5.state = a5.__s; + } while (a5.__d && ++C3 < 25); + a5.state = a5.__s, null != a5.getChildContext && (t4 = h(h({}, t4), a5.getChildContext())), v3 || null == a5.getSnapshotBeforeUpdate || (d5 = a5.getSnapshotBeforeUpdate(y5, p3)), H5 = null != s5 && s5.type === _ && null == s5.key ? s5.props.children : s5, x(n2, Array.isArray(H5) ? H5 : [H5], u4, i4, t4, r3, o3, f4, e4, c4), a5.base = u4.__e, u4.__h = null, a5.__h.length && f4.push(a5), b4 && (a5.__E = a5.__ = null), a5.__e = false; } else - null == r3 && u4.__v === i4.__v ? (u4.__k = i4.__k, u4.__e = i4.__e) : u4.__e = L(i4.__e, u4, i4, t4, o3, r3, f4, c4); - (a5 = l.diffed) && a5(u4); + null == o3 && u4.__v === i4.__v ? (u4.__k = i4.__k, u4.__e = i4.__e) : u4.__e = N(i4.__e, u4, i4, t4, r3, o3, f4, c4); + (s5 = l.diffed) && s5(u4); } catch (n3) { - u4.__v = null, (c4 || null != r3) && (u4.__e = e4, u4.__h = !!c4, r3[r3.indexOf(e4)] = null), l.__e(n3, u4, i4); + u4.__v = null, (c4 || null != o3) && (u4.__e = e4, u4.__h = !!c4, o3[o3.indexOf(e4)] = null), l.__e(n3, u4, i4); } } -function z(n2, u4) { +function M(n2, u4) { l.__c && l.__c(u4, n2), n2.some(function(u5) { try { n2 = u5.__h, u5.__h = [], n2.some(function(n3) { @@ -9173,48 +11387,48 @@ function z(n2, u4) { } }); } -function L(l3, u4, i4, t4, o3, r3, e4, c4) { - var s5, h5, v3, y5 = i4.props, p3 = u4.props, d5 = u4.type, k5 = 0; - if ("svg" === d5 && (o3 = true), null != r3) { - for (; k5 < r3.length; k5++) - if ((s5 = r3[k5]) && "setAttribute" in s5 == !!d5 && (d5 ? s5.localName === d5 : 3 === s5.nodeType)) { - l3 = s5, r3[k5] = null; +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; + 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; break; } } if (null == l3) { if (null === d5) return document.createTextNode(p3); - l3 = o3 ? document.createElementNS("http://www.w3.org/2000/svg", d5) : document.createElement(d5, p3.is && p3), r3 = null, c4 = false; + l3 = r3 ? document.createElementNS("http://www.w3.org/2000/svg", d5) : document.createElement(d5, p3.is && p3), o3 = null, e4 = false; } if (null === d5) - y5 === p3 || c4 && l3.data === p3 || (l3.data = p3); + y5 === p3 || e4 && l3.data === p3 || (l3.data = p3); else { - if (r3 = r3 && n.call(l3.childNodes), h5 = (y5 = i4.props || f).dangerouslySetInnerHTML, v3 = p3.dangerouslySetInnerHTML, !c4) { - if (null != r3) - for (y5 = {}, k5 = 0; k5 < l3.attributes.length; k5++) - y5[l3.attributes[k5].name] = l3.attributes[k5].value; - (v3 || h5) && (v3 && (h5 && v3.__html == h5.__html || v3.__html === l3.innerHTML) || (l3.innerHTML = v3 && v3.__html || "")); + 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; + (h5 || a5) && (h5 && (a5 && h5.__html == a5.__html || h5.__html === l3.innerHTML) || (l3.innerHTML = h5 && h5.__html || "")); } - if (C(l3, p3, y5, o3, c4), v3) + if (H(l3, p3, y5, r3, e4), h5) u4.__k = []; - else if (k5 = u4.props.children, w(l3, Array.isArray(k5) ? k5 : [k5], u4, i4, t4, o3 && "foreignObject" !== d5, r3, e4, r3 ? r3[0] : i4.__k && _(i4, 0), c4), null != r3) - for (k5 = r3.length; k5--; ) - null != r3[k5] && a(r3[k5]); - c4 || ("value" in p3 && void 0 !== (k5 = p3.value) && (k5 !== l3.value || "progress" === d5 && !k5 || "option" === d5 && k5 !== y5.value) && H(l3, "value", k5, y5.value, false), "checked" in p3 && void 0 !== (k5 = p3.checked) && k5 !== l3.checked && H(l3, "checked", k5, y5.checked, false)); + 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)); } return l3; } -function M(n2, u4, i4) { +function O(n2, u4, i4) { try { "function" == typeof n2 ? n2(u4) : n2.current = u4; } catch (n3) { l.__e(n3, i4); } } -function N(n2, u4, i4) { - var t4, o3; - if (l.unmount && l.unmount(n2), (t4 = n2.ref) && (t4.current && t4.current !== n2.__e || M(t4, null, u4)), null != (t4 = n2.__c)) { +function S(n2, u4, i4) { + var t4, r3; + if (l.unmount && l.unmount(n2), (t4 = n2.ref) && (t4.current && t4.current !== n2.__e || O(t4, null, u4)), null != (t4 = n2.__c)) { if (t4.componentWillUnmount) try { t4.componentWillUnmount(); @@ -9224,35 +11438,37 @@ function N(n2, u4, i4) { t4.base = t4.__P = null, n2.__c = void 0; } if (t4 = n2.__k) - for (o3 = 0; o3 < t4.length; o3++) - t4[o3] && N(t4[o3], u4, i4 || "function" != typeof n2.type); - i4 || null == n2.__e || a(n2.__e), n2.__ = n2.__e = n2.__d = void 0; + for (r3 = 0; r3 < t4.length; r3++) + t4[r3] && S(t4[r3], u4, i4 || "function" != typeof n2.type); + i4 || null == n2.__e || v(n2.__e), n2.__ = n2.__e = n2.__d = void 0; } -function O(n2, l3, u4) { +function q(n2, l3, u4) { return this.constructor(n2, u4); } -function P(u4, i4, t4) { - var o3, r3, e4; - l.__ && l.__(u4, i4), r3 = (o3 = "function" == typeof t4) ? null : t4 && t4.__k || i4.__k, e4 = [], j(i4, u4 = (!o3 && t4 || i4).__k = h(p, null, [u4]), r3 || f, f, void 0 !== i4.ownerSVGElement, !o3 && t4 ? [t4] : r3 ? null : i4.firstChild ? n.call(i4.childNodes) : null, e4, !o3 && t4 ? t4 : r3 ? r3.__e : i4.firstChild, o3), z(e4, u4); +function B(u4, i4, t4) { + var r3, o3, f4; + l.__ && l.__(u4, i4), o3 = (r3 = "function" == typeof t4) ? null : t4 && t4.__k || i4.__k, f4 = [], L(i4, u4 = (!r3 && t4 || i4).__k = y(_, null, [u4]), o3 || c, c, void 0 !== i4.ownerSVGElement, !r3 && t4 ? [t4] : o3 ? null : i4.firstChild ? n.call(i4.childNodes) : null, f4, !r3 && t4 ? t4 : o3 ? o3.__e : i4.firstChild, r3), M(f4, u4); } -function S(n2, l3) { - P(n2, l3, S); +function D(n2, l3) { + B(n2, l3, D); } -function q(l3, u4, i4) { - var t4, o3, r3, f4 = s({}, l3.props); - for (r3 in u4) - "key" == r3 ? t4 = u4[r3] : "ref" == r3 ? o3 = u4[r3] : f4[r3] = u4[r3]; - return arguments.length > 2 && (f4.children = arguments.length > 3 ? n.call(arguments, 2) : i4), v(l3.type, f4, t4 || l3.key, o3 || l3.ref, null); +function E(l3, u4, i4) { + var t4, r3, o3, f4 = h({}, l3.props); + for (o3 in u4) + "key" == o3 ? t4 = u4[o3] : "ref" == o3 ? r3 = u4[o3] : f4[o3] = u4[o3]; + return arguments.length > 2 && (f4.children = arguments.length > 3 ? n.call(arguments, 2) : i4), p(l3.type, f4, t4 || l3.key, r3 || l3.ref, null); } -function B(n2, l3) { - var u4 = { __c: l3 = "__cC" + r++, __: n2, Consumer: function(n3, l4) { +function F(n2, l3) { + var u4 = { __c: l3 = "__cC" + e++, __: n2, Consumer: function(n3, l4) { return n3.children(l4); }, Provider: function(n3) { var u5, i4; return this.getChildContext || (u5 = [], (i4 = {})[l3] = this, this.getChildContext = function() { return i4; }, this.shouldComponentUpdate = function(n4) { - this.props.value !== n4.value && u5.some(b); + this.props.value !== n4.value && u5.some(function(n5) { + n5.__e = true, m(n5); + }); }, this.sub = function(n4) { u5.push(n4); var l4 = n4.componentWillUnmount; @@ -9263,11 +11479,11 @@ function B(n2, l3) { } }; return u4.Provider.__ = u4.Consumer.contextType = u4; } -n = e.slice, l = { __e: function(n2, l3, u4, i4) { - for (var t4, o3, r3; l3 = l3.__; ) +n = s.slice, l = { __e: function(n2, l3, u4, i4) { + for (var t4, r3, o3; l3 = l3.__; ) if ((t4 = l3.__c) && !t4.__) try { - if ((o3 = t4.constructor) && null != o3.getDerivedStateFromError && (t4.setState(o3.getDerivedStateFromError(n2)), r3 = t4.__d), null != t4.componentDidCatch && (t4.componentDidCatch(n2, i4 || {}), r3 = t4.__d), r3) + if ((r3 = t4.constructor) && null != r3.getDerivedStateFromError && (t4.setState(r3.getDerivedStateFromError(n2)), o3 = t4.__d), null != t4.componentDidCatch && (t4.componentDidCatch(n2, i4 || {}), o3 = t4.__d), o3) return t4.__E = t4; } catch (l4) { n2 = l4; @@ -9275,12 +11491,14 @@ n = e.slice, l = { __e: function(n2, l3, u4, i4) { throw n2; } }, u = 0, i = function(n2) { return null != n2 && void 0 === n2.constructor; -}, d.prototype.setState = function(n2, l3) { +}, k.prototype.setState = function(n2, l3) { var u4; - u4 = null != this.__s && this.__s !== this.state ? this.__s : this.__s = s({}, this.state), "function" == typeof n2 && (n2 = n2(s({}, u4), this.props)), n2 && s(u4, n2), null != n2 && this.__v && (l3 && this._sb.push(l3), b(this)); -}, d.prototype.forceUpdate = function(n2) { - this.__v && (this.__e = true, n2 && this.__h.push(n2), b(this)); -}, d.prototype.render = p, t = [], g.__r = 0, r = 0; + u4 = null != this.__s && this.__s !== this.state ? this.__s : this.__s = h({}, this.state), "function" == typeof n2 && (n2 = n2(h({}, u4), this.props)), n2 && h(u4, n2), null != n2 && this.__v && (l3 && this._sb.push(l3), m(this)); +}, k.prototype.forceUpdate = function(n2) { + this.__v && (this.__e = true, n2 && this.__h.push(n2), m(this)); +}, k.prototype.render = _, t = [], o = "function" == typeof Promise ? Promise.prototype.then.bind(Promise.resolve()) : setTimeout, f = function(n2, l3) { + return n2.__v.__b - l3.__v.__b; +}, w.__r = 0, e = 0; // node_modules/preact/hooks/dist/hooks.module.js var t2; @@ -9300,18 +11518,16 @@ function d2(t4, u4) { var i4 = r2.__H || (r2.__H = { __: [], __h: [] }); return t4 >= i4.__.length && i4.__.push({ __V: c2 }), i4.__[t4]; } -function p2(n2) { - return o2 = 1, y2(B2, n2); +function h2(n2) { + return o2 = 1, s2(B2, n2); } -function y2(n2, u4, i4) { +function s2(n2, u4, i4) { var o3 = d2(t2++, 2); if (o3.t = n2, !o3.__c && (o3.__ = [i4 ? i4(u4) : B2(void 0, u4), function(n3) { var t4 = o3.__N ? o3.__N[0] : o3.__[0], r3 = o3.t(t4, n3); t4 !== r3 && (o3.__N = [r3, o3.__[1]], o3.__c.setState({})); }], o3.__c = r2, !r2.u)) { - r2.u = true; - var f4 = r2.shouldComponentUpdate; - r2.shouldComponentUpdate = function(n3, t4, r3) { + var f4 = function(n3, t4, r3) { if (!o3.__c.__H) return true; var u5 = o3.__c.__H.__.filter(function(n4) { @@ -9320,33 +11536,42 @@ function y2(n2, u4, i4) { if (u5.every(function(n4) { return !n4.__N; })) - return !f4 || f4.call(this, n3, t4, r3); + return !c4 || c4.call(this, n3, t4, r3); var i5 = false; return u5.forEach(function(n4) { if (n4.__N) { var t5 = n4.__[0]; n4.__ = n4.__N, n4.__N = void 0, t5 !== n4.__[0] && (i5 = true); } - }), !(!i5 && o3.__c.props === n3) && (!f4 || f4.call(this, n3, t4, r3)); + }), !(!i5 && o3.__c.props === n3) && (!c4 || c4.call(this, n3, t4, r3)); }; + r2.u = true; + var c4 = r2.shouldComponentUpdate, e4 = r2.componentWillUpdate; + r2.componentWillUpdate = function(n3, t4, r3) { + if (this.__e) { + var u5 = c4; + c4 = void 0, f4(n3, t4, r3), c4 = u5; + } + e4 && e4.call(this, n3, t4, r3); + }, r2.shouldComponentUpdate = f4; } return o3.__N || o3.__; } -function h2(u4, i4) { +function p2(u4, i4) { var o3 = d2(t2++, 3); !l.__s && z2(o3.__H, i4) && (o3.__ = u4, o3.i = i4, r2.__H.__h.push(o3)); } -function s2(u4, i4) { +function y2(u4, i4) { var o3 = d2(t2++, 4); !l.__s && z2(o3.__H, i4) && (o3.__ = u4, o3.i = i4, r2.__h.push(o3)); } function _2(n2) { - return o2 = 5, F(function() { + return o2 = 5, F2(function() { return { current: n2 }; }, []); } function A2(n2, t4, r3) { - o2 = 6, s2(function() { + o2 = 6, y2(function() { return "function" == typeof n2 ? (n2(t4()), function() { return n2(null); }) : n2 ? (n2.current = t4(), function() { @@ -9354,12 +11579,12 @@ function A2(n2, t4, r3) { }) : void 0; }, null == r3 ? r3 : r3.concat(n2)); } -function F(n2, r3) { +function F2(n2, r3) { var u4 = d2(t2++, 7); return z2(u4.__H, r3) ? (u4.__V = n2(), u4.i = r3, u4.__h = n2, u4.__V) : u4.__; } function T2(n2, t4) { - return o2 = 8, F(function() { + return o2 = 8, F2(function() { return n2; }, t4); } @@ -9371,7 +11596,7 @@ function x2(t4, r3) { l.useDebugValue && l.useDebugValue(r3 ? r3(t4) : t4); } function P2(n2) { - var u4 = d2(t2++, 10), i4 = p2(); + var u4 = d2(t2++, 10), i4 = h2(); return u4.__ = n2, r2.componentDidCatch || (r2.componentDidCatch = function(n3, t4) { u4.__ && u4.__(n3, t4), i4[1](n3); }), [i4[0], function() { @@ -9473,28 +11698,28 @@ function C2(n2, t4) { return true; return false; } -function E(n2, t4) { +function E2(n2, t4) { return n2 === t4 && (0 !== n2 || 1 / n2 == 1 / t4) || n2 != n2 && t4 != t4; } function w3(n2) { this.props = n2; } -function R(n2, e4) { +function x3(n2, e4) { function r3(n3) { var t4 = this.props.ref, r4 = t4 == n3.ref; return !r4 && t4 && (t4.call ? t4(null) : t4.current = null), e4 ? !e4(this.props, n3) || !r4 : C2(this.props, n3); } function u4(e5) { - return this.shouldComponentUpdate = r3, h(n2, e5); + return this.shouldComponentUpdate = r3, y(n2, e5); } return u4.displayName = "Memo(" + (n2.displayName || n2.name) + ")", u4.prototype.isReactComponent = true, u4.__f = true, u4; } -(w3.prototype = new d()).isPureReactComponent = true, w3.prototype.shouldComponentUpdate = function(n2, t4) { +(w3.prototype = new k()).isPureReactComponent = true, w3.prototype.shouldComponentUpdate = function(n2, t4) { return C2(this.props, n2) || C2(this.state, t4); }; -var x3 = l.__b; +var R = l.__b; l.__b = function(n2) { - n2.type && n2.type.__f && n2.ref && (n2.props.ref = n2.ref, n2.ref = null), x3 && x3(n2); + n2.type && n2.type.__f && n2.ref && (n2.props.ref = n2.ref, n2.ref = null), R && R(n2); }; var N2 = "undefined" != typeof Symbol && Symbol.for && Symbol.for("react.forward_ref") || 3911; function k3(n2) { @@ -9505,16 +11730,16 @@ function k3(n2) { return t4.$$typeof = N2, t4.render = t4, t4.prototype.isReactComponent = t4.__f = true, t4.displayName = "ForwardRef(" + (n2.displayName || n2.name) + ")", t4; } var A3 = function(n2, t4) { - return null == n2 ? null : x(x(n2).map(t4)); + return null == n2 ? null : P(P(n2).map(t4)); }; var O2 = { map: A3, forEach: A3, count: function(n2) { - return n2 ? x(n2).length : 0; + return n2 ? P(n2).length : 0; }, only: function(n2) { - var t4 = x(n2); + var t4 = P(n2); if (1 !== t4.length) throw "Children.only"; return t4[0]; -}, toArray: x }; +}, toArray: P }; var T3 = l.__e; l.__e = function(n2, t4, e4, r3) { if (n2.then) { @@ -9537,10 +11762,10 @@ function U(n2, t4, e4) { return U(n3, t4, e4); }), n2.__c && n2.__c.__P === t4 && (n2.__e && e4.insertBefore(n2.__e, n2.__d), n2.__c.__e = true, n2.__c.__P = e4)), n2; } -function D() { +function D2() { this.__u = 0, this.t = null, this.__b = null; } -function F2(n2) { +function F3(n2) { var t4 = n2.__.__c; return t4 && t4.__a && t4.__a(n2); } @@ -9555,7 +11780,7 @@ function M2(n2) { throw u4; if (!r3) throw e4; - return h(r3, o4); + return y(r3, o4); } return o3.displayName = "Lazy", o3.__f = true, o3; } @@ -9565,10 +11790,10 @@ function V2() { l.unmount = function(n2) { var t4 = n2.__c; t4 && t4.__R && t4.__R(), t4 && true === n2.__h && (n2.type = null), I2 && I2(n2); -}, (D.prototype = new d()).__c = function(n2, t4) { +}, (D2.prototype = new k()).__c = function(n2, t4) { var e4 = t4.__c, r3 = this; null == r3.t && (r3.t = []), r3.t.push(e4); - var u4 = F2(r3.__v), o3 = false, i4 = function() { + var u4 = F3(r3.__v), o3 = false, i4 = function() { o3 || (o3 = true, e4.__R = null, u4 ? u4(l3) : l3()); }; e4.__R = i4; @@ -9584,9 +11809,9 @@ l.unmount = function(n2) { } }, c4 = true === t4.__h; r3.__u++ || c4 || r3.setState({ __a: r3.__b = r3.__v.__k[0] }), n2.then(i4, i4); -}, D.prototype.componentWillUnmount = function() { +}, D2.prototype.componentWillUnmount = function() { this.t = []; -}, D.prototype.render = function(n2, e4) { +}, D2.prototype.render = function(n2, e4) { if (this.__b) { if (this.__v.__k) { var r3 = document.createElement("div"), o3 = this.__v.__k[0].__c; @@ -9594,8 +11819,8 @@ l.unmount = function(n2) { } this.__b = null; } - var i4 = e4.__a && h(p, null, n2.fallback); - return i4 && (i4.__h = null), [h(p, null, e4.__a ? null : n2.children), i4]; + var i4 = e4.__a && y(_, null, n2.fallback); + return i4 && (i4.__h = null), [y(_, null, e4.__a ? null : n2.children), i4]; }; var W = function(n2, t4, e4) { if (++e4[1] === e4[0] && n2.o.delete(t4), n2.props.revealOrder && ("t" !== n2.props.revealOrder[0] || !n2.o.size)) @@ -9612,24 +11837,24 @@ function P3(n2) { return n2.context; }, n2.children; } -function $2(n2) { +function j3(n2) { var e4 = this, r3 = n2.i; e4.componentWillUnmount = function() { - P(null, e4.l), e4.l = null, e4.i = null; + B(null, e4.l), e4.l = null, e4.i = null; }, e4.i && e4.i !== r3 && e4.componentWillUnmount(), n2.__v ? (e4.l || (e4.i = r3, e4.l = { nodeType: 1, parentNode: r3, childNodes: [], appendChild: function(n3) { this.childNodes.push(n3), e4.i.appendChild(n3); }, insertBefore: function(n3, t4) { this.childNodes.push(n3), e4.i.appendChild(n3); }, removeChild: function(n3) { this.childNodes.splice(this.childNodes.indexOf(n3) >>> 1, 1), e4.i.removeChild(n3); - } }), P(h(P3, { context: e4.context }, n2.__v), e4.l)) : e4.l && e4.componentWillUnmount(); + } }), B(y(P3, { context: e4.context }, n2.__v), e4.l)) : e4.l && e4.componentWillUnmount(); } -function j3(n2, e4) { - var r3 = h($2, { __v: n2, i: e4 }); +function z3(n2, e4) { + var r3 = y(j3, { __v: n2, i: e4 }); return r3.containerInfo = e4, r3; } -(V2.prototype = new d()).__a = function(n2) { - var t4 = this, e4 = F2(t4.__v), r3 = t4.o.get(n2); +(V2.prototype = new k()).__a = function(n2) { + var t4 = this, e4 = F3(t4.__v), r3 = t4.o.get(n2); return r3[0]++, function(u4) { var o3 = function() { t4.props.revealOrder ? (r3.push(u4), W(t4, n2, r3)) : u4(); @@ -9638,7 +11863,7 @@ function j3(n2, e4) { }; }, V2.prototype.render = function(n2) { this.u = null, this.o = /* @__PURE__ */ new Map(); - var t4 = x(n2.children); + var t4 = P(n2.children); n2.revealOrder && "b" === n2.revealOrder[0] && t4.reverse(); for (var e4 = t4.length; e4--; ) this.o.set(t4[e4], this.u = [1, 0, this.u]); @@ -9649,117 +11874,127 @@ function j3(n2, e4) { W(n2, e4, t4); }); }; -var z3 = "undefined" != typeof Symbol && Symbol.for && Symbol.for("react.element") || 60103; -var B3 = /^(?:accent|alignment|arabic|baseline|cap|clip(?!PathU)|color|dominant|fill|flood|font|glyph(?!R)|horiz|image|letter|lighting|marker(?!H|W|U)|overline|paint|pointer|shape|stop|strikethrough|stroke|text(?!L)|transform|underline|unicode|units|v|vector|vert|word|writing|x(?!C))[A-Z]/; -var H2 = "undefined" != typeof document; -var Z = function(n2) { - return ("undefined" != typeof Symbol && "symbol" == typeof Symbol() ? /fil|che|rad/i : /fil|che|ra/i).test(n2); +var B3 = "undefined" != typeof Symbol && Symbol.for && Symbol.for("react.element") || 60103; +var H2 = /^(?:accent|alignment|arabic|baseline|cap|clip(?!PathU)|color|dominant|fill|flood|font|glyph(?!R)|horiz|image|letter|lighting|marker(?!H|W|U)|overline|paint|pointer|shape|stop|strikethrough|stroke|text(?!L)|transform|underline|unicode|units|v|vector|vert|word|writing|x(?!C))[A-Z]/; +var Z = /^on(Ani|Tra|Tou|BeforeInp|Compo)/; +var Y = /[A-Z0-9]/g; +var $2 = "undefined" != typeof document; +var q3 = function(n2) { + return ("undefined" != typeof Symbol && "symbol" == typeof Symbol() ? /fil|che|rad/ : /fil|che|ra/).test(n2); }; -function Y(n2, t4, e4) { - return null == t4.__k && (t4.textContent = ""), P(n2, t4), "function" == typeof e4 && e4(), n2 ? n2.__c : null; +function G(n2, t4, e4) { + return null == t4.__k && (t4.textContent = ""), B(n2, t4), "function" == typeof e4 && e4(), n2 ? n2.__c : null; } -function q3(n2, t4, e4) { - return S(n2, t4), "function" == typeof e4 && e4(), n2 ? n2.__c : null; +function J(n2, t4, e4) { + return D(n2, t4), "function" == typeof e4 && e4(), n2 ? n2.__c : null; } -d.prototype.isReactComponent = {}, ["componentWillMount", "componentWillReceiveProps", "componentWillUpdate"].forEach(function(t4) { - Object.defineProperty(d.prototype, t4, { configurable: true, get: function() { +k.prototype.isReactComponent = {}, ["componentWillMount", "componentWillReceiveProps", "componentWillUpdate"].forEach(function(t4) { + Object.defineProperty(k.prototype, t4, { configurable: true, get: function() { return this["UNSAFE_" + t4]; }, set: function(n2) { Object.defineProperty(this, t4, { configurable: true, writable: true, value: n2 }); } }); }); -var G = l.event; -function J() { +var K = l.event; +function Q() { } -function K() { +function X() { return this.cancelBubble; } -function Q() { +function nn() { return this.defaultPrevented; } l.event = function(n2) { - return G && (n2 = G(n2)), n2.persist = J, n2.isPropagationStopped = K, n2.isDefaultPrevented = Q, n2.nativeEvent = n2; + return K && (n2 = K(n2)), n2.persist = Q, n2.isPropagationStopped = X, n2.isDefaultPrevented = nn, n2.nativeEvent = n2; }; -var X; -var nn = { configurable: true, get: function() { +var tn; +var en = { configurable: true, get: function() { return this.class; } }; -var tn = l.vnode; +var rn = l.vnode; l.vnode = function(n2) { var t4 = n2.type, e4 = n2.props, u4 = e4; if ("string" == typeof t4) { - var o3 = -1 === t4.indexOf("-"); - for (var i4 in u4 = {}, e4) { - var l3 = e4[i4]; - H2 && "children" === i4 && "noscript" === t4 || "value" === i4 && "defaultValue" in e4 && null == l3 || ("defaultValue" === i4 && "value" in e4 && null == e4.value ? i4 = "value" : "download" === i4 && true === l3 ? l3 = "" : /ondoubleclick/i.test(i4) ? i4 = "ondblclick" : /^onchange(textarea|input)/i.test(i4 + t4) && !Z(e4.type) ? i4 = "oninput" : /^onfocus$/i.test(i4) ? i4 = "onfocusin" : /^onblur$/i.test(i4) ? i4 = "onfocusout" : /^on(Ani|Tra|Tou|BeforeInp|Compo)/.test(i4) ? i4 = i4.toLowerCase() : o3 && B3.test(i4) ? i4 = i4.replace(/[A-Z0-9]/g, "-$&").toLowerCase() : null === l3 && (l3 = void 0), /^oninput$/i.test(i4) && (i4 = i4.toLowerCase(), u4[i4] && (i4 = "oninputCapture")), u4[i4] = l3); + for (var o3 in u4 = {}, e4) { + var i4 = e4[o3]; + if (!("value" === o3 && "defaultValue" in e4 && null == i4 || $2 && "children" === o3 && "noscript" === t4)) { + var l3 = o3.toLowerCase(); + "defaultValue" === o3 && "value" in e4 && null == e4.value ? o3 = "value" : "download" === o3 && true === i4 ? i4 = "" : "ondoubleclick" === l3 ? o3 = "ondblclick" : "onchange" !== l3 || "input" !== t4 && "textarea" !== t4 || q3(e4.type) ? "onfocus" === l3 ? o3 = "onfocusin" : "onblur" === l3 ? o3 = "onfocusout" : Z.test(o3) ? o3 = l3 : -1 === t4.indexOf("-") && H2.test(o3) ? o3 = o3.replace(Y, "-$&").toLowerCase() : null === i4 && (i4 = void 0) : l3 = o3 = "oninput", "oninput" === l3 && u4[o3 = l3] && (o3 = "oninputCapture"), u4[o3] = i4; + } } - "select" == t4 && u4.multiple && Array.isArray(u4.value) && (u4.value = x(e4.children).forEach(function(n3) { + "select" == t4 && u4.multiple && Array.isArray(u4.value) && (u4.value = P(e4.children).forEach(function(n3) { n3.props.selected = -1 != u4.value.indexOf(n3.props.value); - })), "select" == t4 && null != u4.defaultValue && (u4.value = x(e4.children).forEach(function(n3) { + })), "select" == t4 && null != u4.defaultValue && (u4.value = P(e4.children).forEach(function(n3) { n3.props.selected = u4.multiple ? -1 != u4.defaultValue.indexOf(n3.props.value) : u4.defaultValue == n3.props.value; - })), n2.props = u4, e4.class != e4.className && (nn.enumerable = "className" in e4, null != e4.className && (u4.class = e4.className), Object.defineProperty(u4, "className", nn)); + })), n2.props = u4, e4.class != e4.className && (en.enumerable = "className" in e4, null != e4.className && (u4.class = e4.className), Object.defineProperty(u4, "className", en)); } - n2.$$typeof = z3, tn && tn(n2); + n2.$$typeof = B3, rn && rn(n2); }; -var en = l.__r; +var un = l.__r; l.__r = function(n2) { - en && en(n2), X = n2.__c; + un && un(n2), tn = n2.__c; +}; +var on = l.diffed; +l.diffed = function(n2) { + on && on(n2); + var t4 = n2.props, e4 = n2.__e; + null != e4 && "textarea" === n2.type && "value" in t4 && t4.value !== e4.value && (e4.value = null == t4.value ? "" : t4.value), tn = null; }; -var rn = { ReactCurrentDispatcher: { current: { readContext: function(n2) { - return X.__n[n2.__c].props.value; +var ln = { ReactCurrentDispatcher: { current: { readContext: function(n2) { + return tn.__n[n2.__c].props.value; } } } }; -function on(n2) { - return h.bind(null, n2); +function fn(n2) { + return y.bind(null, n2); } -function ln(n2) { - return !!n2 && n2.$$typeof === z3; +function an(n2) { + return !!n2 && n2.$$typeof === B3; } -function cn(n2) { - return ln(n2) ? q.apply(null, arguments) : n2; +function sn(n2) { + return an(n2) ? E.apply(null, arguments) : n2; } -function fn(n2) { - return !!n2.__k && (P(null, n2), true); +function hn(n2) { + return !!n2.__k && (B(null, n2), true); } -function an(n2) { +function vn(n2) { return n2 && (n2.base || 1 === n2.nodeType && n2) || null; } -var sn = function(n2, t4) { +var dn = function(n2, t4) { return n2(t4); }; -var hn = function(n2, t4) { +var pn = function(n2, t4) { return n2(t4); }; -var vn = p; -function dn(n2) { +var mn = _; +function yn(n2) { n2(); } -function pn(n2) { +function _n(n2) { return n2; } -function mn() { - return [false, dn]; +function bn() { + return [false, yn]; } -var yn = s2; -function _n(n2, t4) { - var e4 = t4(), r3 = p2({ h: { __: e4, v: t4 } }), u4 = r3[0].h, o3 = r3[1]; - return s2(function() { - u4.__ = e4, u4.v = t4, E(u4.__, t4()) || o3({ h: u4 }); - }, [n2, e4, t4]), h2(function() { - return E(u4.__, u4.v()) || o3({ h: u4 }), n2(function() { - E(u4.__, u4.v()) || o3({ h: u4 }); +var Sn = y2; +function gn(n2, t4) { + var e4 = t4(), r3 = h2({ h: { __: e4, v: t4 } }), u4 = r3[0].h, o3 = r3[1]; + return y2(function() { + u4.__ = e4, u4.v = t4, E2(u4.__, t4()) || o3({ h: u4 }); + }, [n2, e4, t4]), p2(function() { + return E2(u4.__, u4.v()) || o3({ h: u4 }), n2(function() { + E2(u4.__, u4.v()) || o3({ h: u4 }); }); }, [n2]), e4; } -var bn = { useState: p2, useId: V, useReducer: y2, useEffect: h2, useLayoutEffect: s2, useInsertionEffect: yn, useTransition: mn, useDeferredValue: pn, useSyncExternalStore: _n, startTransition: dn, useRef: _2, useImperativeHandle: A2, useMemo: F, useCallback: T2, useContext: q2, useDebugValue: x2, version: "17.0.2", Children: O2, render: Y, hydrate: q3, unmountComponentAtNode: fn, createPortal: j3, createElement: h, createContext: B, createFactory: on, cloneElement: cn, createRef: y, Fragment: p, isValidElement: ln, findDOMNode: an, Component: d, PureComponent: w3, memo: R, forwardRef: k3, flushSync: hn, unstable_batchedUpdates: sn, StrictMode: vn, Suspense: D, SuspenseList: V2, lazy: M2, __SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED: rn }; +var Cn = { useState: h2, useId: V, useReducer: s2, useEffect: p2, useLayoutEffect: y2, useInsertionEffect: Sn, useTransition: bn, useDeferredValue: _n, useSyncExternalStore: gn, startTransition: yn, useRef: _2, useImperativeHandle: A2, useMemo: F2, useCallback: T2, useContext: q2, useDebugValue: x2, version: "17.0.2", Children: O2, render: G, hydrate: J, unmountComponentAtNode: hn, createPortal: z3, createElement: y, createContext: F, createFactory: fn, cloneElement: sn, createRef: d, Fragment: _, isValidElement: an, findDOMNode: vn, Component: k, PureComponent: w3, memo: x3, forwardRef: k3, flushSync: pn, unstable_batchedUpdates: dn, StrictMode: mn, Suspense: D2, SuspenseList: V2, lazy: M2, __SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED: ln }; // node_modules/preact/compat/client.mjs function createRoot(container) { return { render(children) { - Y(children, container); + G(children, container); }, unmount() { - fn(container); + hn(container); } }; } @@ -9963,9 +12198,9 @@ var T4 = class { codeblock: "Code Block", emoji: "Emoji", image: "Image", - flow: "Flow Note", + flow: "Flow Block", tag: "Tag", - makeMenu: "Make Menu", + makeMenu: "Flow Menu", selectStyle: "Style", toggleKeyboard: "Toggle Keyboard" }, @@ -9985,13 +12220,15 @@ var T4 = class { commandPalette: { enable: "Enable", disabled: "Disable", - openFlow: "Open Flow Editors in Selection", - closeFlow: "Close Flow Editors in Selection", + openFlow: "Open Flow Blocks in Selection", + closeFlow: "Close Flow Blocks in Selection", toggleBold: "Toggle Bold", toggleItalics: "Toggle Italics", openSpaces: "Open Spaces", reloadSpaces: "Reload Spaces", - blink: "Blink", + loadBackupSpace: "Restore Spaces from Backup", + backupSpace: "Backup Space", + blink: "Flow Search", openFileContext: "Open Context Explorer", revealFile: "Reveal File in Spaces", toggleBacklinks: "Toggle Backlinks", @@ -10016,6 +12253,7 @@ var T4 = class { collapseAllFolders: "Collapse All Folders", expandAllFolders: "Expand All Folders", spaceTitle: "Add/Remove in Space", + home: "Home", none: "None", tableView: "Table View", cardView: "Card View", @@ -10047,8 +12285,9 @@ var T4 = class { spaces: "Spaces", tags: "Tags", manageHiddenFiles: "Manage Hidden Files", - unpinSpace: "Unpin Space", - pinSpace: "Pin Space", + unpinSpace: "Unpin", + pinSpace: "Pinned", + homeSpace: "Home", deleteSpace: "Delete Space", changeColor: "Change Color", deleteFiles: "Delete Files", @@ -10063,10 +12302,12 @@ var T4 = class { changeBanner: "Change Cover", removeBanner: "Remove Cover", rename: "Change Name", + saveSpace: "Save Space", createFolder: "New Folder", createNote: "New Note", createCanvas: "New Canvas", createSection: "New Space", + createSectionSmart: "New Smart Space", cancel: "Cancel", search: "Search", delete: "Delete", @@ -10079,7 +12320,7 @@ var T4 = class { syncFields: "Sync Properties", cutTable: "Cut Table", deleteTable: "Delete Table", - blink: "Blink", + blink: "Flow Search", addFile: "Add File", merge: "Merge", saveView: "Save View", @@ -10160,9 +12401,12 @@ var T4 = class { createFolder: "New Folder Name", rename: "Rename", selectDateFormat: "Select/Type Date Format", - renameSection: "Rename Space", + renameSectionSmart: "Edit Smart Space", + renameSection: "Edit Space", + createSectionSmart: "New Smart Space", createSection: "New Space", createNote: "New Note Name", + contextMaker: "Context Maker", select: "Select", collapse: "Collapse", expand: "Expand", @@ -10226,11 +12470,12 @@ var T4 = class { layoutHorizontal: "Horizontal", sectionSidebar: "Spaces", sectionEditor: "Maker Mode", - sectionFlow: "Flow Editor", + sectionFlow: "Flow", sectionAdvanced: "Advanced", sectionDataview: "Dataview", sectionAppearance: "Appearance", sectionContext: "Context", + sectionSync: "Sync and Backup", defaultDateFormat: { name: "Default Date Format", desc: "Set the default date format (ISO 8601)" @@ -10244,8 +12489,8 @@ var T4 = class { desc: "Turn on to have folder notes inside the folder, turn off to have it outside" }, internalLinkFlowEditor: { - name: "Open Flow Editor on Internal Link Click", - desc: "Turn on to toggle Flow Editor directly by clicking on internal links, otherwise a tooltip will be shown" + name: "Open Flow Blocks on Internal Link Click", + desc: "Turn on to toggle Flow Blocks directly by clicking on internal links, otherwise a tooltip will be shown" }, syncContextToFrontmatter: { name: "Sync Context Fields to Frontmatter", @@ -10260,8 +12505,12 @@ var T4 = class { desc: "Show dataview when inline context is enabled" }, inlineContextExplorer: { - name: "Show Inline Context", - desc: "Show the context and a banner at the top of your notes" + name: "Inline Context", + desc: "Display the context and a banner at the top of your notes" + }, + inlineContextExpanded: { + name: "Auto Expand Inline Context", + desc: "Expand the inline context sections when opening a note" }, inlineContextHorizontal: { name: "Inline Title and Sticker Layout", @@ -10308,8 +12557,8 @@ var T4 = class { desc: `Use Emojis to make it easier to find your notes` }, spacesFileExplorerDual: { - name: "Use Spaces Alongside File Explorer", - desc: "This will allow plugins that uses the File Explorer to work while using Spaces" + name: "Compatibility Mode", + desc: "This will improve the compatibility of plugins while using Spaces" }, spacesDeleteOption: { name: "Delete File Option", @@ -10329,23 +12578,35 @@ var T4 = class { desc: `Show/hide other sidebar tabs` }, spacesPerformance: { - name: "Spaces Performance Mode", + name: "Performance Mode", desc: `Turn on performance mode for Spaces, may affect scrolling appearance. Requires Restart` }, inlineStyler: { - name: "Inline Styler", - desc: `Select text to add styling, recommended for Flow Editor` + name: "Flow Styler", + desc: `Select text to add styling` }, inlineStylerColor: { 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" + }, + 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: "Make Menu Trigger", - desc: "Character to open the Make Menu" + name: "Flow Menu Trigger", + desc: "Character to open the Flow Menu" }, mobileMakeBar: { - name: "Make Bar (Mobile)", + name: "Flow Styler (Mobile)", desc: "Replaces the mobile toolbar" }, editorMarkSans: { @@ -10353,24 +12614,32 @@ var T4 = class { desc: `Use the editor without Markdown.` }, editorMakerMode: { - name: "Maker Mode", - desc: `Turn on Maker Mode for a more intuitive editor experience` + name: "Flow (Beta)", + desc: `An integrated and intuitive editor experience` }, editorMakePlacholder: { - name: "Make Menu Hint Text", - desc: `Show a hint text on how to open the Make Menu Shortcut` + name: "Flow Menu Hint Text", + desc: `Show a hint text on how to open the Flow Menu Shortcut` + }, + blink: { + name: "Blink", + desc: `A faster way to search and edit your notes` }, editorMakeMenu: { - name: "Make Menu Shortcut", - desc: `Open the Make menu to quickly add content` + name: "Flow Menu", + desc: `Open the Flow menu to quickly add content` + }, + editorMakeMenuTrigger: { + name: "Flow Menu Shortcut", + desc: `Trigger key to use flow menu` }, editorFlowReplace: { - name: "Flow Editor", - desc: `Open your internal links or toggle your embeds in the flow editor.` + name: "Flow Block", + desc: `Open your internal links or toggle your embeds in the flow block.` }, editorFlowStyle: { - name: "Flow Editor Style", - desc: "Select a theme for your flow editors", + name: "Flow Block Style", + desc: "Select a theme for your flow block", seamless: "Seamless", classic: "Classic", minimal: "Minimal" @@ -10388,6 +12657,8 @@ 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": @@ -10401,8 +12672,9 @@ var defaultIconForExtension = (type, solid) => { break; case "canvas": return uiIconSet["mk-ui-canvas"]; + default: + return solid ? uiIconSet["mk-ui-file-solid"] : uiIconSet["mk-ui-file"]; } - return solid ? uiIconSet["mk-ui-file-solid"] : uiIconSet["mk-ui-file"]; }; var uiIconSet = { "mk-ui-close": ` @@ -10461,6 +12733,9 @@ var uiIconSet = { `, "mk-ui-spaces": ` +`, + "mk-ui-home": ` + `, "mk-ui-tags": ` @@ -10517,6 +12792,19 @@ var uiIconSet = { "mk-ui-edit": ` +`, + "mk-ui-list": ` + + + +`, + "mk-ui-build": ` + + +`, + "mk-ui-check": ` + + ` }; var makeIconSet = { @@ -10611,7 +12899,11 @@ var makeIconSet = { - ` + `, + "mk-make-date": ` + + +` }; var mkLogo = ` @@ -10679,22 +12971,22 @@ var markIconSet = { // src/components/FlowEditor/FlowEditorHover.tsx var FlowEditorHover = (props2) => { - return props2.type == "file" ? /* @__PURE__ */ bn.createElement(bn.Fragment, null, props2.toggle && /* @__PURE__ */ bn.createElement("div", { + return 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"] } - }), /* @__PURE__ */ bn.createElement("div", { + }), /* @__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__ */ bn.createElement(bn.Fragment, null, /* @__PURE__ */ bn.createElement("div", { + })) : /* @__PURE__ */ Cn.createElement(Cn.Fragment, null, /* @__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__ */ bn.createElement("div", { + }), /* @__PURE__ */ Cn.createElement("div", { "aria-label": i18n_default.buttons.deleteTable, onClick: props2.deleteTable, className: "mk-icon-xsmall mk-hover-button", @@ -10704,8 +12996,7 @@ var FlowEditorHover = (props2) => { // src/types/types.ts var eventTypes = { - selectedFileChange: "mkmd-selected-file-change", - activeFileChange: "mkmd-active-file-change", + activePathChange: "mkmd-active-path", refreshView: "mkmd-refresh-view", revealFile: "mkmd-reveal-file", collapseFolders: "mkmd-collapse-folders", @@ -10755,29 +13046,10 @@ var openFileFlowEditor = (file, source) => { }; // src/utils/tree.ts -var import_obsidian33 = require("obsidian"); +var import_obsidian37 = require("obsidian"); // src/components/ContextView/ContextView.tsx -var import_obsidian29 = 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/parser.tsx -var splitString = (str) => { - var _a2; - return (_a2 = str == null ? void 0 : str.match(/(\\.|[^,])+/g)) != null ? _a2 : []; -}; -var splitPropString = (str) => { - var _a2; - return (_a2 = str == null ? void 0 : str.match(/(\\.|[^.])+/g)) != null ? _a2 : []; -}; - -// src/utils/contexts/tags.ts -var import_obsidian5 = require("obsidian"); - -// src/utils/contexts/mdb.ts -var import_lodash3 = __toESM(require_lodash()); +var import_obsidian33 = require("obsidian"); // src/utils/array.ts var insert = (arr, index, newItem) => [ @@ -10785,6 +13057,99 @@ var insert = (arr, index, newItem) => [ 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 onlyUniquePropCaseInsensitive = (prop) => (value, index, self2) => { + return self2.findIndex( + (v3) => value[prop].toLowerCase() == v3[prop].toLowerCase() + ) === index; +}; + +// 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/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/metadata/tags.ts +var import_obsidian2 = require("obsidian"); + +// src/utils/strings.ts +var stickerFromString = (sticker) => { + let html; + try { + html = unifiedToNative(sticker); + } catch (e4) { + html = sticker; + } + return html; +}; +var unifiedToNative = (unified) => { + let unicodes = unified.split("-"); + let 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 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); + } + if (filename.lastIndexOf(".") != -1) { + return filename.substring(0, filename.lastIndexOf(".")); + } + return filename; +}; +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) == "space") + return spaceNameFromContextPath(context.contextPath); + if (context.isRemote) { + return folderPathToString(context.contextPath); + } + return context.contextPath; +}; +var folderNotePathFromAFile = (settings, aFile) => settings.folderNoteInsideFolder ? `${aFile.path}/${aFile.name}.md` : aFile.parent == "/" ? `${aFile.name}.md` : `${aFile.parent}/${aFile.name}.md`; +var folderPathFromFolderNoteFile = (settings, aFile) => settings.folderNoteInsideFolder ? aFile.parent : aFile.parent == "/" ? aFile.name : `${aFile.parent}/${aFile.name}`; // src/utils/sanitize.ts var sanitizeTableName = (name) => { @@ -10800,7 +13165,23 @@ var sanitizeSQLStatement = (name) => { return name == null ? void 0 : name.replace(/'/g, `''`); }; +// 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 fieldTypeForType = (type) => fieldTypes.find((t4) => type == t4.type) || fieldTypes.find((t4) => type == t4.multiType); var fieldTypes = [ { type: "unknown", @@ -10815,33 +13196,39 @@ var fieldTypes = [ { type: "text", label: i18n_default.properties.text.label, - metadata: true + metadata: true, + icon: "mk-make-h3" }, { type: "number", label: i18n_default.properties.number.label, - metadata: true + metadata: true, + icon: "mk-make-tag" }, { type: "boolean", label: i18n_default.properties.boolean.label, - metadata: true + metadata: true, + icon: "mk-make-todo" }, { type: "date", label: i18n_default.properties.date.label, - metadata: true + metadata: true, + icon: "mk-make-date" }, { type: "option", label: i18n_default.properties.option.label, multi: true, - multiType: "option-multi" + multiType: "option-multi", + icon: "mk-make-list" }, { type: "file", label: i18n_default.properties.file.label, - restricted: true + restricted: true, + icon: "mk-make-h3" }, { type: "fileprop", @@ -10852,13 +13239,15 @@ var fieldTypes = [ label: i18n_default.properties.link.label, multi: true, multiType: "link-multi", - metadata: true + metadata: true, + icon: "mk-make-note" }, { type: "context", label: i18n_default.properties.context.label, multi: true, - multiType: "context-multi" + multiType: "context-multi", + icon: "mk-make-note" }, { type: "object", @@ -10871,9 +13260,46 @@ var fieldTypes = [ label: i18n_default.properties.image.label, multi: true, multiType: "image-multi", - metadata: true + metadata: true, + icon: "mk-make-image" } ]; +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"; + } + if (type == "fileprop") { + const { field, property } = parsePropString(value); + if (property == "ctime" || property == "mtime") + return (Date.now() - 60).toString(); + return value; + } + if (type == "file") { + return "Note Name"; + } + if (type == "date") { + return "2020-04-21"; + } + if (type == "number") { + return "123"; + } + if (type == "boolean") { + return "true"; + } + if (type == "link") { + return "[[Select Note]]"; + } + if (type == "option") { + return "one, two"; + } + if (type == "text") { + return name; + } + 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"; + } + return ""; +}; var defaultFileDBSchema = { id: "files", name: "Files", @@ -10893,12 +13319,12 @@ var defaultFileTableSchema = { def: "files" }; var defaultFolderSchema = { - uniques: ["id"], + uniques: [], cols: ["id", "name", "type", "def", "predicate", "primary"], rows: [defaultFileDBSchema, defaultFileListSchema] }; var defaultTagSchema = { - uniques: ["id"], + uniques: [], cols: ["id", "name", "type", "def", "predicate", "primary"], rows: [defaultFileDBSchema, defaultFileTableSchema] }; @@ -10918,26 +13344,6 @@ var fieldSchema = { var defaultFolderFields = { ...fieldSchema, rows: [ - { - name: "_id", - schemaId: "files", - type: "id", - unique: "true", - hidden: "true", - attrs: "", - value: "", - primary: "" - }, - { - name: "_source", - schemaId: "files", - type: "source", - hidden: "true", - unique: "", - attrs: "", - value: "", - primary: "" - }, { name: i18n_default.properties.preview.label, schemaId: "files", @@ -10949,7 +13355,7 @@ var defaultFolderFields = { primary: "" }, { - name: "File", + name: FilePropertyName, schemaId: "files", type: "file", primary: "true", @@ -10975,8 +13381,6 @@ var defaultFieldsForContext = (context) => { return defaultTagFields; } else if (context.type == "folder") { return defaultFolderFields; - } else if (context.type == "query") { - return defaultFolderFields; } return defaultFolderFields; }; @@ -10991,37 +13395,7 @@ var defaultTagFields = { ...fieldSchema, rows: [ { - name: "_id", - schemaId: "files", - type: "id", - unique: "true", - hidden: "true", - attrs: "", - value: "", - primary: "" - }, - { - name: "_source", - schemaId: "files", - type: "source", - hidden: "true", - unique: "", - attrs: "", - value: "", - primary: "" - }, - { - name: "_sourceId", - schemaId: "files", - type: "sourceid", - hidden: "true", - unique: "", - attrs: "", - value: "", - primary: "" - }, - { - name: "File", + name: FilePropertyName, schemaId: "files", type: "file", primary: "true", @@ -11037,8 +13411,6 @@ var defaultMDBTableForContext = (context) => { return defaultTagMDBTable; } else if (context.type == "folder") { return defaultFolderMDBTable; - } else if (context.type == "query") { - return defaultQueryMDBTable; } return defaultFolderMDBTable; }; @@ -11082,8 +13454,6 @@ var defaultTablesForContext = (context) => { return defaultTagTables; } else if (context.type == "folder") { return defaultFolderTables; - } else if (context.type == "query") { - return defaultFolderTables; } return defaultFolderTables; }; @@ -11104,9755 +13474,8351 @@ var defaultTagTables = { ) }; -// src/dispatch/mdb.ts -var import_lodash2 = __toESM(require_lodash()); -var import_obsidian3 = require("obsidian"); - -// 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); -} - -// 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"); +// src/utils/db/db.ts +var import_obsidian = require("obsidian"); +var getDBFile = async (path, isRemote) => { + if (isRemote) { + return fetch(path).then((res) => res.arrayBuffer()); } -} - -// 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; - }; + if (!await app.vault.adapter.exists((0, import_obsidian.normalizePath)(path))) { + 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); + const file = await app.vault.adapter.readBinary( + (0, import_obsidian.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)); } -} - -// 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); + return new sqlJS.Database(); +}; +var saveDBFile = async (path, binary) => { + const file = app.vault.adapter.writeBinary( + (0, import_obsidian.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] }), + {} + ) + ) : [] + } + ], + [] + ); +}; +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; } - if (!amount) { - return date; + 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); } - date.setDate(date.getDate() + amount); - return date; -} - -// 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); +}; +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).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 : ""}`; + })); + try { + db.exec(sqlstr); + } catch (e4) { + console.log(e4); } - 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; +}; +var saveDBToPath = async (plugin, path, tables) => { + const sqlJS = await plugin.sqlJS(); + let db = await getDB(sqlJS, path); + if (!db) { + db.close(); + return false; } -} - -// 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; -} + replaceDB(db, tables); + await saveDBFile(path, db.export().buffer); + db.close(); + return true; +}; -// 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"); +// src/utils/json.ts +var safelyParseJSON = (json) => { + var parsed; + try { + parsed = JSON.parse(json); + } catch (e4) { } - 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 - }); -} + return parsed; +}; -// 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; +// 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; +}; +var parseLinkDisplayString = (string) => { + return filePathToString(parseLinkString(string)); +}; +var parseContextDefString = (str) => { + var _a2; + if (!str || str.length == 0) + return []; + if (str.charAt(0) == "#") { + return str.split("&").map((f4) => ({ + type: "tag", + value: f4 + })); } -} - -// 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; -} + return (_a2 = safelyParseJSON(str)) != null ? _a2 : []; +}; +var parseSpace = (spaceRow) => { + return { + ...spaceRow, + def: parseSpaceDefString(spaceRow.def) + }; +}; +var parseSpaceDefString = (str) => { + var _a2; + if (!str || str.length == 0) + return { type: "focus", folder: "", filters: [] }; + if (str.charAt(0) != "{") { + return { + folder: str, + type: "focus", + filters: [ + { + type: "any", + trueFalse: true, + filters: [ + { + type: "filemeta", + fType: "string", + field: "folder", + fn: "equals", + value: str + } + ] + } + ] + }; + } + return (_a2 = safelyParseJSON(str)) != null ? _a2 : []; +}; -// 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; - }; +// 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, 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; } - 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 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; } - var result; - datesArray.forEach(function(dirtyDate) { - var currentDate = toDate(dirtyDate); - if (result === void 0 || result < currentDate || isNaN(Number(currentDate))) { - result = currentDate; - } - }); - 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; + if (fieldsTables.length == 0) { + db.close(); + return { + schema, + cols: [], + rows: [] }; } - 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); + 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; } - var result; - datesArray.forEach(function(dirtyDate) { - var currentDate = toDate(dirtyDate); - if (result === void 0 || result > currentDate || isNaN(currentDate.getDate())) { - 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(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 }; }); - 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 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; } -} - -// 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; + 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 + } + }; + db.close(); + return saveDBToPath(plugin, context.dbPath, 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 createDefaultDB = async (plugin, context) => { + const sqlJS = await plugin.sqlJS(); + const table = defaultTablesForContext(context); + return saveDBToPath(plugin, context.dbPath, table); +}; +var sanitizeTableSchema = async (plugin, db, context) => { + const sqlJS = await plugin.sqlJS(); + const tableRes = db.exec( + `SELECT name FROM sqlite_master WHERE type='table';` + ); + 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 createDefaultDB(plugin, context); + } +}; +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; + 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 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); + app.workspace.iterateLeaves((leaf) => { + if (leaf.view.getViewType() == CONTEXT_VIEW_TYPE && leaf.view.getState().contextPath == tag) { + leaf.setViewState({ type: "empty" }); + } + }, 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)); } + app.workspace.iterateLeaves((leaf) => { + if (leaf.view.getViewType() == CONTEXT_VIEW_TYPE && leaf.view.getState().contextPath == context.contextPath) { + leaf.setViewState({ type: "empty" }); + } + }, app.workspace["rootSplit"]); }; -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 connectContext = async (plugin, tag, source) => { +}; +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)); } - 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.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) } + }); + } + }, app.workspace["rootSplit"]); +}; +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)); } - 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; -} + 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 } + }); + } + }, app.workspace["rootSplit"]); +}; -// 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/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 stringFromTag = (string) => { + if (string.charAt(0) == "#") { + return string.substring(1, string.length); } - 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 - }); -} - -// node_modules/date-fns/esm/subMilliseconds/index.js -function subMilliseconds(dirtyDate, dirtyAmount) { - requiredArgs(2, arguments); - var amount = toInteger(dirtyAmount); - return addMilliseconds(dirtyDate, -amount); -} - -// 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; - } -} - -// 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; -} - -// 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; -} - -// 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"); - } - 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"); + return string; +}; +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_obsidian2.TFile && f4.extension == "mdb" && f4.name.charAt(0) == "#" + ).map((f4) => tagPathToTag(f4.name))) != null ? _a2 : [] + ]); +}; +var tagExists = (currentCache, findTag) => { + let currentTags = []; + if ((0, import_obsidian2.getAllTags)(currentCache)) { + currentTags = (0, import_obsidian2.getAllTags)(currentCache); } - 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; + 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; } -} - -// 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; -} - -// 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 []; +}; +var removeTagFromFile = (tag, file) => { + const pos = positionsForTag(tag, file); + removeTagInFrontmatter(tag, file); + editTagInFileBody(tag, "", pos, file); +}; +var validateName = (tag) => { + return tag; +}; +var deleteTag = async (plugin, tag, subTags) => { + const files = getAllFilesForTag(tag).map((f4) => getAbstractFileAtPath(app, f4)).filter((f4) => f4 instanceof import_obsidian2.TFile); + files.forEach((file) => removeTagFromFile(tag, file)); + deleteTagContext(plugin, tag); + if (subTags) { + const tags = getAllSubtags(plugin, tag); + tags.forEach((tag2) => deleteTag(plugin, tag2, subTags)); } - return sign + output; -} - -// 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."; +}; +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_obsidian2.TFile) { + const positions = positionsForTag(tag, tFile); + if (positions.length > 0) { + await editTagInFileBody(tag, newTag, positions, tFile); + } else { + await editTagInFrontmatter(tag, newTag, tFile); + } } - }, - 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); + } + await renameTagContextFile(plugin, tag, toTag); + for (const subtag of tags) { + await renameTag(plugin, subtag, subtag.replace(tag, newTag)); } }; -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 getAllSubtags = (plugin, tag) => { + const tags = loadTags(plugin); + return tags.filter((f4) => f4.startsWith(tag) && f4 != tag); }; -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" +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]); }); + }); + } +}; +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; + } + const addTag2 = (value) => { + if (Array.isArray(value)) { + return uniq([...value, stringFromTag(newTag)]).filter((f4) => f4.length > 0); + } else if (typeof value === "string") { + return serializeMultiDisplayString(uniq([ + ...value.replace(/\s/g, "").split(","), + stringFromTag(newTag) + ]).filter((f4) => f4.length > 0)); } - 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 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; }); - } - 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" + if (editKeys.length > 0) { + editKeys.forEach((key2) => { + app.fileManager.processFrontMatter(file, (frontmatter) => { + frontmatter[key2] = processKey(fm[key2]); + }); }); - case "qqqq": - default: - return localize2.quarter(quarter, { - width: "wide", - context: "standalone" + } else { + app.fileManager.processFrontMatter(file, (frontmatter) => { + frontmatter["tag"] = addTag2(fm["tag"]); }); + } + } else { + app.fileManager.processFrontMatter(file, (frontmatter) => { + frontmatter["tag"] = stringFromTag(newTag); + }); } - }, - 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" - }); + } +}; +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; } - }, - 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" - }); - } - }, - w: function w4(date, token, localize2, options) { - var week = getUTCWeek(date, options); - if (token === "wo") { - return localize2.ordinalNumber(week, { - unit: "week" - }); - } - return addLeadingZeros(week, token.length); - }, - I: function I3(date, token, localize2) { - var isoWeek = getUTCISOWeek(date); - if (token === "Io") { - return localize2.ordinalNumber(isoWeek, { - unit: "week" - }); + 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 allTagsForFile = (file) => { + var _a2, _b2, _c2, _d2, _e2, _f, _g, _h, _i, _j; + let rt = []; + if (file instanceof import_obsidian2.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) + ); + } + return uniq(rt); +}; + +// src/utils/path.ts +var import_obsidian3 = require("obsidian"); +var openPath = (plugin, _path) => { + const { type, path } = _path; + if (type == "file" || type == "folder") { + const afile = getAbstractFileAtPath(app, path); + if (afile) { + openAFile(afile, plugin, false); + } else { + if (type == "file") + createNewMarkdownFile( + plugin, + defaultNoteFolder(plugin, null), + path + ); } - return addLeadingZeros(isoWeek, token.length); + return; + } + if (type == "tag") { + openTagContext(path, plugin, false); + return; + } + if (type == "url") { + openURL(path); + return; + } +}; +var pathByString = (plugin, path, source) => { + const [str, alias] = path.split("|"); + const refIndex = str.lastIndexOf("#"); + const [link2, ref] = refIndex > 0 ? [str.substring(0, refIndex), str.substring(refIndex + 1)] : [str, void 0]; + const type = pathTypeByString(link2, source); + return { + fullPath: path, + path: link2, + type, + alias, + ref + }; +}; +var pathTypeByString = (file, source) => { + if (file.charAt(0) == "#") { + return "tag"; + } + if (file.slice(-2) == "//") { + return "space"; + } + if (file.charAt(file.length - 1) == "/") { + return "folder"; + } + let portalFile; + if (source) { + portalFile = app.metadataCache.getFirstLinkpathDest(file, source); + } else { + portalFile = app.vault.getAbstractFileByPath(file); + } + if (portalFile instanceof import_obsidian3.TFolder) { + return "folder"; + } + if (portalFile instanceof import_obsidian3.TFile) { + return "file"; + } + if (file.match(urlRegex)) + return "url"; + return "unknown"; +}; + +// src/utils/contexts/contexts.ts +var contextEmbedStringFromContext = (context, schema) => { + if (context.type == "folder") + return `![![${context.contextPath}/#^${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" + }; +}; +var tagContextFromTag = (plugin, tag, readOnly) => { + return { + type: "tag", + sticker: "", + banner: "", + contextPath: tag, + isRemote: false, + readOnly, + dbPath: getFolderPathFromString(plugin.settings.tagContextFolder) + "/" + tagToTagPath(tag) + ".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, + isRemote: true, + readOnly: true, + dbPath: url + }; +}; +var mdbContextByPath = (plugin, contextPath) => { + if (!contextPath) + return; + if (contextPath.match(urlRegex)) { + return remoteContextFromURL(plugin, contextPath); + } + 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); + } + return null; +}; +var folderContextFromFolder = (plugin, folder, readOnly) => { + return { + type: "folder", + sticker: "", + banner: "", + contextPath: folder, + isRemote: false, + readOnly, + dbPath: (folder == "/" ? "" : folder + "/") + plugin.settings.folderContextFile + ".mdb" + }; +}; +var linkContextRow = (plugin, row, fields) => { + return { + ...row, + ...fields.filter((f4) => f4.type == "fileprop").reduce((p3, c4) => { + const { field, property } = parsePropString(c4.value); + const col = fields.find((f4) => f4.name == field); + if (!col || !property) { + return p3; + } + if (col.type == "file" || col.type == "link") { + return { + ...p3, + [c4.name]: appendFilesMetaData(plugin, property, row[col.name]) + }; + } + if (col.type.includes("context")) { + const context = col.value; + const contextCache = plugin.index.contextsCache.get(context); + if (contextCache) { + return { + ...p3, + [c4.name]: linkContextProp( + property, + row[col.name], + contextCache.rows + ) + }; + } + } + return p3; + }, {}) + }; +}; +var linkContextProp = (propType, rows, contextTableRows) => { + const contextRows = contextTableRows.filter( + (f4) => parseMultiString(rows).contains(f4.File) + ); + return serializeMultiString(uniq(contextRows.map((f4) => f4[propType]).filter((f4) => f4))); +}; + +// 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, + __rest, + __decorate, + __param, + __esDecorate, + __runInitializers, + __propKey, + __setFunctionName, + __metadata, + __awaiter, + __generator, + __exportStar, + __createBinding, + __values, + __read, + __spread, + __spreadArrays, + __spreadArray, + __await, + __asyncGenerator, + __asyncDelegator, + __asyncValues, + __makeTemplateObject, + __importStar, + __importDefault, + __classPrivateFieldGet, + __classPrivateFieldSet, + __classPrivateFieldIn +} = import_tslib.default; + +// src/cm-extensions/flowEditor/selectiveEditor.ts +var editableRange = import_state3.Annotation.define(); +var hiddenLine = import_view3.Decoration.replace({ inclusive: true }); +var hideLine = import_state3.StateField.define({ + create() { + return import_view3.Decoration.none; }, - d: function d4(date, token, localize2) { - if (token === "do") { - return localize2.ordinalNumber(date.getUTCDate(), { - unit: "date" - }); + update(value, tr) { + var _a2; + let builder = new import_state3.RangeSetBuilder(); + if (((_a2 = tr.state.field(selectiveLinesFacet)) == null ? void 0 : _a2[0]) != void 0) { + const starterLine = Math.min( + tr.state.doc.lines, + tr.state.field(selectiveLinesFacet)[0] + ); + builder.add( + tr.state.doc.line(1).from, + tr.state.doc.line(starterLine).from, + hiddenLine + ); + builder.add( + tr.state.doc.line( + Math.min(tr.newDoc.lines, tr.state.field(selectiveLinesFacet)[1]) + ).to, + tr.state.doc.line(tr.newDoc.lines).to, + hiddenLine + ); } - return lightFormatters_default.d(date, token); + const dec = builder.finish(); + return dec; }, - D: function D2(date, token, localize2) { - var dayOfYear = getUTCDayOfYear(date); - if (token === "Do") { - return localize2.ordinalNumber(dayOfYear, { - unit: "dayOfYear" - }); + provide: (f4) => import_view3.EditorView.decorations.from(f4) +}); +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 addLeadingZeros(dayOfYear, token.length); - }, - E: function E2(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 value; + } +}); +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) => { + var _a2; + if (tr.isUserEvent("delete") && !tr.isUserEvent("delete.smart")) { + const initialSelections = tr.startState.selection.ranges.map((range) => ({ + from: range.from, + to: range.to + })); + if (initialSelections.length > 0 && ((_a2 = tr.startState.field(selectiveLinesFacet)) == null ? void 0 : _a2[0])) { + const posRange = lineRangeToPosRange( + tr.startState, + tr.startState.field(selectiveLinesFacet) + ); + const minFrom = Math.max(posRange.from, initialSelections[0].from); + const minTo = Math.min(posRange.to, initialSelections[0].to); + tr.startState.update({ + changes: { + from: Math.min(minFrom, minTo), + to: Math.max(minFrom, minTo) + }, + annotations: import_state3.Transaction.userEvent.of( + `${tr.annotation(import_state3.Transaction.userEvent)}.smart` + ) }); + } } - }, - 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" - }); + return tr; + } +); +var preventModifyTargetRanges = import_state3.EditorState.transactionFilter.of( + (tr) => { + let newTrans = []; + try { + const selectiveLines = tr.startState.field(selectiveLinesFacet); + if (tr.isUserEvent("input") || tr.isUserEvent("delete") || tr.isUserEvent("move")) { + if (selectiveLines == null ? void 0 : selectiveLines[0]) { + const posRange = lineRangeToPosRange( + tr.startState, + tr.startState.field(selectiveLinesFacet) + ); + if (tr.changes.touchesRange(0, posRange.from - 1) || !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, + tr.startState.field(selectiveLinesFacet) + ); + if (tr.changes.touchesRange(0, posRange.from - 1)) { + newTrans.push({ + annotations: [ + editableRange.of([ + selectiveLines[0] + numberNewLines, + selectiveLines[1] + numberNewLines + ]) + ] + }); + } else if (tr.changes.touchesRange(posRange.from - 1, posRange.to)) { + newTrans.push({ + annotations: [ + editableRange.of([ + selectiveLines[0], + selectiveLines[1] + numberNewLines + ]) + ] + }); + } + } + } + } catch (e4) { + return []; } - }, - 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 [tr, ...newTrans]; + } +); +var readOnlyRangesExtension = [smartDelete, preventModifyTargetRanges]; +var editBlockExtensions = () => [ + readOnlyRangesExtension, + hideLine, + selectiveLinesFacet +]; + +// 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; } - }, - 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" - }); + 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; } - }, - 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" - }); + 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; + } + } + } } - return lightFormatters_default.h(date, token); - }, - H: function H4(date, token, localize2) { - if (token === "Ho") { - return localize2.ordinalNumber(date.getUTCHours(), { - unit: "hour" - }); + return tr; + } +); + +// src/components/ContextView/EmbedContextView.tsx +var import_obsidian29 = 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((ref) => ref(node)); + }, + refs + ); +} +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 isNode(node) { + return "nodeType" in node; +} +function getWindow(target) { + var _target$ownerDocument, _target$ownerDocument2; + if (!target) { + return window; + } + if (isWindow(target)) { + return target; + } + if (!isNode(target)) { + return window; + } + 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; +} +function isHTMLElement(node) { + if (isWindow(node)) { + return false; + } + return node instanceof getWindow(node).HTMLElement; +} +function isSVGElement(node) { + return node instanceof getWindow(node).SVGElement; +} +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; + } + 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 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 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; } - 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 [set, clear]; +} +function useLatestValue(value, dependencies) { + if (dependencies === void 0) { + dependencies = [value]; + } + const valueRef = _2(value); + useIsomorphicLayoutEffect(() => { + if (valueRef.current !== value) { + valueRef.current = value; } - return addLeadingZeros(hours, token.length); - }, - m: function m4(date, token, localize2) { - if (token === "mo") { - return localize2.ordinalNumber(date.getUTCMinutes(), { - unit: "minute" - }); + }, 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 ref = _2(); + p2(() => { + ref.current = value; + }, [value]); + return ref.current; +} +var ids = {}; +function useUniqueId(prefix, value) { + return F2(() => { + if (value) { + return value; } - return lightFormatters_default.m(date, token); - }, - s: function s4(date, token, localize2) { - if (token === "so") { - return localize2.ordinalNumber(date.getUTCSeconds(), { - unit: "second" - }); + 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]; } - 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"; + 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 + }; } - switch (token) { - case "X": - return formatTimezoneWithOptionalMinutes(timezoneOffset); - case "XXXX": - case "XX": - return formatTimezone(timezoneOffset); - case "XXXXX": - case "XXX": - default: - return formatTimezone(timezoneOffset, ":"); + } + 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)"; } }, - 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, ":"); + Scale: { + toString(transform) { + if (!transform) { + return; + } + const { + scaleX, + scaleY + } = transform; + return "scaleX(" + scaleX + ") scaleY(" + scaleY + ")"; } }, - 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, ":"); + Transform: { + toString(transform) { + if (!transform) { + return; + } + return [CSS.Translate.toString(transform), CSS.Scale.toString(transform)].join(" "); } }, - 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, ":"); + Transition: { + toString(_ref) { + let { + property, + duration, + easing + } = _ref; + return property + " " + duration + "ms " + easing; } - }, - 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); - } -}; -function formatTimezoneShort(offset, dirtyDelimiter) { - var sign = offset > 0 ? "-" : "+"; - var absOffset = Math.abs(offset); - var hours = Math.floor(absOffset / 60); - var minutes = absOffset % 60; - if (minutes === 0) { - return sign + String(hours); } - var delimiter = dirtyDelimiter || ""; - return sign + String(hours) + delimiter + addLeadingZeros(minutes, 2); -} -function formatTimezoneWithOptionalMinutes(offset, dirtyDelimiter) { - if (offset % 60 === 0) { - var sign = offset > 0 ? "-" : "+"; - return sign + addLeadingZeros(Math.abs(offset) / 60, 2); +}); +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 formatTimezone(offset, dirtyDelimiter); -} -function formatTimezone(offset, dirtyDelimiter) { - var delimiter = dirtyDelimiter || ""; - var sign = offset > 0 ? "-" : "+"; - var absOffset = Math.abs(offset); - var hours = addLeadingZeros(Math.floor(absOffset / 60), 2); - var minutes = addLeadingZeros(absOffset % 60, 2); - return sign + hours + delimiter + minutes; + return element.querySelector(SELECTOR); } -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" - }); - } +// node_modules/@dnd-kit/accessibility/dist/accessibility.esm.js +var hiddenStyles = { + display: "none" }; -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 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); - } - 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" - }); - break; - } - 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")); - } +function HiddenText(_ref) { + let { + id: id2, + value + } = _ref; + return Cn.createElement("div", { + id: id2, + style: hiddenStyles + }, value); } - -// node_modules/date-fns/esm/locale/en-US/_lib/formatDistance/index.js -var formatDistanceLocale = { - lessThanXSeconds: { - one: "less than a second", - other: "less than {{count}} seconds" - }, - xSeconds: { - one: "1 second", - other: "{{count}} seconds" - }, - halfAMinute: "half a minute", - lessThanXMinutes: { - one: "less than a minute", - other: "less than {{count}} minutes" - }, - xMinutes: { - one: "1 minute", - other: "{{count}} minutes" - }, - aboutXHours: { - one: "about 1 hour", - other: "about {{count}} hours" - }, - xHours: { - one: "1 hour", - other: "{{count}} hours" - }, - xDays: { - one: "1 day", - other: "{{count}} days" - }, - aboutXWeeks: { - one: "about 1 week", - other: "about {{count}} weeks" - }, - xWeeks: { - one: "1 week", - other: "{{count}} weeks" - }, - aboutXMonths: { - one: "about 1 month", - other: "about {{count}} months" - }, - xMonths: { - one: "1 month", - other: "{{count}} months" - }, - aboutXYears: { - one: "about 1 year", - other: "about {{count}} years" - }, - xYears: { - one: "1 year", - other: "{{count}} years" - }, - overXYears: { - one: "over 1 year", - other: "over {{count}} years" - }, - almostXYears: { - one: "almost 1 year", - other: "almost {{count}} years" - } +var 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" }; -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()); - } - if (options !== null && options !== void 0 && options.addSuffix) { - if (options.comparison && options.comparison > 0) { - return "in " + result; - } else { - return result + " ago"; +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); } - } - 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; + }, []); + return { + announce, + announcement }; } -// 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]; +// 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 "); } - var index = args.argumentCallback ? args.argumentCallback(dirtyIndex) : dirtyIndex; - return valuesArray[index]; - }; + const unsubscribe = registerListener(listener); + return unsubscribe; + }, [listener, registerListener]); } - -// 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"] +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 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" +var defaultAnnouncements = { + onDragStart(_ref) { + let { + active + } = _ref; + return "Picked up draggable item " + active.id + "."; }, - wide: { - am: "a.m.", - pm: "p.m.", - midnight: "midnight", - noon: "noon", - morning: "morning", - afternoon: "afternoon", - evening: "evening", - night: "night" - } -}; -var formattingDayPeriodValues = { - narrow: { - am: "a", - pm: "p", - midnight: "mi", - noon: "n", - morning: "in the morning", - afternoon: "in the afternoon", - evening: "in the evening", - night: "at night" + 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."; }, - abbreviated: { - am: "AM", - pm: "PM", - midnight: "midnight", - noon: "noon", - morning: "in the morning", - afternoon: "in the afternoon", - evening: "in the evening", - night: "at night" + 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."; }, - 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" + onDragCancel(_ref4) { + let { + active + } = _ref4; + return "Dragging was cancelled. Draggable item " + active.id + " was dropped."; } }; -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"; +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 number + "th"; -}; -var localize = { - ordinalNumber, - era: buildLocalizeFn({ - values: eraValues, - defaultWidth: "wide" - }), - quarter: buildLocalizeFn({ - values: quarterValues, - defaultWidth: "wide", - argumentCallback: function argumentCallback(quarter) { - return quarter - 1; - } - }), - month: buildLocalizeFn({ - values: monthValues, - defaultWidth: "wide" - }), - day: buildLocalizeFn({ - values: dayValues, - defaultWidth: "wide" - }), - dayPeriod: buildLocalizeFn({ - values: dayPeriodValues, - defaultWidth: "wide", - formattingValues: formattingDayPeriodValues, - defaultFormattingWidth: "wide" - }) -}; -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); - }); - 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 - }; - }; + 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; } -function findKey(object, predicate) { - for (var key2 in object) { - if (object.hasOwnProperty(key2) && predicate(object[key2])) { - return key2; - } - } - return void 0; +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 findIndex(array, predicate) { - for (var key2 = 0; key2 < array.length; key2++) { - if (predicate(array[key2])) { - return key2; - } +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 void 0; + return F2( + () => [...sensors].filter((sensor) => sensor != null), + [...sensors] + ); } - -// 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 - }; - }; +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/locale/en-US/_lib/match/index.js -var matchOrdinalNumberPattern = /^(\d+)(th|st|nd|rd)?/i; -var parseOrdinalNumberPattern = /\d+/i; -var matchEraPatterns = { - narrow: /^(b|a)/i, - abbreviated: /^(b\.?\s?c\.?|b\.?\s?c\.?\s?e\.?|a\.?\s?d\.?|c\.?\s?e\.?)/i, - wide: /^(before christ|before common era|anno domini|common era)/i -}; -var parseEraPatterns = { - any: [/^b/i, /^(a|c)/i] -}; -var matchQuarterPatterns = { - narrow: /^[1234]/i, - abbreviated: /^q[1234]/i, - wide: /^[1234](th|st|nd|rd)? quarter/i -}; -var parseQuarterPatterns = { - any: [/1/i, /2/i, /3/i, /4/i] -}; -var matchMonthPatterns = { - narrow: /^[jfmasond]/i, - abbreviated: /^(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)/i, - wide: /^(january|february|march|april|may|june|july|august|september|october|november|december)/i -}; -var parseMonthPatterns = { - narrow: [/^j/i, /^f/i, /^m/i, /^a/i, /^m/i, /^j/i, /^j/i, /^a/i, /^s/i, /^o/i, /^n/i, /^d/i], - any: [/^ja/i, /^f/i, /^mar/i, /^ap/i, /^may/i, /^jun/i, /^jul/i, /^au/i, /^s/i, /^o/i, /^n/i, /^d/i] -}; -var matchDayPatterns = { - narrow: /^[smtwf]/i, - short: /^(su|mo|tu|we|th|fr|sa)/i, - abbreviated: /^(sun|mon|tue|wed|thu|fri|sat)/i, - wide: /^(sunday|monday|tuesday|wednesday|thursday|friday|saturday)/i -}; -var parseDayPatterns = { - narrow: [/^s/i, /^m/i, /^t/i, /^w/i, /^t/i, /^f/i, /^s/i], - any: [/^su/i, /^m/i, /^tu/i, /^w/i, /^th/i, /^f/i, /^sa/i] -}; -var matchDayPeriodPatterns = { - narrow: /^(a|p|mi|n|(in the|at) (morning|afternoon|evening|night))/i, - any: /^([ap]\.?\s?m\.?|midnight|noon|(in the|at) (morning|afternoon|evening|night))/i -}; -var parseDayPeriodPatterns = { - any: { - am: /^a/i, - pm: /^p/i, - midnight: /^mi/i, - noon: /^no/i, - morning: /morning/i, - afternoon: /afternoon/i, - evening: /evening/i, - night: /night/i - } -}; -var match = { - 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; - } - }), - 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 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"); - } - 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"); - } - if (!locale2.localize) { - throw new RangeError("locale must contain localize property"); - } - if (!locale2.formatLong) { - throw new RangeError("locale must contain formatLong property"); - } - var originalDate = toDate(dirtyDate); - if (!isValid(originalDate)) { - throw new RangeError("Invalid time value"); +function getRelativeTransformOrigin(event, rect) { + const eventCoordinates = getEventCoordinates(event); + if (!eventCoordinates) { + return "0 0"; } - var timezoneOffset = getTimezoneOffsetInMilliseconds(originalDate); - var utcDate = subMilliseconds(originalDate, timezoneOffset); - var formatterOptions = { - firstWeekContainsDate, - weekStartsOn, - locale: locale2, - _originalDate: originalDate + const transformOrigin = { + x: (eventCoordinates.x - rect.left) / rect.width * 100, + y: (eventCoordinates.y - rect.top) / rect.height * 100 }; - 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 substring; - }).join("").match(formattingTokensRegExp).map(function(substring) { - if (substring === "''") { - return "'"; + return transformOrigin.x + "% " + transformOrigin.y + "%"; +} +function sortCollisionsAsc(_ref, _ref2) { + let { + data: { + value: a5 } - var firstCharacter = substring[0]; - if (firstCharacter === "'") { - return cleanEscapedString(substring); + } = _ref; + let { + data: { + value: b4 } - var formatter = formatters_default[firstCharacter]; - if (formatter) { - if (!(options !== null && options !== void 0 && options.useAdditionalWeekYearTokens) && isProtectedWeekYearToken(substring)) { - throwProtectedError(substring, dirtyFormatStr, String(dirtyDate)); - } - if (!(options !== null && options !== void 0 && options.useAdditionalDayOfYearTokens) && isProtectedDayOfYearToken(substring)) { - throwProtectedError(substring, dirtyFormatStr, String(dirtyDate)); - } - return formatter(utcDate, substring, locale2.localize, formatterOptions); + } = _ref2; + return a5 - b4; +} +function sortCollisionsDesc(_ref3, _ref4) { + let { + data: { + value: a5 } - if (firstCharacter.match(unescapedLatinCharacterRegExp)) { - throw new RangeError("Format string contains an unescaped latin alphabet character `" + firstCharacter + "`"); + } = _ref3; + let { + data: { + value: b4 } - return substring; - }).join(""); - return result; + } = _ref4; + return b4 - a5; } -function cleanEscapedString(input) { - var matched = input.match(escapedStringRegExp); - if (!matched) { - return input; - } - return matched[1].replace(doubleQuoteRegExp, "'"); +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/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 getFirstCollision(collisions, property) { + if (!collisions || collisions.length === 0) { + return null; } - return target; -} - -// node_modules/date-fns/esm/_lib/cloneObject/index.js -function cloneObject(object) { - return assign({}, object); + const [firstCollision] = collisions; + return property ? firstCollision[property] : firstCollision; } - -// 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"); +function centerOfRectangle(rect, left, top) { + if (left === void 0) { + left = rect.left; } - 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); + if (top === void 0) { + top = rect.top; } - 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); - } + 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 + } + }); } - } 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); + 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); +}; +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; } - -// 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(); +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 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 + }; } - -// 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 getRectDelta(rect1, rect2) { + return rect1 && rect2 ? { + x: rect1.left - rect2.left, + y: rect1.top - rect2.top + } : defaultCoordinates; } - -// node_modules/date-fns/esm/getTime/index.js -function getTime(dirtyDate) { - requiredArgs(1, arguments); - var date = toDate(dirtyDate); - var timestamp = date.getTime(); - return timestamp; +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 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 + }); + }; } - -// node_modules/date-fns/esm/getUnixTime/index.js -function getUnixTime(dirtyDate) { - requiredArgs(1, arguments); - return Math.floor(getTime(dirtyDate) / 1e3); +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; } - -// 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"); +function inverseTransform(rect, transform, transformOrigin) { + const parsedTransform = parseTransform(transform); + if (!parsedTransform) { + return rect; } - 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; + 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 defaultOptions = { + ignoreTransform: false +}; +function getClientRect(element, options) { + if (options === void 0) { + options = defaultOptions; + } + let rect = element.getBoundingClientRect(); + if (options.ignoreTransform) { + const { + transform, + transformOrigin + } = getWindow(element).getComputedStyle(element); + if (transform) { + rect = inverseTransform(rect, transform, transformOrigin); + } } + const { + top, + left, + width, + height, + bottom, + right + } = rect; + return { + top, + left, + width, + height, + bottom, + right + }; } - -// 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; +function getTransformAgnosticClientRect(element) { + return getClientRect(element, { + ignoreTransform: true + }); } - -// 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; +function getWindowClientRect(element) { + const width = element.innerWidth; + const height = element.innerHeight; + return { + top: 0, + left: 0, + right: width, + bottom: height, + width, + height + }; } - -// 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; +function isFixed(node, computedStyle) { + if (computedStyle === void 0) { + computedStyle = getWindow(node).getComputedStyle(node); + } + return computedStyle.position === "fixed"; } - -// node_modules/date-fns/esm/getWeeksInMonth/index.js -function getWeeksInMonth(date, options) { - requiredArgs(1, arguments); - return differenceInCalendarWeeks(lastDayOfMonth(date), startOfMonth(date), options) + 1; +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; + }); } - -// 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(); +function getScrollableAncestors(element, limit) { + const scrollParents = []; + function findScrollableAncestors(node) { + if (limit != null && scrollParents.length >= limit) { + return scrollParents; + } + if (!node) { + return scrollParents; + } + if (isDocument(node) && node.scrollingElement != null && !scrollParents.includes(node.scrollingElement)) { + scrollParents.push(node.scrollingElement); + return scrollParents; + } + if (!isHTMLElement(node) || isSVGElement(node)) { + return scrollParents; + } + if (scrollParents.includes(node)) { + return scrollParents; + } + 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); } - -// 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(); +function getFirstScrollableAncestor(node) { + const [firstScrollableAncestor] = getScrollableAncestors(node, 1); + return firstScrollableAncestor != null ? firstScrollableAncestor : null; } - -// 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 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; } - -// 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 getScrollXCoordinate(element) { + if (isWindow(element)) { + return element.scrollX; + } + return element.scrollLeft; } - -// node_modules/date-fns/esm/subDays/index.js -function subDays(dirtyDate, dirtyAmount) { - requiredArgs(2, arguments); - var amount = toInteger(dirtyAmount); - return addDays(dirtyDate, -amount); +function getScrollYCoordinate(element) { + if (isWindow(element)) { + return element.scrollY; + } + return element.scrollTop; } - -// 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; +function getScrollCoordinates(element) { + return { + x: getScrollXCoordinate(element), + y: getScrollYCoordinate(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); +var Direction2; +(function(Direction3) { + Direction3[Direction3["Forward"] = 1] = "Forward"; + Direction3[Direction3["Backward"] = -1] = "Backward"; +})(Direction2 || (Direction2 = {})); +function isDocumentScrollingElement(element) { + if (!canUseDOM || !element) { + return false; } - date.setFullYear(year); - return date; + return element === document.scrollingElement; } - -// src/utils/contexts/fm.ts -var import_lodash = __toESM(require_lodash()); -var import_obsidian2 = require("obsidian"); - -// src/utils/contexts/dv.ts -var import_obsidian = 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; +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 }; -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] : `${inputArray.join(", ")}`; - 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}` - }); - } - next = sR.next(); +function getScrollDirectionAndSpeed(scrollContainer, scrollContainerRect, _ref, acceleration, thresholdPercentage) { + let { + top, + left, + right, + bottom + } = _ref; + if (acceleration === void 0) { + acceleration = 10; } - return newFields; -}; -async function replaceValues(plugin, fileOrFilePath, attribute, input, previousItemsCount = 0) { - var _a2, _b2; - let file; - if (fileOrFilePath instanceof import_obsidian.TFile) { - file = fileOrFilePath; - } else { - const _file = plugin.app.vault.getAbstractFileByPath(fileOrFilePath); - if (_file instanceof import_obsidian.TFile && _file.extension == "md") { - file = _file; - } else { - throw Error("path doesn't correspond to a proper file"); - } + if (thresholdPercentage === void 0) { + thresholdPercentage = defaultThreshold; } - 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() : []; - let newValue; - let hiddenValue = ""; - newValue = inputArray.length == 1 ? inputArray[0] : `${inputArray.join(", ")}`; - 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); - } - }); - await plugin.app.vault.modify( - file, - newContent.filter((line, i4) => !skippedLines.includes(i4)).join("\n") - ); - const editor = (_b2 = plugin.app.workspace.getActiveViewOfType(import_obsidian.MarkdownView)) == null ? void 0 : _b2.editor; - if (editor) { - const lineNumber = editor.getCursor().line; - editor.setCursor({ - line: editor.getCursor().line, - ch: editor.getLine(lineNumber).length - }); + 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 + }; } - -// src/utils/contexts/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]); - if (plugin.dataViewAPI()) { - if (plugin.dataViewAPI().page(file.path)[f4] && !frontmatter[f4]) { - replaceValues( - plugin, - file.path, - f4, - valueForDataview(col.type, context[f4]) - ); - } else { - frontmatter[f4] = valueForFrontmatter(col.type, context[f4]); - } - } else { - frontmatter[f4] = valueForFrontmatter(col.type, context[f4]); - } - }); - }); +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 + }; } -}; -var frontMatterForFile = (file) => { - let currentCache; - if (file instanceof import_obsidian2.TFile && app.metadataCache.getFileCache(file) !== null) { - currentCache = app.metadataCache.getFileCache(file); + 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; } - return currentCache == null ? void 0 : currentCache.frontmatter; -}; -var frontMatterKeys = (fm) => { - return Object.keys(fm != null ? fm : {}).filter((f4) => f4 != "position").filter((f4) => f4 != "tag" && f4 != "tags"); -}; -var yamlTypeToMDBType = (YAMLtype) => { - switch (YAMLtype) { - case "duration": - return "text"; - break; - case "unknown": - return "text"; - break; + if (!element) { + return; } - return YAMLtype; -}; -var detectYAMLType = (value, key2) => { - if (typeof value === "string") { - if (/\/\/(\S+?(?:jpe?g|png|gif|svg))/gi.test(value) || value.contains("unsplash")) { - return "image"; - } - if (/^\d{4}-\d{2}-\d{2}$/.test(value)) { - return "date"; - } - if (key2 == "tag" || key2 == "tags") { - return "tag"; - } - if (/\[\[.*?\]\]/.test(value)) { - return "link"; - } - } 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 = splitString(value); - } - if (key2 == "tag" || key2 == "tags") { - return "tag-multi"; - } - if (arrayValue.length == 1 && Array.isArray(arrayValue[0]) && arrayValue[0].length == 1 && typeof arrayValue[0][0] === "string") { - return "link"; - } - const types = uniq(arrayValue.map((f4) => detectYAMLType(f4, key2))); - if (types.length == 1 && types[0] == "link") { - return "link-multi"; - } - 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"; + const { + top, + left, + bottom, + right + } = measure(element); + const firstScrollableAncestor = getFirstScrollableAncestor(element); + if (!firstScrollableAncestor) { + return; } - return "text"; -}; -var mergeTableData = (mdb, yamlmdb, types) => { - 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; - }) - }; -}; -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) }), - {} - ); - }); - 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 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 splitString(value).map( - (f4) => valueForFrontmatter(type.replace("-multi", ""), f4) - ); - } else if (type.contains("link") || type.contains("context")) { - return `[[${value}]]`; + if (bottom <= 0 || right <= 0 || top >= window.innerHeight || left >= window.innerWidth) { + element.scrollIntoView({ + block: "center", + inline: "center" + }); } - return value; -}; -var valueForDataview = (type, value) => { - if (type.contains("link") || type.contains("context")) { - return `[[${value}]]`; +} +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 + }); } - return value; }; -var renameFrontmatterKey = (plugin, path, key2, name) => { - const afile = getAbstractFileAtPath(app, path); - if (afile && afile instanceof import_obsidian2.TFile) { - if (app.fileManager.processFrontMatter) { - app.fileManager.processFrontMatter(afile, (frontmatter) => { - if (key2 in frontmatter) { - frontmatter[name] = frontmatter[key2]; - delete frontmatter[key2]; - } +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 defaultValueForType = (value, type) => { - if (type == "date") { - return format(Date.now(), "yyyy-MM-dd"); +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 (type == "number") { - return 0; + if ("x" in measurement && "y" in measurement) { + return dx > measurement.x && dy > measurement.y; } - if (type == "boolean") { - return true; + if ("x" in measurement) { + return dx > measurement.x; } - if (type == "link") { - return "[[Select Note]]"; + if ("y" in measurement) { + return dy > measurement.y; } - if (type == "option") { - return "one, two"; + 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 + }; } - if (type == "text") { - return " "; + 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(); } - 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"; + 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)); } -}; -var changeFrontmatterType = (plugin, path, key2, type) => { - const afile = getAbstractFileAtPath(app, path); - if (afile && afile instanceof import_obsidian2.TFile) { - if (app.fileManager.processFrontMatter) { - app.fileManager.processFrontMatter(afile, (frontmatter) => { - if (key2 in frontmatter) { - frontmatter[key2] = defaultValueForType(frontmatter[key2], type); - } - }); + handleStart() { + const { + activeNode, + onStart + } = this.props; + const node = activeNode.node.current; + if (node) { + scrollIntoViewIfNeeded(node); } + onStart(defaultCoordinates); } -}; -var deleteFrontmatterValue = (plugin, path, key2) => { - const afile = getAbstractFileAtPath(app, path); - if (afile && afile instanceof import_obsidian2.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]; + 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 + }); + 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; } - } - } else { - if (key2 in frontmatter) { - delete frontmatter[key2]; + 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(); + } }; -var saveFrontmatterValue = (plugin, path, key2, value, type, forceSave) => { - const afile = getAbstractFileAtPath(app, path); - if (afile && afile instanceof import_obsidian2.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, 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); - } - } +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; } -}; -var parseFrontMatter = (field, value, dv) => { - 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": - if (!dv) { - return value; - } else { - return format(new Date(value.ts), "yyyy-MM-dd"); +}]; +function isDistanceConstraint(constraint) { + return Boolean(constraint && "distance" in constraint); +} +function isDelayConstraint(constraint) { + return Boolean(constraint && "delay" in constraint); +} +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(); + } + attach() { + const { + events: events2, + props: { + options: { + activationConstraint + } } - break; - case "duration": - return Object.keys(value.values).reduce( - (p3, c4) => [ - ...p3, - ...value.values[c4] > 0 ? [value.values[c4] + " " + c4] : [] - ], - [] - ).join(", "); - break; - case "option-multi": - case "link-multi": - if (typeof value === "string") { - return value; + } = 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; } - return value.map((v3) => { - if (typeof v3 === "string") { - return v3; - } - if (v3.path) { - return v3.path; + if (isDelayConstraint(activationConstraint)) { + this.timeoutId = setTimeout(this.handleStart, activationConstraint.delay); + return; + } + } + this.handleStart(); + } + detach() { + this.listeners.removeAll(); + this.windowListeners.removeAll(); + setTimeout(this.documentListeners.removeAll, 50); + if (this.timeoutId !== null) { + clearTimeout(this.timeoutId); + this.timeoutId = null; + } + } + 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); + } + } + 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(); } - 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; + } + if (isDistanceConstraint(activationConstraint)) { + if (activationConstraint.tolerance != null && hasExceededDistance(delta, activationConstraint.tolerance)) { + return this.handleCancel(); } - return JSON.stringify(v3); - }).join(","); - 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; + if (hasExceededDistance(delta, activationConstraint.distance)) { + return this.handleStart(); } - return value.path; + return; } - break; - case "text": - case "tag": - case "image": - return value; - break; - } - return ""; -}; - -// src/dispatch/mdb.ts -var dispatchDatabaseFileChanged = (dbPath) => { - let evt = new CustomEvent(eventTypes.mdbChange, { detail: { dbPath } }); - window.dispatchEvent(evt); -}; -var processFolderDB = async (plugin, folderPath, processor, fallback) => { - let tags = []; - const folderContext = folderContextFromFolder(plugin, folderPath); - const dbFileExists = getAbstractFileAtPath(app, folderContext.dbPath); - if (dbFileExists) { - const folderDB = await getMDBTable(plugin, folderContext, "files"); - if (folderDB) { - tags.push(...folderDB.schema.def.split("&")); - const newDB = await processor(folderDB, folderContext); - const promises = tags.map((tag) => { - const tagContext = tagContextFromTag(plugin, tag); - const tagFileExists = getAbstractFileAtPath(app, tagContext.dbPath); - if (tagFileExists) { - return consolidateRowsToTag( - plugin, - tagContext, - "files", - folderContext.dbPath, - newDB.rows - ).then((f4) => { - }); - } - }); - return Promise.all(promises); - } else if (fallback) { - await fallback(); } - } else if (fallback) { - await fallback(); + if (event.cancelable) { + event.preventDefault(); + } + onMove(coordinates); } -}; -var saveDB = async (plugin, context, newTable) => { - return saveMDBToPath(plugin, context, newTable); -}; -var renameRow = (folder, filePath, toFilePath) => { - return { - ...folder, - rows: folder.rows.map( - (f4) => f4.File == filePath && f4._source == "folder" ? { ...f4, File: toFilePath } : f4 - ) - }; -}; -var removeRows = (folder, source) => { - return { ...folder, rows: folder.rows.filter((f4) => f4._source != source) }; -}; -var removeRow = (folder, filePath) => { - return { - ...folder, - rows: folder.rows.filter( - (f4) => f4.File != filePath && f4._source == "folder" - ) - }; -}; -var insertRow = (folder, row, parent) => { - const existingRow = folder.rows.find( - (f4) => f4.File == row.File || parent + "/" + f4.File + ".md" == row.File - ); - if (existingRow) { - return { - ...folder, - rows: folder.rows.map( - (f4) => f4.File == existingRow.File ? { ...f4, File: row.File, _source: "folder", ...row } : f4 - ) - }; + handleEnd() { + const { + onEnd + } = this.props; + this.detach(); + onEnd(); } - return { ...folder, rows: [...folder.rows, row] }; -}; -var insertColumns = (table, column) => { - if (table.cols.find((f4) => f4.name == column.name)) { - new import_obsidian3.Notice(i18n_default.notice.duplicatePropertyName); - return; + handleCancel() { + const { + onCancel + } = this.props; + this.detach(); + onCancel(); } - return { - ...table, - cols: [...table.cols, column] - }; -}; -var updateValue = (folder, lookupField, lookupValue, field, value) => { - return { - ...folder, - rows: folder.rows.map( - (f4) => f4[lookupField] == lookupValue ? { - ...f4, - [field]: value - } : f4 - ) - }; -}; -var insertRows = (folder, rows) => { - const newRows = rows.filter( - (row) => { - var _a2; - return ((_a2 = row.File) == null ? void 0 : _a2.length) > 0 && !folder.rows.some((f4) => f4.File == row.File && f4._source == "folder"); + handleKeydown(event) { + if (event.code === KeyboardCode.Esc) { + this.handleCancel(); } - ); - return { ...folder, rows: [...folder.rows, ...newRows] }; -}; -var saveContextToFrontmatter = (file, cols, context, plugin) => { - const afile = getAbstractFileAtPath(app, file); - if (afile && afile instanceof import_obsidian3.TFile) - saveContextToFile(afile, cols, context, plugin); -}; -var removeSourceFromTag = async (plugin, tag, source) => { - const context = tagContextFromTag(plugin, tag); - const tagFileExists = getAbstractFileAtPath(app, context.dbPath); - if (tagFileExists) { - const tagDB = await getMDBTable(plugin, context, "files"); - const files = tagDB.rows.filter((f4) => f4._source == source); - files.forEach( - (row) => saveContextToFrontmatter( - row["File"], - tagDB.cols, - tagDB.cols.reduce((p3, c4) => ({ ...p3, [c4.name]: row[c4.name] }), {}), - plugin - ) - ); - await saveDB(plugin, context, removeRows(tagDB, source)); - await disconnectContext(plugin, tag, source); + } + removeTextSelection() { + var _this$document$getSel; + (_this$document$getSel = this.document.getSelection()) == null ? void 0 : _this$document$getSel.removeAllRanges(); } }; -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) => { - const tagFileExists = getAbstractFileAtPath(app, context.dbPath); - if (!tagFileExists) { - await createDefaultDB(plugin, context); +var events = { + move: { + name: "pointermove" + }, + end: { + name: "pointerup" } - await getMDBTable(plugin, context, "files").then( - (tagDB) => saveDB(plugin, context, updateValue(tagDB, "File", file, field, value)) - ).then((f4) => dispatchDatabaseFileChanged(context.dbPath)); }; -var insertContextColumn = async (plugin, context, field) => { - const saveNewContextColumns = async (table, field2) => { - await saveDB(plugin, context, insertColumns(table, field2)); - }; - const tagFileExists = getAbstractFileAtPath(app, context.dbPath); - if (!tagFileExists) { - await createDefaultDB(plugin, context); +var PointerSensor = class extends AbstractPointerSensor { + constructor(props2) { + const { + event + } = props2; + const listenerTarget = getOwnerDocument(event.target); + super(props2, events, listenerTarget); } - await getMDBTable(plugin, context, "files").then( - (tagDB) => saveNewContextColumns(tagDB, field).then((f4) => { - dispatchDatabaseFileChanged(context.dbPath); - }) - ); }; -var columnsForContext = async (plugin, context) => { - return getMDBTable(plugin, context, "files").then( - (tagDB) => { - var _a2; - return (_a2 = tagDB == null ? void 0 : tagDB.cols) != null ? _a2 : []; +PointerSensor.activators = [{ + eventName: "onPointerDown", + handler: (_ref, _ref2) => { + let { + nativeEvent: event + } = _ref; + let { + onActivation + } = _ref2; + if (!event.isPrimary || event.button !== 0) { + return false; } - ); -}; -var insertContextItems = async (plugin, newPaths, t4) => { - const saveNewContextRows = async (tag, context2) => { - const newRow = newPaths.map((newPath) => ({ File: newPath })); - await saveDB(plugin, context2, insertRows(tag, newRow)); - }; - const context = tagContextFromTag(plugin, t4); - const tagFileExists = getAbstractFileAtPath(app, context.dbPath); - if (!tagFileExists) { - await createDefaultDB(plugin, context); + onActivation == null ? void 0 : onActivation({ + event + }); + return true; + } +}]; +var events$1 = { + move: { + name: "mousemove" + }, + end: { + name: "mouseup" } - await getMDBTable(plugin, context, "files").then( - (tagDB) => saveNewContextRows(tagDB, context) - ); }; -var fileToFM = (file, cols, plugin) => { - const fm = frontMatterForFile(file); - const fmKeys = frontMatterKeys(fm).filter((f4) => cols.some((g4) => f4 == g4)); - const rows = fmKeys.reduce( - (p3, c4) => ({ ...p3, [c4]: parseFrontMatter(c4, fm[c4], false) }), - {} - ); - if (plugin.dataViewAPI()) { - return { ...rows, ...fileToDV(file, cols, plugin) }; +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)); } - return rows; -}; -var fileToDV = (file, cols, plugin) => { - const dvValues = plugin.dataViewAPI().page(file.path); - const fmKeys = 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") - ).filter((f4) => cols.some((g4) => f4 == g4)); - return fmKeys.reduce( - (p3, c4) => ({ - ...p3, - [c4]: parseFrontMatter(c4, dvValues[c4], true) - }), - {} - ); }; -var onMetadataChange = async (plugin, file) => { - const folderPath = getFolderPathFromString(file.path); - let tags = []; - const folderContext = folderContextFromFolder(plugin, folderPath); - const dbFileExists = getAbstractFileAtPath(app, folderContext.dbPath); - if (dbFileExists) { - const folderDB = await getMDBTable(plugin, folderContext, "files"); - if (folderDB) { - tags.push(...folderDB.schema.def.split("&")); - const newDB = { - ...folderDB, - rows: folderDB.rows.map( - (f4) => f4.File == file.path && f4._source == "folder" ? { - ...f4, - ...fileToFM( - file, - folderDB.cols.map((f5) => f5.name), - plugin - ) - } : f4 - ) - }; - const dbChanged = !import_lodash2.default.isEqual(folderDB.rows, newDB.rows); - if (dbChanged) { - await saveDB(plugin, folderContext, newDB); - } - const promises = tags.map((tag) => { - const tagContext = tagContextFromTag(plugin, tag); - const tagFileExists = getAbstractFileAtPath(app, tagContext.dbPath); - if (tagFileExists) { - return getMDBTable(plugin, tagContext, "files").then((tagDB) => { - const newDB2 = { - ...tagDB, - rows: tagDB.rows.map( - (f4) => f4.File == file.path && f4._source == folderContext.dbPath ? { - ...f4, - ...fileToFM( - file, - tagDB.cols.map((f5) => f5.name), - plugin - ) - } : f4 - ) - }; - const dbChanged2 = !import_lodash2.default.isEqual(tagDB.rows, newDB2.rows); - if (dbChanged2) { - return saveDB(plugin, tagContext, newDB2); - } - return; - }); - } - }); - await Promise.all(promises); +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 events$2 = { + move: { + name: "touchmove" + }, + end: { + name: "touchend" } }; -var onFileCreated = async (plugin, newPath) => { - const newFolderPath = getFolderPathFromString(newPath); - await processFolderDB(plugin, newFolderPath, async (folder, path) => { - const amendedFolderDB = insertRow( - folder, - newRowByDBRow({ File: newPath, _source: "folder" }), - newFolderPath - ); - await saveDB(plugin, path, amendedFolderDB); - return amendedFolderDB; - }); +var TouchSensor = class extends AbstractPointerSensor { + constructor(props2) { + super(props2, events$2); + } + 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 onFileChanged = async (plugin, oldPath, newPath) => { - const oldFolderPath = getFolderPathFromString(oldPath); - const newFolderPath = getFolderPathFromString(newPath); - if (oldFolderPath == newFolderPath) { - await processFolderDB(plugin, oldFolderPath, async (folder, context) => { - const amendedFolderDB = renameRow(folder, oldPath, newPath); - await saveDB(plugin, context, amendedFolderDB); - return amendedFolderDB; +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 }); - } else { - await processFolderDB( - plugin, - oldFolderPath, - async (folder, context) => { - const amendedFolderDB = removeRow(folder, oldPath); - await saveDB(plugin, context, amendedFolderDB); - const folderContext = folderContextFromFolder(plugin, newFolderPath); - const fromDBRow = folder.rows.find((f4) => f4.File == oldPath); - const toDBFileExists = getAbstractFileAtPath(app, folderContext.dbPath); - if (toDBFileExists) { - const toFolderDB = await getMDBTable(plugin, folderContext, "files"); - if (toFolderDB) { - const [newDBCols, fmDBCols] = Object.keys(fromDBRow).reduce( - (p3, c4) => fromDBRow[c4].length == 0 ? p3 : toFolderDB.cols.find((f4) => f4.name == fromDBRow[c4]) ? [[...p3[0], c4], p3[1]] : [p3[0], [...p3[1], c4]], - [[], []] - ); - const newRow = { - ...newDBCols.reduce((p3, c4) => ({ ...p3, [c4]: fromDBRow[c4] }), {}), - File: newPath - }; - await saveDB( - plugin, - folderContext, - insertRow(toFolderDB, newRowByDBRow(newRow), newFolderPath) - ); - saveContextToFrontmatter( - newPath, - folder.cols, - fmDBCols.reduce((p3, c4) => ({ ...p3, [c4]: fromDBRow[c4] }), {}), - plugin - ); + return true; + } +}]; +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; } - } else { - saveContextToFrontmatter( - newPath, - folder.cols, - Object.keys(fromDBRow).reduce( - (p3, c4) => ({ ...p3, [c4]: fromDBRow[c4] }), - {} - ), - plugin - ); } - return amendedFolderDB; - }, - async () => { - const folderContext = folderContextFromFolder(plugin, newFolderPath); - const toDBFileExists = getAbstractFileAtPath(app, folderContext.dbPath); - if (toDBFileExists) { - const toFolderDB = await getMDBTable(plugin, folderContext, "files"); + 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 } }; -var onFileDeleted = async (plugin, oldPath) => { - const oldFolderPath = getFolderPathFromString(oldPath); - await processFolderDB(plugin, oldFolderPath, async (folder, context) => { - const amendedFolderDB = removeRow(folder, oldPath); - await saveDB(plugin, context, amendedFolderDB); - return amendedFolderDB; - }); -}; -var onFolderChanged = async (plugin, oldPath, newPath) => { - await processFolderDB(plugin, newPath, async (folder, context) => { - const newDB = { - ...folder, - rows: folder.rows.map( - (f4) => getFolderPathFromString(f4["File"]) == oldPath ? { ...f4, File: f4["File"].replace(oldPath, newPath) } : f4 - ) +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) }; - await saveDB(plugin, context, newDB); - return newDB; - }); -}; -var onFolderDeleted = async (oldPath) => { -}; - -// src/utils/db/db.ts -var import_obsidian4 = require("obsidian"); -var getDBFile = async (path, isRemote) => { - if (isRemote) { - return fetch(path).then((res) => res.arrayBuffer()); - } - if (!await app.vault.adapter.exists((0, import_obsidian4.normalizePath)(path))) { - return null; - } - const file = await app.vault.adapter.readBinary( - (0, import_obsidian4.normalizePath)(path) + 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; + } + 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; + } + 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; + } + return previousValue; + }, [containers, queue, dragging, disabled, measure]); + p2(() => { + containersRef.current = containers; + }, [containers]); + p2( + () => { + if (disabled) { + return; + } + measureDroppableContainers(); + }, + [dragging, disabled] ); - return file; -}; -var getDB = async (sqlJS, path, isRemote) => { - const buf = await getDBFile(path, isRemote); - if (buf) { - return new sqlJS.Database(new Uint8Array(buf)); - } - return new sqlJS.Database(); -}; -var saveDBAndKeepAlive = (db, path) => { - const results = saveDBFile(path, db.export().buffer); - return results; -}; -var saveAndCloseDB = async (db, path) => { - await saveDBFile(path, db.export().buffer); - db.close(); -}; -var saveDBFile = async (path, binary) => { - const file = app.vault.adapter.writeBinary( - (0, import_obsidian4.normalizePath)(path), - binary + p2( + () => { + if (queue && queue.length > 0) { + setQueue(null); + } + }, + [JSON.stringify(queue)] ); - 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] }), - {} - ) - ) : [] + p2( + () => { + if (disabled || typeof frequency !== "number" || timeoutId.current !== null) { + return; } - ], - [] + timeoutId.current = setTimeout(() => { + measureDroppableContainers(); + timeoutId.current = null; + }, frequency); + }, + [frequency, disabled, measureDroppableContainers, ...dependencies] ); -}; -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; - } - if (tables.length == 1) - return tables[0]; - return null; -}; -var updateDB = (db, tables, updateCol, updateRef) => { - const sqlstr = Object.keys(tables).map((t4) => { - const tableFields = tables[t4].cols.filter((f4) => f4 != updateRef); - const rowsQuery = tables[t4].rows.reduce((prev, curr) => { - var _a2; - return `${prev} UPDATE "${t4}" SET ${tableFields.map((c4) => { - var _a3; - return `${c4}='${(_a3 = sanitizeSQLStatement(curr == null ? void 0 : curr[c4])) != null ? _a3 : ""}'`; - }).join(", ")} WHERE ${updateCol}='${(_a2 = sanitizeSQLStatement(curr == null ? void 0 : curr[updateRef])) != null ? _a2 : ""}';`; - }, ""); - return rowsQuery; - }).join("; "); - try { - db.exec(sqlstr); - } catch (e4) { - console.log(e4); - } -}; -var execQuery = (db, sqlstr) => { - try { - db.exec(sqlstr); - } catch (e4) { - console.log(e4); - } -}; -var deleteFromDB = (db, table, condition) => { - const sqlstr = `DELETE FROM "${table}" WHERE ${condition};`; - try { - db.exec(sqlstr); - } catch (e4) { - console.log(e4); - } -}; -var dropTable = (db, table) => { - const sqlstr = `DROP TABLE IF EXISTS "${table}";`; - try { - db.exec(sqlstr); - } catch (e4) { - console.log(e4); - } -}; -var insertIntoDB = (db, tables, replace) => { - const sqlstr = Object.keys(tables).map((t4) => { - const tableFields = tables[t4].cols; - const rowsQuery = tables[t4].rows.reduce((prev, curr) => { - return `${prev} ${replace ? "REPLACE" : "INSERT"} INTO "${t4}" VALUES (${tableFields.map((c4) => { - var _a2; - return `'${(_a2 = sanitizeSQLStatement(curr == null ? void 0 : curr[c4])) != null ? _a2 : ""}'`; - }).join(", ")});`; - }, ""); - return rowsQuery; - }).join("; "); - try { - db.exec(`BEGIN TRANSACTION; ${sqlstr} COMMIT;`); - } catch (e4) { - console.log(e4); - } -}; -var replaceDB = (db, tables) => { - const sqlstr = Object.keys(tables).map((t4) => { - const tableFields = tables[t4].cols; - const fieldQuery = uniq(tableFields).map((f4) => `'${sanitizeSQLStatement(f4)}' char`).join(", "); - const rowsQuery = tables[t4].rows.reduce((prev, curr) => { - return `${prev} REPLACE INTO "${t4}" VALUES (${tableFields.map((c4) => { - var _a2; - return `'${(_a2 = sanitizeSQLStatement(curr == null ? void 0 : curr[c4])) != null ? _a2 : ""}'`; - }).join(", ")});`; - }, ""); - 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 TABLE IF EXISTS "${t4}"; ${fieldQuery.length > 0 ? insertQuery : ""}`; - }).join("; "); - try { - db.exec(sqlstr); - } catch (e4) { - console.log(e4); - } -}; -var saveDBToPath = async (plugin, path, tables) => { - const sqlJS = await plugin.sqlJS(); - let db = await getDB(sqlJS, path); - replaceDB(db, tables); - await saveDBFile(path, db.export().buffer); - dispatchDatabaseFileChanged(path); - db.close(); - return true; -}; - -// 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, 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) => { - 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 ${fields.reduce((p3, c4) => [...p3, `"${c4.name}"`], []).join(", ")} 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 getMDBSchema = async (plugin, context, schema) => { - 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 tables = db.exec( - `SELECT * FROM m_schema WHERE id='${sanitizeSQLStatement(schema)}'` - ); - db.close(); - if (!tables[0] || !tables[0].values[0]) { - return null; - } - return tables[0].values.map((f4) => { - const [id2, name, type, def, predicate, primary] = f4; - return { id: id2, name, type, def, predicate, primary }; - })[0]; -}; -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; + droppableRects, + measureDroppableContainers, + measuringScheduled: queue != null + }; + function isDisabled() { + switch (strategy) { + case MeasuringStrategy.Always: + return false; + case MeasuringStrategy.BeforeDragging: + return dragging; + default: + return !dragging; + } } - 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: mdb.cols.filter((c4) => c4.unique == "true").map((c4) => c4.name), - cols: mdb.cols.map((c4) => c4.name), - rows: mdb.rows +} +function useInitialValue(value, computeFn) { + return useLazyMemo((previousValue) => { + if (!value) { + return null; } - }; - db.close(); - return saveDBToPath(plugin, context.dbPath, tables); -}; -var optionValuesForColumn = (column, table) => { - var _a2; - return uniq( - (_a2 = table == null ? void 0 : table.rows.reduce((p3, c4) => { - return [...p3, ...splitString(c4[column])]; - }, [])) != null ? _a2 : [] - ); -}; -var createDefaultDB = async (plugin, context) => { - const sqlJS = await plugin.sqlJS(); - const table = defaultTablesForContext(context); - return saveDBToPath(plugin, context.dbPath, table); -}; -var sanitizeTableSchema = async (plugin, db, context) => { - const sqlJS = await plugin.sqlJS(); - const tableRes = db.exec( - `SELECT name FROM sqlite_master WHERE type='table';` + if (previousValue) { + return previousValue; + } + return typeof computeFn === "function" ? computeFn(value) : value; + }, [computeFn, value]); +} +function useInitialRect(node, measure) { + return useInitialValue(node, measure); +} +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; + } + const { + MutationObserver + } = window; + return new MutationObserver(handleMutations); + }, [handleMutations, disabled]); + p2(() => { + return () => mutationObserver == null ? void 0 : mutationObserver.disconnect(); + }, [mutationObserver]); + return mutationObserver; +} +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] ); - 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 createDefaultDB(plugin, context); - } -}; -var newRowByDBRow = (row) => ({ - _id: genId(), - ...row -}); -var rowWithID = (row, tag) => { - return row._id && row._id.length > 0 ? row : { - ...newRowByDBRow({ ...row, _source: tag ? "tag" : "folder" }) - }; -}; -var createNewRow = (mdb, row, index) => { - if (index) { - return { - ...mdb, - rows: insert(mdb.rows, index, newRowByDBRow(row)) - }; - } - return { - ...mdb, - rows: [...mdb.rows, newRowByDBRow(row)] - }; -}; -var consolidateFilesToTable = async (plugin, context, table, files) => { - const sqlJS = await plugin.sqlJS(); - const isTag = context.type == "tag" ? true : false; - let db; - if (getAbstractFileAtPath(app, context.dbPath)) { - const buf = await getDBFile(context.dbPath, context.isRemote); - db = new sqlJS.Database(new Uint8Array(buf)); - } else { - db = new sqlJS.Database(); - await createDefaultDB(plugin, context); + p2(() => { + return () => resizeObserver == null ? void 0 : resizeObserver.disconnect(); + }, [resizeObserver]); + return resizeObserver; +} +function defaultMeasure(element) { + return new Rect(getClientRect(element), element); +} +function useRect(element, measure, fallbackRect) { + if (measure === void 0) { + measure = defaultMeasure; } - const mdbTable = await getMDBTable(plugin, context, table); - const missingFiles = files.filter((f4) => !(mdbTable == null ? void 0 : mdbTable.rows.some((g4) => g4.File == f4 && g4._source != ""))).map((f4) => ({ File: f4 })); - const mergeDuplicates = (rows) => { - const mergeFields = (row, row2) => { - return { ...row, ...row2 }; - }; - return rows.reduce((p3, c4) => { - const findIndex2 = p3.findIndex((f4) => f4._source != "" && f4.File == c4.File); - if (findIndex2 != -1) { - return p3.map((f4, i4) => i4 == findIndex2 ? mergeFields(f4, c4) : f4); + const [rect, measureRect] = s2(reducer2, null); + const mutationObserver = useMutationObserver({ + callback(records) { + if (!element) { + return; } - return [...p3, c4]; - }, []); - }; - let linkedFolderContexts = [""]; - if (isTag) { - const contexts = uniq( - mdbTable.rows.map((f4) => f4._source).filter((f4) => f4 != "" && f4 != "tag") - ); - const promises = contexts.map( - (c4) => getMDBTable(plugin, mdbContextByDBPath(plugin, c4), "files").then((f4) => [ - f4, - c4 - ]) - ); - const results = await Promise.all(promises); - linkedFolderContexts.push( - ...results.filter( - ([f4, g4]) => { - var _a2, _b2; - return (_b2 = (_a2 = f4 == null ? void 0 : f4.schema) == null ? void 0 : _a2.def) == null ? void 0 : _b2.split("&").some((h5) => h5 == context.contextPath); + for (const record of records) { + const { + type, + target + } = record; + if (type === "childList" && target instanceof HTMLElement && target.contains(element)) { + measureRect(); + break; } - ).map(([f4, g4]) => g4) - ); - } - const nonLinkedRows = mdbTable.rows.filter( - (f4) => linkedFolderContexts.some((g4) => g4 == f4._source) && !missingFiles.some((g4) => f4.File == g4.File) - ); - const newRows = [ - ...nonLinkedRows, - ...[ - ...mergeDuplicates( - mdbTable.rows.filter( - (f4) => (f4._source != "" || missingFiles.some((g4) => f4.File == g4.File)) && files.some((g4) => g4 == f4.File) - ) - ), - ...missingFiles - ].map((f4) => rowWithID(f4, isTag)) - ]; - const newCols = [ - ...(isTag ? defaultTagFields : defaultFolderFields).rows, - ...mdbTable.cols - ].filter(onlyUniqueProp("name")); - const newMDBTable = { - ...mdbTable, - cols: newCols, - rows: newRows - }; - const dbChanged = !import_lodash3.default.isEqual(newMDBTable, mdbTable); - if (dbChanged) { - await saveMDBToPath(plugin, context, newMDBTable); - } - db.close(); - return newMDBTable; -}; -var consolidateRowsToTag = async (plugin, context, table, source, rows) => { - const sqlJS = await plugin.sqlJS(); - if (getAbstractFileAtPath(app, context.dbPath)) { - } else { - await createDefaultDB(plugin, context); - } - const mdbTable = await getMDBTable(plugin, context, table); - const prevRows = mdbTable.rows.map((f4) => { - if (f4._source != source) { - return f4; - } - const row = rows.find((g4) => g4._id == f4._sourceId); - return row ? { ...f4, File: row["File"] } : f4; - }).filter( - (f4) => f4._source != source || rows.some((g4) => g4._id == f4._sourceId) - ); - const missingRows = rows.filter( - (f4) => !mdbTable.rows.some((g4) => g4._source == source && g4._sourceId == f4._id) - ).map( - (f4) => newRowByDBRow({ File: f4.File, _source: source, _sourceId: f4._id }) - ); - const newRows = [...prevRows, ...missingRows]; - const newMDBTable = { - ...mdbTable, - cols: [...defaultTagFields.rows, ...mdbTable.cols].filter( - onlyUniqueProp("name") - ), - rows: newRows - }; - const dbChanged = !import_lodash3.default.isEqual(newMDBTable, mdbTable); - if (dbChanged) { - await saveMDBToPath(plugin, context, newMDBTable); - } - return newMDBTable; -}; -var deleteTagContext = async (plugin, tag) => { - const context = tagContextFromTag(plugin, tag); - if (getAbstractFileAtPath(app, context.dbPath)) { - await deleteFile(plugin, getAbstractFileAtPath(app, context.dbPath)); - } - app.workspace.iterateLeaves((leaf) => { - if (leaf.view.getViewType() == CONTEXT_VIEW_TYPE && leaf.view.getState().contextPath == tag) { - leaf.setViewState({ type: "empty" }); + } } - }, app.workspace["rootSplit"]); - let event = new CustomEvent(eventTypes.metadataChange, { - detail: { tags: [tag] } }); - window.dispatchEvent(event); -}; -var connectContext = async (plugin, tag, source) => { - var _a2; - const context = tagContextFromTag(plugin, tag); - if (getAbstractFileAtPath(app, context.dbPath)) { - const sqlJS = await plugin.sqlJS(); - const db = await getDB(sqlJS, context.dbPath); - let table = selectDB(db, "m_context"); - if (!table) { - execQuery(db, `CREATE TABLE IF NOT EXISTS "m_context" (source);`); - table = { uniques: [], cols: ["source"], rows: [] }; - } - const contextExists = ((_a2 = selectDB(db, "m_context", `source='${source}'`)) == null ? void 0 : _a2.rows.length) > 0; - if (!contextExists) { - insertIntoDB(db, { m_context: { ...table, rows: [{ source }] } }, true); - saveAndCloseDB(db, context.dbPath); + 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 { - db.close(); + resizeObserver == null ? void 0 : resizeObserver.disconnect(); + mutationObserver == null ? void 0 : mutationObserver.disconnect(); } - } -}; -var disconnectContext = async (plugin, tag, source) => { - const context = tagContextFromTag(plugin, tag); - if (getAbstractFileAtPath(app, context.dbPath)) { - const sqlJS = await plugin.sqlJS(); - const db = await getDB(sqlJS, context.dbPath); - let table = selectDB(db, "m_context"); - if (!table) { - execQuery(db, `CREATE TABLE IF NOT EXISTS "m_context" (source);`); + }, [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; + } + const newRect = measure(element); + if (JSON.stringify(currentRect) === JSON.stringify(newRect)) { + return currentRect; } - deleteFromDB(db, "m_context", `source = '${source}'`); - saveAndCloseDB(db, context.dbPath); + return newRect; } -}; -var renameTagContext = 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( - getAbstractFileAtPath(app, context.dbPath), - tagToTagPath(newTag) + ".mdb" - ); - } else { - await deleteFile(plugin, getAbstractFileAtPath(app, context.dbPath)); +} +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; } - 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 } - }); + 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; +} +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; } - }, app.workspace["rootSplit"]); - const sqlJS = await plugin.sqlJS(); - const db = await getDB(sqlJS, newTagDBPath); - let table = selectDB(db, "m_context"); - if (!table) { - execQuery(db, `CREATE TABLE IF NOT EXISTS "m_context" (source);`); - } - const sources = table == null ? void 0 : table.rows; - if ((sources == null ? void 0 : sources.length) > 0) { - sources.forEach((c4) => { - if (getAbstractFileAtPath(app, c4.source)) { - getDB(sqlJS, newTagDBPath).then((db2) => { - const schemas = selectDB(db2, "m_schema"); - const newSchemas = { - ...schemas, - rows: schemas.rows.map( - (f4) => { - var _a2; - return ((_a2 = f4.def) == null ? void 0 : _a2.includes(tag)) ? { ...f4, def: f4.def.replace(tag, newTag) } : f4; - } - ) - }; - const fields = selectDB(db2, "m_fields"); - const newFields = { - ...fields, - rows: fields.rows.map( - (f4) => f4.type.includes("context") && f4.value == tag ? { ...f4, value: newTag } : f4 - ) - }; - db2.close(); - saveDBToPath(plugin, c4.source, { - m_fields: newFields, - m_schema: newSchemas - }); + 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); }); - insertIntoDB(db, { m_context: table }); - saveAndCloseDB(db, context.dbPath); } - let event = new CustomEvent(eventTypes.metadataChange, { - detail: { tags: [tag, newTag] } - }); - window.dispatchEvent(event); - } -}; - -// src/utils/contexts/tags.ts -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 stringFromTag = (string) => { - if (string.charAt(0) == "#") { - return string.substring(1, string.length); + }, [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]); +} +function useScrollOffsetsDelta(scrollOffsets, dependencies) { + if (dependencies === void 0) { + dependencies = []; } - return string; -}; -var loadTags = (plugin) => { - var _a2; - const folder = plugin.settings.tagContextFolder == "" ? app.vault.getRoot() : getAbstractFileAtPath( - app, - getFolderPathFromString(plugin.settings.tagContextFolder) + const initialScrollOffsets = _2(null); + p2( + () => { + initialScrollOffsets.current = null; + }, + dependencies ); - return uniq([ - ...Object.keys(app.metadataCache.getTags()), - ...(_a2 = folder == null ? void 0 : folder.children.filter( - (f4) => f4 instanceof import_obsidian5.TFile && f4.extension == "mdb" && f4.name.charAt(0) == "#" - ).map((f4) => tagPathToTag(f4.name))) != null ? _a2 : [] - ]); -}; -var tagExists = (currentCache, findTag) => { - let currentTags = []; - if ((0, import_obsidian5.getAllTags)(currentCache)) { - currentTags = (0, import_obsidian5.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; + 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; +} +function useSensorSetup(sensors) { + p2( + () => { + if (!canUseDOM) { + return; } - 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; -}; -var deleteTag = async (plugin, tag, subTags) => { - const files = getAllFilesForTag(tag).map((f4) => getAbstractFileAtPath(app, f4)).filter((f4) => f4 instanceof import_obsidian5.TFile); - files.forEach((file) => removeTagFromFile(tag, file)); - deleteTagContext(plugin, tag); - if (subTags) { - const tags = getAllSubtags(plugin, tag); - tags.forEach((tag2) => deleteTag(plugin, tag2, subTags)); - } -}; -var addTag = async (plugin, tag) => { - const context = tagContextFromTag(plugin, tag); - await createDefaultDB(plugin, context); - let event = new CustomEvent(eventTypes.metadataChange, { - detail: { tags: [tag] } - }); - window.dispatchEvent(event); -}; -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_obsidian5.TFile) { - const positions = positionsForTag(tag, tFile); - if (positions.length > 0) { - await editTagInFileBody(tag, newTag, positions, tFile); - } else { - await editTagInFrontmatter(tag, newTag, tFile); - } - } + 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; + }) + ); +} +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; } - await renameTagContext(plugin, tag, toTag); - for (const subtag of tags) { - await renameTag(plugin, subtag, subtag.replace(tag, newTag)); + 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(); } -}; -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; + 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)); } - 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 value.replace(/\s/g, "").split(",").filter((f4) => stringFromTag(oldTag) != f4).join(", "); - } - return value; - }; - const tagKeys = ["tag", "tags"]; - 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 getMeasurableNode(node) { + if (!node) { + return null; } -}; -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; + if (node.children.length > 1) { + return node; } - const addTag2 = (value) => { - if (Array.isArray(value)) { - return uniq([...value, stringFromTag(newTag)]); - } else if (typeof value === "string") { - return uniq([ - ...value.replace(/\s/g, "").split(","), - stringFromTag(newTag) - ]).join(", "); - } - 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 uniq( - value.replace(/\s/g, "").split(",").map( - (f4) => stringFromTag(oldTag) == f4 ? stringFromTag(newTag) : f4 - ) - ).join(", "); - } - return value; - }; - const tagKeys = ["tag", "tags"]; - 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["tag"] = addTag2(fm["tag"]); + 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; } - } else { - app.fileManager.processFrontMatter(file, (frontmatter) => { - frontmatter["tag"] = stringFromTag(newTag); - }); } - } -}; -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; + }, [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); } - text2 = text2.slice(0, startOff) + newTag + text2.slice(startOff + oldTag.length); - offset += offsetOffset; - } - if (text2 !== original) { - await app.vault.modify(file, text2); - return true; - } + 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 allTagsForFile = (file) => { - var _a2, _b2, _c2, _d2, _e2, _f, _g, _h, _i, _j; - let rt = []; - if (file instanceof import_obsidian5.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" ? splitString(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" ? splitString(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 defaultMeasuringConfiguration = { + draggable: { + measure: getTransformAgnosticClientRect + }, + droppable: { + measure: getTransformAgnosticClientRect, + strategy: MeasuringStrategy.WhileDragging, + frequency: MeasuringFrequency.Optimized + }, + dragOverlay: { + measure: getClientRect } - return uniq(rt); -}; - -// src/utils/contexts/contexts.ts -var queryContextFromQuery = (plugin, query, readOnly) => { - return { - type: "query", - contextPath: query, - isRemote: false, - readOnly, - dbPath: getFolderPathFromString(plugin.settings.tagContextFolder) + "/" + queryToQueryPath(query) + ".mdb" - }; -}; -var queryToQueryPath = (tag) => { - if (!tag) - return null; - let string = tag; - if (string.charAt(0) != "?") - string = "?" + string; - return string.replace(/\//g, "+"); -}; -var tagContextFromTag = (plugin, tag, readOnly) => { - return { - type: "tag", - contextPath: tag, - isRemote: false, - readOnly, - dbPath: getFolderPathFromString(plugin.settings.tagContextFolder) + "/" + tagToTagPath(tag) + ".mdb" - }; }; -var contextDisplayName = (context) => { - if (!context) - return ""; - if ((context == null ? void 0 : context.type) == "folder") - return folderPathToString(context.contextPath); - if (context.isRemote) { - return folderPathToString(context.contextPath); +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; } - return context.contextPath; -}; -var mdbContextByDBPath = (plugin, dbPath) => { - if (dbPath.match(urlRegex)) { - return remoteContextFromURL(plugin, dbPath); + toArray() { + return Array.from(this.values()); } - return dbPath.endsWith((plugin == null ? void 0 : plugin.settings.folderContextFile) + ".mdb") ? folderContextFromFolder(plugin, getFolderFromPath(app, dbPath).path) : tagContextFromTag(plugin, tagPathToTag(dbPath)); -}; -var remoteContextFromURL = (plugin, url) => { - return { - type: "unknown", - contextPath: url, - isRemote: true, - readOnly: true, - dbPath: url - }; -}; -var mdbContextByContextPath = (plugin, contextPath) => { - if (!contextPath) - return; - if (contextPath.match(urlRegex)) { - return remoteContextFromURL(plugin, contextPath); + getEnabled() { + return this.toArray().filter((_ref) => { + let { + disabled + } = _ref; + return !disabled; + }); } - const viewType = viewTypeByString(contextPath); - if (viewType == "query") { - return queryContextFromQuery(plugin, contextPath); - } else if (viewType == "folder") { - return folderContextFromFolder(plugin, contextPath); - } else if (viewType == "tag") { - return tagContextFromTag(plugin, contextPath); + 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; } - return null; }; -var folderContextFromFolder = (plugin, folder, readOnly) => { - return { - type: "folder", - contextPath: folder, - isRemote: false, - readOnly, - dbPath: (folder == "/" ? "" : folder + "/") + plugin.settings.folderContextFile + ".mdb" - }; +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 linkContextRow = (row, fields, tagContexts) => { +var InternalContext = /* @__PURE__ */ F(defaultInternalContext); +var PublicContext = /* @__PURE__ */ F(defaultPublicContext); +function getInitialState() { return { - ...row, - ...fields.filter((f4) => f4.type == "fileprop").reduce((p3, c4) => { - const refCol = splitPropString(c4.value); - const col = refCol.length == 1 ? fields.find((f4) => f4.name == "File") : fields.find((f4) => f4.name == refCol[0]); - const prop = refCol.length == 1 ? refCol[0] : refCol[1]; - if (!col || !prop) { - return p3; + draggable: { + active: null, + initialCoordinates: { + x: 0, + y: 0 + }, + nodes: /* @__PURE__ */ new Map(), + translate: { + x: 0, + y: 0 } - if (col.type == "file" || col.type == "link") { - return { - ...p3, - [c4.name]: appendFilesMetaData(prop, row[col.name]) - }; + }, + 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; } - if (col.type.includes("context")) { - const context = col.value; - if (tagContexts[context]) { - return { - ...p3, - [c4.name]: linkContextProp( - prop, - row[col.name], - tagContexts[context] - ) - }; + 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 { + 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; } - return p3; - }, {}) - }; -}; -var linkContextProp = (propType, rows, contextTable) => { - const contextRows = contextTable.rows.filter( - (f4) => splitString(rows).contains(f4.File) - ); - return uniq(contextRows.map((f4) => f4[propType]).filter((f4) => f4)).join(","); -}; - -// 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, - __rest, - __decorate, - __param, - __metadata, - __awaiter, - __generator, - __exportStar, - __createBinding, - __values, - __read, - __spread, - __spreadArrays, - __spreadArray, - __await, - __asyncGenerator, - __asyncDelegator, - __asyncValues, - __makeTemplateObject, - __importStar, - __importDefault, - __classPrivateFieldGet, - __classPrivateFieldSet, - __classPrivateFieldIn -} = import_tslib.default; - -// src/cm-extensions/flowEditor/selectiveEditor.ts -var editableRange = import_state3.Annotation.define(); -var hiddenLine = import_view3.Decoration.replace({ inclusive: true }); -var hideLine = import_state3.StateField.define({ - create() { - return import_view3.Decoration.none; - }, - update(value, tr) { - var _a2; - let builder = new import_state3.RangeSetBuilder(); - if (((_a2 = tr.state.field(selectiveLinesFacet)) == null ? void 0 : _a2[0]) != void 0) { - const starterLine = Math.min( - tr.state.doc.lines, - tr.state.field(selectiveLinesFacet)[0] - ); - builder.add( - tr.state.doc.line(1).from, - tr.state.doc.line(starterLine).from, - hiddenLine - ); - builder.add( - tr.state.doc.line( - Math.min(tr.newDoc.lines, tr.state.field(selectiveLinesFacet)[1]) - ).to, - tr.state.doc.line(tr.newDoc.lines).to, - hiddenLine - ); + const containers = new DroppableContainersMap(state.droppable.containers); + containers.set(id2, { + ...element, + disabled + }); + return { + ...state, + droppable: { + ...state.droppable, + containers + } + }; } - const dec = builder.finish(); - return dec; - }, - provide: (f4) => import_view3.EditorView.decorations.from(f4) -}); -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]) - ]; + case Action.UnregisterDroppable: { + const { + id: id2, + key: key2 + } = action; + const element = state.droppable.containers.get(id2); + if (!element || key2 !== element.key) { + return state; } - return tr.annotation(editableRange); + const containers = new DroppableContainersMap(state.droppable.containers); + containers.delete(id2); + return { + ...state, + droppable: { + ...state.droppable, + containers + } + }; } - return value; - } -}); -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) => { - var _a2; - if (tr.isUserEvent("delete") && !tr.isUserEvent("delete.smart")) { - const initialSelections = tr.startState.selection.ranges.map((range) => ({ - from: range.from, - to: range.to - })); - if (initialSelections.length > 0 && ((_a2 = tr.startState.field(selectiveLinesFacet)) == null ? void 0 : _a2[0])) { - const posRange = lineRangeToPosRange( - tr.startState, - tr.startState.field(selectiveLinesFacet) - ); - const minFrom = Math.max(posRange.from, initialSelections[0].from); - const minTo = Math.min(posRange.to, initialSelections[0].to); - tr.startState.update({ - changes: { - from: Math.min(minFrom, minTo), - to: Math.max(minFrom, minTo) - }, - annotations: import_state3.Transaction.userEvent.of( - `${tr.annotation(import_state3.Transaction.userEvent)}.smart` - ) - }); - } + default: { + return state; } - return tr; } -); -var preventModifyTargetRanges = import_state3.EditorState.transactionFilter.of( - (tr) => { - let newTrans = []; - try { - const selectiveLines = tr.startState.field(selectiveLinesFacet); - if (tr.isUserEvent("input") || tr.isUserEvent("delete") || tr.isUserEvent("move")) { - if (selectiveLines == null ? void 0 : selectiveLines[0]) { - const posRange = lineRangeToPosRange( - tr.startState, - tr.startState.field(selectiveLinesFacet) - ); - if (tr.changes.touchesRange(0, posRange.from - 1) || !tr.changes.touchesRange(posRange.from, posRange.to)) { - return []; - } - } +} +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; + } + if (!activatorEvent && previousActivatorEvent && previousActiveId != null) { + if (!isKeyboardEvent(previousActivatorEvent)) { + 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, - tr.startState.field(selectiveLinesFacet) - ); - if (tr.changes.touchesRange(0, posRange.from - 1)) { - newTrans.push({ - annotations: [ - editableRange.of([ - selectiveLines[0] + numberNewLines, - selectiveLines[1] + numberNewLines - ]) - ] - }); - } else if (tr.changes.touchesRange(posRange.from - 1, posRange.to)) { - newTrans.push({ - annotations: [ - editableRange.of([ - selectiveLines[0], - selectiveLines[1] + numberNewLines - ]) - ] - }); - } - } + if (document.activeElement === previousActivatorEvent.target) { + return; } - } catch (e4) { - return []; - } - return [tr, ...newTrans]; - } -); -var readOnlyRangesExtension = [smartDelete, preventModifyTargetRanges]; -var editBlockExtensions = () => [ - readOnlyRangesExtension, - hideLine, - selectiveLinesFacet -]; - -// 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; - } - 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); + const draggableNode = draggableNodes.get(previousActiveId); + if (!draggableNode) { + return; } - if (oldSel.to >= posRange.to && tr.annotation(arrowKeyAnnotation) == 4) { - focusFlowEditorParent(flowID, false); + const { + activatorNode, + node + } = draggableNode; + if (!activatorNode.current && !node.current) { + return; } - 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 (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) - }; + requestAnimationFrame(() => { + for (const element of [activatorNode.current, node.current]) { + if (!element) { + continue; + } + const focusableNode = findFirstFocusableNode(element); + if (focusableNode) { + focusableNode.focus(); break; } } - } + }); } - return tr; - } -); - -// src/components/ContextView/EmbedContextView.tsx -var import_obsidian21 = require("obsidian"); - -// node_modules/@dnd-kit/utilities/dist/utilities.esm.js -function useCombinedRefs(...refs) { - return F( - () => (node) => { - refs.forEach((ref) => ref(node)); - }, - refs - ); -} -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]"; + }, [activatorEvent, disabled, draggableNodes, previousActiveId, previousActivatorEvent]); + return null; } -function isNode(node) { - return "nodeType" in node; +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 getWindow(target) { - var _target$ownerDocument, _target$ownerDocument2; - if (!target) { - return window; - } - if (isWindow(target)) { - return target; - } - if (!isNode(target)) { - return window; - } - return (_target$ownerDocument = (_target$ownerDocument2 = target.ownerDocument) == null ? void 0 : _target$ownerDocument2.defaultView) != null ? _target$ownerDocument : window; +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 isDocument(node) { +function useLayoutShiftScrollCompensation(_ref) { + let { + activeNode, + measure, + initialRect, + config = true + } = _ref; + const initialized = _2(false); const { - Document - } = getWindow(node); - return node instanceof Document; -} -function isHTMLElement(node) { - if (isWindow(node)) { - return false; - } - return node instanceof getWindow(node).HTMLElement; -} -function isSVGElement(node) { - return node instanceof getWindow(node).SVGElement; -} -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; - } - return document; -} -var useIsomorphicLayoutEffect = canUseDOM ? s2 : h2; -function useEvent(handler) { - const handlerRef = _2(handler); + x: x5, + y: y5 + } = typeof config === "boolean" ? { + x: config, + y: config + } : config; useIsomorphicLayoutEffect(() => { - handlerRef.current = handler; - }); - return T2(function(...args) { - 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; + const disabled = !x5 && !y5; + if (disabled || !activeNode) { + initialized.current = false; + return; } - }, []); - return [set, clear]; -} -function useLatestValue(value, dependencies = [value]) { - const valueRef = _2(value); - useIsomorphicLayoutEffect(() => { - if (valueRef.current !== value) { - valueRef.current = value; + if (initialized.current || !initialRect) { + return; } - }, dependencies); - return valueRef; -} -function useLazyMemo(callback, dependencies) { - const valueRef = _2(); - return F( - () => { - 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 ref = _2(); - h2(() => { - ref.current = value; - }, [value]); - return ref.current; -} -var ids = {}; -function useUniqueId(prefix, value) { - return F(() => { - if (value) { - return value; + const node = activeNode == null ? void 0 : activeNode.node.current; + if (!node || node.isConnected === false) { + return; } - const id2 = ids[prefix] == null ? 0 : ids[prefix] + 1; - ids[prefix] = id2; - return `${prefix}-${id2}`; - }, [prefix, value]); -} -function createAdjustmentFn(modifier) { - return (object, ...adjustments) => { - 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; - } + 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 + }); } - 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 - }; } - } - if (hasViewportRelativeCoordinates(event)) { - return { - x: event.clientX, - y: event.clientY - }; - } - return null; + }, [activeNode, x5, y5, initialRect, measure]); } -var CSS = /* @__PURE__ */ Object.freeze({ - Translate: { - toString(transform) { - if (!transform) { +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 { - x: x5, - y: y5 - } = transform; - return `translate3d(${x5 ? Math.round(x5) : 0}px, ${y5 ? Math.round(y5) : 0}px, 0)`; + 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); } - }, - Scale: { - toString(transform) { - if (!transform) { + }, [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 { - scaleX, - scaleY - } = transform; - return `scaleX(${scaleX}) scaleY(${scaleY})`; - } - }, - Transform: { - toString(transform) { - if (!transform) { + active: active2, + activatorEvent: activatorEvent2, + collisions: collisions2, + droppableContainers: droppableContainers2, + scrollAdjustedTranslate: scrollAdjustedTranslate2 + } = sensorContext.current; + if (!active2 || activeRef.current == null || !activatorEvent2 || !scrollAdjustedTranslate2) { return; } - return [CSS.Translate.toString(transform), CSS.Scale.toString(transform)].join(" "); - } - }, - Transition: { - toString({ - property, - duration, - easing - }) { - return `${property} ${duration}ms ${easing}`; + 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 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 bn.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) { +var NullContext = /* @__PURE__ */ F(null); +var defaultRole = "button"; +var ID_PREFIX = "Droppable"; +function useDraggable(_ref) { let { id: id2, - announcement + data, + disabled = false, + attributes } = _ref; - return bn.createElement("div", { - id: id2, - style: visuallyHidden, - role: "status", - "aria-live": "assertive", - "aria-atomic": true - }, announcement); -} -function useAnnouncement() { - const [announcement, setAnnouncement] = p2(""); - const announce = T2((value) => { - if (value != null) { - setAnnouncement(value); - } - }, []); - return { - announce, - announcement - }; -} - -// node_modules/@dnd-kit/core/dist/core.esm.js -var DndMonitorContext = /* @__PURE__ */ B(null); -function useDndMonitor(listener) { - const registerListener = q2(DndMonitorContext); - h2(() => { - if (!registerListener) { - throw new Error("useDndMonitor must be used within a children of "); - } - const unsubscribe = registerListener(listener); - return unsubscribe; - }, [listener, registerListener]); + 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); + } + }; + }, + [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 { + active, + activatorEvent, + activeNodeRect, + attributes: memoizedAttributes, + isDragging, + listeners: disabled ? void 0 : listeners, + node, + over, + setNodeRef, + setActivatorNodeRef, + transform + }; } -function useDndMonitorProvider() { - const [listeners] = p2(() => /* @__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]; +function useDndContext() { + return q2(PublicContext); } -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 + "."; - } - 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; - } - return "Draggable item " + active.id + " was dropped."; - }, - onDragCancel(_ref4) { - let { - active - } = _ref4; - return "Dragging was cancelled. Draggable item " + active.id + " was dropped."; - } +var ID_PREFIX$1 = "Droppable"; +var defaultResizeObserverConfig = { + timeout: 25 }; -function Accessibility(_ref) { +function useDroppable(_ref) { let { - announcements = defaultAnnouncements, - container, - hiddenTextDescribedById, - screenReaderInstructions = defaultScreenReaderInstructions + data, + disabled = false, + id: id2, + resizeObserverConfig } = _ref; + const key2 = useUniqueId(ID_PREFIX$1); const { - announce, - announcement - } = useAnnouncement(); - const liveRegionId = useUniqueId("DndLiveRegion"); - const [mounted, setMounted] = p2(false); - h2(() => { - setMounted(true); - }, []); - useDndMonitor(F(() => ({ - onDragStart(_ref2) { - let { - active - } = _ref2; - announce(announcements.onDragStart({ - active - })); - }, - onDragMove(_ref3) { - let { - active, - over - } = _ref3; - if (announcements.onDragMove) { - announce(announcements.onDragMove({ - active, - over - })); + 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; + return; } + if (callbackId.current != null) { + clearTimeout(callbackId.current); + } + callbackId.current = setTimeout(() => { + measureDroppableContainers(Array.isArray(ids2.current) ? ids2.current : [ids2.current]); + callbackId.current = null; + }, resizeObserverTimeout); }, - 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; - } - const markup = bn.createElement(bn.Fragment, null, bn.createElement(HiddenText, { - id: hiddenTextDescribedById, - value: screenReaderInstructions.draggable - }), bn.createElement(LiveRegion, { - id: liveRegionId, - announcement - })); - return container ? j3(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 F( - () => ({ - sensor, - options: options != null ? options : {} - }), - [sensor, options] + [resizeObserverTimeout] ); -} -function useSensors() { - for (var _len = arguments.length, sensors = new Array(_len), _key = 0; _key < _len; _key++) { - sensors[_key] = arguments[_key]; - } - return F( - () => [...sensors].filter((sensor) => sensor != null), - [...sensors] + const resizeObserver = useResizeObserver({ + callback: handleResize, + disabled: resizeObserverDisabled || !active + }); + const handleNodeChange = T2((newElement, previousElement) => { + if (!resizeObserver) { + return; + } + 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) { + return; + } + 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 () => dispatch({ + type: Action.UnregisterDroppable, + key: key2, + id: id2 + }); + }, + [id2] ); -} -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 + p2(() => { + if (disabled !== previous.current.disabled) { + dispatch({ + type: Action.SetDroppableDisabled, + id: id2, + key: key2, + disabled + }); + previous.current.disabled = disabled; + } + }, [id2, key2, disabled, dispatch]); + return { + active, + rect, + isOver: (over == null ? void 0 : over.id) === id2, + node: nodeRef, + over, + setNodeRef }; - return transformOrigin.x + "% " + transformOrigin.y + "%"; } -function sortCollisionsAsc(_ref, _ref2) { +function AnimationManager(_ref) { let { - data: { - value: a5 - } + animation, + children } = _ref; - let { - data: { - value: b4 - } - } = _ref2; - return a5 - b4; -} -function sortCollisionsDesc(_ref3, _ref4) { - let { - data: { - value: a5 + const [clonedChildren, setClonedChildren] = h2(null); + const [element, setElement] = h2(null); + const previousChildren = usePrevious(children); + if (!children && !clonedChildren && previousChildren) { + setClonedChildren(previousChildren); + } + useIsomorphicLayoutEffect(() => { + if (!element) { + return; } - } = _ref3; - let { - data: { - value: b4 + 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; } - } = _ref4; - return b4 - a5; + Promise.resolve(animation(id2, element)).then(() => { + setClonedChildren(null); + }); + }, [animation, clonedChildren, element]); + return Cn.createElement(Cn.Fragment, null, children, clonedChildren ? sn(clonedChildren, { + ref: setElement + }) : null); } -function cornersOfRectangle(_ref5) { +var defaultTransform = { + x: 0, + y: 0, + scaleX: 1, + scaleY: 1 +}; +function NullifiedContextProvider(_ref) { 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 - }]; + children + } = _ref; + return Cn.createElement(InternalContext.Provider, { + value: defaultInternalContext + }, Cn.createElement(ActiveDraggableContext.Provider, { + value: defaultTransform + }, children)); } -function getFirstCollision(collisions, property) { - if (!collisions || collisions.length === 0) { +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 [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 + const scaleAdjustedTransform = adjustScale2 ? transform : { + ...transform, + scaleX: 1, + scaleY: 1 }; -} -var closestCenter = (_ref) => { + 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 + }; + return Cn.createElement(as, { + className, + style: styles, + ref + }, children); +}); +var defaultDropAnimationSideEffects = (options) => (_ref) => { let { - collisionRect, - droppableRects, - droppableContainers + active, + dragOverlay } = _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 - } - }); + 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); } } - 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 - } - }); + if (styles != null && styles.dragOverlay) { + for (const [key2, value] of Object.entries(styles.dragOverlay)) { + if (value === void 0) { + continue; + } + dragOverlay.node.style.setProperty(key2, value); } } - 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)); + if (className != null && className.active) { + active.node.classList.add(className.active); } - return 0; -} -var rectIntersection = (_ref) => { + 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); + } + }; +}; +var defaultKeyframeResolver = (_ref2) => { 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 - } - }); + transform: { + initial, + final + } + } = _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" } } - } - 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]; +function useDropAnimation(_ref3) { + let { + config, + draggableNodes, + droppableContainers, + measuringConfiguration + } = _ref3; + return useEvent((id2, node) => { + if (config === null) { + return; } - 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 + const activeDraggable = draggableNodes.get(id2); + if (!activeDraggable) { + return; + } + const activeNode = activeDraggable.node.current; + if (!activeNode) { + return; + } + const measurableNode = getMeasurableNode(node); + if (!measurableNode) { + return; + } + 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 }); - }; -} -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; - } +function createDefaultDropAnimation(options) { 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 + duration, + easing, + sideEffects, + keyframes + } = { + ...defaultDropAnimationConfiguration, + ...options }; -} -var defaultOptions2 = { - ignoreTransform: false -}; -function getClientRect(element, options) { - if (options === void 0) { - options = defaultOptions2; - } - let rect = element.getBoundingClientRect(); - if (options.ignoreTransform) { - const { - getComputedStyle - } = getWindow(element); - const { + return (_ref4) => { + let { + active, + dragOverlay, transform, - transformOrigin - } = getComputedStyle(element); - if (transform) { - rect = inverseTransform(rect, transform, transformOrigin); + ...rest + } = _ref4; + if (!duration) { + return; } - } - 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 + const delta = { + x: dragOverlay.rect.left - active.rect.left, + y: dragOverlay.rect.top - active.rect.top + }; + 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 + } + }); + 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(); + }; + }); }; } -function isFixed(node, computedStyle) { - if (computedStyle === void 0) { - computedStyle = getWindow(node).getComputedStyle(node); - } - return computedStyle.position === "fixed"; +var key = 0; +function useKey(id2) { + return F2(() => { + if (id2 == null) { + return; + } + key++; + return key; + }, [id2]); } -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; +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 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)); +}); + +// 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 getScrollableAncestors(element, limit) { - const scrollParents = []; - function findScrollableAncestors(node) { - if (limit != null && scrollParents.length >= limit) { - return scrollParents; - } - if (!node) { - return scrollParents; - } - if (isDocument(node) && node.scrollingElement != null && !scrollParents.includes(node.scrollingElement)) { - scrollParents.push(node.scrollingElement); - return scrollParents; - } - if (!isHTMLElement(node) || isSVGElement(node)) { - return scrollParents; - } - if (scrollParents.includes(node)) { - return scrollParents; - } - const { - getComputedStyle - } = getWindow(node); - const computedStyle = getComputedStyle(node); - if (node !== element) { - if (isScrollable(node, computedStyle)) { - scrollParents.push(node); - } - } - if (isFixed(node, computedStyle)) { - return scrollParents; +function getSortedRects(items, rects) { + return items.reduce((accumulator, id2, index) => { + const rect = rects.get(id2); + if (rect) { + accumulator[index] = rect; } - return findScrollableAncestors(node.parentNode); - } - if (!element) { - return scrollParents; - } - return findScrollableAncestors(element); + return accumulator; + }, Array(items.length)); } -function getFirstScrollableAncestor(node) { - const [firstScrollableAncestor] = getScrollableAncestors(node, 1); - return firstScrollableAncestor != null ? firstScrollableAncestor : null; +function isValidIndex(index) { + return index !== null && index >= 0; } -function getScrollableElement(element) { - if (!canUseDOM || !element) { - return null; - } - if (isWindow(element)) { - return element; - } - if (!isNode(element)) { - return null; +function itemsEqual(a5, b4) { + if (a5 === b4) { + return true; } - if (isDocument(element) || element === getOwnerDocument(element).scrollingElement) { - return window; + if (a5.length !== b4.length) { + return false; } - if (isHTMLElement(element)) { - return element; + for (let i4 = 0; i4 < a5.length; i4++) { + if (a5[i4] !== b4[i4]) { + return false; + } } - return null; + return true; } -function getScrollXCoordinate(element) { - if (isWindow(element)) { - return element.scrollX; +function normalizeDisabled(disabled) { + if (typeof disabled === "boolean") { + return { + draggable: disabled, + droppable: disabled + }; } - return element.scrollLeft; + return disabled; } -function getScrollYCoordinate(element) { - if (isWindow(element)) { - return element.scrollY; +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; } - 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; + 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 + }; } - return element === document.scrollingElement; -} -function getScrollPosition(scrollingContainer) { - const minScroll = { + 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 - }; - 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 + y: 0, + ...defaultScale }; - const isTop = scrollingContainer.scrollTop <= minScroll.y; - const isLeft = scrollingContainer.scrollLeft <= minScroll.x; - const isBottom = scrollingContainer.scrollTop >= maxScroll.y; - const isRight = scrollingContainer.scrollLeft >= maxScroll.x; +}; +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 { - isTop, - isLeft, - isBottom, - isRight, - maxScroll, - minScroll + x: newRect.left - oldRect.left, + y: newRect.top - oldRect.top, + scaleX: newRect.width / oldRect.width, + scaleY: newRect.height / oldRect.height }; -} -var defaultThreshold = { - x: 0.2, - y: 0.2 }; -function getScrollDirectionAndSpeed(scrollContainer, scrollContainerRect, _ref, acceleration, thresholdPercentage) { +var defaultScale$1 = { + scaleX: 1, + scaleY: 1 +}; +var verticalListSortingStrategy = (_ref) => { + var _rects$activeIndex; let { - top, - left, - right, - bottom + activeIndex, + activeNodeRect: fallbackActiveRect, + index, + rects, + overIndex } = _ref; - if (acceleration === void 0) { - acceleration = 10; - } - if (thresholdPercentage === void 0) { - thresholdPercentage = defaultThreshold; + const activeNodeRect = (_rects$activeIndex = rects[activeIndex]) != null ? _rects$activeIndex : fallbackActiveRect; + if (!activeNodeRect) { + return null; } - 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 (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 (!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); + const itemGap = getItemGap$1(rects, index, activeIndex); + if (index > activeIndex && index <= overIndex) { + return { + x: 0, + y: -activeNodeRect.height - itemGap, + ...defaultScale$1 + }; } - return { - direction, - speed - }; -} -function getScrollElementRect(element) { - if (element === document.scrollingElement) { - const { - innerWidth: innerWidth2, - innerHeight: innerHeight2 - } = window; + if (index < activeIndex && index >= overIndex) { return { - top: 0, - left: 0, - right: innerWidth2, - bottom: innerHeight2, - width: innerWidth2, - height: innerHeight2 + x: 0, + y: activeNodeRect.height + itemGap, + ...defaultScale$1 }; } - const { - top, - left, - right, - bottom - } = element.getBoundingClientRect(); return { - top, - left, - right, - bottom, - width: element.clientWidth, - height: element.clientHeight + x: 0, + y: 0, + ...defaultScale$1 }; -} -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; +}; +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 (bottom <= 0 || right <= 0 || top >= window.innerHeight || left >= window.innerWidth) { - element.scrollIntoView({ - block: "center", - inline: "center" - }); + 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 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 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 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 getEventListenerTarget(target) { +}); +function SortableContext(_ref) { + let { + children, + id: id2, + items: userDefinedItems, + strategy = rectSortingStrategy, + disabled: disabledProp = false + } = _ref; const { - EventTarget - } = getWindow(target); - return target instanceof EventTarget ? target : getOwnerDocument(target); + 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); } -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; +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 ("x" in measurement) { - return dx > measurement.x; + if (previousItems !== items && index === newIndex) { + return false; } - if ("y" in measurement) { - return dy > measurement.y; + if (isSorting) { + return true; } - 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] + return newIndex !== index && containerId === previousContainerId; }; -var defaultKeyboardCoordinateGetter = (event, _ref) => { +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 { - currentCoordinates + disabled, + index, + node, + rect } = _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 + 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); + } } - } = 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(); + } + if (index !== previousIndex.current) { + previousIndex.current = index; + } + }, [disabled, index, node, rect]); + p2(() => { + if (derivedTransform) { + setDerivedtransform(null); + } + }, [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 + }, + ...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 + } + }); + const { + active, + activatorEvent, + activeNodeRect, + attributes, + setNodeRef: setDraggableNodeRef, + listeners, + isDragging, + over, + setActivatorNodeRef, + transform + } = useDraggable({ + id: id2, + data, + 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 = animateLayoutChanges3({ + 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(() => { + if (isSorting && previous.current.newIndex !== newIndex) { + previous.current.newIndex = newIndex; + } + if (containerId !== previous.current.containerId) { + previous.current.containerId = containerId; + } + if (items !== previous.current.items) { + previous.current.items = items; + } + }, [isSorting, newIndex, containerId, items]); + p2(() => { + if (activeId === previous.current.activeId) { + return; + } + 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, + 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; + } + if (shouldDisplaceDragSource && !isKeyboardEvent(activatorEvent) || !transition) { + return void 0; + } + if (isSorting || shouldAnimateLayoutChanges) { + return CSS.Transition.toString({ + ...transition, + property: transitionProperty + }); + } + return void 0; } - 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)); +} +function normalizeLocalDisabled(localDisabled, globalDisabled) { + var _localDisabled$dragga, _localDisabled$droppa; + if (typeof localDisabled === "boolean") { + return { + draggable: localDisabled, + droppable: false + }; } - handleStart() { - const { - activeNode, - onStart - } = this.props; - const node = activeNode.node.current; - if (node) { - scrollIntoViewIfNeeded(node); - } - onStart(defaultCoordinates); + 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; } - 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); + 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; + } + return false; +} +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; } - if (keyboardCodes.cancel.includes(code)) { - this.handleCancel(event); + const rect = droppableRects.get(entry.id); + if (!rect) { return; } - const { - collisionRect - } = context.current; - const currentCoordinates = collisionRect ? { - x: collisionRect.left, - y: collisionRect.top - } : defaultCoordinates; - if (!this.referenceCoordinates) { - this.referenceCoordinates = currentCoordinates; + 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 newCoordinates = coordinateGetter(event, { - active, - context: context.current, - currentCoordinates - }); - if (newCoordinates) { - const coordinatesDelta = subtract(newCoordinates, currentCoordinates); - const scrollDelta = { + }); + 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; + } + 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 offset = hasDifferentScrollAncestors || !hasSameContainer ? { x: 0, y: 0 + } : { + x: isAfterActive ? collisionRect.width - newRect.width : 0, + y: isAfterActive ? collisionRect.height - newRect.height : 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)); + const rectCoordinates = { + x: newRect.left, + y: newRect.top + }; + const newCoordinates = offset.x && offset.y ? rectCoordinates : subtract(rectCoordinates, offset); + return newCoordinates; } } } - handleMove(event, coordinates) { - const { - onMove - } = this.props; - event.preventDefault(); - onMove(coordinates); - } - handleEnd(event) { - const { - onEnd - } = this.props; - event.preventDefault(); - this.detach(); - onEnd(); + return void 0; +}; +function isSameContainer(a5, b4) { + if (!hasSortableData(a5) || !hasSortableData(b4)) { + return false; } - handleCancel(event) { - const { - onCancel - } = this.props; - event.preventDefault(); - this.detach(); - onCancel(); + return a5.data.current.sortable.containerId === b4.data.current.sortable.containerId; +} +function isAfter(a5, b4) { + if (!hasSortableData(a5) || !hasSortableData(b4)) { + return false; } - detach() { - this.listeners.removeAll(); - this.windowListeners.removeAll(); + if (!isSameContainer(a5, b4)) { + return false; } + return a5.data.current.sortable.index < b4.data.current.sortable.index; +} + +// src/components/ContextView/CardsView/CardsView.tsx +var import_classnames4 = __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; }; -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; +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); } -}]; -function isDistanceConstraint(constraint) { - return Boolean(constraint && "distance" in constraint); + return array.filter((f4, i4) => i4 < lastIndex && i4 >= newIndex); +}; + +// src/components/ui/menus/selectMenu/concerns/matchers.js +function escapeForRegExp(string) { + return string.replace(/[-\\^$*+?.()|[\]{}]/g, "\\$&"); } -function isDelayConstraint(constraint) { - return Boolean(constraint && "delay" in constraint); +function matchAny(string) { + return new RegExp(escapeForRegExp(string), "gi"); } -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(); - } - 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(); - } - detach() { - this.listeners.removeAll(); - this.windowListeners.removeAll(); - setTimeout(this.documentListeners.removeAll, 50); - if (this.timeoutId !== null) { - clearTimeout(this.timeoutId); - this.timeoutId = null; - } - } - 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); - } - } - 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); - } - 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(); - } - } - removeTextSelection() { - var _this$document$getSel; - (_this$document$getSel = this.document.getSelection()) == null ? void 0 : _this$document$getSel.removeAllRanges(); - } -}; -var events = { - move: { - name: "pointermove" +function matchExact(string) { + return new RegExp(`^${escapeForRegExp(string)}$`, "i"); +} + +// src/components/ContextView/MDBContext.tsx +var import_lodash2 = __toESM(require_lodash()); +var import_obsidian6 = require("obsidian"); + +// 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" }, - end: { - name: "pointerup" + isEmpty: { + type: ["text", "file", "link", "link-multi", "fileprop", "image"], + fn: (v3, f4) => empty(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: stringEqual, + valueType: "text" + }, + isNot: { + type: ["text", "file", "link", "context", "fileprop"], + fn: (v3, f4) => !stringEqual(v3, f4), + valueType: "text" + }, + equal: { + type: ["number"], + fn: stringEqual, + valueType: "number" + }, + isGreatThan: { + type: ["number"], + fn: greaterThan, + valueType: "number" + }, + isLessThan: { + type: ["number"], + fn: lessThan, + 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: lessThan, + valueType: "date" + }, + dateAfter: { + type: ["date", "fileprop"], + fn: greaterThan, + valueType: "date" + }, + isAnyInList: { + type: ["option", "context", "option-multi", "context-multi", "tags-multi", "tags"], + fn: listIncludes, + 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" } }; -var PointerSensor = class extends AbstractPointerSensor { - constructor(props2) { - const { - event - } = props2; - const listenerTarget = getOwnerDocument(event.target); - super(props2, events, listenerTarget); - } + +// src/utils/contexts/predicate/filter.ts +var stringEqual = (value, filterValue) => { + return value == filterValue; }; -PointerSensor.activators = [{ - eventName: "onPointerDown", - handler: (_ref, _ref2) => { - let { - nativeEvent: event - } = _ref; - let { - onActivation - } = _ref2; - if (!event.isPrimary || event.button !== 0) { - return false; - } - onActivation == null ? void 0 : onActivation({ - event - }); +var empty = (value, filterValue) => { + return (value != null ? value : "").length == 0; +}; +var stringCompare = (value, filterValue) => { + return (value != null ? value : "").toLowerCase().includes((filterValue != null ? filterValue : "").toLowerCase()); +}; +var greaterThan = (value, filterValue) => { + return parseFloat(value) > parseFloat(filterValue); +}; +var lessThan = (value, filterValue) => { + return parseInt(value) > parseInt(filterValue); +}; +var listIncludes = (value, filterValue) => { + const valueList = value ? parseMultiString(value) : []; + const strings = filterValue ? parseMultiString(filterValue) : []; + return strings.some((f4) => valueList.some((g4) => g4 == f4)); +}; +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 events$1 = { - move: { - name: "mousemove" + return result; +}; + +// 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 }, - end: { - name: "mouseup" + 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 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 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; }; -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; + +// node_modules/date-fns/esm/_lib/toInteger/index.js +function toInteger(dirtyNumber) { + if (dirtyNumber === null || dirtyNumber === true || dirtyNumber === false) { + return NaN; } -}]; -var events$2 = { - move: { - name: "touchmove" - }, - end: { - name: "touchend" + var number = Number(dirtyNumber); + if (isNaN(number)) { + return number; } -}; -var TouchSensor = class extends AbstractPointerSensor { - constructor(props2) { - super(props2, events$2); + 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"); } - static setup() { - window.addEventListener(events$2.move.name, noop2, { - capture: false, - passive: false - }); - return function teardown() { - window.removeEventListener(events$2.move.name, noop2); +} + +// 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; }; - function noop2() { - } } -}; -TouchSensor.activators = [{ - eventName: "onTouchStart", - handler: (_ref, _ref2) => { - let { - nativeEvent: event - } = _ref; - let { - onActivation - } = _ref2; - const { - touches - } = event; - if (touches.length > 1) { - return false; + 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); } - onActivation == null ? void 0 : onActivation({ - event - }); - return true; + return new Date(NaN); } -}]; -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 = F(() => { - 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 = F(() => order === TraversalOrder.TreeOrder ? [...scrollableAncestors].reverse() : scrollableAncestors, [order, scrollableAncestors]); - h2( - () => { - 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 + +// 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); } -}; -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]); + if (!amount) { + return date; + } + date.setDate(date.getDate() + amount); + return date; } -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]); + +// 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 (!amount) { + return date; + } + 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; + } } -function useCombineActivators(sensors, getSyntheticHandler) { - return F(() => 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]); + +// 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); } -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 [containerIdsScheduledForMeasurement, setContainerIdsScheduledForMeasurement] = p2(null); - const measuringScheduled = containerIdsScheduledForMeasurement != 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; - } - setContainerIdsScheduledForMeasurement((value) => value ? value.concat(ids2) : ids2); - }, [disabledRef]); - const timeoutId = _2(null); - const droppableRects = useLazyMemo((previousValue) => { - if (disabled && !dragging) { - return defaultValue; - } - const ids2 = containerIdsScheduledForMeasurement; - if (!previousValue || previousValue === defaultValue || containersRef.current !== containers || ids2 != null) { - const map = /* @__PURE__ */ new Map(); - for (let container of containers) { - if (!container) { - continue; - } - if (ids2 && ids2.length > 0 && !ids2.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; - } - return previousValue; - }, [containers, containerIdsScheduledForMeasurement, dragging, disabled, measure]); - h2(() => { - containersRef.current = containers; - }, [containers]); - h2( - () => { - if (disabled) { - return; - } - requestAnimationFrame(() => measureDroppableContainers()); - }, - [dragging, disabled] - ); - h2(() => { - if (measuringScheduled) { - setContainerIdsScheduledForMeasurement(null); - } - }, [measuringScheduled]); - h2( - () => { - 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 - }; - function isDisabled() { - switch (strategy) { - case MeasuringStrategy.Always: - return false; - case MeasuringStrategy.BeforeDragging: - return dragging; - default: - return !dragging; - } + +// node_modules/date-fns/esm/_lib/defaultOptions/index.js +var defaultOptions2 = {}; +function getDefaultOptions() { + return defaultOptions2; +} + +// 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"); } + 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 useInitialValue(value, computeFn) { - return useLazyMemo((previousValue) => { - if (!value) { - return null; - } - if (previousValue) { - return previousValue; - } - return typeof computeFn === "function" ? computeFn(value) : value; - }, [computeFn, value]); + +// node_modules/date-fns/esm/startOfISOWeek/index.js +function startOfISOWeek(dirtyDate) { + requiredArgs(1, arguments); + return startOfWeek(dirtyDate, { + weekStartsOn: 1 + }); } -function useInitialRect(node, measure) { - return useInitialValue(node, measure); + +// 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; + } } -function useMutationObserver(_ref) { - let { - callback, - disabled - } = _ref; - const handleMutations = useEvent(callback); - const mutationObserver = F(() => { - if (disabled || typeof window === "undefined" || typeof window.MutationObserver === "undefined") { - return void 0; - } - const { - MutationObserver - } = window; - return new MutationObserver(handleMutations); - }, [handleMutations, disabled]); - h2(() => { - return () => mutationObserver == null ? void 0 : mutationObserver.disconnect(); - }, [mutationObserver]); - return mutationObserver; + +// 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 useResizeObserver(_ref) { - let { - callback, - disabled - } = _ref; - const handleResize = useEvent(callback); - const resizeObserver = F( - () => { - if (disabled || typeof window === "undefined" || typeof window.ResizeObserver === "undefined") { - return void 0; - } - const { - ResizeObserver - } = window; - return new ResizeObserver(handleResize); - }, - [disabled] - ); - h2(() => { - return () => resizeObserver == null ? void 0 : resizeObserver.disconnect(); - }, [resizeObserver]); - return resizeObserver; + +// 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 defaultMeasure(element) { - return new Rect(getClientRect(element), element); + +// 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 useRect(element, measure, fallbackRect) { - if (measure === void 0) { - measure = defaultMeasure; + +// 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 [rect, measureRect] = y2(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; - } - } + 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 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 { - 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; - } - const newRect = measure(element); - if (JSON.stringify(currentRect) === JSON.stringify(newRect)) { - return currentRect; - } - return newRect; + 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; + }; } + return _typeof3(obj); } -function useRectDelta(rect) { - const initialRect = useInitialValue(rect); - return getRectDelta(rect, initialRect); +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 result || new Date(NaN); } -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]); - h2(() => { - previousNode.current = node; - }, [node]); - return ancestors; + +// 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; + } } -function useScrollOffsets(elements) { - const [scrollCoordinates, setScrollCoordinates] = p2(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); - }); - }, []); - h2(() => { - 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); + +// 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; }; - function cleanup(elements2) { - elements2.forEach((element) => { - const scrollableElement = getScrollableElement(element); - scrollableElement == null ? void 0 : scrollableElement.removeEventListener("scroll", handleScroll); - }); - } - }, [handleScroll, elements]); - return F(() => { - if (elements.length) { - return scrollCoordinates ? Array.from(scrollCoordinates.values()).reduce((acc, coordinates) => add(acc, coordinates), defaultCoordinates) : getScrollOffsets(elements); - } - return defaultCoordinates; - }, [elements, scrollCoordinates]); + } else { + _typeof4 = function _typeof5(obj2) { + return obj2 && typeof Symbol === "function" && obj2.constructor === Symbol && obj2 !== Symbol.prototype ? "symbol" : typeof obj2; + }; + } + return _typeof4(obj); } -function useScrollOffsetsDelta(scrollOffsets, dependencies) { - if (dependencies === void 0) { - dependencies = []; +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 initialScrollOffsets = _2(null); - h2( - () => { - initialScrollOffsets.current = null; - }, - dependencies - ); - h2(() => { - 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; + var date = toDate(dirtyDate); + return !isNaN(Number(date)); } -function useSensorSetup(sensors) { - h2( - () => { - 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/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; } -function useSyntheticListeners(listeners, id2) { - return F(() => { - return listeners.reduce((acc, _ref) => { - let { - eventName, - handler - } = _ref; - acc[eventName] = (event) => { - handler(event, id2); - }; - return acc; - }, {}); - }, [listeners, id2]); + +// 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); } -function useWindowRect(element) { - return F(() => element ? getWindowClientRect(element) : null, [element]); + +// node_modules/date-fns/esm/differenceInMilliseconds/index.js +function differenceInMilliseconds(dateLeft, dateRight) { + requiredArgs(2, arguments); + return toDate(dateLeft).getTime() - toDate(dateRight).getTime(); } -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] = y2(reducer2, defaultValue$2); - const resizeObserver = useResizeObserver({ - callback: measureRects - }); - if (elements.length > 0 && rects === defaultValue$2) { - measureRects(); + +// 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); } - useIsomorphicLayoutEffect(() => { - if (elements.length) { - elements.forEach((element) => resizeObserver == null ? void 0 : resizeObserver.observe(element)); - } else { - resizeObserver == null ? void 0 : resizeObserver.disconnect(); - measureRects(); +}; +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); } - }, [elements]); - return rects; - function reducer2() { - if (!elements.length) { - return defaultValue$2; + 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 elements.map((element) => isDocumentScrollingElement(element) ? windowRect : new Rect(measure(element), element)); + result = sign * (difference - Number(isLastMonthNotFull)); } + return result === 0 ? 0 : result; } -function getMeasurableNode(node) { - if (!node) { - return null; - } - if (node.children.length > 1) { - return node; + +// 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"); } - const firstChild = node.children[0]; - return isHTMLElement(firstChild) ? firstChild : node; + 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; } -function useDragOverlayMeasuring(_ref) { - let { - measure - } = _ref; - const [rect, setRect] = p2(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 + +// node_modules/date-fns/esm/endOfISOWeek/index.js +function endOfISOWeek(dirtyDate) { + requiredArgs(1, arguments); + return endOfWeek(dirtyDate, { + weekStartsOn: 1 }); - 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 F(() => ({ - 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 - } -}; -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; + +// node_modules/date-fns/esm/subMilliseconds/index.js +function subMilliseconds(dirtyDate, dirtyAmount) { + requiredArgs(2, arguments); + var amount = toInteger(dirtyAmount); + return addMilliseconds(dirtyDate, -amount); +} + +// 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; } - toArray() { - return Array.from(this.values()); +} + +// 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; +} + +// 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; +} + +// 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"); } - getEnabled() { - return this.toArray().filter((_ref) => { - let { - disabled - } = _ref; - return !disabled; - }); + 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"); } - 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 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; } -}; -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 +} + +// 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; +} + +// node_modules/date-fns/esm/_lib/addLeadingZeros/index.js +function addLeadingZeros(number, targetLength) { + var sign = number < 0 ? "-" : ""; + var output = Math.abs(number).toString(); + while (output.length < targetLength) { + output = "0" + output; + } + return sign + output; +} + +// 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); }, - scrollableAncestors: [], - scrollableAncestorRects: [], - measuringConfiguration: defaultMeasuringConfiguration, - measureDroppableContainers: noop, - windowRect: null, - measuringScheduled: false -}; -var defaultInternalContext = { - activatorEvent: null, - activators: [], - active: null, - activeNodeRect: null, - ariaDescribedById: { - draggable: "" + M: function M3(date, token) { + var month = date.getUTCMonth(); + return token === "M" ? String(month + 1) : addLeadingZeros(month + 1, 2); }, - dispatch: noop, - draggableNodes: /* @__PURE__ */ new Map(), - over: null, - measureDroppableContainers: noop -}; -var InternalContext = /* @__PURE__ */ B(defaultInternalContext); -var PublicContext = /* @__PURE__ */ B(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 { - 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 - } - }; - } - 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; + 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 RestoreFocus(_ref) { - let { - disabled - } = _ref; - const { - active, - activatorEvent, - draggableNodes - } = q2(InternalContext); - const previousActivatorEvent = usePrevious(activatorEvent); - const previousActiveId = usePrevious(active == null ? void 0 : active.id); - h2(() => { - if (disabled) { - return; +}; +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" + }); } - 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; - } - } + }, + 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" }); } - }, [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 F( - () => ({ - 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; + 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); } - const node = activeNode == null ? void 0 : activeNode.node.current; - if (!node || node.isConnected === false) { - return; + if (token === "Yo") { + return localize2.ordinalNumber(weekYear, { + unit: "year" + }); } - const rect = measure(node); - const rectDelta = getRectDelta(rect, initialRect); - if (!x5) { - rectDelta.x = 0; + 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" + }); } - if (!y5) { - rectDelta.y = 0; + }, + 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" + }); } - 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 + }, + 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" }); - } } - }, [activeNode, x5, y5, initialRect, measure]); -} -var ActiveDraggableContext = /* @__PURE__ */ B({ - ...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__ */ R(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 = y2(reducer, void 0, getInitialState); - const [state, dispatch] = store; - const [dispatchMonitorEvent, registerMonitorListener] = useDndMonitorProvider(); - const [status, setStatus] = p2(Status.Uninitialized); - const isInitialized = status === Status.Initialized; - const { - draggable: { - active: activeId, - nodes: draggableNodes, - translate - }, - droppable: { - containers: droppableContainers + }, + 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" + }); } - } = state; - const node = activeId ? draggableNodes.get(activeId) : null; - const activeRects = _2({ - initial: null, - translated: null - }); - const active = F(() => { - 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] = p2(null); - const [activatorEvent, setActivatorEvent] = p2(null); - const latestProps = useLatestValue(props2, Object.values(props2)); - const draggableDescribedById = useUniqueId("DndDescribedBy", id2); - const enabledDroppableContainers = F(() => 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 = F(() => 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] = p2(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 - } - }; - sn(() => { - 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) - }); - sn(() => { - setActiveSensor(sensorInstance); - setActivatorEvent(event.nativeEvent); + }, + w: function w4(date, token, localize2, options) { + var week = getUTCWeek(date, options); + if (token === "wo") { + return localize2.ordinalNumber(week, { + unit: "week" }); - 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; - sn(() => { - 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]); - h2( - () => { - 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 - }; - sn(() => { - onDragMove == null ? void 0 : onDragMove(event); - dispatchMonitorEvent({ - type: "onDragMove", - event - }); + return addLeadingZeros(week, token.length); + }, + I: function I3(date, token, localize2) { + var isoWeek = getUTCISOWeek(date); + if (token === "Io") { + return localize2.ordinalNumber(isoWeek, { + unit: "week" }); - }, - [scrollAdjustedTranslate.x, scrollAdjustedTranslate.y] - ); - h2( - () => { - 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 - }; - sn(() => { - setOver(over2); - onDragOver == null ? void 0 : onDragOver(event); - dispatchMonitorEvent({ - type: "onDragOver", - event - }); + } + return addLeadingZeros(isoWeek, token.length); + }, + d: function d4(date, token, localize2) { + if (token === "do") { + return localize2.ordinalNumber(date.getUTCDate(), { + unit: "date" }); - }, - [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 = F(() => { - 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 = F(() => { - 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 bn.createElement(DndMonitorContext.Provider, { - value: registerMonitorListener - }, bn.createElement(InternalContext.Provider, { - value: internalContext - }, bn.createElement(PublicContext.Provider, { - value: publicContext - }, bn.createElement(ActiveDraggableContext.Provider, { - value: transform - }, children)), bn.createElement(RestoreFocus, { - disabled: (accessibility == null ? void 0 : accessibility.restoreFocus) === false - })), bn.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__ */ B(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 lightFormatters_default.d(date, token); + }, + D: function D3(date, token, localize2) { + var dayOfYear = getUTCDayOfYear(date); + if (token === "Do") { + return localize2.ordinalNumber(dayOfYear, { + unit: "dayOfYear" }); - return () => { - const node2 = draggableNodes.get(id2); - if (node2 && node2.key === key2) { - draggableNodes.delete(id2); - } - }; - }, - [draggableNodes, id2] - ); - const memoizedAttributes = F(() => ({ - 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; - 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 resizeObserver = useResizeObserver({ - callback: handleResize, - disabled: resizeObserverDisabled || !active - }); - const handleNodeChange = T2((newElement, previousElement) => { - if (!resizeObserver) { - return; } - if (previousElement) { - resizeObserver.unobserve(previousElement); - resizeObserverConnected.current = false; - } - if (newElement) { - resizeObserver.observe(newElement); + 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" + }); } - }, [resizeObserver]); - const [nodeRef, setNodeRef] = useNodeRef(handleNodeChange); - const dataRef = useLatestValue(data); - h2(() => { - if (!resizeObserver || !nodeRef.current) { - return; + }, + 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" + }); } - 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 () => dispatch({ - type: Action.UnregisterDroppable, - key: key2, - id: id2 - }); - }, - [id2] - ); - h2(() => { - if (disabled !== previous.current.disabled) { - dispatch({ - type: Action.SetDroppableDisabled, - id: id2, - key: key2, - disabled - }); - previous.current.disabled = disabled; + }, + 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" + }); } - }, [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] = p2(null); - const [element, setElement] = p2(null); - const previousChildren = usePrevious(children); - if (!children && !clonedChildren && previousChildren) { - setClonedChildren(previousChildren); - } - useIsomorphicLayoutEffect(() => { - if (!element) { - return; + }, + 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" + }); } - 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; + }, + 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" + }); } - Promise.resolve(animation(id2, element)).then(() => { - setClonedChildren(null); - }); - }, [animation, clonedChildren, element]); - return bn.createElement(bn.Fragment, null, children, clonedChildren ? cn(clonedChildren, { - ref: setElement - }) : null); -} -var defaultTransform = { - x: 0, - y: 0, - scaleX: 1, - scaleY: 1 -}; -function NullifiedContextProvider(_ref) { - let { - children - } = _ref; - return bn.createElement(InternalContext.Provider, { - value: defaultInternalContext - }, bn.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 - }; - return bn.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); + }, + 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"; } - } - if (styles != null && styles.dragOverlay) { - for (const [key2, value] of Object.entries(styles.dragOverlay)) { - if (value === void 0) { - continue; - } - dragOverlay.node.style.setProperty(key2, value); + 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" + }); } - } - 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); + }, + 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; } - if (className != null && className.active) { - active.node.classList.remove(className.active); + 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" + }); } - }; -}; -var defaultKeyframeResolver = (_ref2) => { - let { - transform: { - initial, - final + }, + 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" + }); } - } = _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" - } + return lightFormatters_default.h(date, token); + }, + H: function H4(date, token, localize2) { + if (token === "Ho") { + return localize2.ordinalNumber(date.getUTCHours(), { + unit: "hour" + }); } - }) -}; -function useDropAnimation(_ref3) { - let { - config, - draggableNodes, - droppableContainers, - measuringConfiguration - } = _ref3; - return useEvent((id2, node) => { - if (config === null) { - return; + 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" + }); } - const activeDraggable = draggableNodes.get(id2); - if (!activeDraggable) { - return; + 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" + }); } - const activeNode = activeDraggable.node.current; - if (!activeNode) { - return; + return addLeadingZeros(hours, token.length); + }, + m: function m4(date, token, localize2) { + if (token === "mo") { + return localize2.ordinalNumber(date.getUTCMinutes(), { + unit: "minute" + }); } - const measurableNode = getMeasurableNode(node); - if (!measurableNode) { - return; + return lightFormatters_default.m(date, token); + }, + s: function s4(date, token, localize2) { + if (token === "so") { + return localize2.ordinalNumber(date.getUTCSeconds(), { + unit: "second" + }); } - const { - transform - } = getWindow(node).getComputedStyle(node); - const parsedTransform = parseTransform(transform); - if (!parsedTransform) { - return; + 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 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 - }; - return (_ref4) => { - let { - active, - dragOverlay, - transform, - ...rest - } = _ref4; - if (!duration) { - return; + switch (token) { + case "X": + return formatTimezoneWithOptionalMinutes(timezoneOffset); + case "XXXX": + case "XX": + return formatTimezone(timezoneOffset); + case "XXXXX": + case "XXX": + default: + return formatTimezone(timezoneOffset, ":"); } - const delta = { - x: dragOverlay.rect.left - active.rect.left, - y: dragOverlay.rect.top - active.rect.top - }; - 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 - } - }); - const [firstKeyframe] = animationKeyframes; - const lastKeyframe = animationKeyframes[animationKeyframes.length - 1]; - if (JSON.stringify(firstKeyframe) === JSON.stringify(lastKeyframe)) { - return; + }, + 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, ":"); } - 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(); - }; - }); - }; -} -var key = 0; -function useKey(id2) { - return F(() => { - if (id2 == null) { - return; + }, + 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, ":"); } - key++; - return key; - }, [id2]); -} -var DragOverlay = /* @__PURE__ */ bn.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 ref = initialRect ? dragOverlay.setRef : void 0; - return bn.createElement(NullifiedContextProvider, null, bn.createElement(AnimationManager, { - animation: dropAnimation - }, active && key2 ? bn.createElement(PositionedOverlay, { - key: key2, - id: active.id, - ref, - 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; + }, + 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, ":"); } - 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; + }, + 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); } - for (let i4 = 0; i4 < a5.length; i4++) { - if (a5[i4] !== b4[i4]) { - return false; - } +}; +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); } - return true; + var delimiter = dirtyDelimiter || ""; + return sign + String(hours) + delimiter + addLeadingZeros(minutes, 2); } -function normalizeDisabled(disabled) { - if (typeof disabled === "boolean") { - return { - draggable: disabled, - droppable: disabled - }; +function formatTimezoneWithOptionalMinutes(offset, dirtyDelimiter) { + if (offset % 60 === 0) { + var sign = offset > 0 ? "-" : "+"; + return sign + addLeadingZeros(Math.abs(offset) / 60, 2); } - return disabled; + return formatTimezone(offset, dirtyDelimiter); } -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 - }; +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; +} +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" + }); } - 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; +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" + }); } - if (activeIndex < index) { - return previousRect ? currentRect.left - (previousRect.left + previousRect.width) : nextRect.left - (currentRect.left + currentRect.width); +}; +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); } - 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; + 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" + }); + break; } - return { - x: newRect.left - oldRect.left, - y: newRect.top - oldRect.top, - scaleX: newRect.width / oldRect.width, - scaleY: newRect.height / oldRect.height - }; + return dateTimeFormat.replace("{{date}}", dateLongFormatter(datePattern, formatLong2)).replace("{{time}}", timeLongFormatter(timePattern, formatLong2)); }; -var defaultScale$1 = { - scaleX: 1, - scaleY: 1 +var longFormatters = { + p: timeLongFormatter, + P: dateTimeLongFormatter }; -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 - }; +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")); } - if (index < activeIndex && index >= overIndex) { - return { - x: 0, - y: activeNodeRect.height + itemGap, - ...defaultScale$1 - }; +} + +// 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" } - return { - x: 0, - y: 0, - ...defaultScale$1 - }; }; -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 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()); } - if (activeIndex < index) { - return previousRect ? currentRect.top - (previousRect.top + previousRect.height) : nextRect ? nextRect.top - (currentRect.top + currentRect.height) : 0; + if (options !== null && options !== void 0 && options.addSuffix) { + if (options.comparison && options.comparison > 0) { + return "in " + result; + } else { + return result + " ago"; + } } - return nextRect ? nextRect.top - (currentRect.top + currentRect.height) : previousRect ? currentRect.top - (previousRect.top + previousRect.height) : 0; + 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; + }; } -var ID_PREFIX2 = "Sortable"; -var Context = /* @__PURE__ */ bn.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, - measuringScheduled - } = useDndContext(); - const containerId = useUniqueId(ID_PREFIX2, id2); - const useDragOverlay = Boolean(dragOverlay.rect !== null); - const items = F(() => 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 && !measuringScheduled) { - measureDroppableContainers(items); + +// 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]; } - }, [itemsHaveChanged, items, isDragging, measureDroppableContainers, measuringScheduled]); - h2(() => { - previousItemsRef.current = items; - }, [items]); - const contextValue = F( - () => ({ - 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 bn.createElement(Context.Provider, { - value: contextValue - }, children); + var index = args.argumentCallback ? args.argumentCallback(dirtyIndex) : dirtyIndex; + return valuesArray[index]; + }; } -var defaultNewIndexGetter = (_ref) => { - let { - id: id2, - items, - activeIndex, - overIndex - } = _ref; - return arrayMove(items, activeIndex, overIndex).indexOf(id2); + +// 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 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; +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" } - if (isSorting) { - return true; +}; +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" } - return newIndex !== index && containerId === previousContainerId; }; -var defaultTransition2 = { - duration: 200, - easing: "ease" +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"; }; -var transitionProperty = "transform"; -var disabledTransition = /* @__PURE__ */ CSS.Transition.toString({ - property: transitionProperty, - duration: 0, - easing: "linear" -}); -var defaultAttributes = { - roleDescription: "sortable" +var localize = { + ordinalNumber, + era: buildLocalizeFn({ + values: eraValues, + defaultWidth: "wide" + }), + quarter: buildLocalizeFn({ + values: quarterValues, + defaultWidth: "wide", + argumentCallback: function argumentCallback(quarter) { + return quarter - 1; + } + }), + month: buildLocalizeFn({ + values: monthValues, + defaultWidth: "wide" + }), + day: buildLocalizeFn({ + values: dayValues, + defaultWidth: "wide" + }), + dayPeriod: buildLocalizeFn({ + values: dayPeriodValues, + defaultWidth: "wide", + formattingValues: formattingDayPeriodValues, + defaultFormattingWidth: "wide" + }) }; -function useDerivedTransform(_ref) { - let { - disabled, - index, - node, - rect - } = _ref; - const [derivedTransform, setDerivedtransform] = p2(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 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; } - if (index !== previousIndex.current) { - previousIndex.current = index; + 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; } - }, [disabled, index, node, rect]); - h2(() => { - if (derivedTransform) { - requestAnimationFrame(() => { - setDerivedtransform(null); - }); + } + return void 0; +} +function findIndex(array, predicate) { + for (var key2 = 0; key2 < array.length; key2++) { + if (predicate(array[key2])) { + return key2; } - }, [derivedTransform]); - return derivedTransform; + } + return void 0; } -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 = F(() => ({ - sortable: { - containerId, - index, - items - }, - ...customData - }), [containerId, customData, index, items]); - const itemsAfterCurrentSortable = F(() => items.slice(items.indexOf(id2)), [items, id2]); - const { - rect, - node, - isOver, - setNodeRef: setDroppableNodeRef - } = useDroppable({ - id: id2, - data, - disabled: disabled.droppable, - resizeObserverConfig: { - updateMeasurementsFor: itemsAfterCurrentSortable, - ...resizeObserverConfig - } - }); - const { - active, - activatorEvent, - activeNodeRect, - attributes, - setNodeRef: setDraggableNodeRef, - listeners, - isDragging, - over, - setActivatorNodeRef, - transform - } = useDraggable({ - id: id2, - data, - 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 = animateLayoutChanges3({ - 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 - }); - h2(() => { - if (isSorting && previous.current.newIndex !== newIndex) { - previous.current.newIndex = newIndex; - } - if (containerId !== previous.current.containerId) { - previous.current.containerId = containerId; - } - if (items !== previous.current.items) { - previous.current.items = items; - } - }, [isSorting, newIndex, containerId, items]); - h2(() => { - if (activeId === previous.current.activeId) { - return; - } - 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, - rect, - index, - newIndex, - items, - isOver, - isSorting, - isDragging, - listeners, - node, - overIndex, - over, - setNodeRef, - setActivatorNodeRef, - setDroppableNodeRef, - setDraggableNodeRef, - transform: derivedTransform != null ? derivedTransform : finalTransform, - transition: getTransition() + +// 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 + }; }; - function getTransition() { - if (derivedTransform || itemsHaveChanged && previous.current.newIndex === index) { - return disabledTransition; - } - if (shouldDisplaceDragSource && !isKeyboardEvent(activatorEvent) || !transition) { - return void 0; +} + +// node_modules/date-fns/esm/locale/en-US/_lib/match/index.js +var matchOrdinalNumberPattern = /^(\d+)(th|st|nd|rd)?/i; +var parseOrdinalNumberPattern = /\d+/i; +var matchEraPatterns = { + narrow: /^(b|a)/i, + abbreviated: /^(b\.?\s?c\.?|b\.?\s?c\.?\s?e\.?|a\.?\s?d\.?|c\.?\s?e\.?)/i, + wide: /^(before christ|before common era|anno domini|common era)/i +}; +var parseEraPatterns = { + any: [/^b/i, /^(a|c)/i] +}; +var matchQuarterPatterns = { + narrow: /^[1234]/i, + abbreviated: /^q[1234]/i, + wide: /^[1234](th|st|nd|rd)? quarter/i +}; +var parseQuarterPatterns = { + any: [/1/i, /2/i, /3/i, /4/i] +}; +var matchMonthPatterns = { + narrow: /^[jfmasond]/i, + abbreviated: /^(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)/i, + wide: /^(january|february|march|april|may|june|july|august|september|october|november|december)/i +}; +var parseMonthPatterns = { + narrow: [/^j/i, /^f/i, /^m/i, /^a/i, /^m/i, /^j/i, /^j/i, /^a/i, /^s/i, /^o/i, /^n/i, /^d/i], + any: [/^ja/i, /^f/i, /^mar/i, /^ap/i, /^may/i, /^jun/i, /^jul/i, /^au/i, /^s/i, /^o/i, /^n/i, /^d/i] +}; +var matchDayPatterns = { + narrow: /^[smtwf]/i, + short: /^(su|mo|tu|we|th|fr|sa)/i, + abbreviated: /^(sun|mon|tue|wed|thu|fri|sat)/i, + wide: /^(sunday|monday|tuesday|wednesday|thursday|friday|saturday)/i +}; +var parseDayPatterns = { + narrow: [/^s/i, /^m/i, /^t/i, /^w/i, /^t/i, /^f/i, /^s/i], + any: [/^su/i, /^m/i, /^tu/i, /^w/i, /^th/i, /^f/i, /^sa/i] +}; +var matchDayPeriodPatterns = { + narrow: /^(a|p|mi|n|(in the|at) (morning|afternoon|evening|night))/i, + any: /^([ap]\.?\s?m\.?|midnight|noon|(in the|at) (morning|afternoon|evening|night))/i +}; +var parseDayPeriodPatterns = { + any: { + am: /^a/i, + pm: /^p/i, + midnight: /^mi/i, + noon: /^no/i, + morning: /morning/i, + afternoon: /afternoon/i, + evening: /evening/i, + night: /night/i + } +}; +var match = { + ordinalNumber: buildMatchPatternFn({ + matchPattern: matchOrdinalNumberPattern, + parsePattern: parseOrdinalNumberPattern, + valueCallback: function valueCallback(value) { + return parseInt(value, 10); } - if (isSorting || shouldAnimateLayoutChanges) { - return CSS.Transition.toString({ - ...transition, - property: transitionProperty - }); + }), + 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; } - return void 0; + }), + 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 } -} -function normalizeLocalDisabled(localDisabled, globalDisabled) { - var _localDisabled$dragga, _localDisabled$droppa; - if (typeof localDisabled === "boolean") { - return { - draggable: localDisabled, - droppable: false - }; +}; +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"); } - 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; + 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"); } - 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; + if (!locale2.localize) { + throw new RangeError("locale must contain localize property"); } - return false; -} -var directions = [KeyboardCode.Down, KeyboardCode.Right, KeyboardCode.Up, KeyboardCode.Left]; -var sortableKeyboardCoordinates = (event, _ref) => { - let { - context: { - active, - collisionRect, - droppableRects, - droppableContainers, - over, - scrollableAncestors + if (!locale2.formatLong) { + throw new RangeError("locale must contain formatLong property"); + } + 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); } - } = _ref; - if (directions.includes(event.code)) { - event.preventDefault(); - if (!active || !collisionRect) { - return; + return substring; + }).join("").match(formattingTokensRegExp).map(function(substring) { + if (substring === "''") { + return "'"; } - const filteredContainers = []; - droppableContainers.getEnabled().forEach((entry) => { - if (!entry || entry != null && entry.disabled) { - return; - } - const rect = droppableRects.get(entry.id); - if (!rect) { - return; + var firstCharacter = substring[0]; + if (firstCharacter === "'") { + return cleanEscapedString(substring); + } + var formatter = formatters_default[firstCharacter]; + if (formatter) { + if (!(options !== null && options !== void 0 && options.useAdditionalWeekYearTokens) && isProtectedWeekYearToken(substring)) { + throwProtectedError(substring, dirtyFormatStr, String(dirtyDate)); } - 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; + if (!(options !== null && options !== void 0 && options.useAdditionalDayOfYearTokens) && isProtectedDayOfYearToken(substring)) { + throwProtectedError(substring, dirtyFormatStr, String(dirtyDate)); } - }); - 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; + return formatter(utcDate, substring, locale2.localize, formatterOptions); } - 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; - } + 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 void 0; -}; -function isSameContainer(a5, b4) { - if (!hasSortableData(a5) || !hasSortableData(b4)) { - return false; - } - return a5.data.current.sortable.containerId === b4.data.current.sortable.containerId; + return matched[1].replace(doubleQuoteRegExp, "'"); } -function isAfter2(a5, b4) { - if (!hasSortableData(a5) || !hasSortableData(b4)) { - return false; + +// 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"); } - if (!isSameContainer(a5, b4)) { - return false; + for (var property in object) { + if (Object.prototype.hasOwnProperty.call(object, property)) { + ; + target[property] = object[property]; + } } - return a5.data.current.sortable.index < b4.data.current.sortable.index; + return target; } -// src/components/ContextView/CardsView/CardsView.tsx -var import_classnames3 = __toESM(require_classnames()); +// node_modules/date-fns/esm/_lib/cloneObject/index.js +function cloneObject(object) { + return assign({}, object); +} -// 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); - } - return array.filter((f4, i4) => i4 < lastIndex && i4 >= newIndex); -}; +// 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); + } + 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); + } + } + } 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); + } + } +} -// src/components/ui/menus/selectMenu/concerns/matchers.js -function escapeForRegExp(string) { - return string.replace(/[-\\^$*+?.()|[\]{}]/g, "\\$&"); +// 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 matchAny(string) { - return new RegExp(escapeForRegExp(string), "gi"); + +// 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 matchExact(string) { - return new RegExp(`^${escapeForRegExp(string)}$`, "i"); + +// node_modules/date-fns/esm/getTime/index.js +function getTime(dirtyDate) { + requiredArgs(1, arguments); + var date = toDate(dirtyDate); + var timestamp = date.getTime(); + return timestamp; } -// src/components/ContextView/MDBContext.tsx -var import_lodash4 = __toESM(require_lodash()); -var import_obsidian8 = require("obsidian"); +// node_modules/date-fns/esm/getUnixTime/index.js +function getUnixTime(dirtyDate) { + requiredArgs(1, arguments); + return Math.floor(getTime(dirtyDate) / 1e3); +} -// src/utils/contexts/predicate/filter.ts -var stringEqual = (value, filterValue) => { - return value == filterValue; -}; -var stringCompare = (value, filterValue) => { - return (value != null ? value : "").toLowerCase().includes((filterValue != null ? filterValue : "").toLowerCase()); -}; -var greaterThan = (value, filterValue) => { - return parseFloat(value) > parseFloat(filterValue); -}; -var lessThan = (value, filterValue) => { - return parseInt(value) > parseInt(filterValue); -}; -var listIncludes = (value, filterValue) => { - const valueList = value ? splitString(value) : []; - const strings = filterValue ? splitString(filterValue) : []; - return strings.some((f4) => valueList.some((g4) => g4 == f4)); -}; -var filterFnTypes = { - include: { - type: ["text", "file", "link", "link-multi", "fileprop"], - fn: stringCompare, - label: i18n_default.filterTypes.contains, - valueType: "text" - }, - notInclude: { - type: ["text", "file", "link", "link-multi", "fileprop"], - fn: (v3, f4) => !stringCompare(v3, f4), - label: i18n_default.filterTypes.notContains, - valueType: "text" - }, - is: { - type: ["text", "file", "link", "context", "fileprop"], - fn: stringEqual, - label: i18n_default.filterTypes.is, - valueType: "text" - }, - isNot: { - type: ["text", "file", "link", "context", "fileprop"], - fn: (v3, f4) => !stringEqual(v3, f4), - label: i18n_default.filterTypes.isNot, - valueType: "text" - }, - equal: { - type: ["number"], - fn: stringEqual, - label: "=", - valueType: "number" - }, - isGreatThan: { - type: ["number"], - fn: greaterThan, - label: ">", - valueType: "number" - }, - isLessThan: { - type: ["number"], - fn: lessThan, - label: "<", - valueType: "number" - }, - isLessThanOrEqual: { - type: ["number"], - fn: (v3, f4) => !greaterThan(v3, f4), - label: "\u2264", - valueType: "number" - }, - isGreatThanOrEqual: { - type: ["number"], - fn: (v3, f4) => !lessThan(v3, f4), - label: "\u2265", - valueType: "number" - }, - dateBefore: { - type: ["date"], - fn: lessThan, - label: i18n_default.filterTypes.before, - valueType: "date" - }, - dateAfter: { - type: ["date"], - fn: greaterThan, - label: i18n_default.filterTypes.after, - valueType: "date" - }, - isAnyInList: { - type: ["option", "context", "option-multi", "context-multi"], - fn: listIncludes, - label: i18n_default.filterTypes.anyOf, - valueType: "list" - }, - isNoneInList: { - type: ["option", "context", "option-multi", "context-multi"], - fn: (v3, f4) => !listIncludes(v3, f4), - label: i18n_default.filterTypes.noneOf, - valueType: "list" - }, - isTrue: { - type: ["boolean"], - fn: (v3, f4) => v3 == "true", - label: i18n_default.filterTypes.checked, - valueType: "boolean" - }, - isFalse: { - type: ["boolean"], - fn: (v3, f4) => v3 != "true", - label: i18n_default.filterTypes.unchecked, - valueType: "boolean" +// 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 filterReturnForCol = (col, filter, row) => { - if (!col) - return true; - const filterType = filterFnTypes[filter.type]; - let result = true; - if (filterType) { - result = filterType.fn(row[filter.field], filter.value); + 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; } - return result; -}; +} -// src/utils/contexts/predicate/sort.ts -var simpleSort = (a5, b4) => { - if (a5 < b4) - return -1; - if (a5 > b4) - return 1; - return 0; +// 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 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_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: ")" } }; -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(splitString(value).length, splitString(filterValue).length); -var normalizedSortForType = (type, desc) => { - return Object.keys(sortFnTypes).find( - (f4) => sortFnTypes[f4].type.some((g4) => g4 == type) && sortFnTypes[f4].desc == desc - ); +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 sortFnTypes = { - alphabetical: { - type: ["text", "file", "link", "context"], - fn: stringSort, - label: i18n_default.sortTypes.alphaAsc, - desc: false - }, - reverseAlphabetical: { - type: ["text", "file", "link", "context"], - fn: (v3, f4) => stringSort(v3, f4) * -1, - label: i18n_default.sortTypes.alphaDesc, - desc: true - }, - earliest: { - type: ["date"], - fn: stringSort, - label: i18n_default.sortTypes.earliest, - desc: false - }, - latest: { - type: ["date"], - 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"], - fn: numSort, - label: "1 \u2192 9", - desc: false - }, - reverseNumber: { - type: ["number"], - 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 decodeLink = (value) => { + return value ? value.replace(/🕌🔧/gu, "[[").replace(/🐓🐀/gu, "]]") : value; }; -var sortReturnForCol = (col, sort, row, row2) => { - if (!col) - return 0; - const sortType = sortFnTypes[sort.type]; - if (sortType) { - return sortType.fn(row[sort.field], row2[sort.field]); +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}` + }); + } + next = sR.next(); } - return 0; + return newFields; }; - -// src/components/ui/modals/vaultChangeModals.ts -var import_obsidian6 = require("obsidian"); -var VaultChangeModal = class extends import_obsidian6.Modal { - constructor(plugin, file, action, space) { - super(plugin.app); - this.file = file; - this.action = action; - this.plugin = plugin; - this.space = space; +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"); + } } - onOpen() { - let { contentEl } = this; - let 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") { - inputEl.value = this.file.name.substring( - 0, - this.file.name.lastIndexOf(".") + 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() : []; + 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); + }); + return decodeLink(encodedLine); } - 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") { - newName = this.file.name.lastIndexOf(".") == -1 ? newName : newName + this.file.name.substring(this.file.name.lastIndexOf(".")); - renameFile(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_obsidian6.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(); + }); + 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 }); } - onClose() { - let { contentEl } = this; - contentEl.empty(); +} + +// 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 (/^\d{4}-\d{2}-\d{2}$/.test(value)) { + return "date"; + } + if (key2 == "tag" || key2 == "tags") { + return "tag"; + } + if (/\[\[.*?\]\]/.test(value)) { + return "link"; + } + } 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 (key2 == "tag" || key2 == "tags") { + return "tag-multi"; + } + if (arrayValue.length == 1 && Array.isArray(arrayValue[0]) && arrayValue[0].length == 1 && typeof arrayValue[0][0] === "string") { + return "link"; + } + const types = uniq(arrayValue.map((f4) => detectYAMLType(f4, key2))); + if (types.length == 1 && types[0] == "link") { + return "link-multi"; + } + 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"; }; -var MoveSuggestionModal = class extends import_obsidian6.FuzzySuggestModal { - constructor(app2, files) { - super(app2); - this.files = files; + +// 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; } - getItemText(item) { - return item.path; + 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]); + }); + }); } - getItems() { - return getAllFoldersInVault(this.app); +}; +var frontMatterForFile = (file) => { + let currentCache; + if (file instanceof import_obsidian5.TFile && app.metadataCache.getFileCache(file) !== null) { + currentCache = app.metadataCache.getFileCache(file); } - onChooseItem(item, evt) { - this.files.forEach((f4) => { - const file = getAbstractFileAtPath(app, f4); - if (file) { - this.app.vault.rename(file, item.path + "/" + file.name); + return currentCache == null ? void 0 : currentCache.frontmatter; +}; +var mergeTableData = (mdb, yamlmdb, types) => { + 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; + }) + }; +}; +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) }), + {} + ); + }); + 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 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; }; -function getAllFoldersInVault(app2) { - let folders = []; - let rootFolder = app2.vault.getRoot(); - folders.push(rootFolder); - function recursiveFx(folder) { - for (let child of folder.children) { - if (child instanceof import_obsidian6.TFolder) { - let childFolder = child; - folders.push(childFolder); - if (childFolder.children) - recursiveFx(childFolder); - } +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]; + } + }); } } - recursiveFx(rootFolder); - return folders; -} -var AddToSpaceModal = class extends import_obsidian6.FuzzySuggestModal { - constructor(plugin, files) { - super(app); - this.plugin = plugin; - this.files = files; +}; +var defaultValueForType = (value, type) => { + if (type == "date") { + return format(Date.now(), "yyyy-MM-dd"); } - getItemText(space) { - return space.name; + if (type == "number") { + return 0; } - getItems() { - return retrieveSpaces(this.plugin); + if (type == "boolean") { + return true; } - onChooseItem(space, evt) { - this.files.forEach((f4) => { - const file = getAbstractFileAtPath(app, f4); - if (file) { - insertSpaceItemAtIndex(this.plugin, space.name, file.path, 0); - } - }); + 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"; } }; - -// 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: [] +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); + } + }); + } + } }; - -// src/dispatch/spaces.ts -var dispatchSpaceDatabaseFileChanged = (type) => { - let evt = new CustomEvent(eventTypes.spacesChange, { - detail: { - changeType: type +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]; + } + } + }); } - }); - window.dispatchEvent(evt); + } }; -var onFileCreated2 = async (plugin, newPath, folder) => { - var _a2; - const parent = (_a2 = getAbstractFileAtPath(app, newPath).parent) == null ? void 0 : _a2.path; - const db = plugin.spaceDBInstance(); - insertIntoDB( - db, - { - vault: { - ...vaultSchema, - rows: [ - { - path: newPath, - parent, - created: Math.trunc(Date.now() / 1e3).toString(), - folder: folder ? "true" : "false" +var saveFrontmatterValue = (plugin, path, key2, value, type, forceSave) => { + let afile = getAbstractFileAtPath(app, path); + const fileCache = plugin.index.files.get(path); + if (afile && fileCache) { + if (fileCache.isFolder && fileCache.folderNote) { + afile = getAbstractFileAtPath(app, path + ".md"); + } + if (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, 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); + } } - ] + }); } - }, - true - ); - plugin.saveSpacesDB(); - dispatchSpaceDatabaseFileChanged("vault"); -}; -var onFileDeleted2 = (plugin, oldPath) => { - const db = plugin.spaceDBInstance(); - deleteFromDB(db, "vault", `path = '${sanitizeSQLStatement(oldPath)}'`); - deleteFromDB(db, "spaceItems", `path = '${sanitizeSQLStatement(oldPath)}'`); - plugin.saveSpacesDB(); - dispatchSpaceDatabaseFileChanged("vault"); + } + } }; -var onFileChanged2 = (plugin, oldPath, newPath) => { - const newFolderPath = getFolderPathFromString(newPath); - const db = plugin.spaceDBInstance(); - updateDB( - db, - { - vault: { - uniques: [], - cols: ["path", "parent"], - rows: [{ path: newPath, oldPath, parent: newFolderPath }] + +// 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; } - }, - "path", - "oldPath" - ); - updateDB( - db, - { - spaceItems: { - uniques: [], - cols: ["path"], - rows: [{ path: newPath, oldPath }] + 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; + } + return value.path; } - }, - "path", - "oldPath" - ); - plugin.saveSpacesDB(); - dispatchSpaceDatabaseFileChanged("vault"); + break; + case "text": + case "tag": + case "image": + return value; + break; + } + return ""; }; -var onFolderChanged2 = (plugin, oldPath, newPath) => { - const newFolderPath = getFolderFromPath(app, newPath).parent.path; - const db = plugin.spaceDBInstance(); - updateDB( - db, - { - vault: { - uniques: [], - cols: ["path", "parent"], - rows: [{ path: newPath, oldPath, parent: newFolderPath }] - } - }, - "path", - "oldPath" - ); - execQuery( - db, - `UPDATE vault SET parent=REPLACE(parent,'${sanitizeSQLStatement( - oldPath - )}','${sanitizeSQLStatement( - newPath - )}') WHERE parent LIKE '${sanitizeSQLStatement(oldPath)}%';` - ); - execQuery( - db, - `UPDATE vault SET path=REPLACE(path,'${sanitizeSQLStatement( - oldPath - )}','${sanitizeSQLStatement( - newPath - )}') WHERE path LIKE '${sanitizeSQLStatement(oldPath)}%/';` - ); - updateDB( - db, - { - spaceItems: { - uniques: [], - cols: ["path"], - rows: [{ path: newPath, oldPath }] - } - }, - "path", - "oldPath" + +// src/utils/contexts/predicate/predicate.tsx +var defaultPredicateFnForType = (type, types) => { + const fnType = Object.keys(types).find( + (f4) => types[f4].type.find((g4) => g4 == type) ); - plugin.saveSpacesDB(); - dispatchSpaceDatabaseFileChanged("vault"); -}; -var onFolderDeleted2 = (plugin, oldPath) => { - const db = plugin.spaceDBInstance(); - deleteFromDB( - db, - "vault", - `path = '${sanitizeSQLStatement( - oldPath - )}' OR parent LIKE '${sanitizeSQLStatement(oldPath)}%'` + return fnType; +}; +var predicateFnsForType = (type, types) => { + const fnTypes = Object.keys(types).filter( + (f4) => types[f4].type.find((g4) => g4 == type) ); - deleteFromDB(db, "spaceItems", `path = '${sanitizeSQLStatement(oldPath)}'`); - plugin.saveSpacesDB(); - dispatchSpaceDatabaseFileChanged("vault"); + return fnTypes; }; - -// src/utils/spaces/spaces.ts -var import_obsidian7 = require("obsidian"); -var rebuildIndex = async (plugin) => { - console.time("Reindex Spaces Data"); - const db = plugin.spaceDBInstance(); - indexCurrentFileTree(db); - plugin.saveSpacesDB(); - dispatchSpaceDatabaseFileChanged("vault"); - console.timeEnd("Reindex Spaces Data"); -}; -var spaceItemToTreeNode = (space, collapsed, sortable) => { - return { - id: space.name, - spaceItem: space, - parentId: null, - depth: 0, - index: 0, - space: 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, - index: i4, - collapsed, - sortable, - childrenCount -}); -var folderSortFn = (sortStrategy, direction) => (a5, b4) => { - if (sortStrategy == "rank") { - return a5.rank.localeCompare(b4.rank, void 0, { numeric: true }); - } - const sortFns = [ - compareByField("folder", 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) => { - let items = []; - let i4 = index; - vaultItems2[path].sort(folderSortFn(sortStrategy, direction)).forEach((item) => { - const collapsed = !openNodes2.includes(item.path); - i4 = i4 + 1; - let newItems = []; - if (vaultItems2[item.path] && !collapsed) { - newItems.push( - ...flattenTree(item.path, vaultItems2, openNodes2, depth2 + 1, i4) - ); - } - 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) => { - var _a2; - if (!path) - return null; - const db = plugin.spaceDBInstance(); - const table = selectDB(db, "vault", `path='${sanitizeSQLStatement(path)}'`); - return (_a2 = table == null ? void 0 : table.rows) == null ? void 0 : _a2[0]; -}; -var saveFileSticker = (plugin, path, sticker) => { - const db = plugin.spaceDBInstance(); - updateDB( - db, - { - vault: { - ...vaultSchema, - cols: ["path", "sticker"], - rows: [{ path, sticker }] - } - }, - "path", - "path" - ); - plugin.saveSpacesDB(); - dispatchSpaceDatabaseFileChanged("sticker"); -}; -var saveFileColor = (plugin, path, color) => { - const db = plugin.spaceDBInstance(); - updateDB( - db, - { - vault: { - ...vaultSchema, - cols: ["path", "color"], - rows: [{ path, color }] - } - }, - "path", - "path" - ); - plugin.saveSpacesDB(); - dispatchSpaceDatabaseFileChanged("sticker"); -}; -var saveSpaceSticker = (plugin, name, sticker) => { - const db = plugin.spaceDBInstance(); - updateDB( - db, - { - spaces: { - ...spaceSchema, - cols: ["name", "sticker"], - rows: [{ name, sticker }] - } - }, - "name", - "name" - ); - plugin.saveSpacesDB(); - dispatchSpaceDatabaseFileChanged("space"); -}; -var updateFileRank = (plugin, item, vaultTree, rank) => { - const db = plugin.spaceDBInstance(); - if (Object.keys(vaultTree).includes(item.parent)) { - let fixedRank = rank; - if (parseInt(item.rank) > rank) - fixedRank = rank + 1; - const newItems = insert( - vaultTree[item.parent].filter((f4) => f4.path != item.path), - fixedRank, - item - ).map((f4, index) => ({ path: f4.path, rank: index.toString() })); - updateDB( - db, - { - vault: { - ...vaultSchema, - cols: ["path", "rank"], - rows: newItems - } - }, - "path", - "path" - ); - plugin.saveSpacesDB(); - dispatchSpaceDatabaseFileChanged("vault"); - } -}; -var moveAFileToNewParentAtIndex = (plugin, item, newParent, vaultTree, index) => { - var _a2; - const currFile = getAbstractFileAtPath(app, item.path); - const newPath = newParent == "/" ? currFile.name : newParent + "/" + currFile.name; - const newItem = { - ...item, - path: newPath, - parent: newParent, - rank: index.toString() - }; - if (Object.keys(vaultTree).includes(newParent)) { - vaultTree[newParent] = insert(vaultTree[newParent], index, newItem); - const db = plugin.spaceDBInstance(); - const table = selectDB( - db, - "vault", - `parent='${sanitizeSQLStatement(newParent)}'` - ); - const rows = insert( - (_a2 = table == null ? void 0 : table.rows.sort( - (a5, b4) => a5.rank.localeCompare(b4.rank, void 0, { numeric: true }) - )) != null ? _a2 : [], - index, - newItem - ).map((f4, index2) => ({ ...f4, rank: index2.toString() })); - insertIntoDB(db, { - vault: { - ...vaultSchema, - rows: [newItem] - } - }); - deleteFromDB(db, "vault", `path='${sanitizeSQLStatement(item.path)}'`); - updateDB( - db, - { - vault: { - ...vaultSchema, - cols: ["path", "rank"], - rows - } - }, - "path", - "path" - ); - plugin.saveSpacesDB(); - const afile = getAbstractFileAtPath(app, item.path); - moveFile(getAbstractFileAtPath(app, newParent), afile); - } else { - const afile = getAbstractFileAtPath(app, item.path); - moveFile(getAbstractFileAtPath(app, newParent), afile); - } -}; -var insertSpaceAtIndex = (plugin, space, pinned, rank, def) => { - const db = plugin.spaceDBInstance(); - let newSpace = { name: space, pinned: pinned ? "true" : "false", def }; - const spaces2 = retrieveSpaces(plugin); - const spaceExists = spaces2.find((f4) => f4.name == space); - let fixedRank = rank; - if (spaceExists) { - updateDB( - db, - { - spaces: { - ...spaceSchema, - rows: [{ ...spaceExists, ...newSpace }] - } - }, - "name", - "name" - ); - if (parseInt(spaceExists.rank) < rank) - fixedRank = rank - 1; - } else { - insertIntoDB(db, { - spaces: { - ...spaceSchema, - rows: [newSpace] - } - }); - } - const newSpaces = insert( - spaces2.filter((f4) => f4.name != space), - fixedRank, - newSpace - ).map((f4, index) => ({ name: f4.name, rank: index.toString() })); - updateDB( - db, - { - spaces: { - ...spaceSchema, - cols: ["name", "rank"], - rows: newSpaces - } - }, - "name", - "name" - ); - plugin.saveSpacesDB(); - dispatchSpaceDatabaseFileChanged("space"); -}; -var insertSpaceItemAtIndex = (plugin, spaceName, path, rank) => { - var _a2; - const db = plugin.spaceDBInstance(); - const space = retrieveSpaces(plugin).find((f4) => f4.name == spaceName); - if (!space) - return; - let newSpace = { - space: space.name, - path, - rank: rank.toString() - }; - const spaceItems = retrieveSpaceItems(plugin, [space]); - const spaceExists = (_a2 = spaceItems[space.name]) != null ? _a2 : []; - const pathExists = spaceExists.find((f4) => f4.path == path); - let fixedRank = rank; - if (!pathExists) { - insertIntoDB(db, { - spaceItems: { - ...spaceItemsSchema, - rows: [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() - })); - updateDB( - db, - { - spaceItems: { - ...spaceItemsSchema, - rows: newSpaceItems - } - }, - `space='${space.name}' AND path`, - "path" - ); - plugin.saveSpacesDB(); - dispatchSpaceDatabaseFileChanged("space"); -}; -var renameSpace = (plugin, space, newName) => { - const db = plugin.spaceDBInstance(); - updateDB( - db, - { - spaces: { - ...spaceSchema, - cols: ["name"], - rows: [{ oldName: space, name: newName }] - } - }, - "name", - "oldName" - ); - updateDB( - db, - { - spaceItems: { - ...spaceItemsSchema, - cols: ["space"], - rows: [{ oldSpace: space, space: newName }] - } - }, - "space", - "oldSpace" - ); - plugin.saveSpacesDB(); - plugin.settings.expandedSpaces = plugin.settings.expandedSpaces.map( - (f4) => f4 == space ? newName : f4 - ); - plugin.saveSettings(); - dispatchSpaceDatabaseFileChanged("space"); -}; -var removeSpace = (plugin, space) => { - const db = plugin.spaceDBInstance(); - deleteFromDB(db, "spaces", `name='${sanitizeSQLStatement(space)}'`); - deleteFromDB(db, "spaceItems", `space='${sanitizeSQLStatement(space)}'`); - plugin.saveSpacesDB(); - dispatchSpaceDatabaseFileChanged("space"); -}; -var updateSpaceSort = (plugin, space, sort) => { - const db = plugin.spaceDBInstance(); - updateDB( - db, - { - spaces: { - ...spaceSchema, - cols: ["name", "sort"], - rows: [{ name: space, sort: JSON.stringify(sort) }] - } - }, - "name", - "name" - ); - plugin.saveSpacesDB(); - dispatchSpaceDatabaseFileChanged("space"); -}; -var toggleSpacePin = (plugin, space, state) => { - const db = plugin.spaceDBInstance(); - updateDB( - db, - { - spaces: { - ...spaceSchema, - cols: ["name", "pinned"], - rows: [{ name: space, pinned: state ? "true" : "false" }] - } - }, - "name", - "name" - ); - plugin.saveSpacesDB(); - dispatchSpaceDatabaseFileChanged("space"); -}; -var addPathsToSpace = (plugin, space, paths) => { - const db = plugin.spaceDBInstance(); - insertIntoDB(db, { - spaceItems: { - ...spaceItemsSchema, - rows: [...paths.map((p3) => ({ space, path: p3 }))] - } - }); - plugin.saveSpacesDB(); - dispatchSpaceDatabaseFileChanged("space"); -}; -var removePathsFromSpace = (plugin, space, paths) => { - const db = plugin.spaceDBInstance(); - paths.forEach( - (path) => deleteFromDB( - db, - "spaceItems", - `space='${sanitizeSQLStatement(space)}' AND path='${sanitizeSQLStatement( - path - )}'` - ) - ); - plugin.saveSpacesDB(); - dispatchSpaceDatabaseFileChanged("space"); -}; -var retrieveSpaces = (plugin) => { - const db = plugin.spaceDBInstance(); - const table = selectDB(db, "spaces"); - if (table) { - return table.rows.sort( - (a5, b4) => a5.rank.localeCompare(b4.rank, void 0, { numeric: true }) - ); - } - return []; -}; -var retrieveSpaceItems = (plugin, spaces2) => { - const db = plugin.spaceDBInstance(); - let retrievedSpaces = {}; - spaces2.forEach((space) => { - var _a2, _b2, _c2, _d2; - const table = selectDB( - db, - "spaceItems", - `space='${sanitizeSQLStatement(space.name)}'` - ); - let rows = (_a2 = table == null ? void 0 : table.rows) != null ? _a2 : []; - if (((_b2 = space.def) == null ? void 0 : _b2.length) > 0) { - const spaceItems = ((_d2 = (_c2 = selectDB(db, "vault", `parent='${sanitizeSQLStatement(space.def)}'`)) == null ? void 0 : _c2.rows) != null ? _d2 : []).filter(excludeVaultItemPredicate(plugin)); - const extraItems = rows.filter( - (f4) => !spaceItems.some((g4) => g4.path == f4.path) - ); - rows = rows.filter((f4) => !extraItems.some((g4) => f4.path == g4.path)); - extraItems.forEach( - (row) => deleteFromDB( - db, - "spaceItems", - `space='${sanitizeSQLStatement( - space.name - )}' AND path='${sanitizeSQLStatement(row.path)}'` - ) - ); - spaceItems.forEach((row) => { - if (!rows.some((f4) => f4.path == row.path)) { - const newItem = { space: space.name, path: row.path, rank: "0" }; - insertIntoDB(db, { - spaceItems: { - ...spaceItemsSchema, - rows: [newItem] - } - }); - rows.push(newItem); - } - }); - } - retrievedSpaces[space.name] = rows.sort( - (a5, b4) => a5.rank.localeCompare(b4.rank, void 0, { numeric: true }) - ); - }); - return retrievedSpaces; -}; -var retrieveFolders = async (plugin, paths) => { - const db = plugin.spaceDBInstance(); - let retrievedFolders = {}; - paths.forEach((folder) => { - const table = selectDB( - db, - "vault", - `parent='${sanitizeSQLStatement(folder)}'` - ); - if (table) { - retrievedFolders[folder] = table.rows.filter( - excludeVaultItemPredicate(plugin) - ); - } - }); - return retrievedFolders; -}; -var retrieveAllFiles = async (plugin) => { - const db = plugin.spaceDBInstance(); - let retrievedFolders = {}; - const table = selectDB( - db, - "vault" - ); - if (table) { - return table.rows.filter( - excludeVaultItemPredicate(plugin) - ); - } - return []; -}; -var migrateIndex = async (plugin) => { - console.time("Migrate Spaces Data"); - const db = plugin.spaceDBInstance(); - initiateDB(db); - indexCurrentFileTree(db); - mergeCurrentRanks(db, plugin.settings.folderRank); - mergeExistingFileIcons(db, plugin.settings.fileIcons); - mergeSpaces(db, plugin.settings.spaces); - plugin.saveSpacesDB(); - dispatchSpaceDatabaseFileChanged("vault"); - plugin.settings.folderRank = null; - plugin.settings.fileIcons = null; - plugin.settings.spaces = null; - plugin.saveSettings(); - console.timeEnd("Migrate Spaces Data"); -}; -var initiateDB = (db) => { - replaceDB(db, { - vault: vaultSchema, - spaces: spaceSchema, - spaceItems: spaceItemsSchema - }); -}; -var indexCurrentFileTree = (db) => { - var _a2, _b2; - let treeItems = []; - import_obsidian7.Vault.recurseChildren(app.vault.getRoot(), (file) => { - var _a3; - treeItems.push({ - path: file.path, - parent: (_a3 = file.parent) == null ? void 0 : _a3.path, - created: file instanceof import_obsidian7.TFile ? file.stat.ctime.toString() : void 0, - folder: file instanceof import_obsidian7.TFolder ? "true" : "false" - }); - }); - const currentPaths = (_b2 = (_a2 = selectDB(db, "vault")) == null ? void 0 : _a2.rows) != null ? _b2 : []; - 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) - ); - fixRows.forEach((row) => { - updateDB(db, { vault: { ...vaultSchema, rows: [row] } }, "path", "path"); - }); - deleteRows.forEach((path) => { - deleteFromDB(db, "vault", `path='${sanitizeSQLStatement(path.path)}'`); - }); - deleteRows.forEach((path) => { - deleteFromDB(db, "spaceItems", `path='${sanitizeSQLStatement(path.path)}'`); - }); - const chunkSize = 20; - for (let i4 = 0; i4 < newRows.length; i4 += chunkSize) { - const chunk = newRows.slice(i4, i4 + chunkSize); - insertIntoDB(db, { - vault: { - ...vaultSchema, - rows: chunk - } - }); - } -}; -var mergeExistingFileIcons = (db, fileIcons) => { - const dbRows = fileIcons.map(([path, sticker]) => ({ - path, - sticker - })); - updateDB( - db, - { - vault: { - uniques: [], - cols: ["sticker"], - rows: dbRows - } - }, - "path", - "path" - ); -}; -var mergeCurrentRanks = (db, ranks) => { - const flattenStringTreeChildren = (path, children) => { - const dbRows2 = []; - children.forEach((item, index) => { - dbRows2.push({ - path: path + item.node, - rank: index.toString() - }); - if (item.children.length > 0) { - dbRows2.push( - ...flattenStringTreeChildren(path + item.node + "/", item.children) - ); - } - }); - return dbRows2; - }; - const dbRows = flattenStringTreeChildren("", ranks.children); - updateDB( - db, - { - vault: { - uniques: [], - cols: ["rank"], - rows: dbRows - } - }, - "path", - "path" - ); -}; -var mergeSpaces = (db, sectionTrees) => { - let spaces2 = []; - let spaceItems = []; - sectionTrees.forEach((space, index) => { - spaces2.push({ name: space.section, rank: index.toString() }); - spaceItems.push( - ...space.children.map((f4, index2) => ({ - space: space.section, - path: f4, - rank: index2.toString() - })) - ); - }); - insertIntoDB(db, { - spaces: { - ...spaceSchema, - rows: spaces2 - }, - spaceItems: { - ...spaceItemsSchema, - rows: spaceItems - } - }); -}; -var newFolderInVault = (plugin, activeFile2) => { - let vaultChangeModal = new VaultChangeModal( - plugin, - plugin.app.vault.getRoot(), - "create folder", - "/" - ); - vaultChangeModal.open(); -}; -var newFileInVault = async (plugin, activeFile2, canvas) => { - let newFile; - if (canvas) { - newFile = await createNewCanvasFile(plugin, plugin.app.vault.getRoot(), ""); - } else { - newFile = await createNewMarkdownFile( - plugin, - plugin.app.vault.getRoot(), - "" - ); - } -}; -var newFolderInSpace = (plugin, space, activeFile2) => { - var _a2; - let vaultChangeModal = new VaultChangeModal( - plugin, - ((_a2 = space == null ? void 0 : space.def) == null ? void 0 : _a2.length) > 0 ? getFolderFromPath(app, space.def) : defaultNoteFolder(plugin, activeFile2), - "create folder", - space.name - ); - vaultChangeModal.open(); -}; -var newFileInSpace = async (plugin, space, activeFile2, canvas) => { - var _a2, _b2; - let newFile; - if (canvas) { - newFile = await createNewCanvasFile( - plugin, - ((_a2 = space == null ? void 0 : space.def) == null ? void 0 : _a2.length) > 0 ? getFolderFromPath(app, space.def) : defaultNoteFolder(plugin, activeFile2), - "" - ); - } else { - newFile = await createNewMarkdownFile( - plugin, - ((_b2 = space == null ? void 0 : space.def) == null ? void 0 : _b2.length) > 0 ? getFolderFromPath(app, space.def) : defaultNoteFolder(plugin, activeFile2), - "" - ); - } - if (space.name != "/") - addPathsToSpace(plugin, space.name, [newFile.path]); -}; - -// 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.type)); +var cleanPredicateType = (type, definedTypes) => { + return type.filter((f4) => Object.keys(definedTypes).find((g4) => g4 == f4.fn)); }; var validatePredicate = (prevPredicate) => { if (!prevPredicate) { @@ -20878,7 +21844,8 @@ var defaultPredicate = { }; // src/components/ContextView/MDBContext.tsx -var MDBContext = B({ +var MDBContext = F({ + def: [], tables: [], cols: [], sortedColumns: [], @@ -20928,53 +21895,54 @@ var MDBContext = B({ }); var MDBProvider = (props2) => { var _a2; - const [readMode, setReadMode] = p2(props2.context.readOnly); - const [dbFileExists, setDBFileExists] = p2(false); - const [schema, setSchema] = p2(null); - const [searchString, setSearchString] = p2(null); - const [schemaTable, setSchemaTable] = p2(null); + 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] = p2(null); - const [dbSchema, setDBSchema] = p2(null); - const [contextTable, setContextTable] = p2({}); - const [predicate, setPredicate] = p2(defaultPredicate); - const [selectedRows, setSelectedRows] = p2([]); - const [metadataCache, setMetadataCache] = p2(null); + 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 = F(() => { + const contextInfo = F2(() => { return props2.context; }, [props2.context]); - const tagContexts = F( - () => { - var _a3, _b2, _c2; - return ((_a3 = dbSchema == null ? void 0 : dbSchema.def) == null ? void 0 : _a3.length) > 0 ? (_c2 = (_b2 = dbSchema == null ? void 0 : dbSchema.def) == null ? void 0 : _b2.split("&")) != null ? _c2 : [] : []; - }, - [dbSchema] + const tagContexts = F2( + () => def.filter((f4) => f4.type == "tag").map((f4) => f4.value), + [def] ); - const cols = F( + const cols = F2( () => { var _a3; - return [ - ...(_a3 = tableData == null ? void 0 : tableData.cols.map((f4) => ({ ...f4, table: "" }))) != null ? _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 != "File" && f4.type != "fileprop").map((f4) => ({ ...f4, table: c4 }))) != null ? _b2 : [] + ...(_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 = F( + const data = F2( () => { var _a3; return (_a3 = tableData == null ? void 0 : tableData.rows.map( (r3, index) => linkContextRow( + props2.plugin, { _index: index.toString(), ...r3, @@ -20993,21 +21961,20 @@ var MDBProvider = (props2) => { return { ...p3, ...contextRowsWithKeysAppended }; }, {}) }, - cols, - contextTable + cols ) )) != null ? _a3 : []; }, [tableData, schema, contextTable] ); - const sortedColumns = F(() => { + 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 = F( + const filteredData = F2( () => data.filter((f4) => { return predicate.filters.reduce((p3, c4) => { return p3 ? filterReturnForCol( @@ -21068,6 +22035,9 @@ var MDBProvider = (props2) => { await saveDBToPath(props2.plugin, contextInfo.dbPath, { m_schema: newSchemaTable }); + if (!dbFileExists) { + saveDB2(tableData); + } } if (table.id == (schema == null ? void 0 : schema.id)) { setSchema(table); @@ -21200,7 +22170,7 @@ var MDBProvider = (props2) => { { File: c4.path, ...fmKeys.reduce((p4, c5) => { - const value = parseFrontMatter(c5, fm[c5], false); + const value = parseFrontMatter(c5, fm[c5]); if ((value == null ? void 0 : value.length) > 0) return { ...p4, [c5]: value }; return p4; @@ -21226,8 +22196,8 @@ var MDBProvider = (props2) => { } 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); + 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, @@ -21235,44 +22205,59 @@ var MDBProvider = (props2) => { }); } }; - h2(() => { - if (props2.schema && schemaTable && (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 + 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 (preselectDBSchema) { - setDBSchema(preselectDBSchema); - return; + 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 { - 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: [] - }); - }); + 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) + ); + } } } }, [schemaTable]); @@ -21280,43 +22265,27 @@ var MDBProvider = (props2) => { if (getAbstractFileAtPath(app, contextInfo.dbPath) || contextInfo.isRemote) { setDBFileExists(true); getMDBTableSchemas(props2.plugin, contextInfo).then((f4) => { - setSchemaTable({ + setSchemaTable((prev) => ({ ...defaultSchema, rows: f4 - }); - if (!props2.schema) - setDBSchema(f4 == null ? void 0 : f4.find((g4) => g4.type == "db")); + })); }); } else { if (props2.schema) { saveDB2(defaultMDBTableForContext(contextInfo)).then((f4) => { - setSchemaTable(defaultSchema); + setSchemaTable((prev) => defaultSchema); }); } else { - setSchemaTable(defaultSchema); - setDBSchema(defaultFileDBSchema); + setSchemaTable((prev) => defaultSchema); + setDBSchema((prev) => defaultFileDBSchema); } } }; - const refreshMetadata = async (evt) => { - var _a3, _b2, _c2; - if (!dbFileExists) { - return; - } - if ((_a3 = evt.detail) == null ? void 0 : _a3.file) { - refreshFile(evt.detail.file); - return; - } - if (((_c2 = (_b2 = evt.detail) == null ? void 0 : _b2.tags) == null ? void 0 : _c2.length) > 0) { - refreshTags(evt.detail.tags); - return; - } - }; const refreshFile = async (file) => { var _a3; - if (file.path == props2.file) { + if (file.path == props2.file && dbSchema) { const fCache = (_a3 = app.metadataCache.getCache(file.path)) == null ? void 0 : _a3.frontmatter; - if ((0, import_lodash4.isEqual)(fCache, metadataCache)) + if ((0, import_lodash2.isEqual)(fCache, metadataCache)) return; setMetadataCache(fCache); if (dbSchema.primary) { @@ -21335,8 +22304,18 @@ var MDBProvider = (props2) => { } }; const refreshSpace = async (evt) => { - if (!dbFileExists) { + 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) { loadDefaultTableData(); + } else if (evt.detail.type == "vault") { + refreshMDB(contextInfo.contextPath); } }; const getMDBData = () => { @@ -21344,54 +22323,29 @@ var MDBProvider = (props2) => { (f4) => setTableData(f4) ); }; - const refreshMDB = async (evt) => { + const refreshMDB = async (contextPath) => { if (!dbFileExists || (dbSchema == null ? void 0 : dbSchema.primary) != "true") { return; } - if (evt.detail.dbPath == contextInfo.dbPath) { + if (contextPath == contextInfo.contextPath) { if (dbSchema) { - if (schema) - getMDBSchema(props2.plugin, contextInfo, schema.id).then((f4) => { - if (f4) { - setSchema(f4); - const newSchemaTable = { - ...schemaTable, - rows: schemaTable.rows.map((s5) => s5.id == f4.id ? f4 : s5) - }; - setSchemaTable(newSchemaTable); - } - }); - getMDBTable(props2.plugin, contextInfo, dbSchema.id).then( - (f4) => setTableData(f4) - ); + loadTables(); } } else { const tag = Object.keys(contextTable).find( - (t4) => tagContextFromTag(props2.plugin, t4).dbPath == evt.detail.dbPath + (t4) => tagContextFromTag(props2.plugin, t4).contextPath == contextPath ); if (tag) loadContextFields(tag); } }; - h2(() => { - window.addEventListener(eventTypes.metadataChange, refreshMetadata); - return () => { - window.removeEventListener(eventTypes.metadataChange, refreshMetadata); - }; - }, [refreshMetadata]); - h2(() => { + p2(() => { window.addEventListener(eventTypes.spacesChange, refreshSpace); return () => { window.removeEventListener(eventTypes.spacesChange, refreshSpace); }; }, [refreshSpace]); - h2(() => { - window.addEventListener(eventTypes.mdbChange, refreshMDB); - return () => { - window.removeEventListener(eventTypes.mdbChange, refreshMDB); - }; - }, [refreshMDB]); - h2(() => { + p2(() => { loadTables(); }, [contextInfo]); const saveDB2 = async (newTable) => { @@ -21417,21 +22371,21 @@ var MDBProvider = (props2) => { await saveDBToPath(props2.plugin, contextInfo.dbPath, dbField).then( (f4) => { setDBFileExists(true); - f4 ? setTableData(newTable) : new import_obsidian8.Notice("DB ERROR"); + f4 ? setTableData(newTable) : new import_obsidian6.Notice("DB ERROR"); } ); } else { await saveMDBToPath(props2.plugin, contextInfo, newTable).then((f4) => { setDBFileExists(true); - f4 ? setTableData(newTable) : new import_obsidian8.Notice("DB ERROR"); + f4 ? setTableData(newTable) : new import_obsidian6.Notice("DB ERROR"); }); } }; - h2(() => { + p2(() => { var _a3; if (!schemaTable || !dbSchema) return; - const _schema = (schema == null ? void 0 : schema.def) == dbSchema.id ? schema : (_a3 = schemaTable.rows.find((f4) => f4.def == dbSchema.id)) != null ? _a3 : { + 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", @@ -21453,30 +22407,44 @@ var MDBProvider = (props2) => { } } }, [dbSchema]); - h2(() => { - if (dbFileExists) - parsePredicate(schema == null ? void 0 : schema.predicate); + p2(() => { + if (dbFileExists && schema) { + parsePredicate(schema.predicate); + } }, [schema]); - h2(() => { + p2(() => { if (dbFileExists && tableData) getContextTags(tableData); }, [tableData]); const selectRows = (lastSelected, rows) => { if (lastSelected) { const path = tableData.rows[parseInt(lastSelected)].File; - let evt = new CustomEvent(eventTypes.selectedFileChange, { - detail: { filePath: path } + let evt = new CustomEvent(eventTypes.activePathChange, { + detail: { + selection: path, + path: { + ...pathByString(props2.plugin, contextInfo.contextPath), + ref: schema == null ? void 0 : schema.id + } + } }); window.dispatchEvent(evt); } else { - let evt = new CustomEvent(eventTypes.selectedFileChange, { - detail: { filePath: null } + let evt = new CustomEvent(eventTypes.activePathChange, { + detail: { + path: { + ...pathByString(props2.plugin, contextInfo.contextPath), + ref: schema == null ? void 0 : schema.id + }, + selection: null + } }); window.dispatchEvent(evt); } setSelectedRows(rows); }; const loadDefaultTableData = () => { + var _a3, _b2; let files; if (contextInfo.type == "folder") { files = folderChildren( @@ -21488,15 +22456,26 @@ var MDBProvider = (props2) => { ); setTableData({ ...defaultMDBTableForContext(contextInfo), - rows: files.map( - (f4) => newRowByDBRow({ _source: "folder", File: f4.path }) - ) + rows: files.map((f4) => ({ File: f4.path })) }); } else if (contextInfo.type == "tag") { files = getAllFilesForTag(contextInfo.contextPath).map((f4) => getAbstractFileAtPath(app, f4)).filter((f4) => f4); setTableData({ ...defaultMDBTableForContext(contextInfo), - rows: files.map((f4) => newRowByDBRow({ _source: "tag", File: f4.path })) + rows: files.map((f4) => ({ File: f4.path })) + }); + } else if (contextInfo.type == "space") { + files = [ + ...(_b2 = (_a3 = props2.plugin.index.spaces) == null ? void 0 : _a3.getInverse( + contextInfo.contextPath.substring( + 0, + contextInfo.contextPath.length - 2 + ) + )) != null ? _b2 : [] + ].map((f4) => getAbstractFileAtPath(app, f4)).filter((f4) => f4); + setTableData({ + ...defaultMDBTableForContext(contextInfo), + rows: files.map((f4) => ({ File: f4.path })) }); } }; @@ -21507,48 +22486,24 @@ var MDBProvider = (props2) => { } }; const runDef = async () => { - let files; if (contextInfo.type == "folder") { - files = folderChildren( - props2.plugin, - getAbstractFileAtPath( - props2.plugin.app, - contextInfo.contextPath - ) - ); - consolidateFilesToTable( - props2.plugin, - contextInfo, - dbSchema.id, - files.map((f4) => f4.path) - ).then((f4) => { + getMDBTable(props2.plugin, contextInfo, "files").then((f4) => { for (let c4 of tagContexts) { loadTagContext(c4, f4.rows); } setTableData(f4); return f4; - }).then((f4) => syncAllMetadata(f4)); + }); } else if (contextInfo.type == "tag") { - files = getAllFilesForTag(contextInfo.contextPath).map((f4) => getAbstractFileAtPath(app, f4)).filter((f4) => f4); - consolidateFilesToTable( - props2.plugin, - contextInfo, - dbSchema.id, - files.map((f4) => f4.path) - ).then((f4) => { + getMDBTable(props2.plugin, contextInfo, "files").then((f4) => { for (let c4 of tagContexts) { loadTagContext(c4, f4.rows); } setTableData(f4); return f4; - }).then((f4) => syncAllMetadata(f4)); - } else if (contextInfo.type == "query") { - retrieveAllFiles(props2.plugin).then((g4) => g4.map((f4) => getAbstractFileAtPath(app, f4.path)).filter((f4) => f4)).then((files2) => consolidateFilesToTable( - props2.plugin, - contextInfo, - dbSchema.id, - files2.map((f4) => f4.path) - )).then((f4) => { + }); + } else if (contextInfo.type == "space") { + getMDBTable(props2.plugin, contextInfo, "files").then((f4) => { setTableData(f4); return f4; }); @@ -21559,12 +22514,10 @@ var MDBProvider = (props2) => { } }; const loadTagContext = async (tag, files) => { - consolidateRowsToTag( + getMDBTable( props2.plugin, tagContextFromTag(props2.plugin, tag), - dbSchema.id, - contextInfo.dbPath, - files + "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)); @@ -21607,7 +22560,7 @@ var MDBProvider = (props2) => { }); setPredicate(cleanedPredicate); }; - h2(() => { + p2(() => { setPredicate((p3) => ({ ...p3, colsOrder: uniq([ @@ -21661,7 +22614,7 @@ var MDBProvider = (props2) => { mdbtable = contextTable[table]; } if (column.name == "") { - new import_obsidian8.Notice(i18n_default.notice.noPropertyName); + new import_obsidian6.Notice(i18n_default.notice.noPropertyName); return false; } if (!oldColumn && mdbtable.cols.find( @@ -21669,7 +22622,7 @@ var MDBProvider = (props2) => { ) || oldColumn && oldColumn.name != column.name && mdbtable.cols.find( (f4) => f4.name.toLowerCase() == column.name.toLowerCase() )) { - new import_obsidian8.Notice(i18n_default.notice.duplicatePropertyName); + new import_obsidian6.Notice(i18n_default.notice.duplicatePropertyName); return false; } const oldFieldIndex = oldColumn ? mdbtable.cols.findIndex((f4) => f4.name == oldColumn.name) : -1; @@ -21715,8 +22668,9 @@ var MDBProvider = (props2) => { } return true; }; - return /* @__PURE__ */ bn.createElement(MDBContext.Provider, { + return /* @__PURE__ */ Cn.createElement(MDBContext.Provider, { value: { + def, readMode, contextInfo, data, @@ -21756,7 +22710,7 @@ var MDBProvider = (props2) => { }; // src/components/ContextView/CardsView/CardColumnView.tsx -var import_classnames = __toESM(require_classnames()); +var import_classnames2 = __toESM(require_classnames()); // node_modules/@tanstack/table-core/build/lib/index.mjs function functionalUpdate(updater, input) { @@ -21781,7 +22735,7 @@ function flattenBy(arr, getChildren) { subArr.forEach((item) => { flat.push(item); const children = getChildren(item); - if (children == null ? void 0 : children.length) { + if (children != null && children.length) { recurse(children); } }); @@ -21793,7 +22747,6 @@ function memo(getDeps, fn2, opts) { let deps = []; let result; return () => { - var _a2; let depTime; if (opts.key && opts.debug) depTime = Date.now(); @@ -21807,9 +22760,9 @@ function memo(getDeps, fn2, opts) { if (opts.key && opts.debug) resultTime = Date.now(); result = fn2(...newDeps); - (_a2 = opts == null ? void 0 : opts.onChange) == null ? void 0 : _a2.call(opts, result); + opts == null ? void 0 : opts.onChange == null ? void 0 : opts.onChange(result); if (opts.key && opts.debug) { - if (opts == null ? void 0 : 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; @@ -21846,9 +22799,10 @@ function createColumn(table, columnDef, depth, parent) { accessorFn = (originalRow) => { let result = originalRow; for (const key2 of accessorKey.split(".")) { - result = result[key2]; + var _result; + result = (_result = result) == null ? void 0 : _result[key2]; if (result === void 0) { - throw new Error(`"${key2}" in deeply nested key "${accessorKey}" returned undefined.`); + console.warn(`"${key2}" in deeply nested key "${accessorKey}" returned undefined.`); } } return result; @@ -21871,8 +22825,8 @@ function createColumn(table, columnDef, depth, parent) { columnDef: resolvedColumnDef, columns: [], getFlatColumns: memo(() => [true], () => { - var _a2; - return [column, ...(_a2 = column.columns) == null ? void 0 : _a2.flatMap((d5) => d5.getFlatColumns())]; + var _column$columns; + return [column, ...(_column$columns = column.columns) == null ? void 0 : _column$columns.flatMap((d5) => d5.getFlatColumns())]; }, { key: false, debug: () => { @@ -21881,8 +22835,8 @@ function createColumn(table, columnDef, depth, parent) { } }), getLeafColumns: memo(() => [table._getOrderColumnsFn()], (orderColumns2) => { - var _a2; - if ((_a2 = column.columns) == null ? void 0 : _a2.length) { + var _column$columns2; + if ((_column$columns2 = column.columns) != null && _column$columns2.length) { let leafColumns = column.columns.flatMap((column2) => column2.getLeafColumns()); return orderColumns2(leafColumns); } @@ -21896,8 +22850,7 @@ function createColumn(table, columnDef, depth, parent) { }) }; column = table._features.reduce((obj, feature) => { - var _a2; - return Object.assign(obj, (_a2 = feature.createColumn) == null ? void 0 : _a2.call(feature, column, table)); + return Object.assign(obj, feature.createColumn == null ? void 0 : feature.createColumn(column, table)); }, column); return column; } @@ -21933,8 +22886,7 @@ function createHeader(table, column, options) { }) }; table._features.forEach((feature) => { - var _a2; - Object.assign(header, (_a2 = feature.createHeader) == null ? void 0 : _a2.call(feature, header, table)); + Object.assign(header, feature.createHeader == null ? void 0 : feature.createHeader(header, table)); }); return header; } @@ -21945,7 +22897,7 @@ var Headers = { 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 ? void 0 : left.includes(column.id)) && !(right == null ? void 0 : right.includes(column.id))); + 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; }, { @@ -21956,7 +22908,7 @@ var Headers = { } }), getCenterHeaderGroups: memo(() => [table.getAllColumns(), table.getVisibleLeafColumns(), table.getState().columnPinning.left, table.getState().columnPinning.right], (allColumns, leafColumns, left, right) => { - leafColumns = leafColumns.filter((column) => !(left == null ? void 0 : left.includes(column.id)) && !(right == null ? void 0 : right.includes(column.id))); + leafColumns = leafColumns.filter((column) => !(left != null && left.includes(column.id)) && !(right != null && right.includes(column.id))); return buildHeaderGroups(allColumns, leafColumns, table, "center"); }, { key: "getCenterHeaderGroups", @@ -22069,8 +23021,8 @@ var Headers = { }), getCenterLeafHeaders: memo(() => [table.getCenterFlatHeaders()], (flatHeaders) => { return flatHeaders.filter((header) => { - var _a2; - return !((_a2 = header.subHeaders) == null ? void 0 : _a2.length); + var _header$subHeaders; + return !((_header$subHeaders = header.subHeaders) != null && _header$subHeaders.length); }); }, { key: "getCenterLeafHeaders", @@ -22081,8 +23033,8 @@ var Headers = { }), getLeftLeafHeaders: memo(() => [table.getLeftFlatHeaders()], (flatHeaders) => { return flatHeaders.filter((header) => { - var _a2; - return !((_a2 = header.subHeaders) == null ? void 0 : _a2.length); + var _header$subHeaders2; + return !((_header$subHeaders2 = header.subHeaders) != null && _header$subHeaders2.length); }); }, { key: "getLeftLeafHeaders", @@ -22093,8 +23045,8 @@ var Headers = { }), getRightLeafHeaders: memo(() => [table.getRightFlatHeaders()], (flatHeaders) => { return flatHeaders.filter((header) => { - var _a2; - return !((_a2 = header.subHeaders) == null ? void 0 : _a2.length); + var _header$subHeaders3; + return !((_header$subHeaders3 = header.subHeaders) != null && _header$subHeaders3.length); }); }, { key: "getRightLeafHeaders", @@ -22104,9 +23056,8 @@ var Headers = { } }), getLeafHeaders: memo(() => [table.getLeftHeaderGroups(), table.getCenterHeaderGroups(), table.getRightHeaderGroups()], (left, center, right) => { - var _a2, _b2, _c2; - var _left$0$headers, _center$0$headers, _right$0$headers; - return [...(_left$0$headers = (_a2 = left[0]) == null ? void 0 : _a2.headers) != null ? _left$0$headers : [], ...(_center$0$headers = (_b2 = center[0]) == null ? void 0 : _b2.headers) != null ? _center$0$headers : [], ...(_right$0$headers = (_c2 = right[0]) == null ? void 0 : _c2.headers) != null ? _right$0$headers : []].map((header) => { + 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(); }, { @@ -22120,8 +23071,7 @@ var Headers = { } }; function buildHeaderGroups(allColumns, columnsToGroup, table, headerFamily) { - var _a2; - var _headerGroups$0$heade; + var _headerGroups$0$heade, _headerGroups$; let maxDepth = 0; const findMaxDepth = function(columns, depth) { if (depth === void 0) { @@ -22129,8 +23079,8 @@ function buildHeaderGroups(allColumns, columnsToGroup, table, headerFamily) { } maxDepth = Math.max(maxDepth, depth); columns.filter((column) => column.getIsVisible()).forEach((column) => { - var _a3; - if ((_a3 = column.columns) == null ? void 0 : _a3.length) { + var _column$columns; + if ((_column$columns = column.columns) != null && _column$columns.length) { findMaxDepth(column.columns, depth + 1); } }, 0); @@ -22211,7 +23161,7 @@ function buildHeaderGroups(allColumns, columnsToGroup, table, headerFamily) { }; }); }; - recurseHeadersForSpans((_headerGroups$0$heade = (_a2 = headerGroups[0]) == null ? void 0 : _a2.headers) != null ? _headerGroups$0$heade : []); + recurseHeadersForSpans((_headerGroups$0$heade = (_headerGroups$ = headerGroups[0]) == null ? void 0 : _headerGroups$.headers) != null ? _headerGroups$0$heade : []); return headerGroups; } var defaultColumnSizing = { @@ -22264,7 +23214,7 @@ var ColumnSizing = { resetSize: () => { table.setColumnSizing((_ref2) => { let { - [column.id]: _7, + [column.id]: _9, ...rest } = _ref2; return rest; @@ -22303,13 +23253,12 @@ var ColumnSizing = { }, getResizeHandler: () => { const column = table.getColumn(header.column.id); - const canResize = column.getCanResize(); + const canResize = column == null ? void 0 : column.getCanResize(); return (e4) => { - var _a2; - if (!canResize) { + if (!column || !canResize) { return; } - (_a2 = e4.persist) == null ? void 0 : _a2.call(e4); + e4.persist == null ? void 0 : e4.persist(); if (isTouchStartEvent(e4)) { if (e4.touches && e4.touches.length > 1) { return; @@ -22375,14 +23324,14 @@ var ColumnSizing = { return false; }, upHandler: (e5) => { - var _a3; + var _e$touches$; document.removeEventListener("touchmove", touchEvents.moveHandler); document.removeEventListener("touchend", touchEvents.upHandler); if (e5.cancelable) { e5.preventDefault(); e5.stopPropagation(); } - onEnd((_a3 = e5.touches[0]) == null ? void 0 : _a3.clientX); + onEnd((_e$touches$ = e5.touches[0]) == null ? void 0 : _e$touches$.clientX); } }; const passiveIfSupported = passiveEventSupported() ? { @@ -22410,14 +23359,8 @@ var ColumnSizing = { }, createTable: (table) => { return { - setColumnSizing: (updater) => { - var _a2, _b2; - return (_b2 = (_a2 = table.options).onColumnSizingChange) == null ? void 0 : _b2.call(_a2, updater); - }, - setColumnSizingInfo: (updater) => { - var _a2, _b2; - return (_b2 = (_a2 = table.options).onColumnSizingInfoChange) == null ? void 0 : _b2.call(_a2, updater); - }, + 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 : {}); @@ -22427,30 +23370,26 @@ var ColumnSizing = { table.setColumnSizingInfo(defaultState ? getDefaultColumnSizingInfoState() : (_table$initialState$c2 = table.initialState.columnSizingInfo) != null ? _table$initialState$c2 : getDefaultColumnSizingInfoState()); }, getTotalSize: () => { - var _a2; - var _table$getHeaderGroup; - return (_table$getHeaderGroup = (_a2 = table.getHeaderGroups()[0]) == null ? void 0 : _a2.headers.reduce((sum2, header) => { + 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 _a2; - var _table$getLeftHeaderG; - return (_table$getLeftHeaderG = (_a2 = table.getLeftHeaderGroups()[0]) == null ? void 0 : _a2.headers.reduce((sum2, header) => { + 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 _a2; - var _table$getCenterHeade; - return (_table$getCenterHeade = (_a2 = table.getCenterHeaderGroups()[0]) == null ? void 0 : _a2.headers.reduce((sum2, header) => { + 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 _a2; - var _table$getRightHeader; - return (_table$getRightHeader = (_a2 = table.getRightHeaderGroups()[0]) == null ? void 0 : _a2.headers.reduce((sum2, header) => { + 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; } @@ -22517,10 +23456,7 @@ var Expanding = { }); } }, - setExpanded: (updater) => { - var _a2, _b2; - return (_b2 = (_a2 = table.options).onExpandedChange) == null ? void 0 : _b2.call(_a2, updater); - }, + setExpanded: (updater) => table.options.onExpandedChange == null ? void 0 : table.options.onExpandedChange(updater), toggleAllRowsExpanded: (expanded) => { if (expanded != null ? expanded : !table.getIsAllRowsExpanded()) { table.setExpanded(true); @@ -22529,17 +23465,15 @@ var Expanding = { } }, resetExpanded: (defaultState) => { - var _a2; - var _table$initialState$e; - table.setExpanded(defaultState ? {} : (_table$initialState$e = (_a2 = table.initialState) == null ? void 0 : _a2.expanded) != null ? _table$initialState$e : {}); + 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) => { - var _a2; - (_a2 = e4.persist) == null ? void 0 : _a2.call(e4); + e4.persist == null ? void 0 : e4.persist(); table.toggleAllRowsExpanded(); }; }, @@ -22586,7 +23520,7 @@ var Expanding = { toggleExpanded: (expanded) => { table.setExpanded((old) => { var _expanded; - const exists = old === true ? true : !!(old == null ? void 0 : old[row.id]); + const exists = old === true ? true : !!(old != null && old[row.id]); let oldExpanded = {}; if (old === true) { Object.keys(table.getRowModel().rowsById).forEach((rowId) => { @@ -22604,7 +23538,7 @@ var Expanding = { } if (exists && !expanded) { const { - [row.id]: _7, + [row.id]: _9, ...rest } = oldExpanded; return rest; @@ -22613,15 +23547,13 @@ var Expanding = { }); }, getIsExpanded: () => { - var _a2, _b2; var _table$options$getIsR; const expanded = table.getState().expanded; - return !!((_table$options$getIsR = (_b2 = (_a2 = table.options).getIsRowExpanded) == null ? void 0 : _b2.call(_a2, row)) != null ? _table$options$getIsR : expanded === true || (expanded == null ? void 0 : expanded[row.id])); + 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 _a2, _b2, _c2; - var _table$options$getRow, _table$options$enable; - return (_table$options$getRow = (_b2 = (_a2 = table.options).getRowCanExpand) == null ? void 0 : _b2.call(_a2, row)) != null ? _table$options$getRow : ((_table$options$enable = table.options.enableExpanding) != null ? _table$options$enable : true) && !!((_c2 = row.subRows) == null ? void 0 : _c2.length); + 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(); @@ -22635,40 +23567,40 @@ var Expanding = { } }; var includesString = (row, columnId, filterValue) => { - var _a2; + var _row$getValue; const search = filterValue.toLowerCase(); - return Boolean((_a2 = row.getValue(columnId)) == null ? void 0 : _a2.toLowerCase().includes(search)); + 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 _a2; - return Boolean((_a2 = row.getValue(columnId)) == null ? void 0 : _a2.includes(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 _a2; - return ((_a2 = row.getValue(columnId)) == null ? void 0 : _a2.toLowerCase()) === filterValue.toLowerCase(); + 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 _a2; - return (_a2 = row.getValue(columnId)) == null ? void 0 : _a2.includes(filterValue); + var _row$getValue4; + return (_row$getValue4 = row.getValue(columnId)) == null ? void 0 : _row$getValue4.includes(filterValue); }; -arrIncludes.autoRemove = (val) => testFalsey(val) || !(val == null ? void 0 : val.length); +arrIncludes.autoRemove = (val) => testFalsey(val) || !(val != null && val.length); var arrIncludesAll = (row, columnId, filterValue) => { return !filterValue.some((val) => { - var _a2; - return !((_a2 = row.getValue(columnId)) == null ? void 0 : _a2.includes(val)); + var _row$getValue5; + return !((_row$getValue5 = row.getValue(columnId)) != null && _row$getValue5.includes(val)); }); }; -arrIncludesAll.autoRemove = (val) => testFalsey(val) || !(val == null ? void 0 : val.length); +arrIncludesAll.autoRemove = (val) => testFalsey(val) || !(val != null && val.length); var arrIncludesSome = (row, columnId, filterValue) => { return filterValue.some((val) => { - var _a2; - return (_a2 = row.getValue(columnId)) == null ? void 0 : _a2.includes(val); + var _row$getValue6; + return (_row$getValue6 = row.getValue(columnId)) == null ? void 0 : _row$getValue6.includes(val); }); }; -arrIncludesSome.autoRemove = (val) => testFalsey(val) || !(val == null ? void 0 : val.length); +arrIncludesSome.autoRemove = (val) => testFalsey(val) || !(val != null && val.length); var equals = (row, columnId, filterValue) => { return row.getValue(columnId) === filterValue; }; @@ -22731,8 +23663,8 @@ var Filters = { maxLeafRowFilterDepth: 100, globalFilterFn: "auto", getColumnCanGlobalFilter: (column) => { - var _a2, _b2; - const value = (_b2 = (_a2 = table.getCoreRowModel().flatRows[0]) == null ? void 0 : _a2._getAllCellsByColumnId()[column.id]) == null ? void 0 : _b2.getValue(); + 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"; } }; @@ -22760,28 +23692,25 @@ var Filters = { return filterFns.weakEquals; }, getFilterFn: () => { - var _a2; - var _table$options$filter; - return isFunction(column.columnDef.filterFn) ? column.columnDef.filterFn : column.columnDef.filterFn === "auto" ? column.getAutoFilterFn() : (_table$options$filter = (_a2 = table.options.filterFns) == null ? void 0 : _a2[column.columnDef.filterFn]) != null ? _table$options$filter : filterFns[column.columnDef.filterFn]; + 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 _a2, _b2; 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 = (_b2 = (_a2 = table.options).getColumnCanGlobalFilter) == null ? void 0 : _b2.call(_a2, column)) != null ? _table$options$getCol : true) && !!column.accessorFn; + 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 _a2, _b2; - return (_b2 = (_a2 = table.getState().columnFilters) == null ? void 0 : _a2.find((d5) => d5.id === column.id)) == null ? void 0 : _b2.value; + 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 _a2; - var _table$getState$colum; - return (_table$getState$colum = (_a2 = table.getState().columnFilters) == null ? void 0 : _a2.findIndex((d5) => d5.id === column.id)) != null ? _table$getState$colum : -1; + 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) => { @@ -22805,7 +23734,7 @@ var Filters = { return d5; })) != null ? _old$map : []; } - if (old == null ? void 0 : old.length) { + if (old != null && old.length) { return [...old, newFilterObj]; } return [newFilterObj]; @@ -22846,19 +23775,17 @@ var Filters = { return filterFns.includesString; }, getGlobalFilterFn: () => { - var _a2; - var _table$options$filter2; + var _table$options$filter3, _table$options$filter4; const { globalFilterFn } = table.options; - return isFunction(globalFilterFn) ? globalFilterFn : globalFilterFn === "auto" ? table.getGlobalAutoFilterFn() : (_table$options$filter2 = (_a2 = table.options.filterFns) == null ? void 0 : _a2[globalFilterFn]) != null ? _table$options$filter2 : filterFns[globalFilterFn]; + 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) => { - var _a2, _b2; const leafColumns = table.getAllLeafColumns(); const updateFn = (old) => { - var _a3; - return (_a3 = functionalUpdate(updater, old)) == null ? void 0 : _a3.filter((filter) => { + 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(); @@ -22869,19 +23796,17 @@ var Filters = { return true; }); }; - (_b2 = (_a2 = table.options).onColumnFiltersChange) == null ? void 0 : _b2.call(_a2, updateFn); + table.options.onColumnFiltersChange == null ? void 0 : table.options.onColumnFiltersChange(updateFn); }, setGlobalFilter: (updater) => { - var _a2, _b2; - (_b2 = (_a2 = table.options).onGlobalFilterChange) == null ? void 0 : _b2.call(_a2, updater); + table.options.onGlobalFilterChange == null ? void 0 : table.options.onGlobalFilterChange(updater); }, resetGlobalFilter: (defaultState) => { table.setGlobalFilter(defaultState ? void 0 : table.initialState.globalFilter); }, resetColumnFilters: (defaultState) => { - var _a2; - var _table$initialState$c; - table.setColumnFilters(defaultState ? [] : (_table$initialState$c = (_a2 = table.initialState) == null ? void 0 : _a2.columnFilters) != null ? _table$initialState$c : []); + 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: () => { @@ -23017,9 +23942,8 @@ var Grouping = { getDefaultColumnDef: () => { return { aggregatedCell: (props2) => { - var _a2, _b2; - var _toString; - return (_toString = (_b2 = (_a2 = props2.getValue()) == null ? void 0 : _a2.toString) == null ? void 0 : _b2.call(_a2)) != null ? _toString : null; + 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" }; @@ -23040,7 +23964,7 @@ var Grouping = { return { toggleGrouping: () => { table.setGrouping((old) => { - if (old == null ? void 0 : old.includes(column.id)) { + if (old != null && old.includes(column.id)) { return old.filter((d5) => d5 !== column.id); } return [...old != null ? old : [], column.id]; @@ -23051,12 +23975,12 @@ var Grouping = { 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 _a2; - return (_a2 = table.getState().grouping) == null ? void 0 : _a2.includes(column.id); + var _table$getState$group; + return (_table$getState$group = table.getState().grouping) == null ? void 0 : _table$getState$group.includes(column.id); }, getGroupedIndex: () => { - var _a2; - return (_a2 = table.getState().grouping) == null ? void 0 : _a2.indexOf(column.id); + 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(); @@ -23077,25 +24001,20 @@ var Grouping = { } }, getAggregationFn: () => { - var _a2; - var _table$options$aggreg; + 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 = (_a2 = table.options.aggregationFns) == null ? void 0 : _a2[column.columnDef.aggregationFn]) != null ? _table$options$aggreg : aggregationFns[column.columnDef.aggregationFn]; + 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) => { - var _a2, _b2; - return (_b2 = (_a2 = table.options).onGroupingChange) == null ? void 0 : _b2.call(_a2, updater); - }, + setGrouping: (updater) => table.options.onGroupingChange == null ? void 0 : table.options.onGroupingChange(updater), resetGrouping: (defaultState) => { - var _a2; - var _table$initialState$g; - table.setGrouping(defaultState ? [] : (_table$initialState$g = (_a2 = table.initialState) == null ? void 0 : _a2.grouping) != null ? _table$initialState$g : []); + 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: () => { @@ -23120,14 +24039,14 @@ var Grouping = { getIsGrouped: () => column.getIsGrouped() && column.id === row.groupingColumnId, getIsPlaceholder: () => !cell.getIsGrouped() && column.getIsGrouped(), getIsAggregated: () => { - var _a2; - return !cell.getIsGrouped() && !cell.getIsPlaceholder() && !!((_a2 = row.subRows) == null ? void 0 : _a2.length); + var _row$subRows; + return !cell.getIsGrouped() && !cell.getIsPlaceholder() && !!((_row$subRows = row.subRows) != null && _row$subRows.length); } }; } }; function orderColumns(leafColumns, grouping, groupedColumnMode) { - if (!(grouping == null ? void 0 : grouping.length) || !groupedColumnMode) { + if (!(grouping != null && grouping.length) || !groupedColumnMode) { return leafColumns; } const nonGroupingColumns = leafColumns.filter((col) => !grouping.includes(col.id)); @@ -23151,17 +24070,14 @@ var Ordering = { }, createTable: (table) => { return { - setColumnOrder: (updater) => { - var _a2, _b2; - return (_b2 = (_a2 = table.options).onColumnOrderChange) == null ? void 0 : _b2.call(_a2, updater); - }, + 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 ? void 0 : columnOrder.length)) { + if (!(columnOrder != null && columnOrder.length)) { orderedColumns = columns; } else { const columnOrderCopy = [...columnOrder]; @@ -23226,12 +24142,11 @@ var Pagination = { } }, setPagination: (updater) => { - var _a2, _b2; const safeUpdater = (old) => { let newState = functionalUpdate(updater, old); return newState; }; - return (_b2 = (_a2 = table.options).onPaginationChange) == null ? void 0 : _b2.call(_a2, safeUpdater); + return table.options.onPaginationChange == null ? void 0 : table.options.onPaginationChange(safeUpdater); }, resetPagination: (defaultState) => { var _table$initialState$p; @@ -23249,14 +24164,12 @@ var Pagination = { }); }, resetPageIndex: (defaultState) => { - var _a2, _b2; - var _table$initialState$p2; - table.setPageIndex(defaultState ? defaultPageIndex : (_table$initialState$p2 = (_b2 = (_a2 = table.initialState) == null ? void 0 : _a2.pagination) == null ? void 0 : _b2.pageIndex) != null ? _table$initialState$p2 : defaultPageIndex); + 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 _a2, _b2; - var _table$initialState$p3; - table.setPageSize(defaultState ? defaultPageSize : (_table$initialState$p3 = (_b2 = (_a2 = table.initialState) == null ? void 0 : _a2.pagination) == null ? void 0 : _b2.pageSize) != null ? _table$initialState$p3 : defaultPageSize); + 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) => { @@ -23284,7 +24197,7 @@ var Pagination = { getPageOptions: memo(() => [table.getPageCount()], (pageCount) => { let pageOptions = []; if (pageCount && pageCount > 0) { - pageOptions = [...new Array(pageCount)].fill(null).map((_7, i4) => i4); + pageOptions = [...new Array(pageCount)].fill(null).map((_9, i4) => i4); } return pageOptions; }, { @@ -23358,20 +24271,20 @@ var Pinning = { 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 ? void 0 : columnIds.includes(d5))), - right: [...((_old$right = old == null ? void 0 : old.right) != null ? _old$right : []).filter((d5) => !(columnIds == null ? void 0 : columnIds.includes(d5))), ...columnIds] + 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 ? void 0 : columnIds.includes(d5))), ...columnIds], - right: ((_old$right2 = old == null ? void 0 : old.right) != null ? _old$right2 : []).filter((d5) => !(columnIds == null ? void 0 : columnIds.includes(d5))) + 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 ? void 0 : columnIds.includes(d5))), - right: ((_old$right3 = old == null ? void 0 : old.right) != null ? _old$right3 : []).filter((d5) => !(columnIds == null ? void 0 : columnIds.includes(d5))) + 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))) }; }); }, @@ -23393,10 +24306,9 @@ var Pinning = { return isLeft ? "left" : isRight ? "right" : false; }, getPinnedIndex: () => { - var _a2, _b2; - var _table$getState$colum; + var _table$getState$colum, _table$getState$colum2, _table$getState$colum3; const position = column.getIsPinned(); - return position ? (_table$getState$colum = (_b2 = (_a2 = table.getState().columnPinning) == null ? void 0 : _a2[position]) == null ? void 0 : _b2.indexOf(column.id)) != null ? _table$getState$colum : -1 : 0; + 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; } }; }, @@ -23442,22 +24354,19 @@ var Pinning = { }, createTable: (table) => { return { - setColumnPinning: (updater) => { - var _a2, _b2; - return (_b2 = (_a2 = table.options).onColumnPinningChange) == null ? void 0 : _b2.call(_a2, updater); - }, + setColumnPinning: (updater) => table.options.onColumnPinningChange == null ? void 0 : table.options.onColumnPinningChange(updater), resetColumnPinning: (defaultState) => { - var _a2; - var _table$initialState$c; - return table.setColumnPinning(defaultState ? getDefaultPinningState() : (_table$initialState$c = (_a2 = table.initialState) == null ? void 0 : _a2.columnPinning) != null ? _table$initialState$c : getDefaultPinningState()); + 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 _a2, _b2, _c2; + var _pinningState$positio; const pinningState = table.getState().columnPinning; if (!position) { - return Boolean(((_a2 = pinningState.left) == null ? void 0 : _a2.length) || ((_b2 = pinningState.right) == null ? void 0 : _b2.length)); + 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((_c2 = pinningState[position]) == null ? void 0 : _c2.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); @@ -23507,10 +24416,7 @@ var RowSelection = { }, createTable: (table) => { return { - setRowSelection: (updater) => { - var _a2, _b2; - return (_b2 = (_a2 = table.options).onRowSelectionChange) == null ? void 0 : _b2.call(_a2, updater); - }, + 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 : {}); @@ -23615,7 +24521,7 @@ var RowSelection = { rowSelection } = table.getState(); let isAllPageRowsSelected = !!paginationFlatRows.length; - if (isAllPageRowsSelected && paginationFlatRows.some((row) => !rowSelection[row.id])) { + if (isAllPageRowsSelected && paginationFlatRows.some((row) => row.getCanSelect() && !rowSelection[row.id])) { isAllPageRowsSelected = false; } return isAllPageRowsSelected; @@ -23699,17 +24605,17 @@ var RowSelection = { getToggleSelectedHandler: () => { const canSelect = row.getCanSelect(); return (e4) => { - var _a2; + var _target; if (!canSelect) return; - row.toggleSelected((_a2 = e4.target) == null ? void 0 : _a2.checked); + row.toggleSelected((_target = e4.target) == null ? void 0 : _target.checked); }; } }; } }; var mutateRowIsSelected = (selectedRowIds, id2, value, table) => { - var _a2; + var _row$subRows; const row = table.getRow(id2); if (value) { if (!row.getCanMultiSelect()) { @@ -23721,7 +24627,7 @@ var mutateRowIsSelected = (selectedRowIds, id2, value, table) => { } else { delete selectedRowIds[id2]; } - if (((_a2 = row.subRows) == null ? void 0 : _a2.length) && row.getCanSelectSubRows()) { + if ((_row$subRows = row.subRows) != null && _row$subRows.length && row.getCanSelectSubRows()) { row.subRows.forEach((row2) => mutateRowIsSelected(selectedRowIds, row2.id, value, table)); } }; @@ -23731,13 +24637,13 @@ function selectRowsFn(table, rowModel) { const newSelectedRowsById = {}; const recurseRows = function(rows, depth) { return rows.map((row) => { - var _a2; + var _row$subRows2; const isSelected = isRowSelected(row, rowSelection); if (isSelected) { newSelectedFlatRows.push(row); newSelectedRowsById[row.id] = row; } - if ((_a2 = row.subRows) == null ? void 0 : _a2.length) { + if ((_row$subRows2 = row.subRows) != null && _row$subRows2.length) { row = { ...row, subRows: recurseRows(row.subRows) @@ -23901,12 +24807,11 @@ var Sorting = { return "desc"; }, getSortingFn: () => { - var _a2; - var _table$options$sortin; + 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 = (_a2 = table.options.sortingFns) == null ? void 0 : _a2[column.columnDef.sortingFn]) != null ? _table$options$sortin : sortingFns[column.columnDef.sortingFn]; + 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(); @@ -23917,14 +24822,14 @@ var Sorting = { let newSorting = []; let sortAction; let nextDesc = hasManualValue ? desc : nextSortingOrder === "desc"; - if ((old == null ? void 0 : old.length) && column.getCanMultiSort() && multi) { + if (old != null && old.length && column.getCanMultiSort() && multi) { if (existingSorting) { sortAction = "toggle"; } else { sortAction = "add"; } } else { - if ((old == null ? void 0 : old.length) && existingIndex !== old.length - 1) { + if (old != null && old.length && existingIndex !== old.length - 1) { sortAction = "replace"; } else if (existingSorting) { sortAction = "toggle"; @@ -23993,40 +24898,34 @@ var Sorting = { return (_ref2 = (_column$columnDef$ena2 = column.columnDef.enableMultiSort) != null ? _column$columnDef$ena2 : table.options.enableMultiSort) != null ? _ref2 : !!column.accessorFn; }, getIsSorted: () => { - var _a2; - const columnSort = (_a2 = table.getState().sorting) == null ? void 0 : _a2.find((d5) => d5.id === column.id); + 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 _a2; - var _table$getState$sorti; - return (_table$getState$sorti = (_a2 = table.getState().sorting) == null ? void 0 : _a2.findIndex((d5) => d5.id === column.id)) != null ? _table$getState$sorti : -1; + 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 ? void 0 : old.length) ? old.filter((d5) => d5.id !== column.id) : []); + table.setSorting((old) => old != null && old.length ? old.filter((d5) => d5.id !== column.id) : []); }, getToggleSortingHandler: () => { const canSort = column.getCanSort(); return (e4) => { - var _a2, _b2, _c2, _d2; if (!canSort) return; - (_a2 = e4.persist) == null ? void 0 : _a2.call(e4); - (_d2 = column.toggleSorting) == null ? void 0 : _d2.call(column, void 0, column.getCanMultiSort() ? (_c2 = (_b2 = table.options).isMultiSortEvent) == null ? void 0 : _c2.call(_b2, e4) : false); + 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) => { - var _a2, _b2; - return (_b2 = (_a2 = table.options).onSortingChange) == null ? void 0 : _b2.call(_a2, updater); - }, + setSorting: (updater) => table.options.onSortingChange == null ? void 0 : table.options.onSortingChange(updater), resetSorting: (defaultState) => { - var _a2; - var _table$initialState$s; - table.setSorting(defaultState ? [] : (_table$initialState$s = (_a2 = table.initialState) == null ? void 0 : _a2.sorting) != null ? _table$initialState$s : []); + 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: () => { @@ -24064,9 +24963,8 @@ var Visibility = { } }, getIsVisible: () => { - var _a2; - var _table$getState$colum; - return (_table$getState$colum = (_a2 = table.getState().columnVisibility) == null ? void 0 : _a2[column.id]) != null ? _table$getState$colum : true; + 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; @@ -24074,8 +24972,7 @@ var Visibility = { }, getToggleVisibilityHandler: () => { return (e4) => { - var _a2; - (_a2 = column.toggleVisibility) == null ? void 0 : _a2.call(column, e4.target.checked); + column.toggleVisibility == null ? void 0 : column.toggleVisibility(e4.target.checked); }; } }; @@ -24103,10 +25000,7 @@ var Visibility = { createTable: (table) => { const makeVisibleColumnsMethod = (key2, getColumns) => { return memo(() => [getColumns(), getColumns().filter((d5) => d5.getIsVisible()).map((d5) => d5.id).join("_")], (columns) => { - return columns.filter((d5) => { - var _a2; - return (_a2 = d5.getIsVisible) == null ? void 0 : _a2.call(d5); - }); + return columns.filter((d5) => d5.getIsVisible == null ? void 0 : d5.getIsVisible()); }, { key: key2, debug: () => { @@ -24121,10 +25015,7 @@ var Visibility = { getLeftVisibleLeafColumns: makeVisibleColumnsMethod("getLeftVisibleLeafColumns", () => table.getLeftLeafColumns()), getRightVisibleLeafColumns: makeVisibleColumnsMethod("getRightVisibleLeafColumns", () => table.getRightLeafColumns()), getCenterVisibleLeafColumns: makeVisibleColumnsMethod("getCenterVisibleLeafColumns", () => table.getCenterLeafColumns()), - setColumnVisibility: (updater) => { - var _a2, _b2; - return (_b2 = (_a2 = table.options).onColumnVisibilityChange) == null ? void 0 : _b2.call(_a2, updater); - }, + 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 : {}); @@ -24132,26 +25023,17 @@ var Visibility = { toggleAllColumnsVisible: (value) => { var _value; value = (_value = value) != null ? _value : !table.getIsAllColumnsVisible(); - table.setColumnVisibility(table.getAllLeafColumns().reduce((obj, column) => { - var _a2; - return { - ...obj, - [column.id]: !value ? !((_a2 = column.getCanHide) == null ? void 0 : _a2.call(column)) : value - }; - }, {})); + table.setColumnVisibility(table.getAllLeafColumns().reduce((obj, column) => ({ + ...obj, + [column.id]: !value ? !(column.getCanHide != null && column.getCanHide()) : value + }), {})); }, - getIsAllColumnsVisible: () => !table.getAllLeafColumns().some((column) => { - var _a2; - return !((_a2 = column.getIsVisible) == null ? void 0 : _a2.call(column)); - }), - getIsSomeColumnsVisible: () => table.getAllLeafColumns().some((column) => { - var _a2; - return (_a2 = column.getIsVisible) == null ? void 0 : _a2.call(column); - }), + 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 _a2; - table.toggleAllColumnsVisible((_a2 = e4.target) == null ? void 0 : _a2.checked); + var _target; + table.toggleAllColumnsVisible((_target = e4.target) == null ? void 0 : _target.checked); }; } }; @@ -24167,8 +25049,7 @@ function createTable(options) { _features: features }; const defaultOptions3 = table._features.reduce((obj, feature) => { - var _a2; - return Object.assign(obj, (_a2 = feature.getDefaultOptions) == null ? void 0 : _a2.call(feature, table)); + return Object.assign(obj, feature.getDefaultOptions == null ? void 0 : feature.getDefaultOptions(table)); }, {}); const mergeOptions = (options2) => { if (table.options.mergeOptions) { @@ -24185,9 +25066,8 @@ function createTable(options) { ...(_options$initialState = options.initialState) != null ? _options$initialState : {} }; table._features.forEach((feature) => { - var _a2; var _feature$getInitialSt; - initialState = (_feature$getInitialSt = (_a2 = feature.getInitialState) == null ? void 0 : _a2.call(feature, initialState)) != null ? _feature$getInitialSt : initialState; + initialState = (_feature$getInitialSt = feature.getInitialState == null ? void 0 : feature.getInitialState(initialState)) != null ? _feature$getInitialSt : initialState; }); const queued = []; let queuedTimeout = false; @@ -24223,13 +25103,11 @@ function createTable(options) { return table.options.state; }, setState: (updater) => { - var _a2, _b2; - (_b2 = (_a2 = table.options).onStateChange) == null ? void 0 : _b2.call(_a2, updater); + table.options.onStateChange == null ? void 0 : table.options.onStateChange(updater); }, _getRowId: (row, index, parent) => { - var _a2, _b2; var _table$options$getRow; - return (_table$options$getRow = (_b2 = (_a2 = table.options).getRowId) == null ? void 0 : _b2.call(_a2, row, index, parent)) != null ? _table$options$getRow : `${parent ? [parent.id, index].join(".") : index}`; + 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) { @@ -24265,13 +25143,11 @@ function createTable(options) { return null; }, cell: (props2) => { - var _a2, _b2; - var _props$renderValue$to; - return (_props$renderValue$to = (_b2 = (_a2 = props2.renderValue()) == null ? void 0 : _a2.toString) == null ? void 0 : _b2.call(_a2)) != null ? _props$renderValue$to : null; + 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) => { - var _a2; - return Object.assign(obj, (_a2 = feature.getDefaultColumnDef) == null ? void 0 : _a2.call(feature)); + return Object.assign(obj, feature.getDefaultColumnDef == null ? void 0 : feature.getDefaultColumnDef()); }, {}), ...defaultColumn }; @@ -24339,18 +25215,14 @@ function createTable(options) { getColumn: (columnId) => { const column = table._getAllFlatColumnsById()[columnId]; if (!column) { - if (true) { - console.warn(`[Table] Column with id ${columnId} does not exist.`); - } - throw new Error(); + console.error(`[Table] Column with id '${columnId}' does not exist.`); } return column; } }; Object.assign(table, coreInstance); table._features.forEach((feature) => { - var _a2; - return Object.assign(table, (_a2 = feature.createTable) == null ? void 0 : _a2.call(feature, table)); + return Object.assign(table, feature.createTable == null ? void 0 : feature.createTable(table)); }); return table; } @@ -24378,13 +25250,11 @@ function createCell(table, row, column, columnId) { }) }; table._features.forEach((feature) => { - var _a2; - Object.assign(cell, (_a2 = feature.createCell) == null ? void 0 : _a2.call(feature, cell, column, row, table)); + Object.assign(cell, feature.createCell == null ? void 0 : feature.createCell(cell, column, row, table)); }, {}); return cell; } var createRow = (table, id2, original, rowIndex, depth, subRows) => { - var _a2; let row = { id: id2, index: rowIndex, @@ -24397,7 +25267,7 @@ var createRow = (table, id2, original, rowIndex, depth, subRows) => { return row._valuesCache[columnId]; } const column = table.getColumn(columnId); - if (!column.accessorFn) { + if (!(column != null && column.accessorFn)) { return void 0; } row._valuesCache[columnId] = column.accessorFn(row.original, rowIndex); @@ -24408,7 +25278,7 @@ var createRow = (table, id2, original, rowIndex, depth, subRows) => { return row._uniqueValuesCache[columnId]; } const column = table.getColumn(columnId); - if (!column.accessorFn) { + if (!(column != null && column.accessorFn)) { return void 0; } if (!column.columnDef.getUniqueValues) { @@ -24450,7 +25320,7 @@ var createRow = (table, id2, original, rowIndex, depth, subRows) => { }; for (let i4 = 0; i4 < table._features.length; i4++) { const feature = table._features[i4]; - Object.assign(row, (_a2 = feature == null ? void 0 : feature.createRow) == null ? void 0 : _a2.call(feature, row, table)); + Object.assign(row, feature == null ? void 0 : feature.createRow == null ? void 0 : feature.createRow(row, table)); } return row; }; @@ -24462,7 +25332,6 @@ function getCoreRowModel() { rowsById: {} }; const accessRows = function(originalRows, depth, parent) { - var _a2; if (depth === void 0) { depth = 0; } @@ -24473,8 +25342,9 @@ function getCoreRowModel() { rowModel.rowsById[row.id] = row; rows.push(row); if (table.options.getSubRows) { + var _row$originalSubRows; row.originalSubRows = table.options.getSubRows(originalRows[i4], i4); - if ((_a2 = row.originalSubRows) == null ? void 0 : _a2.length) { + if ((_row$originalSubRows = row.originalSubRows) != null && _row$originalSubRows.length) { row.subRows = accessRows(row.originalSubRows, depth + 1, row); } } @@ -24546,7 +25416,7 @@ function getGroupedRowModel() { return row._groupingValuesCache[columnId2]; } const column = table.getColumn(columnId2); - const aggregateFn = column.getAggregationFn(); + const aggregateFn = column == null ? void 0 : column.getAggregationFn(); if (aggregateFn) { row._groupingValuesCache[columnId2] = aggregateFn(columnId2, leafRows, groupedRows2); return row._groupingValuesCache[columnId2]; @@ -24618,9 +25488,9 @@ function getExpandedRowModel() { function expandRows(rowModel) { const expandedRows = []; const handleRow = (row) => { - var _a2; + var _row$subRows; expandedRows.push(row); - if (((_a2 = row.subRows) == null ? void 0 : _a2.length) && row.getIsExpanded()) { + if ((_row$subRows = row.subRows) != null && _row$subRows.length && row.getIsExpanded()) { row.subRows.forEach(handleRow); } }; @@ -24634,7 +25504,7 @@ function expandRows(rowModel) { // node_modules/@tanstack/react-table/build/lib/index.mjs function flexRender(Comp, props2) { - return !Comp ? null : isReactComponent(Comp) ? /* @__PURE__ */ h(Comp, props2) : Comp; + return !Comp ? null : isReactComponent(Comp) ? /* @__PURE__ */ y(Comp, props2) : Comp; } function isReactComponent(component) { return isClassComponent(component) || typeof component === "function" || isExoticComponent(component); @@ -24656,10 +25526,10 @@ function useReactTable(options) { renderFallbackValue: null, ...options }; - const [tableRef] = p2(() => ({ + const [tableRef] = h2(() => ({ current: createTable(resolvedOptions) })); - const [state, setState] = p2(() => tableRef.current.initialState); + const [state, setState] = h2(() => tableRef.current.initialState); tableRef.current.setOptions((prev) => ({ ...prev, ...options, @@ -24668,19 +25538,435 @@ function useReactTable(options) { ...options.state }, onStateChange: (updater) => { - var _a2; setState(updater); - (_a2 = options.onStateChange) == null ? void 0 : _a2.call(options, updater); + options.onStateChange == null ? void 0 : options.onStateChange(updater); } })); return tableRef.current; } +// src/dispatch/mdb.ts +var import_lodash3 = __toESM(require_lodash()); +var import_obsidian7 = require("obsidian"); + +// src/utils/contexts/file.ts +var renameRowForFile = (folder, filePath, toFilePath) => { + return { + ...folder, + rows: folder.rows.map( + (f4) => f4.File == filePath ? { ...f4, File: toFilePath } : f4 + ) + }; +}; +var removeRowForFile = (folder, filePath) => { + return { + ...folder, + rows: folder.rows.filter( + (f4) => f4.File != filePath + ) + }; +}; +var removeRowsForFile = (folder, filePaths) => { + return { + ...folder, + rows: folder.rows.filter( + (f4) => !filePaths.includes(f4.File) + ) + }; +}; + +// src/utils/contexts/links.ts +var valueContainsLink = (link2, value) => { + return parseMultiString(value).some((f4) => link2 == parseLinkString(f4)); +}; +var replaceLinkInValue = (link2, newLink, value) => { + return serializeMultiString(parseMultiString(value).map((f4) => parseLinkString(f4) == link2 ? newLink : link2)); +}; +var removeLinkInValue = (link2, value) => { + return serializeMultiString(parseMultiString(value).filter((f4) => f4 != link2)); +}; +var linkColumns = (cols) => { + return cols.filter((f4) => f4.type.startsWith("link") || f4.type.startsWith("context")); +}; +var removeLinksInRow = (plugin, row, link2, cols) => { + if (cols.length == 0) { + return row; + } + const deltaRow = cols.reduce((p3, c4) => { + if (valueContainsLink(link2, row[c4.name])) { + const newValue = removeLinkInValue(link2, row[c4.name]); + saveFrontmatterValue( + plugin, + row.File, + c4.name, + newValue, + c4.type, + plugin.settings.saveAllContextToFrontmatter + ); + return { ...p3, [c4.name]: newValue }; + } + return p3; + }, {}); + return { ...row, ...deltaRow }; +}; +var renameLinksInRow = (plugin, row, link2, newLink, cols) => { + if (cols.length == 0) { + return row; + } + const deltaRow = cols.reduce((p3, c4) => { + if (valueContainsLink(link2, row[c4.name])) { + const newValue = replaceLinkInValue(link2, newLink, row[c4.name]); + saveFrontmatterValue( + plugin, + row.File, + c4.name, + newValue, + c4.type, + plugin.settings.saveAllContextToFrontmatter + ); + return { ...p3, [c4.name]: newValue }; + } + return p3; + }, {}); + return { ...row, ...deltaRow }; +}; + +// src/utils/metadata/dataview/parseDataview.ts +var parseDataview = (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 format(new Date(value.ts), "yyyy-MM-dd"); + 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; + } + return value.path; + } + break; + case "text": + case "tag": + case "image": + return value; + break; + } + return ""; +}; + +// src/dispatch/mdb.ts +var processContextFile = async (plugin, context, processor, fallback) => { + const dbFileExists = getAbstractFileAtPath(app, context.dbPath); + if (dbFileExists) { + const contextDB = await getMDBTable(plugin, context, "files"); + if (contextDB) { + await processor(contextDB, context); + return; + } else if (fallback) { + await fallback(); + } + } else if (fallback) { + await fallback(); + } +}; +var saveDB = async (plugin, context, newTable) => { + return saveMDBToPath(plugin, context, newTable); +}; +var insertColumns = (table, column) => { + if (table.cols.find((f4) => f4.name == column.name)) { + new import_obsidian7.Notice(i18n_default.notice.duplicatePropertyName); + return; + } + return { + ...table, + cols: [...table.cols, column] + }; +}; +var updateValue = (folder, lookupField, lookupValue, field, value) => { + return { + ...folder, + rows: folder.rows.map( + (f4) => f4[lookupField] == lookupValue ? { + ...f4, + [field]: value + } : f4 + ) + }; +}; +var insertRowsIfUnique = (folder, rows) => { + return { ...folder, rows: [...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_obsidian7.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) => { + const tagFileExists = getAbstractFileAtPath(app, context.dbPath); + if (!tagFileExists) { + await createDefaultDB(plugin, context); + } + await getMDBTable(plugin, context, "files").then( + (tagDB) => { + const newMDB = updateValue(tagDB, FilePropertyName, file, field, value); + return saveDB(plugin, context, newMDB).then((f4) => newMDB); + } + ); +}; +var insertContextColumn = async (plugin, context, field) => { + const tagFileExists = getAbstractFileAtPath(app, context.dbPath); + if (!tagFileExists) { + await createDefaultDB(plugin, context); + } + await getMDBTable(plugin, context, "files").then((tagDB) => { + const newDB = insertColumns(tagDB, field); + saveDB(plugin, context, newDB).then((f4) => newDB); + return newDB; + }); +}; +var insertContextItems = async (plugin, newPaths, t4) => { + const saveNewContextRows = async (tag, context2) => { + const newRow = newPaths.map((newPath) => ({ File: newPath })); + await saveDB(plugin, context2, insertRowsIfUnique(tag, newRow)); + }; + const context = tagContextFromTag(plugin, t4); + const tagFileExists = getAbstractFileAtPath(app, context.dbPath); + if (!tagFileExists) { + await createDefaultDB(plugin, context); + } + await getMDBTable(plugin, context, "files").then( + (tagDB) => saveNewContextRows(tagDB, context) + ); +}; +var fileToFM = (file, cols, plugin) => { + const fm = frontMatterForFile(file); + const fmKeys = frontMatterKeys(fm).filter((f4) => cols.some((g4) => f4 == g4)); + const rows = fmKeys.reduce( + (p3, c4) => ({ ...p3, [c4]: parseFrontMatter(c4, fm[c4]) }), + {} + ); + if (plugin.dataViewAPI()) { + return { ...rows, ...fileToDV(file, cols, plugin) }; + } + return rows; +}; +var fileToDV = (file, cols, plugin) => { + const dvValues = plugin.dataViewAPI().page(file.path); + const fmKeys = 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") + ).filter((f4) => cols.some((g4) => f4 == g4)); + return fmKeys.reduce( + (p3, c4) => ({ + ...p3, + [c4]: parseDataview(c4, dvValues[c4]) + }), + {} + ); +}; +var onMetadataChange = async (plugin, file, contexts) => { + const promises = contexts.map((context) => { + return processContextFile(plugin, context, async (mdb, context2) => { + const newDB = { + ...mdb, + rows: mdb.rows.map( + (f4) => f4.File == file.path ? { + ...f4, + ...fileToFM( + file, + mdb.cols.map((f5) => f5.name), + plugin + ) + } : f4 + ) + }; + if (!import_lodash3.default.isEqual(mdb, newDB)) { + await saveDB(plugin, context2, newDB); + } + return newDB; + }); + }); + return Promise.all(promises); +}; +var renameTagInContexts = async (plugin, oldTag, newTag, contexts) => { + 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 }; + }; + const promises = contexts.map((context) => { + return processContextFile(plugin, context, async (mdb, context2) => { + const newDB = changeTagInContextMDB(mdb); + if (!import_lodash3.default.isEqual(mdb, newDB)) { + await saveDB(plugin, context2, newDB); + } + return newDB; + }); + }); + return Promise.all(promises); +}; +var removeTagInContexts = async (plugin, tag, contexts) => { + 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 }; + }; + const promises = contexts.map((context) => { + return processContextFile(plugin, context, async (mdb, context2) => { + const newDB = deleteTagInContextMDB(mdb); + if (!import_lodash3.default.isEqual(mdb, newDB)) { + await saveDB(plugin, context2, 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_lodash3.default.isEqual(mdb, newDB)) { + await saveDB(plugin, context2, 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) => { + const linkCols = linkColumns(mdb.cols); + const newDB = { + ...mdb, + rows: mdb.rows.map((r3) => renameLinksInRow(plugin, r3, oldPath, newPath, linkCols)) + }; + if (!import_lodash3.default.isEqual(mdb, newDB)) { + await saveDB(plugin, context2, 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) => { + const linkCols = linkColumns(mdb.cols); + const newDB = { + ...mdb, + rows: mdb.rows.map((r3) => removeLinksInRow(plugin, r3, path, linkCols)) + }; + if (!import_lodash3.default.isEqual(mdb, newDB)) { + await saveDB(plugin, context2, 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) => { + const newDB = renameRowForFile(mdb, oldPath, newPath); + if (!import_lodash3.default.isEqual(mdb, newDB)) { + await saveDB(plugin, context2, 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) => { + const removeRow = mdb.rows.find((f4) => f4.File == path); + if (removeRow) { + saveContextToFrontmatter(path, mdb.cols, removeRow, plugin); + } + const newDB = removeRowForFile(mdb, path); + if (!import_lodash3.default.isEqual(mdb, newDB)) { + await saveDB(plugin, context2, newDB); + } + return newDB; + }); + }); + return Promise.all(promises); +}; +var removeFilesInContext = async (plugin, paths, context) => { + return processContextFile(plugin, context, async (mdb, context2) => { + mdb.rows.forEach((row) => { + if (paths.includes(row.File)) + saveContextToFrontmatter(row.File, mdb.cols, row, plugin); + }); + const newDB = removeRowsForFile(mdb, paths); + if (!import_lodash3.default.isEqual(mdb, newDB)) { + await saveDB(plugin, context2, newDB); + } + return newDB; + }); +}; + // src/components/ui/menus/menuItems.tsx -var import_obsidian9 = require("obsidian"); +var import_obsidian8 = require("obsidian"); // src/components/ui/menus/selectMenu/SelectMenuComponent.tsx -var import_lodash5 = __toESM(require_lodash()); +var import_lodash4 = __toESM(require_lodash()); // src/components/ui/menus/selectMenu/concerns/focusNextElement.js function focusNextElement(scope, currentTarget) { @@ -24714,19 +26000,19 @@ var STYLE_PROPS = [ ]; var SelectMenuInput = k3( (props2, input) => { - const { classNames: classNames8, inputAttributes, inputEventHandlers, index } = props2; + const { classNames: classNames9, inputAttributes, inputEventHandlers, index } = props2; const sizer = _2(null); - const [inputWidth, setInputWidth] = p2(null); - const [query, setQuery] = p2(""); - const [placeholderText, setPlaceholderText] = p2(""); - h2(() => { + const [inputWidth, setInputWidth] = h2(null); + const [query, setQuery] = h2(""); + const [placeholderText, setPlaceholderText] = h2(""); + p2(() => { copyInputStyles(); updateInputWidth(); setTimeout(() => { input.current.focus(); }, 50); }, []); - h2(() => { + p2(() => { if (query !== props2.query || placeholderText !== props2.placeholderText) { setQuery(props2.query); setPlaceholderText(props2.placeholderText); @@ -24746,18 +26032,18 @@ var SelectMenuInput = k3( setInputWidth(_inputWidth); } }; - return /* @__PURE__ */ bn.createElement("div", { - className: classNames8.searchWrapper - }, /* @__PURE__ */ bn.createElement("input", { + return /* @__PURE__ */ Cn.createElement("div", { + className: classNames9.searchWrapper + }, /* @__PURE__ */ Cn.createElement("input", { ...inputAttributes, ...inputEventHandlers, ref: input, value: query, placeholder: placeholderText, - className: classNames8.searchInput, + className: classNames9.searchInput, role: "combobox", style: { width: "100%" } - }), /* @__PURE__ */ bn.createElement("div", { + }), /* @__PURE__ */ Cn.createElement("div", { ref: sizer, style: SIZER_STYLES }, query || placeholderText)); @@ -24767,11 +26053,11 @@ var SelectMenuInput_default = SelectMenuInput; // src/components/ui/menus/selectMenu/SelectMenuPill.tsx var SelectMenuPillComponent = (props2) => { - return /* @__PURE__ */ bn.createElement("button", { + return /* @__PURE__ */ Cn.createElement("button", { type: "button", className: props2.classNames.selectedTag, onClick: props2.onDelete - }, /* @__PURE__ */ bn.createElement("span", { + }, /* @__PURE__ */ Cn.createElement("span", { className: props2.classNames.selectedTagName }, props2.tag.name)); }; @@ -24784,24 +26070,24 @@ function markIt(name, query) { } var SelectMenuSuggestionsComponent = (props2) => { const ref = _2(null); - h2(() => { + p2(() => { var _a2; if (props2.active) { (_a2 = ref == null ? void 0 : ref.current) == null ? void 0 : _a2.scrollIntoViewIfNeeded(); } }, [props2.active]); - return /* @__PURE__ */ bn.createElement(bn.Fragment, null, props2.item.onToggle && /* @__PURE__ */ bn.createElement("div", null, "Toggle"), /* @__PURE__ */ bn.createElement("span", { + return /* @__PURE__ */ Cn.createElement(Cn.Fragment, null, props2.item.onToggle && /* @__PURE__ */ Cn.createElement("div", null, "Toggle"), /* @__PURE__ */ Cn.createElement("span", { ref, dangerouslySetInnerHTML: { __html: markIt(props2.item.name, props2.query) } - }), props2.item.description && /* @__PURE__ */ bn.createElement("span", { + }), props2.item.description && /* @__PURE__ */ Cn.createElement("span", { className: "mk-description", ref, dangerouslySetInnerHTML: { __html: markIt(props2.item.description, props2.query) } - }), props2.item.removeable && /* @__PURE__ */ bn.createElement("div", null, "Remove")); + }), props2.item.removeable && /* @__PURE__ */ Cn.createElement("div", null, "Remove")); }; var SelectMenuSuggestions = (props2) => { const timer = _2(null); @@ -24814,35 +26100,35 @@ var SelectMenuSuggestions = (props2) => { }; const options = props2.options.map((item, index) => { const key2 = `${props2.id}-${index}`; - const classNames8 = []; + const classNames9 = []; if (props2.index === index) { - classNames8.push(props2.classNames.suggestionActive); + classNames9.push(props2.classNames.suggestionActive); } if (item.disabled) { - classNames8.push(props2.classNames.suggestionDisabled); + classNames9.push(props2.classNames.suggestionDisabled); } - return /* @__PURE__ */ bn.createElement("li", { + return /* @__PURE__ */ Cn.createElement("li", { id: key2, key: key2, role: "option", - className: classNames8.join(" "), + className: classNames9.join(" "), "aria-disabled": Boolean(item.disabled), onMouseDown: (e4) => e4.preventDefault(), onClick: () => props2.addTag(item), onMouseOver: (e4) => mouseOver(e4, index), onMouseOut: (e4) => props2.hoverSelect && clearTimeout(timer.current) - }, /* @__PURE__ */ bn.createElement(SelectMenuSuggestionsComponent, { + }, /* @__PURE__ */ Cn.createElement(SelectMenuSuggestionsComponent, { item, query: props2.query, active: index == props2.index })); }); - return /* @__PURE__ */ bn.createElement("div", { + return /* @__PURE__ */ Cn.createElement("div", { className: props2.classNames.suggestions - }, /* @__PURE__ */ bn.createElement("ul", { + }, /* @__PURE__ */ Cn.createElement("ul", { role: "listbox", id: props2.id - }, options, props2.query && props2.allowNew && /* @__PURE__ */ bn.createElement("li", { + }, options, props2.query && props2.allowNew && /* @__PURE__ */ Cn.createElement("li", { onMouseDown: (e4) => e4.preventDefault(), onClick: () => props2.addTag({ name: props2.query, value: props2.query }) }, "Add ", props2.query))); @@ -24930,16 +26216,16 @@ function getOptions(props2, query) { } return options; } -var SelectMenuComponent = bn.forwardRef( +var SelectMenuComponent = Cn.forwardRef( (_props, ref) => { const props2 = { ...defaultProps, ..._props }; - const [options, setOptions] = p2([]); + const [options, setOptions] = h2([]); const inputRef = _2(null); - const [query, setQuery] = p2(""); - const [focused, setFocused] = p2(false); - const [index, setIndex] = p2(0); + const [query, setQuery] = h2(""); + const [focused, setFocused] = h2(false); + const [index, setIndex] = h2(0); const onComposition = _2(false); - h2(() => { + p2(() => { if (ref) { ref.current = () => { var _a2; @@ -24952,14 +26238,14 @@ var SelectMenuComponent = bn.forwardRef( }; } }, [focused]); - h2(() => { + p2(() => { var _a2; if (index != -1 && props2.onHover && props2.hoverSelect) { debounceFn((_a2 = options[index]) == null ? void 0 : _a2.value); } }, [index, options]); const debounceFn = T2( - (0, import_lodash5.debounce)(handleDebounceFn, 100, { + (0, import_lodash4.debounce)(handleDebounceFn, 100, { leading: false }), [] @@ -24967,7 +26253,7 @@ var SelectMenuComponent = bn.forwardRef( function handleDebounceFn(inputValue) { props2.onHover(inputValue); } - h2(() => { + p2(() => { if (query.length == 0 && props2.defaultSuggestions) { setOptions(props2.defaultSuggestions); return; @@ -25080,41 +26366,41 @@ var SelectMenuComponent = bn.forwardRef( onCompositionStart: onInput }; const expanded = focused && query.length >= props2.minQueryLength; - const classNames8 = Object.assign({}, CLASS_NAMES, props2.classNames); - const rootClassNames = [classNames8.root]; - focused && rootClassNames.push(classNames8.rootFocused); - return /* @__PURE__ */ bn.createElement("div", { + const classNames9 = Object.assign({}, CLASS_NAMES, props2.classNames); + const rootClassNames = [classNames9.root]; + focused && rootClassNames.push(classNames9.rootFocused); + return /* @__PURE__ */ Cn.createElement("div", { ref: container, className: rootClassNames.join(" ") - }, !props2.suggestionsOnly ? /* @__PURE__ */ bn.createElement("div", { - className: classNames8.selected, + }, !props2.suggestionsOnly ? /* @__PURE__ */ Cn.createElement("div", { + className: classNames9.selected, "aria-relevant": "additions removals", "aria-live": "polite" - }, /* @__PURE__ */ bn.createElement(bn.Fragment, null, props2.tags.map((tag, i4) => /* @__PURE__ */ bn.createElement(SelectMenuPill_default, { + }, /* @__PURE__ */ Cn.createElement(Cn.Fragment, null, props2.tags.map((tag, i4) => /* @__PURE__ */ Cn.createElement(SelectMenuPill_default, { key: i4, tag, - classNames: classNames8, + classNames: classNames9, onDelete: (e4) => onDeleteTag(i4, e4) - }))), /* @__PURE__ */ bn.createElement("div", { - className: classNames8.search - }, /* @__PURE__ */ bn.createElement(SelectMenuInput_default, { + }))), /* @__PURE__ */ Cn.createElement("div", { + className: classNames9.search + }, /* @__PURE__ */ Cn.createElement(SelectMenuInput_default, { ref: inputRef, query, index, id: props2.id, - classNames: classNames8, + classNames: classNames9, inputAttributes: props2.inputAttributes, inputEventHandlers, expanded, placeholderText: props2.placeholderText - }))) : null, options.length || props2.allowNew ? /* @__PURE__ */ bn.createElement(SelectMenuSuggestions_default, { + }))) : null, options.length || props2.allowNew ? /* @__PURE__ */ Cn.createElement(SelectMenuSuggestions_default, { options, hoverSelect: props2.hoverSelect, query, setIndex, index, id: props2.id, - classNames: classNames8, + classNames: classNames9, expanded, addTag: addTag2, allowNew: props2.allowNew @@ -25124,7 +26410,7 @@ var SelectMenuComponent = bn.forwardRef( var SelectMenuComponent_default = SelectMenuComponent; // src/components/ui/menus/selectMenu.tsx -var SelectMenu = bn.forwardRef( +var SelectMenu = Cn.forwardRef( (props2, ref) => { var _a2; const initialOptions = props2.options.map((o3, i4) => { @@ -25133,7 +26419,7 @@ var SelectMenu = bn.forwardRef( id: i4 + 1 }; }); - h2(() => { + p2(() => { setSuggestions( props2.options.map((o3, i4) => { return { @@ -25143,8 +26429,8 @@ var SelectMenu = bn.forwardRef( }) ); }, [props2.options]); - const [suggestions, setSuggestions] = p2(initialOptions); - const [tags, setTags] = p2( + const [suggestions, setSuggestions] = h2(initialOptions); + const [tags, setTags] = h2( props2.value.map( (v3) => { var _a3; @@ -25158,7 +26444,7 @@ var SelectMenu = bn.forwardRef( ); const onDelete = T2( (tagIndex) => { - const newTags = tags.filter((_7, i4) => i4 !== tagIndex); + const newTags = tags.filter((_9, i4) => i4 !== tagIndex); setTags(newTags); props2.saveOptions( suggestions.map((f4) => f4.value), @@ -25212,7 +26498,7 @@ var SelectMenu = bn.forwardRef( }, [suggestions] ); - return /* @__PURE__ */ bn.createElement(SelectMenuComponent_default, { + return /* @__PURE__ */ Cn.createElement(SelectMenuComponent_default, { tags: props2.multi ? tags : [], suggestions, ref, @@ -25256,7 +26542,7 @@ var inputMenuItem = (menuItem, value, setValue) => { return menuItem; }; var showSelectMenu = (point, optionProps) => { - const menu = new import_obsidian9.Menu(); + const menu = new import_obsidian8.Menu(); menu.dom.toggleClass("mk-menu", true); menu.setUseNativeMenu(false); const frag = document.createDocumentFragment(); @@ -25279,7 +26565,7 @@ var showSelectMenu = (point, optionProps) => { menu.onHide(() => optionProps.onHide && optionProps.onHide()); const root = createRoot(div); root.render( - /* @__PURE__ */ bn.createElement(bn.Fragment, null, /* @__PURE__ */ bn.createElement(SelectMenu, { + /* @__PURE__ */ Cn.createElement(Cn.Fragment, null, /* @__PURE__ */ Cn.createElement(SelectMenu, { hide: () => { menu.hide(); optionProps.onHide && optionProps.onHide(); @@ -25315,7 +26601,7 @@ var disclosureMenuItem = (menuItem, multi, editable, title, value, options, save { multi, editable, - value: (_a2 = splitString(value)) != null ? _a2 : [], + value: (_a2 = parseMultiString(value)) != null ? _a2 : [], options, saveOptions, searchable: true, @@ -25329,25 +26615,25 @@ var disclosureMenuItem = (menuItem, multi, editable, title, value, options, save // src/components/ContextView/DataTypeView/OptionCell.tsx var OptionCell = (props2) => { var _a2, _b2; - const initialValue = (props2.multi ? (_a2 = splitString(props2.initialValue)) != null ? _a2 : [] : [props2.initialValue]).filter((f4) => f4); + const initialValue = (props2.multi ? (_a2 = parseMultiString(props2.initialValue)) != null ? _a2 : [] : [props2.initialValue]).filter((f4) => f4); const initialOptions = [ - ...(_b2 = splitString(props2.options).filter((f4) => f4).map((t4) => ({ name: t4, value: t4 }))) != null ? _b2 : [], + ...(_b2 = parseMultiString(props2.options).filter((f4) => f4).map((t4) => ({ name: t4, value: t4 }))) != null ? _b2 : [], ...initialValue.map((f4) => ({ name: f4, value: f4 })) ].filter(onlyUniqueProp("value")); - const [options, setOptions] = p2(initialOptions); - const [value, setValue] = p2(initialValue); - h2(() => { + const [options, setOptions] = h2(initialOptions); + const [value, setValue] = h2(initialValue); + p2(() => { var _a3; setValue( - (props2.multi ? (_a3 = splitString(props2.initialValue)) != null ? _a3 : [] : [props2.initialValue]).filter((f4) => f4) + (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( - options.map((f4) => f4.value).join(","), - newValues.join(",") + serializeMultiString(options.map((f4) => f4.value)), + serializeMultiString(newValues) ); }; const saveOptions = (_options, _value) => { @@ -25357,16 +26643,16 @@ var OptionCell = (props2) => { ); setValue(_value); props2.saveOptions( - _options.filter((f4) => f4.length > 0).join(","), - _value.join(",") + serializeMultiString(_options.filter((f4) => f4.length > 0)), + serializeMultiString(_value) ); } else { const newValues = uniq([...value, _value[0]]); setOptions(_options.map((t4) => ({ name: t4, value: t4 }))); setValue(newValues); props2.saveOptions( - _options.filter((f4) => f4.length > 0).join(","), - newValues.join(",") + serializeMultiString(_options.filter((f4) => f4.length > 0)), + serializeMultiString(newValues) ); } }; @@ -25381,7 +26667,8 @@ var OptionCell = (props2) => { showAll: true, onHide: () => props2.setEditMode(null) }); - return /* @__PURE__ */ bn.createElement(OptionCellBase, { + return /* @__PURE__ */ Cn.createElement(OptionCellBase, { + baseClass: "mk-cell-option", value, menuProps, multi: props2.multi, @@ -25399,7 +26686,7 @@ var OptionCellBase = (props2) => { valueClass } = props2; const menuRef = _2(null); - h2(() => { + p2(() => { if (props2.editMode == 2) { if (!menuRef.current) showMenu(); @@ -25414,64 +26701,70 @@ var OptionCellBase = (props2) => { ); }; const editable = props2.editMode > 0; - return /* @__PURE__ */ bn.createElement("div", { - className: "mk-cell-option", + return /* @__PURE__ */ Cn.createElement("div", { + className: props2.baseClass, ref - }, value.length > 0 ? value.map((o3) => /* @__PURE__ */ bn.createElement("div", { + }, value.length > 0 ? value.map((o3) => /* @__PURE__ */ Cn.createElement("div", { className: "mk-cell-option-item" - }, (getLabelString ? getLabelString(o3).length > 0 : o3.length > 0) ? /* @__PURE__ */ bn.createElement(bn.Fragment, null, /* @__PURE__ */ bn.createElement("div", { + }, (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__ */ bn.createElement("div", { + }, getLabelString ? getLabelString(o3) : o3), editable && props2.multi ? /* @__PURE__ */ Cn.createElement("div", { className: "mk-icon-xsmall", onClick: () => removeValue(o3), dangerouslySetInnerHTML: { __html: uiIconSet["mk-ui-close"] } - }) : /* @__PURE__ */ bn.createElement(bn.Fragment, null)) : /* @__PURE__ */ bn.createElement("div", null, i18n_default.labels.select), editable && !props2.multi && value.length > 0 ? /* @__PURE__ */ bn.createElement(bn.Fragment, null, /* @__PURE__ */ bn.createElement("span", null), /* @__PURE__ */ bn.createElement("div", { + }) : /* @__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-collapse-sm"] } - })) : /* @__PURE__ */ bn.createElement(bn.Fragment, null))) : editable && !props2.multi ? /* @__PURE__ */ bn.createElement("div", { + })) : /* @__PURE__ */ Cn.createElement(Cn.Fragment, null))) : editable && !props2.multi ? /* @__PURE__ */ Cn.createElement("div", { className: "mk-cell-option-item" - }, /* @__PURE__ */ bn.createElement("div", { + }, /* @__PURE__ */ Cn.createElement("div", { onClick: (e4) => !props2.multi && showMenu() - }, i18n_default.labels.select)) : props2.editMode == -1 ? /* @__PURE__ */ bn.createElement("div", { + }, i18n_default.labels.select)) : props2.editMode == -1 ? /* @__PURE__ */ Cn.createElement("div", { className: "mk-cell-option-item mk-cell-empty" - }, /* @__PURE__ */ bn.createElement("div", null, i18n_default.menu.none)) : /* @__PURE__ */ bn.createElement(bn.Fragment, null), editable && props2.multi ? /* @__PURE__ */ bn.createElement("div", { + }, /* @__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__ */ bn.createElement(bn.Fragment, null)); + }) : /* @__PURE__ */ Cn.createElement(Cn.Fragment, null)); }; // src/components/ContextView/DataTypeView/ContextCell.tsx var ContextCell = (props2) => { var _a2, _b2, _c2; - const initialValue = (props2.multi ? (_a2 = splitString(props2.initialValue)) != null ? _a2 : [] : [props2.initialValue]).filter((f4) => (f4 == null ? void 0 : f4.length) > 0).map((f4) => ({ - path: f4, - label: fileNameToString(folderPathToString(f4)) - })); + const stringValueToLink = (strings) => strings.map((f4) => { + return { + label: parseLinkDisplayString(f4), + path: parseLinkString(f4) + }; + }); + const initialValue = stringValueToLink( + props2.multi ? (_a2 = parseMultiString(props2.initialValue)) != null ? _a2 : [] : [props2.initialValue] + ); const ref = _2(null); - const options = (_c2 = (_b2 = props2.contextTable) == null ? void 0 : _b2.rows.map((f4) => ({ - name: fileNameToString(folderPathToString(f4["File"])), - value: f4["File"] - }))) != null ? _c2 : []; - const [value, setValue] = p2(initialValue); + 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 + })); + const [value, setValue] = h2(initialValue); const removeValue = (v3) => { const newValues = value.filter((f4) => f4.path != v3.path); setValue(newValues); - props2.saveValue(newValues.map((f4) => f4.path).join(",")); + props2.saveValue(serializeMultiString(newValues.map((f4) => f4.path))); }; - h2(() => { + p2(() => { var _a3; setValue( - (props2.multi ? (_a3 = splitString(props2.initialValue)) != null ? _a3 : [] : [props2.initialValue]).filter((f4) => (f4 == null ? void 0 : f4.length) > 0).map((f4) => ({ - path: f4, - label: fileNameToString(folderPathToString(f4)) - })) + stringValueToLink( + props2.multi ? (_a3 = parseMultiString(props2.initialValue)) != null ? _a3 : [] : [props2.initialValue] + ) ); }, [props2.initialValue]); const saveOptions = (_options, _value) => { @@ -25483,7 +26776,7 @@ var ContextCell = (props2) => { label: fileNameToString(folderPathToString(f4)) })) ); - props2.saveValue(_value.join(",")); + props2.saveValue(serializeMultiString(_value)); } else { const newValue = _value[0]; if (newValue) { @@ -25494,7 +26787,7 @@ var ContextCell = (props2) => { path: f4 })) ); - props2.saveValue(newValues.join(",")); + props2.saveValue(serializeMultiString(newValues)); } } }; @@ -25518,7 +26811,8 @@ var ContextCell = (props2) => { onHide: () => props2.setEditMode(null) }; }; - return /* @__PURE__ */ bn.createElement(OptionCellBase, { + return /* @__PURE__ */ Cn.createElement(OptionCellBase, { + baseClass: "mk-cell-context", menuProps, openItem: openLink, getLabelString: (o3) => o3.label, @@ -25530,7 +26824,7 @@ var ContextCell = (props2) => { }; // src/components/ui/menus/datePickerMenu.tsx -var import_obsidian10 = require("obsidian"); +var import_obsidian9 = require("obsidian"); // node_modules/react-day-picker/dist/index.esm.js var __assign2 = function() { @@ -25633,7 +26927,7 @@ function formatWeekNumber(weekNumber) { return "".concat(weekNumber); } function formatWeekdayName(weekday, options) { - return format(weekday, "cccccc", options); + return format(weekday, "cccccc", options).toUpperCase(); } function formatYearCaption(year, options) { return format(year, "yyyy", options); @@ -25674,13 +26968,13 @@ var labels = /* @__PURE__ */ Object.freeze({ labelMonthDropdown, labelNext, labelPrevious, - labelWeekday, labelWeekNumber, + labelWeekday, labelYearDropdown }); function getDefaultContextValues() { var captionLayout = "buttons"; - var classNames8 = defaultClassNames; + var classNames9 = defaultClassNames; var locale2 = en_US_default; var modifiersClassNames = {}; var modifiers = {}; @@ -25689,7 +26983,7 @@ function getDefaultContextValues() { var today = new Date(); return { captionLayout, - classNames: classNames8, + classNames: classNames9, formatters: formatters3, labels, locale: locale2, @@ -25719,7 +27013,7 @@ function parseFromToProps(props2) { toDate: toDate2 ? startOfDay(toDate2) : void 0 }; } -var DayPickerContext = B(void 0); +var DayPickerContext = F(void 0); function DayPickerProvider(props2) { var _a2; var initialProps = props2.initialProps; @@ -25734,7 +27028,7 @@ function DayPickerProvider(props2) { onSelect = initialProps.onSelect; } var value = __assign2(__assign2(__assign2({}, defaultContextValues), initialProps), { captionLayout, classNames: __assign2(__assign2({}, defaultContextValues.classNames), initialProps.classNames), components: __assign2({}, initialProps.components), formatters: __assign2(__assign2({}, defaultContextValues.formatters), initialProps.formatters), fromDate, labels: __assign2(__assign2({}, defaultContextValues.labels), initialProps.labels), mode: initialProps.mode || defaultContextValues.mode, modifiers: __assign2(__assign2({}, defaultContextValues.modifiers), initialProps.modifiers), modifiersClassNames: __assign2(__assign2({}, defaultContextValues.modifiersClassNames), initialProps.modifiersClassNames), onSelect, styles: __assign2(__assign2({}, defaultContextValues.styles), initialProps.styles), toDate: toDate2 }); - return bn.createElement(DayPickerContext.Provider, { value }, props2.children); + return Cn.createElement(DayPickerContext.Provider, { value }, props2.children); } function useDayPicker() { var context = q2(DayPickerContext); @@ -25744,14 +27038,14 @@ function useDayPicker() { return context; } function CaptionLabel(props2) { - var _a2 = useDayPicker(), locale2 = _a2.locale, classNames8 = _a2.classNames, styles = _a2.styles, formatCaption2 = _a2.formatters.formatCaption; - return bn.createElement("h2", { className: classNames8.caption_label, style: styles.caption_label, "aria-live": "polite", "aria-atomic": "true", id: props2.id }, formatCaption2(props2.displayMonth, { locale: locale2 })); + 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 bn.createElement( + return Cn.createElement( "svg", __assign2({ width: "8px", height: "8px", viewBox: "0 0 120 120", "data-testid": "iconDropdown" }, props2), - bn.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" }) + 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) { @@ -25759,26 +27053,26 @@ function Dropdown(props2) { 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 bn.createElement( + return Cn.createElement( "div", { className, style }, - bn.createElement("span", { className: dayPicker.classNames.vhidden }, props2["aria-label"]), - bn.createElement("select", { name: props2.name, "aria-label": props2["aria-label"], className: dayPicker.classNames.dropdown, style: dayPicker.styles.dropdown, value, onChange }, children), - bn.createElement( + 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, - bn.createElement(IconDropdownComponent, { className: dayPicker.classNames.dropdown_icon, style: dayPicker.styles.dropdown_icon }) + 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, classNames8 = _b2.classNames, components = _b2.components, labelMonthDropdown2 = _b2.labels.labelMonthDropdown; + 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 bn.createElement(bn.Fragment, null); + return Cn.createElement(Cn.Fragment, null); if (!toDate2) - return bn.createElement(bn.Fragment, null); + return Cn.createElement(Cn.Fragment, null); var dropdownMonths = []; if (isSameYear(fromDate, toDate2)) { var date = startOfMonth(fromDate); @@ -25797,19 +27091,19 @@ function MonthsDropdown(props2) { props2.onChange(newMonth); }; var DropdownComponent2 = (_a2 = components === null || components === void 0 ? void 0 : components.Dropdown) !== null && _a2 !== void 0 ? _a2 : Dropdown; - return bn.createElement(DropdownComponent2, { name: "months", "aria-label": labelMonthDropdown2(), className: classNames8.dropdown_month, style: styles.dropdown_month, onChange: handleChange, value: props2.displayMonth.getMonth(), caption: formatMonthCaption2(props2.displayMonth, { locale: locale2 }) }, dropdownMonths.map(function(m5) { - return bn.createElement("option", { key: m5.getMonth(), value: m5.getMonth() }, formatMonthCaption2(m5, { locale: locale2 })); + 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, classNames8 = _b2.classNames, components = _b2.components, formatYearCaption2 = _b2.formatters.formatYearCaption, labelYearDropdown2 = _b2.labels.labelYearDropdown; + 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 bn.createElement(bn.Fragment, null); + return Cn.createElement(Cn.Fragment, null); if (!toDate2) - return bn.createElement(bn.Fragment, null); + return Cn.createElement(Cn.Fragment, null); var fromYear = fromDate.getFullYear(); var toYear = toDate2.getFullYear(); for (var year = fromYear; year <= toYear; year++) { @@ -25820,12 +27114,12 @@ function YearsDropdown(props2) { props2.onChange(newMonth); }; var DropdownComponent2 = (_a2 = components === null || components === void 0 ? void 0 : components.Dropdown) !== null && _a2 !== void 0 ? _a2 : Dropdown; - return bn.createElement(DropdownComponent2, { name: "years", "aria-label": labelYearDropdown2(), className: classNames8.dropdown_year, style: styles.dropdown_year, onChange: handleChange, value: displayMonth.getFullYear(), caption: formatYearCaption2(displayMonth, { locale: locale2 }) }, years.map(function(year2) { - return bn.createElement("option", { key: year2.getFullYear(), value: year2.getFullYear() }, formatYearCaption2(year2, { locale: locale2 })); + 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 = p2(defaultValue2), uncontrolledValue = _a2[0], setValue = _a2[1]; + var _a2 = h2(defaultValue2), uncontrolledValue = _a2[0], setValue = _a2[1]; var value = controlledValue === void 0 ? uncontrolledValue : controlledValue; return [value, setValue]; } @@ -25902,7 +27196,7 @@ function getPreviousMonth(startingMonth, options) { } return addMonths(month, -offset); } -var NavigationContext = B(void 0); +var NavigationContext = F(void 0); function NavigationProvider(props2) { var dayPicker = useDayPicker(); var _a2 = useNavigationState(), currentMonth = _a2[0], goToMonth = _a2[1]; @@ -25933,7 +27227,7 @@ function NavigationProvider(props2) { nextMonth, isDateDisplayed }; - return bn.createElement(NavigationContext.Provider, { value }, props2.children); + return Cn.createElement(NavigationContext.Provider, { value }, props2.children); } function useNavigation() { var context = q2(NavigationContext); @@ -25944,38 +27238,38 @@ function useNavigation() { } function CaptionDropdowns(props2) { var _a2; - var _b2 = useDayPicker(), classNames8 = _b2.classNames, styles = _b2.styles, components = _b2.components; + var _b2 = useDayPicker(), classNames9 = _b2.classNames, styles = _b2.styles, components = _b2.components; var goToMonth = useNavigation().goToMonth; var handleMonthChange = function(newMonth) { goToMonth(newMonth); }; var CaptionLabelComponent = (_a2 = components === null || components === void 0 ? void 0 : components.CaptionLabel) !== null && _a2 !== void 0 ? _a2 : CaptionLabel; - var captionLabel = bn.createElement(CaptionLabelComponent, { id: props2.id, displayMonth: props2.displayMonth }); - return bn.createElement( + var captionLabel = Cn.createElement(CaptionLabelComponent, { id: props2.id, displayMonth: props2.displayMonth }); + return Cn.createElement( "div", - { className: classNames8.caption_dropdowns, style: styles.caption_dropdowns }, - bn.createElement("div", { className: classNames8.vhidden }, captionLabel), - bn.createElement(MonthsDropdown, { onChange: handleMonthChange, displayMonth: props2.displayMonth }), - bn.createElement(YearsDropdown, { onChange: handleMonthChange, displayMonth: props2.displayMonth }) + { 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 bn.createElement( + return Cn.createElement( "svg", __assign2({ width: "16px", height: "16px", viewBox: "0 0 120 120" }, props2), - bn.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" }) + 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 bn.createElement( + return Cn.createElement( "svg", __assign2({ width: "16px", height: "16px", viewBox: "0 0 120 120" }, props2), - bn.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" }) + 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(), classNames8 = _a2.classNames, styles = _a2.styles; - var classNamesArr = [classNames8.button_reset, classNames8.button]; + var _a2 = useDayPicker(), classNames9 = _a2.classNames, styles = _a2.styles; + var classNamesArr = [classNames9.button_reset, classNames9.button]; if (props2.className) { classNamesArr.push(props2.className); } @@ -25984,38 +27278,37 @@ var Button = k3(function(props2, ref) { if (props2.style) { Object.assign(style, props2.style); } - return bn.createElement("button", __assign2({}, props2, { ref, type: "button", className, style })); + return Cn.createElement("button", __assign2({}, props2, { ref, type: "button", className, style })); }); function Navigation(props2) { var _a2, _b2; - var _c2 = useDayPicker(), dir = _c2.dir, locale2 = _c2.locale, classNames8 = _c2.classNames, styles = _c2.styles, _d2 = _c2.labels, labelPrevious2 = _d2.labelPrevious, labelNext2 = _d2.labelNext, components = _c2.components; + 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 bn.createElement(bn.Fragment, null); + return Cn.createElement(Cn.Fragment, null); } var previousLabel = labelPrevious2(props2.previousMonth, { locale: locale2 }); var previousClassName = [ - classNames8.nav_button, - classNames8.nav_button_previous + classNames9.nav_button, + classNames9.nav_button_previous ].join(" "); var nextLabel = labelNext2(props2.nextMonth, { locale: locale2 }); var nextClassName = [ - classNames8.nav_button, - classNames8.nav_button_next + 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 bn.createElement( + return Cn.createElement( "div", - { className: classNames8.nav, style: styles.nav }, - !props2.hidePrevious && bn.createElement(Button, { name: "previous-month", "aria-label": previousLabel, className: previousClassName, style: styles.nav_button_previous, disabled: !props2.previousMonth, onClick: props2.onPreviousClick }, dir === "rtl" ? bn.createElement(IconRightComponent, { className: classNames8.nav_icon, style: styles.nav_icon }) : bn.createElement(IconLeftComponent, { className: classNames8.nav_icon, style: styles.nav_icon })), - !props2.hideNext && bn.createElement(Button, { name: "next-month", "aria-label": nextLabel, className: nextClassName, style: styles.nav_button_next, disabled: !props2.nextMonth, onClick: props2.onNextClick }, dir === "rtl" ? bn.createElement(IconLeftComponent, { className: classNames8.nav_icon, style: styles.nav_icon }) : bn.createElement(IconRightComponent, { className: classNames8.nav_icon, style: styles.nav_icon })) + { 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 })) ); } function CaptionNavigation(props2) { var _a2; - var _b2; - var _c2 = useDayPicker(), numberOfMonths = _c2.numberOfMonths, dir = _c2.dir, components = _c2.components; - var _d2 = useNavigation(), previousMonth = _d2.previousMonth, nextMonth = _d2.nextMonth, goToMonth = _d2.goToMonth, displayMonths = _d2.displayMonths; + 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); }); @@ -26036,40 +27329,45 @@ function CaptionNavigation(props2) { return; goToMonth(nextMonth); }; - var CaptionLabelComponent = (_b2 = components === null || components === void 0 ? void 0 : components.CaptionLabel) !== null && _b2 !== void 0 ? _b2 : CaptionLabel; - var captionLabel = bn.createElement(CaptionLabelComponent, { id: props2.id, displayMonth: props2.displayMonth }); - return bn.createElement( - bn.Fragment, - null, - captionLabel, - bn.createElement(Navigation, { displayMonth: props2.displayMonth, hideNext, hidePrevious, nextMonth, previousMonth, onPreviousClick: handlePreviousClick, onNextClick: handleNextClick }) - ); + return Cn.createElement(Navigation, { displayMonth: props2.displayMonth, hideNext, hidePrevious, nextMonth, previousMonth, onPreviousClick: handlePreviousClick, onNextClick: handleNextClick }); } function Caption(props2) { var _a2; - var _b2 = useDayPicker(), classNames8 = _b2.classNames, disableNavigation = _b2.disableNavigation, styles = _b2.styles, captionLayout = _b2.captionLayout, components = _b2.components; + 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 = bn.createElement(CaptionLabelComponent, { id: props2.id, displayMonth: props2.displayMonth }); + caption = Cn.createElement(CaptionLabelComponent, { id: props2.id, displayMonth: props2.displayMonth }); } else if (captionLayout === "dropdown") { - caption = bn.createElement(CaptionDropdowns, { displayMonth: props2.displayMonth, id: props2.id }); + 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 = bn.createElement(CaptionNavigation, { displayMonth: props2.displayMonth, id: props2.id }); + 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 bn.createElement("div", { className: classNames8.caption, style: styles.caption }, caption); + return Cn.createElement("div", { className: classNames9.caption, style: styles.caption }, caption); } -function Footer() { +function Footer(props2) { var _a2 = useDayPicker(), footer = _a2.footer, styles = _a2.styles, tfoot = _a2.classNames.tfoot; if (!footer) - return bn.createElement(bn.Fragment, null); - return bn.createElement( + return Cn.createElement(Cn.Fragment, null); + return Cn.createElement( "tfoot", { className: tfoot, style: styles.tfoot }, - bn.createElement( + Cn.createElement( "tr", null, - bn.createElement("td", { colSpan: 8 }, footer) + Cn.createElement("td", { colSpan: 8 }, footer) ) ); } @@ -26083,37 +27381,32 @@ function getWeekdays(locale2, weekStartsOn, ISOWeek) { return days; } function HeadRow() { - var _a2 = useDayPicker(), classNames8 = _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 _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 bn.createElement( + return Cn.createElement( "tr", - { style: styles.head_row, className: classNames8.head_row }, - showWeekNumber && bn.createElement("th", { scope: "col", style: styles.head_cell, className: classNames8.head_cell }), + { 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 bn.createElement( - "th", - { key: i4, scope: "col", className: classNames8.head_cell, style: styles.head_cell }, - bn.createElement("span", { "aria-hidden": true }, formatWeekdayName2(weekday, { locale: locale2 })), - bn.createElement("span", { className: classNames8.vhidden }, labelWeekday2(weekday, { locale: locale2 })) - ); + 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 Head() { var _a2; - var _b2 = useDayPicker(), classNames8 = _b2.classNames, styles = _b2.styles, components = _b2.components; + 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 bn.createElement( + return Cn.createElement( "thead", - { style: styles.head, className: classNames8.head }, - bn.createElement(HeadRowComponent, null) + { style: styles.head, className: classNames9.head }, + Cn.createElement(HeadRowComponent, null) ); } function DayContent(props2) { var _a2 = useDayPicker(), locale2 = _a2.locale, formatDay2 = _a2.formatters.formatDay; - return bn.createElement(bn.Fragment, null, formatDay2(props2.date, { locale: locale2 })); + return Cn.createElement(Cn.Fragment, null, formatDay2(props2.date, { locale: locale2 })); } -var SelectMultipleContext = B(void 0); +var SelectMultipleContext = F(void 0); function SelectMultipleProvider(props2) { if (!isDayPickerMultiple(props2.initialProps)) { var emptyContextValue = { @@ -26122,9 +27415,9 @@ function SelectMultipleProvider(props2) { disabled: [] } }; - return bn.createElement(SelectMultipleContext.Provider, { value: emptyContextValue }, props2.children); + return Cn.createElement(SelectMultipleContext.Provider, { value: emptyContextValue }, props2.children); } - return bn.createElement(SelectMultipleProviderInternal, { initialProps: props2.initialProps, children: props2.children }); + return Cn.createElement(SelectMultipleProviderInternal, { initialProps: props2.initialProps, children: props2.children }); } function SelectMultipleProviderInternal(_a2) { var initialProps = _a2.initialProps, children = _a2.children; @@ -26168,7 +27461,7 @@ function SelectMultipleProviderInternal(_a2) { onDayClick, modifiers }; - return bn.createElement(SelectMultipleContext.Provider, { value: contextValue }, children); + return Cn.createElement(SelectMultipleContext.Provider, { value: contextValue }, children); } function useSelectMultiple() { var context = q2(SelectMultipleContext); @@ -26200,12 +27493,12 @@ function addToRange(day, range) { if (isSameDay(from, day)) { return void 0; } - if (isAfter(from, day)) { + if (isAfter2(from, day)) { return { from: day, to }; } return { from, to: day }; } -var SelectRangeContext = B(void 0); +var SelectRangeContext = F(void 0); function SelectRangeProvider(props2) { if (!isDayPickerRange(props2.initialProps)) { var emptyContextValue = { @@ -26217,9 +27510,9 @@ function SelectRangeProvider(props2) { disabled: [] } }; - return bn.createElement(SelectRangeContext.Provider, { value: emptyContextValue }, props2.children); + return Cn.createElement(SelectRangeContext.Provider, { value: emptyContextValue }, props2.children); } - return bn.createElement(SelectRangeProviderInternal, { initialProps: props2.initialProps, children: props2.children }); + return Cn.createElement(SelectRangeProviderInternal, { initialProps: props2.initialProps, children: props2.children }); } function SelectRangeProviderInternal(_a2) { var initialProps = _a2.initialProps, children = _a2.children; @@ -26289,7 +27582,7 @@ function SelectRangeProviderInternal(_a2) { }); } } - return bn.createElement(SelectRangeContext.Provider, { value: { selected, onDayClick, modifiers } }, children); + return Cn.createElement(SelectRangeContext.Provider, { value: { selected, onDayClick, modifiers } }, children); } function useSelectRange() { var context = q2(SelectRangeContext); @@ -26353,7 +27646,7 @@ function getInternalModifiers(dayPicker, selectMultiple, selectRange2) { } return internalModifiers; } -var ModifiersContext = B(void 0); +var ModifiersContext = F(void 0); function ModifiersProvider(props2) { var dayPicker = useDayPicker(); var selectMultiple = useSelectMultiple(); @@ -26361,7 +27654,7 @@ function ModifiersProvider(props2) { var internalModifiers = getInternalModifiers(dayPicker, selectMultiple, selectRange2); var customModifiers = getCustomModifiers(dayPicker.modifiers); var modifiers = __assign2(__assign2({}, internalModifiers), customModifiers); - return bn.createElement(ModifiersContext.Provider, { value: modifiers }, props2.children); + return Cn.createElement(ModifiersContext.Provider, { value: modifiers }, props2.children); } function useModifiers() { var context = q2(ModifiersContext); @@ -26432,7 +27725,7 @@ function isMatch(day, matchers) { var diffAfter = differenceInCalendarDays(matcher.after, day); var isDayBefore = diffBefore > 0; var isDayAfter = diffAfter < 0; - var isClosedInterval = isAfter(matcher.before, matcher.after); + var isClosedInterval = isAfter2(matcher.before, matcher.after); if (isClosedInterval) { return isDayAfter && isDayBefore; } else { @@ -26540,12 +27833,12 @@ function getNextFocus(focusedDay, options) { }); } } -var FocusContext = B(void 0); +var FocusContext = F(void 0); function FocusProvider(props2) { var navigation = useNavigation(); var modifiers = useModifiers(); - var _a2 = p2(), focusedDay = _a2[0], setFocusedDay = _a2[1]; - var _b2 = p2(), lastFocused = _b2[0], setLastFocused = _b2[1]; + 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() { @@ -26606,7 +27899,7 @@ function FocusProvider(props2) { return moveFocus("endOfWeek", "after"); } }; - return bn.createElement(FocusContext.Provider, { value }, props2.children); + return Cn.createElement(FocusContext.Provider, { value }, props2.children); } function useFocusContext() { var context = q2(FocusContext); @@ -26620,15 +27913,15 @@ function useActiveModifiers(day, displayMonth) { var activeModifiers = getActiveModifiers(day, modifiers, displayMonth); return activeModifiers; } -var SelectSingleContext = B(void 0); +var SelectSingleContext = F(void 0); function SelectSingleProvider(props2) { if (!isDayPickerSingle(props2.initialProps)) { var emptyContextValue = { selected: void 0 }; - return bn.createElement(SelectSingleContext.Provider, { value: emptyContextValue }, props2.children); + return Cn.createElement(SelectSingleContext.Provider, { value: emptyContextValue }, props2.children); } - return bn.createElement(SelectSingleProviderInternal, { initialProps: props2.initialProps, children: props2.children }); + return Cn.createElement(SelectSingleProviderInternal, { initialProps: props2.initialProps, children: props2.children }); } function SelectSingleProviderInternal(_a2) { var initialProps = _a2.initialProps, children = _a2.children; @@ -26645,7 +27938,7 @@ function SelectSingleProviderInternal(_a2) { selected: initialProps.selected, onDayClick }; - return bn.createElement(SelectSingleContext.Provider, { value: contextValue }, children); + return Cn.createElement(SelectSingleContext.Provider, { value: contextValue }, children); } function useSelectSingle() { var context = q2(SelectSingleContext); @@ -26793,19 +28086,19 @@ function isInternalModifier(modifier) { return Object.values(InternalModifier).includes(modifier); } function getDayClassNames(dayPicker, activeModifiers) { - var classNames8 = [dayPicker.classNames.day]; + var classNames9 = [dayPicker.classNames.day]; Object.keys(activeModifiers).forEach(function(modifier) { var customClassName = dayPicker.modifiersClassNames[modifier]; if (customClassName) { - classNames8.push(customClassName); + classNames9.push(customClassName); } else if (isInternalModifier(modifier)) { var internalClassName = dayPicker.classNames["day_".concat(modifier)]; if (internalClassName) { - classNames8.push(internalClassName); + classNames9.push(internalClassName); } } }); - return classNames8; + return classNames9; } function getDayStyle(dayPicker, activeModifiers) { var style = __assign2({}, dayPicker.styles.day); @@ -26824,7 +28117,7 @@ function useDayRender(day, displayMonth, buttonRef) { var eventHandlers = useDayEventHandlers(day, activeModifiers); var selectedDays = useSelectedDays(); var isButton = Boolean(dayPicker.onDayClick || dayPicker.mode !== "default"); - h2(function() { + p2(function() { var _a3; if (activeModifiers.outside) return; @@ -26844,21 +28137,18 @@ function useDayRender(day, displayMonth, buttonRef) { ]); var className = getDayClassNames(dayPicker, activeModifiers).join(" "); var style = getDayStyle(dayPicker, activeModifiers); - var ariaLabel = dayPicker.labels.labelDay(day, activeModifiers, { - locale: dayPicker.locale - }); 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 = bn.createElement(DayContentComponent, { date: day, displayMonth, activeModifiers }); + var children = Cn.createElement(DayContentComponent, { date: day, displayMonth, activeModifiers }); var divProps = { style, className, children, - "aria-label": ariaLabel + role: "gridcell" }; var isFocusTarget = focusContext.focusTarget && isSameDay(focusContext.focusTarget, day) && !activeModifiers.outside; var isFocused = focusContext.focusedDay && isSameDay(focusContext.focusedDay, day); - var buttonProps = __assign2(__assign2(__assign2({}, divProps), (_a2 = { disabled: activeModifiers.disabled }, _a2["aria-pressed"] = activeModifiers.selected, _a2["aria-label"] = ariaLabel, _a2.tabIndex = isFocused || isFocusTarget ? 0 : -1, _a2)), eventHandlers); + var buttonProps = __assign2(__assign2(__assign2({}, divProps), (_a2 = { disabled: activeModifiers.disabled, role: "gridcell" }, _a2["aria-selected"] = activeModifiers.selected, _a2.tabIndex = isFocused || isFocusTarget ? 0 : -1, _a2)), eventHandlers); var dayRender = { isButton, isHidden, @@ -26873,48 +28163,48 @@ function Day(props2) { var buttonRef = _2(null); var dayRender = useDayRender(props2.date, props2.displayMonth, buttonRef); if (dayRender.isHidden) { - return bn.createElement(bn.Fragment, null); + return Cn.createElement("div", { role: "gridcell" }); } if (!dayRender.isButton) { - return bn.createElement("div", __assign2({}, dayRender.divProps)); + return Cn.createElement("div", __assign2({}, dayRender.divProps)); } - return bn.createElement(Button, __assign2({ name: "day", ref: buttonRef }, dayRender.buttonProps)); + return Cn.createElement(Button, __assign2({ 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, classNames8 = _a2.classNames, locale2 = _a2.locale, labelWeekNumber2 = _a2.labels.labelWeekNumber, formatWeekNumber2 = _a2.formatters.formatWeekNumber; + 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 bn.createElement("span", { className: classNames8.weeknumber, style: styles.weeknumber }, content); + return Cn.createElement("span", { className: classNames9.weeknumber, style: styles.weeknumber }, content); } var label = labelWeekNumber2(Number(weekNumber), { locale: locale2 }); var handleClick = function(e4) { onWeekNumberClick(weekNumber, dates, e4); }; - return bn.createElement(Button, { name: "week-number", "aria-label": label, className: classNames8.weeknumber, style: styles.weeknumber, onClick: handleClick }, content); + 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, classNames8 = _c2.classNames, showWeekNumber = _c2.showWeekNumber, components = _c2.components; + 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 = bn.createElement( + weekNumberCell = Cn.createElement( "td", - { className: classNames8.cell, style: styles.cell }, - bn.createElement(WeeknumberComponent, { number: props2.weekNumber, dates: props2.dates }) + { className: classNames9.cell, style: styles.cell }, + Cn.createElement(WeeknumberComponent, { number: props2.weekNumber, dates: props2.dates }) ); } - return bn.createElement( + return Cn.createElement( "tr", - { className: classNames8.row, style: styles.row }, + { className: classNames9.row, style: styles.row }, weekNumberCell, props2.dates.map(function(date) { - return bn.createElement( + return Cn.createElement( "td", - { className: classNames8.cell, style: styles.cell, key: getUnixTime(date) }, - bn.createElement(DayComponent, { displayMonth: props2.displayMonth, date }) + { className: classNames9.cell, style: styles.cell, key: getUnixTime(date), role: "presentation" }, + Cn.createElement(DayComponent, { displayMonth: props2.displayMonth, date }) ); }) ); @@ -26960,7 +28250,7 @@ function getMonthWeeks(month, options) { } function Table(props2) { var _a2, _b2, _c2; - var _d2 = useDayPicker(), locale2 = _d2.locale, classNames8 = _d2.classNames, styles = _d2.styles, hideHead = _d2.hideHead, fixedWeeks = _d2.fixedWeeks, components = _d2.components, weekStartsOn = _d2.weekStartsOn, firstWeekContainsDate = _d2.firstWeekContainsDate, ISOWeek = _d2.ISOWeek; + 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, @@ -26971,20 +28261,20 @@ function Table(props2) { 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 bn.createElement( + return Cn.createElement( "table", - { className: classNames8.table, style: styles.table, role: "grid", "aria-labelledby": props2["aria-labelledby"] }, - !hideHead && bn.createElement(HeadComponent, null), - bn.createElement("tbody", { className: classNames8.tbody, style: styles.tbody }, weeks.map(function(week) { - return bn.createElement(RowComponent, { displayMonth: props2.displayMonth, key: week.weekNumber, dates: week.dates, weekNumber: week.weekNumber }); + { 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 }); })), - bn.createElement(FooterComponent, null) + Cn.createElement(FooterComponent, { displayMonth: props2.displayMonth }) ); } function canUseDOM2() { return !!(typeof window !== "undefined" && window.document && window.document.createElement); } -var useIsomorphicLayoutEffect2 = canUseDOM2() ? s2 : h2; +var useIsomorphicLayoutEffect2 = canUseDOM2() ? y2 : p2; var serverHandoffComplete = false; var id = 0; function genId2() { @@ -26993,13 +28283,13 @@ function genId2() { function useId(providedId) { var _a2; var initialId = providedId !== null && providedId !== void 0 ? providedId : serverHandoffComplete ? genId2() : null; - var _b2 = p2(initialId), id2 = _b2[0], setId = _b2[1]; + var _b2 = h2(initialId), id2 = _b2[0], setId = _b2[1]; useIsomorphicLayoutEffect2(function() { if (id2 === null) { setId(genId2()); } }, []); - h2(function() { + p2(function() { if (serverHandoffComplete === false) { serverHandoffComplete = true; } @@ -27010,10 +28300,10 @@ function Month(props2) { var _a2; var _b2; var dayPicker = useDayPicker(); - var dir = dayPicker.dir, classNames8 = dayPicker.classNames, styles = dayPicker.styles, components = dayPicker.components; + 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 = [classNames8.month]; + var className = [classNames9.month]; var style = styles.month; var isStart = props2.displayIndex === 0; var isEnd = props2.displayIndex === displayMonths.length - 1; @@ -27022,31 +28312,31 @@ function Month(props2) { _a2 = [isStart, isEnd], isEnd = _a2[0], isStart = _a2[1]; } if (isStart) { - className.push(classNames8.caption_start); + className.push(classNames9.caption_start); style = __assign2(__assign2({}, style), styles.caption_start); } if (isEnd) { - className.push(classNames8.caption_end); + className.push(classNames9.caption_end); style = __assign2(__assign2({}, style), styles.caption_end); } if (isCenter) { - className.push(classNames8.caption_between); + className.push(classNames9.caption_between); style = __assign2(__assign2({}, style), styles.caption_between); } var CaptionComponent = (_b2 = components === null || components === void 0 ? void 0 : components.Caption) !== null && _b2 !== void 0 ? _b2 : Caption; - return bn.createElement( + return Cn.createElement( "div", { key: props2.displayIndex, className: className.join(" "), style }, - bn.createElement(CaptionComponent, { id: captionId, displayMonth: props2.displayMonth }), - bn.createElement(Table, { "aria-labelledby": captionId, displayMonth: props2.displayMonth }) + 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 = p2(false), hasInitialFocus = _a2[0], setHasInitialFocus = _a2[1]; - h2(function() { + var _a2 = h2(false), hasInitialFocus = _a2[0], setHasInitialFocus = _a2[1]; + p2(function() { if (!dayPicker.initialFocus) return; if (!focusContext.focusTarget) @@ -27062,43 +28352,43 @@ function Root() { focusContext.focusTarget, focusContext ]); - var classNames8 = [dayPicker.classNames.root, dayPicker.className]; + var classNames9 = [dayPicker.classNames.root, dayPicker.className]; if (dayPicker.numberOfMonths > 1) { - classNames8.push(dayPicker.classNames.multiple_months); + classNames9.push(dayPicker.classNames.multiple_months); } if (dayPicker.showWeekNumber) { - classNames8.push(dayPicker.classNames.with_weeknumber); + classNames9.push(dayPicker.classNames.with_weeknumber); } var style = __assign2(__assign2({}, dayPicker.styles.root), dayPicker.style); - return bn.createElement( + return Cn.createElement( "div", - { className: classNames8.join(" "), style, dir: dayPicker.dir }, - bn.createElement("div", { className: dayPicker.classNames.months, style: dayPicker.styles.months }, navigation.displayMonths.map(function(month, i4) { - return bn.createElement(Month, { key: i4, displayIndex: i4, displayMonth: month }); + { 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 = __rest2(props2, ["children"]); - return bn.createElement( + return Cn.createElement( DayPickerProvider, { initialProps }, - bn.createElement( + Cn.createElement( NavigationProvider, null, - bn.createElement( + Cn.createElement( SelectSingleProvider, { initialProps }, - bn.createElement( + Cn.createElement( SelectMultipleProvider, { initialProps }, - bn.createElement( + Cn.createElement( SelectRangeProvider, { initialProps }, - bn.createElement( + Cn.createElement( ModifiersProvider, null, - bn.createElement(FocusProvider, null, children) + Cn.createElement(FocusProvider, null, children) ) ) ) @@ -27107,16 +28397,16 @@ function RootProvider(props2) { ); } function DayPicker(props2) { - return bn.createElement( + return Cn.createElement( RootProvider, __assign2({}, props2), - bn.createElement(Root, null) + Cn.createElement(Root, null) ); } // src/components/ui/menus/datePickerMenu.tsx var showDatePickerMenu = (point, value, setValue, format2) => { - const menu = new import_obsidian10.Menu(); + const menu = new import_obsidian9.Menu(); menu.dom.toggleClass("mk-menu", true); menu.setUseNativeMenu(false); const frag = document.createDocumentFragment(); @@ -27138,7 +28428,7 @@ var showDatePickerMenu = (point, value, setValue, format2) => { }; const root = createRoot(div); root.render( - /* @__PURE__ */ bn.createElement(bn.Fragment, null, /* @__PURE__ */ bn.createElement(DayPicker, { + /* @__PURE__ */ Cn.createElement(Cn.Fragment, null, /* @__PURE__ */ Cn.createElement(DayPicker, { defaultMonth: value, mode: "single", selected: value, @@ -27170,11 +28460,11 @@ var showDatePickerMenu = (point, value, setValue, format2) => { // src/components/ContextView/DataTypeView/DateCell.tsx var DateCell = (props2) => { var _a2; - const [value, setValue] = p2(props2.initialValue); - h2(() => { + const [value, setValue] = h2(props2.initialValue); + p2(() => { setValue(props2.initialValue); }, [props2.initialValue]); - const date = F(() => { + const date = F2(() => { const dateTime = Date.parse(value); return dateTime > 0 ? new Date(dateTime + new Date().getTimezoneOffset() * 60 * 1e3) : null; }, [value]); @@ -27186,7 +28476,7 @@ var DateCell = (props2) => { }; const menuRef = _2(null); const ref = _2(null); - h2(() => { + p2(() => { if (props2.editMode == 2 /* EditModeActive */) { if (ref.current) { showPicker(); @@ -27216,10 +28506,10 @@ var DateCell = (props2) => { menuRef.current.hide(); } }; - return /* @__PURE__ */ bn.createElement("div", { + return /* @__PURE__ */ Cn.createElement("div", { className: "mk-cell-date", onClick: (e4) => !value && showPicker(e4) - }, props2.editMode == 2 ? /* @__PURE__ */ bn.createElement("input", { + }, props2.editMode == 2 ? /* @__PURE__ */ Cn.createElement("input", { onClick: (e4) => e4.stopPropagation(), className: "mk-cell-text", ref, @@ -27228,7 +28518,7 @@ var DateCell = (props2) => { onChange: (e4) => setValue(e4.target.value), onMouseDown: () => showPicker(), onKeyDown - }) : /* @__PURE__ */ bn.createElement("div", { + }) : /* @__PURE__ */ Cn.createElement("div", { className: "mk-cell-date-value", onClick: (e4) => showPicker(e4) }, date ? format( @@ -32626,203 +33916,2204 @@ var emojis = { n: ["wales flag", "flag-wales"], u: "1f3f4-e0067-e0062-e0077-e006c-e0073-e007f" } - ] + ] +}; + +// src/components/ui/modals/stickerModal.tsx +var import_obsidian10 = require("obsidian"); +var stickerModal = class extends import_obsidian10.FuzzySuggestModal { + constructor(app2, setIcon) { + super(app2); + this.setIcon = setIcon; + this.resultContainerEl.toggleClass("mk-sticker-modal", true); + this.inputEl.focus(); + this.emptyStateText = i18n_default.labels.findStickers; + this.limit = 0; + } + renderSuggestion(item, el) { + el.innerHTML = stickerFromString(item.item.unicode); + el.setAttr("aria-label", item.item.label); + } + getItemText(item) { + return item.label + item.desc; + } + getItems() { + const allEmojis = Object.keys(emojis).reduce( + (p3, c4) => [ + ...p3, + ...emojis[c4].map((e4) => ({ + label: e4.n[0], + desc: e4.n[1], + variants: e4.v, + unicode: e4.u + })) + ], + [] + ); + return allEmojis; + } + onChooseItem(item, evt) { + this.setIcon(item.unicode); + } +}; + +// src/hooks/useLongPress.tsx +function isMouseEvent(e4) { + return e4 && "screenX" in e4; +} + +// src/components/FileSticker/FileSticker.tsx +var import_obsidian13 = require("obsidian"); + +// src/components/ui/modals/vaultChangeModals.ts +var import_obsidian11 = require("obsidian"); +var VaultChangeModal = class extends import_obsidian11.Modal { + constructor(plugin, file, action, space) { + super(plugin.app); + this.file = file; + this.action = action; + this.plugin = plugin; + this.space = space; + } + onOpen() { + let { contentEl } = this; + let 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") { + 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") { + 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_obsidian11.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() { + let { contentEl } = this; + contentEl.empty(); + } +}; +var MoveSuggestionModal = class extends import_obsidian11.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); + } + }); + } +}; +function getAllFoldersInVault(app2) { + let folders = []; + let rootFolder = app2.vault.getRoot(); + folders.push(rootFolder); + function recursiveFx(folder) { + for (let child of folder.children) { + if (child instanceof import_obsidian11.TFolder) { + let childFolder = child; + folders.push(childFolder); + if (childFolder.children) + recursiveFx(childFolder); + } + } + } + recursiveFx(rootFolder); + return folders; +} +var AddToSpaceModal = class extends import_obsidian11.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.files.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_obsidian11.FuzzySuggestModal { + constructor(plugin, file) { + super(app); + this.plugin = plugin; + this.file = this.plugin.index.files.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/utils/spaces/spaces.ts +var import_lodash6 = __toESM(require_lodash()); +var import_obsidian12 = 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_lodash5 = __toESM(require_lodash()); + +// src/types/space.ts +var FMBannerKey = "banner"; +var FMAliasKey = "alias"; +var FMStickerKey = "sticker"; +var FMColorKey = "color"; +var FMMetadataKeys = [FMBannerKey, FMAliasKey, FMStickerKey, FMColorKey]; + +// 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", + rank: cache.rank + }; +}; +var parseSpaceCache = (space, spaceItems) => { + return { + name: space.name, + space, + spaceItems + }; +}; + +// src/utils/spaces/spaces.ts +var rebuildIndex = async (plugin, save) => { + var _a2, _b2; + console.time("Make.md Vault Index"); + const newTables = indexCurrentFileTree((_a2 = plugin.index.vaultDBCache) != null ? _a2 : [], (_b2 = plugin.index.spacesItemsDBCache) != null ? _b2 : []); + if (save && (!import_lodash6.default.isEqual(newTables.vault.rows, plugin.index.vaultDBCache) || !import_lodash6.default.isEqual(newTables.spaceItems.rows, plugin.index.spacesItemsDBCache))) { + plugin.index.saveSpacesDB(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) => { + let 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; + let 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) => { + if (!path) + return null; + return plugin.index.vaultDBCache.find((f4) => f4.path == path); +}; +var saveFileSticker = (plugin, path, sticker) => { + if (plugin.settings.spacesEnabled) { + const newVaultDB = plugin.index.vaultDBCache.map((f4) => f4.path == path ? { ...f4, sticker } : f4); + plugin.index.saveSpacesDB({ vault: { ...vaultSchema, rows: newVaultDB } }); + } + saveFrontmatterValue( + plugin, + path, + FMStickerKey, + sticker, + "text", + true + ); + plugin.index.reloadFile(getAbstractFileAtPath(app, path)).then((f4) => plugin.index.broadcast("space")); +}; +var saveFolderSort = (plugin, path, sort) => { + if (plugin.settings.spacesEnabled) { + const newVaultDB = plugin.index.vaultDBCache.map((f4) => f4.path == path ? { ...f4, folder: sort } : f4); + plugin.index.saveSpacesDB({ vault: { ...vaultSchema, rows: newVaultDB } }); + plugin.index.reloadFile(getAbstractFileAtPath(app, path)).then((f4) => plugin.index.broadcast("vault")); + } +}; +var saveFileColor = (plugin, path, color) => { + if (plugin.settings.spacesEnabled) { + const newVaultDB = plugin.index.vaultDBCache.map((f4) => f4.path == path ? { ...f4, color } : f4); + plugin.index.saveSpacesDB({ vault: { ...vaultSchema, rows: newVaultDB } }); + } + saveFrontmatterValue( + plugin, + path, + FMColorKey, + color, + "text", + true + ); + plugin.index.reloadFile(getAbstractFileAtPath(app, path)).then((f4) => plugin.index.broadcast("space")); +}; +var saveSpaceSticker = (plugin, name, sticker) => { + const newSpaceDB = plugin.index.spacesDBCache.map((f4) => f4.name == name ? { ...f4, sticker } : f4); + plugin.index.saveSpacesDB({ 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; + }); + plugin.index.saveSpacesDB({ vault: { ...vaultSchema, rows: newVaultDB } }); + let promises = newItems.map((f4) => plugin.index.files.set(f4.path, { ...plugin.index.files.get(f4.path), rank: f4.rank })); + 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() + }; + 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, index2) => ({ ...f4, rank: index2.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; + }); + plugin.index.saveSpacesDB({ vault: { ...vaultSchema, rows: newVaultTable } }); + const afile = getAbstractFileAtPath(app, item.path); + await moveFile(getAbstractFileAtPath(app, newParent), afile); + let promises = rows.map((f4) => plugin.index.files.set(f4.path, { ...plugin.index.files.get(f4.path), rank: f4.rank })); + await Promise.all(promises); + plugin.index.broadcast("space"); +}; +var insertSpaceAtIndex = (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; + }); + plugin.index.saveSpacesDB({ 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.spacesCache.get(spaceName)) == null ? void 0 : _a2.space; + if (!space) + return; + let 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; + }); + plugin.index.saveSpacesDB({ spaceItems: { ...spaceItemsSchema, rows: newSpaceItemsRows } }); + await plugin.index.reloadSpace(space.name); + let promises = newSpaceItemsRows.map((f4) => plugin.index.reloadFile(getAbstractFileAtPath(app, f4.path))); + await Promise.all(promises); + plugin.index.broadcast("vault"); +}; +var saveSpace = (plugin, space, newSpace) => { + const newSpaceRows = plugin.index.spacesDBCache.map((f4) => f4.name == space ? serializeSpace(newSpace) : f4); + let newSpaceItemsRows = plugin.index.spacesItemsDBCache.map((f4) => f4.space == space ? { ...f4, space: newSpace.name } : f4); + plugin.index.saveSpacesDB({ 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); + } + plugin.index.reloadSpace(space); + plugin.index.initalizeFiles(); +}; +var removeSpace = (plugin, space) => { + const newSpaceRows = plugin.index.spacesDBCache.filter((f4) => f4.name != space); + const newSpaceItemsRows = plugin.index.spacesItemsDBCache.filter((f4) => f4.space != space); + plugin.index.saveSpacesDB({ 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.spacesCache.get(spaceName)) == null ? void 0 : _a2.space; + if (space) + saveSpace(plugin, spaceName, { + ...space, + sort: JSON.stringify(sort) + }); +}; +var toggleSpacePin = (plugin, spaceName, type) => { + var _a2; + const space = (_a2 = plugin.index.spacesCache.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 }))]; + plugin.index.saveSpacesDB({ spaceItems: { ...spaceItemsSchema, rows: newSpaceItemsRows } }); + await plugin.index.reloadSpace(space); + let 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))); + plugin.index.saveSpacesDB({ spaceItems: { ...spaceItemsSchema, rows: newSpaceItemsRows } }); + await plugin.index.reloadSpace(space); + let promises = paths.map((f4) => plugin.index.reloadFile(getAbstractFileAtPath(app, f4))); + await Promise.all(promises); + plugin.index.broadcast("vault"); +}; +var retrieveSpaceItems = (plugin, spaces2) => { + let retrievedSpaces = {}; + spaces2.forEach((space) => { + let 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) => { + let retrievedFolders = {}; + paths.forEach((folder) => { + let files = []; + for (let k5 of plugin.index.files.values()) { + if (k5.parent == folder) + files.push(k5); + } + retrievedFolders[folder] = files.filter( + excludeVaultItemPredicate(plugin.settings) + ).map((f4) => plugin.index.files.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 = (vaultDB, spaceItemsDB) => { + let treeItems = []; + import_obsidian12.Vault.recurseChildren(app.vault.getRoot(), (file) => { + var _a2; + if (file.path != "/") + treeItems.push({ + path: file.path, + parent: (_a2 = file.parent) == null ? void 0 : _a2.path, + created: file instanceof import_obsidian12.TFile ? file.stat.ctime.toString() : void 0, + folder: file instanceof import_obsidian12.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 newFolderInVault = (plugin, activeFile2) => { + let vaultChangeModal = new VaultChangeModal( + plugin, + plugin.app.vault.getRoot(), + "create folder", + "/" + ); + vaultChangeModal.open(); +}; +var newFileInVault = async (plugin, activeFile2, canvas) => { + let newFile; + if (canvas) { + newFile = await createNewCanvasFile(plugin, plugin.app.vault.getRoot(), ""); + } else { + newFile = await createNewMarkdownFile( + plugin, + plugin.app.vault.getRoot(), + "" + ); + } +}; +var newFolderInSpace = (plugin, space, activeFile2) => { + let 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]); +}; + +// src/utils/emoji.ts +var saveFileIcons = (plugin, files, icon) => { + files.forEach((file) => { + saveFileSticker(plugin, file, icon); + }); +}; +var saveFileColors = (plugin, files, icon) => { + files.forEach((file) => { + saveFileColor(plugin, file, icon); + }); +}; +var saveSpaceIcon = (plugin, space, icon) => { + saveSpaceSticker(plugin, space, icon); +}; +var removeSpaceIcon = (plugin, space) => { + saveSpaceSticker(plugin, space, ""); +}; +var saveFileIcon = (plugin, data, icon) => { + saveFileSticker(plugin, data.path, icon); +}; +var removeFileIcons = (plugin, files) => { + files.forEach((file) => { + saveFileSticker(plugin, file, ""); + }); +}; +var removeFileIcon = (plugin, data) => { + saveFileSticker(plugin, data.path, ""); +}; + +// src/components/FileSticker/FileSticker.tsx +var FileSticker = (props2) => { + const { fileCache } = props2; + const triggerStickerContextMenu = (e4) => { + if (!fileCache) + return; + e4.preventDefault(); + const fileMenu = new import_obsidian13.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, + (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(); + let vaultChangeModal = new stickerModal( + props2.plugin.app, + (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: (fileCache == null ? void 0 : fileCache.color.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) } : { + __html: defaultIconForExtension( + fileCache == null ? void 0 : fileCache.extension, + (fileCache == null ? void 0 : fileCache.color) ? true : false + ) + }, + onClick: (e4) => triggerStickerMenu(e4) + })); +}; + +// src/components/ContextView/ContextBuilder/BuilderMetadataFields.tsx +var import_obsidian14 = 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); + } + 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_obsidian14.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"] + } + })))); +}; + +// src/components/Spaces/SpaceEditor.tsx +var import_obsidian22 = require("obsidian"); + +// src/types/metadata.ts +var fileProps = { + "name": { + label: "File Name", + field: "name", + vType: "text", + type: "fileprop" + }, + "path": { + label: "Path", + field: "path", + vType: "text", + type: "fileprop" + }, + "parent": { + label: "Folder", + field: "parent", + vType: "text", + type: "fileprop" + }, + "sticker": { + label: "Sticker", + field: "sticker", + vType: "text", + type: "fileprop" + }, + "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 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" + } +}; + +// src/utils/contexts/predicate/filterFns/filterFnLabels.ts +var filterFnLabels = { + isEmpty: "is empty", + isNotEmpty: "is not empty", + 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/ui/menus/newPropertyMenu.tsx +var import_obsidian15 = require("obsidian"); +var NewPropertyMenuComponent = (props2) => { + const [fieldName, setFieldName] = h2(""); + const [fieldSource, setFieldSource] = h2( + props2.fileMetadata ? "fm" : "" + ); + const [fieldValue, setFieldValue] = h2(""); + const [fieldType, setFieldType] = h2("text"); + const options = F2(() => { + let options2 = []; + if (props2.fileMetadata) { + options2.push({ + name: "File Metadata", + value: "fm", + description: "This note only" + }); + } + if (props2.contextPath) { + options2.push({ + name: folderPathToString(props2.contextPath), + value: "", + description: `All notes in ${folderPathToString(props2.contextPath)}` + }); + } + options2.push( + ...props2.tags.map((f4) => ({ + name: f4, + value: f4, + description: `All notes tagged ${f4}` + })) + ); + return options2; + }, []); + const selectedType = (_9, value) => { + setFieldType(value[0]); + }; + const selectedValue = (value) => { + setFieldValue(value); + }; + const selectedSource = (_9, value) => { + setFieldSource(value[0]); + }; + const toggleMulti = () => { + const field = fieldTypes.find( + (f4) => f4.type == fieldType || f4.multiType == fieldType + ); + setFieldType(field.type == fieldType ? field.multiType : field.type); + }; + const selectType = (e4) => { + showSelectMenu(e4.target.getBoundingClientRect(), { + multi: false, + editable: false, + searchable: false, + saveOptions: selectedType, + value: [], + showAll: true, + options: fieldTypes.filter((f4) => fieldSource == "fm" ? f4.metadata : !f4.restricted).map((f4, i4) => ({ + id: i4 + 1, + name: f4.label, + value: f4.type, + icon: "" + })) + }); + }; + const selectedContext = (value) => { + setFieldValue(value); + }; + const type = F2( + () => { + var _a2; + return (_a2 = fieldTypeForType(fieldType)) != null ? _a2 : fieldTypes[0]; + }, + [fieldType] + ); + const selectSource = (e4) => { + showSelectMenu(e4.target.getBoundingClientRect(), { + multi: false, + editable: false, + searchable: false, + saveOptions: selectedSource, + value: [], + showAll: true, + options + }); + }; + const saveField = () => { + if (fieldName.length == 0) { + new import_obsidian15.Notice(i18n_default.notice.noPropertyName); + return; + } + props2.saveField(fieldSource, { + name: fieldName, + type: fieldType, + value: fieldValue, + schemaId: props2.schemaId + }); + props2.hide(); + }; + const onKeyDown = (e4) => { + if (e4.key == "Enter") { + saveField(); + } + }; + p2(() => { + setTimeout(() => { + input.current.focus(); + }, 50); + }, []); + const input = _2(null); + return /* @__PURE__ */ Cn.createElement(Cn.Fragment, null, /* @__PURE__ */ Cn.createElement("div", { + className: "menu-item" + }, /* @__PURE__ */ Cn.createElement("span", null, "Name"), /* @__PURE__ */ Cn.createElement("input", { + type: "text", + ref: input, + onKeyDown, + onChange: (e4) => setFieldName(e4.target.value), + onMouseDown: (e4) => e4.stopPropagation(), + value: fieldName + })), /* @__PURE__ */ Cn.createElement("div", { + className: "menu-separator" + }), 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", { + 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", { + className: "menu-item" + }, /* @__PURE__ */ Cn.createElement("span", null, i18n_default.labels.multiple), /* @__PURE__ */ Cn.createElement("input", { + type: "checkbox", + checked: fieldType == type.multiType, + onChange: () => toggleMulti() + })) : /* @__PURE__ */ Cn.createElement(Cn.Fragment, null), /* @__PURE__ */ Cn.createElement("div", { + className: "menu-separator" + }), fieldSource != "fm" ? /* @__PURE__ */ Cn.createElement(PropertyValueComponent, { + plugin: props2.plugin, + table: fieldSource, + fields: props2.fields, + fieldType, + value: fieldValue, + contextPath: props2.contextPath, + saveValue: selectedValue, + saveContext: selectedContext + }) : /* @__PURE__ */ Cn.createElement(Cn.Fragment, null), /* @__PURE__ */ Cn.createElement("div", { + className: "menu-separator" + }), /* @__PURE__ */ Cn.createElement("div", { + className: "menu-item", + onClick: (e4) => saveField() + }, /* @__PURE__ */ Cn.createElement("span", null, "Save Property")), /* @__PURE__ */ Cn.createElement("div", { + className: "menu-item", + 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(); + menu.setUseNativeMenu(false); + 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(NewPropertyMenuComponent, { + plugin, + tags, + schemaId, + contextPath, + fields, + hide: () => menu.hide(), + saveField, + fileMetadata + })) + ); + menu.addItem((menuItem) => { + menuItem.setTitle(frag); + menuItem.dom.toggleClass("mk-properties", true); + }); + 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(position); + return menu; +}; + +// 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/modals/stickerModal.tsx -var import_obsidian11 = require("obsidian"); - -// src/utils/emoji.ts -var unifiedToNative = (unified) => { - let unicodes = unified.split("-"); - let codePoints = unicodes.map((u4) => `0x${u4}`); - return String.fromCodePoint(...codePoints); -}; -var saveFileIcons = (plugin, files, icon) => { - files.forEach((file) => { - saveFileSticker(plugin, file, icon); - }); -}; -var saveFileColors = (plugin, files, icon) => { - files.forEach((file) => { - saveFileColor(plugin, file, icon); - }); +// src/components/ui/menus/propertyMenu.tsx +var import_obsidian16 = require("obsidian"); +var PropertyValueComponent = (props2) => { + const selectContext = (e4) => { + var _a2; + showSelectMenu(e4.target.getBoundingClientRect(), { + 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.contextsCache.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.contextsCache.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" + }, + { + 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 + }); + }; + 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 saveSpaceIcon = (plugin, space, icon) => { - saveSpaceSticker(plugin, space, icon); +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: "" + })) + }); + }; + 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 removeSpaceIcon = (plugin, space) => { - saveSpaceSticker(plugin, space, ""); +var showPropertyMenu = (plugin, position, editable, options, field, fields, contextPath, saveField, saveContext, hide, deleteColumn, sortColumn, hidden) => { + const menu = new import_obsidian16.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; }; -var saveFileIcon = (plugin, data, icon) => { - saveFileSticker(plugin, data.path, icon); + +// src/components/ContextView/ContextBuilder/ContextBuilderView.tsx +var import_classnames = __toESM(require_classnames()); + +// src/components/ContextView/TagsView/TagsView.tsx +var import_obsidian17 = require("obsidian"); +var TagsView = (props2) => { + const showTagMenu = (e4, tag) => { + e4.stopPropagation(); + e4.preventDefault(); + const menu = new import_obsidian17.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.map((f4, i4) => /* @__PURE__ */ Cn.createElement("div", { + 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"] } + }))); }; -var removeFileIcons = (plugin, files) => { - files.forEach((file) => { - saveFileSticker(plugin, file, ""); + +// 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) + }); + }; + 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); + }; + return /* @__PURE__ */ Cn.createElement(TagsView, { + plugin: props2.plugin, + tags: tagContexts, + canOpen: false, + addTag: props2.canAdd && addTag2, + removeTag: removeContext }); }; -var removeFileIcon = (plugin, data) => { - saveFileSticker(plugin, data.path, ""); + +// 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 + } + }), + useSensor(TouchSensor, { + activationConstraint: { + delay: 250, + tolerance: 5 + } + }), + useSensor(KeyboardSensor, { + coordinateGetter: sortableKeyboardCoordinates + }) + ); + const resetState = () => { + setActiveId(null); + setOverId(null); + }; + 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 }) => { + 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) + ) + }); + 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 + }; + return /* @__PURE__ */ Cn.createElement("div", { + ref: setNodeRef, + style, + ...attributes, + ...listeners + }, props2.value); +} -// src/components/ui/modals/stickerModal.tsx -var stickerModal = class extends import_obsidian11.FuzzySuggestModal { - constructor(app2, setIcon) { - super(app2); - this.setIcon = setIcon; - this.resultContainerEl.toggleClass("mk-sticker-modal", true); - this.inputEl.focus(); - this.emptyStateText = i18n_default.labels.findStickers; - this.limit = 0; - } - renderSuggestion(item, el) { - el.innerHTML = unifiedToNative(item.item.unicode); - el.setAttr("aria-label", item.item.label); - } - getItemText(item) { - return item.label + item.desc; - } - getItems() { - const allEmojis = Object.keys(emojis).reduce( - (p3, c4) => [ - ...p3, - ...emojis[c4].map((e4) => ({ - label: e4.n[0], - desc: e4.n[1], - variants: e4.v, - unicode: e4.u - })) - ], - [] +// 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); + } + } + }; + 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 + ); + } + }).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) + ); + }; + const saveNewField = (source, field) => { + saveColumn({ ...field, table: "" }); + }; + const newProperty = (e4) => { + const offset = e4.target.getBoundingClientRect(); + showNewPropertyMenu( + props2.plugin, + { x: offset.left, y: offset.top + 30 }, + tagContexts, + [], + saveNewField, + "files", + contextInfo.contextPath, + false ); - return allEmojis; - } - onChooseItem(item, evt) { - this.setIcon(item.unicode); - } -}; - -// src/hooks/useLongPress.tsx -function isMouseEvent(e4) { - return e4 && "screenX" in e4; -} - -// src/components/FileSticker/FileSticker.tsx -var import_obsidian12 = require("obsidian"); -var FileSticker = (props2) => { - const [vaultItem, setVaultItem] = p2( - vaultItemForPath(props2.plugin, props2.filePath) - ); - const reloadIcon = (e4) => { - if (e4.detail.changeType == "sticker" || e4.detail.changeType == "sync") - setVaultItem(vaultItemForPath(props2.plugin, props2.filePath)); }; - h2(() => { - if ((vaultItem == null ? void 0 : vaultItem.path) != props2.filePath) { - setVaultItem(vaultItemForPath(props2.plugin, props2.filePath)); - } - window.addEventListener(eventTypes.spacesChange, reloadIcon); - return () => { - window.removeEventListener(eventTypes.spacesChange, reloadIcon); + 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: [] } + ); }; - }, [props2.filePath]); - const triggerStickerContextMenu = (e4) => { - 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, - (emoji) => saveFileSticker(props2.plugin, props2.filePath, emoji) + 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) + ); + 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) ); - vaultChangeModal.open(); - }); - }); - fileMenu.addItem((menuItem) => { - menuItem.setTitle(i18n_default.buttons.removeIcon); - menuItem.setIcon("lucide-file-minus"); - menuItem.onClick((ev) => { - removeFileIcons(props2.plugin, [props2.filePath]); + } else { + syncMetadataContext(yamlTableData, yamlTypes, table); + } + } + }; + const syncMetadataContext = (yamlTableData, yamlTypes, table) => { + if (contextTable[table]) { + const newTable = mergeTableData( + contextTable[table], + yamlTableData, + yamlTypes + ); + saveContextDB(newTable, table); + saveSchema({ + ...dbSchema, + def: updateTagsForDefString( + dbSchema.def, + uniq([...tagContexts, table]) + ) }); - }); - if (isMouseEvent(e4)) { - fileMenu.showAtPosition({ x: e4.pageX, y: e4.pageY }); } else { - fileMenu.showAtPosition({ - x: e4.nativeEvent.locationX, - y: e4.nativeEvent.locationY + 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]) + ) + }); }); } - return false; - }; - const triggerStickerMenu = (e4) => { - e4.stopPropagation(); - let vaultChangeModal = new stickerModal( - props2.plugin.app, - (emoji) => saveFileSticker(props2.plugin, props2.filePath, emoji) - ); - vaultChangeModal.open(); }; - const color = vaultItem == null ? void 0 : vaultItem.color; - return /* @__PURE__ */ bn.createElement("div", { - className: `mk-file-icon ${(vaultItem == null ? void 0 : vaultItem.sticker) ? "" : "mk-file-icon-placeholder"}` - }, /* @__PURE__ */ bn.createElement("button", { - "aria-label": i18n_default.buttons.changeIcon, - onContextMenu: triggerStickerContextMenu, - style: (color == null ? void 0 : color.length) > 0 ? { - "--label-color": `${vaultItem.color}`, - "--icon-color": `#ffffff` - } : { - "--icon-color": `var(--text-muted)` + 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, { + plugin: props2.plugin, + initialValue: defaultValueForPropertyType( + f4.name, + f4.value, + f4.type + ), + index: 0, + file: "", + column: { ...f4, table: "" }, + editable: false, + updateValue: (v3) => { }, - dangerouslySetInnerHTML: (vaultItem == null ? void 0 : vaultItem.sticker) ? { __html: unifiedToNative(vaultItem.sticker) } : (vaultItem == null ? void 0 : vaultItem.folder) == "true" ? { - __html: color ? uiIconSet["mk-ui-folder-solid"] : uiIconSet["mk-ui-folder"] - } : { - __html: defaultIconForExtension( - fileExtensionForFile(vaultItem == null ? void 0 : vaultItem.path), - color ? true : false - ) + updateFieldValue: (fv, v3) => { }, - onClick: (e4) => triggerStickerMenu(e4) - })); + 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"] + } + }))), (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", { + 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"] + } + })))))), (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`), + dangerouslySetInnerHTML: { + __html: uiIconSet["mk-ui-edit"] + } + }), "Properties"), /* @__PURE__ */ Cn.createElement("div", { + className: (0, import_classnames.default)( + "mk-section-title", + section == 1 && "mk-is-active" + ), + onClick: () => setSection(1) + }, /* @__PURE__ */ Cn.createElement("div", { + className: (0, import_classnames.default)(`mk-icon-small`), + dangerouslySetInnerHTML: { + __html: uiIconSet["mk-ui-stack"] + } + }), "Layout"))); }; -// src/components/ui/modals/editSpaceModal.ts -var import_obsidian13 = require("obsidian"); -var EditSpaceModal = class extends import_obsidian13.Modal { - constructor(plugin, space, action) { +// src/components/ui/modals/contextEditorModal.tsx +var import_obsidian18 = require("obsidian"); +var ContextEditorModal = class extends import_obsidian18.Modal { + constructor(plugin, context, view) { super(plugin.app); - this.space = space; - this.action = action; + 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; - if (this.action === "rename") { - headerText = i18n_default.labels.renameSection; - } else if (this.action === "create") { - headerText = i18n_default.labels.createSection; - } + 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_obsidian19 = require("obsidian"); +var MergeColumnModal = class extends import_obsidian19.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 inputEl = contentEl.createEl("input"); - inputEl.style.cssText = "width: 100%; height: 2.5em; margin-bottom: 15px;"; - if (this.action === "rename") { - inputEl.value = this.space; + 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); } - inputEl.focus(); - let changeButtonText; - if (this.action === "rename") { - changeButtonText = i18n_default.buttons.rename; - } else if (this.action === "create") { - changeButtonText = i18n_default.buttons.createSection; + 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 }); @@ -32830,5046 +36121,4794 @@ var EditSpaceModal = class extends import_obsidian13.Modal { text: i18n_default.buttons.cancel }); cancelButton.style.cssText = "float: right;"; - cancelButton.addEventListener("click", () => { - myModal.close(); - }); - const onClickAction = async () => { - let newName = inputEl.value.replace(/\//g, ""); - if (newName.length == 0) { - new import_obsidian13.Notice(i18n_default.notice.newSpaceName); - return; - } - if (retrieveSpaces(this.plugin).find((f4) => f4.name == newName)) { - new import_obsidian13.Notice(i18n_default.notice.duplicateSpaceName); - return; - } - if (this.action === "rename") { - renameSpace(this.plugin, this.space, newName); - } else if (this.action === "create") { - insertSpaceAtIndex(this.plugin, newName, false, 0); - } - myModal.close(); - }; - changeButton.addEventListener("click", onClickAction); - inputEl.addEventListener("keydown", (e4) => { - if (e4.key === "Enter") - onClickAction(); - }); - } - onClose() { - let { contentEl } = this; - contentEl.empty(); - } -}; - -// src/components/ui/menus/fileMenu.tsx -var import_obsidian14 = require("obsidian"); - -// src/utils/color.ts -var colors = [ - ["Red", "#eb3b5a"], - ["Orange", "#fa8231"], - ["Yellow", "#f7b731"], - ["Green", "#20bf6b"], - ["Turquoise", "#0fb9b1"], - ["Teal", "#2d98da"], - ["Blue", "#3867d6"], - ["Purple", "#8854d0"], - ["Charcoal", "#4b6584"] -]; - -// src/components/ui/menus/fileMenu.tsx -var triggerSectionMenu = (plugin, spaceName, spaces2, e4, activeFile2) => { - const fileMenu = new import_obsidian14.Menu(); - const space = spaces2.find((f4) => f4.name == spaceName); - fileMenu.addItem((menuItem) => { - menuItem.setIcon("edit"); - menuItem.setTitle(i18n_default.buttons.createNote); - menuItem.onClick((ev) => { - newFileInSpace(plugin, space, activeFile2); - }); - }); - fileMenu.addItem((menuItem) => { - menuItem.setIcon("layout-dashboard"); - menuItem.setTitle(i18n_default.buttons.createCanvas); - menuItem.onClick((ev) => { - newFileInSpace(plugin, space, activeFile2, true); - }); - }); - fileMenu.addItem((menuItem) => { - menuItem.setIcon("folder-plus"); - menuItem.setTitle(i18n_default.buttons.createFolder); - menuItem.onClick((ev) => { - newFolderInSpace(plugin, space, activeFile2); - }); - }); - fileMenu.addSeparator(); - fileMenu.addItem((menuItem) => { - var _a2; - const pinned = ((_a2 = spaces2.find((f4) => f4.name == spaceName)) == null ? void 0 : _a2.pinned) == "true"; - if (pinned) { - menuItem.setTitle(i18n_default.menu.unpinSpace); - } else { - menuItem.setTitle(i18n_default.menu.pinSpace); - } - menuItem.setIcon("pin"); - menuItem.onClick((ev) => { - toggleSpacePin(plugin, spaceName, !pinned); - }); - }); - if (plugin.settings.spacesStickers) { - fileMenu.addSeparator(); - fileMenu.addItem((menuItem) => { - menuItem.setTitle(i18n_default.buttons.changeIcon); - menuItem.setIcon("lucide-sticker"); - menuItem.onClick((ev) => { - let vaultChangeModal = new stickerModal( - plugin.app, - (emoji) => saveSpaceIcon(plugin, spaceName, emoji) - ); - vaultChangeModal.open(); - }); - }); - fileMenu.addItem((menuItem) => { - menuItem.setTitle(i18n_default.buttons.removeIcon); - menuItem.setIcon("lucide-file-minus"); - menuItem.onClick((ev) => { - removeSpaceIcon(plugin, spaceName); - }); - }); - } - 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(); - }); - }); - fileMenu.addSeparator(); - fileMenu.addItem((menuItem) => { - const sortOption = ["rank", true]; - menuItem.setTitle(i18n_default.menu.customSort); - menuItem.setChecked( - space.sort == JSON.stringify(sortOption) || space.sort == "" - ); - menuItem.onClick((ev) => { - updateSpaceSort(plugin, spaceName, sortOption); - }); - }); - fileMenu.addSeparator(); - fileMenu.addItem((menuItem) => { - const sortOption = ["path", true]; - menuItem.setTitle(i18n_default.menu.fileNameSortAlphaAsc); - menuItem.setChecked(space.sort == JSON.stringify(sortOption)); - menuItem.onClick((ev) => { - updateSpaceSort(plugin, spaceName, sortOption); - }); - }); - fileMenu.addItem((menuItem) => { - const sortOption = ["path", false]; - menuItem.setTitle(i18n_default.menu.fileNameSortAlphaDesc); - menuItem.setChecked(space.sort == JSON.stringify(sortOption)); - menuItem.onClick((ev) => { - updateSpaceSort(plugin, spaceName, sortOption); - }); - }); - fileMenu.addSeparator(); - fileMenu.addItem((menuItem) => { - const sortOption = ["created", false]; - menuItem.setTitle(i18n_default.menu.createdTimeSortAsc); - menuItem.setChecked(space.sort == JSON.stringify(sortOption)); - menuItem.onClick((ev) => { - updateSpaceSort(plugin, spaceName, sortOption); - }); - }); - fileMenu.addItem((menuItem) => { - const sortOption = ["created", true]; - menuItem.setTitle(i18n_default.menu.createdTimeSortDesc); - menuItem.setChecked(space.sort == JSON.stringify(sortOption)); - menuItem.onClick((ev) => { - updateSpaceSort(plugin, spaceName, sortOption); - }); - }); - fileMenu.addSeparator(); - fileMenu.addItem((menuItem) => { - menuItem.setTitle(i18n_default.menu.edit); - menuItem.setIcon("pencil"); - menuItem.onClick((ev) => { - let vaultChangeModal = new EditSpaceModal(plugin, space.name, "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 = retrieveSpaces(plugin); - const spaceItems = retrieveSpaceItems(plugin, spaces2); - const fileMenu = new import_obsidian14.Menu(); - fileMenu.addSeparator(); - fileMenu.addItem((menuItem) => { - menuItem.setTitle(i18n_default.menu.spaceTitle); - menuItem.setDisabled(true); - }); - spaces2.map((f4) => { - fileMenu.addItem((menuItem) => { - const allIn = files.reduce( - (p3, c4) => { - var _a2; - return p3 ? (_a2 = spaceItems[f4.name]) == null ? void 0 : _a2.some((g4) => g4.path == c4) : p3; - }, - true - ); - if (allIn) { - menuItem.setIcon("checkmark"); - menuItem.setTitle(f4.name); - } else { - menuItem.setTitle(f4.name); - menuItem.setIcon("plus"); - } - menuItem.onClick((ev) => { - if (allIn) { - removePathsFromSpace(plugin, f4.name, files); - } else { - addPathsToSpace(plugin, f4.name, files); - } - }); - }); - }); - 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] })) - ], - (_7, values) => { - saveFileColors(plugin, files, values[0]); - } - ); - }); - fileMenu.addItem((menuItem) => { - menuItem.setTitle(i18n_default.buttons.changeIcon); - menuItem.setIcon("lucide-sticker"); - menuItem.onClick((ev) => { - let vaultChangeModal = new stickerModal( - plugin.app, - (emoji) => saveFileIcons(plugin, files, emoji) - ); - vaultChangeModal.open(); - }); - }); - fileMenu.addItem((menuItem) => { - menuItem.setTitle(i18n_default.buttons.removeIcon); - menuItem.setIcon("lucide-file-minus"); - menuItem.onClick((ev) => { - removeFileIcons(plugin, files); - }); - }); - } - fileMenu.addSeparator(); - fileMenu.addItem((menuItem) => { - menuItem.setTitle(i18n_default.menu.deleteFiles); - menuItem.setIcon("trash"); - menuItem.onClick((ev) => { - deleteFiles(plugin, files); - }); - }); - 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) - ); - }); - }); - 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(); - }); + 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); } - if (isMouseEvent(e4)) { - fileMenu.showAtPosition({ x: e4.pageX, y: e4.pageY }); - } else { - fileMenu.showAtPosition({ - x: e4.nativeEvent.locationX, - y: e4.nativeEvent.locationY - }); + onClose() { + let { contentEl } = this; + contentEl.empty(); } - return false; }; -var triggerFileMenu = (plugin, file, isFolder, e4) => { - const spaces2 = retrieveSpaces(plugin); - const spaceItems = retrieveSpaceItems(plugin, spaces2); - const fileMenu = new import_obsidian14.Menu(); - if (isFolder) { - fileMenu.addSeparator(); - fileMenu.addItem((menuItem) => { - menuItem.setIcon("edit"); - menuItem.setTitle(i18n_default.buttons.createNote); - menuItem.onClick((ev) => { - newFileInFolder(plugin, file); - }); + +// src/components/ui/modals/saveViewModal.ts +var import_obsidian20 = require("obsidian"); +var SaveViewModal = class extends import_obsidian20.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 }); - fileMenu.addItem((menuItem) => { - menuItem.setIcon("layout-dashboard"); - menuItem.setTitle(i18n_default.buttons.createCanvas); - menuItem.onClick((ev) => { - createNewCanvasFile(plugin, file, ""); - }); + const cancelButton = contentEl.createEl("button", { + text: i18n_default.buttons.cancel }); - 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(); - }); + cancelButton.style.cssText = "float: right;"; + cancelButton.addEventListener("click", () => { + myModal.close(); }); - } - fileMenu.addSeparator(); - fileMenu.addItem((menuItem) => { - menuItem.setTitle(i18n_default.menu.spaceTitle); - menuItem.setDisabled(true); - }); - spaces2.map((f4, i4) => { - var _a2; - const itemExists = (_a2 = spaceItems[f4.name]) == null ? void 0 : _a2.some((g4) => g4.path == file.path); - fileMenu.addItem((menuItem) => { - var _a3; - menuItem.setTitle(f4.name); - if (((_a3 = f4.def) == null ? void 0 : _a3.length) > 0) { - menuItem.setDisabled(true); - menuItem.setIcon("folder"); + 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 { - if (itemExists) { - menuItem.setIcon("checkmark"); - } else { - menuItem.setIcon("plus"); - } - menuItem.onClick((ev) => { - if (!itemExists) { - insertSpaceItemAtIndex(plugin, f4.name, file.path, 0); - } else { - removePathsFromSpace(plugin, f4.name, [file.path]); - } - }); + this.saveSchema({ ...this.schema, name: newName }); } - }); - }); - if (isFolder) { - fileMenu.addSeparator(); - fileMenu.addItem((menuItem) => { - menuItem.setTitle(i18n_default.menu.createFolderSpace); - menuItem.setIcon("plus-square"); - menuItem.onClick((ev) => { - insertSpaceAtIndex(plugin, file.name, false, 0, file.path); - }); - }); - } - 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] })) - ], - (_7, values) => { - saveFileColor(plugin, file.path, values[0]); - } - ); - }); - fileMenu.addItem((menuItem) => { - menuItem.setTitle(i18n_default.buttons.changeIcon); - menuItem.setIcon("lucide-sticker"); - menuItem.onClick((ev) => { - let vaultChangeModal = new stickerModal( - plugin.app, - (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); - }); - }); - } - 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); + myModal.close(); + }; + changeButton.addEventListener("click", onClickAction); + inputEl.addEventListener("keydown", (e4) => { + if (e4.key === "Enter") { + e4.preventDefault(); + onClickAction(); } }); - }); - 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(); - }); - }); } - 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 - }); + onClose() { + let { contentEl } = this; + contentEl.empty(); } - return false; }; -// src/components/ContextView/DataTypeView/FileCell.tsx -var import_obsidian15 = require("obsidian"); -var FileCell = (props2) => { - var _a2; - const fileOrCleanPath = (f4) => { - if (!f4) - return { - path: "" - }; - const isInFolder = !props2.isFolder || f4.includes(props2.folder); - const fileExists2 = getAbstractFileAtPath(app, f4); - const cleanPath = (path) => path.replace(props2.folder + "/", "").replace(".md", ""); - return isInFolder ? fileExists2 ? { path: f4, file: fileExists2 } : { path: cleanPath(f4) } : { path: f4 }; - }; - const initialValue = (props2.multi ? (_a2 = splitString(props2.initialValue)) != null ? _a2 : [] : [props2.initialValue]).map((f4) => fileOrCleanPath(f4)); - const [value, setValue] = p2(initialValue); - const ref = _2(null); - const onKeyDown = (e4) => { - e4.stopPropagation(); - e4.key == "Enter" && e4.target.blur(); +// src/components/ContextView/FilterBar/FilterBar.tsx +var import_obsidian21 = require("obsidian"); + +// src/components/ContextView/FilterBar/SearchBar.tsx +var SearchBar = (props2) => { + const clearSearch = () => { + props2.setSearchString(""); }; - const fileExists = (name) => { - if (!name) - return false; - return getAbstractFileAtPath(app, `${props2.folder}/${name}.md`) ? true : false; + 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 onBlur = () => { - var _a3; - if (!ref.current) - return; - if (fileExists((_a3 = ref.current) == null ? void 0 : _a3.value)) { - new import_obsidian15.Notice(i18n_default.notice.fileExists); - } else { - props2.saveValue(ref.current.value); - props2.setEditMode(null); - } + 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 newFile = async (file) => { - const filePath = file.path.replace(/\//g, "").replace(/\./g, ""); - const path = `${props2.folder}/${filePath}.md`; - if (filePath.length == 0) { + const openView = (e4, view) => { + const dbSchema2 = tables.find((f4) => f4.type == "db" && f4.id == view.def); + if (dbSchema2) { + selectView(dbSchema2, view.id); return; } - if (fileExists(path)) { - new import_obsidian15.Notice(i18n_default.notice.fileExists); - } else { - await createNewMarkdownFile( - props2.plugin, - getAbstractFileAtPath(app, props2.folder), - filePath - ); - } - }; - const deleteRow = () => { - props2.deleteRow(); + return; }; - h2(() => { - var _a3; - if (props2.editMode == 2) { - (_a3 = ref == null ? void 0 : ref.current) == null ? void 0 : _a3.focus(); - } - }, [props2.editMode]); - return /* @__PURE__ */ bn.createElement("div", { - className: "mk-cell-file" - }, value.map((v3, i4) => { - var _a3; - if (props2.editMode == 0) { - if (v3.file) { - return /* @__PURE__ */ bn.createElement("div", { - className: "mk-cell-file-title" - }, v3 ? v3.file instanceof import_obsidian15.TFile ? fileNameToString(v3.file.name) : v3.file.name : "", (v3 == null ? void 0 : v3.file) instanceof import_obsidian15.TFile && v3.file.extension != "md" && /* @__PURE__ */ bn.createElement("span", { - className: "nav-file-tag" - }, (_a3 = v3.file) == null ? void 0 : _a3.extension), /* @__PURE__ */ bn.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__ */ bn.createElement("div", { - className: "mk-cell-file-title" - }, v3.path); - } - } - if (v3.file) { - return /* @__PURE__ */ bn.createElement(bn.Fragment, null, /* @__PURE__ */ bn.createElement("div", { - className: "mk-cell-file-item", - onContextMenu: (e4) => triggerFileMenu( - props2.plugin, - v3.file, - v3.file instanceof import_obsidian15.TFolder, - e4 - ) - }, /* @__PURE__ */ bn.createElement(FileSticker, { - plugin: props2.plugin, - filePath: v3.file.path - }), /* @__PURE__ */ bn.createElement("div", { - className: "mk-cell-file-name", - onClick: (e4) => openFile( - { ...v3.file, isFolder: v3.file instanceof import_obsidian15.TFolder }, - props2.plugin, - e4.ctrlKey || e4.metaKey - ) - }, v3 ? v3.file instanceof import_obsidian15.TFile ? fileNameToString(v3.file.name) : v3.file.name : ""))); - } - return /* @__PURE__ */ bn.createElement(bn.Fragment, null, /* @__PURE__ */ bn.createElement("div", { - className: "mk-cell-file-item" - }, /* @__PURE__ */ bn.createElement("div", { - className: "mk-file-icon" - }, /* @__PURE__ */ bn.createElement("button", { - onClick: (e4) => newFile(v3), - dangerouslySetInnerHTML: { - __html: uiIconSet["mk-ui-new-file"] - } - })), props2.editMode > 1 ? /* @__PURE__ */ bn.createElement("input", { - className: "mk-cell-file-name", - type: "text", - placeholder: "Untitled", - ref, - value: v3.path, - onKeyDown, - onBlur - }) : /* @__PURE__ */ bn.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"; - } - 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 FilePropertyCell = (props2) => { - const { propertyValue } = props2; - const [cache, setCache] = p2(null); - const initialValue = props2.initialValue; - if (propertyValue == "folder" || propertyValue == "File.folder") { - return /* @__PURE__ */ bn.createElement("div", { - className: "mk-cell-fileprop", - onClick: () => { - openTFolder( - getAbstractFileAtPath(app, initialValue), - props2.plugin, - false - ); + 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 } - }, folderPathToString(initialValue)); - } - if (propertyValue == "extension" || propertyValue == "File.extension") { - return /* @__PURE__ */ bn.createElement("div", { - className: "mk-cell-fileprop" - }, initialValue); - } else if (propertyValue == "ctime" || propertyValue == "mtime" || propertyValue == "File.mtime" || propertyValue == "File.ctime") { - const date = new Date(parseInt(initialValue)).getTime() ? new Date(parseInt(initialValue)) : null; - return /* @__PURE__ */ bn.createElement("div", { - className: "mk-cell-fileprop" - }, date && formatDistance3(new Date(date), new Date(), { addSuffix: true })); - } else if (propertyValue == "size" || propertyValue == "File.size") { - return /* @__PURE__ */ bn.createElement("div", { - className: "mk-cell-fileprop" - }, humanFileSize(parseInt(initialValue))); - } - return /* @__PURE__ */ bn.createElement("div", { - className: "mk-cell-fileprop" - }, initialValue); -}; - -// src/components/ContextView/DataTypeView/NumberCell.tsx -var NumberCell = (props2) => { - const { initialValue, saveValue } = props2; - const [value, setValue] = bn.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); - } + const clearFilters = () => { + savePredicate({ + ...predicate, + filters: [], + sort: [] + }); }; - bn.useEffect(() => { - setValue(initialValue); - }, [initialValue]); - h2(() => { - var _a2; - if (props2.editMode == 2) { - (_a2 = ref == null ? void 0 : ref.current) == null ? void 0 : _a2.focus(); - } - }, [props2.editMode]); - return props2.editMode > 1 ? /* @__PURE__ */ bn.createElement("input", { - className: "mk-cell-text", - type: "number", - step: "any", - ref, - value, - onChange: (e4) => setValue(e4.target.value), - onKeyDown, - onBlur - }) : /* @__PURE__ */ bn.createElement("div", { - className: "mk-cell-number" - }, value); -}; - -// src/components/ContextView/DataTypeView/TextCell.tsx -var TextCell = (props2) => { - const { initialValue, saveValue } = props2; - const [value, setValue] = bn.useState(initialValue); - const ref = _2(null); - const onBlur = () => { - if (initialValue != value) - saveValue(value); + const clearHiddenCols = () => { + savePredicate({ + ...predicate, + colsHidden: [] + }); }; - 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 removeFilter = (filter) => { + const newFilters = [ + ...predicate.filters.filter((f4) => f4.field != filter.field) + ]; + savePredicate({ + ...predicate, + filters: newFilters + }); + }; + const viewContextMenu = (e4, _schema) => { + const fileMenu = new import_obsidian21.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 + }); } }; - bn.useEffect(() => { - setValue(initialValue); - }, [initialValue]); - h2(() => { + const showFilterMenu = (e4) => { + const menu = new import_obsidian21.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"); + }); + }); + 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; - if (props2.editMode == 2) { - (_a2 = ref == null ? void 0 : ref.current) == null ? void 0 : _a2.focus(); + 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.editMode]); - return props2.editMode > 1 ? /* @__PURE__ */ bn.createElement("input", { - onClick: (e4) => e4.stopPropagation(), - className: "mk-cell-text", - ref, - type: "text", - value, - onChange: (e4) => setValue(e4.target.value), - onKeyDown, - onBlur - }) : /* @__PURE__ */ bn.createElement("div", { - className: "mk-cell-text" - }, value); -}; - -// src/components/ui/menus/newPropertyMenu.tsx -var import_obsidian17 = require("obsidian"); - -// src/components/ui/menus/propertyMenu.tsx -var import_obsidian16 = require("obsidian"); -var PropertyValueComponent = (props2) => { - const selectContext = (e4) => { - var _a2; - showSelectMenu(e4.target.getBoundingClientRect(), { - multi: false, - editable: true, - searchable: true, - saveOptions: (_7, 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 saveGroupBy = (_9, groupBy2) => { + savePredicate({ + ...predicate, + groupBy: groupBy2 }); }; - const selectFileProp = (e4) => { - const properties2 = props2.fields.filter( - (f4) => f4.type == "file" || f4.type == "context" && f4.table == props2.table - ).reduce((p3, c4) => { - var _a2, _b2; - return [ - ...p3, - ...c4.type == "file" ? filePropTypes.map((f4) => ({ - name: c4.name + "." + f4.name, - value: c4.name + "." + f4.value - })) : (_b2 = (_a2 = props2.context[c4.value]) == null ? void 0 : _a2.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: (_7, v3) => props2.saveValue(v3[0]), - value: [], - options: properties2, - showAll: true + const removeSort = (sort) => { + const newSort = [...predicate.sort.filter((f4) => f4.field != sort.field)]; + savePredicate({ + ...predicate, + sort: newSort }); }; - const selectDateFormat = (e4) => { - const formats = [ - { - name: "2020-04-21", - value: "yyyy-MM-dd" - }, - { - name: "Apr 21, 2020", - value: "MMM d, yyyy" - }, + 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 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 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 }, { - name: "Tue Apr 21, 2020", - value: "EEE MMM d, yyyy" + 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 } - ]; - showSelectMenu(e4.target.getBoundingClientRect(), { - multi: false, - editable: true, - searchable: false, - saveOptions: (_7, v3) => props2.saveValue(v3[0]), - value: [], - options: formats, - showAll: true, - placeholder: i18n_default.labels.selectDateFormat - }); + ); }; - return props2.fieldType.startsWith("date") ? /* @__PURE__ */ bn.createElement("div", { - className: "menu-item", - onClick: (e4) => selectDateFormat(e4) - }, /* @__PURE__ */ bn.createElement("span", null, i18n_default.labels.dateFormat), /* @__PURE__ */ bn.createElement("span", null, props2.value)) : props2.fieldType.startsWith("context") ? /* @__PURE__ */ bn.createElement("div", { - className: "menu-item", - onClick: (e4) => selectContext(e4) - }, /* @__PURE__ */ bn.createElement("span", null, i18n_default.labels.propertyContext), /* @__PURE__ */ bn.createElement("span", null, props2.value)) : props2.fieldType == "fileprop" ? /* @__PURE__ */ bn.createElement("div", { - className: "menu-item", - onClick: (e4) => selectFileProp(e4) - }, /* @__PURE__ */ bn.createElement("span", null, i18n_default.labels.propertyFileProp), /* @__PURE__ */ bn.createElement("span", null, props2.value)) : /* @__PURE__ */ bn.createElement(bn.Fragment, null); -}; -var PropertyMenuComponent = (props2) => { - var _a2; - const [field, setField] = p2(props2.field); - const selectedType = (_7, value) => { - const newField = { - ...field, - type: value[0], - value: getNewValueForType(field, value) - }; - setField(newField); - props2.saveField(newField); + const showColsMenu = (e4) => { + let vaultChangeModal = new ContextEditorModal( + props2.plugin, + contextInfo, + schema == null ? void 0 : schema.id + ); + vaultChangeModal.open(); }; - const selectedValue = (value) => { - const newField = { ...field, value }; - setField(newField); - props2.saveField(newField); + 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 selectedContext = (context) => { - const newField = { ...field, value: context }; - setField(newField); - props2.saveContext(newField, [context]); + 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 toggleMulti = () => { - const newField = { - ...field, - type: field.type == fieldType.multiType ? fieldType.type : fieldType.multiType + 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 + ] + }); }; - setField(newField); - props2.saveField(newField); + 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 + } + ); }; - const fieldType = (_a2 = fieldTypes.find((f4) => f4.type == field.type || f4.multiType == field.type)) != null ? _a2 : fieldTypes[0]; - const getNewValueForType = (f4, value) => { - if (value[0].startsWith("option")) { - return props2.options.join(","); - } - return value[0] == fieldType.type || value[0] == fieldType.multiType ? f4.value : null; + 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 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 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 + } + ); }; - return /* @__PURE__ */ bn.createElement(bn.Fragment, null, /* @__PURE__ */ bn.createElement("div", { - className: "menu-item", - onClick: (e4) => selectType(e4) - }, /* @__PURE__ */ bn.createElement("span", null, i18n_default.labels.propertyType), /* @__PURE__ */ bn.createElement("span", null, fieldType.label)), fieldType.multi ? /* @__PURE__ */ bn.createElement("div", { - className: "menu-item" - }, /* @__PURE__ */ bn.createElement("span", null, i18n_default.labels.multiple), /* @__PURE__ */ bn.createElement("input", { - type: "checkbox", - checked: field.type == fieldType.multiType, - onChange: () => toggleMulti() - })) : /* @__PURE__ */ bn.createElement(bn.Fragment, null), /* @__PURE__ */ bn.createElement("div", { - className: "menu-separator" - }), /* @__PURE__ */ bn.createElement(PropertyValueComponent, { - plugin: props2.plugin, - table: field.table, - fields: props2.fields, - fieldType: fieldType.type, - value: field.value, - context: props2.context, - saveValue: selectedValue, - saveContext: selectedContext - })); -}; -var showPropertyMenu = (plugin, position, editable, options, field, fields, contextTables, saveField, saveContext, hide, deleteColumn, sortColumn, hidden) => { - const menu = new import_obsidian16.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__ */ bn.createElement(bn.Fragment, null, /* @__PURE__ */ bn.createElement(PropertyMenuComponent, { - plugin, - field, - fields, - context: contextTables, - options, - saveField, - saveContext - })) + 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 + } ); - 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"); + }; + const showAddMenu = (e4) => { + const fileMenu = new import_obsidian21.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); }); - } - menu.addItem((menuItem) => { - menuItem.setTitle(i18n_default.menu.deleteProperty); - menuItem.onClick(() => { - deleteColumn(field); + }); + fileMenu.addItem((menuItem) => { + menuItem.setIcon("layout-dashboard"); + menuItem.setTitle(i18n_default.buttons.createCanvas); + menuItem.onClick((ev) => { + createNewCanvasFile(props2.plugin, folder, ""); }); - 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, - type: normalizedSortForType(field.type, false) - }); + 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 }); + } else { + fileMenu.showAtPosition({ + x: e4.nativeEvent.locationX, + y: e4.nativeEvent.locationY + }); + } + return false; + }; + const showFMMenu2 = (e4) => { + const menu = new import_obsidian21.Menu(); menu.addItem((menuItem) => { - menuItem.setTitle(i18n_default.menu.sortDescending); - menuItem.setIcon("sort-desc"); + menuItem.setIcon("log-in"); + menuItem.setTitle(i18n_default.menu.mergeProperties); menuItem.onClick(() => { - sortColumn({ - field: field.name + field.table, - type: normalizedSortForType(field.type, true) - }); + showMergeColumnModal(); }); }); - } - menu.showAtPosition(position); - return menu; -}; - -// src/components/ui/menus/newPropertyMenu.tsx -var NewPropertyMenuComponent = (props2) => { - const [fieldName, setFieldName] = p2(""); - const [fieldSource, setFieldSource] = p2( - props2.fileMetadata ? "fm" : props2.folder ? "" : props2.tags[0] - ); - const [fieldValue, setFieldValue] = p2(""); - const [fieldType, setFieldType] = p2("text"); - const [context, setContext] = p2(null); - const options = F(() => { - let options2 = []; - if (props2.fileMetadata) { - options2.push({ - name: "File Metadata", - value: "fm", - description: "This note only" - }); - } - if (props2.folder) { - options2.push({ - name: props2.folder, - value: "", - description: `All notes in ${props2.folder}` + 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; + }) }); + } 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 + ); } - options2.push( - ...props2.tags.map((f4) => ({ - name: f4, - value: f4, - description: `All notes tagged ${f4}` - })) - ); - return options2; - }, []); - const selectedType = (_7, value) => { - setFieldType(value[0]); - }; - const selectedValue = (value) => { - setFieldValue(value); - }; - const selectedSource = (_7, value) => { - setFieldSource(value[0]); }; - const toggleMulti = () => { - const field = fieldTypes.find( - (f4) => f4.type == fieldType || f4.multiType == fieldType + const showMergeColumnModal = () => { + 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 ); - setFieldType(field.type == fieldType ? field.multiType : field.type); - }; - const selectType = (e4) => { - showSelectMenu(e4.target.getBoundingClientRect(), { - multi: false, - editable: false, - searchable: false, - saveOptions: selectedType, - value: [], - showAll: true, - options: fieldTypes.filter((f4) => fieldSource == "fm" ? f4.metadata : !f4.restricted).map((f4, i4) => ({ - id: i4 + 1, - name: f4.label, - value: f4.type, - icon: "" - })) - }); - }; - const selectedContext = (value) => { - setFieldValue(value); - }; - const type = F( - () => { - var _a2; - return (_a2 = fieldTypes.find((f4) => f4.type == fieldType || f4.multiType == fieldType)) != null ? _a2 : fieldTypes[0]; - }, - [fieldType] - ); - const selectSource = (e4) => { - showSelectMenu(e4.target.getBoundingClientRect(), { - multi: false, - editable: false, - searchable: false, - saveOptions: selectedSource, - value: [], - showAll: true, - options - }); + vaultChangeModal.open(); }; - const saveField = () => { - if (fieldName.length == 0) { - new import_obsidian17.Notice(i18n_default.notice.noPropertyName); - return; - } - props2.saveField(fieldSource, { - name: fieldName, - type: fieldType, - value: fieldValue, - schemaId: props2.schemaId - }); - props2.hide(); + const showSaveViewModal = () => { + let vaultChangeModal = new SaveViewModal(schema, saveSchema, "new view"); + vaultChangeModal.open(); }; - const onKeyDown = (e4) => { - if (e4.key == "Enter") { - saveField(); - } + const editViewModal = () => { + let vaultChangeModal = new SaveViewModal(schema, saveSchema, "rename view"); + vaultChangeModal.open(); }; - h2(() => { - setTimeout(() => { - input.current.focus(); - }, 50); - }, []); - const input = _2(null); - return /* @__PURE__ */ bn.createElement(bn.Fragment, null, /* @__PURE__ */ bn.createElement("div", { - className: "menu-item" - }, /* @__PURE__ */ bn.createElement("span", null, "Name"), /* @__PURE__ */ bn.createElement("input", { - type: "text", - ref: input, - onKeyDown, - onChange: (e4) => setFieldName(e4.target.value), - onMouseDown: (e4) => e4.stopPropagation(), - value: fieldName - })), /* @__PURE__ */ bn.createElement("div", { - className: "menu-separator" - }), options.length > 1 && /* @__PURE__ */ bn.createElement("div", { - className: "menu-item", - onClick: (e4) => selectSource(e4) - }, /* @__PURE__ */ bn.createElement("span", null, "Context"), /* @__PURE__ */ bn.createElement("span", null, fieldSource == "fm" ? "File Metadata" : fieldSource == "" ? props2.folder : fieldSource)), /* @__PURE__ */ bn.createElement("div", { - className: "menu-item", - onClick: (e4) => selectType(e4) - }, /* @__PURE__ */ bn.createElement("span", null, "Type"), /* @__PURE__ */ bn.createElement("span", null, type.label)), type.multi ? /* @__PURE__ */ bn.createElement("div", { - className: "menu-item" - }, /* @__PURE__ */ bn.createElement("span", null, i18n_default.labels.multiple), /* @__PURE__ */ bn.createElement("input", { - type: "checkbox", - checked: fieldType == type.multiType, - onChange: () => toggleMulti() - })) : /* @__PURE__ */ bn.createElement(bn.Fragment, null), /* @__PURE__ */ bn.createElement("div", { - className: "menu-separator" - }), fieldSource != "fm" ? /* @__PURE__ */ bn.createElement(PropertyValueComponent, { - plugin: props2.plugin, - table: fieldSource, - fields: props2.fields, - fieldType, - value: fieldValue, - context, - saveValue: selectedValue, - saveContext: selectedContext - }) : /* @__PURE__ */ bn.createElement(bn.Fragment, null), /* @__PURE__ */ bn.createElement("div", { - className: "menu-separator" - }), /* @__PURE__ */ bn.createElement("div", { - className: "menu-item", - onClick: (e4) => saveField() - }, /* @__PURE__ */ bn.createElement("span", null, "Save Property")), /* @__PURE__ */ bn.createElement("div", { - className: "menu-item", - onClick: (e4) => props2.hide() - }, /* @__PURE__ */ bn.createElement("span", null, "Cancel"))); -}; -var showNewPropertyMenu = (plugin, position, tags, fields, saveField, schemaId, folder, fileMetadata) => { - const menu = new import_obsidian17.Menu(); - menu.setUseNativeMenu(false); - 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__ */ bn.createElement(bn.Fragment, null, /* @__PURE__ */ bn.createElement(NewPropertyMenuComponent, { - plugin, - tags, - schemaId, - folder, - fields, - hide: () => menu.hide(), - saveField, - fileMetadata - })) - ); - menu.addItem((menuItem) => { - menuItem.setTitle(frag); - menuItem.dom.toggleClass("mk-properties", true); - }); - 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(position); - return menu; -}; - -// src/hooks/useCombinedRef.tsx -function useCombinedRefs2(...refs) { - return F( - () => (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" - } -]; -var ColumnHeader = (props2) => { - const [field, setField] = p2(props2.column); - const menuRef = _2(null); - const { - loadContextFields, - contextInfo, - predicate, - tableData, - tagContexts, - contextTable, - cols, - newColumn, - saveColumn, - hideColumn, - sortColumn, - delColumn - } = q2(MDBContext); - h2(() => { - 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 selectFilterValue = (e4, filter) => { + var _a2, _b2, _c2; + switch (filterFnTypes[filter.fn].valueType) { + case "text": + case "number": + { + const menu = new import_obsidian21.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 }); } - } - } - }; - 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 + 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; } - }).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 }, - contextInfo.type == "folder" ? tagContexts : [contextInfo.contextPath], - cols, - (source, field2) => newColumn({ ...field2, table: source }), - tableData.schema.id, - contextInfo.type == "folder" ? folderPathToString(contextInfo.contextPath) : null, - 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, - contextTable, - saveField, - saveContext, - hideColumn, - delColumn, - sortColumn, - predicate.colsHidden.includes(field.name + field.table) - ); - } - }; - const ref = _2(null); - const setNodeRef = useCombinedRefs2(setDroppableNodeRef, setDraggableNodeRef); - return /* @__PURE__ */ bn.createElement("div", { - ref: setNodeRef, - ...listeners, - ...attributes, - className: "mk-col-header", - onClick: (e4) => { - toggleMenu(e4); - } - }, /* @__PURE__ */ bn.createElement("div", { - ref - }, props2.column.name.length > 0 ? field.name : "+", /* @__PURE__ */ bn.createElement("span", { - className: "mk-col-header-context", - "aria-label": props2.column.table.length > 0 ? props2.column.table : "" - }, props2.column.table.length > 0 ? "#" : ""))); -}; - -// src/components/ContextView/TableView/TableView.tsx -var import_lodash6 = __toESM(require_lodash()); -var import_obsidian19 = require("obsidian"); - -// src/components/ui/modals/imageModal.tsx -var import_obsidian18 = require("obsidian"); -var imageModal = class extends import_obsidian18.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 = 0; - } - 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); - } - getItemText(item) { - return item; - } - getSuggestions(query) { - let allImages = []; - if (query.match(urlRegex)) - allImages.push(query); - allImages.push( - ...getAllAbstractFilesInVault(this.plugin, app).filter( - (f4) => f4 instanceof import_obsidian18.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: [] - } - })); - } - getItems() { - let allImages = []; - allImages.push( - ...getAllAbstractFilesInVault(this.plugin, app).filter( - (f4) => f4 instanceof import_obsidian18.TFile && ["png", "jpg", "jpeg"].contains(f4.extension) - ).map((f4) => f4.path) - ); - return allImages; - } - onChooseItem(item, evt) { - this.selectImage(item); - } -}; - -// src/components/ContextView/DataTypeView/ImageCell.tsx -var ImageCell = (props2) => { - const { initialValue, saveValue } = props2; - const [value, setValue] = bn.useState(initialValue); - const menuRef = _2(null); - h2(() => { - if (props2.editMode == 2 /* EditModeActive */) { - if (!menuRef.current) - showModal(); + 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; } - }, []); - const file = F(() => { - const f4 = getAbstractFileAtPath(app, value); - return f4 ? app.vault.getResourcePath(f4) : value; - }, [value]); - bn.useEffect(() => { - setValue(initialValue); - }, [initialValue]); - const showModal = () => { - let vaultChangeModal = new imageModal( - props2.plugin, - props2.plugin.app, - (image) => saveValue(image) - ); - vaultChangeModal.open(); - props2.setEditMode(null); }; - return /* @__PURE__ */ bn.createElement("div", { - className: "mk-cell-image" - }, /* @__PURE__ */ bn.createElement("img", { - src: file - }), props2.editMode > 0 ? /* @__PURE__ */ bn.createElement("div", { - className: "mk-image-selector" - }, /* @__PURE__ */ bn.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__ */ bn.createElement("div", { - onClick: () => saveValue(""), - className: "mk-hover-button mk-icon-xsmall", + 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) => /* @__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"] + } + }), /* @__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), dangerouslySetInnerHTML: { __html: uiIconSet["mk-ui-close"] } - })) : /* @__PURE__ */ bn.createElement(bn.Fragment, null)); + }))), 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))); }; - -// src/utils/strings.ts -var indexOfCharElseEOS = (char, str) => { - if (str.indexOf("|") > 0) - return str.indexOf("|"); - return str.length; +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); }; -// src/components/ContextView/DataTypeView/LinkCell.tsx -var LinkCell = (props2) => { - var _a2; - const initialValue = (props2.multi ? (_a2 = splitString(props2.initialValue)) != null ? _a2 : [] : [props2.initialValue]).filter((f4) => f4); - const stringValueToLink = (strings) => strings.map((f4) => { - const match2 = /\[\[(.*?)\]\]/g.exec(f4); - const stringValue = (match2 == null ? void 0 : match2.length) > 1 ? match2[1].substring(0, indexOfCharElseEOS("|", match2[1])) : f4; - if (stringValue) - return { - label: filePathToString(stringValue), - value: stringValue +// src/components/Spaces/SpaceEditor.tsx +var SpaceEditor = k3( + (props2, ref) => { + var _a2; + const [def, setDef] = h2( + (_a2 = props2.def) != null ? _a2 : { + type: "smart", + folder: "", + filters: [{ type: "any", trueFalse: true, filters: [] }] + } + ); + const selectFilterValue = (e4, filter, i4, k5) => { + var _a3; + const saveFilterValue = (value) => { + setDefFilterValue(value, i4, k5); }; - return { - label: "", - value: "" + switch ((_a3 = filterFnTypes[filter.fn]) == null ? void 0 : _a3.valueType) { + case "text": + case "number": + { + const menu = new import_obsidian22.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; + } }; - }); - h2(() => { - var _a3; - setValue( - resolveLinks( - stringValueToLink( - props2.multi ? (_a3 = splitString(props2.initialValue)) != null ? _a3 : [] : [props2.initialValue] - ) - ) - ); - }, [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] = p2( - resolveLinks(stringValueToLink(initialValue)) - ); - const removeValue = (v3) => { - const newValues = value.filter((f4) => f4.value != v3.value); - setValue(newValues); - props2.saveValue(newValues.map((f4) => f4.value).join(",")); - }; - const saveOptions = (_7, _value) => { - if (!props2.multi) { - setValue(resolveLinks(stringValueToLink(_value))); - props2.saveValue(_value.join(",")); - } else { - const newValue = _value[0]; - if (newValue) { - const newValues = uniq([...value.map((f4) => f4.value), newValue]); - setValue(resolveLinks(stringValueToLink(newValues))); - props2.saveValue(newValues.join(",")); + 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 typeForField = (type, field) => { + if (type == "frontmatter") { + return "text"; } - } - }; - const menuProps = () => { - const options = getAllAbstractFilesInVault(props2.plugin, app).map((f4) => ({ - name: fileNameToString(f4.name), - value: f4.path - })); - const _options = !props2.multi ? [{ name: i18n_default.menu.none, value: "" }, ...options] : options; - return { - multi: false, - editable: true, - value: value.map((f4) => f4.value), - options: _options, - saveOptions, - placeholder: i18n_default.labels.linkItemSelectPlaceholder, - detail: true, - searchable: true + if (type == "filemeta") { + return fileMeta[field].vType; + } + if (type == "fileprop") { + return fileProps[field].vType; + } + return "text"; }; - }; - 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)); - } - }; - return /* @__PURE__ */ bn.createElement(OptionCellBase, { - 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 = splitString(props2.initialValue)) != null ? _a2 : []).filter( - (f4) => (f4 == null ? void 0 : f4.length) > 0 - ); - const [value, setValue] = p2(initialValue); - h2(() => { - var _a3; - setValue((_a3 = splitString(props2.initialValue)) != null ? _a3 : []); - }, [props2.initialValue]); - const removeValue = (v3) => { - const newValues = value.filter((f4) => f4 != v3); - setValue(newValues); - props2.saveValue(newValues.join(",")); - }; - const saveOptions = (_options, _value) => { - if (!props2.multi) { - setValue(_value); - props2.saveValue(_value.join(",")); - } else { - const newValue = _value[0]; - if (newValue) { - const newValues = uniq([...value, newValue]); - setValue(newValues); - props2.saveValue(newValues.join(",")); + 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; } - } - }; - 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 { - multi: false, - editable: true, - value, - options: _options, - saveOptions, - placeholder: i18n_default.labels.tagItemSelectPlaceholder, - searchable: true, - showAll: true, - onHide: () => props2.setEditMode(null) + 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 + ) + }); + 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 + ) + }); }; - }; - return /* @__PURE__ */ bn.createElement(OptionCellBase, { - menuProps, - value, - multi: props2.multi, - editMode: props2.editMode, - removeValue - }); -}; - -// 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] = p2(null); - const [lastSelectedIndex, setLastSelectedIndex] = p2(null); - const [selectedColumn, setSelectedColumn] = p2(null); - const [currentEdit, setCurrentEdit] = p2(null); - const [overId, setOverId] = p2(null); - const [openFlows, setOpenFlows] = p2([]); - const [colsSize, setColsSize] = p2({}); - const ref = _2(null); - h2(() => { - setColsSize({ ...predicate.colsSize, "+": 30 }); - }, [predicate]); - h2(() => { - setCurrentEdit(null); - }, [selectedColumn, lastSelectedIndex]); - h2(() => { - 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 (row._source == "folder") { - deleteFile(props2.plugin, getAbstractFileAtPath(app, row.File)); - } - if (row) { - saveDB2({ - ...tableData, - rows: tableData.rows.filter((f4, i4) => i4 != rowIndex) + 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 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( - 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) + }; + 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 + ) + }); + }; + const addDefFilter = (groupIndex) => { + if (groupIndex == 0 && def.filters.length == 0) { + setDef({ + ...def, + filters: [ + { + type: "any", + trueFalse: true, + filters: [ + { + type: "", + fType: "", + field: "", + value: "", + fn: "" + } + ] + } + ] + }); + } else { + setDef({ + ...def, + filters: def.filters.map( + (f4, i4) => i4 == groupIndex ? { + ...f4, + filters: [ + ...f4.filters, + { + type: "", + fType: "", + field: "", + value: "", + fn: "" + } + ] + } : f4 ) - ]) - ); - } 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 clearCell = () => { - setCellValue(""); + 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 + ) + }); }; - const copyCell = () => { - navigator.clipboard.writeText( - tableData.rows[parseInt(lastSelectedIndex)][selectedColumn] - ); + 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 + ) + }); + } }; - const nextRow = () => { - const newIndex = selectNextIndex( - lastSelectedIndex, - data.map((f4) => f4._index) + 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 + } ); - selectRows(newIndex, [newIndex]); - setLastSelectedIndex(newIndex); }; - const lastRow = () => { - const newIndex = selectPrevIndex( - lastSelectedIndex, - data.map((f4) => f4._index) + 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 + } ); - 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]); + const selectField = (e4, i4, k5) => { + const offset = e4.target.getBoundingClientRect(); + const allFiles = retrieveAllFiles( + props2.plugin.index.vaultDBCache, + props2.plugin.settings + ); + const frontmatter = allMetadataForFiles( + props2.plugin, + allFiles.map((f5) => getAbstractFileAtPath(app, f5.path)).filter((f5) => f5 instanceof import_obsidian22.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: 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 } + ); + }; + p2(() => { + ref.current = def; + }, [def]); + return /* @__PURE__ */ Cn.createElement("div", null, 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, { + group: f4, + selectGroupType, + addDefGroup, + addDefFilter, + selectField, + i: i4, + removeDefGroup + }, f4.filters.map((filter, k5) => /* @__PURE__ */ Cn.createElement(DefFilter, { + filter, + i: i4, + k: k5, + selectField, + selectFilter, + selectFilterValue, + addDefFilter, + removeDefFilter + }))))) : /* @__PURE__ */ Cn.createElement(Cn.Fragment, null)); + } +); +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_obsidian23 = require("obsidian"); +var EditSpaceModal = class extends import_obsidian23.Modal { + constructor(plugin, space, action) { + super(plugin.app); + this.space = space; + this.action = action; + this.plugin = plugin; + } + onOpen() { + let { contentEl } = this; + let myModal = this; + let headerText; + if (this.action === "rename") { + if (this.space.def.type == "smart") { + headerText = i18n_default.labels.renameSectionSmart; + } else { + headerText = i18n_default.labels.renameSection; + } + 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; } - return; - } - if (e4.key == "ArrowDown") { - nextRow(); - e4.preventDefault(); } - if (e4.key == "ArrowUp") { - lastRow(); - e4.preventDefault(); + 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; } - if (e4.key == "ArrowLeft") { - const newIndex = selectPrevIndex( - selectedColumn, - columns.map((f4) => f4.accessorKey).filter((f4) => f4 != "+") - ); - setSelectedColumn(newIndex); + inputEl.focus(); + const queryEl = contentEl.createDiv("mk-space-query"); + const root = createRoot(queryEl); + this.ref = Cn.createRef(); + root.render( + /* @__PURE__ */ Cn.createElement(SpaceEditor, { + 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; } - if (e4.key == "ArrowRight") { - const newIndex = selectNextIndex( - selectedColumn, - columns.map((f4) => f4.accessorKey).filter((f4) => f4 != "+") + 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.replace(/\//g, ""); + if (newName.length == 0) { + new import_obsidian23.Notice(i18n_default.notice.newSpaceName); + return; + } + if (this.plugin.index.spacesCache.has(newName) && newName != this.space.name) { + new import_obsidian23.Notice(i18n_default.notice.duplicateSpaceName); + return; + } + 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 + ); + } + myModal.close(); + }; + changeButton.addEventListener("click", onClickAction); + inputEl.addEventListener("keydown", (e4) => { + if (e4.key === "Enter") + onClickAction(); + }); + } + onClose() { + let { contentEl } = this; + contentEl.empty(); + } +}; + +// src/components/ui/menus/fileMenu.tsx +var import_obsidian24 = require("obsidian"); + +// src/utils/color.ts +var colors = [ + ["Red", "#eb3b5a"], + ["Orange", "#fa8231"], + ["Yellow", "#f7b731"], + ["Green", "#20bf6b"], + ["Turquoise", "#0fb9b1"], + ["Teal", "#2d98da"], + ["Blue", "#3867d6"], + ["Purple", "#8854d0"], + ["Charcoal", "#4b6584"] +]; + +// src/components/ui/menus/fileMenu.tsx +var triggerSectionAddMenu = (plugin, e4) => { + const fileMenu = new import_obsidian24.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" ); - setSelectedColumn(newIndex); - } - }; - const columns = F( - () => { - 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 = fieldTypes.find((t4) => f4.type == t4.type) || fieldTypes.find((t4) => f4.type == t4.multiType); - if (!fieldType) { - return /* @__PURE__ */ bn.createElement(bn.Fragment, null, initialValue); - } - if (fieldType.type == "file") { - return /* @__PURE__ */ bn.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__ */ bn.createElement(BooleanCell, { - ...cellProps, - column: f4 - }); - } else if (fieldType.type == "option") { - return /* @__PURE__ */ bn.createElement(OptionCell, { - ...cellProps, - options: f4.value, - multi: fieldType.multiType == f4.type, - saveOptions: saveFieldValue - }); - } else if (fieldType.type == "date") { - return /* @__PURE__ */ bn.createElement(DateCell, { - ...cellProps - }); - } else if (fieldType.type == "context") { - return /* @__PURE__ */ bn.createElement(ContextCell, { - ...cellProps, - multi: fieldType.multiType == f4.type, - contextTable: contextTable[f4.value], - contextTag: f4.value - }); - } else if (fieldType.type == "fileprop") { - return /* @__PURE__ */ bn.createElement(FilePropertyCell, { - ...cellProps - }); - } else if (fieldType.type == "tag") { - return /* @__PURE__ */ bn.createElement(TagCell, { - ...cellProps, - multi: fieldType.multiType == f4.type - }); - } else if (fieldType.type == "number") { - return /* @__PURE__ */ bn.createElement(NumberCell, { - ...cellProps - }); - } else if (fieldType.type == "link") { - return /* @__PURE__ */ bn.createElement(LinkCell, { - ...cellProps, - multi: fieldType.multiType == f4.type, - file: data[index]["File"] - }); - } else if (fieldType.type == "image") { - return /* @__PURE__ */ bn.createElement(ImageCell, { - ...cellProps - }); - } else { - return /* @__PURE__ */ bn.createElement(TextCell, { - ...cellProps - }); - } - } - }; - })) != null ? _a2 : [], - ...readMode ? [] : [ - { - header: "+", - meta: { schemaId: dbSchema == null ? void 0 : dbSchema.id }, - accessorKey: "+", - size: 20, - cell: () => /* @__PURE__ */ bn.createElement(bn.Fragment, null) + vaultChangeModal.open(); + }); + }); + 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: [] } - ] - ]; - }, - [cols, currentEdit, predicate, contextTable, toggleFlow, openFlows] - ); - const groupBy2 = F( - () => { - 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 - } + }, + "create" + ); + vaultChangeModal.open(); + }); }); - const sensors = useSensors( - useSensor(MouseSensor, { - activationConstraint: { - distance: 10 - } - }), - useSensor(TouchSensor, { - activationConstraint: { - delay: 250, - tolerance: 5 - } - }) - ); - const measuring = { - droppable: { - strategy: MeasuringStrategy.Always - } - }; - function handleDragStart(event) { - const { - active: { id: activeId2 } - } = event; - setActiveId(activeId2); - setOverId(overId); - document.body.style.setProperty("cursor", "grabbing"); + 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 }) { - var _a2; - const overId2 = over == null ? void 0 : over.id; - if (overId2) { - setOverId((_a2 = over == null ? void 0 : over.id) != null ? _a2 : null); - } + return false; +}; +var triggerSectionMenu = (plugin, space, spaces2, e4, activeFile2) => { + if (!space) + return; + const fileMenu = new import_obsidian24.Menu(); + const spaceName = space.name; + fileMenu.addItem((menuItem) => { + menuItem.setIcon("edit"); + menuItem.setTitle(i18n_default.buttons.createNote); + menuItem.onClick((ev) => { + newFileInSpace(plugin, space, activeFile2); + }); + }); + fileMenu.addItem((menuItem) => { + menuItem.setIcon("layout-dashboard"); + menuItem.setTitle(i18n_default.buttons.createCanvas); + menuItem.onClick((ev) => { + newFileInSpace(plugin, space, activeFile2, true); + }); + }); + fileMenu.addItem((menuItem) => { + menuItem.setIcon("folder-plus"); + menuItem.setTitle(i18n_default.buttons.createFolder); + menuItem.onClick((ev) => { + newFolderInSpace(plugin, space, activeFile2); + }); + }); + 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"); + }); + }); + 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"); + }); + }); + 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"); + }); + }); + if (plugin.settings.spacesStickers) { + fileMenu.addSeparator(); + fileMenu.addItem((menuItem) => { + menuItem.setTitle(i18n_default.buttons.changeIcon); + menuItem.setIcon("lucide-sticker"); + menuItem.onClick((ev) => { + let vaultChangeModal = new stickerModal( + plugin.app, + (emoji) => saveSpaceIcon(plugin, spaceName, emoji) + ); + vaultChangeModal.open(); + }); + }); + fileMenu.addItem((menuItem) => { + menuItem.setTitle(i18n_default.buttons.removeIcon); + menuItem.setIcon("lucide-file-minus"); + menuItem.onClick((ev) => { + removeSpaceIcon(plugin, spaceName); + }); + }); } - const saveFilter = (filter) => { - savePredicate({ - ...predicate, - filters: [ - ...predicate.filters.filter((s5) => s5.field != filter.field), - filter - ] + 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(); }); - }; - const selectCell = (e4, index, column) => { - if (platformIsMobile() || column == "+") - 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_obsidian19.Menu(); - menu.addItem((item) => { - item.setIcon("trash"); - item.setTitle(i18n_default.menu.deleteRow); - item.onClick(() => { - deleteRow(index); + }); + fileMenu.addSeparator(); + if (space.def.type == "focus") { + fileMenu.addItem((menuItem) => { + const sortOption = ["rank", true]; + menuItem.setTitle(i18n_default.menu.customSort); + menuItem.setChecked( + space.sort == JSON.stringify(sortOption) || space.sort == "" + ); + menuItem.onClick((ev) => { + updateSpaceSort(plugin, spaceName, sortOption); }); }); - if (isMouseEvent(e4)) { - menu.showAtPosition({ x: e4.pageX, y: e4.pageY }); - } else { - menu.showAtPosition({ - x: e4.nativeEvent.locationX, - y: e4.nativeEvent.locationY + fileMenu.addSeparator(); + } + fileMenu.addItem((menuItem) => { + const sortOption = ["path", true]; + menuItem.setTitle(i18n_default.menu.fileNameSortAlphaAsc); + menuItem.setChecked(space.sort == JSON.stringify(sortOption)); + menuItem.onClick((ev) => { + updateSpaceSort(plugin, spaceName, sortOption); + }); + }); + fileMenu.addItem((menuItem) => { + const sortOption = ["path", false]; + menuItem.setTitle(i18n_default.menu.fileNameSortAlphaDesc); + menuItem.setChecked(space.sort == JSON.stringify(sortOption)); + menuItem.onClick((ev) => { + updateSpaceSort(plugin, spaceName, sortOption); + }); + }); + fileMenu.addSeparator(); + fileMenu.addItem((menuItem) => { + const sortOption = ["ctime", false]; + menuItem.setTitle(i18n_default.menu.createdTimeSortAsc); + menuItem.setChecked(space.sort == JSON.stringify(sortOption)); + menuItem.onClick((ev) => { + updateSpaceSort(plugin, spaceName, sortOption); + }); + }); + fileMenu.addItem((menuItem) => { + const sortOption = ["ctime", true]; + menuItem.setTitle(i18n_default.menu.createdTimeSortDesc); + menuItem.setChecked(space.sort == JSON.stringify(sortOption)); + menuItem.onClick((ev) => { + updateSpaceSort(plugin, spaceName, sortOption); + }); + }); + 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_obsidian24.Menu(); + fileMenu.addSeparator(); + fileMenu.addItem((menuItem) => { + menuItem.setIcon("plus"); + menuItem.setTitle("Add to Space"); + menuItem.onClick((ev) => { + let vaultChangeModal = new AddToSpaceModal( + plugin, + selectedFiles2.map((f4) => f4.path) + ); + 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]); + } + ); + }); + fileMenu.addItem((menuItem) => { + menuItem.setTitle(i18n_default.buttons.changeIcon); + menuItem.setIcon("lucide-sticker"); + menuItem.onClick((ev) => { + let vaultChangeModal = new stickerModal( + plugin.app, + (emoji) => saveFileIcons(plugin, files, emoji) + ); + vaultChangeModal.open(); + }); + }); + fileMenu.addItem((menuItem) => { + menuItem.setTitle(i18n_default.buttons.removeIcon); + menuItem.setIcon("lucide-file-minus"); + menuItem.onClick((ev) => { + removeFileIcons(plugin, files); }); - } - }; - 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__ */ bn.createElement(DndContext, { - sensors, - collisionDetection: closestCenter, - measuring, - onDragStart: handleDragStart, - onDragOver: handleDragOver, - onDragEnd: handleDragEnd, - onDragCancel: handleDragCancel - }, /* @__PURE__ */ bn.createElement("div", { - className: "mk-table", - ref, - tabIndex: 1, - onKeyDown - }, /* @__PURE__ */ bn.createElement("table", { - ...{} - }, /* @__PURE__ */ bn.createElement("thead", null, table.getHeaderGroups().map((headerGroup) => /* @__PURE__ */ bn.createElement("tr", { - key: headerGroup.id - }, /* @__PURE__ */ bn.createElement("th", null), headerGroup.headers.map((header) => { - var _a2; - return /* @__PURE__ */ bn.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__ */ bn.createElement(bn.Fragment, null) : /* @__PURE__ */ bn.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__ */ bn.createElement(ColumnHeader, { - plugin: props2.plugin, - isNew: true, - editable: true, - column: { - name: "", - schemaId: header.column.columnDef.meta.schemaId, - type: "text", - table: "" - } - }), /* @__PURE__ */ bn.createElement("div", { - ...{ - onMouseDown: header.getResizeHandler(), - onTouchStart: header.getResizeHandler(), - className: `mk-resizer ${header.column.getIsResizing() ? "isResizing" : ""}` - } - })); - })))), /* @__PURE__ */ bn.createElement("tbody", null, table.getRowModel().rows.map((row) => /* @__PURE__ */ bn.createElement(bn.Fragment, null, /* @__PURE__ */ bn.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"] + fileMenu.addSeparator(); + fileMenu.addItem((menuItem) => { + menuItem.setTitle(i18n_default.menu.deleteFiles); + menuItem.setIcon("trash"); + menuItem.onClick((ev) => { + deleteFiles(plugin, files); + }); + }); + 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) ); - showContextMenu(e4, rowIndex); - }, - key: row.id - }, /* @__PURE__ */ bn.createElement("td", null), row.getVisibleCells().map( - (cell) => { - var _a2, _b2; - return cell.getIsGrouped() ? /* @__PURE__ */ bn.createElement("td", { - className: "mk-td-group", - colSpan: cols.length + (readMode ? 0 : 1) - }, /* @__PURE__ */ bn.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__ */ bn.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__ */ bn.createElement("tfoot", null, contextInfo.type == "folder" && !readMode ? /* @__PURE__ */ bn.createElement("tr", null, /* @__PURE__ */ bn.createElement("th", { - className: "mk-row-new", - colSpan: cols.length + (readMode ? 1 : 2), - onClick: () => { - newRow(); - } - }, "+ New")) : /* @__PURE__ */ bn.createElement(bn.Fragment, null))), j3( - /* @__PURE__ */ bn.createElement(DragOverlay, { - dropAnimation: null, - zIndex: 1600 - }, activeId ? /* @__PURE__ */ bn.createElement(ColumnHeader, { - plugin: props2.plugin, - editable: false, - column: { - name: activeId, - schemaId: tableData.schema.id, - type: "text", - table: "" - } - }) : null), - document.body - ))); -}; - -// src/components/ContextView/DataTypeView/BooleanCell.tsx -var BooleanCell = (props2) => { - const { initialValue, saveValue } = props2; - const [value, setValue] = bn.useState(initialValue == "true"); - const onChange = () => { - if (props2.editMode == -1 /* EditModeReadOnly */) { - return; - } - setValue(!value); - saveValue(!value ? "true" : "false"); - }; - h2(() => { - if (props2.editMode == 2 /* EditModeActive */) { - setValue(!value); - saveValue(!value ? "true" : "false"); - props2.setEditMode(null); - } - }, [props2.editMode]); - bn.useEffect(() => { - setValue(initialValue == "true"); - }, [initialValue]); - if (props2.editMode < 1 /* EditModeView */) { - return /* @__PURE__ */ bn.createElement("div", { - className: "mk-cell-checkbox-item" - }, /* @__PURE__ */ bn.createElement("input", { - type: "checkbox", - checked: value, - onChange - }), /* @__PURE__ */ bn.createElement("div", null, props2.column.name)); + }); + }); + 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(); + }); + }); } - return /* @__PURE__ */ bn.createElement("div", { - className: "mk-cell-text" - }, /* @__PURE__ */ bn.createElement("input", { - type: "checkbox", - checked: value, - onChange - })); + 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/ContextView/DataTypeView/ObjectCell.tsx -var ObjectCell = (props2) => { - const { initialValue, saveValue } = props2; - const [value, setValue] = bn.useState(safelyParseJSON(initialValue)); - const saveKey = (key2, newKey) => { - if (key2 != newKey) - saveValue({ - ...value, - [newKey]: value[key2], - [key2]: void 0 +var triggerFileMenu = (plugin, file, isFolder, e4) => { + const spaces2 = plugin.index.allSpaces(); + const spaceItems = retrieveSpaceItems(plugin, spaces2); + const cache = plugin.index.files.get(file.path); + const fileMenu = new import_obsidian24.Menu(); + if (isFolder) { + fileMenu.addSeparator(); + fileMenu.addItem((menuItem) => { + menuItem.setIcon("edit"); + menuItem.setTitle(i18n_default.buttons.createNote); + menuItem.onClick((ev) => { + newFileInFolder(plugin, file); }); - }; - const saveVal = (key2, val) => { - saveValue({ - ...value, - [key2]: val }); - }; - bn.useEffect(() => { - setValue(safelyParseJSON(initialValue)); - }, [initialValue]); - return /* @__PURE__ */ bn.createElement("div", { - className: "mk-cell-object" - }, Object.keys(value).map((f4) => /* @__PURE__ */ bn.createElement("div", { - className: "mk-cell-object-row" - }, /* @__PURE__ */ bn.createElement("input", { - onClick: (e4) => e4.stopPropagation(), - className: "mk-cell-text", - type: "text", - value: f4, - onBlur: (e4) => saveKey(f4, e4.target.value) - }), /* @__PURE__ */ bn.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) => { - const [vaultItem, setVaultItem] = p2(null); - const previewImage = F(() => { - 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 = F(() => { - return getAbstractFileAtPath(app, previewImage); - }, [previewImage]); - const loadIcon = () => { - setVaultItem(vaultItemForPath(props2.plugin, props2.file)); - }; - h2(() => { - loadIcon(); - window.addEventListener(eventTypes.spacesChange, loadIcon); - return () => { - window.removeEventListener(eventTypes.spacesChange, loadIcon); - }; - }, [props2.file]); - return previewImage ? /* @__PURE__ */ bn.createElement("div", { - className: "mk-file-preview", - style: { - backgroundSize: "cover", - backgroundPositionY: "50%", - backgroundImage: `url(${previewFile ? app.vault.getResourcePath(previewFile) : previewImage})` - } - }) : /* @__PURE__ */ bn.createElement("div", { - className: "mk-file-preview", - style: (vaultItem == null ? void 0 : vaultItem.color.length) > 0 ? { - "--label-color": `${vaultItem.color}`, - "--icon-color": `#ffffff` - } : { - "--label-color": `var(--background-secondary-alt)`, - "--icon-color": `var(--text-muted)` - } - }, /* @__PURE__ */ bn.createElement("div", { - className: "mk-file-icon", - dangerouslySetInnerHTML: (vaultItem == null ? void 0 : vaultItem.sticker) ? { __html: unifiedToNative(vaultItem.sticker) } : (vaultItem == null ? void 0 : vaultItem.folder) == "true" ? { __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 = fieldTypes.find((t4) => column.type == t4.type) || fieldTypes.find((t4) => column.type == t4.multiType); - if (!fieldType) { - return /* @__PURE__ */ bn.createElement(bn.Fragment, null); - } - if (fieldType.type == "preview") { - return /* @__PURE__ */ bn.createElement(PreviewCell, { - ...viewProps, - file, - row: props2.row, - columns: props2.cols + fileMenu.addItem((menuItem) => { + menuItem.setIcon("layout-dashboard"); + menuItem.setTitle(i18n_default.buttons.createCanvas); + menuItem.onClick((ev) => { + createNewCanvasFile(plugin, file, ""); + }); }); - } else if (fieldType.type == "file") { - return /* @__PURE__ */ bn.createElement(FileCell, { - isFolder: false, - ...viewProps, - multi: fieldType.multiType == column.type, - openFlow: props2.openFlow + 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(); + }); }); - } else if (fieldType.type == "boolean") { - return /* @__PURE__ */ bn.createElement(BooleanCell, { - ...viewProps, - column + } + 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(); }); - } else if (fieldType.type == "option") { - return /* @__PURE__ */ bn.createElement(OptionCell, { - ...viewProps, - options: column.value, - multi: fieldType.multiType == column.type, - saveOptions: saveFieldValue + }); + fileMenu.addItem((menuItem) => { + menuItem.setIcon("minus-square"); + menuItem.setTitle("Remove from Space"); + menuItem.onClick((ev) => { + let vaultChangeModal = new RemoveFromSpaceModal(plugin, file.path); + vaultChangeModal.open(); }); - } else if (fieldType.type == "date") { - return /* @__PURE__ */ bn.createElement(DateCell, { - ...viewProps + }); + if (isFolder) { + fileMenu.addSeparator(); + 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 + ); + }); }); - } else if (fieldType.type == "context") { - return /* @__PURE__ */ bn.createElement(ContextCell, { - ...viewProps, - multi: fieldType.multiType == column.type, - contextTable: props2.contextTable[column.value], - contextTag: column.value + } + fileMenu.addSeparator(); + fileMenu.addItem((menuItem) => { + menuItem.setTitle("Sort By"); + menuItem.setDisabled(true); + }); + fileMenu.addItem((menuItem) => { + menuItem.setTitle(i18n_default.menu.fileNameSortAlphaAsc); + menuItem.setChecked(cache.folderSort == "path_asc"); + menuItem.onClick((ev) => { + saveFolderSort(plugin, file.path, "path_asc"); }); - } else if (fieldType.type == "fileprop") { - return /* @__PURE__ */ bn.createElement(FilePropertyCell, { - ...viewProps + }); + fileMenu.addItem((menuItem) => { + menuItem.setTitle(i18n_default.menu.fileNameSortAlphaDesc); + menuItem.setChecked(cache.folderSort == "path_desc"); + menuItem.onClick((ev) => { + saveFolderSort(plugin, file.path, "path_desc"); }); - } else if (fieldType.type == "number") { - return /* @__PURE__ */ bn.createElement(NumberCell, { - ...viewProps + }); + fileMenu.addItem((menuItem) => { + menuItem.setTitle(i18n_default.menu.createdTimeSortAsc); + menuItem.setChecked(cache.folderSort == "ctime_asc"); + menuItem.onClick((ev) => { + saveFolderSort(plugin, file.path, "ctime_asc"); }); - } else if (fieldType.type == "link") { - return /* @__PURE__ */ bn.createElement(LinkCell, { - ...viewProps, - multi: fieldType.multiType == column.type, - file + }); + fileMenu.addItem((menuItem) => { + menuItem.setTitle(i18n_default.menu.createdTimeSortDesc); + menuItem.setChecked(cache.folderSort == "ctime_desc"); + menuItem.onClick((ev) => { + saveFolderSort(plugin, file.path, "ctime_desc"); }); - } else if (fieldType.type == "tag") { - return /* @__PURE__ */ bn.createElement(TagCell, { - ...viewProps, - multi: fieldType.multiType == column.type + }); + 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]); + } + ); }); - } else if (fieldType.type == "image") { - return /* @__PURE__ */ bn.createElement(ImageCell, { - ...viewProps + fileMenu.addItem((menuItem) => { + menuItem.setTitle(i18n_default.buttons.changeIcon); + menuItem.setIcon("lucide-sticker"); + menuItem.onClick((ev) => { + let vaultChangeModal = new stickerModal( + plugin.app, + (emoji) => saveFileIcon(plugin, file, emoji) + ); + vaultChangeModal.open(); + }); }); - } else if (fieldType.type == "object") { - return /* @__PURE__ */ bn.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__ */ bn.createElement(TextCell, { - ...viewProps + 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(); + }); }); -}; - -// src/components/ContextView/CardsView/CardColumnView.tsx -var CardColumnView = k3( - ({ - id: id2, - children, - columns = 1, - handleProps, - horizontal, - hover, - onClick, - onRemove, - plugin, - field, - label, - file, - placeholder: placeholder2, - style, - scrollable, - shadow, - unstyled, - ...props2 - }, ref) => { - const Component2 = "div"; - const { updateValue: updateValue2, updateFieldValue, contextTable } = q2(MDBContext); - return /* @__PURE__ */ bn.createElement(Component2, { - ...props2, - ref, - style: { - ...style, - "--columns": columns - }, - className: (0, import_classnames.default)( - "mk-list-group", - unstyled && "unstyled", - horizontal && "horizontal", - hover && "hover", - placeholder2 && "placeholder", - scrollable && "scrollable", - shadow && "shadow" - ), - onClick, - tabIndex: onClick ? 0 : void 0 - }, label != null && field ? /* @__PURE__ */ bn.createElement("div", { - className: "mk-list-group-header" - }, /* @__PURE__ */ bn.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__ */ bn.createElement("div", { - className: "Actions", - ...handleProps - })) : null, placeholder2 ? children : /* @__PURE__ */ bn.createElement("ul", null, children)); + 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); + } + }); + }); + 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(); + }); + }); } -); - -// src/components/ContextView/CardsView/CardView.tsx -var import_classnames2 = __toESM(require_classnames()); + 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/FlowEditor/FlowView.tsx -var FlowView = (props2) => { +// src/components/ContextView/DataTypeView/FileCell.tsx +var import_obsidian25 = require("obsidian"); +var FileCell = (props2) => { + const fileOrCleanPath = (f4) => { + if (!f4) + return { + path: "" + }; + const fileCache = props2.plugin.index.files.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 loadFile = async () => { - const div = ref.current; - const [link, refStr] = parseOutReferences(props2.path); - const type = viewTypeByString(link); - const portalType = type == "tag" || type == "folder" ? "context" : "doc"; - const leaf = await spawnLeafFromFile( - props2.plugin, - link, - div, - portalType, - refStr, - props2.from, - props2.to - ); + const onKeyDown = (e4) => { + e4.stopPropagation(); + e4.key == "Enter" && e4.target.blur(); }; - const toggleFlow = () => { - if (props2.load) { - loadFile(); + 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_obsidian25.Notice(i18n_default.notice.fileExists); } else { - ref.current.empty(); + props2.saveValue(ref.current.value); + props2.setEditMode(null); } }; - h2(() => { - toggleFlow(); - }, [props2.load, props2.path, props2.from, props2.to]); - return /* @__PURE__ */ bn.createElement("div", { - className: "mk-flowspace-editor", - ref - }); -}; - -// src/components/ContextView/CardsView/CardView.tsx -var CardView = bn.memo( - bn.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(e4.shiftKey ? 1 : e4.metaKey ? 2 : 0, value["_index"]); - } else if (e4.detail === 2) { - onSelect(3, value["_index"]); - } - }; - const { updateValue: updateValue2, updateFieldValue, contextTable } = q2(MDBContext); - h2(() => { - if (!dragOverlay) { - return; - } - document.body.style.cursor = "grabbing"; - return () => { - document.body.style.cursor = ""; - }; - }, [dragOverlay]); - const [openFlow, setOpenFlow] = p2(false); - return renderItem ? renderItem({ - dragOverlay: Boolean(dragOverlay), - dragging: Boolean(dragging), - sorting: Boolean(sorting), - index, - fadeIn: Boolean(fadeIn), - listeners, - ref, - style, - transform, - transition, - value - }) : /* @__PURE__ */ bn.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 - }, value && cols.filter((f4) => f4.type == "preview" && f4.table == "").map((f4) => /* @__PURE__ */ bn.createElement(DataTypeView, { - row: value, - cols, - plugin, - initialValue: value[f4.name + f4.table], - column: f4, - index: parseInt(id2), - file: value["File"], - editable: false, - updateValue: (v3) => updateValue2(f4.name, v3, f4.table, parseInt(id2), value["File"]), - updateFieldValue: (v3, fv) => updateFieldValue( - f4.name, - fv, - v3, - f4.table, - parseInt(id2), - value["File"] - ), - contextTable - })), /* @__PURE__ */ bn.createElement("div", { - className: "mk-list-content" - }, /* @__PURE__ */ bn.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__ */ bn.createElement(DataTypeView, { - openFlow: () => setOpenFlow((o3) => !o3), - plugin, - initialValue: value[f4.name + f4.table], - column: f4, - index: parseInt(id2), - file: value["File"], - editable: false, - updateValue: (v3) => updateValue2( - f4.name, - v3, - f4.table, - parseInt(id2), - value["File"] - ), - updateFieldValue: (v3, fv) => updateFieldValue( - f4.name, - fv, - v3, - f4.table, - parseInt(id2), - value["File"] - ), - contextTable - }) : /* @__PURE__ */ bn.createElement(bn.Fragment, null); - })), /* @__PURE__ */ bn.createElement(FlowView, { - plugin, - path: value.File, - load: openFlow - }))); + const newFile = async (file) => { + const filePath = file.path.replace(/\//g, "").replace(/\./g, ""); + const path = `${props2.folder}/${filePath}.md`; + if (filePath.length == 0) { + return; } - ) -); - -// 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; - 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__ */ bn.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 - }, - 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 = F(() => { - var _a3, _b3; - if (groupBy2) { - const options = uniq([ - "", - ...(_a3 = splitString(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) - }; - }, - { "": [] } + if (fileExists(path)) { + new import_obsidian25.Notice(i18n_default.notice.fileExists); + } else { + await createNewMarkdownFile( + props2.plugin, + getAbstractFileAtPath(app, props2.folder), + filePath ); } - return { - "": (_b3 = filteredData == null ? void 0 : filteredData.map((r3) => r3._index)) != null ? _b3 : [] - }; - }, [filteredData, predicate]); - const containers = F( - () => Object.keys(items).map((f4, i4) => "-" + i4.toString()), - [items] - ); - const [activeId, setActiveId] = p2(null); - const [overId, setOverId] = p2(null); - const recentlyMovedToNewContainer = _2(false); - const isSortingContainer = activeId ? containers.includes(activeId) : false; - const [lastSelectedIndex, setLastSelectedIndex] = p2(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(); + const deleteRow = () => { + props2.deleteRow(); }; - h2(() => { - requestAnimationFrame(() => { - recentlyMovedToNewContainer.current = false; - }); - }, [items]); - const selectItem = (modifier, index) => { - if (platformIsMobile()) { - const file = getAbstractFileAtPath( - app, - tableData.rows[parseInt(index)].File - ); - if (file) - openAFile(file, plugin, false); - return; + p2(() => { + var _a2; + if (props2.editMode == 2) { + (_a2 = ref == null ? void 0 : ref.current) == null ? void 0 : _a2.focus(); } - if (modifier == 3) { - const file = getAbstractFileAtPath( - app, - tableData.rows[parseInt(index)].File - ); - if (file) - openAFile(file, plugin, false); - return; + }, [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", { + className: "mk-cell-file-title" + }, v3 && v3.fileCache ? fileNameToString(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", { + className: "mk-cell-file-title" + }, v3.path); + } } - 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, - filteredData.map((f4) => f4._index) - ) - ]) - ); - } else { - selectRows(index, [index]); + 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 + ) + }, v3 && v3.fileCache ? filePathToString(v3.fileCache.name) : ""))); } - setLastSelectedIndex(index); + 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"; + } + 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 + ); + } + }, 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/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") { - selectRows(null, []); - setLastSelectedIndex(null); + setValue(initialValue); + e4.target.blur(); + props2.setEditMode(null); } - if (e4.key == "Enter") { - const file = getAbstractFileAtPath( - app, - tableData.rows[parseInt(lastSelectedIndex)].File - ); - if (file) - openAFile(file, plugin, false); - return; + }; + Cn.useEffect(() => { + setValue(initialValue); + }, [initialValue]); + p2(() => { + var _a2; + if (props2.editMode == 2) { + (_a2 = ref == null ? void 0 : ref.current) == null ? void 0 : _a2.focus(); } - if (e4.key == "ArrowDown") { - const newIndex = selectNextIndex( - lastSelectedIndex, - filteredData.map((f4) => f4._index) - ); - selectRows(newIndex, [newIndex]); - setLastSelectedIndex(newIndex); + }, [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); } - if (e4.key == "ArrowUp") { - const newIndex = selectPrevIndex( - lastSelectedIndex, - filteredData.map((f4) => f4._index) - ); - selectRows(newIndex, [newIndex]); - setLastSelectedIndex(newIndex); + if (e4.key == "Escape") { + setValue(initialValue); + e4.target.blur(); + props2.setEditMode(null); } }; - return /* @__PURE__ */ bn.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__ */ bn.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__ */ bn.createElement("div", { - className: "mk-list-view" - }, /* @__PURE__ */ bn.createElement(SortableContext, { - items: [...containers, PLACEHOLDER_ID], - strategy: vertical ? verticalListSortingStrategy : horizontalListSortingStrategy - }, containers.map((containerId) => /* @__PURE__ */ bn.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__ */ bn.createElement(SortableContext, { - items: items[Object.keys(items)[parseInt(containerId) * -1]], - strategy - }, items[Object.keys(items)[parseInt(containerId) * -1]].map( - (value, index) => { - return /* @__PURE__ */ bn.createElement(SortableItem, { - 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 - }); + Cn.useEffect(() => { + setValue(initialValue); + }, [initialValue]); + p2(() => { + var _a2; + if (props2.editMode == 2) { + (_a2 = ref == null ? void 0 : ref.current) == null ? void 0 : _a2.focus(); } - ))))))), j3( - /* @__PURE__ */ bn.createElement(DragOverlay, { - adjustScale: adjustScale2 - }, activeId ? containers.includes(activeId) ? renderContainerDragOverlay(activeId) : renderSortableItemDragOverlay(activeId) : null), - document.body - )); - function renderSortableItemDragOverlay(id2) { - return /* @__PURE__ */ bn.createElement("div", { - className: viewType == "card" ? "mk-cards-container" : "mk-list-container" - }, /* @__PURE__ */ bn.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 + }, [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); +}; + +// src/components/ContextView/TableView/TableView.tsx +var import_lodash7 = __toESM(require_lodash()); +var import_obsidian27 = require("obsidian"); + +// 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) { + 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); + } + getItemText(item) { + return item; + } + getSuggestions(query) { + let allImages = []; + if (query.match(urlRegex)) + allImages.push(query); + allImages.push( + ...getAllAbstractFilesInVault(this.plugin, app).filter( + (f4) => f4 instanceof import_obsidian26.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: [] + } })); } - function renderContainerDragOverlay(containerId) { - return /* @__PURE__ */ bn.createElement(CardColumnView, { - 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__ */ bn.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 - }) - )); + getItems() { + let allImages = []; + allImages.push( + ...getAllAbstractFilesInVault(this.plugin, app).filter( + (f4) => f4 instanceof import_obsidian26.TFile && ["png", "jpg", "jpeg"].contains(f4.extension) + ).map((f4) => f4.path) + ); + return allImages; } - function getNextContainerId() { - const containeIds = Object.keys(items); - const lastContaineId = containeIds[containeIds.length - 1]; - return String.fromCharCode(lastContaineId.charCodeAt(0) + 1); + onChooseItem(item, evt) { + this.selectImage(item); } }; -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 SortableItem({ - 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 + +// 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) + ); + 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/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 mounted = useMountStatus(); - const mountedWhileDragging = isDragging && !mounted; - return /* @__PURE__ */ bn.createElement(CardView, { - ref: disabled ? void 0 : setNodeRef, + p2(() => { + var _a3; + setValue( + resolveLinks( + stringValueToLink( + props2.multi ? (_a3 = parseMultiString(props2.initialValue)) != null ? _a3 : [] : [props2.initialValue] + ) + ) + ); + }, [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 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, + editable: true, + value: value.map((f4) => f4.value), + options: _options, + saveOptions, + placeholder: i18n_default.labels.linkItemSelectPlaceholder, + detail: true, + searchable: 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)); + } + }; + 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, - 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 + 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 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 { + 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 }); -} -function useMountStatus() { - const [isMounted, setIsMounted] = p2(false); - h2(() => { - const timeout = setTimeout(() => setIsMounted(true), 500); - return () => clearTimeout(timeout); - }, []); - return isMounted; -} - -// src/components/ContextView/FlowListView/FlowListView.tsx -var import_obsidian20 = require("obsidian"); -var FlowListView = (props2) => { - const { filteredData: data } = q2(MDBContext); - const flowItems = F(() => { - return data.map((f4) => getAbstractFileAtPath(app, f4.File)).filter((f4) => f4 instanceof import_obsidian20.TFile && f4.extension == "md"); - }, [data]); - return /* @__PURE__ */ bn.createElement("div", { - className: "mk-flow-container" - }, flowItems.map((f4) => /* @__PURE__ */ bn.createElement("div", null, /* @__PURE__ */ bn.createElement("span", null, fileNameToString(f4.name)), /* @__PURE__ */ bn.createElement(FlowView, { - plugin: props2.plugin, - path: f4.path, - load: true - })))); -}; - -// 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__ */ bn.createElement(FlowListView, { - plugin: props2.plugin - }) : schema.type == "table" ? /* @__PURE__ */ bn.createElement(TableView, { - plugin: props2.plugin - }) : /* @__PURE__ */ bn.createElement(CardsView, { - plugin: props2.plugin - }) : /* @__PURE__ */ bn.createElement(bn.Fragment, null); -}; - -// src/components/ContextView/EmbedContextViewComponent.tsx -var EmbedContextViewComponent = (props2) => { - const context = mdbContextByContextPath(props2.plugin, props2.path); - return /* @__PURE__ */ bn.createElement(MDBProvider, { - plugin: props2.plugin, - context, - schema: props2.schema - }, context && /* @__PURE__ */ bn.createElement(ContextListView, { - plugin: props2.plugin - })); }; -// src/components/ContextView/EmbedContextView.tsx -var EMBED_CONTEXT_VIEW_TYPE = "make-inline-context"; -var EmbedContextView = class extends import_obsidian21.ItemView { - constructor(leaf, plugin) { - super(leaf); - this.navigation = true; - this.plugin = plugin; - } - getViewType() { - return EMBED_CONTEXT_VIEW_TYPE; - } - getDisplayText() { - return this.file; - } - async onClose() { - this.destroy(); - } - destroy() { - if (this.root) - this.root.unmount(); - } - async onOpen() { - this.destroy(); - } - async setState(state, result) { - var _a2, _b2; - this.file = state.file; - this.ref = state.ref ? state.ref.substring(1, state.ref.length) : null; - this.constructInlineContext(this.file); - await super.setState(state, result); - const type = viewTypeByString(this.file); - const title = type == "tag" ? this.file : (_b2 = (_a2 = getAbstractFileAtPath(app, this.file)) == null ? void 0 : _a2.name) != null ? _b2 : this.file; - 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; +// 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(); } - return; - } - getState() { - let state = super.getState(); - state.file = this.file; - return state; - } - constructInlineContext(file) { - this.destroy(); - this.root = createRoot(this.contentEl); - this.root.render( - /* @__PURE__ */ bn.createElement("div", null, /* @__PURE__ */ bn.createElement(EmbedContextViewComponent, { - plugin: this.plugin, - path: this.file, - schema: this.ref - })) - ); - } -}; - -// src/components/FlowEditor/FlowEditor.tsx -var import_obsidian22 = require("obsidian"); -var popovers = /* @__PURE__ */ new WeakMap(); -var mouseCoords = { x: 0, y: 0 }; -function nosuper(base) { - const derived = function() { - return Object.setPrototypeOf(new import_obsidian22.Component(), new.target.prototype); + }, [currentEdit]); + const saveColsSize = (colSize) => { + const newColSize = colSize(colsSize); + setColsSize(newColSize); + debouncedSavePredicate(newColSize); }; - derived.prototype = base.prototype; - return Object.setPrototypeOf(derived, base); -} -var _a, _b, _c, _d, _e; -var FlowEditor = class extends nosuper(import_obsidian22.HoverPopover) { - constructor(parent, targetEl, plugin, waitTime, onShowCallback) { - super(); - this.targetEl = targetEl; - this.plugin = plugin; - this.onShowCallback = onShowCallback; - this.abortController = this.addChild(new import_obsidian22.Component()); - this.detaching = false; - this.opening = false; - this.rootSplit = new import_obsidian22.WorkspaceSplit( - window.app.workspace, - "vertical" + const debouncedSavePredicate = T2( + (0, import_lodash7.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) + }); + } + }; + const toggleFlow = (path) => { + setOpenFlows( + (f4) => f4.find((p3) => p3 == path) ? f4.filter((p3) => p3 != path) : uniq([...f4, path]) ); - 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; + }; + const selectItem = (modifier, index) => { + if (modifier == 3) { + const file = getAbstractFileAtPath( + app, + tableData.rows[parseInt(index)].File + ); + if (file) + openAFile(file, props2.plugin, false); + return; } - this.onTarget = true; - this.parent = parent; - this.waitTime = waitTime; - this.state = import_obsidian22.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); + 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]); } - 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); - } + 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 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(); } - 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; + 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 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((he) => he); - } - 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(); + return; } - let leafCount = 0; - this.plugin.app.workspace.iterateLeaves((leaf) => { - leafCount++; - }, this.rootSplit); - if (leafCount === 0) { - this.hide(); - } else if (leafCount > 1) { + if (e4.key == "ArrowDown") { + nextRow(); + e4.preventDefault(); } - 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); - 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_obsidian22.WorkspaceTabs) { - this.rootSplit.replaceChild(index, item.children[0]); + if (e4.key == "ArrowUp") { + lastRow(); + e4.preventDefault(); + } + if (e4.key == "ArrowLeft") { + const newIndex = selectPrevIndex( + selectedColumn, + columns.map((f4) => f4.accessorKey).filter((f4) => f4 != "+") + ); + 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 == 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) } - }); - }) - ); - } - leaves() { - const leaves = []; - this.plugin.app.workspace.iterateLeaves((leaf) => { - leaves.push(leaf); - }, this.rootSplit); - return leaves; - } - 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); + ] + ]; + }, + [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 }, - { once: true, capture: true } - ); - if (this.parent) { - this.parent.flowEditor = this; + grouping: groupBy2, + expanded: true + }, + onColumnSizingChange: saveColsSize, + getCoreRowModel: getCoreRowModel(), + getExpandedRowModel: getExpandedRowModel(), + getGroupedRowModel: getGroupedRowModel(), + meta: { + updateData: updateValue2, + updateFieldValue } - const viewHeaderEl = this.hoverEl.querySelector(".view-header"); - viewHeaderEl == null ? void 0 : viewHeaderEl.remove(); - const sizer = this.hoverEl.querySelector(".workspace-leaf"); - this.hoverEl.appendChild(sizer); - const inlineTitle = this.hoverEl.querySelector(".inline-title"); - inlineTitle == null ? void 0 : inlineTitle.remove(); - (_b2 = this.onShowCallback) == null ? void 0 : _b2.call(this); - this.onShowCallback = void 0; - } - transition() { - if (this.shouldShow()) { - if (this.state === import_obsidian22.PopoverState.Hiding) { - this.state = import_obsidian22.PopoverState.Shown; - clearTimeout(this.timer); + }); + const sensors = useSensors( + useSensor(MouseSensor, { + activationConstraint: { + distance: 10 } - } else { - if (this.state === import_obsidian22.PopoverState.Showing) { - this.hide(); - } else { - if (this.state === import_obsidian22.PopoverState.Shown) { - this.state = import_obsidian22.PopoverState.Hiding; - this.timer = window.setTimeout(() => { - if (this.shouldShow()) { - this.transition(); - } else { - this.hide(); - } - }, this.waitTime); - } + }), + useSensor(TouchSensor, { + activationConstraint: { + delay: 250, + tolerance: 5 } + }) + ); + const measuring = { + droppable: { + strategy: MeasuringStrategy.Always } + }; + function handleDragStart(event) { + const { + active: { id: activeId2 } + } = event; + setActiveId(activeId2); + setOverId(overId); + document.body.style.setProperty("cursor", "grabbing"); } - shouldShow() { - return this.shouldShowSelf() || this.shouldShowChild(); + 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); + } } - shouldShowChild() { - return FlowEditor.activePopovers().some((popover) => { - if (popover !== this && popover.targetEl && this.hoverEl.contains(popover.targetEl)) { - return popover.shouldShow(); - } - return false; + const saveFilter = (filter) => { + savePredicate({ + ...predicate, + filters: [ + ...predicate.filters.filter((s5) => s5.field != filter.field), + filter + ] }); - } - shouldShowSelf() { - return !this.detaching && !!(this.onTarget || this.state == import_obsidian22.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_obsidian22.PopoverState.Shown; - this.timer = 0; - this.shownPos = mouseCoords; - this.targetEl.replaceChildren(this.hoverEl); - this.onShow(); - app.workspace.onLayoutChange(); - this.load(); + }; + const selectCell = (e4, index, column) => { + if (platformIsMobile() || column == "+") + 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_obsidian27.Menu(); + menu.addItem((item) => { + item.setIcon("trash"); + item.setTitle(i18n_default.menu.deleteRow); + item.onClick(() => { + deleteRow(index); + }); + }); + if (isMouseEvent(e4)) { + menu.showAtPosition({ x: e4.pageX, y: e4.pageY }); } else { - this.hide(); + 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) + ) + }); } - onHide() { - var _a2; - this.oldPopover = null; - if (((_a2 = this.parent) == null ? void 0 : _a2.flowEditor) === this) { - this.parent.flowEditor = null; - } + function handleDragCancel() { + resetState(); } - hide() { + 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, + 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; - this.onTarget = false; - this.detaching = true; - if (this.timer) { - clearTimeout(this.timer); - this.timer = 0; + 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 + ) + }) : /* @__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" + } + } + }, 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() + )); } - this.hoverEl.hide(); - if (this.opening) + ))))), /* @__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), + 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/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; - const leaves = this.leaves(); - if (leaves.length) { - leaves.forEach((leaf) => leaf.detach()); + } + 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 + }), /* @__PURE__ */ Cn.createElement("div", null, props2.column.name)); + } + return /* @__PURE__ */ Cn.createElement("div", { + className: "mk-cell-text" + }, /* @__PURE__ */ Cn.createElement("input", { + type: "checkbox", + checked: value, + onChange + })); +}; + +// 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 + }); + }; + 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) => { + 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.files.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: (vaultItem == null ? void 0 : vaultItem.color.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) } : (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 + }); + } else if (fieldType.type == "file") { + return /* @__PURE__ */ Cn.createElement(FileCell, { + isFolder: false, + ...viewProps, + multi: fieldType.multiType == column.type, + openFlow: props2.openFlow + }); + } 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 + }); + } else if (fieldType.type == "context") { + return /* @__PURE__ */ Cn.createElement(ContextCell, { + ...viewProps, + multi: fieldType.multiType == column.type, + contextTable: props2.contextTable[column.value], + contextTag: column.value + }); + } else if (fieldType.type == "fileprop") { + return /* @__PURE__ */ Cn.createElement(LookUpCell, { + ...viewProps, + file + }); + } else if (fieldType.type == "number") { + return /* @__PURE__ */ Cn.createElement(NumberCell, { + ...viewProps + }); + } else if (fieldType.type == "link") { + return /* @__PURE__ */ Cn.createElement(LinkCell, { + ...viewProps, + multi: fieldType.multiType == column.type, + file + }); + } else if (fieldType.type == "tag") { + return /* @__PURE__ */ Cn.createElement(TagCell, { + ...viewProps, + multi: fieldType.multiType == column.type + }); + } else if (fieldType.type == "image") { + return /* @__PURE__ */ Cn.createElement(ImageCell, { + ...viewProps + }); + } else if (fieldType.type == "object") { + return /* @__PURE__ */ Cn.createElement(ObjectCell, { + ...viewProps + }); + } + return /* @__PURE__ */ Cn.createElement(TextCell, { + ...viewProps + }); +}; + +// src/components/ContextView/CardsView/CardColumnView.tsx +var CardColumnView = k3( + ({ + id: id2, + children, + columns = 1, + handleProps, + horizontal, + hover, + onClick, + onRemove, + plugin, + field, + label, + file, + placeholder: placeholder2, + 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", + placeholder2 && "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, placeholder2 ? children : /* @__PURE__ */ Cn.createElement("ul", null, children)); + } +); + +// src/components/ContextView/CardsView/CardView.tsx +var import_classnames3 = __toESM(require_classnames()); + +// src/components/FlowEditor/FlowView.tsx +var FlowView = (props2) => { + const ref = _2(null); + const loadFile = async () => { + const div = ref.current; + const { + path: link2, + ref: refStr, + type + } = pathByString(props2.plugin, props2.path); + const portalType = type == "tag" || type == "folder" ? "context" : "doc"; + await spawnLeafFromFile( + props2.plugin, + link2, + div, + portalType, + refStr, + props2.from, + props2.to + ); + }; + const toggleFlow = () => { + if (props2.load) { + loadFile(); } else { - this.parent = null; - (_a2 = this.abortController) == null ? void 0 : _a2.unload(); - this.abortController = void 0; - return this.nativeHide(); + ref.current.empty(); } - } - nativeHide() { - var _a2; - const { hoverEl, targetEl } = this; - this.state = import_obsidian22.PopoverState.Hidden; - hoverEl.detach(); - if (targetEl) { - const parent = targetEl.matchParent(".mk-hover-popover"); - if (parent) - (_a2 = popovers.get(parent)) == null ? void 0 : _a2.transition(); + }; + p2(() => { + toggleFlow(); + }, [props2.load, props2.path, props2.from, props2.to]); + return /* @__PURE__ */ Cn.createElement("div", { + className: "mk-flowspace-editor", + ref + }); +}; + +// 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(e4.shiftKey ? 1 : e4.metaKey ? 2 : 0, value["_index"]); + } else if (e4.detail === 2) { + onSelect(3, value["_index"]); + } + }; + const { updateValue: updateValue2, updateFieldValue, contextTable } = q2(MDBContext); + p2(() => { + if (!dragOverlay) { + return; + } + 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 + }))); } - this.onHide(); - this.unload(); - } - resolveLink(linkText, sourcePath) { - const link = (0, import_obsidian22.parseLinktext)(linkText); - const tFile = link ? this.plugin.app.metadataCache.getFirstLinkpathDest( - link.path, - sourcePath != null ? sourcePath : "" - ) : null; - return tFile; - } - 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(); + ) +); + +// 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; + 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, { + 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, + 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) + }; + }, + { "": [] } + ); } - this.plugin.app.workspace.setActiveLeaf(leaf); - return leaf; - } - buildState(parentMode, eState) { return { - active: false, - state: {}, - eState + "": (_b3 = filteredData == null ? void 0 : filteredData.map((r3) => r3._index)) != null ? _b3 : [] }; - } - buildEphemeralState(file, link) { - const cache = this.plugin.app.metadataCache.getFileCache(file); - const subpath = cache ? (0, import_obsidian22.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; + }, [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 eState; - } -}; - -// src/utils/flow/flowEditor.ts -var import_obsidian23 = require("obsidian"); -var parseOutReferences = (ostr) => { - const str = ostr.split("|")[0]; - const refIndex = str.lastIndexOf("#"); - return refIndex != -1 ? [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]; + return "-" + Object.keys(items).findIndex((key2) => items[key2].includes(id2)).toString(); + }; + const getIndex = (id2) => { + const container = findContainer(id2); + if (!container) { + return -1; } - 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) + 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; + }); + }, [items]); + const selectItem = (modifier, index) => { + if (platformIsMobile()) { + const file = getAbstractFileAtPath( + app, + tableData.rows[parseInt(index)].File + ); + if (file) + openAFile(file, plugin, false); return; - let dom = el; - while (!dom.hasClass("mk-floweditor") && !dom.hasClass("workspace") && dom.parentElement) { - dom = dom.parentElement; } - if (!dom.hasClass("mk-floweditor") && !dom.hasClass("workspace") && !(dom.nodeName == "HTML")) { + if (modifier == 3) { + const file = getAbstractFileAtPath( + app, + tableData.rows[parseInt(index)].File + ); + if (file) + openAFile(file, plugin, false); return; } - setTimeout(async () => { - var _a2; - let leafFound = false; - if (app.workspace.activeEditor) { - if (app.workspace.activeEditor.editMode.cm.dom == view.dom) { - leafFound = true; - loadFlowEditorsForLeafForID( - app.workspace.activeEditor.editMode.cm, - (_a2 = app.workspace.activeEditor.file) == null ? void 0 : _a2.path, - make, - id2 - ); - } - } - if (!leafFound) { - app.workspace.iterateLeaves((leaf) => { - var _a3, _b2; - const cm = (_a3 = leaf.view.editor) == null ? void 0 : _a3.cm; - if (cm && view.dom == cm.dom) { - leafFound = true; - loadFlowEditorsForLeafForID( - cm, - (_b2 = leaf.view.file) == null ? void 0 : _b2.path, - make, - id2 - ); - } - }, app.workspace["rootSplit"]); - } - }); - }); -}; -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 [link, ref] = parseOutReferences(flowEditorInfo2.link); - if (dom) { - if (link.charAt(0) == "#") { - if (!dom.hasAttribute("ready")) { - dom.setAttribute("ready", ""); - createFlowEditorInElement( - flowEditorInfo2.id, - dom, - ref ? "block" : "flow", - link - ); - } - 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, + filteredData.map((f4) => f4._index) + ) + ]) + ); + } else { + selectRows(index, [index]); } - if (link.charAt(link.length - 1) == "/") { - const folder = getAbstractFileAtPath( + setLastSelectedIndex(index); + }; + const onKeyDown = (e4) => { + if (e4.key == "Escape") { + selectRows(null, []); + setLastSelectedIndex(null); + } + if (e4.key == "Enter") { + const file = getAbstractFileAtPath( app, - link.substring(0, link.length - 1) + tableData.rows[parseInt(lastSelectedIndex)].File ); - if (!dom.hasAttribute("ready") && folder) { - dom.setAttribute("ready", ""); - createFlowEditorInElement( - flowEditorInfo2.id, - dom, - "context", - folder.path, - ref - ); - return; - } + if (file) + openAFile(file, plugin, false); + return; } - const file = getFileFromString(link, source); - const aFile = getAbstractFileAtPath(app, link); - 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] - ); + 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 } - } else { - if (aFile instanceof import_obsidian23.TFolder) { - if (!dom.hasAttribute("ready")) { - dom.setAttribute("ready", ""); - createFlowEditorInElement( - flowEditorInfo2.id, - dom, - ref ? "block" : "flow", - link - ); - } + }, + 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; } - 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(), link); - loadFlowEditor(cm, flowEditorInfo2, source, make); - }; - createDiv.setText(`"${link}" ` + i18n_default.labels.noFile); - createDiv.addEventListener("click", createFile); - } - } -}; -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) - }); - } - } - } - } + const activeContainer = findContainer(active.id); + if (!activeContainer) { + 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) - }); - } - } + const overId2 = over == null ? void 0 : over.id; + if (!overId2) { + resetState(); + return; } - }, app.workspace["rootSplit"]); - } -}; -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 spawnLeafFromFile = async (plugin, file, el, type, ref, from, to) => { - var _a2; - if (type == "context") { - const newLeaf2 = spawnPortal(plugin, el); - newLeaf2.setViewState({ - type: EMBED_CONTEXT_VIEW_TYPE, - state: { file: removeTrailingSlashFromFolder(file), ref } - }); - return newLeaf2; - } - let portalFile = plugin.app.vault.getAbstractFileByPath(file); - if (!portalFile || !Object.keys(app.embedRegistry.embedByExtension).some( - (f4) => f4 == portalFile.extension - )) - return; - const newLeaf = spawnPortal(plugin, el, portalFile.name); - await newLeaf.openFile(portalFile, { active: false }); - 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])] - }); - } - return newLeaf; -}; -var spawnNewPortal = async (plugin, evt) => { - var _a2, _b2, _c2; - const { file, el, ref, from, to, type } = evt.detail; - const newLeaf = await spawnLeafFromFile(plugin, file, el, type, ref); - if (!((_a2 = newLeaf == null ? void 0 : newLeaf.view) == null ? void 0 : _a2.editor)) { - return; - } - 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 (overId2 === PLACEHOLDER_ID) { + return; } - } - if (e4.key == "ArrowDown") { - if (e4.metaKey == true) { - view.dispatch({ - annotations: arrowKeyAnnotation.of(4) - }); - } else { - view.dispatch({ - annotations: arrowKeyAnnotation.of(2) - }); + 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] + ), + "" + ); + } } - } - }); - if (from && to) { - (_c2 = newLeaf.view.editor) == null ? void 0 : _c2.cm.dispatch({ - annotations: [editableRange.of([from, to])] - }); - } -}; -var spawnPortal = (plugin, initiatingEl, fileName, onShowCallback) => { - const parent = plugin.app.workspace.activeLeaf; - if (!initiatingEl) - initiatingEl = parent.containerEl; - const hoverPopover = new FlowEditor( - parent, - initiatingEl, + 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, - void 0, - onShowCallback - ); - if (fileName) - hoverPopover.titleEl.textContent = fileName.substring( - 0, - fileName.lastIndexOf(".") - ); - return hoverPopover.attachLeaf(); -}; - -// src/components/ui/modals/mergeColumnModal.ts -var import_obsidian24 = require("obsidian"); -var MergeColumnModal = class extends import_obsidian24.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); + 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 + }); } - 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(); - } -}; - -// src/components/ui/modals/saveViewModal.ts -var import_obsidian25 = require("obsidian"); -var SaveViewModal = class extends import_obsidian25.Modal { - constructor(schema, saveSchema, action) { - super(app); - this.schema = schema; - this.saveSchema = saveSchema; - this.action = action; + ))))))), 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 + })); } - 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(); - }; - changeButton.addEventListener("click", onClickAction); - inputEl.addEventListener("keydown", (e4) => { - if (e4.key === "Enter") { - e4.preventDefault(); - onClickAction(); - } - }); + function renderContainerDragOverlay(containerId) { + return /* @__PURE__ */ Cn.createElement(CardColumnView, { + 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 + }) + )); } - onClose() { - let { contentEl } = this; - contentEl.empty(); + 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; +} -// src/components/ContextView/FilterBar/FilterBar.tsx +// src/components/ContextView/FlowListView/FlowListView.tsx var import_obsidian28 = 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_obsidian28.TFile && f4.extension == "md"); + }, [data]); + 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 + })))); +}; -// src/components/ContextView/FilterBar/SearchBar.tsx -var SearchBar = (props2) => { - const clearSearch = () => { - props2.setSearchString(""); - }; - return /* @__PURE__ */ bn.createElement("div", { - className: "mk-view-search" - }, /* @__PURE__ */ bn.createElement("button", { - dangerouslySetInnerHTML: { __html: uiIconSet["mk-ui-search"] } - }), /* @__PURE__ */ bn.createElement(bn.Fragment, null, /* @__PURE__ */ bn.createElement("input", { - onChange: (e4) => props2.setSearchString(e4.target.value), - placeholder: i18n_default.labels.searchPlaceholder, - className: "mk-search-bar" - }), /* @__PURE__ */ bn.createElement("button", { - dangerouslySetInnerHTML: { __html: uiIconSet["mk-ui-clear"] }, - onClick: () => clearSearch() - }))); +// 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/ui/modals/syncMetadataModal.tsx -var import_obsidian26 = require("obsidian"); -var SyncMetadataModal = class extends import_obsidian26.Modal { - constructor(plugin, files, syncColumns, fields) { - super(plugin.app); +// src/components/ContextView/EmbedContextViewComponent.tsx +var EmbedContextViewComponent = (props2) => { + const context = mdbContextByPath(props2.plugin, props2.path); + return /* @__PURE__ */ Cn.createElement(MDBProvider, { + plugin: props2.plugin, + context, + schema: props2.schema + }, context && /* @__PURE__ */ Cn.createElement(ContextListView, { + plugin: props2.plugin + })); +}; + +// src/components/ContextView/EmbedContextView.tsx +var EMBED_CONTEXT_VIEW_TYPE = "make-inline-context"; +var EmbedContextView = class extends import_obsidian29.ItemView { + constructor(leaf, plugin) { + super(leaf); + this.navigation = true; this.plugin = plugin; - this.files = files; - let closeButton = this.modalEl.querySelector( - ".modal-close-button" - ); - closeButton.style.display = "none"; - this.syncColumns = syncColumns; - this.fields = fields; } - 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__ */ bn.createElement(SyncMetadataComponent, { - plugin: this.plugin, - files: this.files, - syncColumns: this.syncColumns, - close: () => this.close(), - columns: this.fields - }) - ); + getViewType() { + return EMBED_CONTEXT_VIEW_TYPE; } - onClose() { - let { contentEl } = this; - contentEl.empty(); + getDisplayText() { + return this.contextPath; } -}; -var metadatTypeFilterPredicate = (value, index, self2) => { - return self2.findIndex( - (v3) => value["type"] == v3["type"] && value["name"] == v3["name"] - ) === index; -}; -var SyncMetadataComponent = (props2) => { - const { plugin } = props2; - const cols = props2.files.reduce((p3, c4) => { - const fm = frontMatterForFile(c4); - const fmKeys = uniqCaseInsensitive(frontMatterKeys(fm)); - if (props2.plugin.dataViewAPI()) { - const dvValues = props2.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); - } - return [ - ...p3, - ...fmKeys.map((f4) => ({ name: f4, type: "fm" })) - ].filter(metadatTypeFilterPredicate); - }, []); - const [syncColumns, setSyncColumns] = p2( - cols.filter( - (f4) => props2.columns ? !props2.columns.some((g4) => g4.name == f4.name) : true - ) - ); - const [table, setTable] = p2(""); - const toggleColumn = (column) => { - if (syncColumns.find((f4) => f4.name == column.name && f4.type == column.type)) { - setSyncColumns( - (s5) => s5.filter((f4) => !(f4.name == column.name && f4.type == column.type)) - ); - } else { - setSyncColumns((s5) => [...s5, column]); + async onClose() { + this.destroy(); + } + destroy() { + if (this.root) + this.root.unmount(); + } + async onOpen() { + 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); + 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; + const headerEl = this.leaf.view.headerEl; + if (headerEl) { + headerEl.querySelector(".view-header-title").innerText = title; } - }; - const saveContexts = (_7, value) => { - setTable(value[0]); - }; - 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: [ - { name: "Folder", value: "" }, - ...f4.map((m5) => ({ name: m5, value: m5 })) - ], - saveOptions: saveContexts, - placeholder: i18n_default.labels.tagItemSelectPlaceholder, - searchable: true, - showAll: true - } + return; + } + getState() { + let state = super.getState(); + state.contextPath = this.contextPath; + return state; + } + constructInlineContext(file) { + this.destroy(); + this.root = createRoot(this.contentEl); + this.root.render( + /* @__PURE__ */ Cn.createElement("div", null, /* @__PURE__ */ Cn.createElement(EmbedContextViewComponent, { + plugin: this.plugin, + path: this.contextPath, + schema: this.ref + })) ); - }; - const sync = () => { - props2.syncColumns(syncColumns, table); - props2.close(); - }; - return /* @__PURE__ */ bn.createElement("div", { - className: "modal-content" - }, /* @__PURE__ */ bn.createElement("div", { - className: "setting-item setting-item-heading" - }, i18n_default.labels.syncProperties), /* @__PURE__ */ bn.createElement("div", { - className: "setting-item" - }, i18n_default.descriptions.syncProperties), /* @__PURE__ */ bn.createElement("div", { - className: "setting-item" - }, /* @__PURE__ */ bn.createElement("div", { - className: "setting-item-info" - }, /* @__PURE__ */ bn.createElement("div", { - className: "setting-item-name" - }, i18n_default.labels.selectContext), /* @__PURE__ */ bn.createElement("div", { - className: "setting-item-description" - }, i18n_default.descriptions.selectContext)), /* @__PURE__ */ bn.createElement("div", { - className: "setting-item-control" - }, /* @__PURE__ */ bn.createElement("button", { - onClick: (e4) => showContextMenu(e4) - }, table == "" ? i18n_default.buttons.currentFolder : table))), /* @__PURE__ */ bn.createElement("div", { - className: "setting-item" - }, /* @__PURE__ */ bn.createElement("div", { - className: "setting-item-info" - }, /* @__PURE__ */ bn.createElement("div", { - className: "setting-item-name" - }, i18n_default.labels.syncProperties), /* @__PURE__ */ bn.createElement("div", { - className: "setting-item-description" - }, i18n_default.descriptions.syncMetadata), cols.map((f4, index) => /* @__PURE__ */ bn.createElement("div", { - className: "mobile-option-setting-item" - }, /* @__PURE__ */ bn.createElement("input", { - type: "checkbox", - checked: syncColumns.some( - (g4) => g4.name == f4.name && g4.type == f4.type - ), - onChange: () => toggleColumn(f4) - }), /* @__PURE__ */ bn.createElement("span", { - className: "mobile-option-setting-item-name" - }, f4.name, /* @__PURE__ */ bn.createElement("span", { - className: "nav-file-tag" - }, f4.type)))))), /* @__PURE__ */ bn.createElement("button", { - style: { marginRight: 8 }, - onClick: () => sync() - }, i18n_default.buttons.sync), /* @__PURE__ */ bn.createElement("button", { - onClick: () => props2.close() - }, i18n_default.buttons.cancel)); + } }; -// src/components/ContextView/FilterBar/TagSelector.tsx -var import_lodash7 = __toESM(require_lodash()); - -// src/components/ContextView/TagsView/TagsView.tsx -var import_obsidian27 = require("obsidian"); -var TagsView = (props2) => { - const showTagMenu = (e4, tag) => { - e4.stopPropagation(); - e4.preventDefault(); - const menu = new import_obsidian27.Menu(); - menu.addItem((menuItem) => { - menuItem.setIcon("hash"); - menuItem.setTitle(i18n_default.menu.openTag); - menuItem.onClick(() => { - openContext(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 }); +// src/components/FlowEditor/FlowEditor.tsx +var import_obsidian30 = require("obsidian"); +var popovers = /* @__PURE__ */ new WeakMap(); +var mouseCoords = { x: 0, y: 0 }; +function nosuper(base) { + const derived = function() { + return Object.setPrototypeOf(new import_obsidian30.Component(), new.target.prototype); }; - 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: (_7, value) => props2.addTag(value[0]), - placeholder: i18n_default.labels.contextItemSelectPlaceholder, - searchable: true, - showAll: true - } + derived.prototype = base.prototype; + return Object.setPrototypeOf(derived, base); +} +var _a, _b, _c, _d, _e; +var FlowEditor = class extends nosuper(import_obsidian30.HoverPopover) { + constructor(parent, targetEl, plugin, waitTime, onShowCallback) { + super(); + this.targetEl = targetEl; + this.plugin = plugin; + this.onShowCallback = onShowCallback; + this.abortController = this.addChild(new import_obsidian30.Component()); + this.detaching = false; + this.opening = false; + this.rootSplit = new import_obsidian30.WorkspaceSplit( + window.app.workspace, + "vertical" ); - }; - return /* @__PURE__ */ bn.createElement("div", { - className: "mk-tag-selector" - }, props2.tags.map((f4, i4) => /* @__PURE__ */ bn.createElement("div", { - onContextMenu: (e4) => showTagMenu(e4, f4), - onClick: (e4) => openContext(f4, props2.plugin, e4.metaKey) - }, /* @__PURE__ */ bn.createElement("span", { - className: "cm-hashtag cm-hashtag-begin" - }, "#"), /* @__PURE__ */ bn.createElement("span", { - className: "cm-hashtag cm-hashtag-end" - }, stringFromTag(f4)))), props2.addTag && /* @__PURE__ */ bn.createElement("button", { - "aria-label": i18n_default.buttons.addTag, - onClick: (e4) => showContextMenu(e4) - }, /* @__PURE__ */ bn.createElement("div", { - className: "mk-icon-xsmall", - dangerouslySetInnerHTML: { __html: uiIconSet["mk-ui-plus"] } - })), props2.syncTags && /* @__PURE__ */ bn.createElement("button", { - "aria-label": i18n_default.buttons.syncFields, - onClick: (e4) => props2.syncTags() - }, /* @__PURE__ */ bn.createElement("div", { - className: "mk-icon-xsmall", - dangerouslySetInnerHTML: { __html: uiIconSet["mk-ui-sync"] } - }))); -}; - -// src/components/ContextView/FilterBar/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); - removeSourceFromTag(props2.plugin, value, contextInfo.dbPath); - saveSchema({ - ...dbSchema, - def: tags.join("&") - }); - }; - const addTag2 = async (tag) => { - const tags = (0, import_lodash7.uniq)([...tagContexts, tag]); - tags.forEach((tag2) => { - initiateContextIfNotExists(props2.plugin, tag2).then((f4) => { - if (f4) { - return consolidateRowsToTag( - props2.plugin, - tagContextFromTag(props2.plugin, tag2), - dbSchema.id, - contextInfo.dbPath, - tableData.rows - ); - } - }).then((f4) => loadContextFields(tag2)); - }); - saveSchema({ - ...dbSchema, - def: tags.join("&") + 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 } }); - connectContext(props2.plugin, tag, contextInfo.dbPath); - }; - 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]: parseFrontMatter(c5, dvValues[c5], true) - }), - {} - ) - } - ] - }; - }, - { 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; + if (waitTime === void 0) { + waitTime = 300; + } + this.onTarget = true; + this.parent = parent; + this.waitTime = waitTime; + this.state = import_obsidian30.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); + } + 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); + } + } + 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((he) => he); + } + 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); + 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_obsidian30.WorkspaceTabs) { + this.rootSplit.replaceChild(index, item.children[0]); } - return { - uniques: [], - cols: (0, import_lodash7.uniq)([...p3.cols, ...fmKeys]), - rows: [ - ...p3.rows, - { - File: c4.path, - ...fmKeys.reduce( - (p4, c5) => ({ - ...p4, - [c5]: parseFrontMatter(c5, fm[c5], false) - }), - {} - ) - } - ] - }; - }, - { uniques: [], cols: [], rows: [] } - ); - }; - let yamlTableData = importYAML( - files, - keys.filter((f4) => f4.type == "fm").map((f4) => f4.name) + }); + }) ); - 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: (0, import_lodash7.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 }; + } + leaves() { + const leaves = []; + this.plugin.app.workspace.iterateLeaves((leaf) => { + leaves.push(leaf); + }, this.rootSplit); + return leaves; + } + 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; } - if (table == "") { - const newTable = mergeTableData(tableData, yamlTableData, yamlTypes); - saveDB2(newTable); - } else { - if (!dbFileExists) { - saveDB2(tableData).then( - () => saveContext(yamlTableData, yamlTypes, table) - ); - } else { - saveContext(yamlTableData, yamlTypes, table); + const viewHeaderEl = this.hoverEl.querySelector(".view-header"); + viewHeaderEl == null ? void 0 : viewHeaderEl.remove(); + const sizer = this.hoverEl.querySelector(".workspace-leaf"); + this.hoverEl.appendChild(sizer); + const inlineTitle = this.hoverEl.querySelector(".inline-title"); + inlineTitle == null ? void 0 : inlineTitle.remove(); + (_b2 = this.onShowCallback) == null ? void 0 : _b2.call(this); + this.onShowCallback = void 0; + } + transition() { + if (this.shouldShow()) { + if (this.state === import_obsidian30.PopoverState.Hiding) { + this.state = import_obsidian30.PopoverState.Shown; + clearTimeout(this.timer); } - } - }; - const saveContext = (yamlTableData, yamlTypes, table) => { - if (contextTable[table]) { - const newTable = mergeTableData( - contextTable[table], - yamlTableData, - yamlTypes - ); - saveContextDB(newTable, table); - saveSchema({ - ...dbSchema, - def: (0, import_lodash7.uniq)([...tagContexts, table]).join("&") - }); } else { - consolidateRowsToTag( - props2.plugin, - tagContextFromTag(props2.plugin, table), - dbSchema.id, - contextInfo.dbPath, - tableData.rows - ).then((f4) => { - if (f4) { - const newTable = mergeTableData(f4, yamlTableData, yamlTypes); - return saveContextDB(newTable, table); + if (this.state === import_obsidian30.PopoverState.Showing) { + this.hide(); + } else { + if (this.state === import_obsidian30.PopoverState.Shown) { + this.state = import_obsidian30.PopoverState.Hiding; + this.timer = window.setTimeout(() => { + if (this.shouldShow()) { + this.transition(); + } else { + this.hide(); + } + }, this.waitTime); } - }).then(() => { - saveSchema({ - ...dbSchema, - def: (0, import_lodash7.uniq)([...tagContexts, table]).join("&") - }); - }); - } - }; - const syncMetadata = () => { - let vaultChangeModal = new SyncMetadataModal( - props2.plugin, - data.map((f4) => getAbstractFileAtPath(app, f4.File)).filter((f4) => f4), - saveMetadata, - cols - ); - vaultChangeModal.open(); - }; - return /* @__PURE__ */ bn.createElement(TagsView, { - plugin: props2.plugin, - tags: tagContexts, - addTag: props2.canAdd && addTag2, - removeTag: removeContext, - syncTags: contextInfo.type != "unknown" && syncMetadata - }); -}; - -// src/components/ContextView/FilterBar/FilterBar.tsx -var FilterBar = (props2) => { - const { folderNoteOpen, viewFolderNote } = props2; - const ctxRef = _2(null); - const { - tables, - data, - setDBSchema, - loadContextFields, - cols, - deleteSchema, - saveSchema, - saveDB: saveDB2, - saveContextDB, - setSchema, - setSearchString, - predicate, - tagContexts, - savePredicate, - schema, - dbSchema, - contextInfo, - contextTable, - tableData - } = q2(MDBContext); - const filteredCols = cols.filter((f4) => f4.hidden != "true"); - const saveViewType = (type) => { - saveSchema({ - ...schema, - type - }); - }; - const selectView = (_dbschema, value) => { - viewFolderNote && folderNoteOpen && 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; + } } - selectView(_dbschema, views[0].id); - return; - }; - const showViewMenu = (e4, _dbschema) => { - const views = 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: views.map((m5) => ({ name: m5.name, value: m5.id })), - saveOptions: (_7, value) => selectView(_dbschema, value[0]), - placeholder: i18n_default.labels.viewItemSelectPlaceholder, - searchable: false, - showAll: true + } + 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(); } - ); - }; - 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 showFilterMenu = (e4) => { - const menu = new import_obsidian28.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"); - }); - }); - 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(); - }); + return false; }); - const offset = e4.target.getBoundingClientRect(); - menu.showAtPosition({ x: offset.left, y: offset.top + 30 }); - }; - const addSort = (_7, 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, - type - }; - savePredicate({ - ...predicate, - sort: [ - ...predicate.sort.filter((s5) => s5.field != newSort.field), - newSort - ] - }); + } + shouldShowSelf() { + return !this.detaching && !!(this.onTarget || this.state == import_obsidian30.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_obsidian30.PopoverState.Shown; + this.timer = 0; + this.shownPos = mouseCoords; + this.targetEl.replaceChildren(this.hoverEl); + this.onShow(); + app.workspace.onLayoutChange(); + this.load(); + } else { + this.hide(); } - }; - const saveGroupBy = (_7, groupBy2) => { - savePredicate({ - ...predicate, - groupBy: groupBy2 - }); - }; - const removeSort = (sort) => { - const newSort = [...predicate.sort.filter((f4) => f4.field != sort.field)]; - savePredicate({ - ...predicate, - sort: newSort - }); - }; - const addFilter = (_7, filter) => { + } + onHide() { 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, - type, - value: "true" - } : { - field, - type, - value: "" - }; - savePredicate({ - ...predicate, - filters: [ - ...predicate.filters.filter((s5) => s5.field != newFilter.field), - newFilter - ] - }); + this.oldPopover = null; + if (((_a2 = this.parent) == null ? void 0 : _a2.flowEditor) === this) { + this.parent.flowEditor = null; } - }; - const changeSortMenu = (e4, sort) => { + } + hide() { var _a2; - const offset = e4.target.getBoundingClientRect(); - const saveSort = (_7, newType) => { - const type = newType[0]; - const newSort = { - ...sort, - type - }; - savePredicate({ - ...predicate, - sort: [ - ...predicate.sort.filter((s5) => s5.field != newSort.field), - newSort - ] - }); - }; - 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) => { - 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: addFilter, - placeholder: i18n_default.labels.propertyItemSelectPlaceholder, - searchable: false, - showAll: true - } - ); - }; - const changeFilterMenu = (e4, filter) => { + 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(); + } + } + nativeHide() { var _a2; - const offset = e4.target.getBoundingClientRect(); - const saveFilter = (_7, newType) => { - const type = newType[0]; - const newFilter = { - ...filter, - type - }; - savePredicate({ - ...predicate, - filters: [ - ...predicate.filters.filter((s5) => s5.field != newFilter.field), - newFilter - ] - }); + const { hoverEl, targetEl } = this; + this.state = import_obsidian30.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 link2 = (0, import_obsidian30.parseLinktext)(linkText); + const tFile = link2 ? this.plugin.app.metadataCache.getFirstLinkpathDest( + link2.path, + sourcePath != null ? sourcePath : "" + ) : null; + return tFile; + } + 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(); + } + this.plugin.app.workspace.setActiveLeaf(leaf); + return leaf; + } + buildState(parentMode, eState) { + return { + active: false, + state: {}, + eState }; - 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: filterFnTypes[f4].label, - value: f4 - })), - saveOptions: saveFilter, - placeholder: i18n_default.labels.filterItemSelectPlaceholder, - searchable: false, - showAll: true - } - ); - }; - 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 - } + } + buildEphemeralState(file, link2) { + const cache = this.plugin.app.metadataCache.getFileCache(file); + const subpath = cache ? (0, import_obsidian30.resolveSubpath)(cache, (link2 == null ? void 0 : link2.subpath) || "") : void 0; + const eState = { subpath: link2 == null ? void 0 : link2.subpath }; + if (subpath) { + eState.line = subpath.start.line; + eState.startLoc = subpath.start; + eState.endLoc = subpath.end || void 0; + } + return eState; + } +}; + +// src/utils/flow/flowEditor.ts +var import_obsidian31 = 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 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 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 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; + } + if (!dom.hasClass("mk-floweditor") && !dom.hasClass("workspace") && !(dom.nodeName == "HTML")) { + return; + } + 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 + ); + } } - ); - }; - 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 + 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"]); } - ); - }; - const showAddMenu = (e4) => { - const fileMenu = new import_obsidian28.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 }); - } else { - fileMenu.showAtPosition({ - x: e4.nativeEvent.locationX, - y: e4.nativeEvent.locationY - }); - } - return false; - }; - const showFMMenu2 = (e4) => { - const menu = new import_obsidian28.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; - }) - }); - } 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 + }); +}; +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(make, flowEditorInfo2.link, source); + if (dom) { + if (type == "folder" || type == "tag" || type == "space") { + const context = mdbContextByPath( + make, + path ); - } - }; - const showMergeColumnModal = () => { - 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 != "File" && 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(); - }; - const selectFilterValue = (e4, filter) => { - var _a2, _b2, _c2; - switch (filterFnTypes[filter.type].valueType) { - case "text": - case "number": - { - const menu = new import_obsidian28.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) + if (!dom.hasAttribute("ready")) { + dom.setAttribute("ready", ""); + createFlowEditorInElement( + flowEditorInfo2.id, + dom, + "context", + context.contextPath, + ref + ); + 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] + ); + } + } else { + if (aFile instanceof import_obsidian31.TFolder) { + if (!dom.hasAttribute("ready")) { + dom.setAttribute("ready", ""); + createFlowEditorInElement( + flowEditorInfo2.id, + dom, + ref ? "block" : "flow", + path ); - menuItem.setIcon("type"); - }); - const offset = e4.target.getBoundingClientRect(); - menu.showAtPosition({ x: offset.left, y: offset.top + 30 }); + } + return; } - 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 - ] - }); + 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(), link); + loadFlowEditor(cm, flowEditorInfo2, source, make); }; - 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; + createDiv.setText(`"${path}" ` + i18n_default.labels.noFile); + createDiv.addEventListener("click", createFile); } - case "list": - { - const col = cols.find((f4) => f4.name + f4.table == filter.field); - const saveOptions = (options, values) => { - const newFilter = { - ...filter, - value: values.join(",") - }; - 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: splitString(filter.value), - options: splitString(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: splitString(filter.value), - options: (_c2 = contextData.map((f4) => ({ - name: filePathToString(f4["File"]), - value: f4["File"] - }))) != null ? _c2 : [], - saveOptions, - placeholder: i18n_default.labels.optionItemSelectPlaceholder, - searchable: true, - showAll: true + } + } +}; +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) + }); } - ); + } } } - break; + } + }, 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) + }); + } + } + } + }, app.workspace["rootSplit"]); + } +}; +var openFileFromPortal = (plugin, evt) => { + const { file: fullLink, source } = evt.detail; + const [link2, ref] = parseOutReferences(fullLink); + const file = getFileFromString(link2, source); + openAFile(file, plugin, false); +}; +var spawnLeafFromFile = async (plugin, file, el, type, ref, from, to) => { + var _a2; + if (type == "context") { + const newLeaf2 = spawnPortal(plugin, el); + newLeaf2.setViewState({ + type: EMBED_CONTEXT_VIEW_TYPE, + state: { contextPath: file, ref } + }); + return newLeaf2; + } + let portalFile = plugin.app.vault.getAbstractFileByPath(file); + if (!portalFile || !Object.keys(app.embedRegistry.embedByExtension).some( + (f4) => f4 == portalFile.extension + )) + return; + const newLeaf = spawnPortal(plugin, el, portalFile.name); + await newLeaf.openFile(portalFile, { active: false }); + 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])] + }); + } + return newLeaf; +}; +var spawnNewPortal = async (plugin, evt) => { + var _a2, _b2, _c2; + const { file, el, ref, from, to, type } = evt.detail; + const newLeaf = await spawnLeafFromFile(plugin, file, el, type, ref); + if (!((_a2 = newLeaf == null ? void 0 : newLeaf.view) == null ? void 0 : _a2.editor)) { + return; + } + 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])] + }); + } +}; +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(".") + ); + return hoverPopover.attachLeaf(); +}; + +// src/components/ContextView/FilterBar/TableSelector.tsx +var import_obsidian32 = require("obsidian"); +var TableSelector = (props2) => { + const { folderNoteOpen, viewFolderNote } = props2; + 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 saveNewSchemas = (_schema) => { const newSchema = { ..._schema, @@ -37898,8 +40937,22 @@ var FilterBar = (props2) => { ); 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; + } + selectView(_dbschema, views[0].id); + return; + }; const viewContextMenu = (e4, _schema) => { - const fileMenu = new import_obsidian28.Menu(); + const fileMenu = new import_obsidian32.Menu(); fileMenu.addSeparator(); fileMenu.addItem((menuItem) => { menuItem.setTitle("Rename Table"); @@ -37927,114 +40980,42 @@ var FilterBar = (props2) => { }); } }; - return /* @__PURE__ */ bn.createElement(bn.Fragment, null, /* @__PURE__ */ bn.createElement(TagSelector, { - plugin: props2.plugin, - canAdd: contextInfo.type == "folder" - }), /* @__PURE__ */ bn.createElement("div", { - className: "mk-view-selector" - }, /* @__PURE__ */ bn.createElement("div", { + return /* @__PURE__ */ Cn.createElement("div", { className: "mk-table-selector" - }, viewFolderNote && /* @__PURE__ */ bn.createElement("button", { + }, viewFolderNote && /* @__PURE__ */ Cn.createElement("button", { className: `mk-folder-note ${folderNoteOpen ? "mk-is-active" : ""}`, onClick: () => viewFolderNote(true) - }, props2.folderNoteName), tables.filter((f4) => f4.type == "db").map((f4) => /* @__PURE__ */ bn.createElement("div", { + }, 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) - }, /* @__PURE__ */ bn.createElement("button", { - onClick: (e4) => openView(e4, f4) - }, f4.name), tables.filter((g4) => g4.type != "db" && g4.def == f4.id).length > 1 && /* @__PURE__ */ bn.createElement("button", { - className: "mk-icon-xsmall mk-collapse", - onClick: (e4) => showViewMenu(e4, f4), - dangerouslySetInnerHTML: { - __html: uiIconSet["mk-ui-collapse"] - } - }))), contextInfo.type == "folder" && /* @__PURE__ */ bn.createElement("button", { + }, f4.name)), contextInfo.type == "folder" && /* @__PURE__ */ Cn.createElement("button", { onClick: (e4) => newTable(e4) - }, "+ Table")), /* @__PURE__ */ bn.createElement("span", null), !props2.folderNoteOpen && /* @__PURE__ */ bn.createElement("div", { - className: "mk-view-options" - }, /* @__PURE__ */ bn.createElement(SearchBar, { - setSearchString - }), /* @__PURE__ */ bn.createElement("button", { - onClick: (e4) => showFilterMenu(e4), - dangerouslySetInnerHTML: { - __html: uiIconSet["mk-ui-view-options"] - } - }), /* @__PURE__ */ bn.createElement("button", { - onClick: (e4) => showFMMenu2(e4), - dangerouslySetInnerHTML: { __html: uiIconSet["mk-ui-options"] } - }), contextInfo.type == "folder" && (dbSchema == null ? void 0 : dbSchema.id) == "files" && /* @__PURE__ */ bn.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) && !folderNoteOpen && /* @__PURE__ */ bn.createElement("div", { - className: "mk-filter-bar" - }, predicate.groupBy.length > 0 && /* @__PURE__ */ bn.createElement("div", { - className: "mk-filter" - }, /* @__PURE__ */ bn.createElement("span", null, "Group By"), /* @__PURE__ */ bn.createElement("span", { - onClick: (e4) => showGroupByMenu(e4) - }, predicate.groupBy[0]), /* @__PURE__ */ bn.createElement("div", { - onClick: () => saveGroupBy(null, []), - dangerouslySetInnerHTML: { __html: uiIconSet["mk-ui-close"] } - })), predicate.sort.map((f4) => /* @__PURE__ */ bn.createElement("div", { - className: "mk-filter" - }, /* @__PURE__ */ bn.createElement("span", null, f4.field), /* @__PURE__ */ bn.createElement("span", { - onClick: (e4) => changeSortMenu(e4, f4) - }, sortFnTypes[f4.type].label), /* @__PURE__ */ bn.createElement("div", { - onClick: () => removeSort(f4), - dangerouslySetInnerHTML: { __html: uiIconSet["mk-ui-close"] } - }))), predicate.filters.map((f4) => /* @__PURE__ */ bn.createElement("div", { - className: "mk-filter" - }, /* @__PURE__ */ bn.createElement("span", null, f4.field), /* @__PURE__ */ bn.createElement("span", { - onClick: (e4) => changeFilterMenu(e4, f4) - }, filterFnTypes[f4.type].label), /* @__PURE__ */ bn.createElement(FilterValueSpan, { - col: cols.find((c4) => c4.name + c4.table == f4.field), - filter: f4, - selectFilterValue - }), /* @__PURE__ */ bn.createElement("div", { - onClick: () => removeFilter(f4), - dangerouslySetInnerHTML: { __html: uiIconSet["mk-ui-close"] } - }))), /* @__PURE__ */ bn.createElement("span", null), /* @__PURE__ */ bn.createElement("button", { - className: "mk-filter-add mk-icon-small", - onClick: () => showSaveViewModal() - }, /* @__PURE__ */ bn.createElement("div", { - dangerouslySetInnerHTML: { __html: uiIconSet["mk-ui-stack"] } - }), "Save View"))); -}; -var FilterValueSpan = (props2) => { - var _a2; - const { filter, selectFilterValue } = props2; - const fieldType = (_a2 = props2.col) == null ? void 0 : _a2.type; - if (fieldType == "boolean" || !fieldType) { - return /* @__PURE__ */ bn.createElement(bn.Fragment, null); - } else if (filter.value.length == 0) { - return /* @__PURE__ */ bn.createElement("span", { - onClick: (e4) => selectFilterValue(e4, filter) - }, "Select"); - } else if (fieldType.startsWith("option") || fieldType.startsWith("context")) { - const options = splitString(filter.value); - return /* @__PURE__ */ bn.createElement("span", { - onClick: (e4) => selectFilterValue(e4, filter) - }, " ", options.map((f4) => /* @__PURE__ */ bn.createElement("span", null, f4))); - } - return /* @__PURE__ */ bn.createElement("span", { - onClick: (e4) => selectFilterValue(e4, filter) - }, filter.value); + }, "+")); }; // src/components/ContextView/ContextViewComponent.tsx var ContextViewComponent = (props2) => { + var _a2; const context = props2.context; - const folder = F(() => { + const contextCache = props2.plugin.index.contextsCache.get( + context.contextPath + ); + const folder = F2(() => { if (props2.context.type == "folder") { - return getAbstractFileAtPath(app, props2.context.contextPath); + return props2.context.contextPath; } return null; }, [props2.context]); - const name = contextDisplayName(context); + const name = (_a2 = contextCache == null ? void 0 : contextCache.name) != null ? _a2 : contextDisplayName(props2.context); const ref = _2(null); - const [flowOpen, setFlowOpen] = p2(false); + const [flowOpen, setFlowOpen] = h2(false); const loadFile = async () => { - const folderNotePath = props2.plugin.settings.folderNoteInsideFolder ? `${folder.path}/${folder.name}.md` : folder && folder.parent.path == "/" ? `${folder.name}.md` : `${folder.parent.path}/${folder.name}.md`; + const fileCache = props2.plugin.index.files.get(folder); + const folderNotePath = folderNotePathFromAFile( + props2.plugin.settings, + fileCache + ); const folderNote = getAbstractFileAtPath(app, folderNotePath); if (folderNote) { const div = ref.current; @@ -38050,7 +41031,7 @@ var ContextViewComponent = (props2) => { newLeaf.openFile(newFile); } }; - h2(() => { + p2(() => { if (flowOpen && folder) { loadFile(); } else { @@ -38061,38 +41042,39 @@ var ContextViewComponent = (props2) => { const viewFolderNote = (open) => { setFlowOpen(open); }; - return /* @__PURE__ */ bn.createElement("div", { + return /* @__PURE__ */ Cn.createElement("div", { className: "mk-folder-scroller" - }, /* @__PURE__ */ bn.createElement("div", { + }, /* @__PURE__ */ Cn.createElement("div", { className: "mk-folder-header" - }, /* @__PURE__ */ bn.createElement("div", { + }, /* @__PURE__ */ Cn.createElement("div", { className: "inline-title" - }, name)), props2.plugin.settings.enableFolderNote && props2.context.type == "folder" ? /* @__PURE__ */ bn.createElement(MDBProvider, { + }, name)), props2.plugin.settings.enableFolderNote && props2.context.type == "folder" ? /* @__PURE__ */ Cn.createElement(MDBProvider, { plugin: props2.plugin, context - }, /* @__PURE__ */ bn.createElement(FilterBar, { - plugin: props2.plugin, - folderNoteName: folder.name, + }, /* @__PURE__ */ Cn.createElement(TableSelector, { + folderNoteName: getFolderFromPath(app, folder).name, folderNoteOpen: flowOpen, viewFolderNote - }), context && !flowOpen && /* @__PURE__ */ bn.createElement(ContextListView, { + }), context && !flowOpen && /* @__PURE__ */ Cn.createElement(Cn.Fragment, null, /* @__PURE__ */ Cn.createElement(FilterBar, { + plugin: props2.plugin + }), /* @__PURE__ */ Cn.createElement(ContextListView, { plugin: props2.plugin - }), flowOpen && /* @__PURE__ */ bn.createElement("div", { + })), flowOpen && /* @__PURE__ */ Cn.createElement("div", { className: "mk-flowspace-editor mk-foldernote", ref - })) : /* @__PURE__ */ bn.createElement(MDBProvider, { + })) : /* @__PURE__ */ Cn.createElement(MDBProvider, { plugin: props2.plugin, context - }, /* @__PURE__ */ bn.createElement(FilterBar, { + }, /* @__PURE__ */ Cn.createElement(FilterBar, { plugin: props2.plugin - }), /* @__PURE__ */ bn.createElement(ContextListView, { + }), /* @__PURE__ */ Cn.createElement(ContextListView, { plugin: props2.plugin }))); }; // src/components/ContextView/ContextView.tsx var CONTEXT_VIEW_TYPE = "make-folder-view"; -var ContextView = class extends import_obsidian29.ItemView { +var ContextView = class extends import_obsidian33.ItemView { constructor(leaf, plugin, viewType) { super(leaf); this.navigation = true; @@ -38117,7 +41099,7 @@ var ContextView = class extends import_obsidian29.ItemView { } async setState(state, result) { this.contextPath = state.contextPath; - this.context = mdbContextByContextPath(this.plugin, this.contextPath); + this.context = mdbContextByPath(this.plugin, this.contextPath); if (!this.context) return; this.constructContext(this.context); @@ -38141,9 +41123,9 @@ var ContextView = class extends import_obsidian29.ItemView { this.destroy(); this.root = createRoot(this.contentEl); this.root.render( - /* @__PURE__ */ bn.createElement("div", { + /* @__PURE__ */ Cn.createElement("div", { className: "mk-folder-view" - }, /* @__PURE__ */ bn.createElement(ContextViewComponent, { + }, /* @__PURE__ */ Cn.createElement(ContextViewComponent, { context, plugin: this.plugin })) @@ -38152,23 +41134,23 @@ var ContextView = class extends import_obsidian29.ItemView { }; // src/components/FileView/FileView.tsx -var import_obsidian31 = require("obsidian"); +var import_obsidian35 = require("obsidian"); // src/components/FileView/FileLinkViewComponent.tsx -var import_obsidian30 = require("obsidian"); +var import_obsidian34 = require("obsidian"); var FileLinkViewComponent = (props2) => { const ref = _2(null); - const [markdown, setMarkdown] = p2(""); - h2(() => { + const [markdown, setMarkdown] = h2(""); + p2(() => { if (ref.current) - import_obsidian30.MarkdownRenderer.renderMarkdown(markdown, ref.current, props2.path, null); + import_obsidian34.MarkdownRenderer.renderMarkdown(markdown, ref.current, props2.path, null); }, [markdown]); - h2(() => { + p2(() => { fetch(props2.path).then((res) => res.text()).then((f4) => setMarkdown(f4)); }, [props2.path]); - return /* @__PURE__ */ bn.createElement("div", { + 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__ */ bn.createElement("div", { + }, /* @__PURE__ */ Cn.createElement("div", { className: "markdown-preview-sizer markdown-preview-section", ref })); @@ -38176,7 +41158,7 @@ var FileLinkViewComponent = (props2) => { // src/components/FileView/FileView.tsx var FILE_VIEW_TYPE = "make-file-view"; -var FileLinkView = class extends import_obsidian31.ItemView { +var FileLinkView = class extends import_obsidian35.ItemView { constructor(leaf, plugin, viewType) { super(leaf); this.navigation = true; @@ -38222,9 +41204,9 @@ var FileLinkView = class extends import_obsidian31.ItemView { this.destroy(); this.root = createRoot(this.contentEl); this.root.render( - /* @__PURE__ */ bn.createElement("div", { + /* @__PURE__ */ Cn.createElement("div", { className: "markdown-reading-view" - }, /* @__PURE__ */ bn.createElement(FileLinkViewComponent, { + }, /* @__PURE__ */ Cn.createElement(FileLinkViewComponent, { path, plugin: this.plugin })) @@ -38233,44 +41215,63 @@ var FileLinkView = class extends import_obsidian31.ItemView { }; // src/utils/file.ts -var import_obsidian32 = require("obsidian"); +var import_obsidian36 = require("obsidian"); +var tFileToAFile = (file) => { + if (!file) + return null; + if (file instanceof import_obsidian36.TFile && file.stat) { + return { + isFolder: false, + name: file.name, + path: file.path, + parent: file.parent.path, + stat: file.stat, + extension: file.extension + }; + } + return { + isFolder: true, + name: file.name, + path: file.path, + parent: file.parent.path + }; +}; var defaultNoteFolder = (plugin, activeFile2) => { var _a2; - return (_a2 = plugin.settings.newFileLocation == "folder" ? getFolderFromPath(app, plugin.settings.newFileFolderPath) : plugin.settings.newFileLocation == "current" && activeFile2 ? getFolderFromPath(app, activeFile2) : plugin.app.vault.getRoot()) != null ? _a2 : plugin.app.vault.getRoot(); + 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(); }; var defaultConfigFile = async (app2) => { return await app2.vault.adapter.read( - (0, import_obsidian32.normalizePath)(app2.vault.configDir + "/app.json") + (0, import_obsidian36.normalizePath)(app2.vault.configDir + "/app.json") ); }; var fileExtensionForFile = (path) => path == null ? void 0 : path.split(".").pop(); -var appendFilesMetaData = (propType, filesString) => { - const files = splitString(filesString).map((f4) => getAbstractFileAtPath(app, f4)).filter((f4) => f4); - return files.map((f4) => appendFileMetaData(propType, f4)).join(","); +var appendFilesMetaData = (plugin, propType, filesString) => { + const files = parseMultiString(filesString).map((f4) => plugin.index.files.get(f4)).filter((f4) => f4); + return serializeMultiString(files.map((f4) => appendFileMetaData(propType, f4))); }; var appendFileMetaData = (propType, file) => { - var _a2, _b2; + var _a2, _b2, _c2; let value = ""; if (file) { if (propType == "folder") { - value = file.parent.path; - } - if (file instanceof import_obsidian32.TFile) { - if (propType == "ctime") { - value = file.stat.ctime.toString(); - } else if (propType == "mtime") { - value = file.stat.mtime.toString(); - } else if (propType == "extension") { - value = file.extension; - } else if (propType == "size") { - value = file.stat.size.toString(); - } else if (propType == "links") { - value = ((_b2 = (_a2 = app.metadataCache.getFileCache(file)) == null ? void 0 : _a2.links) != null ? _b2 : []).map((f4) => f4.link).join(", "); - } else if (propType == "tags") { - value = allTagsForFile(file).join(", "); - } + value = file.parent; + } else if (propType == "ctime") { + value = (_a2 = file.ctime) == null ? void 0 : _a2.toString(); + } else if (propType == "mtime") { + value = (_b2 = file.mtime) == null ? void 0 : _b2.toString(); } else if (propType == "extension") { - value = i18n_default.menu.folder; + value = file.extension; + } else if (propType == "size") { + value = (_c2 = file.size) == null ? void 0 : _c2.toString(); + } else if (propType == "inlinks") { + value = serializeMultiDisplayString(file.inlinks); + } else if (propType == "outlinks") { + value = serializeMultiDisplayString(file.outlinks); + } else if (propType == "tags") { + value = serializeMultiDisplayString(file.tags); + } else if (propType == "spaces") { + value = serializeMultiDisplayString(file.spaces); } } return value; @@ -38278,39 +41279,27 @@ var appendFileMetaData = (propType, file) => { var moveFile = async (folder, file) => { await app.vault.rename(file, folder.path + "/" + file.name); }; -var renameFile = async (file, newName) => { +var renameFile = async (plugin, file, newName) => { + const afile = tFileToAFile(file); + const folderNotePath = folderNotePathFromAFile(plugin.settings, afile); + const folderNote = getAbstractFileAtPath(app, folderNotePath); await app.fileManager.renameFile( file, file.parent.path == "/" ? newName : file.parent.path + "/" + newName ); -}; -var viewTypeByString = (file) => { - if (file.charAt(0) == "#") { - return "tag"; - } - if (file.charAt(0) == "?") { - return "query"; - } - if (file.charAt(file.length - 1) == "/") { - return "folder"; - } - const portalFile = app.vault.getAbstractFileByPath(file); - if (portalFile instanceof import_obsidian32.TFolder) { - return "folder"; - } - if (portalFile instanceof import_obsidian32.TFile) { - return "file"; + if (afile.isFolder && folderNote) { + await app.fileManager.renameFile( + folderNote, + folderNotePathFromAFile(plugin.settings, tFileToAFile(file)) + ); } - if (file.match(urlRegex)) - return "url"; - return null; }; function getAllAbstractFilesInVault(plugin, app2) { let files = []; let rootFolder = app2.vault.getRoot(); function recursiveFx(folder) { for (let child of folderChildren(plugin, folder)) { - if (child instanceof import_obsidian32.TFolder) { + if (child instanceof import_obsidian36.TFolder) { let childFolder = child; if (childFolder.children) recursiveFx(childFolder); @@ -38328,12 +41317,19 @@ var getFolderFromPath = (app2, path) => { const afile = getAbstractFileAtPath(app2, removeTrailingSlashFromFolder(path)); if (!afile) return null; - return afile instanceof import_obsidian32.TFolder ? afile : afile.parent; + return afile instanceof import_obsidian36.TFolder ? afile : afile.parent; }; var getFolderPathFromString = (file) => { var _a2; return (_a2 = getFolderFromPath(app, file)) == null ? void 0 : _a2.path; }; +var getParentPathFromString = (file) => { + const indexOfLastSlash = file.lastIndexOf("/"); + if (indexOfLastSlash == -1) { + return "/"; + } + return file.substring(0, indexOfLastSlash + 1); +}; var deleteFiles = (plugin, files) => { files.forEach((f4) => { const file = getAbstractFileAtPath(app, f4); @@ -38353,6 +41349,25 @@ var deleteFile = (plugin, file) => { var openFile = async (file, plugin, newLeaf) => { openAFile(getAbstractFileAtPath(plugin.app, file.path), plugin, newLeaf); }; +var openSpace = async (spaceName, plugin, newLeaf) => { + if (!plugin.settings.contextEnabled) + return; + let leaf = app.workspace.getLeaf(newLeaf); + const viewType = CONTEXT_VIEW_TYPE; + app.workspace.setActiveLeaf(leaf, { focus: true }); + await leaf.setViewState({ + type: viewType, + state: { contextPath: spaceContextPathFromName(spaceName) } + }); + await app.workspace.requestSaveLayout(); + if (platformIsMobile()) { + app.workspace.leftSplit.collapse(); + } + let evt = new CustomEvent(eventTypes.activePathChange, { + detail: { path: pathByString(plugin, spaceContextPathFromName(spaceName)) } + }); + window.dispatchEvent(evt); +}; var openURL = async (url) => { let leaf = app.workspace.getLeaf(false); if (url.endsWith(".md")) { @@ -38377,13 +41392,13 @@ var openURL = async (url) => { } }; var openAFile = async (file, plugin, newLeaf) => { - if (file instanceof import_obsidian32.TFolder) { + if (file instanceof import_obsidian36.TFolder) { openTFolder(file, plugin, newLeaf); - } else if (file instanceof import_obsidian32.TFile) { + } else if (file instanceof import_obsidian36.TFile) { openTFile(file, plugin, newLeaf); } - let evt = new CustomEvent(eventTypes.activeFileChange, { - detail: { filePath: file.path } + let evt = new CustomEvent(eventTypes.activePathChange, { + detail: { path: pathByString(plugin, file.path) } }); window.dispatchEvent(evt); }; @@ -38407,7 +41422,7 @@ var openTFolder = async (file, plugin, newLeaf) => { app.workspace.leftSplit.collapse(); } }; -var openContext = async (tag, plugin, newLeaf) => { +var openTagContext = async (tag, plugin, newLeaf) => { let leaf = app.workspace.getLeaf(newLeaf); const viewType = CONTEXT_VIEW_TYPE; app.workspace.setActiveLeaf(leaf, { focus: true }); @@ -38416,10 +41431,17 @@ var openContext = async (tag, plugin, newLeaf) => { if (platformIsMobile()) { app.workspace.leftSplit.collapse(); } + let evt = new CustomEvent(eventTypes.activePathChange, { + detail: { path: pathByString(plugin, tag) } + }); + window.dispatchEvent(evt); }; var getAbstractFileAtPath = (app2, path) => { return app2.vault.getAbstractFileByPath(path); }; +var abstractFileAtPathExists = (app2, path) => { + return app2.vault.getAbstractFileByPath(path) ? true : false; +}; var openFileInNewPane = (plugin, file) => { openFile(file, plugin, true); }; @@ -38430,6 +41452,7 @@ var createNewCanvasFile = async (plugin, folder, newFileName, dontOpen) => { ); await app.vault.modify(newFile, "{}"); await renameFile( + plugin, newFile, newFile.name.substring(0, newFile.name.lastIndexOf(".")) + ".canvas" ); @@ -38437,8 +41460,8 @@ var createNewCanvasFile = async (plugin, folder, newFileName, dontOpen) => { return newFile; } await openAFile(newFile, plugin, false); - let evt = new CustomEvent(eventTypes.activeFileChange, { - detail: { filePath: newFile.path } + let evt = new CustomEvent(eventTypes.activePathChange, { + detail: { path: pathByString(plugin, newFile.path) } }); window.dispatchEvent(evt); return newFile; @@ -38461,14 +41484,14 @@ var createNewMarkdownFile = async (plugin, folder, newFileName, content, dontOpe titleEl.focus(); selectElementContents(titleEl); } - let evt = new CustomEvent(eventTypes.activeFileChange, { - detail: { filePath: newFile.path } + let evt = new CustomEvent(eventTypes.activePathChange, { + detail: { path: pathByString(plugin, newFile.path) } }); window.dispatchEvent(evt); return newFile; }; var platformIsMobile = () => { - return import_obsidian32.Platform.isMobile; + return import_obsidian36.Platform.isMobile; }; var newFileInFolder = async (plugin, data, dontOpen) => { await createNewMarkdownFile( @@ -38481,66 +41504,16 @@ var newFileInFolder = async (plugin, data, dontOpen) => { }; // src/utils/tree.ts -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 onlyUniquePropCaseInsensitive = (prop) => (value, index, self2) => { - return self2.findIndex( - (v3) => value[prop].toLowerCase() == v3[prop].toLowerCase() - ) === index; -}; -var fileNameToString = (filename) => filename.substring(0, filename.lastIndexOf(".")) || filename; -var removeLeadingSlash = (path) => path.charAt(0) == "/" ? path.substring(1) : path; -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 folderPathToString = (filename) => removeLeadingSlash(filename.substring(filename.lastIndexOf("/"))) || filename; -var safelyParseJSON = (json) => { - var parsed; - try { - parsed = JSON.parse(json); - } catch (e4) { - } - return parsed; -}; var nodeIsAncestorOfTarget = (node, target) => { var _a2, _b2, _c2; - if (((_a2 = node.item) == null ? void 0 : _a2.folder) == "false") + if (!((_a2 = node.item) == null ? void 0 : _a2.isFolder)) return false; return (_c2 = target.item) == null ? void 0 : _c2.path.contains(((_b2 = node.item) == null ? void 0 : _b2.path) + "/"); }; -var excludeVaultItemPredicate = (plugin) => (f4, index, folder) => !(f4.folder != "true" && plugin.settings.hiddenExtensions.find( +var excludeVaultItemPredicate = (settings) => (f4, index, folder) => !(f4.folder != "true" && settings.hiddenExtensions.find( (e4) => fileExtensionForFile(f4.path) == 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 + "/" + folderPathToString(f4.parent) + ".md" == f4.path)); -var excludeFilePredicate = (plugin) => (f4, index, folder) => !(f4 instanceof import_obsidian33.TFile && plugin.settings.hiddenExtensions.find((e4) => f4.extension == 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)); +)) && !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_obsidian37.TFile && plugin.settings.hiddenExtensions.find((e4) => f4.extension == 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 : []; @@ -38691,12 +41664,12 @@ var flowEditorInfo = import_state6.StateField.define({ return news; }; for (let 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 link2 = match2[1]; + const existingLinks = previous.filter((f4) => f4.link == link2); + const offset = usedContainers.filter((f4) => f4 == link2).length; const existingInfo = existingLinks[offset]; const id2 = existingInfo ? existingInfo.id : genId(); - usedContainers.push(link); + usedContainers.push(link2); const info = { id: id2, link: match2[1], @@ -38711,12 +41684,12 @@ var flowEditorInfo = import_state6.StateField.define({ } for (let 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 link2 = match2[1]; + const existingLinks = previous.filter((f4) => f4.link == link2); + const offset = usedContainers.filter((f4) => f4 == link2).length; const existingInfo = existingLinks[offset]; const id2 = existingInfo ? existingInfo.id : genId(); - usedContainers.push(link); + usedContainers.push(link2); const info = { id: id2, link: match2[1], @@ -38729,12 +41702,12 @@ var flowEditorInfo = import_state6.StateField.define({ }; newValues.push(info); } 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 link2 = match2[1]; + const existingLinks = previous.filter((f4) => f4.link == link2); + const offset = usedContainers.filter((f4) => f4 == link2).length; const existingInfo = existingLinks[offset]; const id2 = existingInfo ? existingInfo.id : genId(); - usedContainers.push(link); + usedContainers.push(link2); const info = { id: id2, link: match2[1], @@ -38822,7 +41795,7 @@ var FlowEditorSelector = class extends import_view4.WidgetType { const reactEl = createRoot(div); const type = this.info.link.contains("/#^") ? "table" : "file"; reactEl.render( - /* @__PURE__ */ bn.createElement(FlowEditorHover, { + /* @__PURE__ */ Cn.createElement(FlowEditorHover, { toggle: true, type, toggleState: true, @@ -38911,7 +41884,7 @@ var flowViewUpdates = import_view5.EditorView.updateListener.of((v3) => { var import_state8 = require("@codemirror/state"); // src/cm-extensions/inlineStylerView/InlineMenu.tsx -var import_classnames4 = __toESM(require_classnames()); +var import_classnames5 = __toESM(require_classnames()); // src/cm-extensions/inlineStylerView/marks.ts var import_state7 = require("@codemirror/state"); @@ -39102,7 +42075,7 @@ var toggleMarkExtension = import_state7.EditorState.transactionFilter.of( // src/cm-extensions/inlineStylerView/Mark.tsx var Mark = (props2) => { const { i: i4, style, active, toggleMarkAction } = props2; - return /* @__PURE__ */ bn.createElement("div", { + return /* @__PURE__ */ Cn.createElement("div", { key: i4, "aria-label": !platformIsMobile() ? i18n_default.styles[style.label] : void 0, className: `mk-mark ${style.mark && active ? "mk-mark-active" : ""}`, @@ -39165,7 +42138,7 @@ function resolveStyles() { var loadStylerIntoContainer = (el, plugin) => { const root = createRoot(el); root.render( - /* @__PURE__ */ bn.createElement(InlineMenuComponent, { + /* @__PURE__ */ Cn.createElement(InlineMenuComponent, { mobile: true, activeMarks: [], plugin @@ -39173,8 +42146,8 @@ var loadStylerIntoContainer = (el, plugin) => { ); }; var InlineMenuComponent = (props2) => { - const [mode, setMode] = p2(props2.mobile ? 0 : 1); - const [colorMode, setColorMode] = p2(null); + const [mode, setMode] = h2(props2.mobile ? 0 : 1); + const [colorMode, setColorMode] = h2(null); const makeMenu = (e4) => { var _a2; e4.preventDefault(); @@ -39224,21 +42197,21 @@ var InlineMenuComponent = (props2) => { } }); }; - const makeMode = () => /* @__PURE__ */ bn.createElement(bn.Fragment, null, /* @__PURE__ */ bn.createElement("div", { + const makeMode = () => /* @__PURE__ */ Cn.createElement(Cn.Fragment, null, /* @__PURE__ */ Cn.createElement("div", { "aria-label": !platformIsMobile() ? i18n_default.commands.makeMenu : void 0, onMouseDown: (e4) => { makeMenu(e4); }, className: "mk-mark", dangerouslySetInnerHTML: { __html: markIconSet["mk-make-slash"] } - }), /* @__PURE__ */ bn.createElement("div", { + }), /* @__PURE__ */ Cn.createElement("div", { "aria-label": !platformIsMobile() ? i18n_default.commands.selectStyle : void 0, onMouseDown: () => { setMode(1); }, className: "mk-mark", dangerouslySetInnerHTML: { __html: markIconSet["mk-make-style"] } - }), /* @__PURE__ */ bn.createElement("div", { + }), /* @__PURE__ */ Cn.createElement("div", { "aria-label": !platformIsMobile() ? i18n_default.commands.image : void 0, onMouseDown: () => { const view = getActiveMarkdownView(); @@ -39246,7 +42219,7 @@ var InlineMenuComponent = (props2) => { }, className: "mk-mark", dangerouslySetInnerHTML: { __html: markIconSet["mk-make-attach"] } - }), /* @__PURE__ */ bn.createElement("div", { + }), /* @__PURE__ */ Cn.createElement("div", { "aria-label": !platformIsMobile() ? i18n_default.commands.toggleKeyboard : void 0, onMouseDown: () => { const view = getActiveMarkdownView(); @@ -39255,14 +42228,14 @@ var InlineMenuComponent = (props2) => { className: "mk-mark", dangerouslySetInnerHTML: { __html: markIconSet["mk-make-keyboard"] } })); - const colorsMode = () => /* @__PURE__ */ bn.createElement(bn.Fragment, null, /* @__PURE__ */ bn.createElement("div", { + const colorsMode = () => /* @__PURE__ */ Cn.createElement(Cn.Fragment, null, /* @__PURE__ */ Cn.createElement("div", { className: "mk-mark", onMouseDown: () => { setColorMode(null); setMode(1); }, dangerouslySetInnerHTML: { __html: uiIconSet["mk-ui-close"] } - }), colors.map((c4, i4) => /* @__PURE__ */ bn.createElement("div", { + }), colors.map((c4, i4) => /* @__PURE__ */ Cn.createElement("div", { key: i4, onMouseDown: () => { var _a2; @@ -39287,22 +42260,22 @@ var InlineMenuComponent = (props2) => { className: "mk-color", style: { background: c4[1] } }))); - const marksMode = () => /* @__PURE__ */ bn.createElement(bn.Fragment, null, props2.mobile ? /* @__PURE__ */ bn.createElement("div", { + const marksMode = () => /* @__PURE__ */ Cn.createElement(Cn.Fragment, null, props2.mobile ? /* @__PURE__ */ Cn.createElement("div", { className: "mk-mark", onMouseDown: () => { setMode(0); }, dangerouslySetInnerHTML: { __html: uiIconSet["mk-ui-close"] } - }) : /* @__PURE__ */ bn.createElement(bn.Fragment, null), resolveStyles().map((s5, i4) => { - return /* @__PURE__ */ bn.createElement(Mark, { + }) : /* @__PURE__ */ Cn.createElement(Cn.Fragment, null), resolveStyles().map((s5, i4) => { + return /* @__PURE__ */ Cn.createElement(Mark, { i: i4, style: s5, active: props2.activeMarks.find((f4) => f4 == s5.mark) ? true : false, toggleMarkAction }); - }), props2.plugin.settings.inlineStylerColors ? /* @__PURE__ */ bn.createElement(bn.Fragment, null, /* @__PURE__ */ bn.createElement("div", { + }), props2.plugin.settings.inlineStylerColors ? /* @__PURE__ */ Cn.createElement(Cn.Fragment, null, /* @__PURE__ */ Cn.createElement("div", { className: "mk-divider" - }), /* @__PURE__ */ bn.createElement("div", { + }), /* @__PURE__ */ Cn.createElement("div", { "aria-label": !platformIsMobile() ? i18n_default.styles.textColor : void 0, onMouseDown: () => { setMode(2); @@ -39314,7 +42287,7 @@ var InlineMenuComponent = (props2) => { }, className: "mk-mark", dangerouslySetInnerHTML: { __html: markIconSet["mk-mark-color"] } - }), /* @__PURE__ */ bn.createElement("div", { + }), /* @__PURE__ */ Cn.createElement("div", { "aria-label": !platformIsMobile() ? i18n_default.styles.highlight : void 0, onMouseDown: () => { setMode(2); @@ -39328,9 +42301,9 @@ var InlineMenuComponent = (props2) => { dangerouslySetInnerHTML: { __html: markIconSet["mk-mark-highlight"] } - })) : /* @__PURE__ */ bn.createElement(bn.Fragment, null)); - return /* @__PURE__ */ bn.createElement("div", { - className: (0, import_classnames4.default)("mk-style-menu", props2.mobile ? "" : "menu"), + })) : /* @__PURE__ */ Cn.createElement(Cn.Fragment, null)); + return /* @__PURE__ */ Cn.createElement("div", { + className: (0, import_classnames5.default)("mk-style-menu", props2.mobile ? "" : "menu"), onMouseDown: (e4) => e4.preventDefault() }, mode == 0 && props2.mobile ? makeMode() : mode == 2 ? colorsMode() : marksMode()); }; @@ -39360,7 +42333,7 @@ var getCursorTooltips = (plugin) => (state) => { dom.className = "cm-tooltip-cursor"; const reactElement = createRoot(dom); reactElement.render( - /* @__PURE__ */ bn.createElement(bn.Fragment, null, /* @__PURE__ */ bn.createElement(InlineMenuComponent, { + /* @__PURE__ */ Cn.createElement(Cn.Fragment, null, /* @__PURE__ */ Cn.createElement(InlineMenuComponent, { plugin, cm: view, activeMarks, @@ -39404,20 +42377,20 @@ var import_view7 = require("@codemirror/view"); // src/components/FileContextView/Backlinks.tsx var BacklinkItem = (props2) => { - const file = F( + const file = F2( () => getAbstractFileAtPath(app, props2.path), [props2.path] ); - const [block, setBlock] = p2([null, null]); - h2(() => { + const [block, setBlock] = h2([null, null]); + p2(() => { var _a2, _b2; const fCache = app.metadataCache.getCache(props2.path); - const link = [...(_a2 = fCache.links) != null ? _a2 : [], ...(_b2 = fCache.embeds) != null ? _b2 : []].find( + const link2 = [...(_a2 = fCache.links) != null ? _a2 : [], ...(_b2 = fCache.embeds) != null ? _b2 : []].find( (f4) => props2.source.includes(f4.displayText) ); - if (link) { + if (link2) { const block2 = fCache.sections.find( - (f4) => f4.position.start.offset <= link.position.start.offset && f4.position.end.offset >= link.position.end.offset + (f4) => f4.position.start.offset <= link2.position.start.offset && f4.position.end.offset >= link2.position.end.offset ); setBlock([ Math.max(1, block2.position.start.line), @@ -39425,10 +42398,10 @@ var BacklinkItem = (props2) => { ]); } }, [props2.path]); - const [collapsed, setCollapsed] = p2(false); - return /* @__PURE__ */ bn.createElement(bn.Fragment, null, /* @__PURE__ */ bn.createElement("div", { + const [collapsed, setCollapsed] = h2(false); + return /* @__PURE__ */ Cn.createElement(Cn.Fragment, null, /* @__PURE__ */ Cn.createElement("div", { className: "mk-file-context-title" - }, /* @__PURE__ */ bn.createElement("button", { + }, /* @__PURE__ */ Cn.createElement("button", { className: `mk-collapse mk-inline-button mk-icon-xsmall ${collapsed ? "mk-collapsed" : ""}`, onClick: (e4) => { setCollapsed(!collapsed); @@ -39437,27 +42410,27 @@ var BacklinkItem = (props2) => { dangerouslySetInnerHTML: { __html: uiIconSet["mk-ui-collapse"] } - }), /* @__PURE__ */ bn.createElement("div", { + }), /* @__PURE__ */ Cn.createElement("div", { onClick: (e4) => { openAFile(file, props2.plugin, false); e4.stopPropagation(); } - }, fileNameToString(file.name))), !collapsed ? /* @__PURE__ */ bn.createElement("div", { + }, fileNameToString(file.name))), !collapsed ? /* @__PURE__ */ Cn.createElement("div", { className: "mk-file-context-backlink" - }, /* @__PURE__ */ bn.createElement(FlowView, { + }, /* @__PURE__ */ Cn.createElement(FlowView, { plugin: props2.plugin, load: true, path: props2.path, from: block[0], to: block[1] - })) : /* @__PURE__ */ bn.createElement(bn.Fragment, null)); + })) : /* @__PURE__ */ Cn.createElement(Cn.Fragment, null)); }; var Backlinks = (props2) => { - const [collapsed, setCollapsed] = p2( + const [collapsed, setCollapsed] = h2( !props2.plugin.settings.inlineBacklinksExpanded ); - const [backlinks, setBacklinks] = p2([]); - h2(() => { + const [backlinks, setBacklinks] = h2([]); + p2(() => { if (!props2.file) return; setBacklinks( @@ -39466,51 +42439,51 @@ var Backlinks = (props2) => { ) ); }, [props2.file]); - h2(() => { + p2(() => { props2.plugin.settings.inlineBacklinksExpanded = !collapsed; props2.plugin.saveSettings(); }, [collapsed]); const toggleBacklinks = () => { setCollapsed(!collapsed); }; - h2(() => { + p2(() => { window.addEventListener(eventTypes.toggleBacklinks, toggleBacklinks); return () => { window.removeEventListener(eventTypes.toggleBacklinks, toggleBacklinks); }; }, [collapsed]); - return backlinks.length > 0 && props2.file ? /* @__PURE__ */ bn.createElement("div", { + return backlinks.length > 0 && props2.file ? /* @__PURE__ */ Cn.createElement("div", { className: "mk-file-context-component mk-note-footer" - }, /* @__PURE__ */ bn.createElement("div", { + }, /* @__PURE__ */ Cn.createElement("div", { className: "mk-file-context-section" - }, /* @__PURE__ */ bn.createElement("div", { + }, /* @__PURE__ */ Cn.createElement("div", { onClick: (e4) => { setCollapsed(!collapsed); e4.stopPropagation(); }, className: "mk-file-context-title" - }, /* @__PURE__ */ bn.createElement("div", { + }, /* @__PURE__ */ Cn.createElement("div", { className: `mk-icon-xsmall`, dangerouslySetInnerHTML: { __html: uiIconSet["mk-ui-backlink"] } - }), i18n_default.labels.backlinks, /* @__PURE__ */ bn.createElement("button", { + }), 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__ */ bn.createElement("div", null, !collapsed && backlinks.map((f4) => { + })), /* @__PURE__ */ Cn.createElement("div", null, !collapsed && backlinks.map((f4) => { var _a2; - return /* @__PURE__ */ bn.createElement(BacklinkItem, { + return /* @__PURE__ */ Cn.createElement(BacklinkItem, { path: f4, plugin: props2.plugin, source: (_a2 = props2.file) == null ? void 0 : _a2.path }); - })))) : /* @__PURE__ */ bn.createElement(bn.Fragment, null); + })))) : /* @__PURE__ */ Cn.createElement(Cn.Fragment, null); }; // src/components/FileContextView/InlineFileContextView.tsx -var import_obsidian37 = require("obsidian"); +var import_obsidian41 = require("obsidian"); // src/components/FileContextView/FileContextList.tsx var FileContextList = (props2) => { @@ -39531,12 +42504,14 @@ var FileContextList = (props2) => { loadContextFields, predicate } = q2(MDBContext); - const [collapsed, setCollapsed] = p2(false); - const fileContext = F(() => { + const [collapsed, setCollapsed] = h2( + !props2.plugin.settings.inlineContextSectionsExpanded + ); + const fileContext = F2(() => { const td = tableData ? { folder: { cols: tableData.cols.filter( - (f4) => f4.name != "File" && !(f4.type == "fileprop" && (f4.value.startsWith("File") || f4.value.indexOf(".") == -1)) && f4.hidden != "true" && f4.type != "preview" + (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) @@ -39547,7 +42522,7 @@ var FileContextList = (props2) => { ...p3, [c4]: { cols: contextTable[c4].cols.filter( - (f4) => f4.name != "File" && f4.type != "fileprop" && f4.hidden != "true" && f4.type != "preview" + (f4) => f4.name != FilePropertyName && f4.type != "fileprop" && f4.hidden != "true" && f4.type != "preview" ), data: contextTable[c4].rows.find( (r3, index) => index == parseInt(props2.path) @@ -39604,7 +42579,7 @@ var FileContextList = (props2) => { options, field, cols, - contextTable, + contextInfo.contextPath, (newField) => saveField(newField, field), (newField, val) => saveContext(newField, field, val), hideColumn, @@ -39613,37 +42588,37 @@ var FileContextList = (props2) => { predicate.colsHidden.includes(field.name + field.table) ); }; - return /* @__PURE__ */ bn.createElement(bn.Fragment, null, fileContext.folder && fileContext.folder.data && fileContext.folder.cols.length > 0 && /* @__PURE__ */ bn.createElement("div", { + 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__ */ bn.createElement("div", { + }, /* @__PURE__ */ Cn.createElement("div", { className: "mk-file-context-title", onClick: (e4) => { setCollapsed(!collapsed); e4.stopPropagation(); } - }, /* @__PURE__ */ bn.createElement("div", { + }, /* @__PURE__ */ Cn.createElement("div", { className: `mk-icon-xsmall`, dangerouslySetInnerHTML: { - __html: contextInfo.type == "folder" ? uiIconSet["mk-ui-folder"] : uiIconSet["mk-ui-tags"] + __html: contextInfo.type == "folder" ? uiIconSet["mk-ui-folder"] : contextInfo.type == "space" ? uiIconSet["mk-ui-spaces"] : uiIconSet["mk-ui-tags"] } - }), contextInfo.type == "folder" ? folderPathToString(contextInfo.contextPath) : stringFromTag(contextInfo.contextPath), /* @__PURE__ */ bn.createElement("button", { + }), 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__ */ bn.createElement(bn.Fragment, null, fileContext.folder.cols.map((f4, i4) => /* @__PURE__ */ bn.createElement("div", { + })), !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__ */ bn.createElement("div", { + }, /* @__PURE__ */ Cn.createElement("div", { className: "mk-file-context-field", onClick: (e4) => showMenu(e4, { ...f4, table: "" }) - }, f4.name), /* @__PURE__ */ bn.createElement("div", { + }, f4.name), /* @__PURE__ */ Cn.createElement("div", { className: "mk-file-context-value" - }, /* @__PURE__ */ bn.createElement(DataTypeView, { + }, /* @__PURE__ */ Cn.createElement(DataTypeView, { plugin: props2.plugin, initialValue: fileContext.folder.data[f4.name], index: fileContext.folder.dataIndex, - file: fileContext.folder.data["File"], + file: fileContext.folder.data[FilePropertyName], column: { ...f4, table: "" }, editable: !contextInfo.readOnly, updateValue: (v3) => updateValue2( @@ -39651,7 +42626,7 @@ var FileContextList = (props2) => { v3, "", fileContext.folder.dataIndex, - fileContext.folder.data["File"] + fileContext.folder.data[FilePropertyName] ), updateFieldValue: (fv, v3) => updateFieldValue( f4.name, @@ -39659,16 +42634,16 @@ var FileContextList = (props2) => { v3, "", fileContext.folder.dataIndex, - fileContext.folder.data["File"] + fileContext.folder.data[FilePropertyName] ), contextTable - }))))) : /* @__PURE__ */ bn.createElement(bn.Fragment, null))); + }))))) : /* @__PURE__ */ Cn.createElement(Cn.Fragment, null))); }; // src/components/ui/menus/fmMenu.tsx -var import_obsidian34 = require("obsidian"); +var import_obsidian38 = require("obsidian"); var showFMMenu = (plugin, position, property, deleteProperty, syncProperty, renameProperty, changeType) => { - const menu = new import_obsidian34.Menu(); + const menu = new import_obsidian38.Menu(); menu.setUseNativeMenu(false); menu.addItem((menuItem) => { var _a2; @@ -39708,8 +42683,8 @@ var showFMMenu = (plugin, position, property, deleteProperty, syncProperty, rena }; // src/components/ui/modals/moveMetadataModal.tsx -var import_obsidian35 = require("obsidian"); -var MovePropertyModal = class extends import_obsidian35.Modal { +var import_obsidian39 = require("obsidian"); +var MovePropertyModal = class extends import_obsidian39.Modal { constructor(plugin, syncProperty, property, file) { super(plugin.app); this.plugin = plugin; @@ -39730,7 +42705,7 @@ var MovePropertyModal = class extends import_obsidian35.Modal { headerEl.innerHTML = i18n_default.labels.syncMetadata; const root = createRoot(contentEl); root.render( - /* @__PURE__ */ bn.createElement(MovePropertyComponent, { + /* @__PURE__ */ Cn.createElement(MovePropertyComponent, { plugin: this.plugin, syncProperty: this.syncProperty, close: () => this.close(), @@ -39746,8 +42721,8 @@ var MovePropertyModal = class extends import_obsidian35.Modal { }; var MovePropertyComponent = (props2) => { const { plugin } = props2; - const [table, setTable] = p2(""); - const saveContexts = (_7, value) => { + const [table, setTable] = h2(""); + const saveContexts = (_9, value) => { setTable(value[0]); }; const showContextMenu = async (e4) => { @@ -39774,26 +42749,26 @@ var MovePropertyComponent = (props2) => { props2.syncProperty(props2.property, table); props2.close(); }; - return /* @__PURE__ */ bn.createElement("div", { + return /* @__PURE__ */ Cn.createElement("div", { className: "modal-content" - }, /* @__PURE__ */ bn.createElement("div", { + }, /* @__PURE__ */ Cn.createElement("div", { className: "setting-item setting-item-heading" - }, i18n_default.labels.syncProperties), /* @__PURE__ */ bn.createElement("div", { + }, i18n_default.labels.syncProperties), /* @__PURE__ */ Cn.createElement("div", { className: "setting-item" - }, /* @__PURE__ */ bn.createElement("div", { + }, /* @__PURE__ */ Cn.createElement("div", { className: "setting-item-info" - }, /* @__PURE__ */ bn.createElement("div", { + }, /* @__PURE__ */ Cn.createElement("div", { className: "setting-item-name" - }, i18n_default.labels.selectContext), /* @__PURE__ */ bn.createElement("div", { + }, i18n_default.labels.selectContext), /* @__PURE__ */ Cn.createElement("div", { className: "setting-item-description" - }, i18n_default.descriptions.selectContext)), /* @__PURE__ */ bn.createElement("div", { + }, i18n_default.descriptions.selectContext)), /* @__PURE__ */ Cn.createElement("div", { className: "setting-item-control" - }, /* @__PURE__ */ bn.createElement("button", { + }, /* @__PURE__ */ Cn.createElement("button", { onClick: (e4) => showContextMenu(e4) - }, table == "" ? i18n_default.buttons.currentFolder : table))), /* @__PURE__ */ bn.createElement("button", { + }, table == "" ? i18n_default.buttons.currentFolder : table))), /* @__PURE__ */ Cn.createElement("button", { style: { marginRight: 8 }, onClick: () => sync() - }, i18n_default.buttons.sync), /* @__PURE__ */ bn.createElement("button", { + }, i18n_default.buttons.sync), /* @__PURE__ */ Cn.createElement("button", { onClick: () => props2.close() }, i18n_default.buttons.cancel)); }; @@ -39801,16 +42776,15 @@ var MovePropertyComponent = (props2) => { // src/components/FileContextView/FrontmatterView.tsx var FrontmatterView = (props2) => { const { path } = props2; - const [values, setValues] = p2({}); - const [cols, setCols] = p2([]); + const [values, setValues] = h2({}); + const [cols, setCols] = h2([]); const refreshData = async () => { - const promises = await Promise.all( - [ - ...props2.tags.map((f4) => tagContextFromTag(props2.plugin, f4)), - folderContextFromFolder(props2.plugin, props2.folder) - ].map((f4) => columnsForContext(props2.plugin, f4)) - ); - const columns = promises.reduce((p3, c4) => [...p3, ...c4], []); + var _a2; + const fileContexts = (_a2 = props2.plugin.index.contexts.get(path)) != null ? _a2 : /* @__PURE__ */ new Set(); + const columns = [...fileContexts].map((f4) => { + var _a3, _b2; + return (_b2 = (_a3 = props2.plugin.index.contextsCache.get(f4)) == null ? void 0 : _a3.cols) != null ? _b2 : []; + }).reduce((p3, c4) => [...p3, ...c4], []); let newCols = []; let newValues = {}; const types = guestimateTypes([path], props2.plugin, false); @@ -39827,7 +42801,7 @@ var FrontmatterView = (props2) => { if (fm) { newCols.push(...cols2); Object.keys(fm).forEach((c4) => { - newValues[c4] = parseFrontMatter(c4, fm[c4], false); + newValues[c4] = parseFrontMatter(c4, fm[c4]); }); } if (props2.plugin.dataViewAPI() && props2.plugin.settings.dataviewInlineContext) { @@ -39851,45 +42825,39 @@ var FrontmatterView = (props2) => { const dv = dvKeys.reduce( (p3, c4) => ({ ...p3, - [c4]: parseFrontMatter(c4, dvValues[c4], true) + [c4]: parseDataview(c4, dvValues[c4]) }), {} ); newCols.push(...dvCols); Object.keys(dv).forEach((c4) => { - newValues[c4] = parseFrontMatter(c4, dvValues[c4], true); + newValues[c4] = parseDataview(c4, dvValues[c4]); }); } setCols( newCols.filter((f4) => { - var _a2; - return !((_a2 = props2.excludeKeys) == null ? void 0 : _a2.some((g4) => g4 == f4.name)); + var _a3; + return !((_a3 = props2.excludeKeys) == null ? void 0 : _a3.some((g4) => g4 == f4.name)); }) ); setValues(newValues); }; - h2(() => { + p2(() => { refreshData(); }, [path, props2.tags]); - const tagsChanged = (evt) => { - var _a2, _b2; - if (((_b2 = (_a2 = evt.detail) == null ? void 0 : _a2.file) == null ? void 0 : _b2.path) == path) { - refreshData(); - } - }; const mdbChanged = (evt) => { - if (evt.detail.dbPath && props2.tags.find( - (f4) => tagContextFromTag(props2.plugin, f4).dbPath == evt.detail.dbPath + if (evt.detail.type == "context" && evt.detail.contextPath && props2.tags.find( + (f4) => tagContextFromTag(props2.plugin, f4).contextPath == evt.detail.contextPath )) { refreshData(); + } else if (evt.detail.type == "file" && evt.detail.name == path) { + refreshData(); } }; - h2(() => { - window.addEventListener(eventTypes.metadataChange, tagsChanged); - window.addEventListener(eventTypes.mdbChange, mdbChanged); + p2(() => { + window.addEventListener(eventTypes.spacesChange, mdbChanged); return () => { - window.removeEventListener(eventTypes.metadataChange, tagsChanged); - window.removeEventListener(eventTypes.mdbChange, mdbChanged); + window.removeEventListener(eventTypes.spacesChange, mdbChanged); }; }, [path, props2.tags]); const saveFMValue = (value, f4) => { @@ -39941,7 +42909,7 @@ var FrontmatterView = (props2) => { multi: false, editable: false, searchable: false, - saveOptions: (_7, v3) => selectedType(v3, key2), + saveOptions: (_9, v3) => selectedType(v3, key2), value: [], showAll: true, options: fieldTypes.filter((f4) => f4.metadata).map((f4, i4) => ({ @@ -39964,17 +42932,17 @@ var FrontmatterView = (props2) => { selectType ); }; - return cols.length > 0 ? /* @__PURE__ */ bn.createElement(bn.Fragment, null, /* @__PURE__ */ bn.createElement("div", { + return cols.length > 0 ? /* @__PURE__ */ Cn.createElement(Cn.Fragment, null, /* @__PURE__ */ Cn.createElement("div", { className: "mk-file-context-section" - }, /* @__PURE__ */ bn.createElement(bn.Fragment, null, cols.map((f4, i4) => /* @__PURE__ */ bn.createElement("div", { + }, /* @__PURE__ */ Cn.createElement(Cn.Fragment, null, cols.map((f4, i4) => /* @__PURE__ */ Cn.createElement("div", { key: i4, className: "mk-file-context-row" - }, /* @__PURE__ */ bn.createElement("div", { + }, /* @__PURE__ */ Cn.createElement("div", { className: "mk-file-context-field", onClick: (e4) => showMenu(e4, f4) - }, f4.name), /* @__PURE__ */ bn.createElement("div", { + }, f4.name), /* @__PURE__ */ Cn.createElement("div", { className: "mk-file-context-value" - }, /* @__PURE__ */ bn.createElement(DataTypeView, { + }, /* @__PURE__ */ Cn.createElement(DataTypeView, { plugin: props2.plugin, initialValue: values[f4.name], index: 0, @@ -39984,14 +42952,14 @@ var FrontmatterView = (props2) => { updateValue: (value) => saveFMValue(value, f4), updateFieldValue: (fieldValue, value) => saveFMValue(value, f4), contextTable: {} - }))))))) : /* @__PURE__ */ bn.createElement(bn.Fragment, null); + }))))))) : /* @__PURE__ */ Cn.createElement(Cn.Fragment, null); }; // src/components/FileContextView/NoteBannerView.tsx -var import_obsidian36 = require("obsidian"); +var import_obsidian40 = require("obsidian"); var NoteBannerView = (props2) => { - const [banner, setBanner] = p2(null); - h2(() => { + const [banner, setBanner] = h2(null); + p2(() => { var _a2; if (props2.link) { const newBanner = (_a2 = getAbstractFileAtPath(app, props2.link)) != null ? _a2 : props2.link; @@ -40004,7 +42972,7 @@ var NoteBannerView = (props2) => { if (!props2.file) return; e4.preventDefault(); - const fileMenu = new import_obsidian36.Menu(); + const fileMenu = new import_obsidian40.Menu(); fileMenu.addSeparator(); fileMenu.addItem((menuItem) => { menuItem.setTitle(i18n_default.buttons.changeBanner); @@ -40016,7 +42984,7 @@ var NoteBannerView = (props2) => { (image) => saveFrontmatterValue( props2.plugin, props2.file.path, - "banner", + FMBannerKey, image, "image", true @@ -40029,7 +42997,7 @@ var NoteBannerView = (props2) => { menuItem.setTitle(i18n_default.buttons.removeBanner); menuItem.setIcon("lucide-file-minus"); menuItem.onClick((ev) => { - deleteFrontmatterValue(props2.plugin, props2.file.path, "banner"); + deleteFrontmatterValue(props2.plugin, props2.file.path, FMBannerKey); }); }); if (isMouseEvent(e4)) { @@ -40042,64 +43010,53 @@ var NoteBannerView = (props2) => { } return false; }; - return /* @__PURE__ */ bn.createElement("div", { + return /* @__PURE__ */ Cn.createElement("div", { className: `mk-note-header`, onContextMenu: triggerBannerContextMenu - }, banner && /* @__PURE__ */ bn.createElement("img", { - src: banner instanceof import_obsidian36.TFile ? app.vault.getResourcePath(banner) : banner + }, banner && /* @__PURE__ */ Cn.createElement("img", { + src: banner instanceof import_obsidian40.TFile ? app.vault.getResourcePath(banner) : banner })); }; // src/components/FileContextView/InlineFileContextView.tsx var InlineFileContextView = (props2) => { - var _a2; + var _a2, _b2; const { file } = props2; const folderPath = (_a2 = file == null ? void 0 : file.parent) == null ? void 0 : _a2.path; - const context = folderContextFromFolder(props2.plugin, folderPath); - const [collapsed, setCollapsed] = p2( + const [collapsed, setCollapsed] = h2( !props2.showHeader ? false : !props2.plugin.settings.inlineContextExpanded ); - const [fileTags, setFileTags] = p2([]); - const [folderTags, setFolderTags] = p2([]); - const tags = F( - () => [...fileTags, ...folderTags], - [fileTags, folderTags] + const [fileCache, setFileCache] = h2( + props2.plugin.index.files.get(file.path) ); - const [banner, setBanner] = p2(null); - h2(() => { + 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.contextsCache.get(f4)).filter((f4) => f4).map((f4) => f4.info); + }, [fileCache]); + const banner = fileCache == null ? void 0 : fileCache.banner; + p2(() => { props2.plugin.settings.inlineBacklinksExpanded = !collapsed; props2.plugin.saveSettings(); }, [collapsed]); const fileNameRef = _2(null); - const refreshTags = (evt) => { + const refreshFile = () => { if (!file || !file.parent) { return; } - const fm = frontMatterForFile(file); - if (fm == null ? void 0 : fm.banner) { - setBanner(fm.banner); - } else { - setBanner(null); - } - const cx = folderContextFromFolder(props2.plugin, file.parent.path); - const dbFileExists = getAbstractFileAtPath(app, cx.dbPath); - if (dbFileExists) { - getMDBTable(props2.plugin, context, "files").then((folderDB) => { - if (folderDB) { - setFolderTags( - folderDB.schema.def.split("&").filter((f4) => f4.length > 0) - ); - } - }); + const fileCache2 = props2.plugin.index.files.get(file.path); + setFileCache(fileCache2); + }; + const cacheChanged = (evt) => { + if (evt.detail.type == "file" && evt.detail.name == file.path) { + refreshFile(); } - const tags2 = allTagsForFile(file); - setFileTags(tags2); }; - h2(() => { - window.addEventListener(eventTypes.metadataChange, refreshTags); - refreshTags(); + p2(() => { + window.addEventListener(eventTypes.spacesChange, cacheChanged); + refreshFile(); return () => { - window.removeEventListener(eventTypes.metadataChange, refreshTags); + window.removeEventListener(eventTypes.spacesChange, cacheChanged); }; }, [file]); const changeCover = (e4) => { @@ -40109,7 +43066,7 @@ var InlineFileContextView = (props2) => { (image) => saveFrontmatterValue( props2.plugin, file.path, - "banner", + FMBannerKey, image, "image", true @@ -40127,7 +43084,7 @@ var InlineFileContextView = (props2) => { editable: true, value: [], options: f4.map((m5) => ({ name: m5, value: m5 })), - saveOptions: (_7, value) => addTag2(value[0]), + saveOptions: (_9, value) => addTag2(value[0]), placeholder: i18n_default.labels.contextItemSelectPlaceholder, searchable: true, showAll: true @@ -40135,11 +43092,11 @@ var InlineFileContextView = (props2) => { ); }; const addTag2 = (tag) => { - if (file instanceof import_obsidian37.TFile && file.extension == "md") + if (file instanceof import_obsidian41.TFile && file.extension == "md") addTagToNote(tag, file); }; const removeTag = (tag) => { - if (file instanceof import_obsidian37.TFile && file.extension == "md") + if (file instanceof import_obsidian41.TFile && file.extension == "md") removeTagFromFile(tag, file); }; const saveField = (source, field) => { @@ -40155,7 +43112,11 @@ var InlineFileContextView = (props2) => { return; } if (source == "") { - insertContextColumn(props2.plugin, context, field); + insertContextColumn( + props2.plugin, + props2.plugin.index.contextsCache.get(fileCache.parent).info, + field + ); return; } insertContextColumn( @@ -40180,7 +43141,7 @@ var InlineFileContextView = (props2) => { const onBlur = (e4) => { const newValue = e4.target.innerText; if (newValue != fileNameToString(file.name)) { - renameFile(file, newValue + ".md"); + renameFile(props2.plugin, file, newValue + ".md"); } }; const onKeyPress = (e4) => { @@ -40210,11 +43171,11 @@ var InlineFileContextView = (props2) => { e4.target.blur(); } }; - s2(() => { + y2(() => { var _a3; (_a3 = props2.editorView) == null ? void 0 : _a3.requestMeasure(); }, []); - h2(() => { + p2(() => { var _a3; if (file == null ? void 0 : file.name.startsWith("Untitled")) { selectElementContents(fileNameRef.current); @@ -40230,24 +43191,24 @@ var InlineFileContextView = (props2) => { (_a4 = fileNameRef.current) == null ? void 0 : _a4.removeEventListener("paste", pasteEvent); }; }, [fileNameRef]); - return /* @__PURE__ */ bn.createElement(bn.Fragment, null, props2.showHeader && /* @__PURE__ */ bn.createElement(NoteBannerView, { + return /* @__PURE__ */ Cn.createElement(Cn.Fragment, null, props2.showHeader && /* @__PURE__ */ Cn.createElement(NoteBannerView, { plugin: props2.plugin, link: banner, file: props2.file - }), /* @__PURE__ */ bn.createElement("div", { + }), /* @__PURE__ */ Cn.createElement("div", { className: "mk-file-context-component" - }, /* @__PURE__ */ bn.createElement("div", { + }, /* @__PURE__ */ Cn.createElement("div", { className: `mk-spacer`, style: { "--header-height": banner ? ((platformIsMobile() ? 1 : 0) * 26 + 138 + (!props2.plugin.settings.spacesStickers || props2.plugin.settings.inlineContextNameLayout == "horizontal" ? 1 : 0) * 50).toString() + "px" : 0 }, onContextMenu: (e4) => e4.preventDefault() - }), /* @__PURE__ */ bn.createElement("div", { + }), /* @__PURE__ */ Cn.createElement("div", { className: `mk-file-context-file ${props2.plugin.settings.inlineContextNameLayout == "horizontal" ? "mk-file-context-file-horizontal" : ""}` - }, /* @__PURE__ */ bn.createElement(bn.Fragment, null, props2.plugin.settings.spacesStickers ? /* @__PURE__ */ bn.createElement(FileSticker, { + }, /* @__PURE__ */ Cn.createElement(Cn.Fragment, null, props2.plugin.settings.spacesStickers && fileCache ? /* @__PURE__ */ Cn.createElement(FileSticker, { plugin: props2.plugin, - filePath: file.path - }) : /* @__PURE__ */ bn.createElement(bn.Fragment, null), /* @__PURE__ */ bn.createElement("div", { + fileCache + }) : /* @__PURE__ */ Cn.createElement(Cn.Fragment, null), /* @__PURE__ */ Cn.createElement("div", { className: "mk-inline-title inline-title", ref: fileNameRef, contentEditable: props2.editable, @@ -40256,7 +43217,7 @@ var InlineFileContextView = (props2) => { onKeyDown, onKeyPress, onKeyUp - }, fileNameToString(file.name))), /* @__PURE__ */ bn.createElement("div", { + }, fileNameToString(file.name))), /* @__PURE__ */ Cn.createElement("div", { className: `mk-collapse mk-icon-xsmall mk-file-context-collapse ${collapsed ? "mk-collapsed" : ""}`, dangerouslySetInnerHTML: { __html: uiIconSet["mk-ui-collapse"] @@ -40265,70 +43226,57 @@ var InlineFileContextView = (props2) => { setCollapsed(!collapsed); e4.stopPropagation(); } - })), !collapsed && props2.editable ? /* @__PURE__ */ bn.createElement(bn.Fragment, null, /* @__PURE__ */ bn.createElement("div", { + })), !collapsed && props2.editable ? /* @__PURE__ */ Cn.createElement(Cn.Fragment, null, /* @__PURE__ */ Cn.createElement("div", { className: "mk-file-context-field-new" - }, /* @__PURE__ */ bn.createElement("button", { + }, /* @__PURE__ */ Cn.createElement("button", { onClick: (e4) => newProperty(e4) - }, /* @__PURE__ */ bn.createElement("div", { + }, /* @__PURE__ */ Cn.createElement("div", { className: "mk-icon-xsmall", dangerouslySetInnerHTML: { __html: uiIconSet["mk-ui-plus"] } - }), platformIsMobile() ? "Property" : "Add Property"), /* @__PURE__ */ bn.createElement("button", { + }), platformIsMobile() ? "Property" : "Add Property"), /* @__PURE__ */ Cn.createElement("button", { onClick: (e4) => showContextMenu(e4) - }, /* @__PURE__ */ bn.createElement("div", { + }, /* @__PURE__ */ Cn.createElement("div", { className: "mk-icon-xsmall", dangerouslySetInnerHTML: { __html: uiIconSet["mk-ui-tags"] } - }), platformIsMobile() ? "Tag" : "Add Tag"), props2.showHeader ? /* @__PURE__ */ bn.createElement("button", { + }), platformIsMobile() ? "Tag" : "Add Tag"), props2.showHeader ? /* @__PURE__ */ Cn.createElement("button", { onClick: (e4) => changeCover(e4) - }, /* @__PURE__ */ bn.createElement("div", { + }, /* @__PURE__ */ Cn.createElement("div", { className: "mk-icon-xsmall", dangerouslySetInnerHTML: { __html: makeIconSet["mk-make-image"] } - }), platformIsMobile() ? "Cover" : "Change Cover") : /* @__PURE__ */ bn.createElement(bn.Fragment, null)), tags.length > 0 ? /* @__PURE__ */ bn.createElement(TagsView, { + }), platformIsMobile() ? "Cover" : "Change Cover") : /* @__PURE__ */ Cn.createElement(Cn.Fragment, null)), tags.length > 0 ? /* @__PURE__ */ Cn.createElement(TagsView, { plugin: props2.plugin, tags, - removeTag - }) : /* @__PURE__ */ bn.createElement(bn.Fragment, null)) : /* @__PURE__ */ bn.createElement("div", { + removeTag, + canOpen: true + }) : /* @__PURE__ */ Cn.createElement(Cn.Fragment, null)) : /* @__PURE__ */ Cn.createElement("div", { style: { height: 16 } - })), !collapsed ? /* @__PURE__ */ bn.createElement("div", { + })), !collapsed ? /* @__PURE__ */ Cn.createElement("div", { className: "mk-file-context-component" - }, /* @__PURE__ */ bn.createElement(FrontmatterView, { + }, /* @__PURE__ */ Cn.createElement(FrontmatterView, { plugin: props2.plugin, path: file.path, folder: folderPath, tags, - excludeKeys: props2.showHeader ? ["banner"] : [], + excludeKeys: props2.showHeader ? FMMetadataKeys : [], editable: props2.editable - }), tags.map((tag, i4) => /* @__PURE__ */ bn.createElement(MDBProvider, { - key: tag, + }), contexts.map((context, i4) => /* @__PURE__ */ Cn.createElement(MDBProvider, { + key: i4, plugin: props2.plugin, - context: tagContextFromTag(props2.plugin, tag, !props2.editable), + context, file: file.path - }, /* @__PURE__ */ bn.createElement(FileContextList, { + }, /* @__PURE__ */ Cn.createElement(FileContextList, { plugin: props2.plugin, path: file.path, - context: tag, color: "var(--tag-background)" - }))), file && folderPath != "/" && /* @__PURE__ */ bn.createElement(MDBProvider, { - plugin: props2.plugin, - context: folderContextFromFolder( - props2.plugin, - folderPath, - !props2.editable - ), - file: file.path - }, /* @__PURE__ */ bn.createElement(FileContextList, { - plugin: props2.plugin, - path: file.path, - context: folderPath, - color: "var(--color-accent-1)" - })), props2.editable ? /* @__PURE__ */ bn.createElement("div", { + }))), props2.editable ? /* @__PURE__ */ Cn.createElement("div", { style: { height: props2.showHeader ? 16 : 8 } - }) : /* @__PURE__ */ bn.createElement(bn.Fragment, null)) : /* @__PURE__ */ bn.createElement(bn.Fragment, null)); + }) : /* @__PURE__ */ Cn.createElement(Cn.Fragment, null)) : /* @__PURE__ */ Cn.createElement(Cn.Fragment, null)); }; // src/cm-extensions/inlineContext/inlineContext.tsx -var import_obsidian38 = require("obsidian"); +var import_obsidian42 = require("obsidian"); var InlineContextWidget = class extends import_view7.WidgetType { constructor(plugin, file, contentEl) { super(); @@ -40350,7 +43298,7 @@ var InlineContextWidget = class extends import_view7.WidgetType { container.toggleClass("cm-line", true); const anchor = createRoot(container); anchor.render( - /* @__PURE__ */ bn.createElement(bn.Fragment, null, /* @__PURE__ */ bn.createElement(InlineFileContextView, { + /* @__PURE__ */ Cn.createElement(Cn.Fragment, null, /* @__PURE__ */ Cn.createElement(InlineFileContextView, { plugin: this.plugin, file: this.file, editorView: view, @@ -40380,7 +43328,7 @@ var BacklinksWidget = class extends import_view7.WidgetType { const container = document.createElement("div"); const anchor = createRoot(container); anchor.render( - /* @__PURE__ */ bn.createElement(bn.Fragment, null, /* @__PURE__ */ bn.createElement(Backlinks, { + /* @__PURE__ */ Cn.createElement(Cn.Fragment, null, /* @__PURE__ */ Cn.createElement(Backlinks, { plugin: this.plugin, file: this.file })) @@ -40414,12 +43362,13 @@ var StatefulDecorationSet = class { this.plugin = plugin; } async computeAsyncDecorations(state, show) { + var _a2; if (!show) return import_view7.Decoration.none; - if (!state.field(import_obsidian38.editorInfoField)) + if (!state.field(import_obsidian42.editorInfoField)) return null; - const infoField = state.field(import_obsidian38.editorInfoField); - if (!infoField.editor.cm) + const infoField = state.field(import_obsidian42.editorInfoField); + if (!((_a2 = infoField.editor) == null ? void 0 : _a2.cm)) return null; const file = infoField.file; const contentEl = infoField.editor.cm.contentDOM; @@ -40477,9 +43426,13 @@ var frontmatterHider = (plugin) => import_state10.StateField.define({ } } }); - const livePreview = tr.state.field(import_obsidian38.editorLivePreviewField); + const livePreview = tr.state.field(import_obsidian42.editorLivePreviewField); if (fmEnd > 0 && fmEnd < tr.state.doc.length && plugin.settings.hideFrontmatter && livePreview) { - builder.add(fmStart, fmEnd + 1, import_view7.Decoration.replace({ inclusive: true })); + builder.add( + fmStart, + fmEnd + 1, + import_view7.Decoration.replace({ inclusive: true }) + ); } const dec = builder.finish(); return dec; @@ -40493,12 +43446,15 @@ var headerViewPlugin = (plugin) => import_view7.ViewPlugin.fromClass( this.flowTypeState = view.state.field(flowTypeStateField, false); if (this.flowTypeState == "doc" || !this.flowTypeState) this.statefulDecorationsSet.updateAsyncDecorations(view.state, true); - this.livePreview = view.state.field(import_obsidian38.editorLivePreviewField, false); + this.livePreview = view.state.field(import_obsidian42.editorLivePreviewField, false); } showHeader(view) { - if ((view.state.field(flowTypeStateField, false) == "doc" || view.state.field(flowTypeStateField, false) == null) && view.state.field(import_obsidian38.editorLivePreviewField, false)) { + if ((view.state.field(flowTypeStateField, false) == "doc" || view.state.field(flowTypeStateField, false) == null) && view.state.field(import_obsidian42.editorLivePreviewField, false)) { if (!this.headerEnabled) { - this.statefulDecorationsSet.updateAsyncDecorations(view.state, true); + this.statefulDecorationsSet.updateAsyncDecorations( + view.state, + true + ); this.headerEnabled = true; } } else { @@ -40508,10 +43464,10 @@ var headerViewPlugin = (plugin) => import_view7.ViewPlugin.fromClass( } update(update) { var _a2, _b2; - const infoField = update.state.field(import_obsidian38.editorInfoField, false); - if (update.docChanged || update.state.field(flowTypeStateField, false) != this.flowTypeState || this.filePath != ((_a2 = infoField.file) == null ? void 0 : _a2.path) || this.livePreview != update.state.field(import_obsidian38.editorLivePreviewField, false)) { + const infoField = update.state.field(import_obsidian42.editorInfoField, false); + if (update.docChanged || update.state.field(flowTypeStateField, false) != this.flowTypeState || this.filePath != ((_a2 = infoField.file) == null ? void 0 : _a2.path) || this.livePreview != update.state.field(import_obsidian42.editorLivePreviewField, false)) { this.filePath = (_b2 = infoField.file) == null ? void 0 : _b2.path; - this.livePreview = update.state.field(import_obsidian38.editorLivePreviewField, false); + this.livePreview = update.state.field(import_obsidian42.editorLivePreviewField, false); this.flowTypeState = update.state.field(flowTypeStateField, false); this.showHeader(update.view); } @@ -40550,40 +43506,42 @@ var lineNumberExtension = (plugin) => (0, import_view8.lineNumbers)({ // src/cm-extensions/cmExtensions.ts var cmExtensions = (plugin, mobile) => { let extensions = []; - if (plugin.settings.lineNumbers) { - extensions.push(lineNumberExtension(plugin)); - } - if (plugin.settings.inlineContext && plugin.settings.contextEnabled) - extensions.push(...[statefulDecorations.field, headerViewPlugin(plugin), frontmatterHider(plugin)]); - extensions.push( - ...[toggleMarkExtension, tooltips({ parent: document.body })] - ); - if (!mobile && plugin.settings.inlineStyler) { - extensions.push(cursorTooltip(plugin)); - } - if (plugin.settings.makeMenuPlaceholder) - extensions.push(placeholder); - if (plugin.settings.editorFlow) { + if (plugin.settings.makerMode) { + if (plugin.settings.inlineContext && plugin.settings.lineNumbers) { + extensions.push(lineNumberExtension(plugin)); + } + if (plugin.settings.inlineContext && plugin.settings.contextEnabled) + extensions.push(...[statefulDecorations.field, headerViewPlugin(plugin), frontmatterHider(plugin)]); extensions.push( - flowTypeStateField, - editBlockExtensions(), - preloadFlowEditor, - flowEditorField, - flowEditorInfo, - flowIDStateField, - flowViewUpdates + ...[toggleMarkExtension, tooltips({ parent: document.body })] ); - if (plugin.settings.internalLinkClickFlow) { - extensions.push(internalLinkToggle); - } else { - extensions.push(internalLinkHover); + if (!mobile && plugin.settings.inlineStyler) { + extensions.push(cursorTooltip(plugin)); + } + if (plugin.settings.flowMenuEnabled && plugin.settings.makeMenuPlaceholder) + extensions.push(placeholder); + if (plugin.settings.editorFlow) { + extensions.push( + flowTypeStateField, + editBlockExtensions(), + preloadFlowEditor, + flowEditorField, + flowEditorInfo, + flowIDStateField, + flowViewUpdates + ); + if (plugin.settings.internalLinkClickFlow) { + extensions.push(internalLinkToggle); + } else { + extensions.push(internalLinkHover); + } } } return extensions; }; // src/components/MakeMenu/MakeMenu.tsx -var import_obsidian39 = require("obsidian"); +var import_obsidian43 = require("obsidian"); // src/components/MakeMenu/commands/default.ts var default_default2 = [ @@ -40688,7 +43646,7 @@ function resolveCommands(plugin) { } // src/components/MakeMenu/MakeMenu.tsx -var MakeMenu = class extends import_obsidian39.EditorSuggest { +var MakeMenu = class extends import_obsidian43.EditorSuggest { constructor(app2, plugin) { super(app2); this.inCmd = false; @@ -40745,7 +43703,10 @@ var MakeMenu = class extends import_obsidian39.EditorSuggest { if (cmd.value == "table") { this.plugin.createTable(this.file.parent.path).then((f4) => { this.context.editor.replaceRange( - `![![${this.file.parent.path}/#^${f4}]]`, + contextEmbedStringFromContext( + folderContextFromFolder(this.plugin, this.file.parent.path), + f4 + ), { ...this.context.start, ch: this.cmdStartCh }, this.context.end ); @@ -40778,8 +43739,8 @@ var MakeMenu = class extends import_obsidian39.EditorSuggest { }; // src/components/StickerMenu/StickerMenu.tsx -var import_obsidian40 = require("obsidian"); -var StickerMenu = class extends import_obsidian40.EditorSuggest { +var import_obsidian44 = require("obsidian"); +var StickerMenu = class extends import_obsidian44.EditorSuggest { constructor(app2, plugin) { super(app2); this.inCmd = false; @@ -40831,7 +43792,7 @@ var StickerMenu = class extends import_obsidian40.EditorSuggest { div.setAttribute("aria-label", value.label); const reactElement = createRoot(div); reactElement.render( - /* @__PURE__ */ bn.createElement(bn.Fragment, null, value.unicode.length > 0 ? unifiedToNative(value.unicode) : i18n_default.commandsSuggest.noResult) + /* @__PURE__ */ Cn.createElement(Cn.Fragment, null, value.unicode.length > 0 ? stickerFromString(value.unicode) : i18n_default.commandsSuggest.noResult) ); el.appendChild(div); } @@ -40839,7 +43800,7 @@ var StickerMenu = class extends import_obsidian40.EditorSuggest { if (cmd.label === i18n_default.commandsSuggest.noResult) return; this.context.editor.replaceRange( - unifiedToNative(cmd.unicode), + stickerFromString(cmd.unicode), { ...this.context.start, ch: this.cmdStartCh }, this.context.end ); @@ -40849,7 +43810,7 @@ var StickerMenu = class extends import_obsidian40.EditorSuggest { }; // src/main.ts -var import_obsidian55 = require("obsidian"); +var import_obsidian62 = require("obsidian"); // src/utils/flow/markdownPost.tsx var getCMFromElement = (el) => { @@ -40876,12 +43837,12 @@ var replaceAllTables = (plugin, el, ctx) => { for (let match2 of element.textContent.matchAll( /(?:!\[!\[|!!\[\[)([^\]]+)\]\]/g )) { - const link = match2[1]; + const link2 = match2[1]; const reactEl = createRoot(element.parentElement); reactEl.render( - /* @__PURE__ */ bn.createElement(FlowView, { + /* @__PURE__ */ Cn.createElement(FlowView, { plugin, - path: link, + path: link2, load: true }) ); @@ -40929,7 +43890,7 @@ var replaceAllEmbed = (el, ctx) => { const div = dom.createDiv("mk-floweditor-selector"); const reactEl = createRoot(div); reactEl.render( - /* @__PURE__ */ bn.createElement(FlowEditorHover, { + /* @__PURE__ */ Cn.createElement(FlowEditorHover, { toggle: true, type: "file", toggleState: false, @@ -40988,7 +43949,7 @@ var replaceAllEmbed = (el, ctx) => { }; // src/components/Spaces/FileTreeView.tsx -var import_obsidian48 = require("obsidian"); +var import_obsidian52 = require("obsidian"); // node_modules/recoil/es/recoil.js function isPromise(p3) { @@ -41150,7 +44111,7 @@ var Recoil_Loadable = { CANCELED }; var _useMutableSource; -var useMutableSource = (_useMutableSource = bn.useMutableSource) !== null && _useMutableSource !== void 0 ? _useMutableSource : bn.unstable_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); } @@ -41786,7 +44747,7 @@ var Recoil_RecoilValueInterface = { }; var { unstable_batchedUpdates -} = bn; +} = Cn; var ReactBatchedUpdates = { unstable_batchedUpdates }; @@ -42050,11 +45011,11 @@ var hamt_1 = createCommonjsModule(function(module2) { var COLLISION = 2; var INDEX = 3; var ARRAY = 4; - var empty = { + var empty2 = { __hamt_isEmpty: true }; var isEmptyNode = function isEmptyNode2(x5) { - return x5 === empty || x5 && x5.__hamt_isEmpty; + return x5 === empty2 || x5 && x5.__hamt_isEmpty; }; var Leaf = function Leaf2(edit, hash2, key2, value) { return { @@ -42094,7 +45055,7 @@ var hamt_1 = createCommonjsModule(function(module2) { }; }; var isLeaf = function isLeaf2(node) { - return node === empty || node.type === LEAF || node.type === COLLISION; + return node === empty2 || node.type === LEAF || node.type === COLLISION; }; var expand = function expand2(edit, frag, child, bitmap, subNodes) { var arr = []; @@ -42162,7 +45123,7 @@ var hamt_1 = createCommonjsModule(function(module2) { return this; else if (_v === nothing) { --size.value; - return empty; + return empty2; } if (canEditNode(edit, this)) { this.value = _v; @@ -42197,7 +45158,7 @@ var hamt_1 = createCommonjsModule(function(module2) { var bit = toBitmap(frag); var indx = fromBitmap(mask, bit); var exists = mask & bit; - var current = exists ? children[indx] : empty; + var current = exists ? children[indx] : empty2; var child = current._modify(edit, keyEq, shift + SIZE, f4, h5, k5, size); if (current === child) return this; @@ -42207,7 +45168,7 @@ var hamt_1 = createCommonjsModule(function(module2) { if (exists && isEmptyNode(child)) { bitmap &= ~bit; if (!bitmap) - return empty; + return empty2; if (children.length <= 2 && isLeaf(children[indx ^ 1])) return children[indx ^ 1]; newChildren = arraySpliceOut(canEdit, indx, children); @@ -42231,7 +45192,7 @@ var hamt_1 = createCommonjsModule(function(module2) { var children = this.children; var frag = hashFragment(shift, h5); var child = children[frag]; - var newChild = (child || empty)._modify(edit, keyEq, shift + SIZE, f4, h5, k5, size); + var newChild = (child || empty2)._modify(edit, keyEq, shift + SIZE, f4, h5, k5, size); if (child === newChild) return this; var canEdit = canEditNode(edit, this); @@ -42243,7 +45204,7 @@ var hamt_1 = createCommonjsModule(function(module2) { --count3; if (count3 <= MIN_ARRAY_NODE) return pack(edit, count3, frag, children); - newChildren = arrayUpdate(canEdit, frag, empty, children); + newChildren = arrayUpdate(canEdit, frag, empty2, children); } else { newChildren = arrayUpdate(canEdit, frag, newChild, children); } @@ -42254,10 +45215,10 @@ var hamt_1 = createCommonjsModule(function(module2) { } return ArrayNode(edit, count3, newChildren); }; - empty._modify = function(edit, keyEq, shift, f4, h5, k5, size) { + empty2._modify = function(edit, keyEq, shift, f4, h5, k5, size) { var v3 = f4(); if (v3 === nothing) - return empty; + return empty2; ++size.value; return Leaf(edit, h5, k5, v3); }; @@ -42359,7 +45320,7 @@ var hamt_1 = createCommonjsModule(function(module2) { return new Map2(0, 0, { keyEq: config && config.keyEq || defKeyCompare, hash: config && config.hash || hash - }, empty, 0); + }, empty2, 0); }; hamt.empty = hamt.make(); var isEmpty = hamt.isEmpty = function(map) { @@ -42526,7 +45487,7 @@ var hamt_1 = createCommonjsModule(function(module2) { return fold(f4, z5, this); }; var forEach = hamt.forEach = function(f4, map) { - return fold(function(_7, value, key2) { + return fold(function(_9, value, key2) { return f4(value, key2, map); }, null, map); }; @@ -43216,7 +46177,7 @@ var { useMemo, useRef, useState -} = bn; +} = Cn; function notInAContext() { throw new Error("This component must be used inside a component."); } @@ -43251,11 +46212,11 @@ function startNextTreeIfNeeded(store) { storeState.graphsByVersion.set(nextVersion, cloneGraph$1(Recoil_nullthrows(storeState.graphsByVersion.get(version)))); } } -var AppContext = bn.createContext({ +var AppContext = Cn.createContext({ current: defaultStore }); var useStoreRef = () => useContext(AppContext); -var MutableSourceContext = bn.createContext(null); +var MutableSourceContext = Cn.createContext(null); function useRecoilMutableSource() { const mutableSource = useContext(MutableSourceContext); if (mutableSource == null) { @@ -43281,12 +46242,12 @@ function sendEndOfBatchNotifications(store) { if (dirtyAtoms.size) { for (const [key2, subscriptions] of storeState.nodeTransactionSubscriptions) { if (dirtyAtoms.has(key2)) { - for (const [_7, subscription] of subscriptions) { + for (const [_9, subscription] of subscriptions) { subscription(store); } } } - for (const [_7, subscription] of storeState.transactionSubscriptions) { + for (const [_9, subscription] of storeState.transactionSubscriptions) { subscription(store); } if (!Recoil_gkx_1("recoil_early_rendering_2021") || storeState.suspendedComponentResolvers.size) { @@ -43329,7 +46290,7 @@ function Batcher({ setNotifyBatcherOfChange }) { const storeRef = useStoreRef(); - const [_7, setState] = useState([]); + const [_9, setState] = useState([]); setNotifyBatcherOfChange(() => setState({})); useEffect(() => { Recoil_Queue.enqueueExecution("Batcher", () => { @@ -43466,7 +46427,7 @@ function RecoilRoot_INTERNAL({ const setNotifyBatcherOfChange = useCallback((x5) => { notifyBatcherOfChange.current = x5; }, [notifyBatcherOfChange]); - const createMutableSource = (_createMutableSource = bn.createMutableSource) !== null && _createMutableSource !== void 0 ? _createMutableSource : bn.unstable_createMutableSource; + 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, @@ -43482,11 +46443,11 @@ function RecoilRoot_INTERNAL({ cleanUpNode$2(storeRef.current, atomKey); } }, []); - return /* @__PURE__ */ bn.createElement(AppContext.Provider, { + return /* @__PURE__ */ Cn.createElement(AppContext.Provider, { value: storeRef - }, /* @__PURE__ */ bn.createElement(MutableSourceContext.Provider, { + }, /* @__PURE__ */ Cn.createElement(MutableSourceContext.Provider, { value: mutableSource - }, /* @__PURE__ */ bn.createElement(Batcher, { + }, /* @__PURE__ */ Cn.createElement(Batcher, { setNotifyBatcherOfChange }), children)); } @@ -43499,7 +46460,7 @@ function RecoilRoot(props2) { if (override === false && ancestorStoreRef.current !== defaultStore) { return props2.children; } - return /* @__PURE__ */ bn.createElement(RecoilRoot_INTERNAL, propsExceptOverride); + return /* @__PURE__ */ Cn.createElement(RecoilRoot_INTERNAL, propsExceptOverride); } var Recoil_RecoilRoot_react = { useStoreRef, @@ -43747,7 +46708,7 @@ function parseNode(line) { var Recoil_stackTraceParser = stackTraceParser; var { useRef: useRef$1 -} = bn; +} = Cn; function useComponentName() { const nameRef = useRef$1(); if (true) { @@ -43822,7 +46783,7 @@ var { useMemo: useMemo$1, useRef: useRef$2, useState: useState$1 -} = bn; +} = Cn; var SUSPENSE_TIMEOUT_MS = 12e4; function handleLoadable(loadable, recoilValue, storeRef) { if (loadable.state === "hasValue") { @@ -43846,7 +46807,7 @@ function validateRecoilValue(recoilValue, hookName) { } function useRecoilInterface_DEPRECATED() { const storeRef = useStoreRef$1(); - const [_7, forceUpdate] = useState$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()); @@ -43892,7 +46853,7 @@ function useRecoilInterface_DEPRECATED() { }); useEffect$1(() => { const subs = subscriptions.current; - return () => subs.forEach((_8, key2) => unsubscribeFrom(key2)); + return () => subs.forEach((_10, key2) => unsubscribeFrom(key2)); }, [unsubscribeFrom]); return useMemo$1(() => { function useSetRecoilState2(recoilState) { @@ -43998,7 +46959,7 @@ function useRecoilValueLoadable_LEGACY(recoilValue) { validateRecoilValue(recoilValue, "useRecoilValueLoadable"); } const storeRef = useStoreRef$1(); - const [_7, forceUpdate] = useState$1([]); + const [_9, forceUpdate] = useState$1([]); const componentName = Recoil_useComponentName(); useEffect$1(() => { const store = storeRef.current; @@ -44356,14 +47317,14 @@ var { } = Recoil_RecoilRoot_react; var { useMemo: useMemo$2 -} = bn; +} = Cn; function useRecoilBridgeAcrossReactRoots() { const store = useStoreRef$3().current; return useMemo$2(() => { function RecoilBridge({ children }) { - return /* @__PURE__ */ bn.createElement(RecoilRoot$1, { + return /* @__PURE__ */ Cn.createElement(RecoilRoot$1, { store_INTERNAL: store }, children); } @@ -46083,8 +49044,8 @@ var Recoil_index_34 = Recoil_index.setBatcher; var Recoil_index_35 = Recoil_index.snapshot_UNSTABLE; // src/components/ui/modals/hiddenFilesModal.tsx -var import_obsidian41 = require("obsidian"); -var HiddenItemsModal = class extends import_obsidian41.Modal { +var import_obsidian45 = require("obsidian"); +var HiddenItemsModal = class extends import_obsidian45.Modal { constructor(plugin) { super(plugin.app); this.plugin = plugin; @@ -46098,7 +49059,7 @@ var HiddenItemsModal = class extends import_obsidian41.Modal { headerEl.innerHTML = i18n_default.labels.hiddenFiles; const listEl = contentEl.createEl("div"); const root = createRoot(listEl); - root.render(/* @__PURE__ */ bn.createElement(HiddenFiles, { + root.render(/* @__PURE__ */ Cn.createElement(HiddenFiles, { plugin: this.plugin })); const cancelButton = contentEl.createEl("button", { @@ -46114,16 +49075,14 @@ var HiddenItemsModal = class extends import_obsidian41.Modal { } onClose() { let { contentEl } = this; - let event = new CustomEvent(eventTypes.vaultChange); - window.dispatchEvent(event); contentEl.empty(); } }; var HiddenFiles = (props2) => { const { plugin } = props2; const ref = _2(null); - const [hiddenFiles, setHiddenFiles] = p2(plugin.settings.hiddenFiles); - const [hiddenExtensions, setHiddenExtensions] = p2( + const [hiddenFiles, setHiddenFiles] = h2(plugin.settings.hiddenFiles); + const [hiddenExtensions, setHiddenExtensions] = h2( plugin.settings.hiddenExtensions ); const saveExtension = (value) => { @@ -46133,7 +49092,7 @@ var HiddenFiles = (props2) => { ]; plugin.saveSettings(); }; - const saveFile = (_7, value) => { + const saveFile = (_9, value) => { plugin.settings.hiddenFiles = [...plugin.settings.hiddenFiles, ...value]; plugin.saveSettings(); }; @@ -46159,7 +49118,7 @@ var HiddenFiles = (props2) => { setHiddenFiles(plugin.settings.hiddenFiles); setHiddenExtensions(plugin.settings.hiddenExtensions); }; - h2(() => { + p2(() => { window.addEventListener(eventTypes.settingsChanged, settingsChanged); return () => { window.removeEventListener(eventTypes.settingsChanged, settingsChanged); @@ -46185,51 +49144,51 @@ var HiddenFiles = (props2) => { } ); }; - return /* @__PURE__ */ bn.createElement("div", { + return /* @__PURE__ */ Cn.createElement("div", { className: "modal-content" - }, /* @__PURE__ */ bn.createElement("div", { + }, /* @__PURE__ */ Cn.createElement("div", { className: "setting-item setting-item-heading" - }, "Extensions"), /* @__PURE__ */ bn.createElement("div", null, hiddenExtensions.map((f4, index) => /* @__PURE__ */ bn.createElement("div", { + }, "Extensions"), /* @__PURE__ */ Cn.createElement("div", null, hiddenExtensions.map((f4, index) => /* @__PURE__ */ Cn.createElement("div", { className: "mobile-option-setting-item" - }, /* @__PURE__ */ bn.createElement("span", { + }, /* @__PURE__ */ Cn.createElement("span", { className: "mobile-option-setting-item-name" - }, f4), /* @__PURE__ */ bn.createElement("div", { + }, f4), /* @__PURE__ */ Cn.createElement("div", { className: "clickable-icon mobile-option-setting-item-option-icon", "aria-label": i18n_default.buttons.delete, dangerouslySetInnerHTML: { __html: uiIconSet["mk-ui-close"] }, onClick: () => removeExtension(index) - })))), /* @__PURE__ */ bn.createElement("div", { + })))), /* @__PURE__ */ Cn.createElement("div", { className: "setting-item" - }, /* @__PURE__ */ bn.createElement("input", { + }, /* @__PURE__ */ Cn.createElement("input", { placeholder: i18n_default.labels.addExtension, type: "text", ref - }), /* @__PURE__ */ bn.createElement("button", { + }), /* @__PURE__ */ Cn.createElement("button", { onClick: (e4) => addExtension() - }, "+ Add")), /* @__PURE__ */ bn.createElement("div", { + }, "+ Add")), /* @__PURE__ */ Cn.createElement("div", { className: "setting-item setting-item-heading" - }, "Files"), /* @__PURE__ */ bn.createElement("div", null, hiddenFiles.map((f4, index) => /* @__PURE__ */ bn.createElement("div", { + }, "Files"), /* @__PURE__ */ Cn.createElement("div", null, hiddenFiles.map((f4, index) => /* @__PURE__ */ Cn.createElement("div", { className: "mobile-option-setting-item" - }, /* @__PURE__ */ bn.createElement("span", { + }, /* @__PURE__ */ Cn.createElement("span", { className: "mobile-option-setting-item-name" - }, f4), /* @__PURE__ */ bn.createElement("div", { + }, f4), /* @__PURE__ */ Cn.createElement("div", { className: "clickable-icon mobile-option-setting-item-option-icon", "aria-label": i18n_default.buttons.delete, dangerouslySetInnerHTML: { __html: uiIconSet["mk-ui-close"] }, onClick: () => removeItem(index) - })))), /* @__PURE__ */ bn.createElement("div", { + })))), /* @__PURE__ */ Cn.createElement("div", { className: "setting-item" - }, /* @__PURE__ */ bn.createElement("button", { + }, /* @__PURE__ */ Cn.createElement("button", { onClick: (e4) => addMenu(e4) }, "+ ", i18n_default.buttons.addFile))); }; // src/components/Spaces/MainMenu.tsx -var import_obsidian42 = require("obsidian"); +var import_obsidian46 = require("obsidian"); // src/recoil/pluginState.ts var activeFile = Recoil_index_4({ - key: "spacesActiveFile", + key: "spacesActivePath", default: null, dangerouslyAllowMutability: true }); @@ -46267,7 +49226,7 @@ var replaceMobileMainMenu = (plugin) => { header.empty(); const reactEl = createRoot(header); reactEl.render( - /* @__PURE__ */ bn.createElement(Recoil_index_2, null, /* @__PURE__ */ bn.createElement(MainMenu, { + /* @__PURE__ */ Cn.createElement(Recoil_index_2, null, /* @__PURE__ */ Cn.createElement(MainMenu, { plugin, compactMode: plugin.settings.spacesCompactMode })) @@ -46278,7 +49237,7 @@ var MainMenu = (props2) => { var _a2; const { plugin } = props2; const [activeView2, setActiveView] = Recoil_index_14(activeView); - const [spaces2, setSpaces] = Recoil_index_14(spaces); + 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( @@ -46294,11 +49253,16 @@ var MainMenu = (props2) => { const newFile = async () => { await createNewMarkdownFile(props2.plugin, folder, "", ""); }; - const newSection = () => { - let vaultChangeModal = new EditSpaceModal(plugin, "", "create"); - vaultChangeModal.open(); + const loadCachedSpaces = () => { + setSpaces([...plugin.index.allSpaces()]); }; - h2(() => { + p2(() => { + window.addEventListener(eventTypes.spacesChange, loadCachedSpaces); + return () => { + window.removeEventListener(eventTypes.spacesChange, loadCachedSpaces); + }; + }, [loadCachedSpaces]); + p2(() => { refreshLeafs(); }, []); const refreshLeafs = () => { @@ -46317,7 +49281,7 @@ var MainMenu = (props2) => { }; const showMenu = (e4) => { const { spaceActive, leafs } = refreshLeafs(); - const menu = new import_obsidian42.Menu(); + const menu = new import_obsidian46.Menu(); !spaceActive && menu.addItem((menuItem) => { menuItem.setIcon("lucide-arrow-left"); menuItem.setTitle(i18n_default.menu.backToSpace); @@ -46330,7 +49294,7 @@ var MainMenu = (props2) => { }); if (plugin.settings.spacesCompactMode) { menu.addItem((menuItem) => { - menuItem.setTitle(i18n_default.menu.spaces); + menuItem.setTitle(i18n_default.menu.home); menuItem.onClick((ev) => { setActiveView("root"); }); @@ -46341,8 +49305,14 @@ var MainMenu = (props2) => { setActiveView("tags"); }); }); + menu.addItem((menuItem) => { + menuItem.setTitle("All Spaces"); + menuItem.onClick((ev) => { + setActiveView("all"); + }); + }); menu.addSeparator(); - spaces2.filter((f4) => f4.pinned == "true").forEach((space) => { + spaces2.filter((f4) => f4.pinned == "true" || f4.pinned == "pinned").forEach((space) => { menu.addItem((menuItem) => { menuItem.setTitle(space.name); menuItem.onClick((ev) => { @@ -46355,16 +49325,48 @@ var MainMenu = (props2) => { } menu.addItem((menuItem) => { menuItem.setIcon("plus"); - menuItem.setTitle(i18n_default.menu.newSpace); + menuItem.setTitle(i18n_default.buttons.createSection); + menuItem.onClick((ev) => { + let vaultChangeModal = new EditSpaceModal( + plugin, + { + name: "", + def: { + type: "focus", + folder: "", + filters: [] + } + }, + "create" + ); + vaultChangeModal.open(); + }); + }); + menu.addItem((menuItem) => { + menuItem.setIcon("plus"); + menuItem.setTitle(i18n_default.buttons.createSectionSmart); menuItem.onClick((ev) => { - newSection(); + let vaultChangeModal = new EditSpaceModal( + plugin, + { + name: "", + def: { + type: "smart", + folder: "", + filters: [] + } + }, + "create" + ); + vaultChangeModal.open(); }); }); + menu.addSeparator(); menu.addItem((menuItem) => { menuItem.setIcon("sync"); menuItem.setTitle("Reload Spaces"); menuItem.onClick((ev) => { - plugin.reloadSpaceDB(false); + plugin.index.loadSpacesDB(); }); }); menu.addItem((menuItem) => { @@ -46425,34 +49427,34 @@ var MainMenu = (props2) => { const offset = ref.current.getBoundingClientRect(); menu.showAtPosition({ x: offset.left, y: offset.top + 30 }); }; - const currentViewName = activeView2 == "root" ? "Spaces" : activeView2 == "tags" ? "Tags" : activeViewSpace2; - const currentViewIcon = activeView2 == "root" ? uiIconSet["mk-ui-spaces"] : activeView2 == "tags" ? uiIconSet["mk-ui-tags"] : ((_a2 = activeSpace == null ? void 0 : activeSpace.sticker) == null ? void 0 : _a2.length) > 0 ? unifiedToNative(activeSpace.sticker) : activeSpace == null ? void 0 : activeSpace.name.charAt(0); - const menuComponent = () => /* @__PURE__ */ bn.createElement("div", { + 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) : activeSpace == null ? void 0 : activeSpace.name.charAt(0); + const menuComponent = () => /* @__PURE__ */ Cn.createElement("div", { className: "mk-main-menu-container" - }, /* @__PURE__ */ bn.createElement("div", { + }, /* @__PURE__ */ Cn.createElement("div", { className: "mk-main-menu-button", ref, onClick: (e4) => showMenu(e4) - }, plugin.settings.spacesCompactMode ? /* @__PURE__ */ bn.createElement(bn.Fragment, null, /* @__PURE__ */ bn.createElement("div", { + }, 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__ */ bn.createElement("div", { + }), currentViewName) : plugin.app.vault.getName(), /* @__PURE__ */ Cn.createElement("div", { dangerouslySetInnerHTML: { __html: uiIconSet["mk-ui-expand"] } }))); - return props2.compactMode ? /* @__PURE__ */ bn.createElement("div", { + return props2.compactMode ? /* @__PURE__ */ Cn.createElement("div", { className: "mk-flow-bar-compact" - }, " ", menuComponent(), /* @__PURE__ */ bn.createElement("button", { + }, " ", menuComponent(), /* @__PURE__ */ Cn.createElement("button", { "aria-label": i18n_default.buttons.newNote, className: "mk-inline-button", onClick: () => newFile() - }, /* @__PURE__ */ bn.createElement("div", { + }, /* @__PURE__ */ Cn.createElement("div", { className: "mk-icon-small", dangerouslySetInnerHTML: { __html: uiIconSet["mk-ui-new-note"] } - })), /* @__PURE__ */ bn.createElement("button", { - "aria-label": "Blink", + })), props2.plugin.settings.blinkEnabled && /* @__PURE__ */ Cn.createElement("button", { + "aria-label": i18n_default.buttons.blink, className: "mk-inline-button", onClick: () => props2.plugin.quickOpen() - }, /* @__PURE__ */ bn.createElement("div", { + }, /* @__PURE__ */ Cn.createElement("div", { className: "mk-icon-small", dangerouslySetInnerHTML: { __html: uiIconSet["mk-ui-blink"] } }))) : menuComponent(); @@ -46547,7 +49549,7 @@ function observeRect(node, cb) { } }; } -var useIsomorphicLayoutEffect3 = typeof window !== "undefined" ? s2 : h2; +var useIsomorphicLayoutEffect3 = typeof window !== "undefined" ? y2 : p2; function rectReducer(state, action) { var rect = action.rect; if (state.height !== rect.height || state.width !== rect.width) { @@ -46562,9 +49564,9 @@ var useRect2 = function useRect3(nodeRef, initialRect) { height: 0 }; } - var _React$useState = bn.useState(nodeRef.current), element = _React$useState[0], setElement = _React$useState[1]; - var _React$useReducer = bn.useReducer(rectReducer, initialRect), rect = _React$useReducer[0], dispatch = _React$useReducer[1]; - var initialRectSet = bn.useRef(false); + 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); @@ -46579,7 +49581,7 @@ var useRect2 = function useRect3(nodeRef, initialRect) { }); } }, [element]); - bn.useEffect(function() { + Cn.useEffect(function() { if (!element) { return; } @@ -46626,7 +49628,7 @@ var useVirtual = function useVirtual2(_ref) { measurements: [], totalSize: 0 }); - var _React$useState = p2(0), scrollOffset = _React$useState[0], setScrollOffset = _React$useState[1]; + 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]; @@ -46640,12 +49642,12 @@ var useVirtual = function useVirtual2(_ref) { var scrollTo = T2(function(offset) { resolvedScrollToFn(offset, defaultScrollToFn); }, [defaultScrollToFn, resolvedScrollToFn]); - var _React$useState2 = p2({}), measuredCache = _React$useState2[0], setMeasuredCache = _React$useState2[1]; + var _React$useState2 = h2({}), measuredCache = _React$useState2[0], setMeasuredCache = _React$useState2[1]; var measure = T2(function() { return setMeasuredCache({}); }, []); var pendingMeasuredCacheIndexesRef = _2([]); - var measurements = F(function() { + 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); @@ -46690,7 +49692,7 @@ var useVirtual = function useVirtual2(_ref) { }; }, [element, scrollKey]); var _calculateRange = calculateRange(latestRef.current), start = _calculateRange.start, end = _calculateRange.end; - var indexes = F(function() { + var indexes = F2(function() { return rangeExtractor({ start, end, @@ -46700,7 +49702,7 @@ var useVirtual = function useVirtual2(_ref) { }, [start, end, overscan, measurements.length, rangeExtractor]); var measureSizeRef = _2(measureSize); measureSizeRef.current = measureSize; - var virtualItems = F(function() { + var virtualItems = F2(function() { var virtualItems2 = []; var _loop = function _loop2(k6, len2) { var i4 = indexes[k6]; @@ -46832,12 +49834,12 @@ function calculateRange(_ref4) { } // src/components/Spaces/TreeView/FolderTreeView.tsx -var import_obsidian44 = require("obsidian"); -var import_classnames6 = __toESM(require_classnames()); +var import_obsidian48 = require("obsidian"); +var import_classnames7 = __toESM(require_classnames()); // src/components/Spaces/TreeView/SectionView.tsx -var import_classnames5 = __toESM(require_classnames()); -var import_obsidian43 = require("obsidian"); +var import_classnames6 = __toESM(require_classnames()); +var import_obsidian47 = require("obsidian"); var SectionItem = k3( ({ childCount, @@ -46855,21 +49857,23 @@ var SectionItem = k3( onCollapse, wrapperRef, plugin, - disabled + disabled, + active }, ref) => { var _a2, _b2; const [activeFile2, setActiveFile] = Recoil_index_14(activeFile); - const [spaces2, setSpaces] = Recoil_index_14(spaces); - const space = spaces2.find((f4) => f4.name == data.space); + const space = (_a2 = plugin.index.spacesCache.get(data.space)) == null ? void 0 : _a2.space; const triggerMenu = (e4) => { - data.space == "/" ? triggerVaultMenu(e4) : triggerSectionMenu(plugin, data.space, spaces2, e4, activeFile2); + data.space == "/" ? triggerVaultMenu(e4) : triggerSectionMenu( + plugin, + space, + [...plugin.index.allSpaces()], + e4, + activeFile2 + ); }; const triggerVaultMenu = (e4) => { - const refreshFileList = () => { - let event = new CustomEvent(eventTypes.vaultChange); - window.dispatchEvent(event); - }; - const fileMenu = new import_obsidian43.Menu(); + const fileMenu = new import_obsidian47.Menu(); fileMenu.addItem((menuItem) => { menuItem.setIcon("edit"); menuItem.setTitle(i18n_default.buttons.createNote); @@ -46910,7 +49914,6 @@ var SectionItem = k3( menuItem.onClick((ev) => { plugin.settings.vaultSort = ["rank", true]; plugin.saveSettings(); - refreshFileList(); }); }); fileMenu.addSeparator(); @@ -46922,7 +49925,6 @@ var SectionItem = k3( menuItem.onClick((ev) => { plugin.settings.vaultSort = ["path", true]; plugin.saveSettings(); - refreshFileList(); }); }); fileMenu.addItem((menuItem) => { @@ -46933,30 +49935,27 @@ var SectionItem = k3( menuItem.onClick((ev) => { plugin.settings.vaultSort = ["path", false]; plugin.saveSettings(); - refreshFileList(); }); }); fileMenu.addSeparator(); fileMenu.addItem((menuItem) => { menuItem.setTitle(i18n_default.menu.createdTimeSortAsc); menuItem.setChecked( - plugin.settings.vaultSort[0] == "created" && plugin.settings.vaultSort[1] == false + plugin.settings.vaultSort[0] == "ctime" && plugin.settings.vaultSort[1] == false ); menuItem.onClick((ev) => { - plugin.settings.vaultSort = ["created", false]; + plugin.settings.vaultSort = ["ctime", false]; plugin.saveSettings(); - refreshFileList(); }); }); fileMenu.addItem((menuItem) => { menuItem.setTitle(i18n_default.menu.createdTimeSortDesc); menuItem.setChecked( - plugin.settings.vaultSort[0] == "created" && plugin.settings.vaultSort[1] == true + plugin.settings.vaultSort[0] == "ctime" && plugin.settings.vaultSort[1] == true ); menuItem.onClick((ev) => { - plugin.settings.vaultSort = ["created", true]; + plugin.settings.vaultSort = ["ctime", true]; plugin.saveSettings(); - refreshFileList(); }); }); if (isMouseEvent(e4)) { @@ -46969,8 +49968,8 @@ var SectionItem = k3( } return false; }; - return /* @__PURE__ */ bn.createElement(bn.Fragment, null, /* @__PURE__ */ bn.createElement("div", { - className: (0, import_classnames5.default)( + 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", @@ -46983,47 +49982,64 @@ var SectionItem = k3( ...style, ...indicator ? { "--spacing": `${indentationWidth * depth}px` } : {} } - }, /* @__PURE__ */ bn.createElement("div", { + }, /* @__PURE__ */ Cn.createElement("div", { onContextMenu: (e4) => triggerMenu(e4), - className: (0, import_classnames5.default)( + 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__ */ bn.createElement("div", { - className: "mk-section-title", - onClick: (e4) => onCollapse(data), - ref, - ...handleProps - }, ((_a2 = data.spaceItem) == null ? void 0 : _a2.sticker) ? /* @__PURE__ */ bn.createElement("div", { - dangerouslySetInnerHTML: { - __html: unifiedToNative((_b2 = data.spaceItem) == null ? void 0 : _b2.sticker) - } - }) : /* @__PURE__ */ bn.createElement(bn.Fragment, null), /* @__PURE__ */ bn.createElement("div", { - className: "mk-tree-text" - }, data.id == "/" ? plugin.app.vault.getName() : data.space), /* @__PURE__ */ bn.createElement("div", { + }, /* @__PURE__ */ Cn.createElement("div", { className: `mk-collapse ${collapsed ? "mk-collapsed" : ""}`, dangerouslySetInnerHTML: { __html: uiIconSet["mk-ui-collapse-sm"] + }, + onClick: (e4) => onCollapse(data) + }), /* @__PURE__ */ Cn.createElement("div", { + className: (0, import_classnames6.default)( + "mk-tree-item", + "nav-folder-title", + active && "is-selected" + ), + 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) : uiIconSet["mk-ui-spaces"] + }, + onClick: () => { + if (!space) + return; + let vaultChangeModal = new stickerModal( + plugin.app, + (emoji) => saveSpaceIcon(plugin, space.name, emoji) + ); + vaultChangeModal.open(); } - })), /* @__PURE__ */ bn.createElement("div", { + })), /* @__PURE__ */ Cn.createElement("div", { + className: "mk-tree-text", + onClick: (e4) => space ? openSpace(space.name, plugin, false) : {} + }, data.id == "/" ? plugin.app.vault.getName() : data.space), /* @__PURE__ */ Cn.createElement("div", { className: "mk-folder-buttons" - }, /* @__PURE__ */ bn.createElement("button", { - "aria-label": i18n_default.buttons.createFolder, - onClick: () => { - data.space == "/" ? newFolderInVault(plugin, activeFile2) : newFolderInSpace(plugin, space, activeFile2); + }, /* @__PURE__ */ Cn.createElement("button", { + "aria-label": i18n_default.buttons.moreOptions, + onClick: (e4) => { + triggerMenu(e4); + e4.stopPropagation(); }, dangerouslySetInnerHTML: { - __html: uiIconSet["mk-ui-new-folder"] + __html: uiIconSet["mk-ui-options"] } - }), /* @__PURE__ */ bn.createElement("button", { + }), data.space == "/" || ((_b2 = space == null ? void 0 : space.def) == null ? void 0 : _b2.type) == "focus" ? /* @__PURE__ */ Cn.createElement("button", { "aria-label": i18n_default.buttons.newNote, onClick: () => { data.space == "/" ? newFileInVault(plugin, activeFile2) : newFileInSpace(plugin, space, activeFile2); }, dangerouslySetInnerHTML: { - __html: uiIconSet["mk-ui-new-note"] + __html: uiIconSet["mk-ui-plus"] } - }))))); + }) : /* @__PURE__ */ Cn.createElement(Cn.Fragment, null)))))); } ); SectionItem.displayName = "SectionItem"; @@ -47056,14 +50072,14 @@ var SortableTreeItem = ({ disabled, data }); - const memoListeners = F(() => { + const memoListeners = F2(() => { return { ...attributes, ...listeners }; }, [isSorting]); if (data.parentId == null) { - return /* @__PURE__ */ bn.createElement(SectionItem, { + return /* @__PURE__ */ Cn.createElement(SectionItem, { ref: setDraggableNodeRef, wrapperRef: setDroppableNodeRef, data, @@ -47076,7 +50092,7 @@ var SortableTreeItem = ({ ...props2 }); } else { - return /* @__PURE__ */ bn.createElement(TreeItem, { + return /* @__PURE__ */ Cn.createElement(TreeItem, { ref: setDraggableNodeRef, wrapperRef: setDroppableNodeRef, data, @@ -47114,7 +50130,7 @@ var TreeItem = k3( }, ref) => { var _a2; const [activeFile2, setActiveFile] = Recoil_index_14(activeFile); - const [hoverTarget, setHoverTarget] = p2(null); + const [hoverTarget, setHoverTarget] = h2(null); const [selectedFiles2, setSelectedFiles] = Recoil_index_14( selectedFiles ); @@ -47123,16 +50139,17 @@ var TreeItem = k3( onSelectRange(file.id); return; } + if (file.item.isFolder) { + onCollapse(data); + } if (!plugin.settings.contextEnabled) { - if (file.item.folder == "true") { - onCollapse(data); - } else { + if (!file.item.isFolder) { openAFile( getAbstractFileAtPath(app, file.item.path), plugin, e4.ctrlKey || e4.metaKey ); - setActiveFile(file.item.path); + setActiveFile(pathByString(plugin, file.item.path)); setSelectedFiles([file]); } } else { @@ -47141,7 +50158,7 @@ var TreeItem = k3( plugin, e4.ctrlKey || e4.metaKey ); - setActiveFile(file.item.path); + setActiveFile(pathByString(plugin, file.item.path)); setSelectedFiles([file]); } }; @@ -47162,7 +50179,7 @@ var TreeItem = k3( return; } const file = getAbstractFileAtPath(app, data.item.path); - if (file instanceof import_obsidian44.TFolder) { + if (file instanceof import_obsidian48.TFolder) { app.dragManager.onDragStart(e4, { icon: "lucide-folder", source: void 0, @@ -47214,7 +50231,7 @@ var TreeItem = k3( } } }; - h2(() => { + p2(() => { if (hoverTarget && plugin.settings.filePreviewOnHover) { window.addEventListener("keydown", onKeyDown); return () => { @@ -47226,8 +50243,8 @@ var TreeItem = k3( draggable: true, onDragStart: dragStarted } : handleProps; - return /* @__PURE__ */ bn.createElement(bn.Fragment, null, /* @__PURE__ */ bn.createElement("div", { - className: (0, import_classnames6.default)( + 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", @@ -47236,40 +50253,38 @@ var TreeItem = k3( ), ref: wrapperRef, style - }, /* @__PURE__ */ bn.createElement("div", { - className: (0, import_classnames6.default)( - data.item.folder == "true" ? "nav-folder" : "nav-file", + }, /* @__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__ */ bn.createElement("div", { + }, !platformIsMobile() && /* @__PURE__ */ Cn.createElement("div", { className: "mk-drag-handle", dangerouslySetInnerHTML: { __html: uiIconSet["mk-ui-handle"] }, ...handleProps - }), /* @__PURE__ */ bn.createElement("div", { - className: (0, import_classnames6.default)( - `mk-tree-item ${data.item.folder == "true" ? "nav-folder-title" : "nav-file-title"} ${active ? "is-active" : ""} ${selected ? "is-selected" : ""}` + }), /* @__PURE__ */ Cn.createElement("div", { + className: (0, import_classnames7.default)( + `mk-tree-item + ${data.item.isFolder ? "nav-folder-title" : "nav-file-title"} + ${data.item.folderNote ? "mk-folder-is-folder-note" : ""} + ${active ? "is-active" : ""} ${selected ? "is-selected" : ""}` ), ref, style: { "--spacing": `${indentationWidth * depth - 28}px`, - "--childrenCount": `${childCount * plugin.settings.spaceRowHeight - 13}px` + "--childrenCount": `${childCount * spaceRowHeight(plugin) - 13}px` }, onMouseLeave: mouseOut, onMouseEnter: hoverItem, onKeyDown, onClick: (e4) => openFileAtTarget(data, e4), "data-path": data.item.path, - onContextMenu: (e4) => selectedFiles2.length > 1 && selectedFiles2.some((f4) => f4.id == data.id) ? triggerMultiFileMenu(plugin, selectedFiles2, e4) : triggerFileMenu( - plugin, - data.file, - data.item.folder == "true", - e4 - ), + onContextMenu: (e4) => selectedFiles2.length > 1 && selectedFiles2.some((f4) => f4.id == data.id) ? triggerMultiFileMenu(plugin, selectedFiles2, e4) : triggerFileMenu(plugin, data.file, data.item.isFolder, e4), ...innerProps - }, data.item.folder == "true" && /* @__PURE__ */ bn.createElement("button", { + }, data.item.isFolder && /* @__PURE__ */ Cn.createElement("button", { "aria-label": `${collapsed ? i18n_default.labels.expand : i18n_default.labels.collapse}`, className: `mk-collapse ${collapsed ? "mk-collapsed" : ""}`, onClick: (e4) => { @@ -47279,30 +50294,25 @@ var TreeItem = k3( dangerouslySetInnerHTML: { __html: uiIconSet["mk-ui-collapse"] } - }), plugin.settings.spacesStickers && /* @__PURE__ */ bn.createElement(FileSticker, { + }), plugin.settings.spacesStickers && /* @__PURE__ */ Cn.createElement(FileSticker, { plugin, - filePath: data.item.path - }), /* @__PURE__ */ bn.createElement("div", { - className: `mk-tree-text ${data.item.folder == "true" ? "nav-folder-title-content" : "nav-file-title-content"}` - }, data.file ? data.item.folder == "true" ? data.file.name : fileNameToString(data.file.name) : ""), data.item.folder == "false" && data.file && data.file.extension != "md" && /* @__PURE__ */ bn.createElement("span", { + fileCache: data.item + }), /* @__PURE__ */ Cn.createElement("div", { + className: `mk-tree-text ${data.item.isFolder ? "nav-folder-title-content" : "nav-file-title-content"}` + }, data.item.name), !data.item.isFolder && ((_a2 = data.item) == null ? void 0 : _a2.extension) != "md" && /* @__PURE__ */ Cn.createElement("span", { className: "nav-file-tag" - }, (_a2 = data.file) == null ? void 0 : _a2.extension), !clone ? /* @__PURE__ */ bn.createElement("div", { + }, data.item.extension), !clone ? /* @__PURE__ */ Cn.createElement("div", { className: "mk-folder-buttons" - }, /* @__PURE__ */ bn.createElement("button", { + }, /* @__PURE__ */ Cn.createElement("button", { "aria-label": i18n_default.buttons.moreOptions, onClick: (e4) => { - triggerFileMenu( - plugin, - data.file, - data.item.folder == "true", - e4 - ); + triggerFileMenu(plugin, data.file, data.item.isFolder, e4); e4.stopPropagation(); }, dangerouslySetInnerHTML: { __html: uiIconSet["mk-ui-options"] } - }), data.item.folder == "true" && /* @__PURE__ */ bn.createElement("button", { + }), data.item.isFolder && /* @__PURE__ */ Cn.createElement("button", { "aria-label": i18n_default.buttons.newNote, onClick: (e4) => { newFileInFolder(plugin, data.file); @@ -47311,25 +50321,25 @@ var TreeItem = k3( dangerouslySetInnerHTML: { __html: uiIconSet["mk-ui-plus"] } - })) : /* @__PURE__ */ bn.createElement(bn.Fragment, null))))); + })) : /* @__PURE__ */ Cn.createElement(Cn.Fragment, null))))); } ); TreeItem.displayName = "TreeItem"; // src/hooks/ForceUpdate.tsx function useForceUpdate() { - const [value, setValue] = p2(0); + const [value, setValue] = h2(0); return () => setValue((value2) => value2 + 1); } // src/components/Spaces/TreeView/FileExplorerVirtualized.tsx -var import_obsidian45 = require("obsidian"); +var import_obsidian49 = require("obsidian"); // src/utils/ui/dnd.ts function getMaxDepth({ previousItem }) { var _a2; if (previousItem) { - if (((_a2 = previousItem.item) == null ? void 0 : _a2.folder) == "true") + if ((_a2 = previousItem.item) == null ? void 0 : _a2.isFolder) return previousItem.depth + 1; return previousItem.depth; } @@ -47391,26 +50401,26 @@ function getProjection(items, activeItem, overItemIndex, previousItem, nextItem, parentId: getParentId() }; function getParentId() { - var _a2, _b2; + var _a2; if (depth === 0) { return previousItem.space == "/" ? "/" : previousItem.space + "//"; } if (!previousItem) { return "/"; } - if (depth === previousItem.depth || depth > previousItem.depth && ((_a2 = previousItem.item) == null ? void 0 : _a2.folder) != "true") { + if (depth === previousItem.depth || depth > previousItem.depth && !previousItem.item.isFolder) { return previousItem.parentId; } if (depth > previousItem.depth) { return previousItem.id; } - const newParent = (_b2 = items.slice(0, overItemIndex).reverse().find((item) => item.depth === depth)) == null ? void 0 : _b2.parentId; + const newParent = (_a2 = items.slice(0, overItemIndex).reverse().find((item) => item.depth === depth)) == null ? void 0 : _a2.parentId; return newParent != null ? newParent : null; } } // src/components/Spaces/TreeView/FileExplorerVirtualized.tsx -var VirtualizedList = bn.memo( +var VirtualizedList = Cn.memo( (props2) => { const { flattenedTree, @@ -47423,13 +50433,13 @@ var VirtualizedList = bn.memo( plugin, indentationWidth } = props2; - const parentRef = bn.useRef(null); - const rowHeight = (index) => platformIsMobile() ? flattenedTree[index].parentId == null ? 52 : 40 : flattenedTree[index].parentId == null ? 40 : plugin.settings.spaceRowHeight; + 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: bn.useCallback( + estimateSize: Cn.useCallback( (index) => rowHeight(index), [flattenedTree] ), @@ -47437,77 +50447,77 @@ var VirtualizedList = bn.memo( }); vRef.current = rowVirtualizer; rowVirtualizer.scrollToIndex; - return /* @__PURE__ */ bn.createElement("div", { + return /* @__PURE__ */ Cn.createElement("div", { ref: parentRef, style: { width: `100%`, height: `100%`, overflow: "auto" } - }, /* @__PURE__ */ bn.createElement("div", { + }, /* @__PURE__ */ Cn.createElement("div", { style: { height: `${rowVirtualizer.totalSize}px`, width: "100%", position: "relative" } - }, rowVirtualizer.virtualItems.map((virtualRow) => { - var _a2; - return /* @__PURE__ */ bn.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__ */ bn.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.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 == ((_a2 = flattenedTree[virtualRow.index].item) == null ? void 0 : _a2.path), - selected: selectedFiles2.some( - (g4) => g4.id == flattenedTree[virtualRow.index].id - ), - collapsed: flattenedTree[virtualRow.index].collapsed, - onCollapse: handleCollapse - })); - }))); + }, 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.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].path, + selected: selectedFiles2.some( + (g4) => g4.id == flattenedTree[virtualRow.index].id + ), + collapsed: flattenedTree[virtualRow.index].collapsed, + onCollapse: handleCollapse + }))))); } ); var FileExplorerComponent = (props2) => { const { plugin } = props2; const indentationWidth = 24; const isMobile = platformIsMobile(); - const [vaultItems, setVaultItems] = p2({}); - const [expandedFolders2, setExpandedFolders] = p2(plugin.settings.expandedFolders); - const [expandedSpaces, setExpandedSpaces] = p2( + 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] = Recoil_index_14(spaces); - const [vaultSort, setVaultSort] = p2( + const [spaces2, setSpaces] = h2([]); + const [vaultSort, setVaultSort] = h2( plugin.settings.vaultSort.length == 2 ? plugin.settings.vaultSort : ["rank", true] ); const [selectedFiles2, setSelectedFiles] = Recoil_index_14( selectedFiles ); const nextTreeScrollPath = _2(null); - const activeSpaces = F( - () => props2.activeSpace ? spaces2.filter((f4) => f4.name == props2.activeSpace) : spaces2.filter((f4) => f4.pinned != "true"), - [spaces2, props2.activeSpace] + 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] = p2(0); + const [offsetLeft, setOffsetLeft] = h2(0); const listRef = _2(null); const forceUpdate = useForceUpdate(); const treeForSpace = (space) => { @@ -47515,7 +50525,7 @@ var FileExplorerComponent = (props2) => { let tree = []; const spaceCollapsed = !expandedSpaces.includes(space.name); const spaceSort = (_a2 = safelyParseJSON(space.sort)) != null ? _a2 : ["rank", true]; - tree.push(spaceItemToTreeNode(space, spaceCollapsed, spaceSort)); + 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; @@ -47546,7 +50556,7 @@ var FileExplorerComponent = (props2) => { 1, 0, itemCollapsed, - spaceSort[0] == "rank" || spaceSort[0] == "", + space.def.type == "focus" && (spaceSort[0] == "rank" || spaceSort[0] == ""), items.length ) ); @@ -47554,7 +50564,7 @@ var FileExplorerComponent = (props2) => { }); return tree; }; - const flattenedTree = F(() => { + const flattenedTree = F2(() => { var _a2; let tree = []; activeSpaces.forEach((space) => { @@ -47581,6 +50591,7 @@ var FileExplorerComponent = (props2) => { depth: 0, index: 0, space: "/", + path: "/", item: null, collapsed: vaultCollapsed, sortable: vaultSort[0] == "rank", @@ -47609,19 +50620,19 @@ var FileExplorerComponent = (props2) => { vaultSort, props2.activeSpace ]); - h2(() => { + p2(() => { if (selectedFiles2.length <= 1) { - if (!selectedFiles2[0] || selectedFiles2[0].item.path != activeFile2) + if (!selectedFiles2[0] || selectedFiles2[0].item.path != (activeFile2 == null ? void 0 : activeFile2.path)) setSelectedFiles([]); if (plugin.settings.revealActiveFile) - revealFile(getAbstractFileAtPath(app, activeFile2)); + revealFile(activeFile2); } - window.addEventListener(eventTypes.activeFileChange, changeActiveFile); + window.addEventListener(eventTypes.activePathChange, changeActiveFile); return () => { - window.removeEventListener(eventTypes.activeFileChange, changeActiveFile); + window.removeEventListener(eventTypes.activePathChange, changeActiveFile); }; }, [activeFile2]); - h2(() => { + p2(() => { window.addEventListener(eventTypes.refreshView, forceUpdate); window.addEventListener(eventTypes.settingsChanged, settingsChanged); window.addEventListener(eventTypes.revealFile, handleRevealFileEvent); @@ -47631,10 +50642,11 @@ var FileExplorerComponent = (props2) => { window.removeEventListener(eventTypes.revealFile, handleRevealFileEvent); }; }, []); - const revealFile = (file) => { + const revealFile = (path) => { var _a2, _b2; - if (!file) + if (!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}`], @@ -47653,33 +50665,33 @@ var FileExplorerComponent = (props2) => { }; const handleRevealFileEvent = (evt) => { if (evt.detail) - revealFile(evt.detail.file); + revealFile(pathByString(plugin, evt.detail.file.path)); }; const retrieveData = async (folders) => { - const spaces3 = retrieveSpaces(plugin); - const spaceItems = retrieveSpaceItems(plugin, spaces3); + setSpaces(plugin.index.allSpaces()); + const spaceItems = plugin.index.spaces; setVaultItems((g4) => ({ ...g4, - ...Object.keys(spaceItems).reduce( - (p3, c4) => ({ - ...p3, - [c4 + "/"]: spaceItems[c4].map((f4) => { - var _a2; - return { - ...(_a2 = vaultItemForPath(plugin, f4.path)) != null ? _a2 : {}, - ...f4 - }; - }) - }), + ...[...plugin.index.spacesCache.keys()].reduce( + (p3, c4) => { + var _a2; + return { + ...p3, + [c4 + "/"]: [...(_a2 = spaceItems.getInverse(c4)) != null ? _a2 : []].map((f4) => { + var _a3; + const fileCache = plugin.index.files.get(f4); + return { ...fileCache, rank: (_a3 = fileCache == null ? void 0 : fileCache.spaceRanks) == null ? void 0 : _a3[c4] }; + }).filter((f4) => f4) + }; + }, {} ) })); - setSpaces(spaces3); retrieveFolders(plugin, folders).then( (f4) => setVaultItems((g4) => ({ ...g4, ...f4 })) ); }; - const flatFolders = F(() => { + const flatFolders = F2(() => { let allFolders = []; if (expandedSpaces.includes("/")) allFolders.push("/"); @@ -47689,7 +50701,7 @@ var FileExplorerComponent = (props2) => { }); return allFolders; }, [expandedSpaces, expandedFolders2]); - h2(() => { + p2(() => { const newFolders = flatFolders; retrieveData(newFolders); window.addEventListener(eventTypes.spacesChange, spaceChangeEvent); @@ -47698,26 +50710,26 @@ var FileExplorerComponent = (props2) => { }; }, [flatFolders]); const spaceChangeEvent = (evt) => { - if (evt.detail.changeType == "vault" || evt.detail.changeType == "space" || evt.detail.changeType == "sync") { + if (evt.detail.type == "vault" || evt.detail.type == "space" || evt.detail.type == "sync") { retrieveData(flatFolders); } }; const changeActiveFile = (evt) => { - let filePath = evt.detail.filePath; - setActiveFile(filePath); + let path = evt.detail.path; + setActiveFile(path); }; const settingsChanged = () => { setVaultSort(plugin.settings.vaultSort); setExpandedFolders(plugin.settings.expandedFolders); setExpandedSpaces(plugin.settings.expandedSpaces); }; - h2(() => { + p2(() => { settingsChanged(); }, []); - const [activeId, setActiveId] = p2(null); - const [overId, setOverId] = p2(null); - const [currentPosition, setCurrentPosition] = p2(null); - h2(() => { + const [activeId, setActiveId] = h2(null); + const [overId, setOverId] = h2(null); + const [currentPosition, setCurrentPosition] = h2(null); + p2(() => { if (!expandedSpaces.includes(props2.activeSpace)) { plugin.settings.expandedSpaces = uniq([ ...plugin.settings.expandedSpaces, @@ -47726,7 +50738,7 @@ var FileExplorerComponent = (props2) => { plugin.saveSettings(); } }, [props2.activeSpace]); - const sortedIds = F( + const sortedIds = F2( () => flattenedTree.map(({ id: id2 }) => id2), [flattenedTree] ); @@ -47758,10 +50770,10 @@ var FileExplorerComponent = (props2) => { const overIndex = overId ? flattenedTree.findIndex(({ id: id2 }) => id2 === overId) : null; const overItem = flattenedTree[overIndex]; const nextItem = flattenedTree[overIndex + 1]; - const dragDepth = F(() => { + const dragDepth = F2(() => { return getDragDepth(offsetLeft, indentationWidth); }, [offsetLeft]); - const projected = F(() => { + const projected = F2(() => { return activeId && overId ? getProjection( flattenedTree, activeItem, @@ -47803,7 +50815,7 @@ var FileExplorerComponent = (props2) => { moveFile2(active, over); } const moveFile2 = async (active, over) => { - var _a2, _b2, _c2, _d2, _e2, _f, _g, _h, _i, _j; + var _a2, _b2, _c2, _d2, _e2, _f, _g, _h, _i, _j, _k, _l, _m, _n2; if (projected) { const clonedItems = flattenedTree; const overIndex2 = clonedItems.findIndex(({ id: id2 }) => id2 === over.id); @@ -47817,10 +50829,12 @@ var FileExplorerComponent = (props2) => { ); if (activeIsSection) { if (overIsSection) { + const activeSpace = activeSpaces.find( + (f4) => f4.name == activeTreeItem.space + ); insertSpaceAtIndex( plugin, - activeTreeItem.space, - false, + activeSpace, overSpace ? parseInt(overSpace.rank) : spaces2.length ); return; @@ -47830,14 +50844,14 @@ var FileExplorerComponent = (props2) => { const parentItem = clonedItems.find(({ id: id2 }) => id2 === parentId); if (overItem2.space != activeItem.space || overItem2.space != "/") { if (parentId != activeTreeItem.parentId) { - const newParent = (parentItem == null ? void 0 : parentItem.item) ? parentItem.item.folder == "true" ? parentItem.item.path : parentItem.item.parent : "/"; + const newParent = (parentItem == null ? void 0 : parentItem.item) ? parentItem.item.isFolder ? parentItem.item.path : parentItem.item.parent : "/"; const newRank = (_b2 = (_a2 = overItem2.item) == null ? void 0 : _a2.rank) != null ? _b2 : "-1"; const newPath = newParent == "/" ? activeItem.file.name : `${newParent}/${activeItem.file.name}`; if (newPath == activeItem.item.path) { removePathsFromSpace(plugin, activeItem.space, [ activeTreeItem.item.path ]); - if (!(((_c2 = overSpace == null ? void 0 : overSpace.def) == null ? void 0 : _c2.length) > 0) && !(parentItem == null ? void 0 : parentItem.item)) { + if (!(((_d2 = (_c2 = overSpace == null ? void 0 : overSpace.def) == null ? void 0 : _c2.folder) == null ? void 0 : _d2.length) > 0) && !(parentItem == null ? void 0 : parentItem.item)) { insertSpaceItemAtIndex( plugin, overItem2.space, @@ -47848,14 +50862,14 @@ var FileExplorerComponent = (props2) => { return; } else { if (plugin.app.vault.getAbstractFileByPath(newPath)) { - new import_obsidian45.Notice(i18n_default.notice.duplicateFile); + new import_obsidian49.Notice(i18n_default.notice.duplicateFile); return; } } removePathsFromSpace(plugin, activeItem.space, [ activeTreeItem.item.path ]); - if (!(((_d2 = overSpace == null ? void 0 : overSpace.def) == null ? void 0 : _d2.length) > 0) && !(parentItem == null ? void 0 : parentItem.item)) { + if (!(((_f = (_e2 = overSpace == null ? void 0 : overSpace.def) == null ? void 0 : _e2.folder) == null ? void 0 : _f.length) > 0) && !(parentItem == null ? void 0 : parentItem.item)) { insertSpaceItemAtIndex( plugin, overItem2.space, @@ -47867,13 +50881,12 @@ var FileExplorerComponent = (props2) => { plugin, activeTreeItem.item, newParent, - vaultItems, parseInt(newRank) ); return; } if (overItem2.space == activeItem.space && overItem2.space != "/") { - const newRank = (_f = (_e2 = overItem2.item) == null ? void 0 : _e2.rank) != null ? _f : "-1"; + const newRank = (_h = (_g = overItem2.item) == null ? void 0 : _g.rank) != null ? _h : "-1"; if (activeTreeItem.parentId == overItem2.space + "//" && (overIsSection || parentId == overItem2.space + "//")) { insertSpaceItemAtIndex( plugin, @@ -47884,15 +50897,10 @@ var FileExplorerComponent = (props2) => { return; } if (activeTreeItem.parentId == overItem2.id) { - updateFileRank(plugin, activeTreeItem.item, vaultItems, -1); + updateFileRank(plugin, activeTreeItem.item, -1); return; } - updateFileRank( - plugin, - activeTreeItem.item, - vaultItems, - parseInt(newRank) - ); + updateFileRank(plugin, activeTreeItem.item, parseInt(newRank)); return; } if (overItem2.space == "/") { @@ -47901,12 +50909,11 @@ var FileExplorerComponent = (props2) => { if (parentId != overItem2.space + "//" && parentId != null) { return; } - if (activeItem.space != overItem2.space && ((_g = overSpace == null ? void 0 : overSpace.def) == null ? void 0 : _g.length) > 0) { + if (activeItem.space != overItem2.space && ((_j = (_i = overSpace == null ? void 0 : overSpace.def) == null ? void 0 : _i.folder) == null ? void 0 : _j.length) > 0) { moveAFileToNewParentAtIndex( plugin, activeTreeItem.item, - overSpace.def, - vaultItems, + (_k = overSpace.def) == null ? void 0 : _k.folder, parseInt(overItem2.item.rank) ); if (activeItem.space != "/") { @@ -47919,39 +50926,37 @@ var FileExplorerComponent = (props2) => { plugin, overItem2.space, activeItem.item.path, - parseInt((_h = overItem2.item) == null ? void 0 : _h.rank) + parseInt((_l = overItem2.item) == null ? void 0 : _l.rank) ); } return; } if (parentId != activeTreeItem.parentId) { if (overIsSection && activeTreeItem.parentId == "///") { - updateFileRank(plugin, activeTreeItem.item, vaultItems, -1); + updateFileRank(plugin, activeTreeItem.item, -1); return; } - const newParent = (parentItem == null ? void 0 : parentItem.item) ? parentItem.item.folder == "true" ? parentItem.item.path : parentItem.item.parent : "/"; - const newRank = (_j = (_i = overItem2.item) == null ? void 0 : _i.rank) != null ? _j : "-1"; + const newParent = (parentItem == null ? void 0 : parentItem.item) ? parentItem.item.isFolder ? parentItem.item.path : parentItem.item.parent : "/"; + const newRank = (_n2 = (_m = overItem2.item) == null ? void 0 : _m.rank) != null ? _n2 : "-1"; const newPath = newParent == "/" ? activeItem.file.name : `${newParent}/${activeItem.file.name}`; if (plugin.app.vault.getAbstractFileByPath(newPath)) { - new import_obsidian45.Notice(i18n_default.notice.duplicateFile); + new import_obsidian49.Notice(i18n_default.notice.duplicateFile); return; } moveAFileToNewParentAtIndex( plugin, activeTreeItem.item, newParent, - vaultItems, parseInt(newRank) ); } else { if (activeTreeItem.parentId == overItem2.id) { - updateFileRank(plugin, activeTreeItem.item, vaultItems, -1); + updateFileRank(plugin, activeTreeItem.item, -1); return; } updateFileRank( plugin, activeTreeItem.item, - vaultItems, parseInt(overItem2.item.rank) ); } @@ -48007,12 +51012,12 @@ var FileExplorerComponent = (props2) => { onDragEnd: handleDragEnd, onDragCancel: handleDragCancel }); - return /* @__PURE__ */ bn.createElement("div", { + return /* @__PURE__ */ Cn.createElement("div", { className: "mk-file-tree" - }, /* @__PURE__ */ bn.createElement(SortableContext, { + }, /* @__PURE__ */ Cn.createElement(SortableContext, { items: sortedIds, strategy: verticalListSortingStrategy - }, /* @__PURE__ */ bn.createElement(VirtualizedList, { + }, /* @__PURE__ */ Cn.createElement(VirtualizedList, { vRef: listRef, flattenedTree, projected, @@ -48022,12 +51027,12 @@ var FileExplorerComponent = (props2) => { selectedFiles: selectedFiles2, selectRange: selectRange2, indentationWidth - }), j3( - /* @__PURE__ */ bn.createElement(DragOverlay, { + }), z3( + /* @__PURE__ */ Cn.createElement(DragOverlay, { dropAnimation: null, modifiers: [adjustTranslate], zIndex: 1600 - }, activeId ? /* @__PURE__ */ bn.createElement(SortableTreeItem, { + }, activeId ? /* @__PURE__ */ Cn.createElement(SortableTreeItem, { id: activeId, data: flattenedTree.find((f4) => f4.id == activeId), indicator: null, @@ -48046,114 +51051,110 @@ var FileExplorerComponent = (props2) => { }; // src/components/Spaces/SpaceSwitcher/SpaceSwitcher.tsx -var import_classnames7 = __toESM(require_classnames()); +var import_classnames8 = __toESM(require_classnames()); var SpaceSwitcher = (props2) => { const [activeView2, setActiveView] = Recoil_index_14(activeView); - const [spaces2, setSpaces] = Recoil_index_14(spaces); + 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 = F( - () => spaces2.filter((f4) => f4.pinned == "true"), + const pinnedSpaces = F2( + () => spaces2.filter((f4) => f4.pinned == "true" || f4.pinned == "pinned"), [spaces2] ); const [activeViewSpace2, setActiveViewSpace] = Recoil_index_14( activeViewSpace ); - const newSection = () => { - let vaultChangeModal = new EditSpaceModal(props2.plugin, "", "create"); - vaultChangeModal.open(); - }; - h2(() => { + p2(() => { loadCachedSpaces(); }, []); const loadCachedSpaces = () => { + setSpaces([...plugin.index.allSpaces()]); setActiveView(plugin.settings.activeView); setActiveViewSpace(plugin.settings.activeSpace); }; - h2(() => { + 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__ */ bn.createElement(bn.Fragment, null, /* @__PURE__ */ bn.createElement("div", { + return /* @__PURE__ */ Cn.createElement(Cn.Fragment, null, /* @__PURE__ */ Cn.createElement("div", { className: "mk-flow-bar" - }, /* @__PURE__ */ bn.createElement("button", { + }, /* @__PURE__ */ Cn.createElement("button", { "aria-label": i18n_default.buttons.newNote, className: "mk-new-note", onClick: () => newFile() - }, /* @__PURE__ */ bn.createElement("div", { + }, /* @__PURE__ */ Cn.createElement("div", { dangerouslySetInnerHTML: { __html: uiIconSet["mk-ui-new-note"] } - }), /* @__PURE__ */ bn.createElement("p", null, i18n_default.buttons.newNote)), /* @__PURE__ */ bn.createElement("button", { + }), /* @__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__ */ bn.createElement("div", { + }, /* @__PURE__ */ Cn.createElement("div", { dangerouslySetInnerHTML: { __html: uiIconSet["mk-ui-blink"] } - }))), /* @__PURE__ */ bn.createElement("div", { + }))), /* @__PURE__ */ Cn.createElement("div", { className: "mk-sidebar-switcher" - }, /* @__PURE__ */ bn.createElement("div", { - className: (0, import_classnames7.default)( + }, /* @__PURE__ */ Cn.createElement("div", { + className: (0, import_classnames8.default)( "mk-sidebar-item", - pinnedSpaces.length == 0 && "mk-sidebar-expanded", activeView2 == "root" && "mk-sidebar-item-active" ), onClick: () => setActiveView("root") - }, /* @__PURE__ */ bn.createElement("div", { + }, /* @__PURE__ */ Cn.createElement("div", { className: "mk-icon-small", - dangerouslySetInnerHTML: { __html: uiIconSet["mk-ui-spaces"] } - }, " "), pinnedSpaces.length == 0 && /* @__PURE__ */ bn.createElement("div", null, "Spaces")), /* @__PURE__ */ bn.createElement("div", { - className: (0, import_classnames7.default)( + dangerouslySetInnerHTML: { __html: uiIconSet["mk-ui-home"] } + })), /* @__PURE__ */ Cn.createElement("div", { + className: (0, import_classnames8.default)( "mk-sidebar-item", - pinnedSpaces.length == 0 && "mk-sidebar-expanded", activeView2 == "tags" && "mk-sidebar-item-active" ), onClick: () => setActiveView("tags") - }, /* @__PURE__ */ bn.createElement("div", { + }, /* @__PURE__ */ Cn.createElement("div", { className: "mk-icon-small", dangerouslySetInnerHTML: { __html: uiIconSet["mk-ui-tags"] } - }, " "), " ", pinnedSpaces.length == 0 && /* @__PURE__ */ bn.createElement("div", null, "Contexts")), /* @__PURE__ */ bn.createElement("div", { + })), /* @__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) => { var _a2; - return /* @__PURE__ */ bn.createElement("div", { - onContextMenu: (e4) => triggerSectionMenu( - props2.plugin, - pin.name, - spaces2, - e4, - activeFile2 - ), - className: (0, import_classnames7.default)( + return /* @__PURE__ */ Cn.createElement("div", { + 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: unifiedToNative(pin.sticker) } : null + dangerouslySetInnerHTML: ((_a2 = pin.sticker) == null ? void 0 : _a2.length) > 0 ? { __html: stickerFromString(pin.sticker) } : null }, pin.name.substring(0, 1)); - })), /* @__PURE__ */ bn.createElement("div", { - className: (0, import_classnames7.default)("mk-sidebar-item"), - onClick: () => newSection() - }, /* @__PURE__ */ bn.createElement("div", { + })), /* @__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_obsidian46 = require("obsidian"); - -// src/utils/contexts/query.ts -var addQuery = async (plugin, query) => { - const context = queryContextFromQuery(plugin, query); - await createDefaultDB(plugin, context); -}; - -// src/components/ui/modals/tagChangeModal.ts -var TagChangeModal = class extends import_obsidian46.Modal { +var import_obsidian50 = require("obsidian"); +var TagChangeModal = class extends import_obsidian50.Modal { constructor(plugin, action, tag) { super(plugin.app); this.action = action; @@ -48168,8 +51169,6 @@ var TagChangeModal = class extends import_obsidian46.Modal { headerText = "Rename Tag"; } else if (this.action === "create tag") { headerText = "New Tag"; - } else if (this.action === "create query") { - headerText = "New Query"; } const headerEl = contentEl.createEl("div", { text: headerText }); headerEl.addClass("modal-title"); @@ -48184,8 +51183,6 @@ var TagChangeModal = class extends import_obsidian46.Modal { changeButtonText = "Rename Tag"; } else if (this.action === "create tag") { changeButtonText = "Create Tag"; - } else if (this.action === "create query") { - changeButtonText = "Create Query"; } const changeButton = contentEl.createEl("button", { text: changeButtonText @@ -48203,8 +51200,6 @@ var TagChangeModal = class extends import_obsidian46.Modal { renameTag(this.plugin, this.tag, newName); } else if (this.action === "create tag") { addTag(this.plugin, newName); - } else if (this.action == "create query") { - addQuery(this.plugin, newName); } myModal.close(); }; @@ -48224,12 +51219,12 @@ var TagChangeModal = class extends import_obsidian46.Modal { // src/components/Spaces/TagContextList/TagContextList.tsx var import_lodash8 = __toESM(require_lodash()); -var import_obsidian47 = require("obsidian"); +var import_obsidian51 = require("obsidian"); var TagContextList = (props2) => { - const [allTags, setAllTags] = p2([]); - const [allQueries, setAllQueries] = p2([]); + const [allTags, setAllTags] = h2([]); + const [allQueries, setAllQueries] = h2([]); const openContextMenu = async (e4, tag) => { - const fileMenu = new import_obsidian47.Menu(); + const fileMenu = new import_obsidian51.Menu(); fileMenu.addItem((menuItem) => { menuItem.setTitle("Rename Tag"); menuItem.setIcon("edit"); @@ -48255,27 +51250,14 @@ var TagContextList = (props2) => { } }; const openContextView = async (tag) => { - openContext(tag, props2.plugin, false); + openTagContext(tag, props2.plugin, false); }; - h2(() => { - window.addEventListener(eventTypes.metadataChange, refreshTags); + p2(() => { window.addEventListener(eventTypes.spacesChange, refreshData); return () => { - window.removeEventListener(eventTypes.metadataChange, refreshTags); window.removeEventListener(eventTypes.spacesChange, refreshData); }; }, []); - const refreshQueries = () => { - 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_obsidian47.TFile && f5.extension == "mdb" && f5.name.charAt(0) == "?" - ).map((f5) => tagPathToTag(fileNameToString(f5.name)))) != null ? _a2 : []; - setAllQueries(f4.filter((g4) => g4)); - }; const refreshData = () => { refreshTags(); }; @@ -48286,16 +51268,16 @@ var TagContextList = (props2) => { getFolderPathFromString(props2.plugin.settings.tagContextFolder) ); const f4 = (_a2 = folder == null ? void 0 : folder.children.filter( - (f5) => f5 instanceof import_obsidian47.TFile && f5.extension == "mdb" && f5.name.charAt(0) == "#" + (f5) => f5 instanceof import_obsidian51.TFile && f5.extension == "mdb" && f5.name.charAt(0) == "#" ).map((f5) => tagPathToTag(fileNameToString(f5.name)))) != null ? _a2 : []; setAllTags( (0, import_lodash8.uniq)([...f4.filter((g4) => g4), ...Object.keys(app.metadataCache.getTags())]) ); }; - h2(() => { + p2(() => { refreshData(); }, []); - const tags = F(() => { + const tags = F2(() => { return (0, import_lodash8.uniq)( allTags.reduce((p3, c4) => { const r3 = c4.split("/"); @@ -48315,17 +51297,17 @@ var TagContextList = (props2) => { }).sort(compareByFieldCaseInsensitive("tag", true)); }, [allTags]); const indentationWidth = 24; - return /* @__PURE__ */ bn.createElement("div", { + return /* @__PURE__ */ Cn.createElement("div", { className: "tag-container mk-context-tree" - }, /* @__PURE__ */ bn.createElement("div", { + }, /* @__PURE__ */ Cn.createElement("div", { className: "mk-tree-wrapper" - }, /* @__PURE__ */ bn.createElement("div", { + }, /* @__PURE__ */ Cn.createElement("div", { className: "mk-section" - }, /* @__PURE__ */ bn.createElement("div", { + }, /* @__PURE__ */ Cn.createElement("div", { className: "mk-section-title" - }, /* @__PURE__ */ bn.createElement("div", { + }, /* @__PURE__ */ Cn.createElement("div", { className: "mk-tree-text" - }, "Tags")), /* @__PURE__ */ bn.createElement("div", null, /* @__PURE__ */ bn.createElement("button", { + }, "Tags")), /* @__PURE__ */ Cn.createElement("div", null, /* @__PURE__ */ Cn.createElement("button", { "aria-label": "New Tag", className: "mk-inline-button", onClick: () => { @@ -48338,18 +51320,18 @@ var TagContextList = (props2) => { dangerouslySetInnerHTML: { __html: uiIconSet["mk-ui-plus"] } - })))), /* @__PURE__ */ bn.createElement("div", { + })))), /* @__PURE__ */ Cn.createElement("div", { className: "tree-item" - }, tags.map((f4) => /* @__PURE__ */ bn.createElement("div", { + }, tags.map((f4) => /* @__PURE__ */ Cn.createElement("div", { 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` } - }, /* @__PURE__ */ bn.createElement("div", { + }, /* @__PURE__ */ Cn.createElement("div", { className: "mk-file-icon" - }, /* @__PURE__ */ bn.createElement("button", { + }, /* @__PURE__ */ Cn.createElement("button", { dangerouslySetInnerHTML: { __html: uiIconSet["mk-ui-tags"] } @@ -48359,18 +51341,32 @@ var TagContextList = (props2) => { // src/components/Spaces/MainList.tsx var MainList = (props2) => { const [activeView2, setActiveView] = Recoil_index_14(activeView); - const [spaces2, setSpaces] = Recoil_index_14(spaces); + const [spaces2, setSpaces] = h2(props2.plugin.index.allSpaces()); const [activeViewSpace2, setActiveViewSpace] = Recoil_index_14( activeViewSpace ); + const [syncState, setSyncState] = h2(props2.plugin.index.syncStatus); const [error, resetError] = P2(); if (error) console.log(error); - h2(() => { - if (activeView2 == "space" && !spaces2.some((f4) => f4.name == activeViewSpace2 && f4.pinned == "true")) { + 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: { @@ -48391,47 +51387,64 @@ var MainList = (props2) => { }; const viewForState = (viewType, space) => { if (viewType == "root") { - return /* @__PURE__ */ bn.createElement(FileExplorerComponent, { + return /* @__PURE__ */ Cn.createElement(FileExplorerComponent, { + viewType, plugin: props2.plugin }); } else if (viewType == "tags") { - return /* @__PURE__ */ bn.createElement(TagContextList, { + return /* @__PURE__ */ Cn.createElement(TagContextList, { plugin: props2.plugin }); } else if (viewType == "space") { - return /* @__PURE__ */ bn.createElement(FileExplorerComponent, { + 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__ */ bn.createElement(FileExplorerComponent, { - plugin: props2.plugin + return /* @__PURE__ */ Cn.createElement(FileExplorerComponent, { + plugin: props2.plugin, + viewType: "root" }); }; - return /* @__PURE__ */ bn.createElement(DndContext, { + return /* @__PURE__ */ Cn.createElement(DndContext, { sensors, collisionDetection: closestCenter, measuring - }, !platformIsMobile() ? props2.plugin.settings.spacesCompactMode ? /* @__PURE__ */ bn.createElement(MainMenu, { + }, !platformIsMobile() ? props2.plugin.settings.spacesCompactMode ? /* @__PURE__ */ Cn.createElement(MainMenu, { plugin: props2.plugin, compactMode: true - }) : /* @__PURE__ */ bn.createElement(SpaceSwitcher, { + }) : /* @__PURE__ */ Cn.createElement(SpaceSwitcher, { + plugin: props2.plugin + }) : /* @__PURE__ */ Cn.createElement(SpaceSwitcher, { plugin: props2.plugin - }) : /* @__PURE__ */ bn.createElement(bn.Fragment, null), viewForState(activeView2, activeViewSpace2)); + }), 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)); }; // src/components/Spaces/FileTreeView.tsx var FILE_TREE_VIEW_TYPE = "mk-file-view"; var VIEW_DISPLAY_TEXT = "Spaces"; var ICON = "layout-grid"; -var FileTreeView = class extends import_obsidian48.ItemView { +var FileTreeView = class extends import_obsidian52.ItemView { constructor(leaf, plugin) { super(leaf); this.navigation = false; this.plugin = plugin; } revealInFolder(file) { - if (file instanceof import_obsidian48.TFolder) { + if (file instanceof import_obsidian52.TFolder) { this.plugin.app.workspace.activeLeaf.setViewState({ type: CONTEXT_VIEW_TYPE, state: { contextPath: file.path } @@ -48473,24 +51486,26 @@ var FileTreeView = class extends import_obsidian48.ItemView { this.destroy(); this.root = createRoot(this.contentEl); this.root.render( - /* @__PURE__ */ bn.createElement("div", { + /* @__PURE__ */ Cn.createElement("div", { className: "mk-sidebar" - }, /* @__PURE__ */ bn.createElement(Recoil_index_2, null, !platformIsMobile() && !this.plugin.settings.spacesCompactMode ? /* @__PURE__ */ bn.createElement(MainMenu, { + }, /* @__PURE__ */ Cn.createElement(Recoil_index_2, null, !platformIsMobile() && !this.plugin.settings.spacesCompactMode ? /* @__PURE__ */ Cn.createElement(MainMenu, { plugin: this.plugin, compactMode: false - }) : null, /* @__PURE__ */ bn.createElement(MainList, { + }) : null, /* @__PURE__ */ Cn.createElement(MainList, { plugin: this.plugin }))) ); } }; -// src/settings.ts -var import_obsidian49 = require("obsidian"); +// src/settings/settings.ts +var import_obsidian53 = require("obsidian"); var DEFAULT_SETTINGS = { defaultInitialization: false, filePreviewOnHover: false, + flowMenuEnabled: true, markSans: false, + blinkEnabled: true, makeMenuPlaceholder: true, mobileMakeBar: true, inlineStyler: true, @@ -48522,15 +51537,9 @@ var DEFAULT_SETTINGS = { deleteFileOption: "trash", expandedFolders: {}, expandedSpaces: ["/"], - folderRank: { - node: "root", - children: [], - isFolder: true - }, openFolders: [], fileIcons: [], - spaces: [], - pinnedSpaces: [], + cachedSpaces: [], menuTriggerChar: "/", emojiTriggerChar: ":", folderContextFile: "context", @@ -48541,69 +51550,32 @@ var DEFAULT_SETTINGS = { vaultSort: ["rank", true], newFileLocation: "root", newFileFolderPath: "", - inlineBacklinks: true, + inlineBacklinks: false, inlineContext: true, inlineBacklinksExpanded: false, inlineContextExpanded: true, + inlineContextSectionsExpanded: true, dataviewInlineContext: false, - inlineContextNameLayout: "vertical" -}; -var MakeMDPluginSettingsTab = class extends import_obsidian49.PluginSettingTab { + inlineContextNameLayout: "vertical", + spacesSyncLastUpdated: "Context/spacesLastSync.log", + spacesSyncTimeoutSeconds: 10, + spacesAutoBackup: true, + spacesAutoBackupInterval: 10, + spacesAutoBackupLast: 0 +}; +var MakeMDPluginSettingsTab = class extends import_obsidian53.PluginSettingTab { constructor(app2, plugin) { super(app2, plugin); this.plugin = plugin; } refreshView() { - let evt = new CustomEvent(eventTypes.refreshView, {}); - window.dispatchEvent(evt); + this.display(); } display() { let { containerEl } = this; containerEl.empty(); - containerEl.createEl("h2", { text: i18n_default.settings.sectionAppearance }); - new import_obsidian49.Setting(containerEl).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_obsidian49.Setting(containerEl).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_obsidian49.Setting(containerEl).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_obsidian49.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_obsidian49.Setting(containerEl).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_obsidian49.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("h2", { text: i18n_default.settings.sectionSidebar }); - new import_obsidian49.Setting(containerEl).setName(i18n_default.settings.spaces.name).setDesc(i18n_default.settings.spaces.desc).addToggle( + containerEl.createEl("h1", { text: i18n_default.settings.sectionSidebar }); + new import_obsidian53.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(); @@ -48615,218 +51587,312 @@ var MakeMDPluginSettingsTab = class extends import_obsidian49.PluginSettingTab { this.refreshView(); }) ); - new import_obsidian49.Setting(containerEl).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_obsidian49.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_obsidian49.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_obsidian49.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(); - }) - ); - containerEl.createEl("h2", { text: "Context" }); - new import_obsidian49.Setting(containerEl).setName(i18n_default.settings.contexts.name).setDesc(i18n_default.settings.contexts.desc).addToggle( + if (this.plugin.settings.spacesEnabled) { + containerEl.createEl("h3", { text: i18n_default.settings.sectionAppearance }); + let spaceAppearances = containerEl.createEl("div"); + new import_obsidian53.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_obsidian53.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_obsidian53.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_obsidian53.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_obsidian53.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(); + }) + ); + containerEl.createEl("h3", { text: "Folder Note" }); + new import_obsidian53.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_obsidian53.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(); + }) + ); + containerEl.createEl("h3", { text: "Sync and Backup" }); + new import_obsidian53.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_obsidian53.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_obsidian53.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_obsidian53.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_obsidian53.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_obsidian53.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_obsidian53.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_obsidian53.Setting(containerEl).setName(i18n_default.settings.spacesDeleteOption.name).setDesc(i18n_default.settings.spacesDeleteOption.desc).addDropdown((dropdown) => { + dropdown.addOption( + "permanent", + i18n_default.settings.spacesDeleteOptions.permanant + ); + dropdown.addOption("trash", i18n_default.settings.spacesDeleteOptions.trash); + dropdown.addOption( + "system-trash", + i18n_default.settings.spacesDeleteOptions["system-trash"] + ); + dropdown.setValue(this.plugin.settings.deleteFileOption); + dropdown.onChange((option) => { + this.plugin.settings.deleteFileOption = option; + this.plugin.saveSettings(); + }); + }); + } + containerEl.createEl("h1", { text: "Context" }); + new import_obsidian53.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(); this.plugin.reloadExtensions(false); }) ); - new import_obsidian49.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_obsidian49.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); - dropdown.onChange((option) => { - this.plugin.settings.inlineContextNameLayout = option; - this.plugin.saveSettings(); + containerEl.createEl("h3", { text: i18n_default.settings.sectionAppearance }); + new import_obsidian53.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(); }); }); - new import_obsidian49.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_obsidian49.Setting(containerEl).setName(i18n_default.settings.openFileContext.name).setDesc(i18n_default.settings.openFileContext.desc).addToggle( + containerEl.createEl("h3", { text: i18n_default.settings.sectionAdvanced }); + new import_obsidian53.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_obsidian49.Setting(containerEl).setName(i18n_default.settings.syncContextToFrontmatter.name).setDesc(i18n_default.settings.syncContextToFrontmatter.desc).addToggle( + new import_obsidian53.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("h2", { text: i18n_default.settings.sectionFlow }); - new import_obsidian49.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; + containerEl.createEl("h1", { text: "Blink" }); + new import_obsidian53.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(); this.plugin.reloadExtensions(false); }) ); - new import_obsidian49.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_obsidian49.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); - dropdown.setValue(this.plugin.settings.editorFlowStyle).onChange(async (value) => { - this.plugin.settings.editorFlowStyle = value; - document.body.classList.toggle("mk-flow-classic", false); - document.body.classList.toggle("mk-flow-seamless", false); - document.body.classList.toggle("mk-flow-minimal", false); - if (value == "seamless") - document.body.classList.toggle("mk-flow-seamless", true); - if (value == "classic") - document.body.classList.toggle("mk-flow-classic", true); - if (value == "minimal") - document.body.classList.toggle("mk-flow-minimal", true); - }); - }); - new import_obsidian49.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(); - this.plugin.reloadExtensions(false); - }) - ); - containerEl.createEl("h2", { text: i18n_default.settings.sectionEditor }); - new import_obsidian49.Setting(containerEl).setName(i18n_default.settings.editorMakerMode.name).setDesc(i18n_default.settings.editorMakerMode.desc).addToggle( + containerEl.createEl("h1", { text: i18n_default.settings.sectionFlow }); + new import_obsidian53.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(); this.refreshView(); }) ); - new import_obsidian49.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.trim().length < 1) { - text2.setValue(this.plugin.settings.menuTriggerChar); - return; - } - let char = value[0]; - if (value.trim().length === 2) { - char = value.replace(this.plugin.settings.menuTriggerChar, ""); - } - text2.setValue(char); - this.plugin.settings.menuTriggerChar = char; - await this.plugin.saveSettings(); + if (this.plugin.settings.makerMode) { + containerEl.createEl("h3", { text: "Inline Context" }); + new import_obsidian53.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_obsidian53.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_obsidian53.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_obsidian53.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); + dropdown.onChange((option) => { + this.plugin.settings.inlineContextNameLayout = option; + this.plugin.saveSettings(); + }); }); - }); - new import_obsidian49.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(); - this.plugin.reloadExtensions(false); - }) - ); - new import_obsidian49.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(); - this.refreshView(); - }) - ); - new import_obsidian49.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); - }) - ); - containerEl.createEl("h2", { text: i18n_default.settings.sectionDataview }); - new import_obsidian49.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(); - }) - ); - containerEl.createEl("h2", { text: i18n_default.settings.sectionAdvanced }); - new import_obsidian49.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_obsidian49.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_obsidian49.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_obsidian49.Setting(containerEl).setName(i18n_default.settings.spacesDeleteOption.name).setDesc(i18n_default.settings.spacesDeleteOption.desc).addDropdown((dropdown) => { - dropdown.addOption( - "permanent", - i18n_default.settings.spacesDeleteOptions.permanant + new import_obsidian53.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); + }) ); - dropdown.addOption("trash", i18n_default.settings.spacesDeleteOptions.trash); - dropdown.addOption( - "system-trash", - i18n_default.settings.spacesDeleteOptions["system-trash"] + new import_obsidian53.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(); + }) ); - dropdown.setValue(this.plugin.settings.deleteFileOption); - dropdown.onChange((option) => { - this.plugin.settings.deleteFileOption = option; - this.plugin.saveSettings(); + new import_obsidian53.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(); + this.plugin.reloadExtensions(false); + }) + ); + containerEl.createEl("h3", { text: "Flow Block" }); + new import_obsidian53.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_obsidian53.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_obsidian53.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); + dropdown.setValue(this.plugin.settings.editorFlowStyle).onChange(async (value) => { + this.plugin.settings.editorFlowStyle = value; + document.body.classList.toggle("mk-flow-classic", false); + document.body.classList.toggle("mk-flow-seamless", false); + document.body.classList.toggle("mk-flow-minimal", false); + if (value == "seamless") + document.body.classList.toggle("mk-flow-seamless", true); + if (value == "classic") + document.body.classList.toggle("mk-flow-classic", true); + if (value == "minimal") + document.body.classList.toggle("mk-flow-minimal", true); + }); }); - }); - new import_obsidian49.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(); - }) - ); + containerEl.createEl("h3", { text: "Flow Menu" }); + new import_obsidian53.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_obsidian53.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.trim().length < 1) { + text2.setValue(this.plugin.settings.menuTriggerChar); + return; + } + let char = value[0]; + if (value.trim().length === 2) { + char = value.replace(this.plugin.settings.menuTriggerChar, ""); + } + text2.setValue(char); + this.plugin.settings.menuTriggerChar = char; + await this.plugin.saveSettings(); + }); + }); + new import_obsidian53.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(); + this.plugin.reloadExtensions(false); + }) + ); + containerEl.createEl("h3", { text: "Flow Styler" }); + new import_obsidian53.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_obsidian53.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_obsidian53.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(); + this.refreshView(); + }) + ); + } } }; // src/components/Blink/Blink.tsx -var import_obsidian50 = require("obsidian"); +var import_obsidian54 = require("obsidian"); // src/components/Blink/BlinkComponent.tsx -var BlinkComponent = bn.forwardRef( +var BlinkComponent = Cn.forwardRef( (props2, ref) => { - const [previewPath, setPreviewPath] = p2(null); - const [allItems, setAllItems] = p2([]); - const defaultOptions3 = F( + const [previewPath, setPreviewPath] = h2(null); + const [allItems, setAllItems] = h2([]); + const defaultOptions3 = F2( () => app.workspace.getLastOpenFiles().filter((f4) => getAbstractFileAtPath(app, f4)).map((f4) => ({ description: f4, value: f4, @@ -48834,7 +51900,7 @@ var BlinkComponent = bn.forwardRef( })), [] ); - h2(() => { + p2(() => { const allTags = loadTags(props2.plugin).map((f4) => ({ value: f4, name: f4 @@ -48860,24 +51926,7 @@ var BlinkComponent = bn.forwardRef( const selectItem = (item) => { if (!item) return; - const type = viewTypeByString(item); - if (type == "file" || type == "folder") { - openAFile(getAbstractFileAtPath(app, item), props2.plugin, false); - return; - } - if (type == "tag") { - openContext(item, props2.plugin, false); - return; - } - if (type == "url") { - openURL(item); - return; - } - createNewMarkdownFile( - props2.plugin, - defaultNoteFolder(props2.plugin, null), - item - ); + openPath(props2.plugin, pathByString(props2.plugin, item)); }; const optionProps = { multi: false, @@ -48886,18 +51935,18 @@ var BlinkComponent = bn.forwardRef( value: [], options: allItems, defaultOptions: defaultOptions3, - saveOptions: (_7, items) => selectItem(items[0]), + saveOptions: (_9, items) => selectItem(items[0]), placeholder: i18n_default.labels.blinkPlaceholder, searchable: true, showAll: true }; - return /* @__PURE__ */ bn.createElement(bn.Fragment, null, /* @__PURE__ */ bn.createElement(SelectMenu, { + return /* @__PURE__ */ Cn.createElement(Cn.Fragment, null, /* @__PURE__ */ Cn.createElement(SelectMenu, { ref, ...optionProps, hide: props2.hide, - previewComponent: previewPath && /* @__PURE__ */ bn.createElement("div", { + previewComponent: previewPath && /* @__PURE__ */ Cn.createElement("div", { className: "mk-blink-preview" - }, /* @__PURE__ */ bn.createElement(FlowView, { + }, /* @__PURE__ */ Cn.createElement(FlowView, { plugin: props2.plugin, path: previewPath, load: true @@ -48907,10 +51956,10 @@ var BlinkComponent = bn.forwardRef( ); // src/components/Blink/Blink.tsx -var Blink = class extends import_obsidian50.Modal { +var Blink = class extends import_obsidian54.Modal { constructor(app2, plugin) { super(app2); - this.ref = bn.createRef(); + this.ref = Cn.createRef(); this.plugin = plugin; this.modalEl.toggleClass("mk-blink-modal", true); this.modalEl.toggleClass("modal", false); @@ -48930,7 +51979,7 @@ var Blink = class extends import_obsidian50.Modal { } this.root = createRoot(this.modalEl); this.root.render( - /* @__PURE__ */ bn.createElement(BlinkComponent, { + /* @__PURE__ */ Cn.createElement(BlinkComponent, { ref: this.ref, plugin, hide: () => this.close() @@ -48940,9 +51989,9 @@ var Blink = class extends import_obsidian50.Modal { }; // src/components/ContextView/MDBFileViewer.tsx -var import_obsidian51 = require("obsidian"); +var import_obsidian55 = require("obsidian"); var MDB_FILE_VIEWER_TYPE = "make-mdb-viewer"; -var MDBFileViewer = class extends import_obsidian51.FileView { +var MDBFileViewer = class extends import_obsidian55.FileView { constructor(leaf, plugin) { super(leaf); this.navigation = true; @@ -48987,9 +52036,9 @@ var MDBFileViewer = class extends import_obsidian51.FileView { this.destroy(); this.root = createRoot(this.contentEl); this.root.render( - /* @__PURE__ */ bn.createElement("div", { + /* @__PURE__ */ Cn.createElement("div", { className: "mk-folder-view" - }, /* @__PURE__ */ bn.createElement(ContextViewComponent, { + }, /* @__PURE__ */ Cn.createElement(ContextViewComponent, { context, plugin: this.plugin })) @@ -48998,11 +52047,11 @@ var MDBFileViewer = class extends import_obsidian51.FileView { }; // src/components/FileContextView/FileContextView.tsx -var import_obsidian52 = require("obsidian"); +var import_obsidian56 = require("obsidian"); var FILE_CONTEXT_VIEW_TYPE = "make-context-view"; var ICON2 = "component"; var VIEW_DISPLAY_TEXT2 = "Context Explorer"; -var FileContextLeafView = class extends import_obsidian52.ItemView { +var FileContextLeafView = class extends import_obsidian56.ItemView { constructor(leaf, plugin) { super(leaf); this.navigation = false; @@ -49040,74 +52089,1009 @@ var FileContextLeafView = class extends import_obsidian52.ItemView { constructFileContext() { this.destroy(); this.root = createRoot(this.contentEl); - this.root.render(/* @__PURE__ */ bn.createElement(FileContextView, { + this.root.render(/* @__PURE__ */ Cn.createElement(FileContextView, { plugin: this.plugin })); } }; var FileContextView = (props2) => { - const [activeFilePath, setActiveFilePath] = p2(null); - const [selectedFilePath, setSelectedFilePath] = p2(null); - const path = F( - () => selectedFilePath != null ? selectedFilePath : activeFilePath, - [selectedFilePath, activeFilePath] - ); - const file = F(() => { - const afile = getAbstractFileAtPath(app, path); + 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.contextsCache.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; - }, [path]); - const folderNoteFile = F(() => { - if (file instanceof import_obsidian52.TFolder) { - const afile2 = getAbstractFileAtPath(app, path + ".md"); + }, [selectedPath]); + const folderNoteFile = F2(() => { + if (file instanceof import_obsidian56.TFolder) { + const afile2 = getAbstractFileAtPath(app, file.path + ".md"); return afile2; } return file; }, [file]); - const changeActiveFile = (evt) => { - setActiveFilePath(evt.detail.filePath); - setSelectedFilePath(null); - }; const changeSelectedFile = (evt) => { - setSelectedFilePath(evt.detail.filePath); + const path = evt.detail.path; + if (evt.detail.selection) { + setSelectedPath(pathByString(props2.plugin, evt.detail.selection)); + } else { + setSelectedPath(path); + } }; - h2(() => { + p2(() => { props2.plugin.activeFileChange(); }, []); - h2(() => { - window.addEventListener(eventTypes.activeFileChange, changeActiveFile); - window.addEventListener(eventTypes.selectedFileChange, changeSelectedFile); + p2(() => { + window.addEventListener(eventTypes.activePathChange, changeSelectedFile); return () => { - window.removeEventListener(eventTypes.activeFileChange, changeActiveFile); window.removeEventListener( - eventTypes.selectedFileChange, + eventTypes.activePathChange, changeSelectedFile ); }; }, [file]); - return file ? /* @__PURE__ */ bn.createElement("div", { + return /* @__PURE__ */ Cn.createElement("div", { className: "mk-file-context" - }, /* @__PURE__ */ bn.createElement(InlineFileContextView, { + }, file && /* @__PURE__ */ Cn.createElement(InlineFileContextView, { plugin: props2.plugin, file, showHeader: false, editable: true - }), /* @__PURE__ */ bn.createElement(Backlinks, { + }), selectedRow && /* @__PURE__ */ Cn.createElement(InlineFileContextView, { + plugin: props2.plugin, + file: selectedRow, + showHeader: false, + editable: true + }), file && /* @__PURE__ */ Cn.createElement(Backlinks, { plugin: props2.plugin, file: folderNoteFile - })) : /* @__PURE__ */ bn.createElement(bn.Fragment, null); + })); +}; + +// src/components/ui/modals/loadSpaceBackupModal.tsx +var import_obsidian57 = require("obsidian"); +var LoadSpaceBackupModal = class extends import_obsidian57.FuzzySuggestModal { + constructor(plugin, files) { + super(app); + this.plugin = plugin; + this.files = files; + } + getItemText(file) { + return file; + } + getItems() { + return this.files; + } + onChooseItem(file, evt) { + this.plugin.index.loadSpaceDBFromBackup(file); + } +}; + +// src/dispatch/spaces.ts +var dispatchSpaceDatabaseFileChanged = (type, action, name, newName) => { + let evt = new CustomEvent(eventTypes.spacesChange, { + detail: { + 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; + plugin.index.saveSpacesDB({ vault: { ...vaultSchema, rows: [...plugin.index.vaultDBCache, { + path: newPath, + parent, + created: Math.trunc(Date.now() / 1e3).toString(), + folder: folder ? "true" : "false" + }] } }); + plugin.index.createFile(newPath); +}; +var onFileDeleted = (plugin, oldPath) => { + const newVaultRows = plugin.index.vaultDBCache.filter((f4) => f4.path != oldPath); + const newSpaceItemsRows = plugin.index.spacesItemsDBCache.filter((f4) => f4.path != oldPath); + plugin.index.saveSpacesDB({ vault: { ...vaultSchema, rows: newVaultRows }, spaceItems: { ...spaceItemsSchema, rows: newSpaceItemsRows } }); + plugin.index.deleteFile(oldPath); +}; +var onFileChanged = (plugin, oldPath, newPath) => { + const newFolderPath = getFolderPathFromString(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); + plugin.index.saveSpacesDB({ vault: { ...vaultSchema, rows: newVaultRows }, spaceItems: { ...spaceItemsSchema, rows: newSpaceItemsRows } }); + plugin.index.renameFile(oldPath, newPath); +}; +var onFolderChanged = (plugin, oldPath, newPath) => { + const newFolderPath = getFolderFromPath(app, newPath).parent.path; + const allChildren = retrieveAllRecursiveChildren(plugin.index.vaultDBCache, plugin.settings, oldPath); + const newVaultRows = plugin.index.vaultDBCache.map((f4) => f4.path == oldPath ? { + ...f4, + path: newPath, + parent: newFolderPath + } : f4.parent.startsWith(oldPath) || f4.path.startsWith(oldPath) ? { + ...f4, + 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); + plugin.index.saveSpacesDB({ vault: { ...vaultSchema, rows: newVaultRows }, spaceItems: { ...spaceItemsSchema, rows: newSpaceItemsRows } }); + plugin.index.renameFile(oldPath, newPath); + allChildren.forEach((f4) => plugin.index.renameFile(f4.path, f4.path.replace(oldPath, newPath))); +}; +var onFolderDeleted = (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.vaultDBCache.filter((f4) => f4.path != oldPath && !f4.parent.startsWith(oldPath)); + plugin.index.saveSpacesDB({ vault: { ...vaultSchema, rows: newVaultRows }, spaceItems: { ...spaceItemsSchema, rows: newSpaceItemsRows } }); + allChildren.forEach((f4) => plugin.index.deleteFile(f4.path)); + plugin.index.deleteFile(oldPath); }; // src/main.ts var import_obsidian_dataview = __toESM(require_lib()); +// src/superstate/superstate.ts +var import_lodash9 = __toESM(require_lodash()); +var import_obsidian59 = require("obsidian"); + +// src/types/indexMap.ts +var _IndexMap = class { + constructor() { + this.map = /* @__PURE__ */ new Map(); + this.invMap = /* @__PURE__ */ new Map(); + } + get(key2) { + let result = this.map.get(key2); + if (result) { + return new Set(result); + } else { + return /* @__PURE__ */ new Set(); + } + } + getInverse(value) { + return this.invMap.get(value) || _IndexMap.EMPTY_SET; + } + set(key2, values) { + var _a2, _b2; + if (!values.size) { + this.delete(key2); + return this; + } + let oldValues = this.map.get(key2); + if (oldValues) { + for (let 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) { + if (!this.invMap.has(value)) + this.invMap.set(value, /* @__PURE__ */ new Set([key2])); + else + (_b2 = this.invMap.get(value)) == null ? void 0 : _b2.add(key2); + } + return this; + } + setInverse(key2, values) { + var _a2, _b2; + if (!values.size) { + this.deleteInverse(key2); + return this; + } + let oldValues = this.invMap.get(key2); + if (oldValues) { + for (let 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) { + if (!this.map.has(value)) + this.map.set(value, /* @__PURE__ */ new Set([key2])); + else + (_b2 = this.map.get(value)) == null ? void 0 : _b2.add(key2); + } + return this; + } + delete(key2) { + var _a2; + let oldValues = this.map.get(key2); + if (!oldValues) + return false; + this.map.delete(key2); + for (let 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); + if (!oldValues) + return false; + this.invMap.delete(key2); + for (let 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); + if (!oldValues) + return false; + this.delete(oldKey); + this.set(newKey, oldValues); + return true; + } + renameInverse(oldKey, newKey) { + let oldValues = this.invMap.get(oldKey); + if (!oldValues) + return false; + this.deleteInverse(oldKey); + this.setInverse(newKey, oldValues); + return true; + } + clear() { + this.map.clear(); + this.invMap.clear(); + } +}; +var IndexMap = _IndexMap; +IndexMap.EMPTY_SET = Object.freeze(/* @__PURE__ */ new Set()); + +// src/utils/superstate/parser.ts +var parseFileCache = (cache) => { + return safelyParseJSON(cache); +}; + +// src/utils/superstate/serializer.ts +var serializeFileCache = (fileCache) => { + return JSON.stringify(fileCache); +}; +var stringifyJob = (job) => `${job.type}:${job.path}`; + +// src/superstate/localCache/localCache.ts +var import_localforage = __toESM(require_localforage()); +var LocalStorageCache = class { + constructor(appId, version) { + this.appId = appId; + this.version = version; + this.persister = import_localforage.default.createInstance({ + name: "superstate/" + appId, + driver: [import_localforage.default.INDEXEDDB], + description: "Cache metadata about files and sections in the dataview index." + }); + } + async recreate() { + await import_localforage.default.dropInstance({ name: "dataview/cache/" + this.appId }); + this.persister = import_localforage.default.createInstance({ + name: "superstate/" + this.appId, + driver: [import_localforage.default.INDEXEDDB], + description: "Cache metadata about files and sections in the dataview index." + }); + } + async loadFile(path) { + return this.persister.getItem(this.fileKey(path)).then((raw) => { + let result = raw; + return result; + }); + } + async storeFile(path, data) { + await this.persister.setItem(this.fileKey(path), data); + } + async synchronize(existing) { + let keys = new Set(await this.allFiles()); + for (let exist of existing) + keys.delete(exist); + for (let key2 of keys) + await this.persister.removeItem(this.fileKey(key2)); + return keys; + } + async allKeys() { + return this.persister.keys(); + } + async allFiles() { + let keys = await this.allKeys(); + return keys.filter((k5) => k5.startsWith("file:")).map((k5) => k5.substring(5)); + } + fileKey(path) { + return "file:" + path; + } +}; + +// src/superstate/workers/manager.ts +var import_obsidian58 = require("obsidian"); + +// inline-worker:__inline-worker +function inlineWorker(scriptText) { + let blob = new Blob([scriptText], { type: "text/javascript" }); + let url = URL.createObjectURL(blob); + let worker = new Worker(url, { "name": "Superstate Worker" }); + URL.revokeObjectURL(url); + return worker; +} + +// src/superstate/workers/entry.worker.ts +function Worker2() { + return inlineWorker('var z_=Object.create;var Zi=Object.defineProperty,k_=Object.defineProperties,Y_=Object.getOwnPropertyDescriptor,Z_=Object.getOwnPropertyDescriptors,J_=Object.getOwnPropertyNames,Wo=Object.getOwnPropertySymbols,X_=Object.getPrototypeOf,No=Object.prototype.hasOwnProperty,Q_=Object.prototype.propertyIsEnumerable;var Uo=(i,p,y)=>p in i?Zi(i,p,{enumerable:!0,configurable:!0,writable:!0,value:y}):i[p]=y,Pt=(i,p)=>{for(var y in p||(p={}))No.call(p,y)&&Uo(i,y,p[y]);if(Wo)for(var y of Wo(p))Q_.call(p,y)&&Uo(i,y,p[y]);return i},Bt=(i,p)=>k_(i,Z_(p));var V_=(i,p)=>()=>(p||i((p={exports:{}}).exports,p),p.exports);var j_=(i,p,y,A)=>{if(p&&typeof p=="object"||typeof p=="function")for(let m of J_(p))!No.call(i,m)&&m!==y&&Zi(i,m,{get:()=>p[m],enumerable:!(A=Y_(p,m))||A.enumerable});return i};var n0=(i,p,y)=>(y=i!=null?z_(X_(i)):{},j_(p||!i||!i.__esModule?Zi(y,"default",{value:i,enumerable:!0}):y,i));var Go=V_((Vt,Ae)=>{(function(){var i,p="4.17.21",y=200,A="Unsupported core-js use. Try https://npms.io/search?q=ponyfill.",m="Expected a function",E="Invalid `variable` option passed into `_.template`",X="__lodash_hash_undefined__",sn=500,rn="__lodash_placeholder__",K=1,yn=2,an=4,z=1,Zn=2,nn=1,In=2,J=4,ln=8,Nn=16,Q=32,nt=64,Rn=128,ht=256,Gn=512,Te=30,Wt="...",Ct=800,Fe=16,Me=1,Ie=2,Re=3,Jn=1/0,qn=9007199254740991,Le=17976931348623157e292,Tt=0/0,mn=4294967295,cn=mn-1,Xn=mn>>>1,Ln=[["ary",Rn],["bind",nn],["bindKey",In],["curry",ln],["curryRight",Nn],["flip",Gn],["partial",Q],["partialRight",nt],["rearg",ht]],wn="[object Arguments]",Ee="[object Array]",fs="[object AsyncFunction]",ne="[object Boolean]",te="[object Date]",os="[object DOMException]",Oe="[object Error]",be="[object Function]",iu="[object GeneratorFunction]",Kn="[object Map]",ee="[object Number]",ss="[object Null]",tt="[object Object]",uu="[object Promise]",as="[object Proxy]",re="[object RegExp]",Hn="[object Set]",ie="[object String]",De="[object Symbol]",ls="[object Undefined]",ue="[object WeakMap]",cs="[object WeakSet]",fe="[object ArrayBuffer]",Ut="[object DataView]",Mr="[object Float32Array]",Ir="[object Float64Array]",Rr="[object Int8Array]",Lr="[object Int16Array]",Er="[object Int32Array]",Or="[object Uint8Array]",br="[object Uint8ClampedArray]",Dr="[object Uint16Array]",Pr="[object Uint32Array]",ps=/\\b__p \\+= \'\';/g,hs=/\\b(__p \\+=) \'\' \\+/g,gs=/(__e\\(.*?\\)|\\b__t\\)) \\+\\n\'\';/g,fu=/&(?:amp|lt|gt|quot|#39);/g,ou=/[&<>"\']/g,_s=RegExp(fu.source),ds=RegExp(ou.source),vs=/<%-([\\s\\S]+?)%>/g,xs=/<%([\\s\\S]+?)%>/g,su=/<%=([\\s\\S]+?)%>/g,ys=/\\.|\\[(?:[^[\\]]*|(["\'])(?:(?!\\1)[^\\\\]|\\\\.)*?\\1)\\]/,ms=/^\\w*$/,ws=/[^.[\\]]+|\\[(?:(-?\\d+(?:\\.\\d+)?)|(["\'])((?:(?!\\2)[^\\\\]|\\\\.)*?)\\2)\\]|(?=(?:\\.|\\[\\])(?:\\.|\\[\\]|$))/g,Br=/[\\\\^$.*+?()[\\]{}|]/g,As=RegExp(Br.source),Wr=/^\\s+/,Ss=/\\s/,Cs=/\\{(?:\\n\\/\\* \\[wrapped with .+\\] \\*\\/)?\\n?/,Ts=/\\{\\n\\/\\* \\[wrapped with (.+)\\] \\*/,Fs=/,? & /,Ms=/[^\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\x7f]+/g,Is=/[()=,{}\\[\\]\\/\\s]/,Rs=/\\\\(\\\\)?/g,Ls=/\\$\\{([^\\\\}]*(?:\\\\.[^\\\\}]*)*)\\}/g,au=/\\w*$/,Es=/^[-+]0x[0-9a-f]+$/i,Os=/^0b[01]+$/i,bs=/^\\[object .+?Constructor\\]$/,Ds=/^0o[0-7]+$/i,Ps=/^(?:0|[1-9]\\d*)$/,Bs=/[\\xc0-\\xd6\\xd8-\\xf6\\xf8-\\xff\\u0100-\\u017f]/g,Pe=/($^)/,Ws=/[\'\\n\\r\\u2028\\u2029\\\\]/g,Be="\\\\ud800-\\\\udfff",Us="\\\\u0300-\\\\u036f",Ns="\\\\ufe20-\\\\ufe2f",Gs="\\\\u20d0-\\\\u20ff",lu=Us+Ns+Gs,cu="\\\\u2700-\\\\u27bf",pu="a-z\\\\xdf-\\\\xf6\\\\xf8-\\\\xff",qs="\\\\xac\\\\xb1\\\\xd7\\\\xf7",Ks="\\\\x00-\\\\x2f\\\\x3a-\\\\x40\\\\x5b-\\\\x60\\\\x7b-\\\\xbf",Hs="\\\\u2000-\\\\u206f",$s=" \\\\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",gu="\\\\ufe0e\\\\ufe0f",_u=qs+Ks+Hs+$s,Ur="[\'\\u2019]",zs="["+Be+"]",du="["+_u+"]",We="["+lu+"]",vu="\\\\d+",ks="["+cu+"]",xu="["+pu+"]",yu="[^"+Be+_u+vu+cu+pu+hu+"]",Nr="\\\\ud83c[\\\\udffb-\\\\udfff]",Ys="(?:"+We+"|"+Nr+")",mu="[^"+Be+"]",Gr="(?:\\\\ud83c[\\\\udde6-\\\\uddff]){2}",qr="[\\\\ud800-\\\\udbff][\\\\udc00-\\\\udfff]",Nt="["+hu+"]",wu="\\\\u200d",Au="(?:"+xu+"|"+yu+")",Zs="(?:"+Nt+"|"+yu+")",Su="(?:"+Ur+"(?:d|ll|m|re|s|t|ve))?",Cu="(?:"+Ur+"(?:D|LL|M|RE|S|T|VE))?",Tu=Ys+"?",Fu="["+gu+"]?",Js="(?:"+wu+"(?:"+[mu,Gr,qr].join("|")+")"+Fu+Tu+")*",Xs="\\\\d*(?:1st|2nd|3rd|(?![123])\\\\dth)(?=\\\\b|[A-Z_])",Qs="\\\\d*(?:1ST|2ND|3RD|(?![123])\\\\dTH)(?=\\\\b|[a-z_])",Mu=Fu+Tu+Js,Vs="(?:"+[ks,Gr,qr].join("|")+")"+Mu,js="(?:"+[mu+We+"?",We,Gr,qr,zs].join("|")+")",na=RegExp(Ur,"g"),ta=RegExp(We,"g"),Kr=RegExp(Nr+"(?="+Nr+")|"+js+Mu,"g"),ea=RegExp([Nt+"?"+xu+"+"+Su+"(?="+[du,Nt,"$"].join("|")+")",Zs+"+"+Cu+"(?="+[du,Nt+Au,"$"].join("|")+")",Nt+"?"+Au+"+"+Su,Nt+"+"+Cu,Qs,Xs,vu,Vs].join("|"),"g"),ra=RegExp("["+wu+Be+lu+gu+"]"),ia=/[a-z][A-Z]|[A-Z]{2}[a-z]|[0-9][a-zA-Z]|[a-zA-Z][0-9]|[^a-zA-Z0-9 ]/,ua=["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"],fa=-1,q={};q[Mr]=q[Ir]=q[Rr]=q[Lr]=q[Er]=q[Or]=q[br]=q[Dr]=q[Pr]=!0,q[wn]=q[Ee]=q[fe]=q[ne]=q[Ut]=q[te]=q[Oe]=q[be]=q[Kn]=q[ee]=q[tt]=q[re]=q[Hn]=q[ie]=q[ue]=!1;var G={};G[wn]=G[Ee]=G[fe]=G[Ut]=G[ne]=G[te]=G[Mr]=G[Ir]=G[Rr]=G[Lr]=G[Er]=G[Kn]=G[ee]=G[tt]=G[re]=G[Hn]=G[ie]=G[De]=G[Or]=G[br]=G[Dr]=G[Pr]=!0,G[Oe]=G[be]=G[ue]=!1;var oa={\\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"},sa={"&":"&","<":"<",">":">",\'"\':""","\'":"'"},aa={"&":"&","<":"<",">":">",""":\'"\',"'":"\'"},la={"\\\\":"\\\\","\'":"\'","\\n":"n","\\r":"r","\\u2028":"u2028","\\u2029":"u2029"},ca=parseFloat,pa=parseInt,Iu=typeof global=="object"&&global&&global.Object===Object&&global,ha=typeof self=="object"&&self&&self.Object===Object&&self,tn=Iu||ha||Function("return this")(),Hr=typeof Vt=="object"&&Vt&&!Vt.nodeType&&Vt,Ft=Hr&&typeof Ae=="object"&&Ae&&!Ae.nodeType&&Ae,Ru=Ft&&Ft.exports===Hr,$r=Ru&&Iu.process,En=function(){try{var l=Ft&&Ft.require&&Ft.require("util").types;return l||$r&&$r.binding&&$r.binding("util")}catch(g){}}(),Lu=En&&En.isArrayBuffer,Eu=En&&En.isDate,Ou=En&&En.isMap,bu=En&&En.isRegExp,Du=En&&En.isSet,Pu=En&&En.isTypedArray;function An(l,g,h){switch(h.length){case 0:return l.call(g);case 1:return l.call(g,h[0]);case 2:return l.call(g,h[0],h[1]);case 3:return l.call(g,h[0],h[1],h[2])}return l.apply(g,h)}function ga(l,g,h,w){for(var M=-1,B=l==null?0:l.length;++M-1}function zr(l,g,h){for(var w=-1,M=l==null?0:l.length;++w-1;);return h}function Hu(l,g){for(var h=l.length;h--&&Gt(g,l[h],0)>-1;);return h}function Sa(l,g){for(var h=l.length,w=0;h--;)l[h]===g&&++w;return w}var Ca=Jr(oa),Ta=Jr(sa);function Fa(l){return"\\\\"+la[l]}function Ma(l,g){return l==null?i:l[g]}function qt(l){return ra.test(l)}function Ia(l){return ia.test(l)}function Ra(l){for(var g,h=[];!(g=l.next()).done;)h.push(g.value);return h}function jr(l){var g=-1,h=Array(l.size);return l.forEach(function(w,M){h[++g]=[M,w]}),h}function $u(l,g){return function(h){return l(g(h))}}function dt(l,g){for(var h=-1,w=l.length,M=0,B=[];++h-1}function dl(n,t){var e=this.__data__,r=tr(e,n);return r<0?(++this.size,e.push([n,t])):e[r][1]=t,this}et.prototype.clear=pl,et.prototype.delete=hl,et.prototype.get=gl,et.prototype.has=_l,et.prototype.set=dl;function rt(n){var t=-1,e=n==null?0:n.length;for(this.clear();++t=t?n:t)),n}function Pn(n,t,e,r,u,o){var s,a=t&K,c=t&yn,_=t&an;if(e&&(s=u?e(n,r,u,o):e(n)),s!==i)return s;if(!$(n))return n;var d=I(n);if(d){if(s=mc(n),!a)return _n(n,s)}else{var v=on(n),x=v==be||v==iu;if(St(n))return Mf(n,a);if(v==tt||v==wn||x&&!u){if(s=c||x?{}:kf(n),!a)return c?ac(n,Ol(s,n)):sc(n,ef(s,n))}else{if(!G[v])return u?n:{};s=wc(n,v,a)}}o||(o=new zn);var S=o.get(n);if(S)return S;o.set(n,s),Ao(n)?n.forEach(function(F){s.add(Pn(F,t,e,F,n,o))}):mo(n)&&n.forEach(function(F,b){s.set(b,Pn(F,t,e,b,n,o))});var T=_?c?Ti:Ci:c?vn:en,L=d?i:T(n);return On(L||n,function(F,b){L&&(b=F,F=n[b]),he(s,b,Pn(F,t,e,b,n,o))}),s}function bl(n){var t=en(n);return function(e){return rf(e,n,t)}}function rf(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 uf(n,t,e){if(typeof n!="function")throw new bn(m);return me(function(){n.apply(i,e)},t)}function ge(n,t,e,r){var u=-1,o=Ue,s=!0,a=n.length,c=[],_=t.length;if(!a)return c;e&&(t=H(t,Sn(e))),r?(o=zr,s=!1):t.length>=y&&(o=oe,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:Co(r);e0&&e(a)?t>1?un(a,t-1,e,r,u):_t(u,a):r||(u[u.length]=a)}return u}var fi=bf(),sf=bf(!0);function Qn(n,t){return n&&fi(n,t,en)}function oi(n,t){return n&&sf(n,t,en)}function rr(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 Bl(n,t){return n!=null&&U.call(n,t)}function Wl(n,t){return n!=null&&t in N(n)}function Ul(n,t,e){return n>=fn(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&&Ze.call(a,c,1),Ze.call(n,c,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;ot(u)?Ze.call(n,u,1):vi(n,u)}}return n}function gi(n,t){return n+Qe(Vu()*(t-n+1))}function Ql(n,t,e,r){for(var u=-1,o=j(Xe((t-n)/(e||1)),0),s=h(o);o--;)s[r?o:++u]=n,n+=e;return s}function _i(n,t){var e="";if(!n||t<1||t>qn)return e;do t%2&&(e+=n),t=Qe(t/2),t&&(n+=n);while(t);return e}function O(n,t){return Oi(Jf(n,t,xn),n+"")}function Vl(n){return tf(Qt(n))}function jl(n,t){var e=Qt(n);return gr(e,Lt(t,0,e.length))}function ve(n,t,e,r){if(!$(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=h(u);++r>>1,s=n[o];s!==null&&!Tn(s)&&(e?s<=t:s=y){var _=t?null:hc(n);if(_)return Ge(_);s=!1,u=oe,c=new Rt}else c=t?[]:a;n:for(;++r=r?n:Bn(n,t,e)}var Ff=$a||function(n){return tn.clearTimeout(n)};function Mf(n,t){if(t)return n.slice();var e=n.length,r=Yu?Yu(e):new n.constructor(e);return n.copy(r),r}function wi(n){var t=new n.constructor(n.byteLength);return new ke(t).set(new ke(n)),t}function ic(n,t){var e=t?wi(n.buffer):n.buffer;return new n.constructor(e,n.byteOffset,n.byteLength)}function uc(n){var t=new n.constructor(n.source,au.exec(n));return t.lastIndex=n.lastIndex,t}function fc(n){return pe?N(pe.call(n)):{}}function If(n,t){var e=t?wi(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=Tn(n),s=t!==i,a=t===null,c=t===t,_=Tn(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 Lf(n,t,e,r){for(var u=-1,o=n.length,s=e.length,a=-1,c=t.length,_=j(o-s,0),d=h(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&&hn(e[0],e[1],s)&&(o=u<3?i:o,u=1),t=N(t);++r-1?u[o?t[s]:s]:i}}function Bf(n){return ft(function(t){var e=t.length,r=e,u=Dn.prototype.thru;for(n&&t.reverse();r--;){var o=t[r];if(typeof o!="function")throw new bn(m);if(u&&!s&&pr(o)=="wrapper")var s=new Dn([],!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&Zn?new Rt:i;for(o.set(n,t),o.set(t,n);++v1?"& ":"")+t[r],t=t.join(e>2?", ":" "),n.replace(Cs,`{\n/* [wrapped with `+t+`] */\n`)}function Sc(n){return I(n)||Dt(n)||!!(Xu&&n&&n[Xu])}function ot(n,t){var e=typeof n;return t=t==null?qn:t,!!t&&(e=="number"||e!="symbol"&&Ps.test(n))&&n>-1&&n%1==0&&n0){if(++t>=Ct)return arguments[0]}else t=0;return n.apply(i,arguments)}}function gr(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,oo(n,e)});function so(n){var t=f(n);return t.__chain__=!0,t}function Dp(n,t){return t(n),n}function _r(n,t){return t(n)}var Pp=ft(function(n){var t=n.length,e=t?n[0]:0,r=this.__wrapped__,u=function(o){return ui(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:_r,args:[u],thisArg:i}),new Dn(r,this.__chain__).thru(function(o){return t&&!o.length&&o.push(i),o}))});function Bp(){return so(this)}function Wp(){return new Dn(this.value(),this.__chain__)}function Up(){this.__values__===i&&(this.__values__=So(this.value()));var n=this.__index__>=this.__values__.length,t=n?i:this.__values__[this.__index__++];return{done:n,value:t}}function Np(){return this}function Gp(n){for(var t,e=this;e instanceof nr;){var r=to(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 qp(){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:_r,args:[bi],thisArg:i}),new Dn(t,this.__chain__)}return this.thru(bi)}function Kp(){return Cf(this.__wrapped__,this.__actions__)}var Hp=or(function(n,t,e){U.call(n,e)?++n[e]:it(n,e,1)});function $p(n,t,e){var r=I(n)?Bu:Dl;return e&&hn(n,t,e)&&(t=i),r(n,C(t,3))}function zp(n,t){var e=I(n)?gt:of;return e(n,C(t,3))}var kp=Pf(eo),Yp=Pf(ro);function Zp(n,t){return un(dr(n,t),1)}function Jp(n,t){return un(dr(n,t),Jn)}function Xp(n,t,e){return e=e===i?1:R(e),un(dr(n,t),e)}function ao(n,t){var e=I(n)?On:yt;return e(n,C(t,3))}function lo(n,t){var e=I(n)?_a:ff;return e(n,C(t,3))}var Qp=or(function(n,t,e){U.call(n,e)?n[e].push(t):it(n,e,[t])});function Vp(n,t,e,r){n=dn(n)?n:Qt(n),e=e&&!r?R(e):0;var u=n.length;return e<0&&(e=j(u+e,0)),wr(n)?e<=u&&n.indexOf(t,e)>-1:!!u&&Gt(n,t,e)>-1}var jp=O(function(n,t,e){var r=-1,u=typeof t=="function",o=dn(n)?h(n.length):[];return yt(n,function(s){o[++r]=u?An(t,s,e):_e(s,t,e)}),o}),nh=or(function(n,t,e){it(n,e,t)});function dr(n,t){var e=I(n)?H:hf;return e(n,C(t,3))}function th(n,t,e,r){return n==null?[]:(I(t)||(t=t==null?[]:[t]),e=r?i:e,I(e)||(e=e==null?[]:[e]),vf(n,t,e))}var eh=or(function(n,t,e){n[e?0:1].push(t)},function(){return[[],[]]});function rh(n,t,e){var r=I(n)?kr:Gu,u=arguments.length<3;return r(n,C(t,4),e,u,yt)}function ih(n,t,e){var r=I(n)?da:Gu,u=arguments.length<3;return r(n,C(t,4),e,u,ff)}function uh(n,t){var e=I(n)?gt:of;return e(n,yr(C(t,3)))}function fh(n){var t=I(n)?tf:Vl;return t(n)}function oh(n,t,e){(e?hn(n,t,e):t===i)?t=1:t=R(t);var r=I(n)?Rl:jl;return r(n,t)}function sh(n){var t=I(n)?Ll:tc;return t(n)}function ah(n){if(n==null)return 0;if(dn(n))return wr(n)?Kt(n):n.length;var t=on(n);return t==Kn||t==Hn?n.size:ci(n).length}function lh(n,t,e){var r=I(n)?Yr:ec;return e&&hn(n,t,e)&&(t=i),r(n,C(t,3))}var ch=O(function(n,t){if(n==null)return[];var e=t.length;return e>1&&hn(n,t[0],t[1])?t=[]:e>2&&hn(t[0],t[1],t[2])&&(t=[t[0]]),vf(n,un(t,1),[])}),vr=za||function(){return tn.Date.now()};function ph(n,t){if(typeof t!="function")throw new bn(m);return n=R(n),function(){if(--n<1)return t.apply(this,arguments)}}function co(n,t,e){return t=e?i:t,t=n&&t==null?n.length:t,ut(n,Rn,i,i,i,i,t)}function po(n,t){var e;if(typeof t!="function")throw new bn(m);return n=R(n),function(){return--n>0&&(e=t.apply(this,arguments)),n<=1&&(t=i),e}}var Pi=O(function(n,t,e){var r=nn;if(e.length){var u=dt(e,Jt(Pi));r|=Q}return ut(n,r,t,e,u)}),ho=O(function(n,t,e){var r=nn|In;if(e.length){var u=dt(e,Jt(ho));r|=Q}return ut(t,r,n,e,u)});function go(n,t,e){t=e?i:t;var r=ut(n,ln,i,i,i,i,i,t);return r.placeholder=go.placeholder,r}function _o(n,t,e){t=e?i:t;var r=ut(n,Nn,i,i,i,i,i,t);return r.placeholder=_o.placeholder,r}function vo(n,t,e){var r,u,o,s,a,c,_=0,d=!1,v=!1,x=!0;if(typeof n!="function")throw new bn(m);t=Un(t)||0,$(e)&&(d=!!e.leading,v="maxWait"in e,o=v?j(Un(e.maxWait)||0,t):o,x="trailing"in e?!!e.trailing:x);function S(Z){var Yn=r,lt=u;return r=u=i,_=Z,s=n.apply(lt,Yn),s}function T(Z){return _=Z,a=me(b,t),d?S(Z):s}function L(Z){var Yn=Z-c,lt=Z-_,Bo=t-Yn;return v?fn(Bo,o-lt):Bo}function F(Z){var Yn=Z-c,lt=Z-_;return c===i||Yn>=t||Yn<0||v&<>=o}function b(){var Z=vr();if(F(Z))return P(Z);a=me(b,L(Z))}function P(Z){return a=i,x&&r?S(Z):(r=u=i,s)}function Fn(){a!==i&&Ff(a),_=0,r=c=u=a=i}function gn(){return a===i?s:P(vr())}function Mn(){var Z=vr(),Yn=F(Z);if(r=arguments,u=this,c=Z,Yn){if(a===i)return T(c);if(v)return Ff(a),a=me(b,t),S(c)}return a===i&&(a=me(b,t)),s}return Mn.cancel=Fn,Mn.flush=gn,Mn}var hh=O(function(n,t){return uf(n,1,t)}),gh=O(function(n,t,e){return uf(n,Un(t)||0,e)});function _h(n){return ut(n,Gn)}function xr(n,t){if(typeof n!="function"||t!=null&&typeof t!="function")throw new bn(m);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(xr.Cache||rt),e}xr.Cache=rt;function yr(n){if(typeof n!="function")throw new bn(m);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 dh(n){return po(2,n)}var vh=rc(function(n,t){t=t.length==1&&I(t[0])?H(t[0],Sn(C())):H(un(t,1),Sn(C()));var e=t.length;return O(function(r){for(var u=-1,o=fn(r.length,e);++u=t}),Dt=lf(function(){return arguments}())?lf:function(n){return k(n)&&U.call(n,"callee")&&!Ju.call(n,"callee")},I=h.isArray,Oh=Lu?Sn(Lu):Gl;function dn(n){return n!=null&&mr(n.length)&&!st(n)}function Y(n){return k(n)&&dn(n)}function bh(n){return n===!0||n===!1||k(n)&&pn(n)==ne}var St=Ya||Yi,Dh=Eu?Sn(Eu):ql;function Ph(n){return k(n)&&n.nodeType===1&&!we(n)}function Bh(n){if(n==null)return!0;if(dn(n)&&(I(n)||typeof n=="string"||typeof n.splice=="function"||St(n)||Xt(n)||Dt(n)))return!n.length;var t=on(n);if(t==Kn||t==Hn)return!n.size;if(ye(n))return!ci(n).length;for(var e in n)if(U.call(n,e))return!1;return!0}function Wh(n,t){return de(n,t)}function Uh(n,t,e){e=typeof e=="function"?e:i;var r=e?e(n,t):i;return r===i?de(n,t,i,e):!!r}function Wi(n){if(!k(n))return!1;var t=pn(n);return t==Oe||t==os||typeof n.message=="string"&&typeof n.name=="string"&&!we(n)}function Nh(n){return typeof n=="number"&&Qu(n)}function st(n){if(!$(n))return!1;var t=pn(n);return t==be||t==iu||t==fs||t==as}function yo(n){return typeof n=="number"&&n==R(n)}function mr(n){return typeof n=="number"&&n>-1&&n%1==0&&n<=qn}function $(n){var t=typeof n;return n!=null&&(t=="object"||t=="function")}function k(n){return n!=null&&typeof n=="object"}var mo=Ou?Sn(Ou):Hl;function Gh(n,t){return n===t||li(n,t,Mi(t))}function qh(n,t,e){return e=typeof e=="function"?e:i,li(n,t,Mi(t),e)}function Kh(n){return wo(n)&&n!=+n}function Hh(n){if(Fc(n))throw new M(A);return cf(n)}function $h(n){return n===null}function zh(n){return n==null}function wo(n){return typeof n=="number"||k(n)&&pn(n)==ee}function we(n){if(!k(n)||pn(n)!=tt)return!1;var t=Ye(n);if(t===null)return!0;var e=U.call(t,"constructor")&&t.constructor;return typeof e=="function"&&e instanceof e&&He.call(e)==qa}var Ui=bu?Sn(bu):$l;function kh(n){return yo(n)&&n>=-qn&&n<=qn}var Ao=Du?Sn(Du):zl;function wr(n){return typeof n=="string"||!I(n)&&k(n)&&pn(n)==ie}function Tn(n){return typeof n=="symbol"||k(n)&&pn(n)==De}var Xt=Pu?Sn(Pu):kl;function Yh(n){return n===i}function Zh(n){return k(n)&&on(n)==ue}function Jh(n){return k(n)&&pn(n)==cs}var Xh=cr(pi),Qh=cr(function(n,t){return n<=t});function So(n){if(!n)return[];if(dn(n))return wr(n)?$n(n):_n(n);if(se&&n[se])return Ra(n[se]());var t=on(n),e=t==Kn?jr:t==Hn?Ge:Qt;return e(n)}function at(n){if(!n)return n===0?n:0;if(n=Un(n),n===Jn||n===-Jn){var t=n<0?-1:1;return t*Le}return n===n?n:0}function R(n){var t=at(n),e=t%1;return t===t?e?t-e:t:0}function Co(n){return n?Lt(R(n),0,mn):0}function Un(n){if(typeof n=="number")return n;if(Tn(n))return Tt;if($(n)){var t=typeof n.valueOf=="function"?n.valueOf():n;n=$(t)?t+"":t}if(typeof n!="string")return n===0?n:+n;n=qu(n);var e=Os.test(n);return e||Ds.test(n)?pa(n.slice(2),e?2:8):Es.test(n)?Tt:+n}function To(n){return Vn(n,vn(n))}function Vh(n){return n?Lt(R(n),-qn,qn):n===0?n:0}function W(n){return n==null?"":Cn(n)}var jh=Yt(function(n,t){if(ye(t)||dn(t)){Vn(t,en(t),n);return}for(var e in t)U.call(t,e)&&he(n,e,t[e])}),Fo=Yt(function(n,t){Vn(t,vn(t),n)}),Ar=Yt(function(n,t,e,r){Vn(t,vn(t),n,r)}),ng=Yt(function(n,t,e,r){Vn(t,en(t),n,r)}),tg=ft(ui);function eg(n,t){var e=kt(n);return t==null?e:ef(e,t)}var rg=O(function(n,t){n=N(n);var e=-1,r=t.length,u=r>2?t[2]:i;for(u&&hn(t[0],t[1],u)&&(r=1);++e1),o}),Vn(n,Ti(n),e),r&&(e=Pn(e,K|yn|an,gc));for(var u=t.length;u--;)vi(e,t[u]);return e});function wg(n,t){return Io(n,yr(C(t)))}var Ag=ft(function(n,t){return n==null?{}:Jl(n,t)});function Io(n,t){if(n==null)return{};var e=H(Ti(n),function(r){return[r]});return t=C(t),xf(n,e,function(r,u){return t(r,u[0])})}function Sg(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=Vu();return fn(n+u*(t-n+ca("1e-"+((u+"").length-1))),t)}return gi(n,t)}var Dg=Zt(function(n,t,e){return t=t.toLowerCase(),n+(e?Eo(t):t)});function Eo(n){return qi(W(n).toLowerCase())}function Oo(n){return n=W(n),n&&n.replace(Bs,Ca).replace(ta,"")}function Pg(n,t,e){n=W(n),t=Cn(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 Bg(n){return n=W(n),n&&ds.test(n)?n.replace(ou,Ta):n}function Wg(n){return n=W(n),n&&As.test(n)?n.replace(Br,"\\\\$&"):n}var Ug=Zt(function(n,t,e){return n+(e?"-":"")+t.toLowerCase()}),Ng=Zt(function(n,t,e){return n+(e?" ":"")+t.toLowerCase()}),Gg=Df("toLowerCase");function qg(n,t,e){n=W(n),t=R(t);var r=t?Kt(n):0;if(!t||r>=t)return n;var u=(t-r)/2;return lr(Qe(u),e)+n+lr(Xe(u),e)}function Kg(n,t,e){n=W(n),t=R(t);var r=t?Kt(n):0;return t&&r>>0,e?(n=W(n),n&&(typeof t=="string"||t!=null&&!Ui(t))&&(t=Cn(t),!t&&qt(n))?At($n(n),0,e):n.split(t,e)):[]}var Jg=Zt(function(n,t,e){return n+(e?" ":"")+qi(t)});function Xg(n,t,e){return n=W(n),e=e==null?0:Lt(R(e),0,n.length),t=Cn(t),n.slice(e,e+t.length)==t}function Qg(n,t,e){var r=f.templateSettings;e&&hn(n,t,e)&&(t=i),n=W(n),t=Ar({},t,r,qf);var u=Ar({},t.imports,r.imports,qf),o=en(u),s=Vr(u,o),a,c,_=0,d=t.interpolate||Pe,v="__p += \'",x=ni((t.escape||Pe).source+"|"+d.source+"|"+(d===su?Ls:Pe).source+"|"+(t.evaluate||Pe).source+"|$","g"),S="//# sourceURL="+(U.call(t,"sourceURL")?(t.sourceURL+"").replace(/\\s/g," "):"lodash.templateSources["+ ++fa+"]")+`\n`;n.replace(x,function(F,b,P,Fn,gn,Mn){return P||(P=Fn),v+=n.slice(_,Mn).replace(Ws,Fa),b&&(a=!0,v+=`\' +\n__e(`+b+`) +\n\'`),gn&&(c=!0,v+=`\';\n`+gn+`;\n__p += \'`),P&&(v+=`\' +\n((__t = (`+P+`)) == null ? \'\' : __t) +\n\'`),_=Mn+F.length,F}),v+=`\';\n`;var T=U.call(t,"variable")&&t.variable;if(!T)v=`with (obj) {\n`+v+`\n}\n`;else if(Is.test(T))throw new M(E);v=(c?v.replace(ps,""):v).replace(hs,"$1").replace(gs,"$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=Do(function(){return B(o,S+"return "+v).apply(i,s)});if(L.source=v,Wi(L))throw L;return L}function Vg(n){return W(n).toLowerCase()}function jg(n){return W(n).toUpperCase()}function n_(n,t,e){if(n=W(n),n&&(e||t===i))return qu(n);if(!n||!(t=Cn(t)))return n;var r=$n(n),u=$n(t),o=Ku(r,u),s=Hu(r,u)+1;return At(r,o,s).join("")}function t_(n,t,e){if(n=W(n),n&&(e||t===i))return n.slice(0,zu(n)+1);if(!n||!(t=Cn(t)))return n;var r=$n(n),u=Hu(r,$n(t))+1;return At(r,0,u).join("")}function e_(n,t,e){if(n=W(n),n&&(e||t===i))return n.replace(Wr,"");if(!n||!(t=Cn(t)))return n;var r=$n(n),u=Ku(r,$n(t));return At(r,u).join("")}function r_(n,t){var e=Te,r=Wt;if($(t)){var u="separator"in t?t.separator:u;e="length"in t?R(t.length):e,r="omission"in t?Cn(t.omission):r}n=W(n);var o=n.length;if(qt(n)){var s=$n(n);o=s.length}if(e>=o)return n;var a=e-Kt(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),Ui(u)){if(n.slice(a).search(u)){var _,d=c;for(u.global||(u=ni(u.source,W(au.exec(u))+"g")),u.lastIndex=0;_=u.exec(d);)var v=_.index;c=c.slice(0,v===i?a:v)}}else if(n.indexOf(Cn(u),a)!=a){var x=c.lastIndexOf(u);x>-1&&(c=c.slice(0,x))}return c+r}function i_(n){return n=W(n),n&&_s.test(n)?n.replace(fu,ba):n}var u_=Zt(function(n,t,e){return n+(e?" ":"")+t.toUpperCase()}),qi=Df("toUpperCase");function bo(n,t,e){return n=W(n),t=e?i:t,t===i?Ia(n)?Ba(n):ya(n):n.match(t)||[]}var Do=O(function(n,t){try{return An(n,i,t)}catch(e){return Wi(e)?e:new M(e)}}),f_=ft(function(n,t){return On(t,function(e){e=jn(e),it(n,e,Pi(n[e],n))}),n});function o_(n){var t=n==null?0:n.length,e=C();return n=t?H(n,function(r){if(typeof r[1]!="function")throw new bn(m);return[e(r[0]),r[1]]}):[],O(function(r){for(var u=-1;++uqn)return[];var e=mn,r=fn(n,mn);t=C(t),n-=mn;for(var u=Qr(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(mn)},Qn(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||I(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:_r,args:[v],thisArg:i}),new Dn(F,x)}return T&&L?n.apply(this,a):(F=this.thru(v),T?r?F.value()[0]:F.value():F)})}),On(["pop","push","shift","sort","splice","unshift"],function(n){var t=qe[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(I(o)?o:[],u)}return this[e](function(s){return t.apply(I(s)?s:[],u)})}}),Qn(D.prototype,function(n,t){var e=f[t];if(e){var r=e.name+"";U.call(zt,r)||(zt[r]=[]),zt[r].push({name:t,func:e})}}),zt[sr(i,In).name]=[{name:"wrapper",func:i}],D.prototype.clone=il,D.prototype.reverse=ul,D.prototype.value=fl,f.prototype.at=Pp,f.prototype.chain=Bp,f.prototype.commit=Wp,f.prototype.next=Up,f.prototype.plant=Gp,f.prototype.reverse=qp,f.prototype.toJSON=f.prototype.valueOf=f.prototype.value=Kp,f.prototype.first=f.prototype.head,se&&(f.prototype[se]=Np),f},vt=Wa();typeof define=="function"&&typeof define.amd=="object"&&define.amd?(tn._=vt,define(function(){return vt})):Ft?((Ft.exports=vt)._=vt,Hr._=vt):tn._=vt}).call(Vt)});var ru=n0(Go());var qo="banner",Ji="alias",Xi="sticker",Qi="color";var ct=i=>[...new Set(i)],Ko=i=>[...new Map(i.map(p=>[p.toLowerCase(),p])).values()];var Ho=i=>{var p;try{p=JSON.parse(i)}catch(y){}return p};var zo=(i,p)=>p.indexOf(i)>0?p.indexOf(i):p.length,t0=i=>i.substring(0,i.length-2),Vi=i=>i.replace(/\\//g,"+")+"//";var ko=i=>i.substring(0,i.lastIndexOf("."))||i,e0=i=>i.charAt(0)=="/"?i.substring(1):i;var $o=i=>e0(i.substring(i.lastIndexOf("/")))||i,ji=i=>i?(i==null?void 0:i.type)=="folder"?$o(i.contextPath):(i==null?void 0:i.type)=="space"?t0(i.contextPath):i.isRemote?$o(i.contextPath):i.contextPath:"";var pt=i=>{var p;return(p=i==null?void 0:i.match(/(\\\\.|[^,])+/g))!=null?p:[]},Yo=i=>{if(!i)return"";let p=/\\[\\[(.*?)\\]\\]/g.exec(i),y=(p==null?void 0:p.length)>1?p[1].substring(0,zo("|",p[1])):i;return y||i};var Zo=i=>{var p;return!i||i.length==0?[]:i.charAt(0)=="#"?i.split("&").map(y=>({type:"tag",value:y})):(p=Ho(i))!=null?p:[]};var Se=(i,p)=>{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(p=="tag"||p=="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 y=Array.isArray(i)?i:[];if(typeof i=="string"&&i.indexOf(",")>-1&&(y=pt(i)),p=="tag"||p=="tags")return"tag-multi";if(y.length==1&&Array.isArray(y[0])&&y[0].length==1&&typeof y[0][0]=="string")return"link";let A=ct(y.map(m=>Se(m,p)));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 Jo=i=>Object.keys(i!=null?i:{}).filter(p=>p!="position").filter(p=>p!="tag"&&p!="tags");var jt=i=>i.join(","),Xo=i=>i.join(", ");var Sr=(i,p)=>{switch(Se(p,i)){case"object":return JSON.stringify(p);case"number":return p.toString();case"boolean":return p?"true":"false";case"date":return p;case"duration":return Xo(Object.keys(p.values).reduce((A,m)=>[...A,...p.values[m]>0?[p.values[m]+" "+m]:[]],[]));case"option-multi":case"link-multi":return typeof p=="string"?p:jt(p.map(A=>A?typeof A=="string"?A:A.path?A.path:Array.isArray(p)&&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(p)&&p.length==1&&Array.isArray(p[0])&&p[0].length==1&&typeof p[0][0]=="string"?p[0][0]:typeof p=="string"?p:p.path;case"text":case"tag":case"image":return p}return""};var Qo=i=>{switch(i){case"duration":return"text";case"unknown":return"text"}return i};var Cr=(i,p)=>i==p,nu=(i,p)=>(i!=null?i:"").length==0,tu=(i,p)=>(i!=null?i:"").toLowerCase().includes((p!=null?p:"").toLowerCase()),Tr=(i,p)=>parseFloat(i)>parseFloat(p),Fr=(i,p)=>parseInt(i)>parseInt(p),eu=(i,p)=>{let y=i?pt(i):[];return(p?pt(p):[]).some(m=>y.some(E=>E==m))};var Ce={isNotEmpty:{type:["text","file","link","link-multi","fileprop","image"],fn:(i,p)=>!nu(i,""),valueType:"none"},isEmpty:{type:["text","file","link","link-multi","fileprop","image"],fn:(i,p)=>nu(i,""),valueType:"none"},include:{fn:(i,p)=>tu(i,p),type:["text","file","link","link-multi","fileprop","image"],valueType:"text"},notInclude:{type:["text","file","link","link-multi","fileprop","image"],fn:(i,p)=>!tu(i,p),valueType:"text"},is:{type:["text","file","link","context","fileprop"],fn:Cr,valueType:"text"},isNot:{type:["text","file","link","context","fileprop"],fn:(i,p)=>!Cr(i,p),valueType:"text"},equal:{type:["number"],fn:Cr,valueType:"number"},isGreatThan:{type:["number"],fn:Tr,valueType:"number"},isLessThan:{type:["number"],fn:Fr,valueType:"number"},isLessThanOrEqual:{type:["number"],fn:(i,p)=>!Tr(i,p),valueType:"number"},isGreatThanOrEqual:{type:["number"],fn:(i,p)=>!Fr(i,p),valueType:"number"},dateBefore:{type:["date","fileprop"],fn:Fr,valueType:"date"},dateAfter:{type:["date","fileprop"],fn:Tr,valueType:"date"},isAnyInList:{type:["option","context","option-multi","context-multi","tags-multi","tags"],fn:eu,valueType:"list"},isNoneInList:{type:["option","context","option-multi","context-multi","tags-multi","tags"],fn:(i,p)=>!eu(i,p),valueType:"list"},isTrue:{type:["boolean"],fn:(i,p)=>i=="true",valueType:"none"},isFalse:{type:["boolean"],fn:(i,p)=>i!="true",valueType:"none"}};var r0=(i,p)=>p.reduce((A,m)=>{let[E,X]=A,sn=m.type=="fileprop"?ns(X,m):m.type=="filemeta"?jo(X,m):m.type=="frontmatter"?Vo(X,m):[],rn=X.filter(K=>!sn.includes(K));return[[...E,...sn],rn]},[[],i])[0],i0=(i,p)=>p.reduce((y,A)=>A.type=="fileprop"?ns(y,A):A.type=="filemeta"?jo(y,A):A.type=="frontmatter"?Vo(y,A):[],i),Vo=(i,p)=>i.filter(y=>{let A=y.frontmatter;if(!A||!A[p.field])return!1;let m=Ce[p.fn],E=!0;return m&&(E=m.fn(Sr(p.field,A[p.field]),p.value)),E}),jo=(i,p)=>i.filter(y=>{let A="";p.field=="outlinks"?A=jt(y.outlinks):p.field=="inlinks"?A=jt(y.inlinks):p.field=="tags"&&(A=jt(y.tags));let m=Ce[p.fn],E=!0;return m&&(E=m.fn(A,p.value)),E}),ns=(i,p)=>i.filter(y=>{if(["path","sticker","color","isFolder","extension","ctime","mtime","size","parent"].includes(p.field)){let m=Ce[p.fn],E=!0;return m&&(E=m.fn(y[p.field],p.value)),E}return!0}),ts=(i,p)=>i.filters.reduce((m,E)=>m&&(E.type=="any"?r0([p],E.filters).length>0:i0([p],E.filters).length>0),!0);var es=(i,p,y)=>{var yn,an,z,Zn,nn,In;if(!p)return{changed:!1,cache:{path:i.dbPath,info:i,name:ji(i),sticker:"",banner:"",cols:[],files:[],rows:[],def:[],defContexts:[],outlinks:[],contexts:[]}};let A=(an=(yn=p.cols)==null?void 0:yn.filter(J=>J.type.startsWith("context")))!=null?an:[],m=(Zn=(z=p.cols)==null?void 0:z.filter(J=>J.type.startsWith("link")))!=null?Zn:[],E=ct(A.map(J=>J.value)),X=ct(p.rows.reduce((J,ln)=>ct([...J,...[...A,...m].flatMap(Nn=>pt(ln[Nn.name]).map(Q=>Yo(Q)))]),[])),sn=Zo(p.schema.def),rn={path:i.dbPath,info:i,name:ji(i),sticker:"",banner:"",cols:p.cols,files:(nn=p.rows.map(J=>J.File))!=null?nn:[],rows:(In=p.rows)!=null?In:[],defContexts:sn.filter(J=>J.type=="tag").map(J=>J.value),def:sn,contexts:E,outlinks:X},K=!0;return y&&ru.default.isEqual(rn,y)&&(K=!0),{changed:K,cache:rn}},u0=i=>{var y,A,m,E,X,sn,rn,K,yn,an;let p=[];return i&&i.tags&&p.push(...(A=(y=i.tags)==null?void 0:y.map(z=>z.tag))!=null?A:[]),i&&((m=i.frontmatter)==null?void 0:m.tags)&&p.push(...(typeof((E=i.frontmatter)==null?void 0:E.tags)=="string"?pt(i.frontmatter.tags.replace(/ /g,"")):Array.isArray((X=i.frontmatter)==null?void 0:X.tags)?(sn=i.frontmatter)==null?void 0:sn.tags:[]).filter(z=>typeof z=="string").map(z=>"#"+z)),i&&((rn=i.frontmatter)==null?void 0:rn.tag)&&p.push(...(typeof((K=i.frontmatter)==null?void 0:K.tag)=="string"?pt(i.frontmatter.tag.replace(/ /g,"")):Array.isArray((yn=i.frontmatter)==null?void 0:yn.tag)?(an=i.frontmatter)==null?void 0:an.tag:[]).filter(z=>typeof z=="string").map(z=>"#"+z)),ct(p)};var f0=(i,p,y,A)=>{let m=[];return m.push(...p.filter(E=>y.has(E))),i.parent!="/"&&m.push(i.parent),A.forEach(E=>{y.has(Vi(E))&&m.push(Vi(E))}),m},rs=(i,p,y,A,m,E,X,sn,rn)=>{var Jn,qn,Le,Tt,mn;let K={path:i.path,name:i.name};i.stat&&(K.ctime=i.stat.ctime,K.mtime=i.stat.mtime,K.size=i.stat.size,K.extension=i.extension);let yn=[],an=u0(E);if(y.has(i.parent))for(let cn of y.get(i.parent).def)cn.type=="tag"&&yn.push(cn.value);yn.push(...an);let z=i.isFolder?i.name:ko(i.name),Zn=(Jn=m==null?void 0:m.sticker)!=null?Jn:"",nn=(qn=m==null?void 0:m.color)!=null?qn:"",In=(Le=m==null?void 0:m.rank)!=null?Le:"",J=(Tt=m==null?void 0:m.folder)!=null?Tt:"";J=="true"&&(J="");let ln=i.parent,Nn=i.isFolder,Q={},nt={},Rn=[],ht=[],Gn=E==null?void 0:E.frontmatter;E!=null&&E.links&&ht.push(...E.links.map(cn=>cn.link));for(let cn of Object.keys(X))i.path in X[cn]&&Rn.push(cn);let Te;if(Gn){let Xn=Ko(Jo(Gn)).reduce((Ln,wn)=>Bt(Pt({},Ln),{[wn]:{name:wn,type:Qo(Se(Gn[wn],wn))}}),{});Object.keys(Xn).forEach(Ln=>{Q[Ln]=Sr(Ln,Gn[Ln]),nt[Ln]=Xn[Ln].type}),Te=Q[qo],Q[Xi]&&(Zn=Gn[Xi]),Q[Qi]&&(nn=Gn[Qi]),Q[Ji]&&(z=Gn[Ji])}let Wt=Bt(Pt({},K),{name:z,tags:ct(yn),fileTags:an,folderNote:sn,sticker:Zn,color:nn,rank:In,parent:ln,banner:Te,isFolder:Nn,folderSort:J,frontmatter:Q,frontmatterTypes:nt,inlinks:Rn,outlinks:ht}),Ct=[],Fe={};for(let[cn,Xn]of A)if(Xn.space.def.type=="smart")ts(Xn.space.def,Wt)&&Ct.push(cn);else if(((mn=Xn.space.def.folder)==null?void 0:mn.length)>0)Xn.space.def.folder==ln&&Ct.push(cn);else{let Ln=Xn.spaceItems.find(wn=>wn.path==Wt.path);Ln&&(Ct.push(cn),Fe[cn]=Ln.rank)}let Me=f0(i,yn,y,Ct),Ie=sn&&!Nn?Bt(Pt({},Wt),{space:[],contexts:[]}):Bt(Pt({},Wt),{spaces:Ct,contexts:ct(Me),spaceRanks:Fe}),Re=!0;return rn&&ru.default.isEqual(Ie,rn)&&(Re=!1),{changed:Re,cache:Ie}};function is(i){let{file:p,settings:y,contextsCache:A,spacesCache:m,vaultItem:E,metadataCache:X,resolvedLinks:sn,folderNote:rn,oldMetadata:K}=i;return rs(p,y,A,m,E,X,sn,rn,K)}function us(i){let{context:p,mdbTable:y,oldCache:A}=i;return es(p,y,A)}var o0=self;o0.onmessage=async i=>{let{payload:p,job:y}=i.data,A;y.type=="file"?A=is(p):y.type=="context"&&(A=us(p));try{postMessage({job:y,result:A})}catch(m){console.log(m),postMessage({job:y,result:{$error:`Failed to index ${y.type} ${y.path}: ${m}`}})}};\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 +var Manager = class extends import_obsidian58.Component { + constructor(numWorkers, cache) { + super(); + this.numWorkers = numWorkers; + this.cache = cache; + this.workers = []; + this.busy = []; + this.reloadQueue = []; + 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) }); + worker.onmessage = (evt) => this.finish(evt.data.job, evt.data.result, index); + this.workers.push(worker); + this.register(() => worker.terminate()); + this.busy.push(false); + } + } + reload(jerb) { + const jobKey = stringifyJob(jerb); + let promise = new Promise((resolve, reject) => { + var _a2; + if (this.callbacks.has(jobKey)) + (_a2 = this.callbacks.get(jobKey)) == null ? void 0 : _a2.push([resolve, reject]); + else + this.callbacks.set(jobKey, [[resolve, reject]]); + }); + if (this.reloadSet.has(jobKey)) + return promise; + this.reloadSet.add(jobKey); + let workerId = this.nextAvailableWorker(); + if (workerId !== void 0) { + this.send(jerb, workerId); + } else { + this.reloadQueue.push(jerb); + } + return promise; + } + finish(jerb, data, index) { + var _a2; + const jobKey = stringifyJob(jerb); + let 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(); + if (job !== void 0) + this.send(job, index); + if ("$error" in data) { + for (let [_9, reject] of calls) + reject(data["$error"]); + } else { + for (let [callback, _9] of calls) + callback(data); + } + } + send(job, workerId) { + if (job.type == "file") { + const file = tFileToAFile(getAbstractFileAtPath(app, job.path)); + if (!file) + return; + const folderNote = (file2) => { + if (!file2.extension || file2.extension.length == 0) { + return abstractFileAtPathExists(app, folderNotePathFromAFile(this.cache.plugin.settings, file2)); + } else if (file2.extension == "md") { + const folderPath = getAbstractFileAtPath(app, folderPathFromFolderNoteFile(this.cache.plugin.settings, file2)); + return folderPath.name == file2.name; + } + return false; + }; + this.workers[workerId].postMessage({ + job, + payload: { + file, + settings: this.cache.plugin.settings, + contextsCache: this.cache.contextsCache, + spacesCache: this.cache.spacesCache, + vaultItem: vaultItemForPath(this.cache.plugin, job.path), + metadataCache: app.metadataCache.getCache(job.path), + resolvedLinks: app.metadataCache.resolvedLinks, + folderNote: folderNote(file), + oldMetadata: this.cache.files.get(job.path) + } + }); + this.busy[workerId] = true; + } + if (job.type == "context") { + const context = mdbContextByPath(this.cache.plugin, job.path); + if (!context) { + return; + } + getMDBTable(this.cache.plugin, context, "files").then((mdbTable) => { + this.workers[workerId].postMessage({ + job, + payload: { + context, + mdbTable, + oldCache: this.cache.contextsCache.get(job.path) + } + }); + this.busy[workerId] = true; + }); + } + } + nextAvailableWorker() { + let index = this.busy.indexOf(false); + return index == -1 ? void 0 : index; + } +}; + +// src/superstate/superstate.ts +var loadContexts = (plugin, spaces2) => { + 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_obsidian59.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) + ); + const allcontexts = (_a2 = folder == null ? void 0 : folder.children.filter( + (f4) => f4 instanceof import_obsidian59.TFile && f4.extension == "mdb" && spaces3.some((s5) => s5.name == f4.basename) + ).map((f4) => spaceContextFromSpace(plugin2, spaceContextPathFromName(f4.basename)))) != null ? _a2 : []; + return allcontexts; + }; + const getAllFolderContextFiles = (plugin2) => { + let files = []; + let rootFolder = app.vault.getRoot(); + function recursiveFx(folder) { + for (let child of folder.children) { + if (child instanceof import_obsidian59.TFolder) { + let childFolder = child; + if (childFolder.children) + recursiveFx(childFolder); + } + if (child instanceof import_obsidian59.TFile && child.basename == plugin2.settings.folderContextFile && child.path != "/") + files.push(child); + } + } + recursiveFx(rootFolder); + return files.map((f4) => folderContextFromFolder(plugin2, f4.parent.path)); + }; + return [...getAllTagContextFiles(plugin), ...getAllFolderContextFiles(plugin), ...getAllSpaceContextFiles(plugin, spaces2)]; +}; +var Superstate = class extends import_obsidian59.Component { + constructor(app2, indexVersion, onChange, plugin) { + super(); + this.app = app2; + this.indexVersion = indexVersion; + this.onChange = onChange; + this.persistSpacesDB = (0, import_lodash9.debounce)( + (tables) => { + saveDBToPath(this.plugin, this.plugin.spacesDBPath, tables).then((f4) => { + this.updateSpaceLastUpdated(); + this.backupSpaceDB(true); + }); + }, + 1e3, + { + leading: false + } + ); + this.initialized = false; + this.plugin = plugin; + this.metadataCache = app2.metadataCache; + this.files = /* @__PURE__ */ new Map(); + this.spacesCache = /* @__PURE__ */ new Map(); + this.spaces = new IndexMap(); + this.tags = new IndexMap(); + this.contextsCache = /* @__PURE__ */ new Map(); + this.contexts = new IndexMap(); + this.contextStoreQueue = 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)); + } + static create(app2, indexVersion, onChange, plugin) { + return new Superstate(app2, indexVersion, onChange, plugin); + } + addToContextStoreQueue(operation) { + this.contextStoreQueue = this.contextStoreQueue.then(operation).catch(() => { + }); + } + async resolveSync() { + 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; + }; + let 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"); + } + while (!spacesReady && counter++ <= this.plugin.settings.spacesSyncTimeoutSeconds * 2) { + spacesReady = await waitIfSpacesFileStillSyncing(500); + } + this.syncStatus = 0; + this.broadcast("sync"); + } + } + } + async initializeIndex() { + await this.loadFromCache(); + this.loadSpacesDB(); + } + async loadSpacesDB() { + var _a2, _b2, _c2, _d2, _e2, _f; + if (this.plugin.settings.spacesEnabled) { + await this.resolveSync(); + 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(); + } + 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; + let resolverFile = getAbstractFileAtPath(app, this.plugin.settings.spacesSyncLastUpdated); + if (!resolverFile) { + return app.vault.create(this.plugin.settings.spacesSyncLastUpdated, f4.mtime.toString()).then((f5) => { + }); + } + return app.vault.modify(getAbstractFileAtPath(app, this.plugin.settings.spacesSyncLastUpdated), f4.mtime.toString()); + } + }); + } + } + async saveSpacesDB(tables, save = 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) { + this.persistSpacesDB(tables); + } + } + async initialize() { + await this.loadFromCache(); + const start = Date.now(); + if (this.plugin.settings.spacesEnabled) + await this.initializeSpaces(); + await this.initializeContexts(); + await this.initalizeFiles(); + this.cleanContexts(); + console.log(`Make.md Superstate: ${Date.now() - start} ms`); + } + async initializeSpaces() { + this.spacesCache = /* @__PURE__ */ new Map(); + let promises = this.spacesDBCache.map((f4) => this.reloadSpace(f4.name)); + await Promise.all(promises); + } + async initializeContexts() { + const allContexts = loadContexts(this.plugin, this.allSpaces()); + let promises = allContexts.map((l3) => this.reloadContext(l3)); + await Promise.all(promises); + } + async cleanContexts() { + this.contextsCache.forEach((context) => { + const contextFiles = [...this.contexts.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))); + }); + this.spacesCache.forEach((space) => { + const removeFiles = [...this.spaces.getInverse(space.name)]; + }); + } + async loadFromCache() { + const allSpaces = this.plugin.settings.cachedSpaces; + let cacheSpacePromises = allSpaces.map((s5) => this.persister.loadFile(s5 + "//").then((serializedSpace) => { + const space = safelyParseJSON(serializedSpace); + if (space) { + this.spacesCache.set(s5, space); + this.broadcast("space", "change", s5); + } + })); + await Promise.all(cacheSpacePromises); + const allFiles = getAllAbstractFilesInVault(this.plugin, app); + let cachePromises = allFiles.map((file) => this.persister.loadFile(file.path).then((f4) => { + if (!f4) + return; + const cache = parseFileCache(f4); + this.files.set(file.path, cache); + this.tags.set(file.path, new Set(cache.tags)); + this.contexts.set(file.path, new Set(cache.contexts)); + this.spaces.set(file.path, new Set(cache.spaces)); + this.broadcast("file", "change", file.path); + this.fileReloaded(file.path); + })); + await Promise.all(cachePromises); + this.broadcast("vault"); + } + async initalizeFiles() { + const allFiles = getAllAbstractFilesInVault(this.plugin, app); + let promises = allFiles.map((l3) => this.reloadFile(l3)); + await Promise.all(promises); + this.broadcast("vault"); + } + async renameTag(tag, newTag) { + const contextCache = this.contextsCache.get(tag); + const existingContext = this.contextsCache.get(newTag); + if (existingContext) { + await this.reloadContext(existingContext.info); + this.tags.getInverse(tag).forEach((file) => this.renameTagInFile(tag, newTag, getAbstractFileAtPath(app, file))); + } else { + this.contextsCache.set(newTag, contextCache); + this.contextsCache.delete(tag); + this.tags.getInverse(tag).forEach((file) => this.renameTagInFile(tag, newTag, getAbstractFileAtPath(app, file))); + } + let allContextsWithTag = []; + for (let [contextPath, contextCache2] of this.contextsCache) { + if (contextCache2.contexts.includes(tag) || contextCache2.defContexts.includes(tag)) { + allContextsWithTag.push(contextCache2.info); + } + } + this.addToContextStoreQueue(() => renameTagInContexts(this.plugin, tag, newTag, allContextsWithTag)); + } + renameTagInFile(tag, newTag, file) { + let oldMetadata; + if (this.files.has(file.path)) { + oldMetadata = this.files.get(file.path); + } + if (oldMetadata) { + const newMetadata = { + ...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) + }; + this.files.set(file.path, newMetadata); + this.tags.set(file.path, new Set(newMetadata.tags)); + this.contexts.set(file.path, new Set(newMetadata.contexts)); + } else { + this.reloadFile(file); + } + this.fileReloaded(file.path); + this.broadcast("file", "change", file.path); + } + deleteTag(tag) { + const contextCache = this.contextsCache.get(tag); + this.contextsCache.delete(tag); + this.tags.getInverse(tag).forEach((file) => { + this.deleteTagInFile(tag, getAbstractFileAtPath(app, file)); + }); + let allContextsWithTag = []; + for (let [contextPath, contextCache2] of this.contextsCache) { + if (contextCache2.contexts.includes(tag) || contextCache2.defContexts.includes(tag)) { + allContextsWithTag.push(contextCache2.info); + } + } + this.addToContextStoreQueue(() => removeTagInContexts(this.plugin, tag, allContextsWithTag)); + } + deleteTagInFile(tag, file) { + let oldMetadata; + if (this.files.has(file.path)) { + oldMetadata = this.files.get(file.path); + } + if (oldMetadata) { + const newMetadata = { + ...oldMetadata, + tags: oldMetadata.tags.filter((f4) => f4 != tag), + fileTags: oldMetadata.fileTags.filter((f4) => f4 != tag), + contexts: oldMetadata.contexts.filter((f4) => f4 != tag) + }; + this.files.set(file.path, newMetadata); + this.tags.set(file.path, new Set(newMetadata.tags)); + this.contexts.set(file.path, new Set(newMetadata.contexts)); + } else { + this.reloadFile(file); + } + this.fileReloaded(file.path); + this.broadcast("file", "change", file.path); + } + metadataChange(file) { + const fileCache = this.files.get(file.path); + if (fileCache && file instanceof import_obsidian59.TFile) { + const allContextsWithFile = fileCache.contexts.map((f4) => { + var _a2; + return (_a2 = this.contextsCache.get(f4)) == null ? void 0 : _a2.info; + }).filter((f4) => f4); + this.addToContextStoreQueue(() => onMetadataChange(this.plugin, file, allContextsWithFile)); + this.reloadFile(file); + } + } + renameFile(oldPath, newPath) { + var _a2, _b2; + const oldParentPath = getParentPathFromString(oldPath); + const newParentPath = getParentPathFromString(newPath); + const fileCache = { ...this.files.get(oldPath), path: newPath, parent: newParentPath }; + this.files.set(newPath, fileCache); + this.files.delete(oldPath); + this.spaces.rename(oldPath, newPath); + const allContextsWithFile = ((_a2 = fileCache.contexts) != null ? _a2 : []).map((f4) => { + var _a3; + return (_a3 = this.contextsCache.get(f4)) == null ? void 0 : _a3.info; + }).filter((f4) => f4); + if (oldParentPath != newParentPath) { + const newFolderPath = getFolderPathFromString(newPath); + const newFolderContext = this.contextsCache.get(newFolderPath); + const newTags = uniq([...fileCache.fileTags, ...(_b2 = newFolderContext == null ? void 0 : newFolderContext.contexts) != null ? _b2 : []]); + const sameContexts = allContextsWithFile.filter((f4) => newTags.includes(f4)); + if (sameContexts.length > 0) + this.addToContextStoreQueue(() => renameFileInContexts(this.plugin, oldPath, newPath, sameContexts).then((f4) => sameContexts.forEach((c4) => this.reloadContext(c4)))); + const newContexts = newTags.filter((f4) => !sameContexts.includes(f4)).map((f4) => { + var _a3; + return (_a3 = this.contextsCache.get(f4)) == null ? void 0 : _a3.info; + }); + if (newContexts.length > 0) + this.addToContextStoreQueue(() => addFileInContexts(this.plugin, newPath, newContexts).then((f4) => newContexts.forEach((c4) => this.reloadContext(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)))); + } else { + this.addToContextStoreQueue(() => renameFileInContexts(this.plugin, oldPath, newPath, allContextsWithFile).then((f4) => { + allContextsWithFile.forEach((c4) => this.reloadContext(c4)); + })); + } + let allContextsWithLink = []; + for (let [contextPath, contextCache] of this.contextsCache) { + if (contextCache.outlinks.includes(oldPath)) { + allContextsWithLink.push(contextCache.info); + } + } + this.spaces.get(newPath).forEach((f4) => this.reloadSpace(f4)); + this.reloadFile(getAbstractFileAtPath(app, newPath)).then((f4) => this.broadcast("space")); + this.addToContextStoreQueue(() => renameLinkInContexts(this.plugin, oldPath, newPath, allContextsWithLink).then((f4) => allContextsWithFile.forEach((c4) => this.reloadContext(c4)))); + } + async createFile(path) { + await this.reloadFile(getAbstractFileAtPath(app, path)); + this.broadcast("space"); + } + deleteFile(path) { + const fileCache = this.files.get(path); + if (!fileCache) + return; + this.files.delete(path); + this.spaces.delete(path); + const allContextsWithFile = fileCache.contexts.map((f4) => { + var _a2; + return (_a2 = this.contextsCache.get(f4)) == null ? void 0 : _a2.info; + }).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.contextsCache) { + if (contextCache.outlinks.includes(path)) { + allContextsWithLink.push(contextCache.info); + } + } + this.addToContextStoreQueue(() => removeLinkInContexts(this.plugin, path, allContextsWithLink).then((f4) => allContextsWithFile.forEach((c4) => this.reloadContext(c4)))); + this.broadcast("space"); + } + async renameSpace(oldSpace, newSpace) { + if (this.spacesCache.has(oldSpace)) { + this.spacesCache.delete(oldSpace); + await this.reloadSpace(newSpace); + } + this.spaces.renameInverse(oldSpace, newSpace); + this.broadcast("space", "rename", oldSpace); + } + deleteSpace(space) { + if (this.spacesCache.has(space)) { + this.spacesCache.delete(space); + } + this.spaces.deleteInverse(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.loadSpacesDB(); + } + } + async reloadContext(context) { + if (!context) + return false; + return this.indexer.reload({ type: "context", path: context.contextPath }).then((r3) => { + const { changed, cache } = r3; + if (!changed) { + return false; + } + this.contextsCache.set(context.contextPath, cache); + this.broadcast("context", "change", context.contextPath); + return true; + }); + } + broadcast(type, action, name, newName) { + dispatchSpaceDatabaseFileChanged(type, action, name, newName); + } + async reloadVault() { + this.broadcast("vault"); + } + allSpaces() { + return [...this.spacesCache.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 }); + } + ); + } + 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; + } + } + const spaceBackupFolder = (0, import_obsidian59.normalizePath)( + `${app.vault.configDir}/plugins/make-md/backups` + ); + if (!await this.app.vault.adapter.exists( + spaceBackupFolder + )) { + await this.app.vault.createFolder(spaceBackupFolder); + } + const backupPath = (0, import_obsidian59.normalizePath)( + `${spaceBackupFolder}/Spaces ${format(Date.now(), "yyyy-MM-dd HH-mm")}.mdb` + ); + if (await this.app.vault.adapter.exists(this.plugin.spacesDBPath) && await !this.app.vault.adapter.exists(backupPath)) + app.vault.adapter.copy(this.plugin.spacesDBPath, backupPath); + } + async loadSpaceDBFromBackup(fileName) { + const filePath = (0, import_obsidian59.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.loadSpacesDB(); + } + } + reloadSpace(spaceName) { + 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.spacesCache.set(spaceName, cache); + this.persister.storeFile(spaceName + "//", JSON.stringify(cache)); + this.plugin.settings.cachedSpaces = this.allSpaces().map((f4) => f4.name); + this.plugin.saveSettings(); + this.broadcast("space", "change", spaceName); + } + } + async reloadFile(file) { + return this.indexer.reload({ type: "file", path: file.path }).then((r3) => { + const { changed, cache } = r3; + if (!changed) { + return false; + } + this.files.set(file.path, cache); + this.tags.set(file.path, new Set(cache.tags)); + this.contexts.set(file.path, new Set(cache.contexts)); + if (!import_lodash9.default.isEqual(cache.spaces, this.spaces.get(file.path))) { + this.spaces.set(file.path, new Set(cache.spaces)); + this.broadcast("space"); + } + this.fileReloaded(file.path); + this.broadcast("file", "change", file.path); + return true; + }); + } + async fileReloaded(path) { + let metadata; + if (this.files.has(path)) { + metadata = this.files.get(path); + } + if (!metadata) { + return false; + } + let missingContexts = []; + let removedContexts = []; + this.contextsCache.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 (missingContexts.length > 0) { + this.addToContextStoreQueue(() => addFileInContexts(this.plugin, path, missingContexts).then((f4) => missingContexts.forEach((c4) => this.reloadContext(c4)))); + } + if (removedContexts.length > 0) { + this.addToContextStoreQueue(() => removeFileInContexts(this.plugin, path, removedContexts).then((f4) => removedContexts.forEach((c4) => this.reloadContext(c4)))); + } + this.persister.storeFile(path, serializeFileCache(metadata)); + } +}; + // src/components/FileContextView/FileHeaderContextView.tsx var FileHeaderContextView = (props2) => { const { name, fm } = props2; - const [collapsed, setCollapsed] = p2(false); + const [collapsed, setCollapsed] = h2(false); const tags = fm.tags; - const [values, setValues] = p2({}); - const [columns, setColumns] = p2([]); - h2(() => { + const [values, setValues] = h2({}); + const [columns, setColumns] = h2([]); + p2(() => { let newCols = []; let newValues = {}; const fmKeys = uniqCaseInsensitive(frontMatterKeys(fm)); @@ -49120,46 +53104,49 @@ var FileHeaderContextView = (props2) => { if (fm) { newCols.push(...cols); Object.keys(fm).forEach((c4) => { - newValues[c4] = parseFrontMatter(c4, fm[c4], false); + newValues[c4] = parseFrontMatter(c4, fm[c4]); }); } setValues(newValues); setColumns(newCols); }, []); - return /* @__PURE__ */ bn.createElement(bn.Fragment, null, fm && /* @__PURE__ */ bn.createElement(NoteBannerView, { + return /* @__PURE__ */ Cn.createElement(Cn.Fragment, null, fm && /* @__PURE__ */ Cn.createElement(NoteBannerView, { plugin: props2.plugin, - link: fm.banner - }), /* @__PURE__ */ bn.createElement("div", { + link: fm[FMBannerKey] + }), /* @__PURE__ */ Cn.createElement("div", { className: "mk-file-context-component" - }, /* @__PURE__ */ bn.createElement("div", { + }, /* @__PURE__ */ Cn.createElement("div", { className: `mk-spacer`, style: { - "--header-height": fm && fm.banner ? ((platformIsMobile() ? 1 : 0) * 26 + 138 + (!fm.icon || props2.plugin.settings.inlineContextNameLayout == "horizontal" ? 1 : 0) * 50).toString() + "px" : 0 + "--header-height": fm && fm[FMBannerKey] ? ((platformIsMobile() ? 1 : 0) * 26 + 138 + (!fm.icon || props2.plugin.settings.inlineContextNameLayout == "horizontal" ? 1 : 0) * 50).toString() + "px" : 0 }, onContextMenu: (e4) => e4.preventDefault() - }), /* @__PURE__ */ bn.createElement("div", { + }), /* @__PURE__ */ Cn.createElement("div", { className: `mk-file-context-file ${props2.plugin.settings.inlineContextNameLayout == "horizontal" ? "mk-file-context-file-horizontal" : ""}` - }, /* @__PURE__ */ bn.createElement(bn.Fragment, null, fm.icon ? /* @__PURE__ */ bn.createElement("div", { + }, /* @__PURE__ */ Cn.createElement(Cn.Fragment, null, fm.icon ? /* @__PURE__ */ Cn.createElement("div", { className: `mk-file-icon` - }, /* @__PURE__ */ bn.createElement("div", { - dangerouslySetInnerHTML: { __html: unifiedToNative(fm.icon) } - })) : /* @__PURE__ */ bn.createElement(bn.Fragment, null), /* @__PURE__ */ bn.createElement("div", { + }, /* @__PURE__ */ Cn.createElement("div", { + dangerouslySetInnerHTML: { + __html: stickerFromString(fm.icon) + } + })) : /* @__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__ */ bn.createElement(TagsView, { + }, fileNameToString(name)), (tags == null ? void 0 : tags.length) > 0 ? /* @__PURE__ */ Cn.createElement(TagsView, { + canOpen: true, plugin: props2.plugin, tags - }) : /* @__PURE__ */ bn.createElement(bn.Fragment, null)))), !collapsed ? /* @__PURE__ */ bn.createElement("div", { + }) : /* @__PURE__ */ Cn.createElement(Cn.Fragment, null)))), !collapsed ? /* @__PURE__ */ Cn.createElement("div", { className: "mk-file-context-component" - }, /* @__PURE__ */ bn.createElement(bn.Fragment, null, /* @__PURE__ */ bn.createElement("div", { + }, /* @__PURE__ */ Cn.createElement(Cn.Fragment, null, /* @__PURE__ */ Cn.createElement("div", { className: "mk-file-context-section" - }, /* @__PURE__ */ bn.createElement(bn.Fragment, null, columns.map((f4, i4) => /* @__PURE__ */ bn.createElement("div", { + }, /* @__PURE__ */ Cn.createElement(Cn.Fragment, null, columns.map((f4, i4) => /* @__PURE__ */ Cn.createElement("div", { key: i4, className: "mk-file-context-row" - }, /* @__PURE__ */ bn.createElement("div", { + }, /* @__PURE__ */ Cn.createElement("div", { className: "mk-file-context-field" - }, f4.name), /* @__PURE__ */ bn.createElement("div", { + }, f4.name), /* @__PURE__ */ Cn.createElement("div", { className: "mk-file-context-value" - }, /* @__PURE__ */ bn.createElement(DataTypeView, { + }, /* @__PURE__ */ Cn.createElement(DataTypeView, { plugin: props2.plugin, initialValue: values[f4.name], index: 0, @@ -49171,34 +53158,38 @@ var FileHeaderContextView = (props2) => { updateFieldValue: (fieldValue, value) => { }, contextTable: {} - })))))))) : /* @__PURE__ */ bn.createElement(bn.Fragment, null)); + })))))))) : /* @__PURE__ */ Cn.createElement(Cn.Fragment, null)); }; // src/components/FileContextView/ReadingModeHeader.tsx var ReadingModeHeader = (props2) => { - const [path, setPath] = p2(props2.filePath); - h2(() => { + const [path, setPath] = h2(props2.filePath); + const ref = _2(null); + p2(() => { setPath(props2.filePath); }, [props2.filePath]); const changeActiveFile = (evt) => { - setPath(evt.detail.filePath); + if (ref.current.closest(".mod-active") && evt.detail.path.type == "file") + setPath(evt.detail.path.path); }; - h2(() => { - window.addEventListener(eventTypes.activeFileChange, changeActiveFile); + p2(() => { + window.addEventListener(eventTypes.activePathChange, changeActiveFile); return () => { - window.removeEventListener(eventTypes.activeFileChange, changeActiveFile); + window.removeEventListener(eventTypes.activePathChange, changeActiveFile); }; }, [path]); - return /* @__PURE__ */ bn.createElement(InlineFileContextView, { + return /* @__PURE__ */ Cn.createElement("div", { + ref + }, /* @__PURE__ */ Cn.createElement(InlineFileContextView, { plugin: props2.plugin, file: getAbstractFileAtPath(app, path), showHeader: true, editable: false - }); + })); }; // src/utils/contexts/markdownPost.tsx -var import_obsidian53 = require("obsidian"); +var import_obsidian60 = require("obsidian"); var replaceInlineContext = (plugin, el, ctx) => { replaceMarkdownForReadingMode(el, (dom) => { let element = dom.querySelector(".mod-header"); @@ -49208,10 +53199,10 @@ var replaceInlineContext = (plugin, el, ctx) => { element.setAttribute("data-path", ctx.sourcePath); element.toggleClass("mk-header", true); const reactEl = createRoot(element); - ctx.addChild(new import_obsidian53.MarkdownRenderChild(element)); + ctx.addChild(new import_obsidian60.MarkdownRenderChild(element)); if (ctx.sourcePath.match(urlRegex)) { reactEl.render( - /* @__PURE__ */ bn.createElement(FileHeaderContextView, { + /* @__PURE__ */ Cn.createElement(FileHeaderContextView, { plugin, fm: ctx.frontmatter, name: filePathToString(ctx.sourcePath) @@ -49219,7 +53210,7 @@ var replaceInlineContext = (plugin, el, ctx) => { ); } else { reactEl.render( - /* @__PURE__ */ bn.createElement(ReadingModeHeader, { + /* @__PURE__ */ Cn.createElement(ReadingModeHeader, { plugin, filePath: ctx.sourcePath }) @@ -49283,10 +53274,10 @@ function around1(obj, method, createWrapper) { } // src/utils/spaces/patches.ts -var import_obsidian54 = require("obsidian"); +var import_obsidian61 = require("obsidian"); var patchFileExplorer = (plugin) => { plugin.register( - around(import_obsidian54.Workspace.prototype, { + around(import_obsidian61.Workspace.prototype, { getLeavesOfType(old) { return function(type) { if (type == "file-explorer") { @@ -49300,7 +53291,7 @@ var patchFileExplorer = (plugin) => { }; var patchWorkspace = (plugin) => { let layoutChanging = false; - const uninstaller = around(import_obsidian54.Workspace.prototype, { + const uninstaller = around(import_obsidian61.Workspace.prototype, { changeLayout(old) { return async function(workspace) { layoutChanging = true; @@ -49321,7 +53312,7 @@ var patchWorkspace = (plugin) => { return false; if (layoutChanging) return false; - if (parent === app.workspace.rootSplit || import_obsidian54.WorkspaceContainer && parent instanceof import_obsidian54.WorkspaceContainer) { + if (parent === app.workspace.rootSplit || import_obsidian61.WorkspaceContainer && parent instanceof import_obsidian61.WorkspaceContainer) { for (const popover of FlowEditor.popoversForWindow( parent.win )) { @@ -49354,15 +53345,12 @@ var patchWorkspace = (plugin) => { }; // src/main.ts -var MakeMDPlugin = class extends import_obsidian55.Plugin { +var MakeMDPlugin = class extends import_obsidian62.Plugin { constructor() { super(...arguments); this.dataViewAPI = () => (0, import_obsidian_dataview.getAPI)(); - this.saveSpacesDB = (0, import_obsidian55.debounce)( - () => this.saveAndReloadSpaceDBIfNeeded(), - 1e3, - true - ); + this.spacesDBLastModify = 0; + this.debouncedRefresh = () => null; this.createTable = async (path) => { const context = folderContextFromFolder(this, path); const schemas = await getMDBTableSchemas(this, context); @@ -49373,52 +53361,35 @@ var MakeMDPlugin = class extends import_obsidian55.Plugin { ); return "Table"; }; - this.triggerVaultChangeEvent = (file, changeType, oldPath) => { - let event = new CustomEvent(eventTypes.vaultChange, { - detail: { - file, - changeType, - oldPath: oldPath ? oldPath : "" - } - }); - window.dispatchEvent(event); - }; - this.metadataChange = (file, data, cache) => { - var _a2, _b2; - if (!(this.dataViewReady && cache)) { - let event = new CustomEvent(eventTypes.metadataChange, { - detail: { file, tags: (_b2 = (_a2 = cache == null ? void 0 : cache.tags) == null ? void 0 : _a2.map((f4) => f4.tag)) != null ? _b2 : [] } - }); - window.dispatchEvent(event); - } - this.addToQueue(() => onMetadataChange(this, file)); + this.metadataChange = (file) => { + this.index.metadataChange(file); }; this.onCreate = (file) => { if (!file) return; - this.triggerVaultChangeEvent(file, "create", ""); - this.addToQueue(() => onFileCreated(this, file.path)); - onFileCreated2(this, file.path, file instanceof import_obsidian55.TFolder); + onFileCreated(this, file.path, file instanceof import_obsidian62.TFolder); }; this.onDelete = (file) => { - this.triggerVaultChangeEvent(file, "delete", ""); - if (file instanceof import_obsidian55.TFile && file.extension != "mdb") { - this.addToQueue(() => onFileDeleted(this, file.path)); - onFileDeleted2(this, file.path); - } else if (file instanceof import_obsidian55.TFolder) { - this.addToQueue(() => onFolderDeleted(file.path)); - onFolderDeleted2(this, file.path); + if (file instanceof import_obsidian62.TFile && file.extension != "mdb") { + onFileDeleted(this, file.path); + } else if (file instanceof import_obsidian62.TFolder) { + onFolderDeleted(this, file.path); } this.activeFileChange(); }; + this.onModify = (file) => { + if (file.path == this.settings.spacesSyncLastUpdated) { + this.index.spacesSynced(); + } + if (file instanceof import_obsidian62.TFile && file.extension == "mdb") { + this.index.reloadContext(mdbContextByDBPath(this, file.path)); + } + }; this.onRename = (file, oldPath) => { - this.triggerVaultChangeEvent(file, "rename", oldPath); - if (file instanceof import_obsidian55.TFile && file.extension != "mdb") { - this.addToQueue(() => onFileChanged(this, oldPath, file.path)); - onFileChanged2(this, oldPath, file.path); - } else if (file instanceof import_obsidian55.TFolder) { - this.addToQueue(() => onFolderChanged(this, oldPath, file.path)); - onFolderChanged2(this, oldPath, file.path); + if (file instanceof import_obsidian62.TFile && file.extension != "mdb") { + onFileChanged(this, oldPath, file.path); + } else if (file instanceof import_obsidian62.TFolder) { + onFolderChanged(this, oldPath, file.path); } this.activeFileChange(); }; @@ -49427,7 +53398,7 @@ var MakeMDPlugin = class extends import_obsidian55.Plugin { if (leafs.length == 0) { let leaf = this.app.workspace.getLeftLeaf(false); await leaf.setViewState({ type: FILE_TREE_VIEW_TYPE }); - if (showAfterAttach) + if (showAfterAttach && !app.workspace.leftSplit.collapsed) this.app.workspace.revealLeaf(leaf); } else { leafs.forEach((leaf) => this.app.workspace.revealLeaf(leaf)); @@ -49453,15 +53424,16 @@ var MakeMDPlugin = class extends import_obsidian55.Plugin { leaf.detach(); } }; - this.openFileContextLeaf = async () => { + this.openFileContextLeaf = async (reveal) => { let leafs = this.app.workspace.getLeavesOfType(FILE_CONTEXT_VIEW_TYPE); if (leafs.length == 0) { let leaf = this.app.workspace.getRightLeaf(false); await leaf.setViewState({ type: FILE_CONTEXT_VIEW_TYPE }); + this.app.workspace.revealLeaf(leaf); } else { leafs.forEach((leaf) => this.app.workspace.revealLeaf(leaf)); } - if (platformIsMobile()) { + if (platformIsMobile() && !reveal) { app.workspace.rightSplit.collapse(); } }; @@ -49478,9 +53450,6 @@ var MakeMDPlugin = class extends import_obsidian55.Plugin { const sqljs = await loadSQL(); return sqljs; } - spaceDBInstance() { - return this.spaceDB; - } openFlow() { const cm = getActiveCM(); if (cm) { @@ -49537,39 +53506,48 @@ var MakeMDPlugin = class extends import_obsidian55.Plugin { }); } } - async saveAndReloadSpaceDBIfNeeded() { - app.vault.adapter.stat(this.spacesDBPath).then((f4) => { - if ((f4 == null ? void 0 : f4.mtime) == this.spacesDBLastModify) { - return saveDBAndKeepAlive(this.spaceDBInstance(), this.spacesDBPath).then((f5) => app.vault.adapter.stat(this.spacesDBPath)).then((f5) => this.spacesDBLastModify = f5 == null ? void 0 : f5.mtime); + loadSuperState() { + this.app.workspace.onLayoutReady(async () => { + if (this.settings.spacesEnabled) + await this.index.initializeIndex(); + else + this.index.initialize(); + 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 (this.dataViewAPI()) { + this.registerEvent( + this.app.metadataCache.on("dataview:index-ready", () => { + this.dataViewReady = true; + }) + ); + this.registerEvent( + this.app.metadataCache.on( + "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_obsidian62.TFile) { + this.metadataChange(file); + } + this.dataViewLastIndex = this.dataViewAPI().index.revision; + } + } + ) + ); } - return this.reloadSpaceDB(false); + await this.openFileTreeLeaf(true); }); } - async reloadSpaceDB(firstLoad) { - var _a2; - (_a2 = this.spaceDB) == null ? void 0 : _a2.close(); - this.spaceDB = await getDB(await loadSQL(), this.spacesDBPath); - dispatchSpaceDatabaseFileChanged("sync"); - if (!firstLoad) { - new import_obsidian55.Notice( - "Spaces were updated from another device and have been reloaded" - ); - } - return app.vault.adapter.stat(this.spacesDBPath).then((f4) => this.spacesDBLastModify = f4 == null ? void 0 : f4.mtime); - } async loadSpaces() { - this.spacesDBPath = (0, import_obsidian55.normalizePath)( - app.vault.configDir + "/plugins/make-md/Spaces.mdb" - ); - await this.reloadSpaceDB(true); - patchWorkspace(this); - document.body.classList.toggle("mk-hide-tabs", !this.settings.sidebarTabs); - document.body.classList.toggle("mk-hide-ribbon", !this.settings.showRibbon); - document.body.classList.toggle( - "mk-folder-lines", - this.settings.folderIndentationLines - ); if (this.settings.spacesEnabled) { + document.body.classList.toggle("mk-hide-tabs", !this.settings.sidebarTabs); + document.body.classList.toggle("mk-hide-ribbon", !this.settings.showRibbon); + document.body.classList.toggle( + "mk-folder-lines", + this.settings.folderIndentationLines + ); document.body.classList.toggle( "mk-spaces-enabled", this.settings.spacesEnabled @@ -49579,46 +53557,6 @@ var MakeMDPlugin = class extends import_obsidian55.Plugin { this.registerView(FILE_TREE_VIEW_TYPE, (leaf) => { return new FileTreeView(leaf, this); }); - this.app.workspace.onLayoutReady(async () => { - const tables = dbResultsToDBTables( - this.spaceDBInstance().exec( - "SELECT name FROM sqlite_schema WHERE type ='table' AND name NOT LIKE 'sqlite_%';" - ) - ); - if (tables.length == 0) { - initiateDB(this.spaceDBInstance()); - } - if (this.settings.folderRank && this.settings.folderRank.children.length > 0) { - migrateIndex(this); - } else { - rebuildIndex(this); - } - 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.app.metadataCache.on("changed", this.metadataChange); - if (this.dataViewAPI()) { - this.registerEvent( - this.app.metadataCache.on("dataview:index-ready", () => { - this.dataViewReady = true; - }) - ); - this.registerEvent( - this.app.metadataCache.on( - "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_obsidian55.TFile) { - this.metadataChange(file); - } - this.dataViewLastIndex = this.dataViewAPI().index.revision; - } - } - ) - ); - } - await this.openFileTreeLeaf(true); - }); } this.registerEvent( app.workspace.on("active-leaf-change", () => this.activeFileChange()) @@ -49628,7 +53566,7 @@ var MakeMDPlugin = class extends import_obsidian55.Plugin { let filePath = null; const activeLeaf = app.workspace.activeLeaf; if ((activeLeaf == null ? void 0 : activeLeaf.view.getViewType()) == CONTEXT_VIEW_TYPE) { - const context = mdbContextByContextPath( + const context = mdbContextByPath( this, activeLeaf == null ? void 0 : activeLeaf.view.getState().contextPath ); @@ -49638,18 +53576,18 @@ var MakeMDPlugin = class extends import_obsidian55.Plugin { filePath = file.path; } } else if ((activeLeaf == null ? void 0 : activeLeaf.view.getViewType()) == "markdown") { - const view = app.workspace.getActiveViewOfType(import_obsidian55.MarkdownView); - if (view instanceof import_obsidian55.MarkdownView) { + const view = app.workspace.getActiveViewOfType(import_obsidian62.MarkdownView); + if (view instanceof import_obsidian62.MarkdownView) { filePath = view.file.path; } } return filePath; } activeFileChange() { - const filePath = this.getActiveFile(); - if (filePath) { - let evt = new CustomEvent(eventTypes.activeFileChange, { - detail: { filePath } + const path = this.getActiveFile(); + if (path) { + let evt = new CustomEvent(eventTypes.activePathChange, { + detail: { path: pathByString(this, path) } }); window.dispatchEvent(evt); } @@ -49687,10 +53625,40 @@ var MakeMDPlugin = class extends import_obsidian55.Plugin { vaultChangeModal.open(); } }); + this.addCommand({ + id: "mk-spaces-remove-file", + name: i18n_default.commandPalette.addFileSpace, + callback: () => { + let vaultChangeModal = new RemoveFromSpaceModal( + this, + this.getActiveFile() + ); + vaultChangeModal.open(); + } + }); this.addCommand({ id: "mk-spaces-reload", name: i18n_default.commandPalette.reloadSpaces, - callback: () => this.reloadSpaceDB(false) + callback: () => this.index.loadSpacesDB() + }); + this.addCommand({ + id: "mk-spaces-load-backup", + name: i18n_default.commandPalette.loadBackupSpace, + callback: () => { + this.app.vault.adapter.list( + (0, import_obsidian62.normalizePath)(`${app.vault.configDir}/plugins/make-md/backups`) + ).then( + (f4) => { + let 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", @@ -49702,7 +53670,7 @@ var MakeMDPlugin = class extends import_obsidian55.Plugin { this.addCommand({ id: "mk-open-file-context", name: i18n_default.commandPalette.openFileContext, - callback: () => this.openFileContextLeaf() + callback: () => this.openFileContextLeaf(true) }); } if (this.settings.inlineBacklinks) { @@ -49715,7 +53683,7 @@ var MakeMDPlugin = class extends import_obsidian55.Plugin { } }); } - if (this.settings.editorFlow) { + if (this.settings.blinkEnabled) { this.addCommand({ id: "mk-blink", name: i18n_default.commandPalette.blink, @@ -49727,6 +53695,8 @@ var MakeMDPlugin = class extends import_obsidian55.Plugin { } ] }); + } + if (this.settings.editorFlow) { this.addCommand({ id: "mk-open-flow", name: i18n_default.commandPalette.openFlow, @@ -49765,15 +53735,6 @@ var MakeMDPlugin = class extends import_obsidian55.Plugin { } loadContext() { if (this.settings.contextEnabled) { - if (this.settings.inlineContext) { - this.registerMarkdownPostProcessor((element, context) => { - replaceInlineContext(this, element, context); - }); - document.body.classList.toggle( - "mk-inline-context-enabled", - this.settings.inlineContext - ); - } this.registerView(FILE_VIEW_TYPE, (leaf) => { return new FileLinkView(leaf, this, FILE_VIEW_TYPE); }); @@ -49807,65 +53768,81 @@ var MakeMDPlugin = class extends import_obsidian55.Plugin { } } loadFlowEditor() { + patchWorkspace(this); document.body.classList.toggle("mk-flow-replace", this.settings.editorFlow); document.body.classList.toggle( "mk-flow-" + this.settings.editorFlowStyle, true ); - if (this.settings.editorFlow) { - this.registerMarkdownPostProcessor((element, context) => { - const removeAllFlowMarks = (el) => { - const embeds = el.querySelectorAll(".internal-embed"); - for (let index = 0; index < embeds.length; index++) { - const embed = embeds.item(index); - if (embed.previousSibling && embed.previousSibling.textContent.slice(-1) == "!") - embed.previousSibling.textContent = embed.previousSibling.textContent.slice(0, -1); - } - }; - removeAllFlowMarks(element); - replaceAllTables(this, element, context); - replaceAllEmbed(element, context); - }); - window.addEventListener( - eventTypes.spawnPortal, - this.spawnPortal.bind(this) - ); - window.addEventListener( - eventTypes.loadPortal, - this.loadPortal.bind(this) - ); - window.addEventListener( - eventTypes.focusPortal, - this.focusPortal.bind(this) - ); - window.addEventListener( - eventTypes.openFilePortal, - this.openFileFromPortal.bind(this) - ); - } + this.registerMarkdownPostProcessor((element, context) => { + const removeAllFlowMarks = (el) => { + const embeds = el.querySelectorAll(".internal-embed"); + for (let index = 0; index < embeds.length; index++) { + const embed = embeds.item(index); + if (embed.previousSibling && embed.previousSibling.textContent.slice(-1) == "!") + embed.previousSibling.textContent = embed.previousSibling.textContent.slice(0, -1); + } + }; + removeAllFlowMarks(element); + replaceAllTables(this, element, context); + replaceAllEmbed(element, context); + }); + window.addEventListener( + eventTypes.spawnPortal, + this.spawnPortal.bind(this) + ); + window.addEventListener( + eventTypes.loadPortal, + this.loadPortal.bind(this) + ); + window.addEventListener( + eventTypes.focusPortal, + this.focusPortal.bind(this) + ); + window.addEventListener( + eventTypes.openFilePortal, + this.openFileFromPortal.bind(this) + ); } loadMakerMode() { if (this.settings.makerMode) { - this.registerEditorSuggest(new MakeMenu(this.app, this)); + if (this.settings.inlineContext) { + this.registerMarkdownPostProcessor((element, context) => { + replaceInlineContext(this, element, context); + }); + document.body.classList.toggle( + "mk-inline-context-enabled", + this.settings.inlineContext + ); + } + if (this.settings.editorFlow) { + this.loadFlowEditor(); + } + if (this.settings.flowMenuEnabled) { + this.registerEditorSuggest(new MakeMenu(this.app, this)); + } this.registerEditorSuggest(new StickerMenu(this.app, this)); - if (platformIsMobile() && this.settings.mobileMakeBar) + if (platformIsMobile() && this.settings.mobileMakeBar && this.settings.inlineStyler) loadStylerIntoContainer(app.mobileToolbar.containerEl, this); } } - addToQueue(operation) { - this.queue = this.queue.then(operation).catch(() => { - }); - } async onload() { console.time("Loading Make.md"); this.loadTime = Date.now(); - this.queue = Promise.resolve(); - (0, import_obsidian55.addIcon)("mk-logo", mkLogo); + (0, import_obsidian62.addIcon)("mk-logo", mkLogo); await this.loadSettings(); + this.index = this.addChild( + Superstate.create(this.app, "0.6", () => { + this.debouncedRefresh(); + }, this) + ); + this.spacesDBPath = (0, import_obsidian62.normalizePath)( + app.vault.configDir + "/plugins/make-md/Spaces.mdb" + ); + this.loadSuperState(); this.addSettingTab(new MakeMDPluginSettingsTab(this.app, this)); await this.loadSpaces(); this.loadContext(); - this.loadFlowEditor(); this.loadMakerMode(); this.reloadExtensions(true); this.loadCommands(); @@ -49899,7 +53876,6 @@ var MakeMDPlugin = class extends import_obsidian55.Plugin { } onunload() { console.log("Unloading Make.md"); - this.spaceDBInstance().close(); window.removeEventListener(eventTypes.spawnPortal, this.spawnPortal); window.removeEventListener(eventTypes.loadPortal, this.loadPortal); window.removeEventListener(eventTypes.focusPortal, this.focusPortal); @@ -49915,6 +53891,12 @@ var MakeMDPlugin = class extends import_obsidian55.Plugin { Licensed under the MIT License (MIT), see http://jedwatson.github.io/classnames */ +/*! + localForage -- Offline Storage, Improved + Version 1.10.0 + https://localforage.github.io/localForage + (c) 2013-2017 Mozilla, Apache License 2.0 +*/ /** * @license * Lodash diff --git a/manifest.json b/manifest.json index 2bb26c1..a277bb2 100755 --- a/manifest.json +++ b/manifest.json @@ -1,7 +1,7 @@ { "id": "make-md", "name": "MAKE.md", - "version": "0.6.23", + "version": "0.7.6", "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 b8f4308..7d6e8e4 100644 --- a/styles.css +++ b/styles.css @@ -151,11 +151,13 @@ } /* src/css/CardsView.css */ +.mk-folder-view .mk-cards-container { + padding-bottom: 60px; +} .mk-cards-container { width: 100%; height: 100%; overflow-x: auto; - padding-bottom: 60px; } .mk-cards-container .mk-list-content > .mk-flowspace-editor { padding-left: 12px !important; @@ -210,11 +212,19 @@ .mk-list-container .mk-list-group-header > div { background: none !important; } +.mk-floweditor > .workspace-leaf > .workspace-leaf-content > .view-content > div > .mk-list-container { + padding-bottom: 0; +} +.mk-floweditor > .workspace-leaf > .workspace-leaf-content > .view-content > div > .mk-list-container .mk-list-item { + padding: 8px; +} +.mk-folder-view .mk-list-container { + padding-bottom: 100px; +} .mk-list-container { width: 100%; height: 100%; overflow-y: auto; - padding-bottom: 100px; } .mk-list-container .mk-list-view { display: flex; @@ -224,9 +234,12 @@ .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 var(--context-padding) 0 var(--context-padding); + padding: 8px; list-style: none; font-size: var(--font-ui-small); color: var(--text-muted); @@ -243,9 +256,12 @@ display: flex; flex-wrap: wrap; align-items: center; - gap: 9px; + 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; } @@ -264,7 +280,6 @@ .mk-list-container .mk-list-fields .mk-cell-file { width: 100%; font-weight: var(--bold-weight); - margin-bottom: -12px; } .mk-cards-container .mk-list-fields { padding: 12px; @@ -500,6 +515,8 @@ body { .mk-cell-date-value:hover { background: var(--interactive-hover); } +.mk-cell-link, +.mk-cell-context, .mk-cell-option { width: 100%; min-height: 24px; @@ -508,7 +525,8 @@ body { display: flex; flex-wrap: wrap; } -.mk-cell-checkbox-item { +.mk-cell-boolean { + padding: 4px; display: flex; align-items: center; gap: 2px; @@ -521,6 +539,9 @@ body { align-items: center; gap: 2px; } +.mk-cell-option-item.mk-is-active { + background: var(--interactive-accent) !important; +} .mk-cell-option-item input { margin: 0; } @@ -666,6 +687,8 @@ body { 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; } @@ -1038,7 +1061,6 @@ body { } .rdp-head_cell { vertical-align: middle; - text-transform: uppercase; font-size: 0.75em; font-weight: 700; text-align: center; @@ -1117,6 +1139,316 @@ body { border-radius: 0; } +/* 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); +} +.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-context-maker { + padding: 0; +} +.mk-context-maker-layout > div > div { + border-bottom: thin solid var(--divider-color); + padding: 4px; +} +.mk-context-maker-layout > div { + display: flex; + flex-direction: column; + gap: 8px; +} + +/* src/css/FilterBar.css */ +.mk-view-selector, +.mk-table-selector { + margin-right: 0; + display: flex; + align-items: center; + padding-left: var(--context-padding); + gap: 16px; + min-height: 48px; + max-width: 100%; + overflow-x: auto; +} +.mk-view-selector { + margin-left: var(--size-4-3); +} +.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 { + border-bottom: thin solid var(--text-normal); + color: var(--text-normal); + background: none !important; +} +.mk-table-selector button, +.mk-view-config button { + background: none; + border: none; + box-shadow: none; + color: var(--text-faint); +} +.mk-view-config button:hover { + color: var(--text-normal); +} +.mk-view-config { + width: 100%; + display: flex; + color: var(--text-faint); + align-items: stretch; + border-bottom: 1px 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); + padding-right: var(--size-4-3); + flex-grow: 1; +} +.mk-view-config span { + flex-grow: 10; +} +.mk-view-config svg { + width: 14px; + height: 14px; +} +.mk-filter-bar { + display: flex; + padding: 8px var(--context-padding); + 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-small); + color: var(--text-muted); + padding: 0px; +} +.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; + padding-left: 4px; +} +.mk-filter div svg { + width: 14px; + height: 14px; +} +.mk-query { + display: flex; + flex-direction: column; + gap: 16px; + margin-bottom: 16px; +} +.mk-query-filters { + flex-direction: column; + padding: 0; + border-bottom: none; +} +.mk-query-filter, +.mk-query-group-type { + display: flex; + width: 100%; +} +.mk-query-group-type { + padding-bottom: 4px; +} +.mk-query-group-type .mk-filter { + align-items: center; +} +.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 { + flex-grow: 1; +} +.mk-folder-note { + display: flex; + align-items: center; + gap: 4px; +} +.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-search-bar { +} +.mk-tag-selector { + display: flex; + gap: 8px; + margin-top: 8px; + margin-bottom: 8px; + flex-wrap: wrap; +} +.mk-tag-selector svg { + color: var(--tag-color) !important; +} +.mk-tag-selector div { + cursor: var(--cursor-link); + font-size: var(--font-ui-medium); + display: flex; +} +.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/FlowEditor.css */ .mk-floweditor .workspace-leaf { all: unset; @@ -1337,215 +1669,6 @@ body { padding-bottom: 10px !important; } -/* src/css/FilterBar.css */ -.mk-table-selector { - margin-right: 0; - display: flex; - align-items: center; - padding-left: var(--context-padding); - gap: 16px; - min-height: 48px; - max-width: 100%; - overflow-x: auto; -} -.mk-table-selector::-webkit-scrollbar { - display: none; -} -.mk-table-selector > div > .mk-collapse { - padding-right: 8px; - padding-left: 0px; -} -.mk-table-selector .mk-collapse.mk-icon-xsmall svg { - color: unset; -} -.mk-table-selector > div > button:not(:last-child) { - padding-right: 0px; -} -.mk-table-selector > div, -.mk-table-selector > button { - border-radius: 0; - margin: 4px -8px; - display: flex; - align-items: center; - border-bottom: thin solid transparent; - height: 100%; -} -.mk-table-selector .mk-is-active button { - color: var(--text-normal); -} -.mk-table-selector .mk-is-active { - border-bottom: thin solid var(--text-normal); - color: var(--text-normal); - background: none !important; -} -.mk-view-selector button { - background: none; - border: none; - box-shadow: none; - color: var(--text-faint); -} -.mk-view-selector button:hover { - color: var(--text-normal); -} -.mk-view-selector { - width: 100%; - display: flex; - color: var(--text-faint); - align-items: stretch; - border-bottom: 1px solid var(--divider-color); - flex-wrap: wrap; -} -.mk-view-selector input { - background: none; - border: none; - flex-grow: 1; -} -.is-phone .mk-view-selector { - flex-wrap: wrap; -} -.is-phone .mk-view-selector 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); - padding-right: var(--size-4-3); - flex-grow: 1; -} -.mk-view-selector span { - flex-grow: 10; -} -.mk-view-selector svg { - width: 14px; - height: 14px; -} -.mk-filter-bar { - display: flex; - padding: 8px var(--context-padding); - gap: 8px; - width: 100%; - border-bottom: 1px solid var(--divider-color); -} -.mk-filter-bar span { - flex-grow: 1; -} -.mk-table-selector .mk-is-active { - color: var(--text-normal) !important; -} -.mk-filter { - display: flex; - font-size: var(--font-ui-small); - color: var(--text-muted); - padding: 0px; -} -.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; - padding-left: 4px; -} -.mk-filter div svg { - width: 14px; - height: 14px; -} -.mk-folder-note { - display: flex; - align-items: center; - gap: 4px; -} -.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-search-bar { -} -.mk-tag-selector { - padding: 0 var(--context-padding); - display: flex; - gap: 8px; - margin-top: 8px; - margin-bottom: 8px; - flex-wrap: wrap; -} -.mk-tag-selector svg { - color: var(--tag-color) !important; -} -.mk-tag-selector div { - cursor: var(--cursor-link); - font-size: var(--font-ui-medium); - display: flex; -} -.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/InlineMenu.css */ body:not(.is-mobile) .mk-style-menu { margin-left: -80px; @@ -1624,7 +1747,7 @@ mark { } .mk-file-context-file.mk-file-context-file-horizontal { flex-direction: row; - align-items: center; + align-items: flex-start; } .mk-header { padding-inline-start: 0 !important; @@ -1635,13 +1758,19 @@ mark { border-radius: 8px; padding: 8px !important; } +.mod-right-split .mk-header { + display: none; +} +.mod-left-split .mk-header { + display: none; +} .markdown-reading-view .mk-file-context-file > .mk-inline-title.inline-title, .markdown-source-view.mod-cm6.is-readable-line-width .mk-file-context-file > .mk-inline-title.inline-title { padding-bottom: 0; - display: flex !important; margin-left: 0 !important; margin-top: 0; padding-top: 0; + margin-bottom: 0; } .mk-file-context-component .mk-tag-selector { margin-top: 4px; @@ -1748,10 +1877,13 @@ mark { .mk-file-context-value input[type=number]:focus { box-shadow: none !important; } +c .mk-section-title, .mk-file-context-title { font-size: var(--font-ui-small); font-weight: var(--bold-weight); color: var(--text-muted); +} +.mk-file-context-title { display: flex; align-items: center; height: 24px; @@ -1983,6 +2115,7 @@ mark { } .mk-image-modal { display: flex; + flex-wrap: wrap; } /* src/css/makerMode.css */ @@ -2048,6 +2181,13 @@ 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; } @@ -2110,6 +2250,9 @@ body.is-mobile .sidebar-toggle-button { flex: 1; overflow: hidden; } +.mk-context-tree .tree-item { + padding: 4px; +} .mk-context-tree .tree-item-self { margin-left: var(--spacing); align-items: center; @@ -2205,45 +2348,48 @@ body:not(.is-mobile) .mk-main-menu-button:hover { /* src/css/SectionView.css */ .mk-section { display: flex; - padding: 4px; - padding-left: 16px; - margin-top: 8px; color: var(--text-muted); font-size: var(--font-ui-smaller); width: 100%; justify-content: space-between; margin-left: 0; } -body:not(.is-mobile) .mk-section { - padding-left: 4px !important; +.mk-section-wrapper { + padding-top: 8px !important; } -body:not(.is-mobile) .mk-section-title:hover { - background: var(--nav-item-background-hover); +.mk-section-tabs { + display: flex; + border-bottom: 1px solid var(--divider-color); +} +.mk-section-tabs .mk-is-active { + background: none; + font-weight: var(--bold-weight); + color: var(--text-normal); +} +.mk-section-tabs .mk-section-title { + font-weight: var(--normal-weight); + background: none; + flex: 1; + display: flex; + justify-content: center; + padding: 12px; + gap: 8px; + height: unset; + flex-direction: column; } .mk-section-title { height: 24px; - border-radius: 4px; - padding-left: 4px; display: flex; min-width: 0; align-items: center; } .mk-section-title .mk-tree-text { - padding: 0.25rem 0rem 0.3rem 0.25rem; -} -body:not(.is-mobile) .mk-section .mk-collapse { - display: none; -} -.mk-section-title .mk-collapse { - display: flex; -} -body:not(.is-mobile) .mk-section-title:hover .mk-collapse { - display: flex; + padding: 0.25rem 0.3rem; } -.mk-section-title .mk-collapse svg { - margin-left: 4px; - width: 10px; - height: 10px; +.mk-section .mk-collapse svg { + margin: 4px; + width: 8px; + height: 8px; } /* src/css/FolderTreeView.css */ @@ -2255,12 +2401,18 @@ body:not(.is-mobile) .mk-section-title:hover .mk-collapse { padding: 0 6px; position: relative; } +.nav-file { + overflow-y: inherit !important; +} .is-mobile .mk-tree-wrapper { padding-top: 6px; padding-bottom: 6px; } .is-mobile .mk-tree-wrapper > div { - padding-left: 8px; + padding-left: 24px; +} +.is-mobile .mk-tree-wrapper > .mk-section { + padding-left: 4px; } .mk-tree-wrapper > div { display: flex; @@ -2524,7 +2676,7 @@ body:not(.is-mobile) .mk-tree-wrapper:not(.mk-section-wrapper):not(.mk-disable-i .mk-sidebar-switcher { display: flex; margin: 8px 12px; - gap: 8px; + gap: 4px; } .mk-sidebar-spaces .mk-sidebar-item { display: flex;