From d30c50cec50da38f810dbf09a358cc287d340564 Mon Sep 17 00:00:00 2001 From: JP Cen Date: Thu, 19 Jan 2023 13:38:06 -0500 Subject: [PATCH] 0.6.12 --- main.js | 16293 ++++++++++++++++++++++++------------------------ manifest.json | 2 +- styles.css | 28 +- 3 files changed, 8090 insertions(+), 8233 deletions(-) diff --git a/main.js b/main.js index 8a03444..c3dedcf 100644 --- a/main.js +++ b/main.js @@ -182,7 +182,7 @@ var require_tslib = __commonJS({ }); }; __generator2 = function(thisArg, body) { - var _4 = { label: 0, sent: function() { + var _5 = { label: 0, sent: function() { if (t4[0] & 1) throw t4[1]; return t4[1]; @@ -198,7 +198,7 @@ var require_tslib = __commonJS({ function step(op) { if (f4) throw new TypeError("Generator is already executing."); - while (g4 && (g4 = 0, op[0] && (_4 = 0)), _4) + while (g4 && (g4 = 0, op[0] && (_5 = 0)), _5) 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; @@ -210,42 +210,42 @@ var require_tslib = __commonJS({ t4 = op; break; case 4: - _4.label++; + _5.label++; return { value: op[1], done: false }; case 5: - _4.label++; + _5.label++; y5 = op[1]; op = [0]; continue; case 7: - op = _4.ops.pop(); - _4.trys.pop(); + op = _5.ops.pop(); + _5.trys.pop(); continue; default: - if (!(t4 = _4.trys, t4 = t4.length > 0 && t4[t4.length - 1]) && (op[0] === 6 || op[0] === 2)) { - _4 = 0; + if (!(t4 = _5.trys, t4 = t4.length > 0 && t4[t4.length - 1]) && (op[0] === 6 || op[0] === 2)) { + _5 = 0; continue; } if (op[0] === 3 && (!t4 || op[1] > t4[0] && op[1] < t4[3])) { - _4.label = op[1]; + _5.label = op[1]; break; } - if (op[0] === 6 && _4.label < t4[1]) { - _4.label = t4[1]; + if (op[0] === 6 && _5.label < t4[1]) { + _5.label = t4[1]; t4 = op; break; } - if (t4 && _4.label < t4[2]) { - _4.label = t4[2]; - _4.ops.push(op); + if (t4 && _5.label < t4[2]) { + _5.label = t4[2]; + _5.ops.push(op); break; } if (t4[2]) - _4.ops.pop(); - _4.trys.pop(); + _5.ops.pop(); + _5.trys.pop(); continue; } - op = body.call(thisArg, _4); + op = body.call(thisArg, _5); } catch (e4) { op = [6, e4]; y5 = 0; @@ -1225,7 +1225,7 @@ var require_lodash = __commonJS({ return string.match(reUnicodeWord) || []; } var runInContext = function runInContext2(context) { - context = context == null ? root : _4.defaults(root.Object(), context, _4.pick(root, contextProps)); + context = context == null ? root : _5.defaults(root.Object(), context, _5.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__"]; @@ -5959,17 +5959,17 @@ var require_lodash = __commonJS({ } return lodash; }; - var _4 = runInContext(); + var _5 = runInContext(); if (typeof define == "function" && typeof define.amd == "object" && define.amd) { - root._ = _4; + root._ = _5; define(function() { - return _4; + return _5; }); } else if (freeModule) { - (freeModule.exports = _4)._ = _4; - freeExports._ = _4; + (freeModule.exports = _5)._ = _5; + freeExports._ = _5; } else { - root._ = _4; + root._ = _5; } }).call(exports); } @@ -9315,14 +9315,14 @@ function T(n2) { 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, _4, k5, b4, g4, m5, x5, A4, C3, $3, H5, I4, T6 = u4.type; + var a5, h5, v3, y5, _5, k5, b4, g4, m5, x5, A4, C3, $3, H5, I4, T6 = 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); 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, _4 = h5.state, v3) + 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, _5 = h5.state, v3) null == T6.getDerivedStateFromProps && null != h5.componentWillMount && h5.componentWillMount(), null != h5.componentDidMount && h5.__h.push(h5.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) { @@ -9334,7 +9334,7 @@ function j(n2, u4, i4, t4, o3, r3, f4, e4, c4) { break n; } null != h5.componentWillUpdate && h5.componentWillUpdate(g4, h5.__s, x5), null != h5.componentDidUpdate && h5.__h.push(function() { - h5.componentDidUpdate(y5, _4, k5); + h5.componentDidUpdate(y5, _5, k5); }); } if (h5.context = x5, h5.props = g4, h5.__v = u4, h5.__P = n2, C3 = l.__r, $3 = 0, "prototype" in T6 && T6.prototype.render) { @@ -9345,7 +9345,7 @@ function j(n2, u4, i4, t4, o3, r3, f4, e4, c4) { 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, _4)), 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; + h5.state = h5.__s, null != h5.getChildContext && (t4 = s(s({}, t4), h5.getChildContext())), v3 || null == h5.getSnapshotBeforeUpdate || (k5 = h5.getSnapshotBeforeUpdate(y5, _5)), 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; } 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); @@ -9991,9 +9991,6 @@ function iterateTreeInSelection(selection, state, iterateFns) { to: selection.to }); } -function iterateTreeInDocument(state, iterateFns) { - (0, import_language2.syntaxTree)(state).iterate({ ...iterateFns }); -} // src/i18n.ts var T4 = class { @@ -10192,7 +10189,7 @@ var T4 = class { label: "Image" }, fileProperty: { - label: "File Property", + label: "Look Up", createdTime: "Created", modifiedTime: "Last Edited", extension: "Extension", @@ -10217,7 +10214,7 @@ var T4 = class { blinkPlaceholder: "Quickly Search a File, Folder, Tag... Press Tab to Edit", searchPlaceholder: "Type to search...", contextItemSelectPlaceholder: "Find Item", - linkItemSelectPlaceholder: "Find Note", + linkItemSelectPlaceholder: "Find or Create Note", optionItemSelectPlaceholder: "Select Option", viewItemSelectPlaceholder: "Select View", tagItemSelectPlaceholder: "Find Tag", @@ -10673,6 +10670,265 @@ var import_obsidian27 = require("obsidian"); // src/utils/contexts/contexts.ts var import_obsidian = require("obsidian"); + +// 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", "tag", "tag-multi", "fileprop"], + fn: stringCompare, + label: i18n_default.filterTypes.contains, + valueType: "text" + }, + notInclude: { + type: ["text", "file", "link", "link-multi", "tag", "tag-multi", "fileprop"], + fn: (v3, f4) => !stringCompare(v3, f4), + label: i18n_default.filterTypes.notContains, + valueType: "text" + }, + is: { + type: ["text", "file", "link", "context", "tag"], + fn: stringEqual, + label: i18n_default.filterTypes.is, + valueType: "text" + }, + isNot: { + type: ["text", "file", "link", "context", "tag"], + 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" + } +}; +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); + } + 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(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 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 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]); + } + return 0; +}; + +// 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 validatePredicate = (prevPredicate) => { + if (!prevPredicate) { + return defaultPredicate; + } + return { + ...defaultPredicate, + filters: Array.isArray(prevPredicate.filters) ? cleanPredicateType(prevPredicate.filters, filterFnTypes) : [], + sort: Array.isArray(prevPredicate.sort) ? cleanPredicateType(prevPredicate.sort, sortFnTypes) : [], + groupBy: Array.isArray(prevPredicate.groupBy) ? prevPredicate.groupBy : [], + colsOrder: Array.isArray(prevPredicate.colsOrder) ? prevPredicate.colsOrder : [], + colsHidden: Array.isArray(prevPredicate.colsHidden) ? prevPredicate.colsHidden : [], + colsSize: prevPredicate.colsSize + }; +}; +var defaultPredicate = { + filters: [], + sort: [], + groupBy: [], + colsOrder: [], + colsHidden: [], + colsSize: {} +}; +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/contexts.ts var tagFromString = (tag) => { if (!tag) return null; @@ -10709,6 +10965,42 @@ var tagContextFromTag = (plugin, tag) => { var folderContextFromFolder = (plugin, folder) => { return (folder == "/" ? "" : folder + "/") + plugin.settings.folderContextFile + ".mdb"; }; +var linkContextRow = (row, fields, tagContexts) => { + 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; + } + if (col.type == "file" || col.type == "link") { + return { + ...p3, + [c4.name]: appendFilesMetaData(prop, row[col.name]) + }; + } + if (col.type.includes("context")) { + const context = col.value; + if (tagContexts[context]) { + return { + ...p3, + [c4.name]: linkContextProp(prop, row[col.name], tagContexts[context]) + }; + } + } + 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_state4 = require("@codemirror/state"); @@ -15162,259 +15454,6 @@ function isAfter(a5, b4) { // src/components/ContextView/CardsView/CardsView.tsx var import_classnames3 = __toESM(require_classnames()); -// 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"], - fn: stringCompare, - label: i18n_default.filterTypes.contains, - valueType: "text" - }, - notInclude: { - type: ["text", "file", "link", "link-multi"], - fn: (v3, f4) => !stringCompare(v3, f4), - label: i18n_default.filterTypes.notContains, - valueType: "text" - }, - is: { - type: ["text", "file", "link", "context"], - fn: stringEqual, - label: i18n_default.filterTypes.is, - valueType: "text" - }, - isNot: { - type: ["text", "file", "link", "context"], - 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" - } -}; -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); - } - 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(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 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 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]); - } - return 0; -}; - -// 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 validatePredicate = (prevPredicate) => { - if (!prevPredicate) { - return defaultPredicate; - } - return { - ...defaultPredicate, - filters: Array.isArray(prevPredicate.filters) ? cleanPredicateType(prevPredicate.filters, filterFnTypes) : [], - sort: Array.isArray(prevPredicate.sort) ? cleanPredicateType(prevPredicate.sort, sortFnTypes) : [], - groupBy: Array.isArray(prevPredicate.groupBy) ? prevPredicate.groupBy : [], - colsOrder: Array.isArray(prevPredicate.colsOrder) ? prevPredicate.colsOrder : [], - colsHidden: Array.isArray(prevPredicate.colsHidden) ? prevPredicate.colsHidden : [], - colsSize: prevPredicate.colsSize - }; -}; -var defaultPredicate = { - filters: [], - sort: [], - groupBy: [], - colsOrder: [], - colsHidden: [], - colsSize: {} -}; -var splitString = (str) => { - var _a2; - return (_a2 = str == null ? void 0 : str.match(/(\\.|[^,])+/g)) != null ? _a2 : []; -}; - // src/utils/ui/selection.ts var selectNextIndex = (currIndex, array) => { if (!currIndex && array.length > 0) @@ -15498,21 +15537,15 @@ var fieldTypes = [ }, { type: "link", - label: i18n_default.properties.link.label, - multi: true, - multiType: "link-multi" + label: i18n_default.properties.link.label }, { type: "context", - label: i18n_default.properties.context.label, - multi: true, - multiType: "context-multi" + label: i18n_default.properties.context.label }, { type: "tag", - label: i18n_default.properties.tag.label, - multi: true, - multiType: "tag-multi" + label: i18n_default.properties.tag.label }, { type: "image", @@ -15681,7890 +15714,7901 @@ var defaultTagTables = { ) }; -// src/utils/contexts/fm.ts -var import_lodash = __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); +} -// src/utils/contexts/dv.ts -var import_obsidian2 = require("obsidian"); -var LocationWrapper = { - "fullLine": { start: "", end: "" }, - "brackets": { start: "[", end: "]" }, - "parenthesis": { start: "(", end: ")" } -}; -var fieldComponents = ["inQuote", "inList", "startStyle", "attribute", "endStyle", "beforeSeparatorSpacer", "afterSeparatorSpacer", "values"]; -var genericFieldRegex = "(?>(\\s+)?)?(?- )?(?[_\\*~`]*)(?[0-9\\w\\p{Letter}\\p{Emoji_Presentation}][-0-9\\w\\p{Letter}\\p{Emoji_Presentation}\\s]*)(?[_\\*~`]*)(?\\s*)"; -var inlineFieldRegex = (attribute) => `(?>(\\s+)?)?(?- )?(?[_\\*~\`]*)(?${attribute})(?[_\\*~\`]*)(?\\s*)::(?\\s*)`; -var fullLineRegex = new RegExp(`^${genericFieldRegex}::\\s*(?.*)?`, "u"); -var inSentenceRegexBrackets = new RegExp(`\\[${genericFieldRegex}::\\s*(?[^\\]]+)?\\]`, "gu"); -var inSentenceRegexPar = new RegExp(`\\(${genericFieldRegex}::\\s*(?[^\\)]+)?\\)`, "gu"); -var encodeLink = (value) => { - return value ? value.replace(/\[\[/g, "\u{1F54C}\u{1F527}").replace(/\]\]/g, "\u{1F413}\u{1F400}") : value; -}; -var decodeLink = (value) => { - return value ? value.replace(/🕌🔧/gu, "[[").replace(/🐓🐀/gu, "]]") : value; -}; -var matchInlineFields = (regex, line, attribute, input, location = "fullLine") => { - const sR = line.matchAll(regex); - let next = sR.next(); - const newFields = []; - while (!next.done) { - const match2 = next.value; - if (match2.groups && Object.keys(match2.groups).every((j4) => fieldComponents.includes(j4))) { - const { inList, inQuote, startStyle, endStyle, beforeSeparatorSpacer, afterSeparatorSpacer, values } = match2.groups; - const inputArray = input ? input.replace(/(\,\s+)/g, ",").split(",") : [""]; - const newValue = inputArray.length == 1 ? inputArray[0] : `${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(); +// 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"); } - return newFields; -}; -async function replaceValues(plugin, fileOrFilePath, attribute, input, previousItemsCount = 0) { - var _a2, _b2; - let file; - if (fileOrFilePath instanceof import_obsidian2.TFile) { - file = fileOrFilePath; +} + +// 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 { - const _file = plugin.app.vault.getAbstractFileByPath(fileOrFilePath); - if (_file instanceof import_obsidian2.TFile && _file.extension == "md") { - file = _file; - } else { - throw Error("path doesn't correspond to a proper file"); - } + _typeof = function _typeof5(obj2) { + return obj2 && typeof Symbol === "function" && obj2.constructor === Symbol && obj2 !== Symbol.prototype ? "symbol" : typeof obj2; + }; } - 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); + 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); } - }); - await plugin.app.vault.modify(file, newContent.filter((line, i4) => !skippedLines.includes(i4)).join("\n")); - const editor = (_b2 = plugin.app.workspace.getActiveViewOfType(import_obsidian2.MarkdownView)) == null ? void 0 : _b2.editor; - if (editor) { - const lineNumber = editor.getCursor().line; - editor.setCursor({ line: editor.getCursor().line, ch: editor.getLine(lineNumber).length }); + return new Date(NaN); } } -// 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, context[f4]); - } else { - frontmatter[f4] = valueForFrontmatter(col.type, context[f4]); - } - } else { - frontmatter[f4] = valueForFrontmatter(col.type, context[f4]); - } - }); - }); +// node_modules/date-fns/esm/addDays/index.js +function addDays(dirtyDate, dirtyAmount) { + requiredArgs(2, arguments); + var date = toDate(dirtyDate); + var amount = toInteger(dirtyAmount); + if (isNaN(amount)) { + return new Date(NaN); } -}; -var frontMatterForFile = (file) => { - let currentCache; - if (file instanceof import_obsidian3.TFile && app.metadataCache.getFileCache(file) !== null) { - currentCache = app.metadataCache.getFileCache(file); + if (!amount) { + return date; } - return currentCache == null ? void 0 : currentCache.frontmatter; -}; -var frontMatterKeys = (fm) => { - return Object.keys(fm != null ? fm : {}).filter((f4) => f4 != "position"); -}; -var yamlTypeToMDBType = (YAMLtype) => { - switch (YAMLtype) { - case "duration": - return "text"; - break; - case "unknown": - return "text"; - break; + 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); } - 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"; - } - return "text"; - } else if (typeof value === "number") { - return "number"; - } else if (typeof value === "boolean") { - return "boolean"; - } else if (!value) { - return "unknown"; - } else if (Array.isArray(value)) { - if (key2 == "tag" || key2 == "tags") { - return "tag-multi"; - } - if (value.length == 1 && Array.isArray(value[0]) && value[0].length == 1 && typeof value[0][0] === "string") { - return "link"; - } - const types = uniq(value.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"; + if (!amount) { + return date; } - 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(onlyUniqueProp("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 parseInt(value); - } else if (type == "boolean") { - return value == "true"; - } else if (type.contains("multi")) { - return splitString(value); + var dayOfMonth = date.getDate(); + var endOfDesiredMonth = new Date(date.getTime()); + endOfDesiredMonth.setMonth(date.getMonth() + amount + 1, 0); + var daysInMonth = endOfDesiredMonth.getDate(); + if (dayOfMonth >= daysInMonth) { + return endOfDesiredMonth; + } else { + date.setFullYear(endOfDesiredMonth.getFullYear(), endOfDesiredMonth.getMonth(), dayOfMonth); + return date; } - return value; -}; -var saveFrontmatterValue = (plugin, path, key2, value, type, forceSave) => { - const afile = getAbstractFileAtPath(app, path); - if (afile) { - if (app.fileManager.processFrontMatter) { - app.fileManager.processFrontMatter(afile, (frontmatter) => { - if (plugin.dataViewAPI()) { - if (plugin.dataViewAPI().page(path)[key2] && !frontmatter[key2]) { - replaceValues(plugin, path, key2, value); - } else { - if (key2 in frontmatter || forceSave) { - frontmatter[key2] = valueForFrontmatter(type, value); - } - } - } else { - if (key2 in frontmatter || forceSave) { - frontmatter[key2] = valueForFrontmatter(type, value); - } - } - }); - } +} + +// 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 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 parseFrontMatter = (field, value, dv) => { - const YAMLtype = detectYAMLType(value, field); - switch (YAMLtype) { - case "number": - return value.toString(); - break; - case "boolean": - return value ? "true" : "false"; - break; - case "date": - if (!dv) { - return value; - } else { - return new Date(value.ts).toDateString(); - } - 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": - case "tag-multi": - return value.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; - } - return value.path; - } - break; - case "text": - case "tag": - case "image": - return value; - break; + var date = toDate(dirtyDate); + var day = date.getDay(); + var diff = (day < weekStartsOn ? 7 : 0) + day - weekStartsOn; + date.setDate(date.getDate() - diff); + date.setHours(0, 0, 0, 0); + return date; +} + +// node_modules/date-fns/esm/startOfISOWeek/index.js +function startOfISOWeek(dirtyDate) { + requiredArgs(1, arguments); + return startOfWeek(dirtyDate, { + weekStartsOn: 1 + }); +} + +// node_modules/date-fns/esm/getISOWeekYear/index.js +function getISOWeekYear(dirtyDate) { + requiredArgs(1, arguments); + var date = toDate(dirtyDate); + var year = date.getFullYear(); + var fourthOfJanuaryOfNextYear = new Date(0); + fourthOfJanuaryOfNextYear.setFullYear(year + 1, 0, 4); + fourthOfJanuaryOfNextYear.setHours(0, 0, 0, 0); + var startOfNextYear = startOfISOWeek(fourthOfJanuaryOfNextYear); + var fourthOfJanuaryOfThisYear = new Date(0); + fourthOfJanuaryOfThisYear.setFullYear(year, 0, 4); + fourthOfJanuaryOfThisYear.setHours(0, 0, 0, 0); + var startOfThisYear = startOfISOWeek(fourthOfJanuaryOfThisYear); + if (date.getTime() >= startOfNextYear.getTime()) { + return year + 1; + } else if (date.getTime() >= startOfThisYear.getTime()) { + return year; + } else { + return year - 1; } - return ""; -}; +} -// src/utils/array.ts -var insert = (arr, index, newItem) => [ - ...arr.slice(0, index), - newItem, - ...arr.slice(index) -]; +// 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; +} -// src/utils/sanitize.ts -var sanitizeTableName = (name) => { - return name == null ? void 0 : name.replace(/[^a-z0-9+]+/gi, ""); -}; -var sanitizeColumnName = (name) => { - return name == null ? void 0 : name.replace(/"/g, ``); -}; -var sanitizeSQLStatement = (name) => { - return name == null ? void 0 : name.replace(/'/g, `''`); -}; +// 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(); +} -// src/dispatch/mdb.ts -var import_obsidian4 = require("obsidian"); -var dispatchDatabaseFileChanged = (dbPath, tag) => { - let evt = new CustomEvent(eventTypes.mdbChange, { detail: { dbPath, tag } }); - window.dispatchEvent(evt); -}; -var processFolderDB = async (plugin, folderPath, processor, fallback) => { - let tags = []; - const dbPath = folderContextFromFolder(plugin, folderPath); - const dbFileExists = getAbstractFileAtPath(app, dbPath); - if (dbFileExists) { - const folderDB = await getMDBTable(plugin, "files", dbPath, false); - if (folderDB) { - tags.push(...folderDB.schema.def.split("&")); - const newDB = await processor(folderDB, dbPath); - const promises = tags.map((tag) => { - const tagdbPath = tagContextFromTag(plugin, tag); - const tagFileExists = getAbstractFileAtPath(app, tagdbPath); - if (tagFileExists) { - return consolidateRowsToTag( - plugin, - tagdbPath, - "files", - dbPath, - newDB.rows - ).then((f4) => { - }); - } - }); - return Promise.all(promises); - } else if (fallback) { - await fallback(); - } - } else if (fallback) { - await fallback(); +// node_modules/date-fns/esm/startOfDay/index.js +function startOfDay(dirtyDate) { + requiredArgs(1, arguments); + var date = toDate(dirtyDate); + date.setHours(0, 0, 0, 0); + return date; +} + +// node_modules/date-fns/esm/differenceInCalendarDays/index.js +var MILLISECONDS_IN_DAY = 864e5; +function differenceInCalendarDays(dirtyDateLeft, dirtyDateRight) { + requiredArgs(2, arguments); + var startOfDayLeft = startOfDay(dirtyDateLeft); + var startOfDayRight = startOfDay(dirtyDateRight); + var timestampLeft = startOfDayLeft.getTime() - getTimezoneOffsetInMilliseconds(startOfDayLeft); + var timestampRight = startOfDayRight.getTime() - getTimezoneOffsetInMilliseconds(startOfDayRight); + return Math.round((timestampLeft - timestampRight) / MILLISECONDS_IN_DAY); +} + +// node_modules/date-fns/esm/addWeeks/index.js +function addWeeks(dirtyDate, dirtyAmount) { + requiredArgs(2, arguments); + var amount = toInteger(dirtyAmount); + var days = amount * 7; + return addDays(dirtyDate, days); +} + +// node_modules/date-fns/esm/addYears/index.js +function addYears(dirtyDate, dirtyAmount) { + requiredArgs(2, arguments); + var amount = toInteger(dirtyAmount); + return addMonths(dirtyDate, amount * 12); +} + +// node_modules/date-fns/esm/max/index.js +function _typeof2(obj) { + "@babel/helpers - typeof"; + if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { + _typeof2 = function _typeof5(obj2) { + return typeof obj2; + }; + } else { + _typeof2 = function _typeof5(obj2) { + return obj2 && typeof Symbol === "function" && obj2.constructor === Symbol && obj2 !== Symbol.prototype ? "symbol" : typeof obj2; + }; } -}; -var saveDB = async (plugin, dbPath, newTable) => { - return saveMDBToPath(plugin, dbPath, 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 - ) + 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; + } + }); + 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 { ...folder, rows: [...folder.rows, row] }; -}; -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"); + return _typeof3(obj); +} +function min(dirtyDatesArray) { + requiredArgs(1, arguments); + var datesArray; + if (dirtyDatesArray && typeof dirtyDatesArray.forEach === "function") { + datesArray = dirtyDatesArray; + } else if (_typeof3(dirtyDatesArray) === "object" && dirtyDatesArray !== null) { + datesArray = Array.prototype.slice.call(dirtyDatesArray); + } else { + return new Date(NaN); + } + var result; + datesArray.forEach(function(dirtyDate) { + var currentDate = toDate(dirtyDate); + if (result === void 0 || result > currentDate || isNaN(currentDate.getDate())) { + result = currentDate; } - ); - return { ...folder, rows: [...folder.rows, ...newRows] }; -}; -var saveContextToFrontmatter = (file, cols, context, plugin) => { - const afile = getAbstractFileAtPath(app, file); - if (afile && afile instanceof import_obsidian4.TFile) - saveContextToFile(afile, cols, context, plugin); -}; -var removeSourceFromTag = async (plugin, tag, source) => { - const dbPath = tagContextFromTag(plugin, tag); - const tagFileExists = getAbstractFileAtPath(app, dbPath); - if (tagFileExists) { - const tagDB = await getMDBTable(plugin, "files", dbPath, true); - 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, dbPath, removeRows(tagDB, source)); + }); + 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 contextShouldExist = async (plugin, tag) => { - const dbPath = tagContextFromTag(plugin, tag); - const tagFileExists = getAbstractFileAtPath(app, dbPath); - if (!tagFileExists) - return false; - return getMDBTable(plugin, "files", dbPath, true).then((f4) => (f4 == null ? void 0 : f4.rows.length) > 0); -}; -var initiateContextIfNotExists = async (plugin, tag) => { - const dbPath = tagContextFromTag(plugin, tag); - const tagFileExists = getAbstractFileAtPath(app, dbPath); - if (tagFileExists) +} + +// 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; + }; + } + 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 createDefaultDB(plugin, dbPath, true); -}; -var insertContextItems = async (plugin, newPaths, t4) => { - const saveNewContextRows = async (tag, path) => { - const newRow = newPaths.map((newPath) => ({ File: newPath })); - await saveDB(plugin, path, insertRows(tag, newRow)); - }; - const dbPath = tagContextFromTag(plugin, t4); - const tagFileExists = getAbstractFileAtPath(app, dbPath); - if (!tagFileExists) { - await createDefaultDB(plugin, dbPath, true); } - await getMDBTable(plugin, "files", dbPath, true).then( - (tagDB) => saveNewContextRows(tagDB, dbPath).then((f4) => { - }) - ); + 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); + } }; -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) }; - } - 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") - ); - 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 dbPath = folderContextFromFolder(plugin, folderPath); - const dbFileExists = getAbstractFileAtPath(app, dbPath); - if (dbFileExists) { - const folderDB = await getMDBTable(plugin, "files", dbPath, false); - 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 - ) - }; - await saveDB(plugin, dbPath, newDB); - const promises = tags.map((tag) => { - const tagdbPath = tagContextFromTag(plugin, tag); - const tagFileExists = getAbstractFileAtPath(app, tagdbPath); - if (tagFileExists) { - return getMDBTable(plugin, "files", tagdbPath, false).then( - (tagDB) => { - const newDB2 = { - ...tagDB, - rows: tagDB.rows.map( - (f4) => f4.File == file.path && f4._source == dbPath ? { - ...f4, - ...fileToFM( - file, - tagDB.cols.map((f5) => f5.name), - plugin - ) - } : f4 - ) - }; - return saveDB(plugin, tagdbPath, newDB2); - } - ); - } - }); - await Promise.all(promises); +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); + } + dateLeft.setMonth(dateLeft.getMonth() - sign * difference); + var isLastMonthNotFull = compareAsc(dateLeft, dateRight) === -sign; + if (isLastDayOfMonth(toDate(dirtyDateLeft)) && difference === 1 && compareAsc(dirtyDateLeft, dateRight) === 1) { + isLastMonthNotFull = false; } + result = sign * (difference - Number(isLastMonthNotFull)); } -}; -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 onFileChanged = async (plugin, oldPath, newPath) => { - const oldFolderPath = getFolderPathFromString(oldPath); - const newFolderPath = getFolderPathFromString(newPath); - if (oldFolderPath == newFolderPath) { - await processFolderDB(plugin, oldFolderPath, async (folder, path) => { - const amendedFolderDB = renameRow(folder, oldPath, newPath); - await saveDB(plugin, path, amendedFolderDB); - return amendedFolderDB; - }); - } else { - await processFolderDB( - plugin, - oldFolderPath, - async (folder, path) => { - const amendedFolderDB = removeRow(folder, oldPath); - await saveDB(plugin, path, amendedFolderDB); - const dbPath = folderContextFromFolder(plugin, newFolderPath); - const fromDBRow = folder.rows.find((f4) => f4.File == oldPath); - const toDBFileExists = getAbstractFileAtPath(app, dbPath); - if (toDBFileExists) { - const toFolderDB = await getMDBTable(plugin, "files", dbPath, false); - 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, - dbPath, - insertRow(toFolderDB, newRowByDBRow(newRow), newFolderPath) - ); - saveContextToFrontmatter( - newPath, - folder.cols, - fmDBCols.reduce((p3, c4) => ({ ...p3, [c4]: fromDBRow[c4] }), {}), - plugin - ); - } - } else { - saveContextToFrontmatter( - newPath, - folder.cols, - Object.keys(fromDBRow).reduce( - (p3, c4) => ({ ...p3, [c4]: fromDBRow[c4] }), - {} - ), - plugin - ); - } - return amendedFolderDB; - }, - async () => { - const dbPath = folderContextFromFolder(plugin, newFolderPath); - const toDBFileExists = getAbstractFileAtPath(app, dbPath); - if (toDBFileExists) { - const toFolderDB = await getMDBTable(plugin, "files", dbPath, false); - } - } - ); + return result === 0 ? 0 : result; +} + +// node_modules/date-fns/esm/differenceInSeconds/index.js +function differenceInSeconds(dateLeft, dateRight, options) { + requiredArgs(2, arguments); + var diff = differenceInMilliseconds(dateLeft, dateRight) / 1e3; + return getRoundingMethod(options === null || options === void 0 ? void 0 : options.roundingMethod)(diff); +} + +// node_modules/date-fns/esm/startOfMonth/index.js +function startOfMonth(dirtyDate) { + requiredArgs(1, arguments); + var date = toDate(dirtyDate); + date.setDate(1); + date.setHours(0, 0, 0, 0); + return date; +} + +// node_modules/date-fns/esm/startOfYear/index.js +function startOfYear(dirtyDate) { + requiredArgs(1, arguments); + var cleanDate = toDate(dirtyDate); + var date = new Date(0); + date.setFullYear(cleanDate.getFullYear(), 0, 1); + date.setHours(0, 0, 0, 0); + return date; +} + +// node_modules/date-fns/esm/endOfWeek/index.js +function endOfWeek(dirtyDate, options) { + var _ref, _ref2, _ref3, _options$weekStartsOn, _options$locale, _options$locale$optio, _defaultOptions$local, _defaultOptions$local2; + requiredArgs(1, arguments); + var defaultOptions3 = getDefaultOptions(); + var weekStartsOn = toInteger((_ref = (_ref2 = (_ref3 = (_options$weekStartsOn = options === null || options === void 0 ? void 0 : options.weekStartsOn) !== null && _options$weekStartsOn !== void 0 ? _options$weekStartsOn : options === null || options === void 0 ? void 0 : (_options$locale = options.locale) === null || _options$locale === void 0 ? void 0 : (_options$locale$optio = _options$locale.options) === null || _options$locale$optio === void 0 ? void 0 : _options$locale$optio.weekStartsOn) !== null && _ref3 !== void 0 ? _ref3 : defaultOptions3.weekStartsOn) !== null && _ref2 !== void 0 ? _ref2 : (_defaultOptions$local = defaultOptions3.locale) === null || _defaultOptions$local === void 0 ? void 0 : (_defaultOptions$local2 = _defaultOptions$local.options) === null || _defaultOptions$local2 === void 0 ? void 0 : _defaultOptions$local2.weekStartsOn) !== null && _ref !== void 0 ? _ref : 0); + if (!(weekStartsOn >= 0 && weekStartsOn <= 6)) { + throw new RangeError("weekStartsOn must be between 0 and 6 inclusively"); } -}; -var onFileDeleted = async (plugin, oldPath) => { - const oldFolderPath = getFolderPathFromString(oldPath); - await processFolderDB(plugin, oldFolderPath, async (folder, path) => { - const amendedFolderDB = removeRow(folder, oldPath); - await saveDB(plugin, path, amendedFolderDB); - return amendedFolderDB; - }); -}; -var onFolderChanged = async (plugin, oldPath, newPath) => { - await processFolderDB(plugin, newPath, async (folder, path) => { - const newDB = { - ...folder, - rows: folder.rows.map( - (f4) => getFolderPathFromString(f4["File"]) == oldPath ? { ...f4, File: f4["File"].replace(oldPath, newPath) } : f4 - ) - }; - await saveDB(plugin, path, newDB); - return newDB; + 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 }); -}; -var onFolderDeleted = async (oldPath) => { -}; +} -// src/utils/db/db.ts -var import_obsidian5 = require("obsidian"); -var getDBFile = async (path) => { - if (!await app.vault.adapter.exists((0, import_obsidian5.normalizePath)(path))) { - return null; - } - const file = await app.vault.adapter.readBinary( - (0, import_obsidian5.normalizePath)(path) - ); - return file; -}; -var getDB = async (sqlJS, path) => { - const buf = await getDBFile(path); - 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 saveDBFile = async (path, binary) => { - const file = app.vault.adapter.writeBinary( - (0, import_obsidian5.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; +// 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; } - 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); +} + +// 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 execQuery = (db, sqlstr) => { - try { - db.exec(sqlstr); - } catch (e4) { - console.log(e4); + 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"); } -}; -var deleteFromDB = (db, table, condition) => { - const sqlstr = `DELETE FROM "${table}" WHERE ${condition};`; - try { - db.exec(sqlstr); - } catch (e4) { - console.log(e4); + 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 dropTable = (db, table) => { - const sqlstr = `DROP TABLE IF EXISTS "${table}";`; - try { - db.exec(sqlstr); - } catch (e4) { - console.log(e4); +} + +// 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; } -}; -var insertIntoDB = (db, tables) => { - const sqlstr = Object.keys(tables).map((t4) => { - const tableFields = tables[t4].cols; - const rowsQuery = tables[t4].rows.reduce((prev, curr) => { - return `${prev} 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; -}; + return sign + output; +} -// 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, tag) => { - if (tag) { - return [ - ...fields, - ...defaultTagFields.rows.filter( - (f4) => !fields.some((g4) => g4.name == f4.name && g4.schemaId == f4.schemaId) - ) - ]; - } - return [ - ...fields, - ...defaultFolderFields.rows.filter( - (f4) => !fields.some((g4) => g4.name == f4.name && g4.schemaId == f4.schemaId) - ) - ]; -}; -var getMDBTable = async (plugin, table, path, tag) => { - const sqlJS = await plugin.sqlJS(); - const buf = await getDBFile(path); - if (!buf) { - return null; - } - const db = new sqlJS.Database(new Uint8Array(buf)); - await sanitizeTableSchema(plugin, db, path, tag); - 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, tag) : fields - ); -}; -var deleteMDBTable = async (plugin, path, mdb) => { - const sqlJS = await plugin.sqlJS(); - const buf = await getDBFile(path); - if (!buf) { - return false; - } - const db = new sqlJS.Database(new Uint8Array(buf)); - deleteFromDB(db, "m_schema", `id = '${sanitizeSQLStatement(mdb)}'`); - deleteFromDB(db, "m_schema", `def = '${sanitizeSQLStatement(mdb)}'`); - deleteFromDB(db, "m_fields", `schemaId = '${sanitizeSQLStatement(mdb)}'`); - dropTable(db, mdb); - await saveDBFile(path, db.export().buffer); - db.close(); - return true; -}; -var getMDBTableSchemas = async (plugin, path, tag) => { - const sqlJS = await plugin.sqlJS(); - const buf = await getDBFile(path); - if (!buf) { - return null; - } - const db = new sqlJS.Database(new Uint8Array(buf)); - await sanitizeTableSchema(plugin, db, path, tag); - 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, path, schema) => { - const sqlJS = await plugin.sqlJS(); - const buf = await getDBFile(path); - 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, path, mdb) => { - var _a2, _b2; - const sqlJS = await plugin.sqlJS(); - const buf = await getDBFile(path); - if (!buf) { - return null; - } - const db = new sqlJS.Database(new Uint8Array(buf)); - const fieldsTables = dbResultsToDBTables( - db.exec(`SELECT * FROM m_fields WHERE schemaId != '${mdb.schema.id}'`) - ); - const tables = { - m_fields: { - uniques: fieldSchema.uniques, - cols: fieldSchema.cols, - rows: [...(_b2 = (_a2 = fieldsTables[0]) == null ? void 0 : _a2.rows) != null ? _b2 : [], ...mdb.cols] - }, - [mdb.schema.id]: { - uniques: mdb.cols.filter((c4) => c4.unique == "true").map((c4) => c4.name), - cols: mdb.cols.map((c4) => c4.name), - rows: mdb.rows - } - }; - db.close(); - return saveDBToPath(plugin, path, 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, path, tag) => { - const sqlJS = await plugin.sqlJS(); - const table = tag ? defaultTagTables : defaultFolderTables; - return saveDBToPath(plugin, path, table); -}; -var sanitizeTableSchema = async (plugin, db, path, tag) => { - 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, path, tag); - } -}; -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, path, table, files, tag) => { - const sqlJS = await plugin.sqlJS(); - const isTag = tag ? true : false; - let db; - if (getAbstractFileAtPath(app, path)) { - const buf = await getDBFile(path); - db = new sqlJS.Database(new Uint8Array(buf)); - } else { - db = new sqlJS.Database(); - await createDefaultDB(plugin, path, false); - } - const mdbTable = await getMDBTable(plugin, table, path, isTag); - const missingFiles = files.filter((f4) => !mdbTable.rows.some((g4) => g4.File == f4 && g4._source != "")).map((f4) => ({ File: f4 })); - const mergeDuplicates = (rows, tag2) => { - 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); - } - return [...p3, c4]; - }, []); - }; - let linkedFolderContexts = [""]; - if (tag) { - const contexts = uniq( - mdbTable.rows.map((f4) => f4._source).filter((f4) => f4 != "" && f4 != "tag") - ); - const promises = contexts.map( - (context) => getMDBTable(plugin, "files", context, false).then((f4) => [f4, context]) - ); - 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 == tag); - }).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) - ), - isTag - ), - ...missingFiles - ].map((f4) => rowWithID(f4, isTag)) - ]; - const newMDBTable = { - ...mdbTable, - cols: [ - ...(isTag ? defaultTagFields : defaultFolderFields).rows, - ...mdbTable.cols - ].filter(onlyUniqueProp("name")), - rows: newRows - }; - await saveMDBToPath(plugin, path, newMDBTable); - db.close(); - return newMDBTable; -}; -var consolidateRowsToTag = async (plugin, path, table, source, rows) => { - const sqlJS = await plugin.sqlJS(); - if (getAbstractFileAtPath(app, path)) { - } else { - await createDefaultDB(plugin, path, true); - } - const mdbTable = await getMDBTable(plugin, table, path, true); - const prevRows = mdbTable.rows.map((f4) => { - if (f4._source != source) { - return f4; +// 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."; } - 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 - }; - await saveMDBToPath(plugin, path, newMDBTable); - return newMDBTable; -}; - -// src/components/ContextView/MDBContext.tsx -var MDBContext = B({ - tables: [], - cols: [], - sortedColumns: [], - data: [], - filteredData: [], - tableData: null, - contextTable: {}, - selectedRows: [], - selectRows: () => { }, - setContextTable: () => { + h: function h3(date, token) { + return addLeadingZeros(date.getUTCHours() % 12 || 12, token.length); }, - predicate: defaultPredicate, - savePredicate: () => { + H: function H3(date, token) { + return addLeadingZeros(date.getUTCHours(), token.length); }, - saveDB: () => null, - saveContextDB: () => null, - schema: null, - dbSchema: null, - setSchema: () => { + m: function m3(date, token) { + return addLeadingZeros(date.getUTCMinutes(), token.length); }, - setDBSchema: () => { + s: function s3(date, token) { + return addLeadingZeros(date.getUTCSeconds(), token.length); }, - dbPath: null, - isFolderContext: false, - folderPath: "", - hideColumn: () => { + 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); + } +}; +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" + }); + } }, - saveColumn: () => false, - newColumn: () => false, - sortColumn: () => { + y: function y4(date, token, localize2) { + if (token === "yo") { + var signedYear = date.getUTCFullYear(); + var year = signedYear > 0 ? signedYear : 1 - signedYear; + return localize2.ordinalNumber(year, { + unit: "year" + }); + } + return lightFormatters_default.y(date, token); }, - delColumn: () => { + Y: function Y2(date, token, localize2, options) { + var signedWeekYear = getUTCWeekYear(date, options); + var weekYear = signedWeekYear > 0 ? signedWeekYear : 1 - signedWeekYear; + if (token === "YY") { + var twoDigitYear = weekYear % 100; + return addLeadingZeros(twoDigitYear, 2); + } + if (token === "Yo") { + return localize2.ordinalNumber(weekYear, { + unit: "year" + }); + } + return addLeadingZeros(weekYear, token.length); }, - saveSchema: () => null, - deleteSchema: () => null, - tagContexts: [], - dbFileExists: false, - searchString: "", - setSearchString: () => { + R: function R2(date, token) { + var isoWeekYear = getUTCISOWeekYear(date); + return addLeadingZeros(isoWeekYear, token.length); }, - loadContextFields: () => { + u: function u3(date, token) { + var year = date.getUTCFullYear(); + return addLeadingZeros(year, token.length); }, - updateValue: () => { + 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" + }); + } }, - updateFieldValue: () => { - } -}); -var MDBProvider = (props2) => { - var _a2, _b2, _c2; - const { dbPath } = props2; - const [dbFileExists, setDBFileExists] = p2(false); - const [schema, setSchema] = p2(null); - const [searchString, setSearchString] = p2(null); - const [schemaTable, setSchemaTable] = p2(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 defaultSchema = props2.tag ? defaultTagSchema : defaultFolderSchema; - const folderPath = (_c2 = (_b2 = props2.folder) != null ? _b2 : props2.tag) != null ? _c2 : ""; - const isFolderContext = props2.folder ? true : false; - const tagContexts = F( - () => { - var _a3, _b3, _c3; - return ((_a3 = dbSchema == null ? void 0 : dbSchema.def) == null ? void 0 : _a3.length) > 0 ? (_c3 = (_b3 = dbSchema == null ? void 0 : dbSchema.def) == null ? void 0 : _b3.split("&")) != null ? _c3 : [] : []; - }, - [dbSchema] - ); - const cols = F( - () => { - var _a3; - return [ - ...(_a3 = tableData == null ? void 0 : tableData.cols.map((f4) => ({ ...f4, table: "" }))) != null ? _a3 : [], - ...tagContexts.reduce( - (p3, c4) => { - var _a4, _b3; - return [ - ...p3, - ...(_b3 = (_a4 = contextTable[c4]) == null ? void 0 : _a4.cols.filter((f4) => f4.name != "File" && f4.type != "fileprop").map((f4) => ({ ...f4, table: c4 }))) != null ? _b3 : [] - ]; - }, - [] - ) - ]; - }, - [tableData, schema, contextTable, tagContexts] - ); - const data = F( - () => { - var _a3; - return (_a3 = tableData == null ? void 0 : tableData.rows.map((r3, index) => ({ - _index: index.toString(), - ...(dbSchema == null ? void 0 : dbSchema.primary) ? { ...appendFileMetadataForRow(r3, tableData.cols) } : r3, - ...tagContexts.reduce((p3, c4) => { - var _a4, _b3, _c3, _d2; - const contextRowIndexByFile = (_b3 = (_a4 = contextTable[c4]) == null ? void 0 : _a4.rows.findIndex((f4) => f4.File == r3.File)) != null ? _b3 : -1; - const contextRowsByFile = (_d2 = (_c3 = contextTable[c4]) == null ? void 0 : _c3.rows[contextRowIndexByFile]) != null ? _d2 : {}; - const contextRowsWithKeysAppended = Object.keys( - contextRowsByFile - ).reduce((pa, ca) => ({ ...pa, [ca + c4]: contextRowsByFile[ca] }), { - ["_index" + c4]: contextRowIndexByFile.toString() - }); - return { ...p3, ...contextRowsWithKeysAppended }; - }, {}) - }))) != null ? _a3 : []; - }, - [tableData, schema, contextTable] - ); - const sortedColumns = F( - () => { - 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( - () => data.filter((f4) => { - return predicate.filters.reduce((p3, c4) => { - return p3 ? filterReturnForCol( - cols.find((col) => col.name + col.table == c4.field), - c4, - f4 - ) : p3; - }, true); - }).filter( - (f4) => (searchString == null ? void 0 : searchString.length) > 0 ? matchAny(searchString).test( - Object.keys(f4).filter((g4) => g4.charAt(0) != "_").map((g4) => f4[g4]).join("|") - ) : true - ).sort((a5, b4) => { - return predicate.sort.reduce((p3, c4) => { - return p3 == 0 ? sortReturnForCol( - cols.find((col) => col.name + col.table == c4.field), - c4, - a5, - b4 - ) : p3; - }, 0); - }), - [predicate, data, cols, searchString] - ); - const deleteSchema = async (table) => { - if (table.primary) - return; - const deleteResult = await deleteMDBTable(props2.plugin, dbPath, table.id); - if (deleteResult) { - const newSchemaTable = { - ...schemaTable, - rows: schemaTable.rows.filter( - (f4) => f4.id != table.id && f4.def != table.id - ) - }; - setSchemaTable(newSchemaTable); - if (dbSchema.id == table.id) { - setDBSchema( - newSchemaTable.rows.find((g4) => g4.type == "db") - ); - } + q: function q4(date, token, localize2) { + var quarter = Math.ceil((date.getUTCMonth() + 1) / 3); + switch (token) { + case "q": + return String(quarter); + case "qq": + return addLeadingZeros(quarter, 2); + case "qo": + return localize2.ordinalNumber(quarter, { + unit: "quarter" + }); + case "qqq": + return localize2.quarter(quarter, { + width: "abbreviated", + context: "standalone" + }); + case "qqqqq": + return localize2.quarter(quarter, { + width: "narrow", + context: "standalone" + }); + case "qqqq": + default: + return localize2.quarter(quarter, { + width: "wide", + context: "standalone" + }); } - }; - const saveSchema = async (table) => { - const newSchema = schemaTable.rows.find((f4) => f4.id == table.id) ? true : false; - const newSchemaTable = newSchema ? { - ...schemaTable, - rows: schemaTable.rows.map((f4) => f4.id == table.id ? table : f4) - } : { - ...schemaTable, - rows: [...schemaTable.rows, table] - }; - await saveDBToPath(props2.plugin, dbPath, { m_schema: newSchemaTable }); - if (table.id == (schema == null ? void 0 : schema.id)) { - setSchema(table); + }, + M: function M4(date, token, localize2) { + var month = date.getUTCMonth(); + switch (token) { + case "M": + case "MM": + return lightFormatters_default.M(date, token); + case "Mo": + return localize2.ordinalNumber(month + 1, { + unit: "month" + }); + case "MMM": + return localize2.month(month, { + width: "abbreviated", + context: "formatting" + }); + case "MMMMM": + return localize2.month(month, { + width: "narrow", + context: "formatting" + }); + case "MMMM": + default: + return localize2.month(month, { + width: "wide", + context: "formatting" + }); } - if (table.id == (dbSchema == null ? void 0 : dbSchema.id)) { - setDBSchema(table); - setTableData((f4) => ({ - ...f4, - schema: table - })); + }, + 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" + }); } - setSchemaTable(newSchemaTable); - }; - const updateValue = (column, value, table, index, file) => { - var _a3, _b3; - const col = (_a3 = table == "" ? tableData : contextTable[table]) == null ? void 0 : _a3.cols.find( - (f4) => f4.name == column - ); - if (col) - saveFrontmatterValue(props2.plugin, file != null ? file : (_b3 = tableData.rows[index]) == null ? void 0 : _b3.File, column, value, col.type, props2.plugin.settings.saveAllContextToFrontmatter); - if (table == "") { - saveDB2({ - ...tableData, - rows: tableData.rows.map( - (r3, i4) => i4 == index ? { - ...r3, - [column]: value - } : r3 - ) + }, + w: function w4(date, token, localize2, options) { + var week = getUTCWeek(date, options); + if (token === "wo") { + return localize2.ordinalNumber(week, { + unit: "week" }); - } else if (contextTable[table]) { - saveContextDB( - { - ...contextTable[table], - rows: contextTable[table].rows.map( - (r3, i4) => i4 == index ? { - ...r3, - [column]: value - } : r3 - ) - }, - table - ); } - }; - const sortColumn = (sort) => { - savePredicate({ - ...predicate, - sort: [sort] - }); - }; - const hideColumn = (col, hidden) => { - savePredicate({ - ...predicate, - colsHidden: hidden ? [...predicate.colsHidden.filter((s5) => s5 != col.name + col.table), col.name + col.table] : predicate.colsHidden.filter((s5) => s5 != col.name + col.table) - }); - }; - const updateFieldValue = (column, fieldValue, value, table, index, file) => { - var _a3; - const col = tableData.cols.find((f4) => f4.name == column); - saveFrontmatterValue(props2.plugin, file != null ? file : (_a3 = tableData.rows[index]) == null ? void 0 : _a3.File, column, value, col.type, props2.plugin.settings.saveAllContextToFrontmatter); - if (table == "") { - const newTable = { - ...tableData, - cols: tableData.cols.map( - (m5) => m5.name == column ? { - ...m5, - value: fieldValue - } : m5 - ), - rows: tableData.rows.map( - (r3, i4) => i4 == index ? { - ...r3, - [column]: value - } : r3 - ) - }; - saveDB2(newTable); - } else if (contextTable[table]) { - saveContextDB( - { - ...contextTable[table], - cols: contextTable[table].cols.map( - (m5) => m5.name == column ? { - ...m5, - value: fieldValue - } : m5 - ), - rows: contextTable[table].rows.map( - (r3, i4) => i4 == index ? { - ...r3, - [column]: value - } : r3 - ) - }, - table - ); + return addLeadingZeros(week, token.length); + }, + I: function I3(date, token, localize2) { + var isoWeek = getUTCISOWeek(date); + if (token === "Io") { + return localize2.ordinalNumber(isoWeek, { + unit: "week" + }); } - }; - const syncAllMetadata = (f4) => { - const files = f4.rows.map((f5) => f5.File); - const importYAML = (files2, fmKeys) => { - return files2.map((f5) => getAbstractFileAtPath(app, f5)).filter((f5) => f5).reduce( - (p3, c4) => { - const fm = frontMatterForFile(c4); - if (!fm) - return p3; - return { - uniques: [], - cols: uniq([...p3.cols, ...fmKeys]), - rows: [ - ...p3.rows, - { - File: c4.path, - ...fmKeys.reduce((p4, c5) => { - const value = parseFrontMatter(c5, fm[c5], false); - if ((value == null ? void 0 : value.length) > 0) - return { ...p4, [c5]: value }; - return p4; - }, {}) - } - ] - }; - }, - { uniques: [], cols: [], rows: [] } - ); - }; - const yamlTableData = importYAML( - files, - f4.cols.filter((f5) => !f5.type.contains("file")).map((f5) => f5.name) - ); - saveDB2({ - ...f4, - rows: f4.rows.map((r3) => { - const fmRow = yamlTableData.rows.find((f5) => f5.File == r3.File); - if (fmRow) { - return { - ...r3, - ...fmRow - }; - } - return r3; - }) - }); - }; - 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 - ); - 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: [] - }) - ); - } + return addLeadingZeros(isoWeek, token.length); + }, + d: function d4(date, token, localize2) { + if (token === "do") { + return localize2.ordinalNumber(date.getUTCDate(), { + unit: "date" + }); } - }, [schemaTable]); - const loadTables = async () => { - if (getAbstractFileAtPath(app, props2.dbPath)) { - setDBFileExists(true); - getMDBTableSchemas( - props2.plugin, - props2.dbPath, - props2.tag ? true : false - ).then((f4) => { - setSchemaTable({ - ...defaultSchema, - rows: f4 - }); - if (!props2.schema) - setDBSchema(f4 == null ? void 0 : f4.find((g4) => g4.type == "db")); + return lightFormatters_default.d(date, token); + }, + D: function D2(date, token, localize2) { + var dayOfYear = getUTCDayOfYear(date); + if (token === "Do") { + return localize2.ordinalNumber(dayOfYear, { + unit: "dayOfYear" }); - } else { - if (props2.schema) { - saveDB2(props2.tag ? defaultTagMDBTable : defaultFolderMDBTable).then( - (f4) => { - setSchemaTable(defaultSchema); - } - ); - } else { - setSchemaTable(defaultSchema); - setDBSchema(defaultFileDBSchema); - } } - }; - const refreshTags = async (evt) => { - if (!dbFileExists) { - loadDefaultTableData(); - } else { - if (dbSchema.primary) { - runDef(); - } else { - getMDBData(); - } + 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" + }); } - }; - const refreshSpace = async (evt) => { - if (!dbFileExists) { - loadDefaultTableData(); + }, + 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" + }); } - }; - const getMDBData = () => { - getMDBTable(props2.plugin, dbSchema.id, dbPath, !isFolderContext).then( - (f4) => setTableData(f4) - ); - }; - const refreshSchema = (schema2) => { - }; - const refreshMDB = async (evt) => { - if (!dbFileExists || (dbSchema == null ? void 0 : dbSchema.primary) != "true") { - 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" + }); } - if (evt.detail.dbPath == dbPath) { - if (dbSchema) { - if (schema) - getMDBSchema(props2.plugin, dbPath, 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, dbSchema.id, dbPath, !isFolderContext).then( - (f4) => setTableData(f4) - ); - } + }, + 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" + }); + } + }, + 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 { - const tag = Object.keys(contextTable).find( - (t4) => tagContextFromTag(props2.plugin, t4) == evt.detail.dbPath - ); - if (tag) - loadContextFields(tag); + dayPeriodEnumValue = hours / 12 >= 1 ? "pm" : "am"; } - }; - h2(() => { - window.addEventListener(eventTypes.mdbChange, refreshMDB); - window.addEventListener(eventTypes.spacesChange, refreshSpace); - window.addEventListener(eventTypes.tagsChange, refreshTags); - return () => { - window.removeEventListener(eventTypes.mdbChange, refreshMDB); - window.removeEventListener(eventTypes.spacesChange, refreshSpace); - window.removeEventListener(eventTypes.tagsChange, refreshTags); - }; - }, [contextTable, dbSchema, dbPath, schema]); - h2(() => { - loadTables(); - }, [dbPath]); - const saveDB2 = async (newTable) => { - var _a3; - if (!dbFileExists) { - const defaultFields = isFolderContext ? defaultFolderFields : defaultTagFields; - const defaultTable = isFolderContext ? defaultFolderTables : defaultTagTables; - const dbField = { - ...defaultTable, - m_fields: { - uniques: defaultFields.uniques, - cols: defaultFields.cols, - rows: [...(_a3 = defaultFields.rows) != null ? _a3 : [], ...newTable.cols] - }, - [newTable.schema.id]: { - uniques: newTable.cols.filter((c4) => c4.unique == "true").map((c4) => c4.name), - cols: newTable.cols.map((c4) => c4.name), - rows: newTable.rows - } - }; - await saveDBToPath(props2.plugin, dbPath, dbField).then((f4) => { - setDBFileExists(true); - f4 ? setTableData(newTable) : new import_obsidian6.Notice("DB ERROR"); - }); + 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 { - await saveMDBToPath(props2.plugin, dbPath, newTable).then((f4) => { - setDBFileExists(true); - f4 ? setTableData(newTable) : new import_obsidian6.Notice("DB ERROR"); + 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" }); } - }; - h2(() => { - 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 : { - ...dbSchema, - id: uniqueNameFromString( - dbSchema.id + "View", - schemaTable.rows.map((f4) => f4.id) - ), - type: "table", - def: dbSchema.id - }; - if (_schema) { - setSchema(_schema); - if (dbFileExists) { - if (dbSchema.primary) { - runDef(); - } else { - getMDBData(); - } - } else { - loadDefaultTableData(); - } + return lightFormatters_default.h(date, token); + }, + H: function H4(date, token, localize2) { + if (token === "Ho") { + return localize2.ordinalNumber(date.getUTCHours(), { + unit: "hour" + }); } - }, [dbSchema]); - h2(() => { - if (dbFileExists) - parsePredicate(schema == null ? void 0 : schema.predicate); - }, [schema]); - h2(() => { - 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 } + 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" }); - window.dispatchEvent(evt); - } else { - let evt = new CustomEvent(eventTypes.selectedFileChange, { - detail: { filePath: 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" }); - window.dispatchEvent(evt); } - setSelectedRows(rows); - }; - const loadDefaultTableData = () => { - let files; - if (props2.folder) { - files = folderChildren( - props2.plugin, - getAbstractFileAtPath(props2.plugin.app, props2.folder) - ); - setTableData({ - ...isFolderContext ? defaultFolderMDBTable : defaultTagMDBTable, - rows: files.map( - (f4) => newRowByDBRow({ _source: "folder", File: f4.path }) - ) + return addLeadingZeros(hours, token.length); + }, + m: function m4(date, token, localize2) { + if (token === "mo") { + return localize2.ordinalNumber(date.getUTCMinutes(), { + unit: "minute" }); - } else if (props2.tag) { - files = getAllFilesForTag(props2.tag).map((f4) => getAbstractFileAtPath(app, f4)).filter((f4) => f4); - setTableData({ - ...isFolderContext ? defaultFolderMDBTable : defaultTagMDBTable, - rows: files.map((f4) => newRowByDBRow({ _source: "tag", File: f4.path })) + } + return lightFormatters_default.m(date, token); + }, + s: function s4(date, token, localize2) { + if (token === "so") { + return localize2.ordinalNumber(date.getUTCSeconds(), { + unit: "second" }); } - }; - const getContextTags = async (_tableData) => { - const contextFields = _tableData.cols.filter((f4) => f4.type.contains("context")).map((f4) => f4.value).filter((f4) => !tagContexts.some((g4) => g4 == f4)); - for (let c4 of contextFields) { - loadContextFields(c4); + 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 runDef = async () => { - let files; - if (props2.folder) { - files = folderChildren( - props2.plugin, - getAbstractFileAtPath(props2.plugin.app, props2.folder) - ); - consolidateFilesToTable( - props2.plugin, - dbPath, - dbSchema.id, - files.map((f4) => f4.path) - ).then((f4) => { - for (let c4 of tagContexts) { - loadTagContext(c4, f4.rows); - } - setTableData(f4); - return f4; - }).then((f4) => syncAllMetadata(f4)); - } else if (props2.tag) { - files = getAllFilesForTag(props2.tag).map((f4) => getAbstractFileAtPath(app, f4)).filter((f4) => f4); - consolidateFilesToTable( - props2.plugin, - dbPath, - dbSchema.id, - files.map((f4) => f4.path), - props2.tag - ).then((f4) => { - for (let c4 of tagContexts) { - loadTagContext(c4, f4.rows); - } - setTableData(f4); - return f4; - }).then((f4) => syncAllMetadata(f4)); + switch (token) { + case "X": + return formatTimezoneWithOptionalMinutes(timezoneOffset); + case "XXXX": + case "XX": + return formatTimezone(timezoneOffset); + case "XXXXX": + case "XXX": + default: + return formatTimezone(timezoneOffset, ":"); } - }; - const loadTagContext = async (tag, files) => { - consolidateRowsToTag( - props2.plugin, - tagContextFromTag(props2.plugin, tag), - dbSchema.id, - dbPath, - files - ).then((f4) => { - if (f4) { - const contextFields = f4.cols.filter((g4) => g4.type.contains("context")).map((g4) => g4.value).filter((g4) => !tagContexts.some((h5) => h5 == g4)); - for (let c4 of contextFields) { - loadContextFields(c4); - } - setContextTable((t4) => ({ - ...t4, - [tag]: f4 - })); - } - }); - }; - const loadContextFields = async (tag) => { - getMDBTable( - props2.plugin, - "files", - tagContextFromTag(props2.plugin, tag), - true - ).then((f4) => { - setContextTable((t4) => ({ - ...t4, - [tag]: f4 - })); - }); - }; - const tagExists = (currentCache, findTag) => { - let currentTags = []; - if ((0, import_obsidian6.getAllTags)(currentCache)) { - currentTags = (0, import_obsidian6.getAllTags)(currentCache); + }, + 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, ":"); } - return currentTags.find((tag) => tag.toLowerCase() == findTag.toLowerCase()) ? true : false; - }; - const 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; - }; - const saveContextDB = async (newTable, context) => { - const dbPath2 = tagContextFromTag(props2.plugin, context); - await saveMDBToPath(props2.plugin, dbPath2, newTable).then( - (f4) => f4 && setContextTable((t4) => ({ - ...t4, - [context]: newTable - })) - ); - }; - const savePredicate = (newPredicate) => { - const cleanedPredicate = validatePredicate(newPredicate); - saveSchema({ - ...schema, - predicate: JSON.stringify(cleanedPredicate) - }); - setPredicate(cleanedPredicate); - }; - h2(() => { - setPredicate((p3) => ({ - ...p3, - colsOrder: uniq([ - ...p3.colsOrder, - ...cols.filter((f4) => f4.hidden != "true").map((c4) => c4.name + c4.table) - ]) - })); - }, [cols]); - const parsePredicate = (predicateStr) => { - const newPredicate = safelyParseJSON(predicateStr); - setPredicate(validatePredicate(newPredicate)); - }; - const delColumn = (column) => { - let mdbtable; - const table = column.table; - if (table == "") { - mdbtable = tableData; - } else if (contextTable[table]) { - mdbtable = contextTable[table]; + }, + 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, ":"); } - const newFields = mdbtable.cols.filter( - (f4, i4) => f4.name != column.name - ); - const newTable = { - ...mdbtable, - cols: newFields, - rows: mdbtable.rows.map((r3) => { - const { [column.name]: val, ...rest } = r3; - return rest; - }) - }; - if (table == "") { - saveDB2(newTable); - } else if (contextTable[table]) { - saveContextDB(newTable, table); - } - }; - const newColumn = (col) => { - return saveColumn(col); - }; - const saveColumn = (newColumn2, oldColumn) => { - let mdbtable; - const column = { - ...newColumn2, - name: sanitizeColumnName(newColumn2.name) - }; - const table = column.table; - if (table == "") { - mdbtable = tableData; - } else if (contextTable[table]) { - mdbtable = contextTable[table]; - } - if (column.name == "") { - new import_obsidian6.Notice(i18n_default.notice.noPropertyName); - return false; - } - if (!oldColumn && mdbtable.cols.find( - (f4) => f4.name.toLowerCase() == column.name.toLowerCase() - ) || oldColumn && oldColumn.name != column.name && mdbtable.cols.find( - (f4) => f4.name.toLowerCase() == column.name.toLowerCase() - )) { - new import_obsidian6.Notice(i18n_default.notice.duplicatePropertyName); - return false; + }, + 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, ":"); } - const oldFieldIndex = oldColumn ? mdbtable.cols.findIndex((f4) => f4.name == oldColumn.name) : -1; - const newFields = oldFieldIndex == -1 ? [...mdbtable.cols, column] : mdbtable.cols.map((f4, i4) => i4 == oldFieldIndex ? column : f4); - const newTable = { - ...mdbtable, - cols: newFields, - rows: mdbtable.rows.map( - (f4) => oldColumn ? { - ...f4, - [column.name]: f4[oldColumn.name], - oldColumn: void 0 - } : f4 - ) - }; - if (oldColumn) - savePredicate({ - filters: predicate.filters.map( - (f4) => f4.field == oldColumn.name + oldColumn.table ? { ...f4, field: column.name + column.table } : f4 - ), - sort: predicate.sort.map( - (f4) => f4.field == oldColumn.name + oldColumn.table ? { ...f4, field: column.name + column.table } : f4 - ), - groupBy: predicate.groupBy.map( - (f4) => f4 == oldColumn.name + oldColumn.table ? column.name + column.table : f4 - ), - colsHidden: predicate.colsHidden.map( - (f4) => f4 == oldColumn.name + oldColumn.table ? column.name + column.table : f4 - ), - colsOrder: predicate.colsOrder.map( - (f4) => f4 == oldColumn.name + oldColumn.table ? column.name + column.table : f4 - ), - colsSize: { - ...predicate.colsSize, - [column.name + column.table]: predicate.colsSize[oldColumn.name + oldColumn.table], - [oldColumn.name + oldColumn.table]: void 0 - } + }, + 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); + } + 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; +} +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" }); - if (table == "") { - syncAllMetadata(newTable); - } else if (contextTable[table]) { - saveContextDB(newTable, table); - } - return true; - }; - return /* @__PURE__ */ bn.createElement(MDBContext.Provider, { - value: { - data, - filteredData, - loadContextFields, - selectedRows, - selectRows, - tableData, - cols, - sortedColumns, - contextTable, - setContextTable, - predicate, - savePredicate, - saveDB: saveDB2, - saveContextDB, - schema, - dbPath, - saveColumn, - hideColumn, - sortColumn, - delColumn, - newColumn, - tagContexts, - tables, - setSchema, - saveSchema, - deleteSchema, - dbFileExists, - dbSchema, - searchString, - setSearchString, - folderPath, - isFolderContext, - setDBSchema, - updateValue, - updateFieldValue - } - }, props2.children); + case "PP": + return formatLong2.date({ + width: "medium" + }); + case "PPP": + return formatLong2.date({ + width: "long" + }); + case "PPPP": + default: + return formatLong2.date({ + width: "full" + }); + } +}; +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; -// src/components/ContextView/CardsView/CardView.tsx -var import_classnames = __toESM(require_classnames()); +// 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")); + } +} -// src/components/FlowEditor/FlowView.tsx -var FlowView = (props2) => { - const ref = _2(null); - const loadFile = () => { - const div = ref.current; - const type = viewTypeByString(props2.path); - const portalType = type == "tag" || type == "folder" ? "context" : "doc"; - spawnLeafFromFile(props2.plugin, props2.path, div, portalType); - }; - const toggleFlow = () => { - if (props2.load) { - loadFile(); +// 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 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 { - ref.current.empty(); + return result + " ago"; } - }; - h2(() => { - toggleFlow(); - }, [props2.load, props2.path]); - return /* @__PURE__ */ bn.createElement("div", { - className: "mk-flowspace-editor", - ref - }); + } + return result; }; +var formatDistance_default = formatDistance; -// node_modules/@tanstack/table-core/build/lib/index.mjs -function functionalUpdate(updater, input) { - return typeof updater === "function" ? updater(input) : updater; -} -function makeStateUpdater(key2, instance) { - return (updater) => { - instance.setState((old) => { - return { - ...old, - [key2]: functionalUpdate(updater, old[key2]) - }; - }); - }; -} -function isFunction(d5) { - return d5 instanceof Function; -} -function flattenBy(arr, getChildren) { - const flat = []; - const recurse = (subArr) => { - subArr.forEach((item) => { - flat.push(item); - const children = getChildren(item); - if (children == null ? void 0 : children.length) { - recurse(children); - } - }); +// 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; }; - recurse(arr); - return flat; } -function memo(getDeps, fn2, opts) { - let deps = []; - let result; - return () => { - var _a2; - let depTime; - if (opts.key && opts.debug) - depTime = Date.now(); - const newDeps = getDeps(); - const depsChanged = newDeps.length !== deps.length || newDeps.some((dep, index) => deps[index] !== dep); - if (!depsChanged) { - return result; - } - deps = newDeps; - let resultTime; - if (opts.key && opts.debug) - resultTime = Date.now(); - result = fn2(...newDeps); - (_a2 = opts == null ? void 0 : opts.onChange) == null ? void 0 : _a2.call(opts, result); - if (opts.key && opts.debug) { - if (opts == null ? void 0 : opts.debug()) { - const depEndTime = Math.round((Date.now() - depTime) * 100) / 100; - const resultEndTime = Math.round((Date.now() - resultTime) * 100) / 100; - const resultFpsPercentage = resultEndTime / 16; - const pad = (str, num) => { - str = String(str); - while (str.length < num) { - str = " " + str; - } - return str; - }; - console.info(`%c\u23F1 ${pad(resultEndTime, 5)} /${pad(depEndTime, 5)} ms`, ` - font-size: .6rem; - font-weight: bold; - color: hsl(${Math.max(0, Math.min(120 - 120 * resultFpsPercentage, 120))}deg 100% 31%);`, opts == null ? void 0 : opts.key); - } + +// 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]; } - return result; + var index = args.argumentCallback ? args.argumentCallback(dirtyIndex) : dirtyIndex; + return valuesArray[index]; }; } -function createColumn(table, columnDef, depth, parent) { - var _ref, _resolvedColumnDef$id; - const defaultColumn = table._getDefaultColumnDef(); - const resolvedColumnDef = { - ...defaultColumn, - ...columnDef - }; - const accessorKey = resolvedColumnDef.accessorKey; - let id2 = (_ref = (_resolvedColumnDef$id = resolvedColumnDef.id) != null ? _resolvedColumnDef$id : accessorKey ? accessorKey.replace(".", "_") : void 0) != null ? _ref : typeof resolvedColumnDef.header === "string" ? resolvedColumnDef.header : void 0; - let accessorFn; - if (resolvedColumnDef.accessorFn) { - accessorFn = resolvedColumnDef.accessorFn; - } else if (accessorKey) { - if (accessorKey.includes(".")) { - accessorFn = (originalRow) => { - let result = originalRow; - for (const key2 of accessorKey.split(".")) { - result = result[key2]; - if (result === void 0) { - throw new Error(`"${key2}" in deeply nested key "${accessorKey}" returned undefined.`); - } - } - return result; - }; - } else { - accessorFn = (originalRow) => originalRow[resolvedColumnDef.accessorKey]; - } - } - if (!id2) { - if (true) { - throw new Error(resolvedColumnDef.accessorFn ? `Columns require an id when using an accessorFn` : `Columns require an id when using a non-string header`); - } - throw new Error(); - } - let column = { - id: `${String(id2)}`, - accessorFn, - parent, - depth, - columnDef: resolvedColumnDef, - columns: [], - getFlatColumns: memo(() => [true], () => { - var _a2; - return [column, ...(_a2 = column.columns) == null ? void 0 : _a2.flatMap((d5) => d5.getFlatColumns())]; - }, { - key: false, - debug: () => { - var _table$options$debugA; - return (_table$options$debugA = table.options.debugAll) != null ? _table$options$debugA : table.options.debugColumns; - } - }), - getLeafColumns: memo(() => [table._getOrderColumnsFn()], (orderColumns2) => { - var _a2; - if ((_a2 = column.columns) == null ? void 0 : _a2.length) { - let leafColumns = column.columns.flatMap((column2) => column2.getLeafColumns()); - return orderColumns2(leafColumns); - } - return [column]; - }, { - key: false, - debug: () => { - var _table$options$debugA2; - return (_table$options$debugA2 = table.options.debugAll) != null ? _table$options$debugA2 : table.options.debugColumns; - } - }) - }; - column = table._features.reduce((obj, feature) => { - var _a2; - return Object.assign(obj, (_a2 = feature.createColumn) == null ? void 0 : _a2.call(feature, column, table)); - }, column); - return column; -} -function createHeader(table, column, options) { - var _options$id; - const id2 = (_options$id = options.id) != null ? _options$id : column.id; - let header = { - id: id2, - column, - index: options.index, - isPlaceholder: !!options.isPlaceholder, - placeholderId: options.placeholderId, - depth: options.depth, - subHeaders: [], - colSpan: 0, - rowSpan: 0, - headerGroup: null, - getLeafHeaders: () => { - const leafHeaders = []; - const recurseHeader = (h5) => { - if (h5.subHeaders && h5.subHeaders.length) { - h5.subHeaders.map(recurseHeader); - } - leafHeaders.push(h5); - }; - recurseHeader(header); - return leafHeaders; - }, - getContext: () => ({ - table, - header, - column - }) - }; - table._features.forEach((feature) => { - var _a2; - Object.assign(header, (_a2 = feature.createHeader) == null ? void 0 : _a2.call(feature, header, table)); - }); - return header; -} -var Headers = { - createTable: (table) => { - return { - getHeaderGroups: memo(() => [table.getAllColumns(), table.getVisibleLeafColumns(), table.getState().columnPinning.left, table.getState().columnPinning.right], (allColumns, leafColumns, left, right) => { - var _left$map$filter, _right$map$filter; - const leftColumns = (_left$map$filter = left == null ? void 0 : left.map((columnId) => leafColumns.find((d5) => d5.id === columnId)).filter(Boolean)) != null ? _left$map$filter : []; - const rightColumns = (_right$map$filter = right == null ? void 0 : right.map((columnId) => leafColumns.find((d5) => d5.id === columnId)).filter(Boolean)) != null ? _right$map$filter : []; - const centerColumns = leafColumns.filter((column) => !(left == null ? void 0 : left.includes(column.id)) && !(right == null ? void 0 : right.includes(column.id))); - const headerGroups = buildHeaderGroups(allColumns, [...leftColumns, ...centerColumns, ...rightColumns], table); - return headerGroups; - }, { - key: "getHeaderGroups", - debug: () => { - var _table$options$debugA; - return (_table$options$debugA = table.options.debugAll) != null ? _table$options$debugA : table.options.debugHeaders; - } - }), - getCenterHeaderGroups: memo(() => [table.getAllColumns(), table.getVisibleLeafColumns(), table.getState().columnPinning.left, table.getState().columnPinning.right], (allColumns, leafColumns, left, right) => { - leafColumns = leafColumns.filter((column) => !(left == null ? void 0 : left.includes(column.id)) && !(right == null ? void 0 : right.includes(column.id))); - return buildHeaderGroups(allColumns, leafColumns, table, "center"); - }, { - key: "getCenterHeaderGroups", - debug: () => { - var _table$options$debugA2; - return (_table$options$debugA2 = table.options.debugAll) != null ? _table$options$debugA2 : table.options.debugHeaders; - } - }), - getLeftHeaderGroups: memo(() => [table.getAllColumns(), table.getVisibleLeafColumns(), table.getState().columnPinning.left], (allColumns, leafColumns, left) => { - var _left$map$filter2; - const orderedLeafColumns = (_left$map$filter2 = left == null ? void 0 : left.map((columnId) => leafColumns.find((d5) => d5.id === columnId)).filter(Boolean)) != null ? _left$map$filter2 : []; - return buildHeaderGroups(allColumns, orderedLeafColumns, table, "left"); - }, { - key: "getLeftHeaderGroups", - debug: () => { - var _table$options$debugA3; - return (_table$options$debugA3 = table.options.debugAll) != null ? _table$options$debugA3 : table.options.debugHeaders; - } - }), - getRightHeaderGroups: memo(() => [table.getAllColumns(), table.getVisibleLeafColumns(), table.getState().columnPinning.right], (allColumns, leafColumns, right) => { - var _right$map$filter2; - const orderedLeafColumns = (_right$map$filter2 = right == null ? void 0 : right.map((columnId) => leafColumns.find((d5) => d5.id === columnId)).filter(Boolean)) != null ? _right$map$filter2 : []; - return buildHeaderGroups(allColumns, orderedLeafColumns, table, "right"); - }, { - key: "getRightHeaderGroups", - debug: () => { - var _table$options$debugA4; - return (_table$options$debugA4 = table.options.debugAll) != null ? _table$options$debugA4 : table.options.debugHeaders; - } - }), - getFooterGroups: memo(() => [table.getHeaderGroups()], (headerGroups) => { - return [...headerGroups].reverse(); - }, { - key: "getFooterGroups", - debug: () => { - var _table$options$debugA5; - return (_table$options$debugA5 = table.options.debugAll) != null ? _table$options$debugA5 : table.options.debugHeaders; - } - }), - getLeftFooterGroups: memo(() => [table.getLeftHeaderGroups()], (headerGroups) => { - return [...headerGroups].reverse(); - }, { - key: "getLeftFooterGroups", - debug: () => { - var _table$options$debugA6; - return (_table$options$debugA6 = table.options.debugAll) != null ? _table$options$debugA6 : table.options.debugHeaders; - } - }), - getCenterFooterGroups: memo(() => [table.getCenterHeaderGroups()], (headerGroups) => { - return [...headerGroups].reverse(); - }, { - key: "getCenterFooterGroups", - debug: () => { - var _table$options$debugA7; - return (_table$options$debugA7 = table.options.debugAll) != null ? _table$options$debugA7 : table.options.debugHeaders; - } - }), - getRightFooterGroups: memo(() => [table.getRightHeaderGroups()], (headerGroups) => { - return [...headerGroups].reverse(); - }, { - key: "getRightFooterGroups", - debug: () => { - var _table$options$debugA8; - return (_table$options$debugA8 = table.options.debugAll) != null ? _table$options$debugA8 : table.options.debugHeaders; - } - }), - getFlatHeaders: memo(() => [table.getHeaderGroups()], (headerGroups) => { - return headerGroups.map((headerGroup) => { - return headerGroup.headers; - }).flat(); - }, { - key: "getFlatHeaders", - debug: () => { - var _table$options$debugA9; - return (_table$options$debugA9 = table.options.debugAll) != null ? _table$options$debugA9 : table.options.debugHeaders; - } - }), - getLeftFlatHeaders: memo(() => [table.getLeftHeaderGroups()], (left) => { - return left.map((headerGroup) => { - return headerGroup.headers; - }).flat(); - }, { - key: "getLeftFlatHeaders", - debug: () => { - var _table$options$debugA10; - return (_table$options$debugA10 = table.options.debugAll) != null ? _table$options$debugA10 : table.options.debugHeaders; - } - }), - getCenterFlatHeaders: memo(() => [table.getCenterHeaderGroups()], (left) => { - return left.map((headerGroup) => { - return headerGroup.headers; - }).flat(); - }, { - key: "getCenterFlatHeaders", - debug: () => { - var _table$options$debugA11; - return (_table$options$debugA11 = table.options.debugAll) != null ? _table$options$debugA11 : table.options.debugHeaders; - } - }), - getRightFlatHeaders: memo(() => [table.getRightHeaderGroups()], (left) => { - return left.map((headerGroup) => { - return headerGroup.headers; - }).flat(); - }, { - key: "getRightFlatHeaders", - debug: () => { - var _table$options$debugA12; - return (_table$options$debugA12 = table.options.debugAll) != null ? _table$options$debugA12 : table.options.debugHeaders; - } - }), - getCenterLeafHeaders: memo(() => [table.getCenterFlatHeaders()], (flatHeaders) => { - return flatHeaders.filter((header) => { - var _a2; - return !((_a2 = header.subHeaders) == null ? void 0 : _a2.length); - }); - }, { - key: "getCenterLeafHeaders", - debug: () => { - var _table$options$debugA13; - return (_table$options$debugA13 = table.options.debugAll) != null ? _table$options$debugA13 : table.options.debugHeaders; - } - }), - getLeftLeafHeaders: memo(() => [table.getLeftFlatHeaders()], (flatHeaders) => { - return flatHeaders.filter((header) => { - var _a2; - return !((_a2 = header.subHeaders) == null ? void 0 : _a2.length); - }); - }, { - key: "getLeftLeafHeaders", - debug: () => { - var _table$options$debugA14; - return (_table$options$debugA14 = table.options.debugAll) != null ? _table$options$debugA14 : table.options.debugHeaders; - } - }), - getRightLeafHeaders: memo(() => [table.getRightFlatHeaders()], (flatHeaders) => { - return flatHeaders.filter((header) => { - var _a2; - return !((_a2 = header.subHeaders) == null ? void 0 : _a2.length); - }); - }, { - key: "getRightLeafHeaders", - debug: () => { - var _table$options$debugA15; - return (_table$options$debugA15 = table.options.debugAll) != null ? _table$options$debugA15 : table.options.debugHeaders; - } - }), - getLeafHeaders: memo(() => [table.getLeftHeaderGroups(), table.getCenterHeaderGroups(), table.getRightHeaderGroups()], (left, center, right) => { - var _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) => { - return header.getLeafHeaders(); - }).flat(); - }, { - key: "getLeafHeaders", - debug: () => { - var _table$options$debugA16; - return (_table$options$debugA16 = table.options.debugAll) != null ? _table$options$debugA16 : table.options.debugHeaders; - } - }) - }; - } -}; -function buildHeaderGroups(allColumns, columnsToGroup, table, headerFamily) { - var _a2; - var _headerGroups$0$heade; - let maxDepth = 0; - const findMaxDepth = function(columns, depth) { - if (depth === void 0) { - depth = 1; - } - maxDepth = Math.max(maxDepth, depth); - columns.filter((column) => column.getIsVisible()).forEach((column) => { - var _a3; - if ((_a3 = column.columns) == null ? void 0 : _a3.length) { - findMaxDepth(column.columns, depth + 1); - } - }, 0); - }; - findMaxDepth(allColumns); - let headerGroups = []; - const createHeaderGroup = (headersToGroup, depth) => { - const headerGroup = { - depth, - id: [headerFamily, `${depth}`].filter(Boolean).join("_"), - headers: [] - }; - const pendingParentHeaders = []; - headersToGroup.forEach((headerToGroup) => { - const latestPendingParentHeader = [...pendingParentHeaders].reverse()[0]; - const isLeafHeader = headerToGroup.column.depth === headerGroup.depth; - let column; - let isPlaceholder = false; - if (isLeafHeader && headerToGroup.column.parent) { - column = headerToGroup.column.parent; - } else { - column = headerToGroup.column; - isPlaceholder = true; - } - if (latestPendingParentHeader && (latestPendingParentHeader == null ? void 0 : latestPendingParentHeader.column) === column) { - latestPendingParentHeader.subHeaders.push(headerToGroup); - } else { - const header = createHeader(table, column, { - id: [headerFamily, depth, column.id, headerToGroup == null ? void 0 : headerToGroup.id].filter(Boolean).join("_"), - isPlaceholder, - placeholderId: isPlaceholder ? `${pendingParentHeaders.filter((d5) => d5.column === column).length}` : void 0, - depth, - index: pendingParentHeaders.length - }); - header.subHeaders.push(headerToGroup); - pendingParentHeaders.push(header); - } - headerGroup.headers.push(headerToGroup); - headerToGroup.headerGroup = headerGroup; - }); - headerGroups.push(headerGroup); - if (depth > 0) { - createHeaderGroup(pendingParentHeaders, depth - 1); - } - }; - const bottomHeaders = columnsToGroup.map((column, index) => createHeader(table, column, { - depth: maxDepth, - index - })); - createHeaderGroup(bottomHeaders, maxDepth - 1); - headerGroups.reverse(); - const recurseHeadersForSpans = (headers) => { - const filteredHeaders = headers.filter((header) => header.column.getIsVisible()); - return filteredHeaders.map((header) => { - let colSpan = 0; - let rowSpan = 0; - let childRowSpans = [0]; - if (header.subHeaders && header.subHeaders.length) { - childRowSpans = []; - recurseHeadersForSpans(header.subHeaders).forEach((_ref) => { - let { - colSpan: childColSpan, - rowSpan: childRowSpan - } = _ref; - colSpan += childColSpan; - childRowSpans.push(childRowSpan); - }); - } else { - colSpan = 1; - } - const minChildRowSpan = Math.min(...childRowSpans); - rowSpan = rowSpan + minChildRowSpan; - header.colSpan = colSpan; - header.rowSpan = rowSpan; - return { - colSpan, - rowSpan - }; - }); - }; - recurseHeadersForSpans((_headerGroups$0$heade = (_a2 = headerGroups[0]) == null ? void 0 : _a2.headers) != null ? _headerGroups$0$heade : []); - return headerGroups; -} -var defaultColumnSizing = { - size: 150, - minSize: 20, - maxSize: Number.MAX_SAFE_INTEGER -}; -var getDefaultColumnSizingInfoState = () => ({ - startOffset: null, - startSize: null, - deltaOffset: null, - deltaPercentage: null, - isResizingColumn: false, - columnSizingStart: [] -}); -var ColumnSizing = { - getDefaultColumnDef: () => { - return defaultColumnSizing; - }, - getInitialState: (state) => { - return { - columnSizing: {}, - columnSizingInfo: getDefaultColumnSizingInfoState(), - ...state - }; - }, - getDefaultOptions: (table) => { - return { - columnResizeMode: "onEnd", - onColumnSizingChange: makeStateUpdater("columnSizing", table), - onColumnSizingInfoChange: makeStateUpdater("columnSizingInfo", table) - }; - }, - createColumn: (column, table) => { - return { - getSize: () => { - var _column$columnDef$min, _ref, _column$columnDef$max; - const columnSize = table.getState().columnSizing[column.id]; - return Math.min(Math.max((_column$columnDef$min = column.columnDef.minSize) != null ? _column$columnDef$min : defaultColumnSizing.minSize, (_ref = columnSize != null ? columnSize : column.columnDef.size) != null ? _ref : defaultColumnSizing.size), (_column$columnDef$max = column.columnDef.maxSize) != null ? _column$columnDef$max : defaultColumnSizing.maxSize); - }, - getStart: (position) => { - const columns = !position ? table.getVisibleLeafColumns() : position === "left" ? table.getLeftVisibleLeafColumns() : table.getRightVisibleLeafColumns(); - const index = columns.findIndex((d5) => d5.id === column.id); - if (index > 0) { - const prevSiblingColumn = columns[index - 1]; - return prevSiblingColumn.getStart(position) + prevSiblingColumn.getSize(); - } - return 0; - }, - resetSize: () => { - table.setColumnSizing((_ref2) => { - let { - [column.id]: _4, - ...rest - } = _ref2; - return rest; - }); - }, - getCanResize: () => { - var _column$columnDef$ena, _table$options$enable; - return ((_column$columnDef$ena = column.columnDef.enableResizing) != null ? _column$columnDef$ena : true) && ((_table$options$enable = table.options.enableColumnResizing) != null ? _table$options$enable : true); - }, - getIsResizing: () => { - return table.getState().columnSizingInfo.isResizingColumn === column.id; - } - }; - }, - createHeader: (header, table) => { - return { - getSize: () => { - let sum2 = 0; - const recurse = (header2) => { - if (header2.subHeaders.length) { - header2.subHeaders.forEach(recurse); - } else { - var _header$column$getSiz; - sum2 += (_header$column$getSiz = header2.column.getSize()) != null ? _header$column$getSiz : 0; - } - }; - recurse(header); - return sum2; - }, - getStart: () => { - if (header.index > 0) { - const prevSiblingHeader = header.headerGroup.headers[header.index - 1]; - return prevSiblingHeader.getStart() + prevSiblingHeader.getSize(); - } - return 0; - }, - getResizeHandler: () => { - const column = table.getColumn(header.column.id); - const canResize = column.getCanResize(); - return (e4) => { - var _a2; - if (!canResize) { - return; - } - (_a2 = e4.persist) == null ? void 0 : _a2.call(e4); - if (isTouchStartEvent(e4)) { - if (e4.touches && e4.touches.length > 1) { - return; - } - } - const startSize = header.getSize(); - const columnSizingStart = header ? header.getLeafHeaders().map((d5) => [d5.column.id, d5.column.getSize()]) : [[column.id, column.getSize()]]; - const clientX = isTouchStartEvent(e4) ? Math.round(e4.touches[0].clientX) : e4.clientX; - const newColumnSizing = {}; - const updateOffset = (eventType, clientXPos) => { - if (typeof clientXPos !== "number") { - return; - } - table.setColumnSizingInfo((old) => { - var _old$startOffset, _old$startSize; - const deltaOffset = clientXPos - ((_old$startOffset = old == null ? void 0 : old.startOffset) != null ? _old$startOffset : 0); - const deltaPercentage = Math.max(deltaOffset / ((_old$startSize = old == null ? void 0 : old.startSize) != null ? _old$startSize : 0), -0.999999); - old.columnSizingStart.forEach((_ref3) => { - let [columnId, headerSize] = _ref3; - newColumnSizing[columnId] = Math.round(Math.max(headerSize + headerSize * deltaPercentage, 0) * 100) / 100; - }); - return { - ...old, - deltaOffset, - deltaPercentage - }; - }); - if (table.options.columnResizeMode === "onChange" || eventType === "end") { - table.setColumnSizing((old) => ({ - ...old, - ...newColumnSizing - })); - } - }; - const onMove = (clientXPos) => updateOffset("move", clientXPos); - const onEnd = (clientXPos) => { - updateOffset("end", clientXPos); - table.setColumnSizingInfo((old) => ({ - ...old, - isResizingColumn: false, - startOffset: null, - startSize: null, - deltaOffset: null, - deltaPercentage: null, - columnSizingStart: [] - })); - }; - const mouseEvents = { - moveHandler: (e5) => onMove(e5.clientX), - upHandler: (e5) => { - document.removeEventListener("mousemove", mouseEvents.moveHandler); - document.removeEventListener("mouseup", mouseEvents.upHandler); - onEnd(e5.clientX); - } - }; - const touchEvents = { - moveHandler: (e5) => { - if (e5.cancelable) { - e5.preventDefault(); - e5.stopPropagation(); - } - onMove(e5.touches[0].clientX); - return false; - }, - upHandler: (e5) => { - var _a3; - 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); - } - }; - const passiveIfSupported = passiveEventSupported() ? { - passive: false - } : false; - if (isTouchStartEvent(e4)) { - document.addEventListener("touchmove", touchEvents.moveHandler, passiveIfSupported); - document.addEventListener("touchend", touchEvents.upHandler, passiveIfSupported); - } else { - document.addEventListener("mousemove", mouseEvents.moveHandler, passiveIfSupported); - document.addEventListener("mouseup", mouseEvents.upHandler, passiveIfSupported); - } - table.setColumnSizingInfo((old) => ({ - ...old, - startOffset: clientX, - startSize, - deltaOffset: 0, - deltaPercentage: 0, - columnSizingStart, - isResizingColumn: column.id - })); - }; - } - }; - }, - createTable: (table) => { - return { - setColumnSizing: (updater) => { - 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); - }, - resetColumnSizing: (defaultState) => { - var _table$initialState$c; - table.setColumnSizing(defaultState ? {} : (_table$initialState$c = table.initialState.columnSizing) != null ? _table$initialState$c : {}); - }, - resetHeaderSizeInfo: (defaultState) => { - var _table$initialState$c2; - table.setColumnSizingInfo(defaultState ? getDefaultColumnSizingInfoState() : (_table$initialState$c2 = table.initialState.columnSizingInfo) != null ? _table$initialState$c2 : getDefaultColumnSizingInfoState()); - }, - getTotalSize: () => { - var _a2; - var _table$getHeaderGroup; - return (_table$getHeaderGroup = (_a2 = table.getHeaderGroups()[0]) == null ? void 0 : _a2.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) => { - 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) => { - 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) => { - return sum2 + header.getSize(); - }, 0)) != null ? _table$getRightHeader : 0; - } - }; - } -}; -var passiveSupported = null; -function passiveEventSupported() { - if (typeof passiveSupported === "boolean") - return passiveSupported; - let supported = false; - try { - const options = { - get passive() { - supported = true; - return false; - } - }; - const noop2 = () => { - }; - window.addEventListener("test", noop2, options); - window.removeEventListener("test", noop2); - } catch (err) { - supported = false; - } - passiveSupported = supported; - return passiveSupported; -} -function isTouchStartEvent(e4) { - return e4.type === "touchstart"; -} -var Expanding = { - getInitialState: (state) => { - return { - expanded: {}, - ...state - }; - }, - getDefaultOptions: (table) => { - return { - onExpandedChange: makeStateUpdater("expanded", table), - paginateExpandedRows: true - }; - }, - createTable: (table) => { - let registered = false; - let queued = false; - return { - _autoResetExpanded: () => { - var _ref, _table$options$autoRe; - if (!registered) { - table._queue(() => { - registered = true; - }); - return; - } - if ((_ref = (_table$options$autoRe = table.options.autoResetAll) != null ? _table$options$autoRe : table.options.autoResetExpanded) != null ? _ref : !table.options.manualExpanding) { - if (queued) - return; - queued = true; - table._queue(() => { - table.resetExpanded(); - queued = false; - }); - } - }, - setExpanded: (updater) => { - var _a2, _b2; - return (_b2 = (_a2 = table.options).onExpandedChange) == null ? void 0 : _b2.call(_a2, updater); - }, - toggleAllRowsExpanded: (expanded) => { - if (expanded != null ? expanded : !table.getIsAllRowsExpanded()) { - table.setExpanded(true); - } else { - table.setExpanded({}); - } - }, - 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 : {}); - }, - getCanSomeRowsExpand: () => { - return table.getRowModel().flatRows.some((row) => row.getCanExpand()); - }, - getToggleAllRowsExpandedHandler: () => { - return (e4) => { - var _a2; - (_a2 = e4.persist) == null ? void 0 : _a2.call(e4); - table.toggleAllRowsExpanded(); - }; - }, - getIsSomeRowsExpanded: () => { - const expanded = table.getState().expanded; - return expanded === true || Object.values(expanded).some(Boolean); - }, - getIsAllRowsExpanded: () => { - const expanded = table.getState().expanded; - if (typeof expanded === "boolean") { - return expanded === true; - } - if (!Object.keys(expanded).length) { - return false; - } - if (table.getRowModel().flatRows.some((row) => !row.getIsExpanded())) { - return false; - } - return true; - }, - getExpandedDepth: () => { - let maxDepth = 0; - const rowIds = table.getState().expanded === true ? Object.keys(table.getRowModel().rowsById) : Object.keys(table.getState().expanded); - rowIds.forEach((id2) => { - const splitId = id2.split("."); - maxDepth = Math.max(maxDepth, splitId.length); - }); - return maxDepth; - }, - getPreExpandedRowModel: () => table.getSortedRowModel(), - getExpandedRowModel: () => { - if (!table._getExpandedRowModel && table.options.getExpandedRowModel) { - table._getExpandedRowModel = table.options.getExpandedRowModel(table); - } - if (table.options.manualExpanding || !table._getExpandedRowModel) { - return table.getPreExpandedRowModel(); - } - return table._getExpandedRowModel(); - } - }; - }, - createRow: (row, table) => { - return { - toggleExpanded: (expanded) => { - table.setExpanded((old) => { - var _expanded; - const exists = old === true ? true : !!(old == null ? void 0 : old[row.id]); - let oldExpanded = {}; - if (old === true) { - Object.keys(table.getRowModel().rowsById).forEach((rowId) => { - oldExpanded[rowId] = true; - }); - } else { - oldExpanded = old; - } - expanded = (_expanded = expanded) != null ? _expanded : !exists; - if (!exists && expanded) { - return { - ...oldExpanded, - [row.id]: true - }; - } - if (exists && !expanded) { - const { - [row.id]: _4, - ...rest - } = oldExpanded; - return rest; - } - return old; - }); - }, - 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])); - }, - 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); - }, - getToggleExpandedHandler: () => { - const canExpand = row.getCanExpand(); - return () => { - if (!canExpand) - return; - row.toggleExpanded(); - }; - } - }; - } -}; -var includesString = (row, columnId, filterValue) => { - var _a2; - const search = filterValue.toLowerCase(); - return Boolean((_a2 = row.getValue(columnId)) == null ? void 0 : _a2.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)); -}; -includesStringSensitive.autoRemove = (val) => testFalsey(val); -var equalsString = (row, columnId, filterValue) => { - var _a2; - return ((_a2 = row.getValue(columnId)) == null ? void 0 : _a2.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); -}; -arrIncludes.autoRemove = (val) => testFalsey(val) || !(val == null ? void 0 : val.length); -var arrIncludesAll = (row, columnId, filterValue) => { - return !filterValue.some((val) => { - var _a2; - return !((_a2 = row.getValue(columnId)) == null ? void 0 : _a2.includes(val)); - }); -}; -arrIncludesAll.autoRemove = (val) => testFalsey(val) || !(val == null ? void 0 : val.length); -var arrIncludesSome = (row, columnId, filterValue) => { - return filterValue.some((val) => { - var _a2; - return (_a2 = row.getValue(columnId)) == null ? void 0 : _a2.includes(val); - }); -}; -arrIncludesSome.autoRemove = (val) => testFalsey(val) || !(val == null ? void 0 : val.length); -var equals = (row, columnId, filterValue) => { - return row.getValue(columnId) === filterValue; -}; -equals.autoRemove = (val) => testFalsey(val); -var weakEquals = (row, columnId, filterValue) => { - return row.getValue(columnId) == filterValue; -}; -weakEquals.autoRemove = (val) => testFalsey(val); -var inNumberRange = (row, columnId, filterValue) => { - let [min3, max3] = filterValue; - const rowValue = row.getValue(columnId); - return rowValue >= min3 && rowValue <= max3; -}; -inNumberRange.resolveFilterValue = (val) => { - let [unsafeMin, unsafeMax] = val; - let parsedMin = typeof unsafeMin !== "number" ? parseFloat(unsafeMin) : unsafeMin; - let parsedMax = typeof unsafeMax !== "number" ? parseFloat(unsafeMax) : unsafeMax; - let min3 = unsafeMin === null || Number.isNaN(parsedMin) ? -Infinity : parsedMin; - let max3 = unsafeMax === null || Number.isNaN(parsedMax) ? Infinity : parsedMax; - if (min3 > max3) { - const temp = min3; - min3 = max3; - max3 = temp; - } - return [min3, max3]; -}; -inNumberRange.autoRemove = (val) => testFalsey(val) || testFalsey(val[0]) && testFalsey(val[1]); -var filterFns = { - includesString, - includesStringSensitive, - equalsString, - arrIncludes, - arrIncludesAll, - arrIncludesSome, - equals, - weakEquals, - inNumberRange -}; -function testFalsey(val) { - return val === void 0 || val === null || val === ""; -} -var Filters = { - getDefaultColumnDef: () => { - return { - filterFn: "auto" - }; - }, - getInitialState: (state) => { - return { - columnFilters: [], - globalFilter: void 0, - ...state - }; - }, - getDefaultOptions: (table) => { - return { - onColumnFiltersChange: makeStateUpdater("columnFilters", table), - onGlobalFilterChange: makeStateUpdater("globalFilter", table), - filterFromLeafRows: false, - maxLeafRowFilterDepth: 100, - globalFilterFn: "auto", - getColumnCanGlobalFilter: (column) => { - var _a2, _b2; - const value = (_b2 = (_a2 = table.getCoreRowModel().flatRows[0]) == null ? void 0 : _a2._getAllCellsByColumnId()[column.id]) == null ? void 0 : _b2.getValue(); - return typeof value === "string" || typeof value === "number"; - } - }; - }, - createColumn: (column, table) => { - return { - getAutoFilterFn: () => { - const firstRow = table.getCoreRowModel().flatRows[0]; - const value = firstRow == null ? void 0 : firstRow.getValue(column.id); - if (typeof value === "string") { - return filterFns.includesString; - } - if (typeof value === "number") { - return filterFns.inNumberRange; - } - if (typeof value === "boolean") { - return filterFns.equals; - } - if (value !== null && typeof value === "object") { - return filterFns.equals; - } - if (Array.isArray(value)) { - return filterFns.arrIncludes; - } - return filterFns.weakEquals; - }, - getFilterFn: () => { - var _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]; - }, - 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; - }, - 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; - }, - 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; - }, - setFilterValue: (value) => { - table.setColumnFilters((old) => { - const filterFn = column.getFilterFn(); - const previousfilter = old == null ? void 0 : old.find((d5) => d5.id === column.id); - const newFilter = functionalUpdate(value, previousfilter ? previousfilter.value : void 0); - if (shouldAutoRemoveFilter(filterFn, newFilter, column)) { - var _old$filter; - return (_old$filter = old == null ? void 0 : old.filter((d5) => d5.id !== column.id)) != null ? _old$filter : []; - } - const newFilterObj = { - id: column.id, - value: newFilter - }; - if (previousfilter) { - var _old$map; - return (_old$map = old == null ? void 0 : old.map((d5) => { - if (d5.id === column.id) { - return newFilterObj; - } - return d5; - })) != null ? _old$map : []; - } - if (old == null ? void 0 : old.length) { - return [...old, newFilterObj]; - } - return [newFilterObj]; - }); - }, - _getFacetedRowModel: table.options.getFacetedRowModel && table.options.getFacetedRowModel(table, column.id), - getFacetedRowModel: () => { - if (!column._getFacetedRowModel) { - return table.getPreFilteredRowModel(); - } - return column._getFacetedRowModel(); - }, - _getFacetedUniqueValues: table.options.getFacetedUniqueValues && table.options.getFacetedUniqueValues(table, column.id), - getFacetedUniqueValues: () => { - if (!column._getFacetedUniqueValues) { - return /* @__PURE__ */ new Map(); - } - return column._getFacetedUniqueValues(); - }, - _getFacetedMinMaxValues: table.options.getFacetedMinMaxValues && table.options.getFacetedMinMaxValues(table, column.id), - getFacetedMinMaxValues: () => { - if (!column._getFacetedMinMaxValues) { - return void 0; - } - return column._getFacetedMinMaxValues(); - } - }; - }, - createRow: (row, table) => { - return { - columnFilters: {}, - columnFiltersMeta: {} - }; - }, - createTable: (table) => { - return { - getGlobalAutoFilterFn: () => { - return filterFns.includesString; - }, - getGlobalFilterFn: () => { - var _a2; - var _table$options$filter2; - 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]; - }, - 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) => { - const column = leafColumns.find((d5) => d5.id === filter.id); - if (column) { - const filterFn = column.getFilterFn(); - if (shouldAutoRemoveFilter(filterFn, filter.value, column)) { - return false; - } - } - return true; - }); - }; - (_b2 = (_a2 = table.options).onColumnFiltersChange) == null ? void 0 : _b2.call(_a2, updateFn); - }, - setGlobalFilter: (updater) => { - var _a2, _b2; - (_b2 = (_a2 = table.options).onGlobalFilterChange) == null ? void 0 : _b2.call(_a2, 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 : []); - }, - getPreFilteredRowModel: () => table.getCoreRowModel(), - getFilteredRowModel: () => { - if (!table._getFilteredRowModel && table.options.getFilteredRowModel) { - table._getFilteredRowModel = table.options.getFilteredRowModel(table); - } - if (table.options.manualFiltering || !table._getFilteredRowModel) { - return table.getPreFilteredRowModel(); - } - return table._getFilteredRowModel(); - }, - _getGlobalFacetedRowModel: table.options.getFacetedRowModel && table.options.getFacetedRowModel(table, "__global__"), - getGlobalFacetedRowModel: () => { - if (table.options.manualFiltering || !table._getGlobalFacetedRowModel) { - return table.getPreFilteredRowModel(); - } - return table._getGlobalFacetedRowModel(); - }, - _getGlobalFacetedUniqueValues: table.options.getFacetedUniqueValues && table.options.getFacetedUniqueValues(table, "__global__"), - getGlobalFacetedUniqueValues: () => { - if (!table._getGlobalFacetedUniqueValues) { - return /* @__PURE__ */ new Map(); - } - return table._getGlobalFacetedUniqueValues(); - }, - _getGlobalFacetedMinMaxValues: table.options.getFacetedMinMaxValues && table.options.getFacetedMinMaxValues(table, "__global__"), - getGlobalFacetedMinMaxValues: () => { - if (!table._getGlobalFacetedMinMaxValues) { - return; - } - return table._getGlobalFacetedMinMaxValues(); - } - }; - } -}; -function shouldAutoRemoveFilter(filterFn, value, column) { - return (filterFn && filterFn.autoRemove ? filterFn.autoRemove(value, column) : false) || typeof value === "undefined" || typeof value === "string" && !value; -} -var sum = (columnId, _leafRows, childRows) => { - return childRows.reduce((sum2, next) => { - const nextValue = next.getValue(columnId); - return sum2 + (typeof nextValue === "number" ? nextValue : 0); - }, 0); -}; -var min = (columnId, _leafRows, childRows) => { - let min3; - childRows.forEach((row) => { - const value = row.getValue(columnId); - if (value != null && (min3 > value || min3 === void 0 && value >= value)) { - min3 = value; - } - }); - return min3; -}; -var max = (columnId, _leafRows, childRows) => { - let max3; - childRows.forEach((row) => { - const value = row.getValue(columnId); - if (value != null && (max3 < value || max3 === void 0 && value >= value)) { - max3 = value; - } - }); - return max3; -}; -var extent = (columnId, _leafRows, childRows) => { - let min3; - let max3; - childRows.forEach((row) => { - const value = row.getValue(columnId); - if (value != null) { - if (min3 === void 0) { - if (value >= value) - min3 = max3 = value; - } else { - if (min3 > value) - min3 = value; - if (max3 < value) - max3 = value; - } - } - }); - return [min3, max3]; -}; -var mean = (columnId, leafRows) => { - let count2 = 0; - let sum2 = 0; - leafRows.forEach((row) => { - let value = row.getValue(columnId); - if (value != null && (value = +value) >= value) { - ++count2, sum2 += value; - } - }); - if (count2) - return sum2 / count2; - return; -}; -var median = (columnId, leafRows) => { - if (!leafRows.length) { - return; - } - let min3 = 0; - let max3 = 0; - leafRows.forEach((row) => { - let value = row.getValue(columnId); - if (typeof value === "number") { - min3 = Math.min(min3, value); - max3 = Math.max(max3, value); - } - }); - return (min3 + max3) / 2; -}; -var unique = (columnId, leafRows) => { - return Array.from(new Set(leafRows.map((d5) => d5.getValue(columnId))).values()); -}; -var uniqueCount = (columnId, leafRows) => { - return new Set(leafRows.map((d5) => d5.getValue(columnId))).size; -}; -var count = (_columnId, leafRows) => { - return leafRows.length; -}; -var aggregationFns = { - sum, - min, - max, - extent, - mean, - median, - unique, - uniqueCount, - count + +// 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 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; - }, - aggregationFn: "auto" - }; - }, - getInitialState: (state) => { - return { - grouping: [], - ...state - }; - }, - getDefaultOptions: (table) => { - return { - onGroupingChange: makeStateUpdater("grouping", table), - groupedColumnMode: "reorder" - }; - }, - createColumn: (column, table) => { - return { - toggleGrouping: () => { - table.setGrouping((old) => { - if (old == null ? void 0 : old.includes(column.id)) { - return old.filter((d5) => d5 !== column.id); - } - return [...old != null ? old : [], column.id]; - }); - }, - getCanGroup: () => { - var _ref, _ref2, _ref3, _column$columnDef$ena; - return (_ref = (_ref2 = (_ref3 = (_column$columnDef$ena = column.columnDef.enableGrouping) != null ? _column$columnDef$ena : true) != null ? _ref3 : table.options.enableGrouping) != null ? _ref2 : true) != null ? _ref : !!column.accessorFn; - }, - getIsGrouped: () => { - var _a2; - return (_a2 = table.getState().grouping) == null ? void 0 : _a2.includes(column.id); - }, - getGroupedIndex: () => { - var _a2; - return (_a2 = table.getState().grouping) == null ? void 0 : _a2.indexOf(column.id); - }, - getToggleGroupingHandler: () => { - const canGroup = column.getCanGroup(); - return () => { - if (!canGroup) - return; - column.toggleGrouping(); - }; - }, - getAutoAggregationFn: () => { - const firstRow = table.getCoreRowModel().flatRows[0]; - const value = firstRow == null ? void 0 : firstRow.getValue(column.id); - if (typeof value === "number") { - return aggregationFns.sum; - } - if (Object.prototype.toString.call(value) === "[object Date]") { - return aggregationFns.extent; - } - }, - getAggregationFn: () => { - var _a2; - var _table$options$aggreg; - 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]; - } - }; - }, - createTable: (table) => { - return { - setGrouping: (updater) => { - var _a2, _b2; - return (_b2 = (_a2 = table.options).onGroupingChange) == null ? void 0 : _b2.call(_a2, 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 : []); - }, - getPreGroupedRowModel: () => table.getFilteredRowModel(), - getGroupedRowModel: () => { - if (!table._getGroupedRowModel && table.options.getGroupedRowModel) { - table._getGroupedRowModel = table.options.getGroupedRowModel(table); - } - if (table.options.manualGrouping || !table._getGroupedRowModel) { - return table.getPreGroupedRowModel(); - } - return table._getGroupedRowModel(); - } - }; - }, - createRow: (row) => { - return { - getIsGrouped: () => !!row.groupingColumnId, - _groupingValuesCache: {} - }; - }, - createCell: (cell, column, row, table) => { - return { - getIsGrouped: () => column.getIsGrouped() && column.id === row.groupingColumnId, - getIsPlaceholder: () => !cell.getIsGrouped() && column.getIsGrouped(), - getIsAggregated: () => { - var _a2; - return !cell.getIsGrouped() && !cell.getIsPlaceholder() && !!((_a2 = row.subRows) == null ? void 0 : _a2.length); - } - }; - } +var quarterValues = { + narrow: ["1", "2", "3", "4"], + abbreviated: ["Q1", "Q2", "Q3", "Q4"], + wide: ["1st quarter", "2nd quarter", "3rd quarter", "4th quarter"] }; -function orderColumns(leafColumns, grouping, groupedColumnMode) { - if (!(grouping == null ? void 0 : grouping.length) || !groupedColumnMode) { - return leafColumns; - } - const nonGroupingColumns = leafColumns.filter((col) => !grouping.includes(col.id)); - if (groupedColumnMode === "remove") { - return nonGroupingColumns; - } - const groupingColumns = grouping.map((g4) => leafColumns.find((col) => col.id === g4)).filter(Boolean); - return [...groupingColumns, ...nonGroupingColumns]; -} -var Ordering = { - getInitialState: (state) => { - return { - columnOrder: [], - ...state - }; - }, - getDefaultOptions: (table) => { - return { - onColumnOrderChange: makeStateUpdater("columnOrder", table) - }; - }, - createTable: (table) => { - return { - setColumnOrder: (updater) => { - var _a2, _b2; - return (_b2 = (_a2 = table.options).onColumnOrderChange) == null ? void 0 : _b2.call(_a2, 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)) { - orderedColumns = columns; - } else { - const columnOrderCopy = [...columnOrder]; - const columnsCopy = [...columns]; - while (columnsCopy.length && columnOrderCopy.length) { - const targetColumnId = columnOrderCopy.shift(); - const foundIndex = columnsCopy.findIndex((d5) => d5.id === targetColumnId); - if (foundIndex > -1) { - orderedColumns.push(columnsCopy.splice(foundIndex, 1)[0]); - } - } - orderedColumns = [...orderedColumns, ...columnsCopy]; - } - return orderColumns(orderedColumns, grouping, groupedColumnMode); - }, { - key: "getOrderColumnsFn" - }) - }; - } +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 defaultPageIndex = 0; -var defaultPageSize = 10; -var getDefaultPaginationState = () => ({ - pageIndex: defaultPageIndex, - pageSize: defaultPageSize -}); -var Pagination = { - getInitialState: (state) => { - return { - ...state, - pagination: { - ...getDefaultPaginationState(), - ...state == null ? void 0 : state.pagination - } - }; - }, - getDefaultOptions: (table) => { - return { - onPaginationChange: makeStateUpdater("pagination", table) - }; - }, - createTable: (table) => { - let registered = false; - let queued = false; - return { - _autoResetPageIndex: () => { - var _ref, _table$options$autoRe; - if (!registered) { - table._queue(() => { - registered = true; - }); - return; - } - if ((_ref = (_table$options$autoRe = table.options.autoResetAll) != null ? _table$options$autoRe : table.options.autoResetPageIndex) != null ? _ref : !table.options.manualPagination) { - if (queued) - return; - queued = true; - table._queue(() => { - table.resetPageIndex(); - queued = false; - }); - } - }, - setPagination: (updater) => { - 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); - }, - resetPagination: (defaultState) => { - var _table$initialState$p; - table.setPagination(defaultState ? getDefaultPaginationState() : (_table$initialState$p = table.initialState.pagination) != null ? _table$initialState$p : getDefaultPaginationState()); - }, - setPageIndex: (updater) => { - table.setPagination((old) => { - let pageIndex = functionalUpdate(updater, old.pageIndex); - const maxPageIndex = typeof table.options.pageCount === "undefined" || table.options.pageCount === -1 ? Number.MAX_SAFE_INTEGER : table.options.pageCount - 1; - pageIndex = Math.max(0, Math.min(pageIndex, maxPageIndex)); - return { - ...old, - pageIndex - }; - }); - }, - resetPageIndex: (defaultState) => { - var _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); - }, - 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); - }, - setPageSize: (updater) => { - table.setPagination((old) => { - const pageSize = Math.max(1, functionalUpdate(updater, old.pageSize)); - const topRowIndex = old.pageSize * old.pageIndex; - const pageIndex = Math.floor(topRowIndex / pageSize); - return { - ...old, - pageIndex, - pageSize - }; - }); - }, - setPageCount: (updater) => table.setPagination((old) => { - var _table$options$pageCo; - let newPageCount = functionalUpdate(updater, (_table$options$pageCo = table.options.pageCount) != null ? _table$options$pageCo : -1); - if (typeof newPageCount === "number") { - newPageCount = Math.max(-1, newPageCount); - } - return { - ...old, - pageCount: newPageCount - }; - }), - getPageOptions: memo(() => [table.getPageCount()], (pageCount) => { - let pageOptions = []; - if (pageCount && pageCount > 0) { - pageOptions = [...new Array(pageCount)].fill(null).map((_4, i4) => i4); - } - return pageOptions; - }, { - key: "getPageOptions", - debug: () => { - var _table$options$debugA; - return (_table$options$debugA = table.options.debugAll) != null ? _table$options$debugA : table.options.debugTable; - } - }), - getCanPreviousPage: () => table.getState().pagination.pageIndex > 0, - getCanNextPage: () => { - const { - pageIndex - } = table.getState().pagination; - const pageCount = table.getPageCount(); - if (pageCount === -1) { - return true; - } - if (pageCount === 0) { - return false; - } - return pageIndex < pageCount - 1; - }, - previousPage: () => { - return table.setPageIndex((old) => old - 1); - }, - nextPage: () => { - return table.setPageIndex((old) => { - return old + 1; - }); - }, - getPrePaginationRowModel: () => table.getExpandedRowModel(), - getPaginationRowModel: () => { - if (!table._getPaginationRowModel && table.options.getPaginationRowModel) { - table._getPaginationRowModel = table.options.getPaginationRowModel(table); - } - if (table.options.manualPagination || !table._getPaginationRowModel) { - return table.getPrePaginationRowModel(); - } - return table._getPaginationRowModel(); - }, - getPageCount: () => { - var _table$options$pageCo2; - return (_table$options$pageCo2 = table.options.pageCount) != null ? _table$options$pageCo2 : Math.ceil(table.getPrePaginationRowModel().rows.length / table.getState().pagination.pageSize); - } - }; - } +var 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 getDefaultPinningState = () => ({ - left: [], - right: [] -}); -var Pinning = { - getInitialState: (state) => { - return { - columnPinning: getDefaultPinningState(), - ...state - }; - }, - getDefaultOptions: (table) => { - return { - onColumnPinningChange: makeStateUpdater("columnPinning", table) - }; - }, - createColumn: (column, table) => { - return { - pin: (position) => { - const columnIds = column.getLeafColumns().map((d5) => d5.id).filter(Boolean); - table.setColumnPinning((old) => { - var _old$left3, _old$right3; - if (position === "right") { - var _old$left, _old$right; - return { - left: ((_old$left = old == null ? void 0 : old.left) != null ? _old$left : []).filter((d5) => !(columnIds == null ? 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] - }; - } - 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))) - }; - } - 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))) - }; - }); - }, - getCanPin: () => { - const leafColumns = column.getLeafColumns(); - return leafColumns.some((d5) => { - var _d$columnDef$enablePi, _table$options$enable; - return ((_d$columnDef$enablePi = d5.columnDef.enablePinning) != null ? _d$columnDef$enablePi : true) && ((_table$options$enable = table.options.enablePinning) != null ? _table$options$enable : true); - }); - }, - getIsPinned: () => { - const leafColumnIds = column.getLeafColumns().map((d5) => d5.id); - const { - left, - right - } = table.getState().columnPinning; - const isLeft = leafColumnIds.some((d5) => left == null ? void 0 : left.includes(d5)); - const isRight = leafColumnIds.some((d5) => right == null ? void 0 : right.includes(d5)); - return isLeft ? "left" : isRight ? "right" : false; - }, - getPinnedIndex: () => { - var _a2, _b2; - var _table$getState$colum; - 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; - } - }; - }, - createRow: (row, table) => { - return { - getCenterVisibleCells: memo(() => [row._getAllVisibleCells(), table.getState().columnPinning.left, table.getState().columnPinning.right], (allCells, left, right) => { - const leftAndRight = [...left != null ? left : [], ...right != null ? right : []]; - return allCells.filter((d5) => !leftAndRight.includes(d5.column.id)); - }, { - key: false, - debug: () => { - var _table$options$debugA; - return (_table$options$debugA = table.options.debugAll) != null ? _table$options$debugA : table.options.debugRows; - } - }), - getLeftVisibleCells: memo(() => [row._getAllVisibleCells(), table.getState().columnPinning.left, ,], (allCells, left) => { - const cells = (left != null ? left : []).map((columnId) => allCells.find((cell) => cell.column.id === columnId)).filter(Boolean).map((d5) => ({ - ...d5, - position: "left" - })); - return cells; - }, { - key: false, - debug: () => { - var _table$options$debugA2; - return (_table$options$debugA2 = table.options.debugAll) != null ? _table$options$debugA2 : table.options.debugRows; - } - }), - getRightVisibleCells: memo(() => [row._getAllVisibleCells(), table.getState().columnPinning.right], (allCells, right) => { - const cells = (right != null ? right : []).map((columnId) => allCells.find((cell) => cell.column.id === columnId)).filter(Boolean).map((d5) => ({ - ...d5, - position: "right" - })); - return cells; - }, { - key: false, - debug: () => { - var _table$options$debugA3; - return (_table$options$debugA3 = table.options.debugAll) != null ? _table$options$debugA3 : table.options.debugRows; - } - }) - }; +var dayPeriodValues = { + narrow: { + am: "a", + pm: "p", + midnight: "mi", + noon: "n", + morning: "morning", + afternoon: "afternoon", + evening: "evening", + night: "night" }, - createTable: (table) => { - return { - setColumnPinning: (updater) => { - var _a2, _b2; - return (_b2 = (_a2 = table.options).onColumnPinningChange) == null ? void 0 : _b2.call(_a2, 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()); - }, - getIsSomeColumnsPinned: (position) => { - var _a2, _b2, _c2; - 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)); - } - return Boolean((_c2 = pinningState[position]) == null ? void 0 : _c2.length); - }, - getLeftLeafColumns: memo(() => [table.getAllLeafColumns(), table.getState().columnPinning.left], (allColumns, left) => { - return (left != null ? left : []).map((columnId) => allColumns.find((column) => column.id === columnId)).filter(Boolean); - }, { - key: "getLeftLeafColumns", - debug: () => { - var _table$options$debugA4; - return (_table$options$debugA4 = table.options.debugAll) != null ? _table$options$debugA4 : table.options.debugColumns; - } - }), - getRightLeafColumns: memo(() => [table.getAllLeafColumns(), table.getState().columnPinning.right], (allColumns, right) => { - return (right != null ? right : []).map((columnId) => allColumns.find((column) => column.id === columnId)).filter(Boolean); - }, { - key: "getRightLeafColumns", - debug: () => { - var _table$options$debugA5; - return (_table$options$debugA5 = table.options.debugAll) != null ? _table$options$debugA5 : table.options.debugColumns; - } - }), - getCenterLeafColumns: memo(() => [table.getAllLeafColumns(), table.getState().columnPinning.left, table.getState().columnPinning.right], (allColumns, left, right) => { - const leftAndRight = [...left != null ? left : [], ...right != null ? right : []]; - return allColumns.filter((d5) => !leftAndRight.includes(d5.id)); - }, { - key: "getCenterLeafColumns", - debug: () => { - var _table$options$debugA6; - return (_table$options$debugA6 = table.options.debugAll) != null ? _table$options$debugA6 : table.options.debugColumns; - } - }) - }; + abbreviated: { + am: "AM", + pm: "PM", + midnight: "midnight", + noon: "noon", + morning: "morning", + afternoon: "afternoon", + evening: "evening", + night: "night" + }, + wide: { + am: "a.m.", + pm: "p.m.", + midnight: "midnight", + noon: "noon", + morning: "morning", + afternoon: "afternoon", + evening: "evening", + night: "night" } }; -var RowSelection = { - getInitialState: (state) => { - return { - rowSelection: {}, - ...state - }; +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" }, - getDefaultOptions: (table) => { - return { - onRowSelectionChange: makeStateUpdater("rowSelection", table), - enableRowSelection: true, - enableMultiRowSelection: true, - enableSubRowSelection: true - }; + abbreviated: { + am: "AM", + pm: "PM", + midnight: "midnight", + noon: "noon", + morning: "in the morning", + afternoon: "in the afternoon", + evening: "in the evening", + night: "at night" }, - createTable: (table) => { + wide: { + am: "a.m.", + pm: "p.m.", + midnight: "midnight", + noon: "noon", + morning: "in the morning", + afternoon: "in the afternoon", + evening: "in the evening", + night: "at night" + } +}; +var 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 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 { - setRowSelection: (updater) => { - var _a2, _b2; - return (_b2 = (_a2 = table.options).onRowSelectionChange) == null ? void 0 : _b2.call(_a2, updater); - }, - resetRowSelection: (defaultState) => { - var _table$initialState$r; - return table.setRowSelection(defaultState ? {} : (_table$initialState$r = table.initialState.rowSelection) != null ? _table$initialState$r : {}); - }, - toggleAllRowsSelected: (value) => { - table.setRowSelection((old) => { - value = typeof value !== "undefined" ? value : !table.getIsAllRowsSelected(); - const rowSelection = { - ...old - }; - const preGroupedFlatRows = table.getPreGroupedRowModel().flatRows; - if (value) { - preGroupedFlatRows.forEach((row) => { - if (!row.getCanSelect()) { - return; - } - rowSelection[row.id] = true; - }); - } else { - preGroupedFlatRows.forEach((row) => { - delete rowSelection[row.id]; - }); - } - return rowSelection; - }); - }, - toggleAllPageRowsSelected: (value) => table.setRowSelection((old) => { - const resolvedValue = typeof value !== "undefined" ? value : !table.getIsAllPageRowsSelected(); - const rowSelection = { - ...old - }; - table.getRowModel().rows.forEach((row) => { - mutateRowIsSelected(rowSelection, row.id, resolvedValue, table); - }); - return rowSelection; - }), - getPreSelectedRowModel: () => table.getCoreRowModel(), - getSelectedRowModel: memo(() => [table.getState().rowSelection, table.getCoreRowModel()], (rowSelection, rowModel) => { - if (!Object.keys(rowSelection).length) { - return { - rows: [], - flatRows: [], - rowsById: {} - }; - } - return selectRowsFn(table, rowModel); - }, { - key: "getSelectedRowModel", - debug: () => { - var _table$options$debugA; - return (_table$options$debugA = table.options.debugAll) != null ? _table$options$debugA : table.options.debugTable; - } - }), - getFilteredSelectedRowModel: memo(() => [table.getState().rowSelection, table.getFilteredRowModel()], (rowSelection, rowModel) => { - if (!Object.keys(rowSelection).length) { - return { - rows: [], - flatRows: [], - rowsById: {} - }; - } - return selectRowsFn(table, rowModel); - }, { - key: false, - debug: () => { - var _table$options$debugA2; - return (_table$options$debugA2 = table.options.debugAll) != null ? _table$options$debugA2 : table.options.debugTable; - } - }), - getGroupedSelectedRowModel: memo(() => [table.getState().rowSelection, table.getSortedRowModel()], (rowSelection, rowModel) => { - if (!Object.keys(rowSelection).length) { - return { - rows: [], - flatRows: [], - rowsById: {} - }; - } - return selectRowsFn(table, rowModel); - }, { - key: false, - debug: () => { - var _table$options$debugA3; - return (_table$options$debugA3 = table.options.debugAll) != null ? _table$options$debugA3 : table.options.debugTable; - } - }), - getIsAllRowsSelected: () => { - const preGroupedFlatRows = table.getFilteredRowModel().flatRows; - const { - rowSelection - } = table.getState(); - let isAllRowsSelected = Boolean(preGroupedFlatRows.length && Object.keys(rowSelection).length); - if (isAllRowsSelected) { - if (preGroupedFlatRows.some((row) => row.getCanSelect() && !rowSelection[row.id])) { - isAllRowsSelected = false; - } - } - return isAllRowsSelected; - }, - getIsAllPageRowsSelected: () => { - const paginationFlatRows = table.getPaginationRowModel().flatRows; - const { - rowSelection - } = table.getState(); - let isAllPageRowsSelected = !!paginationFlatRows.length; - if (isAllPageRowsSelected && paginationFlatRows.some((row) => !rowSelection[row.id])) { - isAllPageRowsSelected = false; - } - return isAllPageRowsSelected; - }, - getIsSomeRowsSelected: () => { - var _table$getState$rowSe; - const totalSelected = Object.keys((_table$getState$rowSe = table.getState().rowSelection) != null ? _table$getState$rowSe : {}).length; - return totalSelected > 0 && totalSelected < table.getFilteredRowModel().flatRows.length; - }, - getIsSomePageRowsSelected: () => { - const paginationFlatRows = table.getPaginationRowModel().flatRows; - return table.getIsAllPageRowsSelected() ? false : paginationFlatRows.some((d5) => d5.getIsSelected() || d5.getIsSomeSelected()); - }, - getToggleAllRowsSelectedHandler: () => { - return (e4) => { - table.toggleAllRowsSelected(e4.target.checked); - }; - }, - getToggleAllPageRowsSelectedHandler: () => { - return (e4) => { - table.toggleAllPageRowsSelected(e4.target.checked); - }; - } + value, + rest }; - }, - createRow: (row, table) => { + }; +} +function findKey(object, predicate) { + for (var key2 in object) { + if (object.hasOwnProperty(key2) && predicate(object[key2])) { + return key2; + } + } + return void 0; +} +function findIndex(array, predicate) { + for (var key2 = 0; key2 < array.length; key2++) { + if (predicate(array[key2])) { + return key2; + } + } + return void 0; +} + +// node_modules/date-fns/esm/locale/_lib/buildMatchPatternFn/index.js +function buildMatchPatternFn(args) { + return function(string) { + var options = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {}; + var matchResult = string.match(args.matchPattern); + if (!matchResult) + return null; + var matchedString = matchResult[0]; + var parseResult = string.match(args.parsePattern); + if (!parseResult) + return null; + var value = args.valueCallback ? args.valueCallback(parseResult[0]) : parseResult[0]; + value = options.valueCallback ? options.valueCallback(value) : value; + var rest = string.slice(matchedString.length); return { - toggleSelected: (value) => { - const isSelected = row.getIsSelected(); - table.setRowSelection((old) => { - value = typeof value !== "undefined" ? value : !isSelected; - if (isSelected === value) { - return old; - } - const selectedRowIds = { - ...old - }; - mutateRowIsSelected(selectedRowIds, row.id, value, table); - return selectedRowIds; - }); - }, - getIsSelected: () => { - const { - rowSelection - } = table.getState(); - return isRowSelected(row, rowSelection); - }, - getIsSomeSelected: () => { - const { - rowSelection - } = table.getState(); - return isSubRowSelected(row, rowSelection) === "some"; - }, - getIsAllSubRowsSelected: () => { - const { - rowSelection - } = table.getState(); - return isSubRowSelected(row, rowSelection) === "all"; - }, - getCanSelect: () => { - var _table$options$enable; - if (typeof table.options.enableRowSelection === "function") { - return table.options.enableRowSelection(row); - } - return (_table$options$enable = table.options.enableRowSelection) != null ? _table$options$enable : true; - }, - getCanSelectSubRows: () => { - var _table$options$enable2; - if (typeof table.options.enableSubRowSelection === "function") { - return table.options.enableSubRowSelection(row); - } - return (_table$options$enable2 = table.options.enableSubRowSelection) != null ? _table$options$enable2 : true; - }, - getCanMultiSelect: () => { - var _table$options$enable3; - if (typeof table.options.enableMultiRowSelection === "function") { - return table.options.enableMultiRowSelection(row); - } - return (_table$options$enable3 = table.options.enableMultiRowSelection) != null ? _table$options$enable3 : true; - }, - getToggleSelectedHandler: () => { - const canSelect = row.getCanSelect(); - return (e4) => { - var _a2; - if (!canSelect) - return; - row.toggleSelected((_a2 = e4.target) == null ? void 0 : _a2.checked); - }; - } + value, + rest }; + }; +} + +// node_modules/date-fns/esm/locale/en-US/_lib/match/index.js +var matchOrdinalNumberPattern = /^(\d+)(th|st|nd|rd)?/i; +var parseOrdinalNumberPattern = /\d+/i; +var matchEraPatterns = { + narrow: /^(b|a)/i, + abbreviated: /^(b\.?\s?c\.?|b\.?\s?c\.?\s?e\.?|a\.?\s?d\.?|c\.?\s?e\.?)/i, + wide: /^(before christ|before common era|anno domini|common era)/i +}; +var parseEraPatterns = { + any: [/^b/i, /^(a|c)/i] +}; +var matchQuarterPatterns = { + narrow: /^[1234]/i, + abbreviated: /^q[1234]/i, + wide: /^[1234](th|st|nd|rd)? quarter/i +}; +var parseQuarterPatterns = { + any: [/1/i, /2/i, /3/i, /4/i] +}; +var matchMonthPatterns = { + narrow: /^[jfmasond]/i, + abbreviated: /^(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)/i, + wide: /^(january|february|march|april|may|june|july|august|september|october|november|december)/i +}; +var parseMonthPatterns = { + narrow: [/^j/i, /^f/i, /^m/i, /^a/i, /^m/i, /^j/i, /^j/i, /^a/i, /^s/i, /^o/i, /^n/i, /^d/i], + any: [/^ja/i, /^f/i, /^mar/i, /^ap/i, /^may/i, /^jun/i, /^jul/i, /^au/i, /^s/i, /^o/i, /^n/i, /^d/i] +}; +var matchDayPatterns = { + narrow: /^[smtwf]/i, + short: /^(su|mo|tu|we|th|fr|sa)/i, + abbreviated: /^(sun|mon|tue|wed|thu|fri|sat)/i, + wide: /^(sunday|monday|tuesday|wednesday|thursday|friday|saturday)/i +}; +var parseDayPatterns = { + narrow: [/^s/i, /^m/i, /^t/i, /^w/i, /^t/i, /^f/i, /^s/i], + any: [/^su/i, /^m/i, /^tu/i, /^w/i, /^th/i, /^f/i, /^sa/i] +}; +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 mutateRowIsSelected = (selectedRowIds, id2, value, table) => { - var _a2; - const row = table.getRow(id2); - if (value) { - if (!row.getCanMultiSelect()) { - Object.keys(selectedRowIds).forEach((key2) => delete selectedRowIds[key2]); - } - if (row.getCanSelect()) { - selectedRowIds[id2] = true; - } - } else { - delete selectedRowIds[id2]; +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"); } - if (((_a2 = row.subRows) == null ? void 0 : _a2.length) && row.getCanSelectSubRows()) { - row.subRows.forEach((row2) => mutateRowIsSelected(selectedRowIds, row2.id, value, table)); + 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"); } -}; -function selectRowsFn(table, rowModel) { - const rowSelection = table.getState().rowSelection; - const newSelectedFlatRows = []; - const newSelectedRowsById = {}; - const recurseRows = function(rows, depth) { - return rows.map((row) => { - var _a2; - const isSelected = isRowSelected(row, rowSelection); - if (isSelected) { - newSelectedFlatRows.push(row); - newSelectedRowsById[row.id] = row; - } - if ((_a2 = row.subRows) == null ? void 0 : _a2.length) { - row = { - ...row, - subRows: recurseRows(row.subRows) - }; + 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"); + } + var timezoneOffset = getTimezoneOffsetInMilliseconds(originalDate); + var utcDate = subMilliseconds(originalDate, timezoneOffset); + var formatterOptions = { + firstWeekContainsDate, + weekStartsOn, + locale: locale2, + _originalDate: originalDate + }; + var result = formatStr.match(longFormattingTokensRegExp).map(function(substring) { + var firstCharacter = substring[0]; + if (firstCharacter === "p" || firstCharacter === "P") { + var longFormatter = longFormatters_default[firstCharacter]; + return longFormatter(substring, locale2.formatLong); + } + return substring; + }).join("").match(formattingTokensRegExp).map(function(substring) { + if (substring === "''") { + 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)); } - if (isSelected) { - return row; + if (!(options !== null && options !== void 0 && options.useAdditionalDayOfYearTokens) && isProtectedDayOfYearToken(substring)) { + throwProtectedError(substring, dirtyFormatStr, String(dirtyDate)); } - }).filter(Boolean); - }; - return { - rows: recurseRows(rowModel.rows), - flatRows: newSelectedFlatRows, - rowsById: newSelectedRowsById - }; + return formatter(utcDate, substring, locale2.localize, formatterOptions); + } + if (firstCharacter.match(unescapedLatinCharacterRegExp)) { + throw new RangeError("Format string contains an unescaped latin alphabet character `" + firstCharacter + "`"); + } + return substring; + }).join(""); + return result; } -function isRowSelected(row, selection) { - var _selection$row$id; - return (_selection$row$id = selection[row.id]) != null ? _selection$row$id : false; +function cleanEscapedString(input) { + var matched = input.match(escapedStringRegExp); + if (!matched) { + return input; + } + return matched[1].replace(doubleQuoteRegExp, "'"); } -function isSubRowSelected(row, selection, table) { - if (row.subRows && row.subRows.length) { - let allChildrenSelected = true; - let someSelected = false; - row.subRows.forEach((subRow) => { - if (someSelected && !allChildrenSelected) { - return; + +// node_modules/date-fns/esm/_lib/assign/index.js +function assign(target, object) { + if (target == null) { + throw new TypeError("assign requires that input parameter not be null or undefined"); + } + for (var property in object) { + if (Object.prototype.hasOwnProperty.call(object, property)) { + ; + target[property] = object[property]; + } + } + return target; +} + +// node_modules/date-fns/esm/_lib/cloneObject/index.js +function cloneObject(object) { + return assign({}, object); +} + +// 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); } - if (isRowSelected(subRow, selection)) { - someSelected = true; + } else { + if (minutes === 0) { + return locale2.formatDistance("lessThanXMinutes", 1, localizeOptions); } else { - allChildrenSelected = false; + return locale2.formatDistance("xMinutes", minutes, localizeOptions); } - }); - return allChildrenSelected ? "all" : someSelected ? "some" : false; + } + } 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 false; } -var reSplitAlphaNumeric = /([0-9]+)/gm; -var alphanumeric = (rowA, rowB, columnId) => { - return compareAlphanumeric(toString(rowA.getValue(columnId)).toLowerCase(), toString(rowB.getValue(columnId)).toLowerCase()); -}; -var alphanumericCaseSensitive = (rowA, rowB, columnId) => { - return compareAlphanumeric(toString(rowA.getValue(columnId)), toString(rowB.getValue(columnId))); -}; -var text = (rowA, rowB, columnId) => { - return compareBasic(toString(rowA.getValue(columnId)).toLowerCase(), toString(rowB.getValue(columnId)).toLowerCase()); -}; -var textCaseSensitive = (rowA, rowB, columnId) => { - return compareBasic(toString(rowA.getValue(columnId)), toString(rowB.getValue(columnId))); -}; -var datetime = (rowA, rowB, columnId) => { - const a5 = rowA.getValue(columnId); - const b4 = rowB.getValue(columnId); - return a5 > b4 ? 1 : a5 < b4 ? -1 : 0; -}; -var basic = (rowA, rowB, columnId) => { - return compareBasic(rowA.getValue(columnId), rowB.getValue(columnId)); -}; -function compareBasic(a5, b4) { - return a5 === b4 ? 0 : a5 > b4 ? 1 : -1; + +// 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 toString(a5) { - if (typeof a5 === "number") { - if (isNaN(a5) || a5 === Infinity || a5 === -Infinity) { - return ""; - } - return String(a5); + +// 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; +} + +// node_modules/date-fns/esm/getTime/index.js +function getTime(dirtyDate) { + requiredArgs(1, arguments); + var date = toDate(dirtyDate); + var timestamp = date.getTime(); + return timestamp; +} + +// node_modules/date-fns/esm/getUnixTime/index.js +function getUnixTime(dirtyDate) { + requiredArgs(1, arguments); + return Math.floor(getTime(dirtyDate) / 1e3); +} + +// node_modules/date-fns/esm/getWeekYear/index.js +function getWeekYear(dirtyDate, options) { + var _ref, _ref2, _ref3, _options$firstWeekCon, _options$locale, _options$locale$optio, _defaultOptions$local, _defaultOptions$local2; + requiredArgs(1, arguments); + var date = toDate(dirtyDate); + var year = date.getFullYear(); + var defaultOptions3 = getDefaultOptions(); + var firstWeekContainsDate = toInteger((_ref = (_ref2 = (_ref3 = (_options$firstWeekCon = options === null || options === void 0 ? void 0 : options.firstWeekContainsDate) !== null && _options$firstWeekCon !== void 0 ? _options$firstWeekCon : options === null || options === void 0 ? void 0 : (_options$locale = options.locale) === null || _options$locale === void 0 ? void 0 : (_options$locale$optio = _options$locale.options) === null || _options$locale$optio === void 0 ? void 0 : _options$locale$optio.firstWeekContainsDate) !== null && _ref3 !== void 0 ? _ref3 : defaultOptions3.firstWeekContainsDate) !== null && _ref2 !== void 0 ? _ref2 : (_defaultOptions$local = defaultOptions3.locale) === null || _defaultOptions$local === void 0 ? void 0 : (_defaultOptions$local2 = _defaultOptions$local.options) === null || _defaultOptions$local2 === void 0 ? void 0 : _defaultOptions$local2.firstWeekContainsDate) !== null && _ref !== void 0 ? _ref : 1); + if (!(firstWeekContainsDate >= 1 && firstWeekContainsDate <= 7)) { + throw new RangeError("firstWeekContainsDate must be between 1 and 7 inclusively"); } - if (typeof a5 === "string") { - return a5; + 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 ""; } -function compareAlphanumeric(aStr, bStr) { - const a5 = aStr.split(reSplitAlphaNumeric).filter(Boolean); - const b4 = bStr.split(reSplitAlphaNumeric).filter(Boolean); - while (a5.length && b4.length) { - const aa = a5.shift(); - const bb = b4.shift(); - const an2 = parseInt(aa, 10); - const bn2 = parseInt(bb, 10); - const combo = [an2, bn2].sort(); - if (isNaN(combo[0])) { - if (aa > bb) { - return 1; - } - if (bb > aa) { - return -1; - } - continue; - } - if (isNaN(combo[1])) { - return isNaN(an2) ? -1 : 1; + +// node_modules/date-fns/esm/startOfWeekYear/index.js +function startOfWeekYear(dirtyDate, options) { + var _ref, _ref2, _ref3, _options$firstWeekCon, _options$locale, _options$locale$optio, _defaultOptions$local, _defaultOptions$local2; + requiredArgs(1, arguments); + var 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/contexts/fm.ts +var import_lodash = __toESM(require_lodash()); +var import_obsidian3 = require("obsidian"); + +// src/utils/contexts/dv.ts +var import_obsidian2 = require("obsidian"); +var LocationWrapper = { + "fullLine": { start: "", end: "" }, + "brackets": { start: "[", end: "]" }, + "parenthesis": { start: "(", end: ")" } +}; +var fieldComponents = ["inQuote", "inList", "startStyle", "attribute", "endStyle", "beforeSeparatorSpacer", "afterSeparatorSpacer", "values"]; +var genericFieldRegex = "(?>(\\s+)?)?(?- )?(?[_\\*~`]*)(?[0-9\\w\\p{Letter}\\p{Emoji_Presentation}][-0-9\\w\\p{Letter}\\p{Emoji_Presentation}\\s]*)(?[_\\*~`]*)(?\\s*)"; +var inlineFieldRegex = (attribute) => `(?>(\\s+)?)?(?- )?(?[_\\*~\`]*)(?${attribute})(?[_\\*~\`]*)(?\\s*)::(?\\s*)`; +var fullLineRegex = new RegExp(`^${genericFieldRegex}::\\s*(?.*)?`, "u"); +var inSentenceRegexBrackets = new RegExp(`\\[${genericFieldRegex}::\\s*(?[^\\]]+)?\\]`, "gu"); +var inSentenceRegexPar = new RegExp(`\\(${genericFieldRegex}::\\s*(?[^\\)]+)?\\)`, "gu"); +var encodeLink = (value) => { + return value ? value.replace(/\[\[/g, "\u{1F54C}\u{1F527}").replace(/\]\]/g, "\u{1F413}\u{1F400}") : value; +}; +var decodeLink = (value) => { + return value ? value.replace(/🕌🔧/gu, "[[").replace(/🐓🐀/gu, "]]") : value; +}; +var matchInlineFields = (regex, line, attribute, input, location = "fullLine") => { + const sR = line.matchAll(regex); + let next = sR.next(); + const newFields = []; + while (!next.done) { + const match2 = next.value; + if (match2.groups && Object.keys(match2.groups).every((j4) => fieldComponents.includes(j4))) { + const { inList, inQuote, startStyle, endStyle, beforeSeparatorSpacer, afterSeparatorSpacer, values } = match2.groups; + const inputArray = input ? input.replace(/(\,\s+)/g, ",").split(",") : [""]; + const newValue = inputArray.length == 1 ? inputArray[0] : `${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}` + }); } - if (an2 > bn2) { - return 1; + next = sR.next(); + } + return newFields; +}; +async function replaceValues(plugin, fileOrFilePath, attribute, input, previousItemsCount = 0) { + var _a2, _b2; + let file; + if (fileOrFilePath instanceof import_obsidian2.TFile) { + file = fileOrFilePath; + } else { + const _file = plugin.app.vault.getAbstractFileByPath(fileOrFilePath); + if (_file instanceof import_obsidian2.TFile && _file.extension == "md") { + file = _file; + } else { + throw Error("path doesn't correspond to a proper file"); } - if (bn2 > an2) { - return -1; + } + 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_obsidian2.MarkdownView)) == null ? void 0 : _b2.editor; + if (editor) { + const lineNumber = editor.getCursor().line; + editor.setCursor({ line: editor.getCursor().line, ch: editor.getLine(lineNumber).length }); } - return a5.length - b4.length; } -var sortingFns = { - alphanumeric, - alphanumericCaseSensitive, - text, - textCaseSensitive, - datetime, - basic -}; -var Sorting = { - getInitialState: (state) => { - return { - sorting: [], - ...state - }; - }, - getDefaultColumnDef: () => { - return { - sortingFn: "auto" - }; - }, - getDefaultOptions: (table) => { - return { - onSortingChange: makeStateUpdater("sorting", table), - isMultiSortEvent: (e4) => { - return e4.shiftKey; - } - }; - }, - createColumn: (column, table) => { - return { - getAutoSortingFn: () => { - const firstRows = table.getFilteredRowModel().flatRows.slice(10); - let isString = false; - for (const row of firstRows) { - const value = row == null ? void 0 : row.getValue(column.id); - if (Object.prototype.toString.call(value) === "[object Date]") { - return sortingFns.datetime; - } - if (typeof value === "string") { - isString = true; - if (value.split(reSplitAlphaNumeric).length > 1) { - return sortingFns.alphanumeric; - } - } - } - if (isString) { - return sortingFns.text; - } - return sortingFns.basic; - }, - getAutoSortDir: () => { - const firstRow = table.getFilteredRowModel().flatRows[0]; - const value = firstRow == null ? void 0 : firstRow.getValue(column.id); - if (typeof value === "string") { - return "asc"; - } - return "desc"; - }, - getSortingFn: () => { - var _a2; - var _table$options$sortin; - 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]; - }, - toggleSorting: (desc, multi) => { - const nextSortingOrder = column.getNextSortingOrder(); - const hasManualValue = typeof desc !== "undefined" && desc !== null; - table.setSorting((old) => { - const existingSorting = old == null ? void 0 : old.find((d5) => d5.id === column.id); - const existingIndex = old == null ? void 0 : old.findIndex((d5) => d5.id === column.id); - let newSorting = []; - let sortAction; - let nextDesc = hasManualValue ? desc : nextSortingOrder === "desc"; - if ((old == null ? void 0 : old.length) && column.getCanMultiSort() && multi) { - if (existingSorting) { - sortAction = "toggle"; - } else { - sortAction = "add"; - } - } else { - if ((old == null ? void 0 : old.length) && existingIndex !== old.length - 1) { - sortAction = "replace"; - } else if (existingSorting) { - sortAction = "toggle"; - } else { - sortAction = "replace"; - } - } - if (sortAction === "toggle") { - if (!hasManualValue) { - if (!nextSortingOrder) { - sortAction = "remove"; - } - } - } - if (sortAction === "add") { - var _table$options$maxMul; - newSorting = [...old, { - id: column.id, - desc: nextDesc - }]; - newSorting.splice(0, newSorting.length - ((_table$options$maxMul = table.options.maxMultiSortColCount) != null ? _table$options$maxMul : Number.MAX_SAFE_INTEGER)); - } else if (sortAction === "toggle") { - newSorting = old.map((d5) => { - if (d5.id === column.id) { - return { - ...d5, - desc: nextDesc - }; - } - return d5; - }); - } else if (sortAction === "remove") { - newSorting = old.filter((d5) => d5.id !== column.id); + +// 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, context[f4]); } else { - newSorting = [{ - id: column.id, - desc: nextDesc - }]; + frontmatter[f4] = valueForFrontmatter(col.type, context[f4]); } - return newSorting; - }); - }, - getFirstSortDir: () => { - var _ref, _column$columnDef$sor; - const sortDescFirst = (_ref = (_column$columnDef$sor = column.columnDef.sortDescFirst) != null ? _column$columnDef$sor : table.options.sortDescFirst) != null ? _ref : column.getAutoSortDir() === "desc"; - return sortDescFirst ? "desc" : "asc"; - }, - getNextSortingOrder: (multi) => { - var _table$options$enable, _table$options$enable2; - const firstSortDirection = column.getFirstSortDir(); - const isSorted = column.getIsSorted(); - if (!isSorted) { - return firstSortDirection; - } - if (isSorted !== firstSortDirection && ((_table$options$enable = table.options.enableSortingRemoval) != null ? _table$options$enable : true) && (multi ? (_table$options$enable2 = table.options.enableMultiRemove) != null ? _table$options$enable2 : true : true)) { - return false; - } - return isSorted === "desc" ? "asc" : "desc"; - }, - getCanSort: () => { - var _column$columnDef$ena, _table$options$enable3; - return ((_column$columnDef$ena = column.columnDef.enableSorting) != null ? _column$columnDef$ena : true) && ((_table$options$enable3 = table.options.enableSorting) != null ? _table$options$enable3 : true) && !!column.accessorFn; - }, - getCanMultiSort: () => { - var _ref2, _column$columnDef$ena2; - return (_ref2 = (_column$columnDef$ena2 = column.columnDef.enableMultiSort) != null ? _column$columnDef$ena2 : table.options.enableMultiSort) != null ? _ref2 : !!column.accessorFn; - }, - getIsSorted: () => { - var _a2; - const columnSort = (_a2 = table.getState().sorting) == null ? void 0 : _a2.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; - }, - clearSorting: () => { - table.setSorting((old) => (old == null ? void 0 : 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); - }; - } - }; - }, - createTable: (table) => { - return { - setSorting: (updater) => { - var _a2, _b2; - return (_b2 = (_a2 = table.options).onSortingChange) == null ? void 0 : _b2.call(_a2, 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 : []); - }, - getPreSortedRowModel: () => table.getGroupedRowModel(), - getSortedRowModel: () => { - if (!table._getSortedRowModel && table.options.getSortedRowModel) { - table._getSortedRowModel = table.options.getSortedRowModel(table); - } - if (table.options.manualSorting || !table._getSortedRowModel) { - return table.getPreSortedRowModel(); + } else { + frontmatter[f4] = valueForFrontmatter(col.type, context[f4]); } - return table._getSortedRowModel(); - } - }; + }); + }); } }; -var Visibility = { - getInitialState: (state) => { - return { - columnVisibility: {}, - ...state - }; - }, - getDefaultOptions: (table) => { - return { - onColumnVisibilityChange: makeStateUpdater("columnVisibility", table) - }; - }, - createColumn: (column, table) => { - return { - toggleVisibility: (value) => { - if (column.getCanHide()) { - table.setColumnVisibility((old) => ({ - ...old, - [column.id]: value != null ? value : !column.getIsVisible() - })); - } - }, - getIsVisible: () => { - var _a2; - var _table$getState$colum; - return (_table$getState$colum = (_a2 = table.getState().columnVisibility) == null ? void 0 : _a2[column.id]) != null ? _table$getState$colum : true; - }, - getCanHide: () => { - var _column$columnDef$ena, _table$options$enable; - return ((_column$columnDef$ena = column.columnDef.enableHiding) != null ? _column$columnDef$ena : true) && ((_table$options$enable = table.options.enableHiding) != null ? _table$options$enable : true); - }, - getToggleVisibilityHandler: () => { - return (e4) => { - var _a2; - (_a2 = column.toggleVisibility) == null ? void 0 : _a2.call(column, e4.target.checked); - }; - } - }; - }, - createRow: (row, table) => { - return { - _getAllVisibleCells: memo(() => [row.getAllCells(), table.getState().columnVisibility], (cells) => { - return cells.filter((cell) => cell.column.getIsVisible()); - }, { - key: false, - debug: () => { - var _table$options$debugA; - return (_table$options$debugA = table.options.debugAll) != null ? _table$options$debugA : table.options.debugRows; - } - }), - getVisibleCells: memo(() => [row.getLeftVisibleCells(), row.getCenterVisibleCells(), row.getRightVisibleCells()], (left, center, right) => [...left, ...center, ...right], { - key: "row.getVisibleCells", - debug: () => { - var _table$options$debugA2; - return (_table$options$debugA2 = table.options.debugAll) != null ? _table$options$debugA2 : table.options.debugRows; - } - }) - }; - }, - 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); - }); - }, { - key: key2, - debug: () => { - var _table$options$debugA3; - return (_table$options$debugA3 = table.options.debugAll) != null ? _table$options$debugA3 : table.options.debugColumns; - } - }); - }; - return { - getVisibleFlatColumns: makeVisibleColumnsMethod("getVisibleFlatColumns", () => table.getAllFlatColumns()), - getVisibleLeafColumns: makeVisibleColumnsMethod("getVisibleLeafColumns", () => table.getAllLeafColumns()), - getLeftVisibleLeafColumns: makeVisibleColumnsMethod("getLeftVisibleLeafColumns", () => table.getLeftLeafColumns()), - getRightVisibleLeafColumns: makeVisibleColumnsMethod("getRightVisibleLeafColumns", () => table.getRightLeafColumns()), - getCenterVisibleLeafColumns: makeVisibleColumnsMethod("getCenterVisibleLeafColumns", () => table.getCenterLeafColumns()), - setColumnVisibility: (updater) => { - var _a2, _b2; - return (_b2 = (_a2 = table.options).onColumnVisibilityChange) == null ? void 0 : _b2.call(_a2, updater); - }, - resetColumnVisibility: (defaultState) => { - var _table$initialState$c; - table.setColumnVisibility(defaultState ? {} : (_table$initialState$c = table.initialState.columnVisibility) != null ? _table$initialState$c : {}); - }, - toggleAllColumnsVisible: (value) => { - var _value; - value = (_value = value) != null ? _value : !table.getIsAllColumnsVisible(); - table.setColumnVisibility(table.getAllLeafColumns().reduce((obj, column) => { - var _a2; - return { - ...obj, - [column.id]: !value ? !((_a2 = column.getCanHide) == null ? void 0 : _a2.call(column)) : 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); - }), - getToggleAllColumnsVisibilityHandler: () => { - return (e4) => { - var _a2; - table.toggleAllColumnsVisible((_a2 = e4.target) == null ? void 0 : _a2.checked); - }; - } - }; +var frontMatterForFile = (file) => { + let currentCache; + if (file instanceof import_obsidian3.TFile && app.metadataCache.getFileCache(file) !== null) { + currentCache = app.metadataCache.getFileCache(file); } + return currentCache == null ? void 0 : currentCache.frontmatter; }; -var features = [Headers, Visibility, Ordering, Pinning, Filters, Sorting, Grouping, Expanding, Pagination, RowSelection, ColumnSizing]; -function createTable(options) { - var _options$initialState; - if (options.debugAll || options.debugTable) { - console.info("Creating Table Instance..."); +var frontMatterKeys = (fm) => { + return Object.keys(fm != null ? fm : {}).filter((f4) => f4 != "position"); +}; +var yamlTypeToMDBType = (YAMLtype) => { + switch (YAMLtype) { + case "duration": + return "text"; + break; + case "unknown": + return "text"; + break; } - let table = { - _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)); - }, {}); - const mergeOptions = (options2) => { - if (table.options.mergeOptions) { - return table.options.mergeOptions(defaultOptions3, options2); + 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"; } - return { - ...defaultOptions3, - ...options2 - }; - }; - const coreInitialState = {}; - let initialState = { - ...coreInitialState, - ...(_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; - }); - const queued = []; - let queuedTimeout = false; - const coreInstance = { - _features: features, - options: { - ...defaultOptions3, - ...options - }, - initialState, - _queue: (cb) => { - queued.push(cb); - if (!queuedTimeout) { - queuedTimeout = true; - Promise.resolve().then(() => { - while (queued.length) { - queued.shift()(); - } - queuedTimeout = false; - }).catch((error) => setTimeout(() => { - throw error; - })); - } - }, - reset: () => { - table.setState(table.initialState); - }, - setOptions: (updater) => { - const newOptions = functionalUpdate(updater, table.options); - table.options = mergeOptions(newOptions); - }, - getState: () => { - return table.options.state; - }, - setState: (updater) => { - var _a2, _b2; - (_b2 = (_a2 = table.options).onStateChange) == null ? void 0 : _b2.call(_a2, 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}`; - }, - getCoreRowModel: () => { - if (!table._getCoreRowModel) { - table._getCoreRowModel = table.options.getCoreRowModel(table); - } - return table._getCoreRowModel(); - }, - getRowModel: () => { - return table.getPaginationRowModel(); - }, - getRow: (id2) => { - const row = table.getRowModel().rowsById[id2]; - if (!row) { - if (true) { - throw new Error(`getRow expected an ID, but got ${id2}`); - } - throw new Error(); + if (/^\d{4}-\d{2}-\d{2}$/.test(value)) { + return "date"; + } + if (key2 == "tag" || key2 == "tags") { + return "tag"; + } + if (/\[\[.*?\]\]/.test(value)) { + return "link"; + } + return "text"; + } else if (typeof value === "number") { + return "number"; + } else if (typeof value === "boolean") { + return "boolean"; + } else if (!value) { + return "unknown"; + } else if (Array.isArray(value)) { + if (key2 == "tag" || key2 == "tags") { + return "tag-multi"; + } + if (value.length == 1 && Array.isArray(value[0]) && value[0].length == 1 && typeof value[0][0] === "string") { + return "link"; + } + const types = uniq(value.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"; + } + 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(onlyUniqueProp("name")), + rows: mdb.rows.map((r3) => { + const fmRow = yamlmdb.rows.find((f4) => f4.File == r3.File); + if (fmRow) { + return { + ...r3, + ...fmRow + }; } - return row; + 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; }, - _getDefaultColumnDef: memo(() => [table.options.defaultColumn], (defaultColumn) => { - var _defaultColumn; - defaultColumn = (_defaultColumn = defaultColumn) != null ? _defaultColumn : {}; - return { - header: (props2) => { - const resolvedColumnDef = props2.header.column.columnDef; - if (resolvedColumnDef.accessorKey) { - return resolvedColumnDef.accessorKey; + {} + ); + 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 parseInt(value); + } else if (type == "boolean") { + return value == "true"; + } else if (type.contains("multi")) { + return splitString(value); + } + return value; +}; +var saveFrontmatterValue = (plugin, path, key2, value, type, forceSave) => { + const afile = getAbstractFileAtPath(app, path); + if (afile) { + if (app.fileManager.processFrontMatter) { + app.fileManager.processFrontMatter(afile, (frontmatter) => { + if (plugin.dataViewAPI()) { + if (plugin.dataViewAPI().page(path)[key2] && !frontmatter[key2]) { + replaceValues(plugin, path, key2, value); + } else { + if (key2 in frontmatter || forceSave) { + frontmatter[key2] = valueForFrontmatter(type, value); + } } - if (resolvedColumnDef.accessorFn) { - return resolvedColumnDef.id; + } else { + if (key2 in frontmatter || forceSave) { + frontmatter[key2] = valueForFrontmatter(type, value); } - 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; - }, - ...table._features.reduce((obj, feature) => { - var _a2; - return Object.assign(obj, (_a2 = feature.getDefaultColumnDef) == null ? void 0 : _a2.call(feature)); - }, {}), - ...defaultColumn - }; - }, { - debug: () => { - var _table$options$debugA; - return (_table$options$debugA = table.options.debugAll) != null ? _table$options$debugA : table.options.debugColumns; - }, - key: "getDefaultColumnDef" - }), - _getColumnDefs: () => table.options.columns, - getAllColumns: memo(() => [table._getColumnDefs()], (columnDefs) => { - const recurseColumns = function(columnDefs2, parent, depth) { - if (depth === void 0) { - depth = 0; } - return columnDefs2.map((columnDef) => { - const column = createColumn(table, columnDef, depth, parent); - const groupingColumnDef = columnDef; - column.columns = groupingColumnDef.columns ? recurseColumns(groupingColumnDef.columns, column, depth + 1) : []; - return column; - }); - }; - return recurseColumns(columnDefs); - }, { - key: "getAllColumns", - debug: () => { - var _table$options$debugA2; - return (_table$options$debugA2 = table.options.debugAll) != null ? _table$options$debugA2 : table.options.debugColumns; - } - }), - getAllFlatColumns: memo(() => [table.getAllColumns()], (allColumns) => { - return allColumns.flatMap((column) => { - return column.getFlatColumns(); }); - }, { - key: "getAllFlatColumns", - debug: () => { - var _table$options$debugA3; - return (_table$options$debugA3 = table.options.debugAll) != null ? _table$options$debugA3 : table.options.debugColumns; - } - }), - _getAllFlatColumnsById: memo(() => [table.getAllFlatColumns()], (flatColumns) => { - return flatColumns.reduce((acc, column) => { - acc[column.id] = column; - return acc; - }, {}); - }, { - key: "getAllFlatColumnsById", - debug: () => { - var _table$options$debugA4; - return (_table$options$debugA4 = table.options.debugAll) != null ? _table$options$debugA4 : table.options.debugColumns; - } - }), - getAllLeafColumns: memo(() => [table.getAllColumns(), table._getOrderColumnsFn()], (allColumns, orderColumns2) => { - let leafColumns = allColumns.flatMap((column) => column.getLeafColumns()); - return orderColumns2(leafColumns); - }, { - key: "getAllLeafColumns", - debug: () => { - var _table$options$debugA5; - return (_table$options$debugA5 = table.options.debugAll) != null ? _table$options$debugA5 : table.options.debugColumns; + } + } +}; +var parseFrontMatter = (field, value, dv) => { + const YAMLtype = detectYAMLType(value, field); + switch (YAMLtype) { + 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"); + ; } - }), - getColumn: (columnId) => { - const column = table._getAllFlatColumnsById()[columnId]; - if (!column) { - if (true) { - console.warn(`[Table] Column with id ${columnId} does not exist.`); + 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": + case "tag-multi": + return value.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; } - throw new Error(); + return value.path; } - return column; + break; + case "text": + case "tag": + case "image": + return value; + break; + } + return ""; +}; + +// src/utils/array.ts +var insert = (arr, index, newItem) => [ + ...arr.slice(0, index), + newItem, + ...arr.slice(index) +]; + +// src/utils/sanitize.ts +var sanitizeTableName = (name) => { + return name == null ? void 0 : name.replace(/[^a-z0-9+]+/gi, ""); +}; +var sanitizeColumnName = (name) => { + return name == null ? void 0 : name.replace(/"/g, ``); +}; +var sanitizeSQLStatement = (name) => { + return name == null ? void 0 : name.replace(/'/g, `''`); +}; + +// src/dispatch/mdb.ts +var import_lodash2 = __toESM(require_lodash()); +var import_obsidian4 = require("obsidian"); +var dispatchDatabaseFileChanged = (dbPath, tag) => { + let evt = new CustomEvent(eventTypes.mdbChange, { detail: { dbPath, tag } }); + window.dispatchEvent(evt); +}; +var processFolderDB = async (plugin, folderPath, processor, fallback) => { + let tags = []; + const dbPath = folderContextFromFolder(plugin, folderPath); + const dbFileExists = getAbstractFileAtPath(app, dbPath); + if (dbFileExists) { + const folderDB = await getMDBTable(plugin, "files", dbPath, false); + if (folderDB) { + tags.push(...folderDB.schema.def.split("&")); + const newDB = await processor(folderDB, dbPath); + const promises = tags.map((tag) => { + const tagdbPath = tagContextFromTag(plugin, tag); + const tagFileExists = getAbstractFileAtPath(app, tagdbPath); + if (tagFileExists) { + return consolidateRowsToTag( + plugin, + tagdbPath, + "files", + dbPath, + newDB.rows + ).then((f4) => { + }); + } + }); + return Promise.all(promises); + } else if (fallback) { + await fallback(); } + } else if (fallback) { + await fallback(); + } +}; +var saveDB = async (plugin, dbPath, newTable) => { + return saveMDBToPath(plugin, dbPath, newTable); +}; +var renameRow = (folder, filePath, toFilePath) => { + return { + ...folder, + rows: folder.rows.map( + (f4) => f4.File == filePath && f4._source == "folder" ? { ...f4, File: toFilePath } : f4 + ) }; - 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 table; -} -function createCell(table, row, column, columnId) { - const getRenderValue = () => { - var _cell$getValue; - return (_cell$getValue = cell.getValue()) != null ? _cell$getValue : table.options.renderFallbackValue; +}; +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" + ) }; - const cell = { - id: `${row.id}_${column.id}`, - row, - column, - getValue: () => row.getValue(columnId), - renderValue: getRenderValue, - getContext: memo(() => [table, column, row, cell], (table2, column2, row2, cell2) => ({ - table: table2, - column: column2, - row: row2, - cell: cell2, - getValue: cell2.getValue, - renderValue: cell2.renderValue - }), { - key: "cell.getContext", - debug: () => table.options.debugAll - }) +}; +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 + ) + }; + } + return { ...folder, rows: [...folder.rows, row] }; +}; +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"); + } + ); + return { ...folder, rows: [...folder.rows, ...newRows] }; +}; +var saveContextToFrontmatter = (file, cols, context, plugin) => { + const afile = getAbstractFileAtPath(app, file); + if (afile && afile instanceof import_obsidian4.TFile) + saveContextToFile(afile, cols, context, plugin); +}; +var removeSourceFromTag = async (plugin, tag, source) => { + const dbPath = tagContextFromTag(plugin, tag); + const tagFileExists = getAbstractFileAtPath(app, dbPath); + if (tagFileExists) { + const tagDB = await getMDBTable(plugin, "files", dbPath, true); + 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, dbPath, removeRows(tagDB, source)); + } +}; +var contextShouldExist = async (plugin, tag) => { + const dbPath = tagContextFromTag(plugin, tag); + const tagFileExists = getAbstractFileAtPath(app, dbPath); + if (!tagFileExists) + return false; + return getMDBTable(plugin, "files", dbPath, true).then((f4) => (f4 == null ? void 0 : f4.rows.length) > 0); +}; +var initiateContextIfNotExists = async (plugin, tag) => { + const dbPath = tagContextFromTag(plugin, tag); + const tagFileExists = getAbstractFileAtPath(app, dbPath); + if (tagFileExists) + return false; + return createDefaultDB(plugin, dbPath, true); +}; +var insertContextItems = async (plugin, newPaths, t4) => { + const saveNewContextRows = async (tag, path) => { + const newRow = newPaths.map((newPath) => ({ File: newPath })); + await saveDB(plugin, path, insertRows(tag, newRow)); }; - table._features.forEach((feature) => { - var _a2; - Object.assign(cell, (_a2 = feature.createCell) == null ? void 0 : _a2.call(feature, cell, column, row, table)); - }, {}); - return cell; -} -var createRow = (table, id2, original, rowIndex, depth, subRows) => { - var _a2; - let row = { - id: id2, - index: rowIndex, - original, - depth, - _valuesCache: {}, - _uniqueValuesCache: {}, - getValue: (columnId) => { - if (row._valuesCache.hasOwnProperty(columnId)) { - return row._valuesCache[columnId]; - } - const column = table.getColumn(columnId); - if (!column.accessorFn) { - return void 0; - } - row._valuesCache[columnId] = column.accessorFn(row.original, rowIndex); - return row._valuesCache[columnId]; - }, - getUniqueValues: (columnId) => { - if (row._uniqueValuesCache.hasOwnProperty(columnId)) { - return row._uniqueValuesCache[columnId]; - } - const column = table.getColumn(columnId); - if (!column.accessorFn) { - return void 0; - } - if (!column.columnDef.getUniqueValues) { - row._uniqueValuesCache[columnId] = [row.getValue(columnId)]; - return row._uniqueValuesCache[columnId]; - } - row._uniqueValuesCache[columnId] = column.columnDef.getUniqueValues(row.original, rowIndex); - return row._uniqueValuesCache[columnId]; - }, - renderValue: (columnId) => { - var _row$getValue; - return (_row$getValue = row.getValue(columnId)) != null ? _row$getValue : table.options.renderFallbackValue; - }, - subRows: subRows != null ? subRows : [], - getLeafRows: () => flattenBy(row.subRows, (d5) => d5.subRows), - getAllCells: memo(() => [table.getAllLeafColumns()], (leafColumns) => { - return leafColumns.map((column) => { - return createCell(table, row, column, column.id); - }); - }, { - key: "row.getAllCells", - debug: () => { - var _table$options$debugA; - return (_table$options$debugA = table.options.debugAll) != null ? _table$options$debugA : table.options.debugRows; - } + const dbPath = tagContextFromTag(plugin, t4); + const tagFileExists = getAbstractFileAtPath(app, dbPath); + if (!tagFileExists) { + await createDefaultDB(plugin, dbPath, true); + } + await getMDBTable(plugin, "files", dbPath, true).then( + (tagDB) => saveNewContextRows(tagDB, dbPath).then((f4) => { + }) + ); +}; +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) }; + } + 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) }), - _getAllCellsByColumnId: memo(() => [row.getAllCells()], (allCells) => { - return allCells.reduce((acc, cell) => { - acc[cell.column.id] = cell; - return acc; - }, {}); - }, { - key: false, - debug: () => { - var _table$options$debugA2; - return (_table$options$debugA2 = table.options.debugAll) != null ? _table$options$debugA2 : table.options.debugRows; + {} + ); +}; +var onMetadataChange = async (plugin, file) => { + const folderPath = getFolderPathFromString(file.path); + let tags = []; + const dbPath = folderContextFromFolder(plugin, folderPath); + const dbFileExists = getAbstractFileAtPath(app, dbPath); + if (dbFileExists) { + const folderDB = await getMDBTable(plugin, "files", dbPath, false); + 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, dbPath, newDB); } - }) - }; - 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)); + const promises = tags.map((tag) => { + const tagdbPath = tagContextFromTag(plugin, tag); + const tagFileExists = getAbstractFileAtPath(app, tagdbPath); + if (tagFileExists) { + return getMDBTable(plugin, "files", tagdbPath, false).then( + (tagDB) => { + const newDB2 = { + ...tagDB, + rows: tagDB.rows.map( + (f4) => f4.File == file.path && f4._source == 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, tagdbPath, newDB2); + } + return; + } + ); + } + }); + await Promise.all(promises); + } } - return row; }; -function getCoreRowModel() { - return (table) => memo(() => [table.options.data], (data) => { - const rowModel = { - rows: [], - flatRows: [], - rowsById: {} - }; - const accessRows = function(originalRows, depth, parent) { - var _a2; - if (depth === void 0) { - depth = 0; - } - const rows = []; - for (let i4 = 0; i4 < originalRows.length; i4++) { - const row = createRow(table, table._getRowId(originalRows[i4], i4, parent), originalRows[i4], i4, depth); - rowModel.flatRows.push(row); - rowModel.rowsById[row.id] = row; - rows.push(row); - if (table.options.getSubRows) { - row.originalSubRows = table.options.getSubRows(originalRows[i4], i4); - if ((_a2 = row.originalSubRows) == null ? void 0 : _a2.length) { - row.subRows = accessRows(row.originalSubRows, depth + 1, row); +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 onFileChanged = async (plugin, oldPath, newPath) => { + const oldFolderPath = getFolderPathFromString(oldPath); + const newFolderPath = getFolderPathFromString(newPath); + if (oldFolderPath == newFolderPath) { + await processFolderDB(plugin, oldFolderPath, async (folder, path) => { + const amendedFolderDB = renameRow(folder, oldPath, newPath); + await saveDB(plugin, path, amendedFolderDB); + return amendedFolderDB; + }); + } else { + await processFolderDB( + plugin, + oldFolderPath, + async (folder, path) => { + const amendedFolderDB = removeRow(folder, oldPath); + await saveDB(plugin, path, amendedFolderDB); + const dbPath = folderContextFromFolder(plugin, newFolderPath); + const fromDBRow = folder.rows.find((f4) => f4.File == oldPath); + const toDBFileExists = getAbstractFileAtPath(app, dbPath); + if (toDBFileExists) { + const toFolderDB = await getMDBTable(plugin, "files", dbPath, false); + 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, + dbPath, + insertRow(toFolderDB, newRowByDBRow(newRow), newFolderPath) + ); + saveContextToFrontmatter( + newPath, + folder.cols, + fmDBCols.reduce((p3, c4) => ({ ...p3, [c4]: fromDBRow[c4] }), {}), + plugin + ); } + } else { + saveContextToFrontmatter( + newPath, + folder.cols, + Object.keys(fromDBRow).reduce( + (p3, c4) => ({ ...p3, [c4]: fromDBRow[c4] }), + {} + ), + plugin + ); + } + return amendedFolderDB; + }, + async () => { + const dbPath = folderContextFromFolder(plugin, newFolderPath); + const toDBFileExists = getAbstractFileAtPath(app, dbPath); + if (toDBFileExists) { + const toFolderDB = await getMDBTable(plugin, "files", dbPath, false); } } - return rows; + ); + } +}; +var onFileDeleted = async (plugin, oldPath) => { + const oldFolderPath = getFolderPathFromString(oldPath); + await processFolderDB(plugin, oldFolderPath, async (folder, path) => { + const amendedFolderDB = removeRow(folder, oldPath); + await saveDB(plugin, path, amendedFolderDB); + return amendedFolderDB; + }); +}; +var onFolderChanged = async (plugin, oldPath, newPath) => { + await processFolderDB(plugin, newPath, async (folder, path) => { + const newDB = { + ...folder, + rows: folder.rows.map( + (f4) => getFolderPathFromString(f4["File"]) == oldPath ? { ...f4, File: f4["File"].replace(oldPath, newPath) } : f4 + ) }; - rowModel.rows = accessRows(data); - return rowModel; - }, { - key: "getRowModel", - debug: () => { - var _table$options$debugA; - return (_table$options$debugA = table.options.debugAll) != null ? _table$options$debugA : table.options.debugTable; - }, - onChange: () => { - table._autoResetPageIndex(); - } + await saveDB(plugin, path, newDB); + return newDB; }); -} -function getGroupedRowModel() { - return (table) => memo(() => [table.getState().grouping, table.getPreGroupedRowModel()], (grouping, rowModel) => { - if (!rowModel.rows.length || !grouping.length) { - return rowModel; - } - const existingGrouping = grouping.filter((columnId) => table.getColumn(columnId)); - const groupedFlatRows = []; - const groupedRowsById = {}; - const groupUpRecursively = function(rows, depth, parentId) { - if (depth === void 0) { - depth = 0; - } - if (depth >= existingGrouping.length) { - return rows.map((row) => { - row.depth = depth; - groupedFlatRows.push(row); - groupedRowsById[row.id] = row; - if (row.subRows) { - row.subRows = groupUpRecursively(row.subRows, depth + 1); - } - return row; - }); +}; +var onFolderDeleted = async (oldPath) => { +}; + +// src/utils/db/db.ts +var import_obsidian5 = require("obsidian"); +var getDBFile = async (path) => { + if (!await app.vault.adapter.exists((0, import_obsidian5.normalizePath)(path))) { + return null; + } + const file = await app.vault.adapter.readBinary( + (0, import_obsidian5.normalizePath)(path) + ); + return file; +}; +var getDB = async (sqlJS, path) => { + const buf = await getDBFile(path); + 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 saveDBFile = async (path, binary) => { + const file = app.vault.adapter.writeBinary( + (0, import_obsidian5.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] }), + {} + ) + ) : [] } - const columnId = existingGrouping[depth]; - const rowGroupsMap = groupBy(rows, columnId); - const aggregatedGroupedRows = Array.from(rowGroupsMap.entries()).map((_ref, index) => { - let [groupingValue, groupedRows2] = _ref; - let id2 = `${columnId}:${groupingValue}`; - id2 = parentId ? `${parentId}>${id2}` : id2; - const subRows = groupUpRecursively(groupedRows2, depth + 1, id2); - const leafRows = depth ? flattenBy(groupedRows2, (row2) => row2.subRows) : groupedRows2; - const row = createRow(table, id2, leafRows[0].original, index, depth); - Object.assign(row, { - groupingColumnId: columnId, - groupingValue, - subRows, - leafRows, - getValue: (columnId2) => { - if (existingGrouping.includes(columnId2)) { - if (row._valuesCache.hasOwnProperty(columnId2)) { - return row._valuesCache[columnId2]; - } - if (groupedRows2[0]) { - var _groupedRows$0$getVal; - row._valuesCache[columnId2] = (_groupedRows$0$getVal = groupedRows2[0].getValue(columnId2)) != null ? _groupedRows$0$getVal : void 0; - } - return row._valuesCache[columnId2]; - } - if (row._groupingValuesCache.hasOwnProperty(columnId2)) { - return row._groupingValuesCache[columnId2]; - } - const column = table.getColumn(columnId2); - const aggregateFn = column.getAggregationFn(); - if (aggregateFn) { - row._groupingValuesCache[columnId2] = aggregateFn(columnId2, leafRows, groupedRows2); - return row._groupingValuesCache[columnId2]; - } - } - }); - subRows.forEach((subRow) => { - groupedFlatRows.push(subRow); - groupedRowsById[subRow.id] = subRow; - }); - return row; - }); - return aggregatedGroupedRows; - }; - const groupedRows = groupUpRecursively(rowModel.rows, 0, ""); - groupedRows.forEach((subRow) => { - groupedFlatRows.push(subRow); - groupedRowsById[subRow.id] = subRow; - }); + ], + [] + ); +}; +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) => { + const sqlstr = Object.keys(tables).map((t4) => { + const tableFields = tables[t4].cols; + const rowsQuery = tables[t4].rows.reduce((prev, curr) => { + return `${prev} 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, tag) => { + if (tag) { + return [ + ...fields, + ...defaultTagFields.rows.filter( + (f4) => !fields.some((g4) => g4.name == f4.name && g4.schemaId == f4.schemaId) + ) + ]; + } + return [ + ...fields, + ...defaultFolderFields.rows.filter( + (f4) => !fields.some((g4) => g4.name == f4.name && g4.schemaId == f4.schemaId) + ) + ]; +}; +var getMDBTable = async (plugin, table, path, tag) => { + const sqlJS = await plugin.sqlJS(); + const buf = await getDBFile(path); + if (!buf) { + return null; + } + const db = new sqlJS.Database(new Uint8Array(buf)); + await sanitizeTableSchema(plugin, db, path, tag); + 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 { - rows: groupedRows, - flatRows: groupedFlatRows, - rowsById: groupedRowsById + schema, + cols: [], + rows: [] }; - }, { - key: "getGroupedRowModel", - debug: () => { - var _table$options$debugA; - return (_table$options$debugA = table.options.debugAll) != null ? _table$options$debugA : table.options.debugTable; - }, - onChange: () => { - table._queue(() => { - table._autoResetExpanded(); - table._autoResetPageIndex(); - }); - } - }); -} -function groupBy(rows, columnId) { - const groupMap = /* @__PURE__ */ new Map(); - return rows.reduce((map, row) => { - const resKey = `${row.getValue(columnId)}`; - const previous = map.get(resKey); - if (!previous) { - map.set(resKey, [row]); - } else { - previous.push(row); - } - return map; - }, groupMap); -} -function getExpandedRowModel() { - return (table) => memo(() => [table.getState().expanded, table.getPreExpandedRowModel(), table.options.paginateExpandedRows], (expanded, rowModel, paginateExpandedRows) => { - if (!rowModel.rows.length || expanded !== true && !Object.keys(expanded != null ? expanded : {}).length) { - return rowModel; - } - if (!paginateExpandedRows) { - return rowModel; - } - return expandRows(rowModel); - }, { - key: "getExpandedRowModel", - debug: () => { - var _table$options$debugA; - return (_table$options$debugA = table.options.debugAll) != null ? _table$options$debugA : table.options.debugTable; - } + } + 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, tag) : fields + ); +}; +var deleteMDBTable = async (plugin, path, mdb) => { + const sqlJS = await plugin.sqlJS(); + const buf = await getDBFile(path); + if (!buf) { + return false; + } + const db = new sqlJS.Database(new Uint8Array(buf)); + deleteFromDB(db, "m_schema", `id = '${sanitizeSQLStatement(mdb)}'`); + deleteFromDB(db, "m_schema", `def = '${sanitizeSQLStatement(mdb)}'`); + deleteFromDB(db, "m_fields", `schemaId = '${sanitizeSQLStatement(mdb)}'`); + dropTable(db, mdb); + await saveDBFile(path, db.export().buffer); + db.close(); + return true; +}; +var getMDBTableSchemas = async (plugin, path, tag) => { + const sqlJS = await plugin.sqlJS(); + const buf = await getDBFile(path); + if (!buf) { + return null; + } + const db = new sqlJS.Database(new Uint8Array(buf)); + await sanitizeTableSchema(plugin, db, path, tag); + 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 }; }); -} -function expandRows(rowModel) { - const expandedRows = []; - const handleRow = (row) => { - var _a2; - expandedRows.push(row); - if (((_a2 = row.subRows) == null ? void 0 : _a2.length) && row.getIsExpanded()) { - row.subRows.forEach(handleRow); - } - }; - rowModel.rows.forEach(handleRow); - return { - rows: expandedRows, - flatRows: rowModel.flatRows, - rowsById: rowModel.rowsById - }; -} - -// node_modules/@tanstack/react-table/build/lib/index.mjs -function flexRender(Comp, props2) { - return !Comp ? null : isReactComponent(Comp) ? /* @__PURE__ */ h(Comp, props2) : Comp; -} -function isReactComponent(component) { - return isClassComponent(component) || typeof component === "function" || isExoticComponent(component); -} -function isClassComponent(component) { - return typeof component === "function" && (() => { - const proto = Object.getPrototypeOf(component); - return proto.prototype && proto.prototype.isReactComponent; - })(); -} -function isExoticComponent(component) { - return typeof component === "object" && typeof component.$$typeof === "symbol" && ["react.memo", "react.forward_ref"].includes(component.$$typeof.description); -} -function useReactTable(options) { - const resolvedOptions = { - state: {}, - onStateChange: () => { - }, - renderFallbackValue: null, - ...options - }; - const [tableRef] = p2(() => ({ - current: createTable(resolvedOptions) - })); - const [state, setState] = p2(() => tableRef.current.initialState); - tableRef.current.setOptions((prev) => ({ - ...prev, - ...options, - state: { - ...state, - ...options.state +}; +var getMDBSchema = async (plugin, path, schema) => { + const sqlJS = await plugin.sqlJS(); + const buf = await getDBFile(path); + 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, path, mdb) => { + var _a2, _b2; + const sqlJS = await plugin.sqlJS(); + const buf = await getDBFile(path); + if (!buf) { + return null; + } + const db = new sqlJS.Database(new Uint8Array(buf)); + const fieldsTables = dbResultsToDBTables( + db.exec(`SELECT * FROM m_fields WHERE schemaId != '${mdb.schema.id}'`) + ); + const tables = { + m_fields: { + uniques: fieldSchema.uniques, + cols: fieldSchema.cols, + rows: [...(_b2 = (_a2 = fieldsTables[0]) == null ? void 0 : _a2.rows) != null ? _b2 : [], ...mdb.cols] }, - onStateChange: (updater) => { - var _a2; - setState(updater); - (_a2 = options.onStateChange) == null ? void 0 : _a2.call(options, updater); + [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 } - })); - return tableRef.current; -} - -// src/components/ui/menus/menuItems.tsx -var import_obsidian7 = require("obsidian"); - -// src/components/ui/menus/selectMenu/concerns/focusNextElement.js -function focusNextElement(scope, currentTarget) { - const interactiveEls = scope.querySelectorAll("a,button,input"); - const currentEl = Array.prototype.findIndex.call( - interactiveEls, - (element) => element === currentTarget + }; + db.close(); + return saveDBToPath(plugin, path, 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 : [] ); - const nextEl = interactiveEls[currentEl - 1] || interactiveEls[currentEl + 1]; - if (nextEl) { - nextEl.focus(); +}; +var createDefaultDB = async (plugin, path, tag) => { + const sqlJS = await plugin.sqlJS(); + const table = tag ? defaultTagTables : defaultFolderTables; + return saveDBToPath(plugin, path, table); +}; +var sanitizeTableSchema = async (plugin, db, path, tag) => { + 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, path, tag); } -} - -// src/components/ui/menus/selectMenu/SelectMenuInput.tsx -var SIZER_STYLES = { - position: "absolute", - width: 0, - height: 0, - visibility: "hidden", - overflow: "scroll", - whiteSpace: "pre" }; -var STYLE_PROPS = [ - "fontSize", - "fontFamily", - "fontWeight", - "fontStyle", - "letterSpacing", - "textTransform" -]; -var SelectMenuInput = k3( - (props2, input) => { - const { classNames: classNames8, inputAttributes, inputEventHandlers, index } = props2; - const sizer = _2(null); - const [inputWidth, setInputWidth] = p2(null); - const [query, setQuery] = p2(""); - const [placeholderText, setPlaceholderText] = p2(""); - h2(() => { - copyInputStyles(); - updateInputWidth(); - setTimeout(() => { - input.current.focus(); - }, 50); - }, []); - h2(() => { - if (query !== props2.query || placeholderText !== props2.placeholderText) { - setQuery(props2.query); - setPlaceholderText(props2.placeholderText); - updateInputWidth(); - } - }, [props2.query, props2.placeholderText]); - const copyInputStyles = () => { - const inputStyle = window.getComputedStyle(input.current); - STYLE_PROPS.forEach((prop) => { - sizer.current.style[prop] = inputStyle[prop]; - }); +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)) }; - const updateInputWidth = () => { - let _inputWidth; - _inputWidth = Math.ceil(sizer.current.scrollWidth) + 2; - if (_inputWidth !== inputWidth) { - setInputWidth(_inputWidth); - } + } + return { + ...mdb, + rows: [...mdb.rows, newRowByDBRow(row)] + }; +}; +var consolidateFilesToTable = async (plugin, path, table, files, tag) => { + const sqlJS = await plugin.sqlJS(); + const isTag = tag ? true : false; + let db; + if (getAbstractFileAtPath(app, path)) { + const buf = await getDBFile(path); + db = new sqlJS.Database(new Uint8Array(buf)); + } else { + db = new sqlJS.Database(); + await createDefaultDB(plugin, path, false); + } + const mdbTable = await getMDBTable(plugin, table, path, isTag); + const missingFiles = files.filter((f4) => !mdbTable.rows.some((g4) => g4.File == f4 && g4._source != "")).map((f4) => ({ File: f4 })); + const mergeDuplicates = (rows, tag2) => { + const mergeFields = (row, row2) => { + return { ...row, ...row2 }; }; - return /* @__PURE__ */ bn.createElement("div", { - className: classNames8.searchWrapper - }, /* @__PURE__ */ bn.createElement("input", { - ...inputAttributes, - ...inputEventHandlers, - ref: input, - value: query, - placeholder: placeholderText, - className: classNames8.searchInput, - role: "combobox", - style: { width: "100%" } - }), /* @__PURE__ */ bn.createElement("div", { - ref: sizer, - style: SIZER_STYLES - }, query || placeholderText)); + 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); + } + return [...p3, c4]; + }, []); + }; + let linkedFolderContexts = [""]; + if (tag) { + const contexts = uniq( + mdbTable.rows.map((f4) => f4._source).filter((f4) => f4 != "" && f4 != "tag") + ); + const promises = contexts.map( + (context) => getMDBTable(plugin, "files", context, false).then((f4) => [f4, context]) + ); + 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 == tag); + }).map(([f4, g4]) => g4) + ); } -); -var SelectMenuInput_default = SelectMenuInput; - -// src/components/ui/menus/selectMenu/SelectMenuSuggestions.tsx -function markIt(name, query) { - const regexp = matchAny(query); - return name.replace(regexp, "$&"); -} -var SelectMenuSuggestionsComponent = (props2) => { - const ref = _2(null); - h2(() => { - var _a2; - if (props2.active) { - (_a2 = ref == null ? void 0 : ref.current) == null ? void 0 : _a2.scrollIntoViewIfNeeded(); + 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) + ), + isTag + ), + ...missingFiles + ].map((f4) => rowWithID(f4, isTag)) + ]; + const newMDBTable = { + ...mdbTable, + cols: [ + ...(isTag ? defaultTagFields : defaultFolderFields).rows, + ...mdbTable.cols + ].filter(onlyUniqueProp("name")), + rows: newRows + }; + await saveMDBToPath(plugin, path, newMDBTable); + db.close(); + return newMDBTable; +}; +var consolidateRowsToTag = async (plugin, path, table, source, rows) => { + const sqlJS = await plugin.sqlJS(); + if (getAbstractFileAtPath(app, path)) { + } else { + await createDefaultDB(plugin, path, true); + } + const mdbTable = await getMDBTable(plugin, table, path, true); + const prevRows = mdbTable.rows.map((f4) => { + if (f4._source != source) { + return f4; } - }, [props2.active]); - return /* @__PURE__ */ bn.createElement(bn.Fragment, null, props2.item.onToggle && /* @__PURE__ */ bn.createElement("div", null, "Toggle"), /* @__PURE__ */ bn.createElement("span", { - ref, - dangerouslySetInnerHTML: { - __html: markIt(props2.item.name, props2.query) + 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 + }; + await saveMDBToPath(plugin, path, newMDBTable); + return newMDBTable; +}; + +// src/components/ContextView/MDBContext.tsx +var MDBContext = B({ + tables: [], + cols: [], + sortedColumns: [], + data: [], + filteredData: [], + tableData: null, + contextTable: {}, + selectedRows: [], + selectRows: () => { + }, + setContextTable: () => { + }, + predicate: defaultPredicate, + savePredicate: () => { + }, + saveDB: () => null, + saveContextDB: () => null, + schema: null, + dbSchema: null, + setSchema: () => { + }, + setDBSchema: () => { + }, + dbPath: null, + isFolderContext: false, + folderPath: "", + hideColumn: () => { + }, + saveColumn: () => false, + newColumn: () => false, + sortColumn: () => { + }, + delColumn: () => { + }, + saveSchema: () => null, + deleteSchema: () => null, + tagContexts: [], + dbFileExists: false, + searchString: "", + setSearchString: () => { + }, + loadContextFields: () => { + }, + updateValue: () => { + }, + updateFieldValue: () => { + } +}); +var MDBProvider = (props2) => { + var _a2, _b2, _c2; + const { dbPath } = props2; + const [dbFileExists, setDBFileExists] = p2(false); + const [schema, setSchema] = p2(null); + const [searchString, setSearchString] = p2(null); + const [schemaTable, setSchemaTable] = p2(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 defaultSchema = props2.tag ? defaultTagSchema : defaultFolderSchema; + const folderPath = (_c2 = (_b2 = props2.folder) != null ? _b2 : props2.tag) != null ? _c2 : ""; + const isFolderContext = props2.folder ? true : false; + const tagContexts = F( + () => { + var _a3, _b3, _c3; + return ((_a3 = dbSchema == null ? void 0 : dbSchema.def) == null ? void 0 : _a3.length) > 0 ? (_c3 = (_b3 = dbSchema == null ? void 0 : dbSchema.def) == null ? void 0 : _b3.split("&")) != null ? _c3 : [] : []; + }, + [dbSchema] + ); + const cols = F( + () => { + var _a3; + return [ + ...(_a3 = tableData == null ? void 0 : tableData.cols.map((f4) => ({ ...f4, table: "" }))) != null ? _a3 : [], + ...tagContexts.reduce( + (p3, c4) => { + var _a4, _b3; + return [ + ...p3, + ...(_b3 = (_a4 = contextTable[c4]) == null ? void 0 : _a4.cols.filter((f4) => f4.name != "File" && f4.type != "fileprop").map((f4) => ({ ...f4, table: c4 }))) != null ? _b3 : [] + ]; + }, + [] + ) + ]; + }, + [tableData, schema, contextTable, tagContexts] + ); + const data = F( + () => { + var _a3; + return (_a3 = tableData == null ? void 0 : tableData.rows.map((r3, index) => linkContextRow({ + _index: index.toString(), + ...r3, + ...tagContexts.reduce((p3, c4) => { + var _a4, _b3, _c3, _d2; + const contextRowIndexByFile = (_b3 = (_a4 = contextTable[c4]) == null ? void 0 : _a4.rows.findIndex((f4) => f4.File == r3.File)) != null ? _b3 : -1; + const contextRowsByFile = (_d2 = (_c3 = contextTable[c4]) == null ? void 0 : _c3.rows[contextRowIndexByFile]) != null ? _d2 : {}; + const contextRowsWithKeysAppended = Object.keys( + contextRowsByFile + ).reduce((pa, ca) => ({ ...pa, [ca + c4]: contextRowsByFile[ca] }), { + ["_index" + c4]: contextRowIndexByFile.toString() + }); + return { ...p3, ...contextRowsWithKeysAppended }; + }, {}) + }, cols, contextTable))) != null ? _a3 : []; + }, + [tableData, schema, contextTable] + ); + const sortedColumns = F( + () => { + 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( + () => data.filter((f4) => { + return predicate.filters.reduce((p3, c4) => { + return p3 ? filterReturnForCol( + cols.find((col) => col.name + col.table == c4.field), + c4, + f4 + ) : p3; + }, true); + }).filter( + (f4) => (searchString == null ? void 0 : searchString.length) > 0 ? matchAny(searchString).test( + Object.keys(f4).filter((g4) => g4.charAt(0) != "_").map((g4) => f4[g4]).join("|") + ) : true + ).sort((a5, b4) => { + return predicate.sort.reduce((p3, c4) => { + return p3 == 0 ? sortReturnForCol( + cols.find((col) => col.name + col.table == c4.field), + c4, + a5, + b4 + ) : p3; + }, 0); + }), + [predicate, data, cols, searchString] + ); + const deleteSchema = async (table) => { + if (table.primary) + return; + const deleteResult = await deleteMDBTable(props2.plugin, dbPath, table.id); + if (deleteResult) { + const newSchemaTable = { + ...schemaTable, + rows: schemaTable.rows.filter( + (f4) => f4.id != table.id && f4.def != table.id + ) + }; + setSchemaTable(newSchemaTable); + if (dbSchema.id == table.id) { + setDBSchema( + newSchemaTable.rows.find((g4) => g4.type == "db") + ); + } } - }), props2.item.description && /* @__PURE__ */ bn.createElement("span", { - className: "mk-description", - ref, - dangerouslySetInnerHTML: { - __html: markIt(props2.item.description, props2.query) + }; + const saveSchema = async (table) => { + const newSchema = schemaTable.rows.find((f4) => f4.id == table.id) ? true : false; + const newSchemaTable = newSchema ? { + ...schemaTable, + rows: schemaTable.rows.map((f4) => f4.id == table.id ? table : f4) + } : { + ...schemaTable, + rows: [...schemaTable.rows, table] + }; + await saveDBToPath(props2.plugin, dbPath, { m_schema: newSchemaTable }); + if (table.id == (schema == null ? void 0 : schema.id)) { + setSchema(table); } - }), props2.item.removeable && /* @__PURE__ */ bn.createElement("div", null, "Remove")); -}; -var SelectMenuSuggestions = (props2) => { - const timer = _2(null); - const mouseOver = (e4, index) => { - if (!props2.hoverSelect) { - return; + if (table.id == (dbSchema == null ? void 0 : dbSchema.id)) { + setDBSchema(table); + setTableData((f4) => ({ + ...f4, + schema: table + })); } - timer.current && clearTimeout(timer.current); - timer.current = setTimeout(() => props2.setIndex(index), 300); + setSchemaTable(newSchemaTable); }; - const options = props2.options.map((item, index) => { - const key2 = `${props2.id}-${index}`; - const classNames8 = []; - if (props2.index === index) { - classNames8.push(props2.classNames.suggestionActive); - } - if (item.disabled) { - classNames8.push(props2.classNames.suggestionDisabled); + const updateValue = (column, value, table, index, file) => { + var _a3, _b3; + const col = (_a3 = table == "" ? tableData : contextTable[table]) == null ? void 0 : _a3.cols.find( + (f4) => f4.name == column + ); + if (col) + saveFrontmatterValue(props2.plugin, file != null ? file : (_b3 = tableData.rows[index]) == null ? void 0 : _b3.File, column, value, col.type, props2.plugin.settings.saveAllContextToFrontmatter); + if (table == "") { + saveDB2({ + ...tableData, + rows: tableData.rows.map( + (r3, i4) => i4 == index ? { + ...r3, + [column]: value + } : r3 + ) + }); + } else if (contextTable[table]) { + saveContextDB( + { + ...contextTable[table], + rows: contextTable[table].rows.map( + (r3, i4) => i4 == index ? { + ...r3, + [column]: value + } : r3 + ) + }, + table + ); } - return /* @__PURE__ */ bn.createElement("li", { - id: key2, - key: key2, - role: "option", - className: classNames8.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, { - item, - query: props2.query, - active: index == props2.index - })); - }); - return /* @__PURE__ */ bn.createElement("div", { - className: props2.classNames.suggestions - }, /* @__PURE__ */ bn.createElement("ul", { - role: "listbox", - id: props2.id - }, options)); -}; -var SelectMenuSuggestions_default = SelectMenuSuggestions; - -// src/components/ui/menus/selectMenu/SelectMenuPill.tsx -var SelectMenuPillComponent = (props2) => { - return /* @__PURE__ */ bn.createElement("button", { - type: "button", - className: props2.classNames.selectedTag, - onClick: props2.onDelete - }, /* @__PURE__ */ bn.createElement("span", { - className: props2.classNames.selectedTagName - }, props2.tag.name)); -}; -var SelectMenuPill_default = SelectMenuPillComponent; - -// src/components/ui/menus/selectMenu/SelectMenuComponent.tsx -var import_lodash2 = __toESM(require_lodash()); -var KEYS = { - ENTER: "Enter", - TAB: "Tab", - BACKSPACE: "Backspace", - UP_ARROW: "ArrowUp", - UP_ARROW_COMPAT: "Up", - DOWN_ARROW: "ArrowDown", - DOWN_ARROW_COMPAT: "Down" -}; -var CLASS_NAMES = { - root: "mk-options-menu", - rootFocused: "is-focused", - selected: "mk-options-menu__selected", - selectedTag: "mk-options-menu__selected-tag", - selectedTagName: "mk-options-menu__selected-tag-name", - search: "mk-options-menu__search", - searchWrapper: "mk-options-menu__search-wrapper", - searchInput: "mk-options-menu__search-input", - suggestions: "mk-options-menu__suggestions", - suggestionActive: "is-active", - suggestionDisabled: "is-disabled" -}; -var defaultProps = { - id: "SelectMenu", - tags: [], - suggestionsOnly: false, - placeholderText: i18n_default.labels.optionItemSelectPlaceholder, - noSuggestionsText: null, - newTagText: null, - suggestions: [], - suggestionsFilter: defaultSuggestionsFilter, - suggestionsTransform: null, - classNames: CLASS_NAMES, - delimiters: [KEYS.ENTER], - minQueryLength: 2, - maxSuggestionsLength: 8, - inputAttributes: {}, - hoverSelect: false -}; -var findMatchIndex = (options, query) => { - return options.findIndex((option) => matchExact(query).test(option.name)); -}; -var pressDelimiter = (props2, query, index, options, addTag) => { - if (query.length >= props2.minQueryLength) { - const match2 = findMatchIndex(options, query); - const _index = index === -1 ? match2 : index; - const tag = _index > -1 ? options[_index] : null; - if (tag) { - addTag(tag); - } else { - addTag({ name: query, value: query }); + }; + const sortColumn = (sort) => { + savePredicate({ + ...predicate, + sort: [sort] + }); + }; + const hideColumn = (col, hidden) => { + savePredicate({ + ...predicate, + colsHidden: hidden ? [...predicate.colsHidden.filter((s5) => s5 != col.name + col.table), col.name + col.table] : predicate.colsHidden.filter((s5) => s5 != col.name + col.table) + }); + }; + const updateFieldValue = (column, fieldValue, value, table, index, file) => { + var _a3; + const col = tableData.cols.find((f4) => f4.name == column); + saveFrontmatterValue(props2.plugin, file != null ? file : (_a3 = tableData.rows[index]) == null ? void 0 : _a3.File, column, value, col.type, props2.plugin.settings.saveAllContextToFrontmatter); + if (table == "") { + const newTable = { + ...tableData, + cols: tableData.cols.map( + (m5) => m5.name == column ? { + ...m5, + value: fieldValue + } : m5 + ), + rows: tableData.rows.map( + (r3, i4) => i4 == index ? { + ...r3, + [column]: value + } : r3 + ) + }; + saveDB2(newTable); + } else if (contextTable[table]) { + saveContextDB( + { + ...contextTable[table], + cols: contextTable[table].cols.map( + (m5) => m5.name == column ? { + ...m5, + value: fieldValue + } : m5 + ), + rows: contextTable[table].rows.map( + (r3, i4) => i4 == index ? { + ...r3, + [column]: value + } : r3 + ) + }, + table + ); } - } -}; -function defaultSuggestionsFilter(item, query) { - const regexp = matchAny(query); - return regexp.test(item.name); -} -function getOptions(props2, query) { - let options; - if (props2.suggestionsTransform) { - options = props2.suggestionsTransform(query, props2.suggestions); - } else { - options = props2.suggestions.filter( - (item) => props2.suggestionsFilter(item, query) + }; + const syncAllMetadata = (f4) => { + const files = f4.rows.map((f5) => f5.File); + const importYAML = (files2, fmKeys) => { + return files2.map((f5) => getAbstractFileAtPath(app, f5)).filter((f5) => f5).reduce( + (p3, c4) => { + const fm = frontMatterForFile(c4); + if (!fm) + return p3; + return { + uniques: [], + cols: uniq([...p3.cols, ...fmKeys]), + rows: [ + ...p3.rows, + { + File: c4.path, + ...fmKeys.reduce((p4, c5) => { + const value = parseFrontMatter(c5, fm[c5], false); + if ((value == null ? void 0 : value.length) > 0) + return { ...p4, [c5]: value }; + return p4; + }, {}) + } + ] + }; + }, + { uniques: [], cols: [], rows: [] } + ); + }; + const yamlTableData = importYAML( + files, + f4.cols.filter((f5) => !f5.type.contains("file")).map((f5) => f5.name) ); - } - options = options.slice(0, props2.maxSuggestionsLength); - if (props2.newTagText && findMatchIndex(options, query) === -1) { - options.push({ id: 0, name: query, value: query }); - } else if (props2.noSuggestionsText && options.length === 0) { - options.push({ - id: 0, - name: props2.noSuggestionsText, - value: "", - disabled: true + saveDB2({ + ...f4, + rows: f4.rows.map((r3) => { + const fmRow = yamlTableData.rows.find((f5) => f5.File == r3.File); + if (fmRow) { + return { + ...r3, + ...fmRow + }; + } + return r3; + }) }); - } - return options; -} -var SelectMenuComponent = bn.forwardRef((_props, ref) => { - const props2 = { ...defaultProps, ..._props }; - const [options, setOptions] = p2([]); - const inputRef = _2(null); - const [query, setQuery] = p2(""); - const [focused, setFocused] = p2(false); - const [index, setIndex] = p2(0); - const onComposition = _2(false); + }; h2(() => { - if (ref) { - ref.current = () => { - var _a2; - if (!focused) { - (_a2 = inputRef == null ? void 0 : inputRef.current) == null ? void 0 : _a2.focus(); - setFocused(true); - return false; + 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 + ); + if (preselectDBSchema) { + setDBSchema(preselectDBSchema); + return; + } } - return true; - }; - } - }, [focused]); - h2(() => { - var _a2; - if (index != -1 && props2.onHover && props2.hoverSelect) { - debounceFn((_a2 = options[index]) == null ? void 0 : _a2.value); + } 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: [] + }) + ); + } } - }, [index, options]); - const debounceFn = T2((0, import_lodash2.debounce)(handleDebounceFn, 100), []); - function handleDebounceFn(inputValue) { - props2.onHover(inputValue); - } - h2(() => { - if (query.length == 0 && props2.defaultSuggestions) { - setOptions(props2.defaultSuggestions); - return; + }, [schemaTable]); + const loadTables = async () => { + if (getAbstractFileAtPath(app, props2.dbPath)) { + setDBFileExists(true); + getMDBTableSchemas( + props2.plugin, + props2.dbPath, + props2.tag ? true : false + ).then((f4) => { + setSchemaTable({ + ...defaultSchema, + rows: f4 + }); + if (!props2.schema) + setDBSchema(f4 == null ? void 0 : f4.find((g4) => g4.type == "db")); + }); + } else { + if (props2.schema) { + saveDB2(props2.tag ? defaultTagMDBTable : defaultFolderMDBTable).then( + (f4) => { + setSchemaTable(defaultSchema); + } + ); + } else { + setSchemaTable(defaultSchema); + setDBSchema(defaultFileDBSchema); + } } - setOptions(getOptions(props2, query)); - }, [query, props2.suggestions]); - const container = _2(null); - const onInput = (e4) => { - if (e4.type === "compositionstart") { - onComposition.current = true; - return; + }; + const refreshTags = async (evt) => { + if (!dbFileExists) { + loadDefaultTableData(); + } else { + if (dbSchema.primary) { + runDef(); + } else { + getMDBData(); + } } - if (e4.type === "compositionend") { - onComposition.current = false; + }; + const refreshSpace = async (evt) => { + if (!dbFileExists) { + loadDefaultTableData(); } - if (onComposition.current) { + }; + const getMDBData = () => { + getMDBTable(props2.plugin, dbSchema.id, dbPath, !isFolderContext).then( + (f4) => setTableData(f4) + ); + }; + const refreshSchema = (schema2) => { + }; + const refreshMDB = async (evt) => { + if (!dbFileExists || (dbSchema == null ? void 0 : dbSchema.primary) != "true") { return; } - const _query = e4.target.value; - if (props2.onInput) { - props2.onInput(_query); + if (evt.detail.dbPath == dbPath) { + if (dbSchema) { + if (schema) + getMDBSchema(props2.plugin, dbPath, 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, dbSchema.id, dbPath, !isFolderContext).then( + (f4) => setTableData(f4) + ); + } + } else { + const tag = Object.keys(contextTable).find( + (t4) => tagContextFromTag(props2.plugin, t4) == evt.detail.dbPath + ); + if (tag) + loadContextFields(tag); } - if (_query.length === query.length + 1 && props2.delimiters.indexOf(query.slice(-1)) > -1) { - pressDelimiter(props2, query, index, options, addTag); - } else if (_query !== query) { - setQuery(_query); + }; + h2(() => { + window.addEventListener(eventTypes.mdbChange, refreshMDB); + window.addEventListener(eventTypes.spacesChange, refreshSpace); + window.addEventListener(eventTypes.tagsChange, refreshTags); + return () => { + window.removeEventListener(eventTypes.mdbChange, refreshMDB); + window.removeEventListener(eventTypes.spacesChange, refreshSpace); + window.removeEventListener(eventTypes.tagsChange, refreshTags); + }; + }, [contextTable, dbSchema, dbPath, schema]); + h2(() => { + loadTables(); + }, [dbPath]); + const saveDB2 = async (newTable) => { + var _a3; + if (!dbFileExists) { + const defaultFields = isFolderContext ? defaultFolderFields : defaultTagFields; + const defaultTable = isFolderContext ? defaultFolderTables : defaultTagTables; + const dbField = { + ...defaultTable, + m_fields: { + uniques: defaultFields.uniques, + cols: defaultFields.cols, + rows: [...(_a3 = defaultFields.rows) != null ? _a3 : [], ...newTable.cols] + }, + [newTable.schema.id]: { + uniques: newTable.cols.filter((c4) => c4.unique == "true").map((c4) => c4.name), + cols: newTable.cols.map((c4) => c4.name), + rows: newTable.rows + } + }; + await saveDBToPath(props2.plugin, dbPath, dbField).then((f4) => { + setDBFileExists(true); + f4 ? setTableData(newTable) : new import_obsidian6.Notice("DB ERROR"); + }); + } else { + await saveMDBToPath(props2.plugin, dbPath, newTable).then((f4) => { + setDBFileExists(true); + f4 ? setTableData(newTable) : new import_obsidian6.Notice("DB ERROR"); + }); } }; - const onKeyDown = (e4) => { - if (props2.delimiters.indexOf(e4.key) > -1) { - if (query || index > -1) { - e4.preventDefault(); + h2(() => { + 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 : { + ...dbSchema, + id: uniqueNameFromString( + dbSchema.id + "View", + schemaTable.rows.map((f4) => f4.id) + ), + type: "table", + def: dbSchema.id + }; + if (_schema) { + setSchema(_schema); + if (dbFileExists) { + if (dbSchema.primary) { + runDef(); + } else { + getMDBData(); + } + } else { + loadDefaultTableData(); } - pressDelimiter(props2, query, index, options, addTag); - } - if (e4.key === KEYS.BACKSPACE) { - pressBackspaceKey(); - } - if (e4.key === KEYS.UP_ARROW || e4.key === KEYS.UP_ARROW_COMPAT) { - pressUpKey(e4); } - if (e4.key === KEYS.DOWN_ARROW || e4.key === KEYS.DOWN_ARROW_COMPAT) { - pressDownKey(e4); + }, [dbSchema]); + h2(() => { + if (dbFileExists) + parsePredicate(schema == null ? void 0 : schema.predicate); + }, [schema]); + h2(() => { + 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 } + }); + window.dispatchEvent(evt); + } else { + let evt = new CustomEvent(eventTypes.selectedFileChange, { + detail: { filePath: null } + }); + window.dispatchEvent(evt); } + setSelectedRows(rows); }; - const onBlur = () => { - setFocused(false); - if (props2.onBlur) { - props2.onBlur(); + const loadDefaultTableData = () => { + let files; + if (props2.folder) { + files = folderChildren( + props2.plugin, + getAbstractFileAtPath(props2.plugin.app, props2.folder) + ); + setTableData({ + ...isFolderContext ? defaultFolderMDBTable : defaultTagMDBTable, + rows: files.map( + (f4) => newRowByDBRow({ _source: "folder", File: f4.path }) + ) + }); + } else if (props2.tag) { + files = getAllFilesForTag(props2.tag).map((f4) => getAbstractFileAtPath(app, f4)).filter((f4) => f4); + setTableData({ + ...isFolderContext ? defaultFolderMDBTable : defaultTagMDBTable, + rows: files.map((f4) => newRowByDBRow({ _source: "tag", File: f4.path })) + }); } }; - const onFocus = () => { - setFocused(true); - if (props2.onFocus) { - props2.onFocus(); + const getContextTags = async (_tableData) => { + const contextFields = _tableData.cols.filter((f4) => f4.type.contains("context")).map((f4) => f4.value).filter((f4) => !tagContexts.some((g4) => g4 == f4)); + for (let c4 of contextFields) { + loadContextFields(c4); } }; - const onDeleteTag = (index2, event) => { - if (container.current) { - focusNextElement(container.current, event.currentTarget); + const runDef = async () => { + let files; + if (props2.folder) { + files = folderChildren( + props2.plugin, + getAbstractFileAtPath(props2.plugin.app, props2.folder) + ); + consolidateFilesToTable( + props2.plugin, + dbPath, + dbSchema.id, + files.map((f4) => f4.path) + ).then((f4) => { + for (let c4 of tagContexts) { + loadTagContext(c4, f4.rows); + } + setTableData(f4); + return f4; + }).then((f4) => syncAllMetadata(f4)); + } else if (props2.tag) { + files = getAllFilesForTag(props2.tag).map((f4) => getAbstractFileAtPath(app, f4)).filter((f4) => f4); + consolidateFilesToTable( + props2.plugin, + dbPath, + dbSchema.id, + files.map((f4) => f4.path), + props2.tag + ).then((f4) => { + for (let c4 of tagContexts) { + loadTagContext(c4, f4.rows); + } + setTableData(f4); + return f4; + }).then((f4) => syncAllMetadata(f4)); } - deleteTag(index2); }; - const addTag = (tag) => { - if (tag.disabled) { - return; - } - if (props2.onValidate && !props2.onValidate(tag)) { - return; - } - props2.onAddition(tag); - clearInput(); + const loadTagContext = async (tag, files) => { + consolidateRowsToTag( + props2.plugin, + tagContextFromTag(props2.plugin, tag), + dbSchema.id, + dbPath, + files + ).then((f4) => { + if (f4) { + const contextFields = f4.cols.filter((g4) => g4.type.contains("context")).map((g4) => g4.value).filter((g4) => !tagContexts.some((h5) => h5 == g4)); + for (let c4 of contextFields) { + loadContextFields(c4); + } + setContextTable((t4) => ({ + ...t4, + [tag]: f4 + })); + } + }); }; - const deleteTag = (i4) => { - props2.onDelete(i4); + const loadContextFields = async (tag) => { + getMDBTable( + props2.plugin, + "files", + tagContextFromTag(props2.plugin, tag), + true + ).then((f4) => { + setContextTable((t4) => ({ + ...t4, + [tag]: f4 + })); + }); }; - const clearInput = () => { - setQuery(""); - setIndex(-1); + const tagExists = (currentCache, findTag) => { + let currentTags = []; + if ((0, import_obsidian6.getAllTags)(currentCache)) { + currentTags = (0, import_obsidian6.getAllTags)(currentCache); + } + return currentTags.find((tag) => tag.toLowerCase() == findTag.toLowerCase()) ? true : false; }; - const clearSelectedIndex = () => { - setIndex(-1); + const 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; }; - const pressUpKey = (e4) => { - e4.preventDefault(); - const size = options.length - 1; - setIndex(index <= 0 ? size : index - 1); + const saveContextDB = async (newTable, context) => { + const dbPath2 = tagContextFromTag(props2.plugin, context); + await saveMDBToPath(props2.plugin, dbPath2, newTable).then( + (f4) => f4 && setContextTable((t4) => ({ + ...t4, + [context]: newTable + })) + ); }; - const pressDownKey = (e4) => { - e4.preventDefault(); - const size = options.length - 1; - setIndex((i4) => i4 >= size ? 0 : i4 + 1); + const savePredicate = (newPredicate) => { + const cleanedPredicate = validatePredicate(newPredicate); + saveSchema({ + ...schema, + predicate: JSON.stringify(cleanedPredicate) + }); + setPredicate(cleanedPredicate); }; - function pressBackspaceKey() { - if (!query.length) { - deleteTag(props2.tags.length - 1); + h2(() => { + setPredicate((p3) => ({ + ...p3, + colsOrder: uniq([ + ...p3.colsOrder, + ...cols.filter((f4) => f4.hidden != "true").map((c4) => c4.name + c4.table) + ]) + })); + }, [cols]); + const parsePredicate = (predicateStr) => { + const newPredicate = safelyParseJSON(predicateStr); + setPredicate(validatePredicate(newPredicate)); + }; + const delColumn = (column) => { + let mdbtable; + const table = column.table; + if (table == "") { + mdbtable = tableData; + } else if (contextTable[table]) { + mdbtable = contextTable[table]; + } + const newFields = mdbtable.cols.filter( + (f4, i4) => f4.name != column.name + ); + const newTable = { + ...mdbtable, + cols: newFields, + rows: mdbtable.rows.map((r3) => { + const { [column.name]: val, ...rest } = r3; + return rest; + }) + }; + if (table == "") { + saveDB2(newTable); + } else if (contextTable[table]) { + saveContextDB(newTable, table); } - } - const focusInput = () => { - inputRef.current.focus(); }; - const inputEventHandlers = { - onChange: onInput, - onBlur, - onFocus, - onInput: () => { - }, - onKeyDown, - onCompositionEnd: onInput, - onCompositionStart: onInput + const newColumn = (col) => { + return saveColumn(col); }; - 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", { - ref: container, - className: rootClassNames.join(" ") - }, !props2.suggestionsOnly ? /* @__PURE__ */ bn.createElement("div", { - className: classNames8.selected, - "aria-relevant": "additions removals", - "aria-live": "polite" - }, /* @__PURE__ */ bn.createElement(bn.Fragment, null, props2.tags.map((tag, i4) => /* @__PURE__ */ bn.createElement(SelectMenuPill_default, { - key: i4, - tag, - classNames: classNames8, - onDelete: (e4) => onDeleteTag(i4, e4) - }))), /* @__PURE__ */ bn.createElement("div", { - className: classNames8.search - }, /* @__PURE__ */ bn.createElement(SelectMenuInput_default, { - ref: inputRef, - query, - index, - id: props2.id, - classNames: classNames8, - inputAttributes: props2.inputAttributes, - inputEventHandlers, - expanded, - placeholderText: props2.placeholderText - }))) : null, options.length ? /* @__PURE__ */ bn.createElement(SelectMenuSuggestions_default, { - options, - hoverSelect: props2.hoverSelect, - query, - setIndex, - index, - id: props2.id, - classNames: classNames8, - expanded, - addTag - }) : null, query && props2.allowNew && /* @__PURE__ */ bn.createElement("div", { - className: "mk-options-menu__suggestions" - }, /* @__PURE__ */ bn.createElement("ul", null, /* @__PURE__ */ bn.createElement("li", { - onMouseDown: (e4) => e4.preventDefault(), - onClick: () => addTag({ name: query, value: query }) - }, "Add ", query))), props2.previewComponent); -}); -var SelectMenuComponent_default = SelectMenuComponent; - -// src/components/ui/menus/selectMenu.tsx -var SelectMenu = bn.forwardRef( - (props2, ref) => { - var _a2; - const initialOptions = props2.options.map((o3, i4) => { - return { - ...o3, - id: i4 + 1 - }; - }); - h2(() => { - setSuggestions( - props2.options.map((o3, i4) => { - return { - ...o3, - id: i4 + 1 - }; - }) - ); - }, [props2.options]); - const [suggestions, setSuggestions] = p2(initialOptions); - const [tags, setTags] = p2( - props2.value.map( - (v3) => { - var _a3; - return (_a3 = initialOptions.find((f4) => f4.value == v3)) != null ? _a3 : { - id: 0, - name: v3, - value: v3 - }; - } + const saveColumn = (newColumn2, oldColumn) => { + let mdbtable; + const column = { + ...newColumn2, + name: sanitizeColumnName(newColumn2.name) + }; + const table = column.table; + if (table == "") { + mdbtable = tableData; + } else if (contextTable[table]) { + mdbtable = contextTable[table]; + } + if (column.name == "") { + new import_obsidian6.Notice(i18n_default.notice.noPropertyName); + return false; + } + if (!oldColumn && mdbtable.cols.find( + (f4) => f4.name.toLowerCase() == column.name.toLowerCase() + ) || oldColumn && oldColumn.name != column.name && mdbtable.cols.find( + (f4) => f4.name.toLowerCase() == column.name.toLowerCase() + )) { + new import_obsidian6.Notice(i18n_default.notice.duplicatePropertyName); + return false; + } + const oldFieldIndex = oldColumn ? mdbtable.cols.findIndex((f4) => f4.name == oldColumn.name) : -1; + const newFields = oldFieldIndex == -1 ? [...mdbtable.cols, column] : mdbtable.cols.map((f4, i4) => i4 == oldFieldIndex ? column : f4); + const newTable = { + ...mdbtable, + cols: newFields, + rows: mdbtable.rows.map( + (f4) => oldColumn ? { + ...f4, + [column.name]: f4[oldColumn.name], + oldColumn: void 0 + } : f4 ) - ); - const onDelete = T2( - (tagIndex) => { - const newTags = tags.filter((_4, i4) => i4 !== tagIndex); - setTags(newTags); - props2.saveOptions( - suggestions.map((f4) => f4.value), - newTags.map((f4) => f4.value) - ); - }, - [suggestions, tags] - ); - const onAddition = T2( - (newTag) => { - let tag = newTag; - let newSuggestions = suggestions; - let newTags = tags; - if (!suggestions.find((s5) => s5.value == newTag.value)) { - tag = { - id: suggestions.length + 1, - name: newTag.name, - value: newTag.name - }; - newSuggestions = [...suggestions, tag]; - setSuggestions(newSuggestions); - } - if (props2.multi) { - if (!tags.find((t4) => t4.value == tag.value)) { - newTags = [...tags, tag]; - setTags(newTags); - } - } else { - newTags = [tag]; - setTags(newTags); - } - props2.saveOptions( - newSuggestions.map((f4) => f4.value), - newTags.map((f4) => f4.value) - ); - if (!props2.multi) { - props2.hide(); - } - }, - [tags, suggestions] - ); - const onValidation = T2( - (newTag) => { - if (!props2.editable && !suggestions.find((s5) => s5.value == newTag.value)) { - return false; - } - if (newTag.name.length == 0) { - return false; + }; + if (oldColumn) + savePredicate({ + filters: predicate.filters.map( + (f4) => f4.field == oldColumn.name + oldColumn.table ? { ...f4, field: column.name + column.table } : f4 + ), + sort: predicate.sort.map( + (f4) => f4.field == oldColumn.name + oldColumn.table ? { ...f4, field: column.name + column.table } : f4 + ), + groupBy: predicate.groupBy.map( + (f4) => f4 == oldColumn.name + oldColumn.table ? column.name + column.table : f4 + ), + colsHidden: predicate.colsHidden.map( + (f4) => f4 == oldColumn.name + oldColumn.table ? column.name + column.table : f4 + ), + colsOrder: predicate.colsOrder.map( + (f4) => f4 == oldColumn.name + oldColumn.table ? column.name + column.table : f4 + ), + colsSize: { + ...predicate.colsSize, + [column.name + column.table]: predicate.colsSize[oldColumn.name + oldColumn.table], + [oldColumn.name + oldColumn.table]: void 0 } - return true; - }, - [suggestions] - ); - return /* @__PURE__ */ bn.createElement(SelectMenuComponent_default, { - tags: props2.multi ? tags : [], - suggestions, - ref, - onDelete, - onAddition, - onValidate: onValidation, - defaultSuggestions: props2.defaultOptions, - placeholderText: (_a2 = props2.placeholder) != null ? _a2 : "", - minQueryLength: 0, - onHover: props2.onHover, - hoverSelect: props2.onHover ? true : false, - maxSuggestionsLength: props2.showAll ? Math.min(50, props2.options.length) : 8, - suggestionsOnly: !props2.searchable && !props2.editable, - allowNew: props2.editable, - previewComponent: props2.previewComponent - }); - } -); - -// src/components/ui/menus/menuItems.tsx -var inputMenuItem = (menuItem, value, setValue) => { - const frag = document.createDocumentFragment(); - const spanEl = frag.createEl("span"); - const inputEl = frag.createEl("input"); - inputEl.type = "text"; - inputEl.value = value; - inputEl.addEventListener("click", (e4) => { - e4.stopImmediatePropagation(); - }); - inputEl.addEventListener("mousedown", (e4) => { - e4.stopImmediatePropagation(); - }); - inputEl.addEventListener("mouseup", (e4) => { - e4.stopImmediatePropagation(); - }); - inputEl.addEventListener("blur", (e4) => { - setValue(inputEl.value); - }); - menuItem.dom.toggleClass("mk-menu-input", true); - menuItem.setTitle(frag); - return menuItem; -}; -var showSelectMenu = (point, optionProps) => { - const menu = new import_obsidian7.Menu(); - menu.dom.toggleClass("mk-menu", true); - menu.setUseNativeMenu(false); - const frag = document.createDocumentFragment(); - const div = frag.createDiv("mk-options-container"); - div.style.minHeight = Math.min( - 200, - (optionProps.options.length + (optionProps.searchable ? 1 : 0)) * 28 - ).toString() + "px"; - div.addEventListener("click", (e4) => { - e4.stopImmediatePropagation(); - }); - div.addEventListener("mousedown", (e4) => { - e4.stopImmediatePropagation(); - }); - div.addEventListener("mouseup", (e4) => { - e4.stopImmediatePropagation(); - }); - div.addEventListener("keydown", (e4) => { - }); - menu.onHide(() => optionProps.onHide && optionProps.onHide()); - const root = createRoot(div); - root.render( - /* @__PURE__ */ bn.createElement(bn.Fragment, null, /* @__PURE__ */ bn.createElement(SelectMenu, { - hide: () => { - menu.hide(); - optionProps.onHide && optionProps.onHide(); - }, - ...optionProps - })) - ); - menu.addItem((item) => { - item.setTitle(frag); - }); - const keys = [...menu.scope.keys]; - for (let i4 = 0; i4 < keys.length; i4++) { - if (keys[i4].key != "Escape") { - menu.scope.unregister(keys[i4]); + }); + if (table == "") { + syncAllMetadata(newTable); + } else if (contextTable[table]) { + saveContextDB(newTable, table); } - } - menu.showAtPosition(point); - return menu; -}; -var disclosureMenuItem = (menuItem, multi, editable, title, value, options, saveOptions) => { - const frag = document.createDocumentFragment(); - const div = frag.createDiv("title"); - div.textContent = title; - const div2 = frag.createDiv("disclosure"); - div2.textContent = value; - menuItem.setTitle(frag); - menuItem.onClick((ev) => { - var _a2; - ev.stopPropagation(); - const offset = menuItem.dom.getBoundingClientRect(); - showSelectMenu( - { x: offset.right + 10, y: offset.top }, - { - multi, - editable, - value: (_a2 = splitString(value)) != null ? _a2 : [], - options, - saveOptions, - searchable: true, - showAll: true - } - ); - }); - return menuItem; + return true; + }; + return /* @__PURE__ */ bn.createElement(MDBContext.Provider, { + value: { + data, + filteredData, + loadContextFields, + selectedRows, + selectRows, + tableData, + cols, + sortedColumns, + contextTable, + setContextTable, + predicate, + savePredicate, + saveDB: saveDB2, + saveContextDB, + schema, + dbPath, + saveColumn, + hideColumn, + sortColumn, + delColumn, + newColumn, + tagContexts, + tables, + setSchema, + saveSchema, + deleteSchema, + dbFileExists, + dbSchema, + searchString, + setSearchString, + folderPath, + isFolderContext, + setDBSchema, + updateValue, + updateFieldValue + } + }, props2.children); }; -// 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 initialOptions = [ - ...(_b2 = splitString(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(() => { - var _a3; - setValue( - (props2.multi ? (_a3 = splitString(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(",") - ); +// src/components/ContextView/CardsView/CardView.tsx +var import_classnames = __toESM(require_classnames()); + +// src/components/FlowEditor/FlowView.tsx +var FlowView = (props2) => { + 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 saveOptions = (_options, _value) => { - if (!props2.multi) { - setOptions( - _options.filter((f4) => f4.length > 0).map((t4) => ({ name: t4, value: t4 })) - ); - setValue(_value); - props2.saveOptions(_options.filter((f4) => f4.length > 0).join(","), _value.join(",")); + const toggleFlow = () => { + if (props2.load) { + loadFile(); } else { - setOptions(_options.map((t4) => ({ name: t4, value: t4 }))); - setValue(_value); - props2.saveOptions(_options.filter((f4) => f4.length > 0).join(","), _value.join(",")); + ref.current.empty(); } }; - const menuProps = () => ({ - multi: false, - editable: true, - value, - options: !props2.multi ? [{ name: i18n_default.menu.none, value: "" }, ...options] : options, - saveOptions, - placeholder: i18n_default.labels.optionItemSelectPlaceholder, - searchable: true, - showAll: true - }); - return /* @__PURE__ */ bn.createElement(OptionCellBase, { - value, - menuProps, - multi: props2.multi, - editMode: props2.editMode, - removeValue + h2(() => { + toggleFlow(); + }, [props2.load, props2.path, props2.from, props2.to]); + return /* @__PURE__ */ bn.createElement("div", { + className: "mk-flowspace-editor", + ref }); }; -var OptionCellBase = (props2) => { - const { - value, - menuProps, - removeValue, - getLabelString, - openItem, - valueClass - } = props2; - const menuRef = _2(null); - h2(() => { - if (props2.editMode == 2) { - if (!menuRef.current) - showMenu(); + +// node_modules/@tanstack/table-core/build/lib/index.mjs +function functionalUpdate(updater, input) { + return typeof updater === "function" ? updater(input) : updater; +} +function makeStateUpdater(key2, instance) { + return (updater) => { + instance.setState((old) => { + return { + ...old, + [key2]: functionalUpdate(updater, old[key2]) + }; + }); + }; +} +function isFunction(d5) { + return d5 instanceof Function; +} +function flattenBy(arr, getChildren) { + const flat = []; + const recurse = (subArr) => { + subArr.forEach((item) => { + flat.push(item); + const children = getChildren(item); + if (children == null ? void 0 : children.length) { + recurse(children); + } + }); + }; + recurse(arr); + return flat; +} +function memo(getDeps, fn2, opts) { + let deps = []; + let result; + return () => { + var _a2; + let depTime; + if (opts.key && opts.debug) + depTime = Date.now(); + const newDeps = getDeps(); + const depsChanged = newDeps.length !== deps.length || newDeps.some((dep, index) => deps[index] !== dep); + if (!depsChanged) { + return result; } - }, [props2.editMode]); - const ref = _2(null); - const showMenu = () => { - const offset = ref.current.getBoundingClientRect(); - menuRef.current = showSelectMenu( - { x: offset.left - 4, y: offset.bottom - 4 }, - menuProps() - ); + deps = newDeps; + let resultTime; + 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); + if (opts.key && opts.debug) { + if (opts == null ? void 0 : opts.debug()) { + const depEndTime = Math.round((Date.now() - depTime) * 100) / 100; + const resultEndTime = Math.round((Date.now() - resultTime) * 100) / 100; + const resultFpsPercentage = resultEndTime / 16; + const pad = (str, num) => { + str = String(str); + while (str.length < num) { + str = " " + str; + } + return str; + }; + console.info(`%c\u23F1 ${pad(resultEndTime, 5)} /${pad(depEndTime, 5)} ms`, ` + font-size: .6rem; + font-weight: bold; + color: hsl(${Math.max(0, Math.min(120 - 120 * resultFpsPercentage, 120))}deg 100% 31%);`, opts == null ? void 0 : opts.key); + } + } + return result; }; - const editable = props2.editMode > 0; - return /* @__PURE__ */ bn.createElement("div", { - className: "mk-cell-option", - ref - }, value.length > 0 ? value.map((o3) => /* @__PURE__ */ bn.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", { - className: valueClass && valueClass(o3), - onClick: () => openItem && openItem(o3) - }, getLabelString ? getLabelString(o3) : o3), editable && props2.multi ? /* @__PURE__ */ bn.createElement("div", { - className: "mk-icon-xsmall", - onClick: () => removeValue(o3), - dangerouslySetInnerHTML: { - __html: uiIconSet["mk-ui-close"] +} +function createColumn(table, columnDef, depth, parent) { + var _ref, _resolvedColumnDef$id; + const defaultColumn = table._getDefaultColumnDef(); + const resolvedColumnDef = { + ...defaultColumn, + ...columnDef + }; + const accessorKey = resolvedColumnDef.accessorKey; + let id2 = (_ref = (_resolvedColumnDef$id = resolvedColumnDef.id) != null ? _resolvedColumnDef$id : accessorKey ? accessorKey.replace(".", "_") : void 0) != null ? _ref : typeof resolvedColumnDef.header === "string" ? resolvedColumnDef.header : void 0; + let accessorFn; + if (resolvedColumnDef.accessorFn) { + accessorFn = resolvedColumnDef.accessorFn; + } else if (accessorKey) { + if (accessorKey.includes(".")) { + accessorFn = (originalRow) => { + let result = originalRow; + for (const key2 of accessorKey.split(".")) { + result = result[key2]; + if (result === void 0) { + throw new Error(`"${key2}" in deeply nested key "${accessorKey}" returned undefined.`); + } + } + return result; + }; + } else { + accessorFn = (originalRow) => originalRow[resolvedColumnDef.accessorKey]; } - }) : /* @__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", { - onClick: (e4) => editable && !props2.multi && showMenu(), - className: "mk-cell-option-select mk-icon-xxsmall mk-icon-rotated", - dangerouslySetInnerHTML: { - __html: uiIconSet["mk-ui-collapse-sm"] + } + if (!id2) { + if (true) { + throw new Error(resolvedColumnDef.accessorFn ? `Columns require an id when using an accessorFn` : `Columns require an id when using a non-string header`); } - })) : /* @__PURE__ */ bn.createElement(bn.Fragment, null))) : editable && !props2.multi ? /* @__PURE__ */ bn.createElement("div", { - className: "mk-cell-option-item" - }, /* @__PURE__ */ bn.createElement("div", { - onClick: (e4) => !props2.multi && showMenu() - }, i18n_default.labels.select)) : props2.editMode == -1 ? /* @__PURE__ */ bn.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", { - onClick: (e4) => editable && showMenu(), - className: "mk-cell-option-new mk-icon-small", - dangerouslySetInnerHTML: { __html: uiIconSet["mk-ui-plus"] } - }) : /* @__PURE__ */ bn.createElement(bn.Fragment, null)); + throw new Error(); + } + let column = { + id: `${String(id2)}`, + accessorFn, + parent, + depth, + columnDef: resolvedColumnDef, + columns: [], + getFlatColumns: memo(() => [true], () => { + var _a2; + return [column, ...(_a2 = column.columns) == null ? void 0 : _a2.flatMap((d5) => d5.getFlatColumns())]; + }, { + key: false, + debug: () => { + var _table$options$debugA; + return (_table$options$debugA = table.options.debugAll) != null ? _table$options$debugA : table.options.debugColumns; + } + }), + getLeafColumns: memo(() => [table._getOrderColumnsFn()], (orderColumns2) => { + var _a2; + if ((_a2 = column.columns) == null ? void 0 : _a2.length) { + let leafColumns = column.columns.flatMap((column2) => column2.getLeafColumns()); + return orderColumns2(leafColumns); + } + return [column]; + }, { + key: false, + debug: () => { + var _table$options$debugA2; + return (_table$options$debugA2 = table.options.debugAll) != null ? _table$options$debugA2 : table.options.debugColumns; + } + }) + }; + column = table._features.reduce((obj, feature) => { + var _a2; + return Object.assign(obj, (_a2 = feature.createColumn) == null ? void 0 : _a2.call(feature, column, table)); + }, column); + return column; +} +function createHeader(table, column, options) { + var _options$id; + const id2 = (_options$id = options.id) != null ? _options$id : column.id; + let header = { + id: id2, + column, + index: options.index, + isPlaceholder: !!options.isPlaceholder, + placeholderId: options.placeholderId, + depth: options.depth, + subHeaders: [], + colSpan: 0, + rowSpan: 0, + headerGroup: null, + getLeafHeaders: () => { + const leafHeaders = []; + const recurseHeader = (h5) => { + if (h5.subHeaders && h5.subHeaders.length) { + h5.subHeaders.map(recurseHeader); + } + leafHeaders.push(h5); + }; + recurseHeader(header); + return leafHeaders; + }, + getContext: () => ({ + table, + header, + column + }) + }; + table._features.forEach((feature) => { + var _a2; + Object.assign(header, (_a2 = feature.createHeader) == null ? void 0 : _a2.call(feature, header, table)); + }); + return header; +} +var Headers = { + createTable: (table) => { + return { + getHeaderGroups: memo(() => [table.getAllColumns(), table.getVisibleLeafColumns(), table.getState().columnPinning.left, table.getState().columnPinning.right], (allColumns, leafColumns, left, right) => { + var _left$map$filter, _right$map$filter; + const leftColumns = (_left$map$filter = left == null ? void 0 : left.map((columnId) => leafColumns.find((d5) => d5.id === columnId)).filter(Boolean)) != null ? _left$map$filter : []; + const rightColumns = (_right$map$filter = right == null ? void 0 : right.map((columnId) => leafColumns.find((d5) => d5.id === columnId)).filter(Boolean)) != null ? _right$map$filter : []; + const centerColumns = leafColumns.filter((column) => !(left == null ? void 0 : left.includes(column.id)) && !(right == null ? void 0 : right.includes(column.id))); + const headerGroups = buildHeaderGroups(allColumns, [...leftColumns, ...centerColumns, ...rightColumns], table); + return headerGroups; + }, { + key: "getHeaderGroups", + debug: () => { + var _table$options$debugA; + return (_table$options$debugA = table.options.debugAll) != null ? _table$options$debugA : table.options.debugHeaders; + } + }), + getCenterHeaderGroups: memo(() => [table.getAllColumns(), table.getVisibleLeafColumns(), table.getState().columnPinning.left, table.getState().columnPinning.right], (allColumns, leafColumns, left, right) => { + leafColumns = leafColumns.filter((column) => !(left == null ? void 0 : left.includes(column.id)) && !(right == null ? void 0 : right.includes(column.id))); + return buildHeaderGroups(allColumns, leafColumns, table, "center"); + }, { + key: "getCenterHeaderGroups", + debug: () => { + var _table$options$debugA2; + return (_table$options$debugA2 = table.options.debugAll) != null ? _table$options$debugA2 : table.options.debugHeaders; + } + }), + getLeftHeaderGroups: memo(() => [table.getAllColumns(), table.getVisibleLeafColumns(), table.getState().columnPinning.left], (allColumns, leafColumns, left) => { + var _left$map$filter2; + const orderedLeafColumns = (_left$map$filter2 = left == null ? void 0 : left.map((columnId) => leafColumns.find((d5) => d5.id === columnId)).filter(Boolean)) != null ? _left$map$filter2 : []; + return buildHeaderGroups(allColumns, orderedLeafColumns, table, "left"); + }, { + key: "getLeftHeaderGroups", + debug: () => { + var _table$options$debugA3; + return (_table$options$debugA3 = table.options.debugAll) != null ? _table$options$debugA3 : table.options.debugHeaders; + } + }), + getRightHeaderGroups: memo(() => [table.getAllColumns(), table.getVisibleLeafColumns(), table.getState().columnPinning.right], (allColumns, leafColumns, right) => { + var _right$map$filter2; + const orderedLeafColumns = (_right$map$filter2 = right == null ? void 0 : right.map((columnId) => leafColumns.find((d5) => d5.id === columnId)).filter(Boolean)) != null ? _right$map$filter2 : []; + return buildHeaderGroups(allColumns, orderedLeafColumns, table, "right"); + }, { + key: "getRightHeaderGroups", + debug: () => { + var _table$options$debugA4; + return (_table$options$debugA4 = table.options.debugAll) != null ? _table$options$debugA4 : table.options.debugHeaders; + } + }), + getFooterGroups: memo(() => [table.getHeaderGroups()], (headerGroups) => { + return [...headerGroups].reverse(); + }, { + key: "getFooterGroups", + debug: () => { + var _table$options$debugA5; + return (_table$options$debugA5 = table.options.debugAll) != null ? _table$options$debugA5 : table.options.debugHeaders; + } + }), + getLeftFooterGroups: memo(() => [table.getLeftHeaderGroups()], (headerGroups) => { + return [...headerGroups].reverse(); + }, { + key: "getLeftFooterGroups", + debug: () => { + var _table$options$debugA6; + return (_table$options$debugA6 = table.options.debugAll) != null ? _table$options$debugA6 : table.options.debugHeaders; + } + }), + getCenterFooterGroups: memo(() => [table.getCenterHeaderGroups()], (headerGroups) => { + return [...headerGroups].reverse(); + }, { + key: "getCenterFooterGroups", + debug: () => { + var _table$options$debugA7; + return (_table$options$debugA7 = table.options.debugAll) != null ? _table$options$debugA7 : table.options.debugHeaders; + } + }), + getRightFooterGroups: memo(() => [table.getRightHeaderGroups()], (headerGroups) => { + return [...headerGroups].reverse(); + }, { + key: "getRightFooterGroups", + debug: () => { + var _table$options$debugA8; + return (_table$options$debugA8 = table.options.debugAll) != null ? _table$options$debugA8 : table.options.debugHeaders; + } + }), + getFlatHeaders: memo(() => [table.getHeaderGroups()], (headerGroups) => { + return headerGroups.map((headerGroup) => { + return headerGroup.headers; + }).flat(); + }, { + key: "getFlatHeaders", + debug: () => { + var _table$options$debugA9; + return (_table$options$debugA9 = table.options.debugAll) != null ? _table$options$debugA9 : table.options.debugHeaders; + } + }), + getLeftFlatHeaders: memo(() => [table.getLeftHeaderGroups()], (left) => { + return left.map((headerGroup) => { + return headerGroup.headers; + }).flat(); + }, { + key: "getLeftFlatHeaders", + debug: () => { + var _table$options$debugA10; + return (_table$options$debugA10 = table.options.debugAll) != null ? _table$options$debugA10 : table.options.debugHeaders; + } + }), + getCenterFlatHeaders: memo(() => [table.getCenterHeaderGroups()], (left) => { + return left.map((headerGroup) => { + return headerGroup.headers; + }).flat(); + }, { + key: "getCenterFlatHeaders", + debug: () => { + var _table$options$debugA11; + return (_table$options$debugA11 = table.options.debugAll) != null ? _table$options$debugA11 : table.options.debugHeaders; + } + }), + getRightFlatHeaders: memo(() => [table.getRightHeaderGroups()], (left) => { + return left.map((headerGroup) => { + return headerGroup.headers; + }).flat(); + }, { + key: "getRightFlatHeaders", + debug: () => { + var _table$options$debugA12; + return (_table$options$debugA12 = table.options.debugAll) != null ? _table$options$debugA12 : table.options.debugHeaders; + } + }), + getCenterLeafHeaders: memo(() => [table.getCenterFlatHeaders()], (flatHeaders) => { + return flatHeaders.filter((header) => { + var _a2; + return !((_a2 = header.subHeaders) == null ? void 0 : _a2.length); + }); + }, { + key: "getCenterLeafHeaders", + debug: () => { + var _table$options$debugA13; + return (_table$options$debugA13 = table.options.debugAll) != null ? _table$options$debugA13 : table.options.debugHeaders; + } + }), + getLeftLeafHeaders: memo(() => [table.getLeftFlatHeaders()], (flatHeaders) => { + return flatHeaders.filter((header) => { + var _a2; + return !((_a2 = header.subHeaders) == null ? void 0 : _a2.length); + }); + }, { + key: "getLeftLeafHeaders", + debug: () => { + var _table$options$debugA14; + return (_table$options$debugA14 = table.options.debugAll) != null ? _table$options$debugA14 : table.options.debugHeaders; + } + }), + getRightLeafHeaders: memo(() => [table.getRightFlatHeaders()], (flatHeaders) => { + return flatHeaders.filter((header) => { + var _a2; + return !((_a2 = header.subHeaders) == null ? void 0 : _a2.length); + }); + }, { + key: "getRightLeafHeaders", + debug: () => { + var _table$options$debugA15; + return (_table$options$debugA15 = table.options.debugAll) != null ? _table$options$debugA15 : table.options.debugHeaders; + } + }), + getLeafHeaders: memo(() => [table.getLeftHeaderGroups(), table.getCenterHeaderGroups(), table.getRightHeaderGroups()], (left, center, right) => { + var _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) => { + return header.getLeafHeaders(); + }).flat(); + }, { + key: "getLeafHeaders", + debug: () => { + var _table$options$debugA16; + return (_table$options$debugA16 = table.options.debugAll) != null ? _table$options$debugA16 : table.options.debugHeaders; + } + }) + }; + } }; - -// 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 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 removeValue = (v3) => { - const newValues = value.filter((f4) => f4.path != v3.path); - setValue(newValues); - props2.saveValue(newValues.map((f4) => f4.path).join(",")); - }; - h2(() => { - 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)) - })) - ); - }, [props2.initialValue]); - const saveOptions = (_options, _value) => { - insertContextItems(props2.plugin, _options, props2.contextTag); - if (!props2.multi) { - setValue( - _value.map((f4) => ({ - path: f4, - label: fileNameToString(folderPathToString(f4)) - })) - ); - props2.saveValue(_value.join(",")); - } else { - const newValue = _value[0]; - if (newValue) { - const newValues = uniq([...value.map((f4) => f4.path), newValue]); - setValue( - newValues.map((f4) => ({ - label: fileNameToString(folderPathToString(f4)), - path: f4 - })) - ); - props2.saveValue(newValues.join(",")); - } +function buildHeaderGroups(allColumns, columnsToGroup, table, headerFamily) { + var _a2; + var _headerGroups$0$heade; + let maxDepth = 0; + const findMaxDepth = function(columns, depth) { + if (depth === void 0) { + depth = 1; } + maxDepth = Math.max(maxDepth, depth); + columns.filter((column) => column.getIsVisible()).forEach((column) => { + var _a3; + if ((_a3 = column.columns) == null ? void 0 : _a3.length) { + findMaxDepth(column.columns, depth + 1); + } + }, 0); }; - const openLink = async (o3) => { - const file = getAbstractFileAtPath(app, o3.path); - if (file) { - openAFile(file, props2.plugin, false); + findMaxDepth(allColumns); + let headerGroups = []; + const createHeaderGroup = (headersToGroup, depth) => { + const headerGroup = { + depth, + id: [headerFamily, `${depth}`].filter(Boolean).join("_"), + headers: [] + }; + const pendingParentHeaders = []; + headersToGroup.forEach((headerToGroup) => { + const latestPendingParentHeader = [...pendingParentHeaders].reverse()[0]; + const isLeafHeader = headerToGroup.column.depth === headerGroup.depth; + let column; + let isPlaceholder = false; + if (isLeafHeader && headerToGroup.column.parent) { + column = headerToGroup.column.parent; + } else { + column = headerToGroup.column; + isPlaceholder = true; + } + if (latestPendingParentHeader && (latestPendingParentHeader == null ? void 0 : latestPendingParentHeader.column) === column) { + latestPendingParentHeader.subHeaders.push(headerToGroup); + } else { + const header = createHeader(table, column, { + id: [headerFamily, depth, column.id, headerToGroup == null ? void 0 : headerToGroup.id].filter(Boolean).join("_"), + isPlaceholder, + placeholderId: isPlaceholder ? `${pendingParentHeaders.filter((d5) => d5.column === column).length}` : void 0, + depth, + index: pendingParentHeaders.length + }); + header.subHeaders.push(headerToGroup); + pendingParentHeaders.push(header); + } + headerGroup.headers.push(headerToGroup); + headerToGroup.headerGroup = headerGroup; + }); + headerGroups.push(headerGroup); + if (depth > 0) { + createHeaderGroup(pendingParentHeaders, depth - 1); } }; - const menuProps = () => { - const _options = !props2.multi ? [{ name: i18n_default.menu.none, value: "" }, ...options] : options; - return { - multi: false, - editable: true, - value: value.map((f4) => f4.path), - options: _options, - saveOptions, - placeholder: i18n_default.labels.contextItemSelectPlaceholder, - searchable: true, - showAll: true, - onHide: () => props2.setEditMode(null) - }; + const bottomHeaders = columnsToGroup.map((column, index) => createHeader(table, column, { + depth: maxDepth, + index + })); + createHeaderGroup(bottomHeaders, maxDepth - 1); + headerGroups.reverse(); + const recurseHeadersForSpans = (headers) => { + const filteredHeaders = headers.filter((header) => header.column.getIsVisible()); + return filteredHeaders.map((header) => { + let colSpan = 0; + let rowSpan = 0; + let childRowSpans = [0]; + if (header.subHeaders && header.subHeaders.length) { + childRowSpans = []; + recurseHeadersForSpans(header.subHeaders).forEach((_ref) => { + let { + colSpan: childColSpan, + rowSpan: childRowSpan + } = _ref; + colSpan += childColSpan; + childRowSpans.push(childRowSpan); + }); + } else { + colSpan = 1; + } + const minChildRowSpan = Math.min(...childRowSpans); + rowSpan = rowSpan + minChildRowSpan; + header.colSpan = colSpan; + header.rowSpan = rowSpan; + return { + colSpan, + rowSpan + }; + }); }; - return /* @__PURE__ */ bn.createElement(OptionCellBase, { - menuProps, - openItem: openLink, - getLabelString: (o3) => o3.label, - value, - multi: props2.multi, - editMode: props2.editMode, - removeValue - }); + recurseHeadersForSpans((_headerGroups$0$heade = (_a2 = headerGroups[0]) == null ? void 0 : _a2.headers) != null ? _headerGroups$0$heade : []); + return headerGroups; +} +var defaultColumnSizing = { + size: 150, + minSize: 20, + maxSize: Number.MAX_SAFE_INTEGER }; - -// src/components/ui/menus/datePickerMenu.tsx -var import_obsidian8 = require("obsidian"); - -// 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" +var getDefaultColumnSizingInfoState = () => ({ + startOffset: null, + startSize: null, + deltaOffset: null, + deltaPercentage: null, + isResizingColumn: false, + columnSizingStart: [] +}); +var ColumnSizing = { + getDefaultColumnDef: () => { + return defaultColumnSizing; }, - xMonths: { - one: "1 month", - other: "{{count}} months" + getInitialState: (state) => { + return { + columnSizing: {}, + columnSizingInfo: getDefaultColumnSizingInfoState(), + ...state + }; }, - aboutXYears: { - one: "about 1 year", - other: "about {{count}} years" + getDefaultOptions: (table) => { + return { + columnResizeMode: "onEnd", + onColumnSizingChange: makeStateUpdater("columnSizing", table), + onColumnSizingInfoChange: makeStateUpdater("columnSizingInfo", table) + }; }, - xYears: { - one: "1 year", - other: "{{count}} years" + createColumn: (column, table) => { + return { + getSize: () => { + var _column$columnDef$min, _ref, _column$columnDef$max; + const columnSize = table.getState().columnSizing[column.id]; + return Math.min(Math.max((_column$columnDef$min = column.columnDef.minSize) != null ? _column$columnDef$min : defaultColumnSizing.minSize, (_ref = columnSize != null ? columnSize : column.columnDef.size) != null ? _ref : defaultColumnSizing.size), (_column$columnDef$max = column.columnDef.maxSize) != null ? _column$columnDef$max : defaultColumnSizing.maxSize); + }, + getStart: (position) => { + const columns = !position ? table.getVisibleLeafColumns() : position === "left" ? table.getLeftVisibleLeafColumns() : table.getRightVisibleLeafColumns(); + const index = columns.findIndex((d5) => d5.id === column.id); + if (index > 0) { + const prevSiblingColumn = columns[index - 1]; + return prevSiblingColumn.getStart(position) + prevSiblingColumn.getSize(); + } + return 0; + }, + resetSize: () => { + table.setColumnSizing((_ref2) => { + let { + [column.id]: _5, + ...rest + } = _ref2; + return rest; + }); + }, + getCanResize: () => { + var _column$columnDef$ena, _table$options$enable; + return ((_column$columnDef$ena = column.columnDef.enableResizing) != null ? _column$columnDef$ena : true) && ((_table$options$enable = table.options.enableColumnResizing) != null ? _table$options$enable : true); + }, + getIsResizing: () => { + return table.getState().columnSizingInfo.isResizingColumn === column.id; + } + }; }, - overXYears: { - one: "over 1 year", - other: "over {{count}} years" + createHeader: (header, table) => { + return { + getSize: () => { + let sum2 = 0; + const recurse = (header2) => { + if (header2.subHeaders.length) { + header2.subHeaders.forEach(recurse); + } else { + var _header$column$getSiz; + sum2 += (_header$column$getSiz = header2.column.getSize()) != null ? _header$column$getSiz : 0; + } + }; + recurse(header); + return sum2; + }, + getStart: () => { + if (header.index > 0) { + const prevSiblingHeader = header.headerGroup.headers[header.index - 1]; + return prevSiblingHeader.getStart() + prevSiblingHeader.getSize(); + } + return 0; + }, + getResizeHandler: () => { + const column = table.getColumn(header.column.id); + const canResize = column.getCanResize(); + return (e4) => { + var _a2; + if (!canResize) { + return; + } + (_a2 = e4.persist) == null ? void 0 : _a2.call(e4); + if (isTouchStartEvent(e4)) { + if (e4.touches && e4.touches.length > 1) { + return; + } + } + const startSize = header.getSize(); + const columnSizingStart = header ? header.getLeafHeaders().map((d5) => [d5.column.id, d5.column.getSize()]) : [[column.id, column.getSize()]]; + const clientX = isTouchStartEvent(e4) ? Math.round(e4.touches[0].clientX) : e4.clientX; + const newColumnSizing = {}; + const updateOffset = (eventType, clientXPos) => { + if (typeof clientXPos !== "number") { + return; + } + table.setColumnSizingInfo((old) => { + var _old$startOffset, _old$startSize; + const deltaOffset = clientXPos - ((_old$startOffset = old == null ? void 0 : old.startOffset) != null ? _old$startOffset : 0); + const deltaPercentage = Math.max(deltaOffset / ((_old$startSize = old == null ? void 0 : old.startSize) != null ? _old$startSize : 0), -0.999999); + old.columnSizingStart.forEach((_ref3) => { + let [columnId, headerSize] = _ref3; + newColumnSizing[columnId] = Math.round(Math.max(headerSize + headerSize * deltaPercentage, 0) * 100) / 100; + }); + return { + ...old, + deltaOffset, + deltaPercentage + }; + }); + if (table.options.columnResizeMode === "onChange" || eventType === "end") { + table.setColumnSizing((old) => ({ + ...old, + ...newColumnSizing + })); + } + }; + const onMove = (clientXPos) => updateOffset("move", clientXPos); + const onEnd = (clientXPos) => { + updateOffset("end", clientXPos); + table.setColumnSizingInfo((old) => ({ + ...old, + isResizingColumn: false, + startOffset: null, + startSize: null, + deltaOffset: null, + deltaPercentage: null, + columnSizingStart: [] + })); + }; + const mouseEvents = { + moveHandler: (e5) => onMove(e5.clientX), + upHandler: (e5) => { + document.removeEventListener("mousemove", mouseEvents.moveHandler); + document.removeEventListener("mouseup", mouseEvents.upHandler); + onEnd(e5.clientX); + } + }; + const touchEvents = { + moveHandler: (e5) => { + if (e5.cancelable) { + e5.preventDefault(); + e5.stopPropagation(); + } + onMove(e5.touches[0].clientX); + return false; + }, + upHandler: (e5) => { + var _a3; + 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); + } + }; + const passiveIfSupported = passiveEventSupported() ? { + passive: false + } : false; + if (isTouchStartEvent(e4)) { + document.addEventListener("touchmove", touchEvents.moveHandler, passiveIfSupported); + document.addEventListener("touchend", touchEvents.upHandler, passiveIfSupported); + } else { + document.addEventListener("mousemove", mouseEvents.moveHandler, passiveIfSupported); + document.addEventListener("mouseup", mouseEvents.upHandler, passiveIfSupported); + } + table.setColumnSizingInfo((old) => ({ + ...old, + startOffset: clientX, + startSize, + deltaOffset: 0, + deltaPercentage: 0, + columnSizingStart, + isResizingColumn: column.id + })); + }; + } + }; }, - almostXYears: { - one: "almost 1 year", - other: "almost {{count}} years" - } -}; -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"; - } + 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); + }, + resetColumnSizing: (defaultState) => { + var _table$initialState$c; + table.setColumnSizing(defaultState ? {} : (_table$initialState$c = table.initialState.columnSizing) != null ? _table$initialState$c : {}); + }, + resetHeaderSizeInfo: (defaultState) => { + var _table$initialState$c2; + table.setColumnSizingInfo(defaultState ? getDefaultColumnSizingInfoState() : (_table$initialState$c2 = table.initialState.columnSizingInfo) != null ? _table$initialState$c2 : getDefaultColumnSizingInfoState()); + }, + getTotalSize: () => { + var _a2; + var _table$getHeaderGroup; + return (_table$getHeaderGroup = (_a2 = table.getHeaderGroups()[0]) == null ? void 0 : _a2.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) => { + 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) => { + 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) => { + return sum2 + header.getSize(); + }, 0)) != null ? _table$getRightHeader : 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 passiveSupported = null; +function passiveEventSupported() { + if (typeof passiveSupported === "boolean") + return passiveSupported; + let supported = false; + try { + const options = { + get passive() { + supported = true; + return false; + } + }; + const noop2 = () => { + }; + window.addEventListener("test", noop2, options); + window.removeEventListener("test", noop2); + } catch (err) { + supported = false; + } + passiveSupported = supported; + return passiveSupported; } - -// node_modules/date-fns/esm/locale/en-US/_lib/formatLong/index.js -var dateFormats = { - full: "EEEE, MMMM do, y", - long: "MMMM do, y", - medium: "MMM d, y", - short: "MM/dd/yyyy" -}; -var timeFormats = { - full: "h:mm:ss a zzzz", - long: "h:mm:ss a z", - medium: "h:mm:ss a", - short: "h:mm a" -}; -var dateTimeFormats = { - full: "{{date}} 'at' {{time}}", - long: "{{date}} 'at' {{time}}", - medium: "{{date}}, {{time}}", - short: "{{date}}, {{time}}" -}; -var formatLong = { - date: buildFormatLongFn({ - formats: dateFormats, - defaultWidth: "full" - }), - time: buildFormatLongFn({ - formats: timeFormats, - defaultWidth: "full" - }), - dateTime: buildFormatLongFn({ - formats: dateTimeFormats, - defaultWidth: "full" - }) -}; -var formatLong_default = formatLong; - -// node_modules/date-fns/esm/locale/en-US/_lib/formatRelative/index.js -var formatRelativeLocale = { - lastWeek: "'last' eeee 'at' p", - yesterday: "'yesterday at' p", - today: "'today at' p", - tomorrow: "'tomorrow at' p", - nextWeek: "eeee 'at' p", - other: "P" -}; -var formatRelative = function formatRelative2(token, _date, _baseDate, _options) { - return formatRelativeLocale[token]; -}; -var formatRelative_default = formatRelative; - -// node_modules/date-fns/esm/locale/_lib/buildLocalizeFn/index.js -function buildLocalizeFn(args) { - return function(dirtyIndex, options) { - var context = options !== null && options !== void 0 && options.context ? String(options.context) : "standalone"; - var valuesArray; - if (context === "formatting" && args.formattingValues) { - var defaultWidth = args.defaultFormattingWidth || args.defaultWidth; - var width = options !== null && options !== void 0 && options.width ? String(options.width) : defaultWidth; - valuesArray = args.formattingValues[width] || args.formattingValues[defaultWidth]; - } else { - var _defaultWidth = args.defaultWidth; - var _width = options !== null && options !== void 0 && options.width ? String(options.width) : args.defaultWidth; - valuesArray = args.values[_width] || args.values[_defaultWidth]; - } - var index = args.argumentCallback ? args.argumentCallback(dirtyIndex) : dirtyIndex; - return valuesArray[index]; - }; +function isTouchStartEvent(e4) { + return e4.type === "touchstart"; } - -// node_modules/date-fns/esm/locale/en-US/_lib/localize/index.js -var eraValues = { - narrow: ["B", "A"], - abbreviated: ["BC", "AD"], - wide: ["Before Christ", "Anno Domini"] -}; -var quarterValues = { - narrow: ["1", "2", "3", "4"], - abbreviated: ["Q1", "Q2", "Q3", "Q4"], - wide: ["1st quarter", "2nd quarter", "3rd quarter", "4th quarter"] -}; -var monthValues = { - narrow: ["J", "F", "M", "A", "M", "J", "J", "A", "S", "O", "N", "D"], - abbreviated: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"], - wide: ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"] -}; -var dayValues = { - narrow: ["S", "M", "T", "W", "T", "F", "S"], - short: ["Su", "Mo", "Tu", "We", "Th", "Fr", "Sa"], - abbreviated: ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"], - wide: ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"] -}; -var dayPeriodValues = { - narrow: { - am: "a", - pm: "p", - midnight: "mi", - noon: "n", - morning: "morning", - afternoon: "afternoon", - evening: "evening", - night: "night" - }, - abbreviated: { - am: "AM", - pm: "PM", - midnight: "midnight", - noon: "noon", - morning: "morning", - afternoon: "afternoon", - evening: "evening", - night: "night" - }, - wide: { - am: "a.m.", - pm: "p.m.", - midnight: "midnight", - noon: "noon", - morning: "morning", - afternoon: "afternoon", - evening: "evening", - night: "night" - } -}; -var 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" +var Expanding = { + getInitialState: (state) => { + return { + expanded: {}, + ...state + }; }, - abbreviated: { - am: "AM", - pm: "PM", - midnight: "midnight", - noon: "noon", - morning: "in the morning", - afternoon: "in the afternoon", - evening: "in the evening", - night: "at night" + getDefaultOptions: (table) => { + return { + onExpandedChange: makeStateUpdater("expanded", table), + paginateExpandedRows: true + }; }, - wide: { - am: "a.m.", - pm: "p.m.", - midnight: "midnight", - noon: "noon", - morning: "in the morning", - afternoon: "in the afternoon", - evening: "in the evening", - night: "at night" - } -}; -var 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 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); + createTable: (table) => { + let registered = false; + let queued = false; return { - value, - rest + _autoResetExpanded: () => { + var _ref, _table$options$autoRe; + if (!registered) { + table._queue(() => { + registered = true; + }); + return; + } + if ((_ref = (_table$options$autoRe = table.options.autoResetAll) != null ? _table$options$autoRe : table.options.autoResetExpanded) != null ? _ref : !table.options.manualExpanding) { + if (queued) + return; + queued = true; + table._queue(() => { + table.resetExpanded(); + queued = false; + }); + } + }, + setExpanded: (updater) => { + var _a2, _b2; + return (_b2 = (_a2 = table.options).onExpandedChange) == null ? void 0 : _b2.call(_a2, updater); + }, + toggleAllRowsExpanded: (expanded) => { + if (expanded != null ? expanded : !table.getIsAllRowsExpanded()) { + table.setExpanded(true); + } else { + table.setExpanded({}); + } + }, + 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 : {}); + }, + getCanSomeRowsExpand: () => { + return table.getRowModel().flatRows.some((row) => row.getCanExpand()); + }, + getToggleAllRowsExpandedHandler: () => { + return (e4) => { + var _a2; + (_a2 = e4.persist) == null ? void 0 : _a2.call(e4); + table.toggleAllRowsExpanded(); + }; + }, + getIsSomeRowsExpanded: () => { + const expanded = table.getState().expanded; + return expanded === true || Object.values(expanded).some(Boolean); + }, + getIsAllRowsExpanded: () => { + const expanded = table.getState().expanded; + if (typeof expanded === "boolean") { + return expanded === true; + } + if (!Object.keys(expanded).length) { + return false; + } + if (table.getRowModel().flatRows.some((row) => !row.getIsExpanded())) { + return false; + } + return true; + }, + getExpandedDepth: () => { + let maxDepth = 0; + const rowIds = table.getState().expanded === true ? Object.keys(table.getRowModel().rowsById) : Object.keys(table.getState().expanded); + rowIds.forEach((id2) => { + const splitId = id2.split("."); + maxDepth = Math.max(maxDepth, splitId.length); + }); + return maxDepth; + }, + getPreExpandedRowModel: () => table.getSortedRowModel(), + getExpandedRowModel: () => { + if (!table._getExpandedRowModel && table.options.getExpandedRowModel) { + table._getExpandedRowModel = table.options.getExpandedRowModel(table); + } + if (table.options.manualExpanding || !table._getExpandedRowModel) { + return table.getPreExpandedRowModel(); + } + return table._getExpandedRowModel(); + } }; - }; -} -function findKey(object, predicate) { - for (var key2 in object) { - if (object.hasOwnProperty(key2) && predicate(object[key2])) { - return key2; - } - } - return void 0; -} -function findIndex(array, predicate) { - for (var key2 = 0; key2 < array.length; key2++) { - if (predicate(array[key2])) { - return key2; - } - } - return void 0; -} - -// node_modules/date-fns/esm/locale/_lib/buildMatchPatternFn/index.js -function buildMatchPatternFn(args) { - return function(string) { - var options = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {}; - var matchResult = string.match(args.matchPattern); - if (!matchResult) - return null; - var matchedString = matchResult[0]; - var parseResult = string.match(args.parsePattern); - if (!parseResult) - return null; - var value = args.valueCallback ? args.valueCallback(parseResult[0]) : parseResult[0]; - value = options.valueCallback ? options.valueCallback(value) : value; - var rest = string.slice(matchedString.length); + }, + createRow: (row, table) => { return { - value, - rest + toggleExpanded: (expanded) => { + table.setExpanded((old) => { + var _expanded; + const exists = old === true ? true : !!(old == null ? void 0 : old[row.id]); + let oldExpanded = {}; + if (old === true) { + Object.keys(table.getRowModel().rowsById).forEach((rowId) => { + oldExpanded[rowId] = true; + }); + } else { + oldExpanded = old; + } + expanded = (_expanded = expanded) != null ? _expanded : !exists; + if (!exists && expanded) { + return { + ...oldExpanded, + [row.id]: true + }; + } + if (exists && !expanded) { + const { + [row.id]: _5, + ...rest + } = oldExpanded; + return rest; + } + return old; + }); + }, + 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])); + }, + 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); + }, + getToggleExpandedHandler: () => { + const canExpand = row.getCanExpand(); + return () => { + if (!canExpand) + return; + row.toggleExpanded(); + }; + } }; - }; -} - -// 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 includesString = (row, columnId, filterValue) => { + var _a2; + const search = filterValue.toLowerCase(); + return Boolean((_a2 = row.getValue(columnId)) == null ? void 0 : _a2.toLowerCase().includes(search)); }; -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] +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 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 +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 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] +equalsString.autoRemove = (val) => testFalsey(val); +var arrIncludes = (row, columnId, filterValue) => { + var _a2; + return (_a2 = row.getValue(columnId)) == null ? void 0 : _a2.includes(filterValue); }; -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 +arrIncludes.autoRemove = (val) => testFalsey(val) || !(val == null ? void 0 : 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 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 - } +arrIncludesAll.autoRemove = (val) => testFalsey(val) || !(val == null ? void 0 : 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 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" - }) +arrIncludesSome.autoRemove = (val) => testFalsey(val) || !(val == null ? void 0 : val.length); +var equals = (row, columnId, filterValue) => { + return row.getValue(columnId) === filterValue; }; -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 - } +equals.autoRemove = (val) => testFalsey(val); +var weakEquals = (row, columnId, filterValue) => { + return row.getValue(columnId) == filterValue; }; -var en_US_default = locale; - -// 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"); +weakEquals.autoRemove = (val) => testFalsey(val); +var inNumberRange = (row, columnId, filterValue) => { + let [min3, max3] = filterValue; + const rowValue = row.getValue(columnId); + return rowValue >= min3 && rowValue <= max3; +}; +inNumberRange.resolveFilterValue = (val) => { + let [unsafeMin, unsafeMax] = val; + let parsedMin = typeof unsafeMin !== "number" ? parseFloat(unsafeMin) : unsafeMin; + let parsedMax = typeof unsafeMax !== "number" ? parseFloat(unsafeMax) : unsafeMax; + let min3 = unsafeMin === null || Number.isNaN(parsedMin) ? -Infinity : parsedMin; + let max3 = unsafeMax === null || Number.isNaN(parsedMax) ? Infinity : parsedMax; + if (min3 > max3) { + const temp = min3; + min3 = max3; + max3 = temp; } + return [min3, max3]; +}; +inNumberRange.autoRemove = (val) => testFalsey(val) || testFalsey(val[0]) && testFalsey(val[1]); +var filterFns = { + includesString, + includesStringSensitive, + equalsString, + arrIncludes, + arrIncludesAll, + arrIncludesSome, + equals, + weakEquals, + inNumberRange +}; +function testFalsey(val) { + return val === void 0 || val === null || val === ""; } - -// node_modules/date-fns/esm/isDate/index.js -function _typeof(obj) { - "@babel/helpers - typeof"; - if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { - _typeof = function _typeof5(obj2) { - return typeof obj2; +var Filters = { + getDefaultColumnDef: () => { + return { + filterFn: "auto" }; - } else { - _typeof = function _typeof5(obj2) { - return obj2 && typeof Symbol === "function" && obj2.constructor === Symbol && obj2 !== Symbol.prototype ? "symbol" : typeof obj2; + }, + getInitialState: (state) => { + return { + columnFilters: [], + globalFilter: void 0, + ...state }; - } - return _typeof(obj); -} -function isDate(value) { - requiredArgs(1, arguments); - return value instanceof Date || _typeof(value) === "object" && Object.prototype.toString.call(value) === "[object Date]"; -} - -// node_modules/date-fns/esm/toDate/index.js -function _typeof2(obj) { - "@babel/helpers - typeof"; - if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { - _typeof2 = function _typeof5(obj2) { - return typeof obj2; + }, + getDefaultOptions: (table) => { + return { + onColumnFiltersChange: makeStateUpdater("columnFilters", table), + onGlobalFilterChange: makeStateUpdater("globalFilter", table), + filterFromLeafRows: false, + 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(); + return typeof value === "string" || typeof value === "number"; + } }; - } else { - _typeof2 = function _typeof5(obj2) { - return obj2 && typeof Symbol === "function" && obj2.constructor === Symbol && obj2 !== Symbol.prototype ? "symbol" : typeof obj2; + }, + createColumn: (column, table) => { + return { + getAutoFilterFn: () => { + const firstRow = table.getCoreRowModel().flatRows[0]; + const value = firstRow == null ? void 0 : firstRow.getValue(column.id); + if (typeof value === "string") { + return filterFns.includesString; + } + if (typeof value === "number") { + return filterFns.inNumberRange; + } + if (typeof value === "boolean") { + return filterFns.equals; + } + if (value !== null && typeof value === "object") { + return filterFns.equals; + } + if (Array.isArray(value)) { + return filterFns.arrIncludes; + } + return filterFns.weakEquals; + }, + getFilterFn: () => { + var _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]; + }, + 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; + }, + 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; + }, + 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; + }, + setFilterValue: (value) => { + table.setColumnFilters((old) => { + const filterFn = column.getFilterFn(); + const previousfilter = old == null ? void 0 : old.find((d5) => d5.id === column.id); + const newFilter = functionalUpdate(value, previousfilter ? previousfilter.value : void 0); + if (shouldAutoRemoveFilter(filterFn, newFilter, column)) { + var _old$filter; + return (_old$filter = old == null ? void 0 : old.filter((d5) => d5.id !== column.id)) != null ? _old$filter : []; + } + const newFilterObj = { + id: column.id, + value: newFilter + }; + if (previousfilter) { + var _old$map; + return (_old$map = old == null ? void 0 : old.map((d5) => { + if (d5.id === column.id) { + return newFilterObj; + } + return d5; + })) != null ? _old$map : []; + } + if (old == null ? void 0 : old.length) { + return [...old, newFilterObj]; + } + return [newFilterObj]; + }); + }, + _getFacetedRowModel: table.options.getFacetedRowModel && table.options.getFacetedRowModel(table, column.id), + getFacetedRowModel: () => { + if (!column._getFacetedRowModel) { + return table.getPreFilteredRowModel(); + } + return column._getFacetedRowModel(); + }, + _getFacetedUniqueValues: table.options.getFacetedUniqueValues && table.options.getFacetedUniqueValues(table, column.id), + getFacetedUniqueValues: () => { + if (!column._getFacetedUniqueValues) { + return /* @__PURE__ */ new Map(); + } + return column._getFacetedUniqueValues(); + }, + _getFacetedMinMaxValues: table.options.getFacetedMinMaxValues && table.options.getFacetedMinMaxValues(table, column.id), + getFacetedMinMaxValues: () => { + if (!column._getFacetedMinMaxValues) { + return void 0; + } + return column._getFacetedMinMaxValues(); + } + }; + }, + createRow: (row, table) => { + return { + columnFilters: {}, + columnFiltersMeta: {} + }; + }, + createTable: (table) => { + return { + getGlobalAutoFilterFn: () => { + return filterFns.includesString; + }, + getGlobalFilterFn: () => { + var _a2; + var _table$options$filter2; + 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]; + }, + 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) => { + const column = leafColumns.find((d5) => d5.id === filter.id); + if (column) { + const filterFn = column.getFilterFn(); + if (shouldAutoRemoveFilter(filterFn, filter.value, column)) { + return false; + } + } + return true; + }); + }; + (_b2 = (_a2 = table.options).onColumnFiltersChange) == null ? void 0 : _b2.call(_a2, updateFn); + }, + setGlobalFilter: (updater) => { + var _a2, _b2; + (_b2 = (_a2 = table.options).onGlobalFilterChange) == null ? void 0 : _b2.call(_a2, 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 : []); + }, + getPreFilteredRowModel: () => table.getCoreRowModel(), + getFilteredRowModel: () => { + if (!table._getFilteredRowModel && table.options.getFilteredRowModel) { + table._getFilteredRowModel = table.options.getFilteredRowModel(table); + } + if (table.options.manualFiltering || !table._getFilteredRowModel) { + return table.getPreFilteredRowModel(); + } + return table._getFilteredRowModel(); + }, + _getGlobalFacetedRowModel: table.options.getFacetedRowModel && table.options.getFacetedRowModel(table, "__global__"), + getGlobalFacetedRowModel: () => { + if (table.options.manualFiltering || !table._getGlobalFacetedRowModel) { + return table.getPreFilteredRowModel(); + } + return table._getGlobalFacetedRowModel(); + }, + _getGlobalFacetedUniqueValues: table.options.getFacetedUniqueValues && table.options.getFacetedUniqueValues(table, "__global__"), + getGlobalFacetedUniqueValues: () => { + if (!table._getGlobalFacetedUniqueValues) { + return /* @__PURE__ */ new Map(); + } + return table._getGlobalFacetedUniqueValues(); + }, + _getGlobalFacetedMinMaxValues: table.options.getFacetedMinMaxValues && table.options.getFacetedMinMaxValues(table, "__global__"), + getGlobalFacetedMinMaxValues: () => { + if (!table._getGlobalFacetedMinMaxValues) { + return; + } + return table._getGlobalFacetedMinMaxValues(); + } }; } - return _typeof2(obj); -} -function toDate(argument) { - requiredArgs(1, arguments); - var argStr = Object.prototype.toString.call(argument); - if (argument instanceof Date || _typeof2(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); - } -} - -// node_modules/date-fns/esm/isValid/index.js -function isValid(dirtyDate) { - requiredArgs(1, arguments); - if (!isDate(dirtyDate) && typeof dirtyDate !== "number") { - return false; - } - var date = toDate(dirtyDate); - return !isNaN(Number(date)); -} - -// node_modules/date-fns/esm/_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/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/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_DAY = 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_DAY) + 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_WEEK = 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_WEEK) + 1; -} - -// node_modules/date-fns/esm/_lib/defaultOptions/index.js -var defaultOptions2 = {}; -function getDefaultOptions() { - return defaultOptions2; -} - -// 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"); - } - 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; - } -} - -// 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_WEEK2 = 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_WEEK2) + 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; +}; +function shouldAutoRemoveFilter(filterFn, value, column) { + return (filterFn && filterFn.autoRemove ? filterFn.autoRemove(value, column) : false) || typeof value === "undefined" || typeof value === "string" && !value; } - -// node_modules/date-fns/esm/_lib/format/lightFormatters/index.js -var formatters = { - y: function y3(date, token) { - var signedYear = date.getUTCFullYear(); - var year = signedYear > 0 ? signedYear : 1 - signedYear; - return addLeadingZeros(token === "yy" ? year % 100 : year, token.length); - }, - M: function M3(date, token) { - var month = date.getUTCMonth(); - return token === "M" ? String(month + 1) : addLeadingZeros(month + 1, 2); - }, - d: function d3(date, token) { - return addLeadingZeros(date.getUTCDate(), token.length); - }, - a: function a3(date, token) { - var dayPeriodEnumValue = date.getUTCHours() / 12 >= 1 ? "pm" : "am"; - switch (token) { - case "a": - case "aa": - return dayPeriodEnumValue.toUpperCase(); - case "aaa": - return dayPeriodEnumValue; - case "aaaaa": - return dayPeriodEnumValue[0]; - case "aaaa": - default: - return dayPeriodEnumValue === "am" ? "a.m." : "p.m."; - } - }, - h: function h3(date, token) { - return addLeadingZeros(date.getUTCHours() % 12 || 12, token.length); - }, - H: function H3(date, token) { - return addLeadingZeros(date.getUTCHours(), token.length); - }, - m: function m3(date, token) { - return addLeadingZeros(date.getUTCMinutes(), token.length); - }, - s: function s3(date, token) { - return addLeadingZeros(date.getUTCSeconds(), token.length); - }, - S: function S2(date, token) { - var numberOfDigits = token.length; - var milliseconds = date.getUTCMilliseconds(); - var fractionalSeconds = Math.floor(milliseconds * Math.pow(10, numberOfDigits - 3)); - return addLeadingZeros(fractionalSeconds, token.length); - } +var sum = (columnId, _leafRows, childRows) => { + return childRows.reduce((sum2, next) => { + const nextValue = next.getValue(columnId); + return sum2 + (typeof nextValue === "number" ? nextValue : 0); + }, 0); }; -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 min2 = (columnId, _leafRows, childRows) => { + let min3; + childRows.forEach((row) => { + const value = row.getValue(columnId); + if (value != null && (min3 > value || min3 === void 0 && value >= value)) { + min3 = value; + } + }); + return min3; }; -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" - }); +var max2 = (columnId, _leafRows, childRows) => { + let max3; + childRows.forEach((row) => { + const value = row.getValue(columnId); + if (value != null && (max3 < value || max3 === void 0 && value >= value)) { + max3 = value; } - }, - y: function y4(date, token, localize2) { - if (token === "yo") { - var signedYear = date.getUTCFullYear(); - var year = signedYear > 0 ? signedYear : 1 - signedYear; - return localize2.ordinalNumber(year, { - unit: "year" - }); + }); + return max3; +}; +var extent = (columnId, _leafRows, childRows) => { + let min3; + let max3; + childRows.forEach((row) => { + const value = row.getValue(columnId); + if (value != null) { + if (min3 === void 0) { + if (value >= value) + min3 = max3 = value; + } else { + if (min3 > value) + min3 = value; + if (max3 < value) + max3 = value; + } } - 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); + }); + return [min3, max3]; +}; +var mean = (columnId, leafRows) => { + let count2 = 0; + let sum2 = 0; + leafRows.forEach((row) => { + let value = row.getValue(columnId); + if (value != null && (value = +value) >= value) { + ++count2, sum2 += value; } - if (token === "Yo") { - return localize2.ordinalNumber(weekYear, { - unit: "year" - }); + }); + if (count2) + return sum2 / count2; + return; +}; +var median = (columnId, leafRows) => { + if (!leafRows.length) { + return; + } + let min3 = 0; + let max3 = 0; + leafRows.forEach((row) => { + let value = row.getValue(columnId); + if (typeof value === "number") { + min3 = Math.min(min3, value); + max3 = Math.max(max3, value); } - return addLeadingZeros(weekYear, token.length); - }, - R: function R2(date, token) { - var isoWeekYear = getUTCISOWeekYear(date); - return addLeadingZeros(isoWeekYear, token.length); + }); + return (min3 + max3) / 2; +}; +var unique = (columnId, leafRows) => { + return Array.from(new Set(leafRows.map((d5) => d5.getValue(columnId))).values()); +}; +var uniqueCount = (columnId, leafRows) => { + return new Set(leafRows.map((d5) => d5.getValue(columnId))).size; +}; +var count = (_columnId, leafRows) => { + return leafRows.length; +}; +var aggregationFns = { + sum, + min: min2, + max: max2, + extent, + mean, + median, + unique, + uniqueCount, + count +}; +var Grouping = { + getDefaultColumnDef: () => { + return { + aggregatedCell: (props2) => { + var _a2, _b2; + var _toString; + return (_toString = (_b2 = (_a2 = props2.getValue()) == null ? void 0 : _a2.toString) == null ? void 0 : _b2.call(_a2)) != null ? _toString : null; + }, + aggregationFn: "auto" + }; }, - u: function u3(date, token) { - var year = date.getUTCFullYear(); - return addLeadingZeros(year, token.length); + getInitialState: (state) => { + return { + grouping: [], + ...state + }; }, - 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" - }); - } + getDefaultOptions: (table) => { + return { + onGroupingChange: makeStateUpdater("grouping", table), + groupedColumnMode: "reorder" + }; }, - 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" + createColumn: (column, table) => { + return { + toggleGrouping: () => { + table.setGrouping((old) => { + if (old == null ? void 0 : old.includes(column.id)) { + return old.filter((d5) => d5 !== column.id); + } + return [...old != null ? old : [], column.id]; }); - } + }, + getCanGroup: () => { + var _ref, _ref2, _ref3, _column$columnDef$ena; + return (_ref = (_ref2 = (_ref3 = (_column$columnDef$ena = column.columnDef.enableGrouping) != null ? _column$columnDef$ena : true) != null ? _ref3 : table.options.enableGrouping) != null ? _ref2 : true) != null ? _ref : !!column.accessorFn; + }, + getIsGrouped: () => { + var _a2; + return (_a2 = table.getState().grouping) == null ? void 0 : _a2.includes(column.id); + }, + getGroupedIndex: () => { + var _a2; + return (_a2 = table.getState().grouping) == null ? void 0 : _a2.indexOf(column.id); + }, + getToggleGroupingHandler: () => { + const canGroup = column.getCanGroup(); + return () => { + if (!canGroup) + return; + column.toggleGrouping(); + }; + }, + getAutoAggregationFn: () => { + const firstRow = table.getCoreRowModel().flatRows[0]; + const value = firstRow == null ? void 0 : firstRow.getValue(column.id); + if (typeof value === "number") { + return aggregationFns.sum; + } + if (Object.prototype.toString.call(value) === "[object Date]") { + return aggregationFns.extent; + } + }, + getAggregationFn: () => { + var _a2; + var _table$options$aggreg; + 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]; + } + }; }, - 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" - }); - } + createTable: (table) => { + return { + setGrouping: (updater) => { + var _a2, _b2; + return (_b2 = (_a2 = table.options).onGroupingChange) == null ? void 0 : _b2.call(_a2, 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 : []); + }, + getPreGroupedRowModel: () => table.getFilteredRowModel(), + getGroupedRowModel: () => { + if (!table._getGroupedRowModel && table.options.getGroupedRowModel) { + table._getGroupedRowModel = table.options.getGroupedRowModel(table); + } + if (table.options.manualGrouping || !table._getGroupedRowModel) { + return table.getPreGroupedRowModel(); + } + return table._getGroupedRowModel(); + } + }; }, - 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" - }); - } + createRow: (row) => { + return { + getIsGrouped: () => !!row.groupingColumnId, + _groupingValuesCache: {} + }; }, - 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); + createCell: (cell, column, row, table) => { + return { + 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); + } + }; + } +}; +function orderColumns(leafColumns, grouping, groupedColumnMode) { + if (!(grouping == null ? void 0 : grouping.length) || !groupedColumnMode) { + return leafColumns; + } + const nonGroupingColumns = leafColumns.filter((col) => !grouping.includes(col.id)); + if (groupedColumnMode === "remove") { + return nonGroupingColumns; + } + const groupingColumns = grouping.map((g4) => leafColumns.find((col) => col.id === g4)).filter(Boolean); + return [...groupingColumns, ...nonGroupingColumns]; +} +var Ordering = { + getInitialState: (state) => { + return { + columnOrder: [], + ...state + }; }, - I: function I3(date, token, localize2) { - var isoWeek = getUTCISOWeek(date); - if (token === "Io") { - return localize2.ordinalNumber(isoWeek, { - unit: "week" - }); - } - return addLeadingZeros(isoWeek, token.length); + getDefaultOptions: (table) => { + return { + onColumnOrderChange: makeStateUpdater("columnOrder", table) + }; }, - d: function d4(date, token, localize2) { - if (token === "do") { - return localize2.ordinalNumber(date.getUTCDate(), { - unit: "date" - }); - } - return lightFormatters_default.d(date, token); + createTable: (table) => { + return { + setColumnOrder: (updater) => { + var _a2, _b2; + return (_b2 = (_a2 = table.options).onColumnOrderChange) == null ? void 0 : _b2.call(_a2, 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)) { + orderedColumns = columns; + } else { + const columnOrderCopy = [...columnOrder]; + const columnsCopy = [...columns]; + while (columnsCopy.length && columnOrderCopy.length) { + const targetColumnId = columnOrderCopy.shift(); + const foundIndex = columnsCopy.findIndex((d5) => d5.id === targetColumnId); + if (foundIndex > -1) { + orderedColumns.push(columnsCopy.splice(foundIndex, 1)[0]); + } + } + orderedColumns = [...orderedColumns, ...columnsCopy]; + } + return orderColumns(orderedColumns, grouping, groupedColumnMode); + }, { + key: "getOrderColumnsFn" + }) + }; + } +}; +var defaultPageIndex = 0; +var defaultPageSize = 10; +var getDefaultPaginationState = () => ({ + pageIndex: defaultPageIndex, + pageSize: defaultPageSize +}); +var Pagination = { + getInitialState: (state) => { + return { + ...state, + pagination: { + ...getDefaultPaginationState(), + ...state == null ? void 0 : state.pagination + } + }; }, - D: function D2(date, token, localize2) { - var dayOfYear = getUTCDayOfYear(date); - if (token === "Do") { - return localize2.ordinalNumber(dayOfYear, { - unit: "dayOfYear" - }); - } - return addLeadingZeros(dayOfYear, token.length); + getDefaultOptions: (table) => { + return { + onPaginationChange: makeStateUpdater("pagination", table) + }; }, - 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" + createTable: (table) => { + let registered = false; + let queued = false; + return { + _autoResetPageIndex: () => { + var _ref, _table$options$autoRe; + if (!registered) { + table._queue(() => { + registered = true; + }); + return; + } + if ((_ref = (_table$options$autoRe = table.options.autoResetAll) != null ? _table$options$autoRe : table.options.autoResetPageIndex) != null ? _ref : !table.options.manualPagination) { + if (queued) + return; + queued = true; + table._queue(() => { + table.resetPageIndex(); + queued = false; + }); + } + }, + setPagination: (updater) => { + 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); + }, + resetPagination: (defaultState) => { + var _table$initialState$p; + table.setPagination(defaultState ? getDefaultPaginationState() : (_table$initialState$p = table.initialState.pagination) != null ? _table$initialState$p : getDefaultPaginationState()); + }, + setPageIndex: (updater) => { + table.setPagination((old) => { + let pageIndex = functionalUpdate(updater, old.pageIndex); + const maxPageIndex = typeof table.options.pageCount === "undefined" || table.options.pageCount === -1 ? Number.MAX_SAFE_INTEGER : table.options.pageCount - 1; + pageIndex = Math.max(0, Math.min(pageIndex, maxPageIndex)); + return { + ...old, + pageIndex + }; }); - case "EEEEEE": - return localize2.day(dayOfWeek, { - width: "short", - context: "formatting" + }, + 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); + }, + 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); + }, + setPageSize: (updater) => { + table.setPagination((old) => { + const pageSize = Math.max(1, functionalUpdate(updater, old.pageSize)); + const topRowIndex = old.pageSize * old.pageIndex; + const pageIndex = Math.floor(topRowIndex / pageSize); + return { + ...old, + pageIndex, + pageSize + }; }); - case "EEEE": - default: - return localize2.day(dayOfWeek, { - width: "wide", - context: "formatting" + }, + setPageCount: (updater) => table.setPagination((old) => { + var _table$options$pageCo; + let newPageCount = functionalUpdate(updater, (_table$options$pageCo = table.options.pageCount) != null ? _table$options$pageCo : -1); + if (typeof newPageCount === "number") { + newPageCount = Math.max(-1, newPageCount); + } + return { + ...old, + pageCount: newPageCount + }; + }), + getPageOptions: memo(() => [table.getPageCount()], (pageCount) => { + let pageOptions = []; + if (pageCount && pageCount > 0) { + pageOptions = [...new Array(pageCount)].fill(null).map((_5, i4) => i4); + } + return pageOptions; + }, { + key: "getPageOptions", + debug: () => { + var _table$options$debugA; + return (_table$options$debugA = table.options.debugAll) != null ? _table$options$debugA : table.options.debugTable; + } + }), + getCanPreviousPage: () => table.getState().pagination.pageIndex > 0, + getCanNextPage: () => { + const { + pageIndex + } = table.getState().pagination; + const pageCount = table.getPageCount(); + if (pageCount === -1) { + return true; + } + if (pageCount === 0) { + return false; + } + return pageIndex < pageCount - 1; + }, + previousPage: () => { + return table.setPageIndex((old) => old - 1); + }, + nextPage: () => { + return table.setPageIndex((old) => { + return old + 1; }); - } + }, + getPrePaginationRowModel: () => table.getExpandedRowModel(), + getPaginationRowModel: () => { + if (!table._getPaginationRowModel && table.options.getPaginationRowModel) { + table._getPaginationRowModel = table.options.getPaginationRowModel(table); + } + if (table.options.manualPagination || !table._getPaginationRowModel) { + return table.getPrePaginationRowModel(); + } + return table._getPaginationRowModel(); + }, + getPageCount: () => { + var _table$options$pageCo2; + return (_table$options$pageCo2 = table.options.pageCount) != null ? _table$options$pageCo2 : Math.ceil(table.getPrePaginationRowModel().rows.length / table.getState().pagination.pageSize); + } + }; + } +}; +var getDefaultPinningState = () => ({ + left: [], + right: [] +}); +var Pinning = { + getInitialState: (state) => { + return { + columnPinning: getDefaultPinningState(), + ...state + }; }, - 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" - }); - } + getDefaultOptions: (table) => { + return { + onColumnPinningChange: makeStateUpdater("columnPinning", table) + }; }, - 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" + createColumn: (column, table) => { + return { + pin: (position) => { + const columnIds = column.getLeafColumns().map((d5) => d5.id).filter(Boolean); + table.setColumnPinning((old) => { + var _old$left3, _old$right3; + if (position === "right") { + var _old$left, _old$right; + return { + left: ((_old$left = old == null ? void 0 : old.left) != null ? _old$left : []).filter((d5) => !(columnIds == null ? 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] + }; + } + 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))) + }; + } + 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))) + }; }); - case "cccc": - default: - return localize2.day(dayOfWeek, { - width: "wide", - context: "standalone" + }, + getCanPin: () => { + const leafColumns = column.getLeafColumns(); + return leafColumns.some((d5) => { + var _d$columnDef$enablePi, _table$options$enable; + return ((_d$columnDef$enablePi = d5.columnDef.enablePinning) != null ? _d$columnDef$enablePi : true) && ((_table$options$enable = table.options.enablePinning) != null ? _table$options$enable : true); }); - } + }, + getIsPinned: () => { + const leafColumnIds = column.getLeafColumns().map((d5) => d5.id); + const { + left, + right + } = table.getState().columnPinning; + const isLeft = leafColumnIds.some((d5) => left == null ? void 0 : left.includes(d5)); + const isRight = leafColumnIds.some((d5) => right == null ? void 0 : right.includes(d5)); + return isLeft ? "left" : isRight ? "right" : false; + }, + getPinnedIndex: () => { + var _a2, _b2; + var _table$getState$colum; + 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; + } + }; }, - 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" - }); - } + createRow: (row, table) => { + return { + getCenterVisibleCells: memo(() => [row._getAllVisibleCells(), table.getState().columnPinning.left, table.getState().columnPinning.right], (allCells, left, right) => { + const leftAndRight = [...left != null ? left : [], ...right != null ? right : []]; + return allCells.filter((d5) => !leftAndRight.includes(d5.column.id)); + }, { + key: false, + debug: () => { + var _table$options$debugA; + return (_table$options$debugA = table.options.debugAll) != null ? _table$options$debugA : table.options.debugRows; + } + }), + getLeftVisibleCells: memo(() => [row._getAllVisibleCells(), table.getState().columnPinning.left, ,], (allCells, left) => { + const cells = (left != null ? left : []).map((columnId) => allCells.find((cell) => cell.column.id === columnId)).filter(Boolean).map((d5) => ({ + ...d5, + position: "left" + })); + return cells; + }, { + key: false, + debug: () => { + var _table$options$debugA2; + return (_table$options$debugA2 = table.options.debugAll) != null ? _table$options$debugA2 : table.options.debugRows; + } + }), + getRightVisibleCells: memo(() => [row._getAllVisibleCells(), table.getState().columnPinning.right], (allCells, right) => { + const cells = (right != null ? right : []).map((columnId) => allCells.find((cell) => cell.column.id === columnId)).filter(Boolean).map((d5) => ({ + ...d5, + position: "right" + })); + return cells; + }, { + key: false, + debug: () => { + var _table$options$debugA3; + return (_table$options$debugA3 = table.options.debugAll) != null ? _table$options$debugA3 : table.options.debugRows; + } + }) + }; }, - 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" - }); - } + createTable: (table) => { + return { + setColumnPinning: (updater) => { + var _a2, _b2; + return (_b2 = (_a2 = table.options).onColumnPinningChange) == null ? void 0 : _b2.call(_a2, 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()); + }, + getIsSomeColumnsPinned: (position) => { + var _a2, _b2, _c2; + 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)); + } + return Boolean((_c2 = pinningState[position]) == null ? void 0 : _c2.length); + }, + getLeftLeafColumns: memo(() => [table.getAllLeafColumns(), table.getState().columnPinning.left], (allColumns, left) => { + return (left != null ? left : []).map((columnId) => allColumns.find((column) => column.id === columnId)).filter(Boolean); + }, { + key: "getLeftLeafColumns", + debug: () => { + var _table$options$debugA4; + return (_table$options$debugA4 = table.options.debugAll) != null ? _table$options$debugA4 : table.options.debugColumns; + } + }), + getRightLeafColumns: memo(() => [table.getAllLeafColumns(), table.getState().columnPinning.right], (allColumns, right) => { + return (right != null ? right : []).map((columnId) => allColumns.find((column) => column.id === columnId)).filter(Boolean); + }, { + key: "getRightLeafColumns", + debug: () => { + var _table$options$debugA5; + return (_table$options$debugA5 = table.options.debugAll) != null ? _table$options$debugA5 : table.options.debugColumns; + } + }), + getCenterLeafColumns: memo(() => [table.getAllLeafColumns(), table.getState().columnPinning.left, table.getState().columnPinning.right], (allColumns, left, right) => { + const leftAndRight = [...left != null ? left : [], ...right != null ? right : []]; + return allColumns.filter((d5) => !leftAndRight.includes(d5.id)); + }, { + key: "getCenterLeafColumns", + debug: () => { + var _table$options$debugA6; + return (_table$options$debugA6 = table.options.debugAll) != null ? _table$options$debugA6 : table.options.debugColumns; + } + }) + }; + } +}; +var RowSelection = { + getInitialState: (state) => { + return { + rowSelection: {}, + ...state + }; }, - 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" + getDefaultOptions: (table) => { + return { + onRowSelectionChange: makeStateUpdater("rowSelection", table), + enableRowSelection: true, + enableMultiRowSelection: true, + enableSubRowSelection: true + }; + }, + createTable: (table) => { + return { + setRowSelection: (updater) => { + var _a2, _b2; + return (_b2 = (_a2 = table.options).onRowSelectionChange) == null ? void 0 : _b2.call(_a2, updater); + }, + resetRowSelection: (defaultState) => { + var _table$initialState$r; + return table.setRowSelection(defaultState ? {} : (_table$initialState$r = table.initialState.rowSelection) != null ? _table$initialState$r : {}); + }, + toggleAllRowsSelected: (value) => { + table.setRowSelection((old) => { + value = typeof value !== "undefined" ? value : !table.getIsAllRowsSelected(); + const rowSelection = { + ...old + }; + const preGroupedFlatRows = table.getPreGroupedRowModel().flatRows; + if (value) { + preGroupedFlatRows.forEach((row) => { + if (!row.getCanSelect()) { + return; + } + rowSelection[row.id] = true; + }); + } else { + preGroupedFlatRows.forEach((row) => { + delete rowSelection[row.id]; + }); + } + return rowSelection; }); - case "bbbb": - default: - return localize2.dayPeriod(dayPeriodEnumValue, { - width: "wide", - context: "formatting" + }, + toggleAllPageRowsSelected: (value) => table.setRowSelection((old) => { + const resolvedValue = typeof value !== "undefined" ? value : !table.getIsAllPageRowsSelected(); + const rowSelection = { + ...old + }; + table.getRowModel().rows.forEach((row) => { + mutateRowIsSelected(rowSelection, row.id, resolvedValue, table); }); - } + return rowSelection; + }), + getPreSelectedRowModel: () => table.getCoreRowModel(), + getSelectedRowModel: memo(() => [table.getState().rowSelection, table.getCoreRowModel()], (rowSelection, rowModel) => { + if (!Object.keys(rowSelection).length) { + return { + rows: [], + flatRows: [], + rowsById: {} + }; + } + return selectRowsFn(table, rowModel); + }, { + key: "getSelectedRowModel", + debug: () => { + var _table$options$debugA; + return (_table$options$debugA = table.options.debugAll) != null ? _table$options$debugA : table.options.debugTable; + } + }), + getFilteredSelectedRowModel: memo(() => [table.getState().rowSelection, table.getFilteredRowModel()], (rowSelection, rowModel) => { + if (!Object.keys(rowSelection).length) { + return { + rows: [], + flatRows: [], + rowsById: {} + }; + } + return selectRowsFn(table, rowModel); + }, { + key: false, + debug: () => { + var _table$options$debugA2; + return (_table$options$debugA2 = table.options.debugAll) != null ? _table$options$debugA2 : table.options.debugTable; + } + }), + getGroupedSelectedRowModel: memo(() => [table.getState().rowSelection, table.getSortedRowModel()], (rowSelection, rowModel) => { + if (!Object.keys(rowSelection).length) { + return { + rows: [], + flatRows: [], + rowsById: {} + }; + } + return selectRowsFn(table, rowModel); + }, { + key: false, + debug: () => { + var _table$options$debugA3; + return (_table$options$debugA3 = table.options.debugAll) != null ? _table$options$debugA3 : table.options.debugTable; + } + }), + getIsAllRowsSelected: () => { + const preGroupedFlatRows = table.getFilteredRowModel().flatRows; + const { + rowSelection + } = table.getState(); + let isAllRowsSelected = Boolean(preGroupedFlatRows.length && Object.keys(rowSelection).length); + if (isAllRowsSelected) { + if (preGroupedFlatRows.some((row) => row.getCanSelect() && !rowSelection[row.id])) { + isAllRowsSelected = false; + } + } + return isAllRowsSelected; + }, + getIsAllPageRowsSelected: () => { + const paginationFlatRows = table.getPaginationRowModel().flatRows; + const { + rowSelection + } = table.getState(); + let isAllPageRowsSelected = !!paginationFlatRows.length; + if (isAllPageRowsSelected && paginationFlatRows.some((row) => !rowSelection[row.id])) { + isAllPageRowsSelected = false; + } + return isAllPageRowsSelected; + }, + getIsSomeRowsSelected: () => { + var _table$getState$rowSe; + const totalSelected = Object.keys((_table$getState$rowSe = table.getState().rowSelection) != null ? _table$getState$rowSe : {}).length; + return totalSelected > 0 && totalSelected < table.getFilteredRowModel().flatRows.length; + }, + getIsSomePageRowsSelected: () => { + const paginationFlatRows = table.getPaginationRowModel().flatRows; + return table.getIsAllPageRowsSelected() ? false : paginationFlatRows.some((d5) => d5.getIsSelected() || d5.getIsSomeSelected()); + }, + getToggleAllRowsSelectedHandler: () => { + return (e4) => { + table.toggleAllRowsSelected(e4.target.checked); + }; + }, + getToggleAllPageRowsSelectedHandler: () => { + return (e4) => { + table.toggleAllPageRowsSelected(e4.target.checked); + }; + } + }; }, - 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" + createRow: (row, table) => { + return { + toggleSelected: (value) => { + const isSelected = row.getIsSelected(); + table.setRowSelection((old) => { + value = typeof value !== "undefined" ? value : !isSelected; + if (isSelected === value) { + return old; + } + const selectedRowIds = { + ...old + }; + mutateRowIsSelected(selectedRowIds, row.id, value, table); + return selectedRowIds; }); + }, + getIsSelected: () => { + const { + rowSelection + } = table.getState(); + return isRowSelected(row, rowSelection); + }, + getIsSomeSelected: () => { + const { + rowSelection + } = table.getState(); + return isSubRowSelected(row, rowSelection) === "some"; + }, + getIsAllSubRowsSelected: () => { + const { + rowSelection + } = table.getState(); + return isSubRowSelected(row, rowSelection) === "all"; + }, + getCanSelect: () => { + var _table$options$enable; + if (typeof table.options.enableRowSelection === "function") { + return table.options.enableRowSelection(row); + } + return (_table$options$enable = table.options.enableRowSelection) != null ? _table$options$enable : true; + }, + getCanSelectSubRows: () => { + var _table$options$enable2; + if (typeof table.options.enableSubRowSelection === "function") { + return table.options.enableSubRowSelection(row); + } + return (_table$options$enable2 = table.options.enableSubRowSelection) != null ? _table$options$enable2 : true; + }, + getCanMultiSelect: () => { + var _table$options$enable3; + if (typeof table.options.enableMultiRowSelection === "function") { + return table.options.enableMultiRowSelection(row); + } + return (_table$options$enable3 = table.options.enableMultiRowSelection) != null ? _table$options$enable3 : true; + }, + getToggleSelectedHandler: () => { + const canSelect = row.getCanSelect(); + return (e4) => { + var _a2; + if (!canSelect) + return; + row.toggleSelected((_a2 = e4.target) == null ? void 0 : _a2.checked); + }; + } + }; + } +}; +var mutateRowIsSelected = (selectedRowIds, id2, value, table) => { + var _a2; + const row = table.getRow(id2); + if (value) { + if (!row.getCanMultiSelect()) { + Object.keys(selectedRowIds).forEach((key2) => delete selectedRowIds[key2]); } - }, - 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" - }); + if (row.getCanSelect()) { + selectedRowIds[id2] = true; } - return lightFormatters_default.h(date, token); - }, - H: function H4(date, token, localize2) { - if (token === "Ho") { - return localize2.ordinalNumber(date.getUTCHours(), { - unit: "hour" - }); + } else { + delete selectedRowIds[id2]; + } + if (((_a2 = row.subRows) == null ? void 0 : _a2.length) && row.getCanSelectSubRows()) { + row.subRows.forEach((row2) => mutateRowIsSelected(selectedRowIds, row2.id, value, table)); + } +}; +function selectRowsFn(table, rowModel) { + const rowSelection = table.getState().rowSelection; + const newSelectedFlatRows = []; + const newSelectedRowsById = {}; + const recurseRows = function(rows, depth) { + return rows.map((row) => { + var _a2; + const isSelected = isRowSelected(row, rowSelection); + if (isSelected) { + newSelectedFlatRows.push(row); + newSelectedRowsById[row.id] = row; + } + if ((_a2 = row.subRows) == null ? void 0 : _a2.length) { + row = { + ...row, + subRows: recurseRows(row.subRows) + }; + } + if (isSelected) { + return row; + } + }).filter(Boolean); + }; + return { + rows: recurseRows(rowModel.rows), + flatRows: newSelectedFlatRows, + rowsById: newSelectedRowsById + }; +} +function isRowSelected(row, selection) { + var _selection$row$id; + return (_selection$row$id = selection[row.id]) != null ? _selection$row$id : false; +} +function isSubRowSelected(row, selection, table) { + if (row.subRows && row.subRows.length) { + let allChildrenSelected = true; + let someSelected = false; + row.subRows.forEach((subRow) => { + if (someSelected && !allChildrenSelected) { + return; + } + if (isRowSelected(subRow, selection)) { + someSelected = true; + } else { + allChildrenSelected = false; + } + }); + return allChildrenSelected ? "all" : someSelected ? "some" : false; + } + return false; +} +var reSplitAlphaNumeric = /([0-9]+)/gm; +var alphanumeric = (rowA, rowB, columnId) => { + return compareAlphanumeric(toString(rowA.getValue(columnId)).toLowerCase(), toString(rowB.getValue(columnId)).toLowerCase()); +}; +var alphanumericCaseSensitive = (rowA, rowB, columnId) => { + return compareAlphanumeric(toString(rowA.getValue(columnId)), toString(rowB.getValue(columnId))); +}; +var text = (rowA, rowB, columnId) => { + return compareBasic(toString(rowA.getValue(columnId)).toLowerCase(), toString(rowB.getValue(columnId)).toLowerCase()); +}; +var textCaseSensitive = (rowA, rowB, columnId) => { + return compareBasic(toString(rowA.getValue(columnId)), toString(rowB.getValue(columnId))); +}; +var datetime = (rowA, rowB, columnId) => { + const a5 = rowA.getValue(columnId); + const b4 = rowB.getValue(columnId); + return a5 > b4 ? 1 : a5 < b4 ? -1 : 0; +}; +var basic = (rowA, rowB, columnId) => { + return compareBasic(rowA.getValue(columnId), rowB.getValue(columnId)); +}; +function compareBasic(a5, b4) { + return a5 === b4 ? 0 : a5 > b4 ? 1 : -1; +} +function toString(a5) { + if (typeof a5 === "number") { + if (isNaN(a5) || a5 === Infinity || a5 === -Infinity) { + 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" - }); + return String(a5); + } + if (typeof a5 === "string") { + return a5; + } + return ""; +} +function compareAlphanumeric(aStr, bStr) { + const a5 = aStr.split(reSplitAlphaNumeric).filter(Boolean); + const b4 = bStr.split(reSplitAlphaNumeric).filter(Boolean); + while (a5.length && b4.length) { + const aa = a5.shift(); + const bb = b4.shift(); + const an2 = parseInt(aa, 10); + const bn2 = parseInt(bb, 10); + const combo = [an2, bn2].sort(); + if (isNaN(combo[0])) { + if (aa > bb) { + return 1; + } + if (bb > aa) { + return -1; + } + continue; } - 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" - }); + if (isNaN(combo[1])) { + return isNaN(an2) ? -1 : 1; } - return addLeadingZeros(hours, token.length); - }, - m: function m4(date, token, localize2) { - if (token === "mo") { - return localize2.ordinalNumber(date.getUTCMinutes(), { - unit: "minute" - }); + if (an2 > bn2) { + return 1; } - return lightFormatters_default.m(date, token); - }, - s: function s4(date, token, localize2) { - if (token === "so") { - return localize2.ordinalNumber(date.getUTCSeconds(), { - unit: "second" - }); + if (bn2 > an2) { + return -1; } - return lightFormatters_default.s(date, token); + } + return a5.length - b4.length; +} +var sortingFns = { + alphanumeric, + alphanumericCaseSensitive, + text, + textCaseSensitive, + datetime, + basic +}; +var Sorting = { + getInitialState: (state) => { + return { + sorting: [], + ...state + }; }, - S: function S3(date, token) { - return lightFormatters_default.S(date, token); + getDefaultColumnDef: () => { + return { + sortingFn: "auto" + }; }, - X: function X2(date, token, _localize, options) { - var originalDate = options._originalDate || date; - var timezoneOffset = originalDate.getTimezoneOffset(); - if (timezoneOffset === 0) { - return "Z"; - } - switch (token) { - case "X": - return formatTimezoneWithOptionalMinutes(timezoneOffset); - case "XXXX": - case "XX": - return formatTimezone(timezoneOffset); - case "XXXXX": - case "XXX": - default: - return formatTimezone(timezoneOffset, ":"); - } + getDefaultOptions: (table) => { + return { + onSortingChange: makeStateUpdater("sorting", table), + isMultiSortEvent: (e4) => { + return e4.shiftKey; + } + }; + }, + createColumn: (column, table) => { + return { + getAutoSortingFn: () => { + const firstRows = table.getFilteredRowModel().flatRows.slice(10); + let isString = false; + for (const row of firstRows) { + const value = row == null ? void 0 : row.getValue(column.id); + if (Object.prototype.toString.call(value) === "[object Date]") { + return sortingFns.datetime; + } + if (typeof value === "string") { + isString = true; + if (value.split(reSplitAlphaNumeric).length > 1) { + return sortingFns.alphanumeric; + } + } + } + if (isString) { + return sortingFns.text; + } + return sortingFns.basic; + }, + getAutoSortDir: () => { + const firstRow = table.getFilteredRowModel().flatRows[0]; + const value = firstRow == null ? void 0 : firstRow.getValue(column.id); + if (typeof value === "string") { + return "asc"; + } + return "desc"; + }, + getSortingFn: () => { + var _a2; + var _table$options$sortin; + 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]; + }, + toggleSorting: (desc, multi) => { + const nextSortingOrder = column.getNextSortingOrder(); + const hasManualValue = typeof desc !== "undefined" && desc !== null; + table.setSorting((old) => { + const existingSorting = old == null ? void 0 : old.find((d5) => d5.id === column.id); + const existingIndex = old == null ? void 0 : old.findIndex((d5) => d5.id === column.id); + let newSorting = []; + let sortAction; + let nextDesc = hasManualValue ? desc : nextSortingOrder === "desc"; + if ((old == null ? void 0 : old.length) && column.getCanMultiSort() && multi) { + if (existingSorting) { + sortAction = "toggle"; + } else { + sortAction = "add"; + } + } else { + if ((old == null ? void 0 : old.length) && existingIndex !== old.length - 1) { + sortAction = "replace"; + } else if (existingSorting) { + sortAction = "toggle"; + } else { + sortAction = "replace"; + } + } + if (sortAction === "toggle") { + if (!hasManualValue) { + if (!nextSortingOrder) { + sortAction = "remove"; + } + } + } + if (sortAction === "add") { + var _table$options$maxMul; + newSorting = [...old, { + id: column.id, + desc: nextDesc + }]; + newSorting.splice(0, newSorting.length - ((_table$options$maxMul = table.options.maxMultiSortColCount) != null ? _table$options$maxMul : Number.MAX_SAFE_INTEGER)); + } else if (sortAction === "toggle") { + newSorting = old.map((d5) => { + if (d5.id === column.id) { + return { + ...d5, + desc: nextDesc + }; + } + return d5; + }); + } else if (sortAction === "remove") { + newSorting = old.filter((d5) => d5.id !== column.id); + } else { + newSorting = [{ + id: column.id, + desc: nextDesc + }]; + } + return newSorting; + }); + }, + getFirstSortDir: () => { + var _ref, _column$columnDef$sor; + const sortDescFirst = (_ref = (_column$columnDef$sor = column.columnDef.sortDescFirst) != null ? _column$columnDef$sor : table.options.sortDescFirst) != null ? _ref : column.getAutoSortDir() === "desc"; + return sortDescFirst ? "desc" : "asc"; + }, + getNextSortingOrder: (multi) => { + var _table$options$enable, _table$options$enable2; + const firstSortDirection = column.getFirstSortDir(); + const isSorted = column.getIsSorted(); + if (!isSorted) { + return firstSortDirection; + } + if (isSorted !== firstSortDirection && ((_table$options$enable = table.options.enableSortingRemoval) != null ? _table$options$enable : true) && (multi ? (_table$options$enable2 = table.options.enableMultiRemove) != null ? _table$options$enable2 : true : true)) { + return false; + } + return isSorted === "desc" ? "asc" : "desc"; + }, + getCanSort: () => { + var _column$columnDef$ena, _table$options$enable3; + return ((_column$columnDef$ena = column.columnDef.enableSorting) != null ? _column$columnDef$ena : true) && ((_table$options$enable3 = table.options.enableSorting) != null ? _table$options$enable3 : true) && !!column.accessorFn; + }, + getCanMultiSort: () => { + var _ref2, _column$columnDef$ena2; + return (_ref2 = (_column$columnDef$ena2 = column.columnDef.enableMultiSort) != null ? _column$columnDef$ena2 : table.options.enableMultiSort) != null ? _ref2 : !!column.accessorFn; + }, + getIsSorted: () => { + var _a2; + const columnSort = (_a2 = table.getState().sorting) == null ? void 0 : _a2.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; + }, + clearSorting: () => { + table.setSorting((old) => (old == null ? void 0 : 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); + }; + } + }; }, - 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, ":"); - } + createTable: (table) => { + return { + setSorting: (updater) => { + var _a2, _b2; + return (_b2 = (_a2 = table.options).onSortingChange) == null ? void 0 : _b2.call(_a2, 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 : []); + }, + getPreSortedRowModel: () => table.getGroupedRowModel(), + getSortedRowModel: () => { + if (!table._getSortedRowModel && table.options.getSortedRowModel) { + table._getSortedRowModel = table.options.getSortedRowModel(table); + } + if (table.options.manualSorting || !table._getSortedRowModel) { + return table.getPreSortedRowModel(); + } + return table._getSortedRowModel(); + } + }; + } +}; +var Visibility = { + getInitialState: (state) => { + return { + columnVisibility: {}, + ...state + }; }, - 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, ":"); - } + getDefaultOptions: (table) => { + return { + onColumnVisibilityChange: makeStateUpdater("columnVisibility", table) + }; }, - 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, ":"); - } + createColumn: (column, table) => { + return { + toggleVisibility: (value) => { + if (column.getCanHide()) { + table.setColumnVisibility((old) => ({ + ...old, + [column.id]: value != null ? value : !column.getIsVisible() + })); + } + }, + 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; + }, + getCanHide: () => { + var _column$columnDef$ena, _table$options$enable; + return ((_column$columnDef$ena = column.columnDef.enableHiding) != null ? _column$columnDef$ena : true) && ((_table$options$enable = table.options.enableHiding) != null ? _table$options$enable : true); + }, + getToggleVisibilityHandler: () => { + return (e4) => { + var _a2; + (_a2 = column.toggleVisibility) == null ? void 0 : _a2.call(column, e4.target.checked); + }; + } + }; }, - t: function t3(date, token, _localize, options) { - var originalDate = options._originalDate || date; - var timestamp = Math.floor(originalDate.getTime() / 1e3); - return addLeadingZeros(timestamp, token.length); + createRow: (row, table) => { + return { + _getAllVisibleCells: memo(() => [row.getAllCells(), table.getState().columnVisibility], (cells) => { + return cells.filter((cell) => cell.column.getIsVisible()); + }, { + key: false, + debug: () => { + var _table$options$debugA; + return (_table$options$debugA = table.options.debugAll) != null ? _table$options$debugA : table.options.debugRows; + } + }), + getVisibleCells: memo(() => [row.getLeftVisibleCells(), row.getCenterVisibleCells(), row.getRightVisibleCells()], (left, center, right) => [...left, ...center, ...right], { + key: "row.getVisibleCells", + debug: () => { + var _table$options$debugA2; + return (_table$options$debugA2 = table.options.debugAll) != null ? _table$options$debugA2 : table.options.debugRows; + } + }) + }; }, - 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); - } - 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; -} -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" - }); - } -}; -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" + 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); + }); + }, { + key: key2, + debug: () => { + var _table$options$debugA3; + return (_table$options$debugA3 = table.options.debugAll) != null ? _table$options$debugA3 : table.options.debugColumns; + } }); + }; + return { + getVisibleFlatColumns: makeVisibleColumnsMethod("getVisibleFlatColumns", () => table.getAllFlatColumns()), + getVisibleLeafColumns: makeVisibleColumnsMethod("getVisibleLeafColumns", () => table.getAllLeafColumns()), + getLeftVisibleLeafColumns: makeVisibleColumnsMethod("getLeftVisibleLeafColumns", () => table.getLeftLeafColumns()), + getRightVisibleLeafColumns: makeVisibleColumnsMethod("getRightVisibleLeafColumns", () => table.getRightLeafColumns()), + getCenterVisibleLeafColumns: makeVisibleColumnsMethod("getCenterVisibleLeafColumns", () => table.getCenterLeafColumns()), + setColumnVisibility: (updater) => { + var _a2, _b2; + return (_b2 = (_a2 = table.options).onColumnVisibilityChange) == null ? void 0 : _b2.call(_a2, updater); + }, + resetColumnVisibility: (defaultState) => { + var _table$initialState$c; + table.setColumnVisibility(defaultState ? {} : (_table$initialState$c = table.initialState.columnVisibility) != null ? _table$initialState$c : {}); + }, + toggleAllColumnsVisible: (value) => { + var _value; + value = (_value = value) != null ? _value : !table.getIsAllColumnsVisible(); + table.setColumnVisibility(table.getAllLeafColumns().reduce((obj, column) => { + var _a2; + return { + ...obj, + [column.id]: !value ? !((_a2 = column.getCanHide) == null ? void 0 : _a2.call(column)) : 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); + }), + getToggleAllColumnsVisibilityHandler: () => { + return (e4) => { + var _a2; + table.toggleAllColumnsVisible((_a2 = e4.target) == null ? void 0 : _a2.checked); + }; + } + }; } }; -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; +var features = [Headers, Visibility, Ordering, Pinning, Filters, Sorting, Grouping, Expanding, Pagination, RowSelection, ColumnSizing]; +function createTable(options) { + var _options$initialState; + if (options.debugAll || options.debugTable) { + console.info("Creating Table Instance..."); } - 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/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/_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; + let table = { + _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)); + }, {}); + const mergeOptions = (options2) => { + if (table.options.mergeOptions) { + return table.options.mergeOptions(defaultOptions3, options2); + } + return { + ...defaultOptions3, + ...options2 + }; + }; + const coreInitialState = {}; + let initialState = { + ...coreInitialState, + ...(_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; + }); + const queued = []; + let queuedTimeout = false; + const coreInstance = { + _features: features, + options: { + ...defaultOptions3, + ...options + }, + initialState, + _queue: (cb) => { + queued.push(cb); + if (!queuedTimeout) { + queuedTimeout = true; + Promise.resolve().then(() => { + while (queued.length) { + queued.shift()(); + } + queuedTimeout = false; + }).catch((error) => setTimeout(() => { + throw error; + })); + } + }, + reset: () => { + table.setState(table.initialState); + }, + setOptions: (updater) => { + const newOptions = functionalUpdate(updater, table.options); + table.options = mergeOptions(newOptions); + }, + getState: () => { + return table.options.state; + }, + setState: (updater) => { + var _a2, _b2; + (_b2 = (_a2 = table.options).onStateChange) == null ? void 0 : _b2.call(_a2, 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}`; + }, + getCoreRowModel: () => { + if (!table._getCoreRowModel) { + table._getCoreRowModel = table.options.getCoreRowModel(table); + } + return table._getCoreRowModel(); + }, + getRowModel: () => { + return table.getPaginationRowModel(); + }, + getRow: (id2) => { + const row = table.getRowModel().rowsById[id2]; + if (!row) { + if (true) { + throw new Error(`getRow expected an ID, but got ${id2}`); + } + throw new Error(); + } + return row; + }, + _getDefaultColumnDef: memo(() => [table.options.defaultColumn], (defaultColumn) => { + var _defaultColumn; + defaultColumn = (_defaultColumn = defaultColumn) != null ? _defaultColumn : {}; + return { + header: (props2) => { + const resolvedColumnDef = props2.header.column.columnDef; + if (resolvedColumnDef.accessorKey) { + return resolvedColumnDef.accessorKey; + } + if (resolvedColumnDef.accessorFn) { + return resolvedColumnDef.id; + } + return null; + }, + cell: (props2) => { + var _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; + }, + ...table._features.reduce((obj, feature) => { + var _a2; + return Object.assign(obj, (_a2 = feature.getDefaultColumnDef) == null ? void 0 : _a2.call(feature)); + }, {}), + ...defaultColumn + }; + }, { + debug: () => { + var _table$options$debugA; + return (_table$options$debugA = table.options.debugAll) != null ? _table$options$debugA : table.options.debugColumns; + }, + key: "getDefaultColumnDef" + }), + _getColumnDefs: () => table.options.columns, + getAllColumns: memo(() => [table._getColumnDefs()], (columnDefs) => { + const recurseColumns = function(columnDefs2, parent, depth) { + if (depth === void 0) { + depth = 0; + } + return columnDefs2.map((columnDef) => { + const column = createColumn(table, columnDef, depth, parent); + const groupingColumnDef = columnDef; + column.columns = groupingColumnDef.columns ? recurseColumns(groupingColumnDef.columns, column, depth + 1) : []; + return column; + }); + }; + return recurseColumns(columnDefs); + }, { + key: "getAllColumns", + debug: () => { + var _table$options$debugA2; + return (_table$options$debugA2 = table.options.debugAll) != null ? _table$options$debugA2 : table.options.debugColumns; + } + }), + getAllFlatColumns: memo(() => [table.getAllColumns()], (allColumns) => { + return allColumns.flatMap((column) => { + return column.getFlatColumns(); + }); + }, { + key: "getAllFlatColumns", + debug: () => { + var _table$options$debugA3; + return (_table$options$debugA3 = table.options.debugAll) != null ? _table$options$debugA3 : table.options.debugColumns; + } + }), + _getAllFlatColumnsById: memo(() => [table.getAllFlatColumns()], (flatColumns) => { + return flatColumns.reduce((acc, column) => { + acc[column.id] = column; + return acc; + }, {}); + }, { + key: "getAllFlatColumnsById", + debug: () => { + var _table$options$debugA4; + return (_table$options$debugA4 = table.options.debugAll) != null ? _table$options$debugA4 : table.options.debugColumns; + } + }), + getAllLeafColumns: memo(() => [table.getAllColumns(), table._getOrderColumnsFn()], (allColumns, orderColumns2) => { + let leafColumns = allColumns.flatMap((column) => column.getLeafColumns()); + return orderColumns2(leafColumns); + }, { + key: "getAllLeafColumns", + debug: () => { + var _table$options$debugA5; + return (_table$options$debugA5 = table.options.debugAll) != null ? _table$options$debugA5 : table.options.debugColumns; + } + }), + getColumn: (columnId) => { + const column = table._getAllFlatColumnsById()[columnId]; + if (!column) { + if (true) { + console.warn(`[Table] Column with id ${columnId} does not exist.`); + } + throw new Error(); + } + 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 table; } -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 createCell(table, row, column, columnId) { + const getRenderValue = () => { + var _cell$getValue; + return (_cell$getValue = cell.getValue()) != null ? _cell$getValue : table.options.renderFallbackValue; + }; + const cell = { + id: `${row.id}_${column.id}`, + row, + column, + getValue: () => row.getValue(columnId), + renderValue: getRenderValue, + getContext: memo(() => [table, column, row, cell], (table2, column2, row2, cell2) => ({ + table: table2, + column: column2, + row: row2, + cell: cell2, + getValue: cell2.getValue, + renderValue: cell2.renderValue + }), { + key: "cell.getContext", + debug: () => table.options.debugAll + }) + }; + table._features.forEach((feature) => { + var _a2; + Object.assign(cell, (_a2 = feature.createCell) == null ? void 0 : _a2.call(feature, cell, column, row, table)); + }, {}); + return cell; } - -// 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"); - } - var timezoneOffset = getTimezoneOffsetInMilliseconds(originalDate); - var utcDate = subMilliseconds(originalDate, timezoneOffset); - var formatterOptions = { - firstWeekContainsDate, - weekStartsOn, - locale: locale2, - _originalDate: originalDate +var createRow = (table, id2, original, rowIndex, depth, subRows) => { + var _a2; + let row = { + id: id2, + index: rowIndex, + original, + depth, + _valuesCache: {}, + _uniqueValuesCache: {}, + getValue: (columnId) => { + if (row._valuesCache.hasOwnProperty(columnId)) { + return row._valuesCache[columnId]; + } + const column = table.getColumn(columnId); + if (!column.accessorFn) { + return void 0; + } + row._valuesCache[columnId] = column.accessorFn(row.original, rowIndex); + return row._valuesCache[columnId]; + }, + getUniqueValues: (columnId) => { + if (row._uniqueValuesCache.hasOwnProperty(columnId)) { + return row._uniqueValuesCache[columnId]; + } + const column = table.getColumn(columnId); + if (!column.accessorFn) { + return void 0; + } + if (!column.columnDef.getUniqueValues) { + row._uniqueValuesCache[columnId] = [row.getValue(columnId)]; + return row._uniqueValuesCache[columnId]; + } + row._uniqueValuesCache[columnId] = column.columnDef.getUniqueValues(row.original, rowIndex); + return row._uniqueValuesCache[columnId]; + }, + renderValue: (columnId) => { + var _row$getValue; + return (_row$getValue = row.getValue(columnId)) != null ? _row$getValue : table.options.renderFallbackValue; + }, + subRows: subRows != null ? subRows : [], + getLeafRows: () => flattenBy(row.subRows, (d5) => d5.subRows), + getAllCells: memo(() => [table.getAllLeafColumns()], (leafColumns) => { + return leafColumns.map((column) => { + return createCell(table, row, column, column.id); + }); + }, { + key: "row.getAllCells", + debug: () => { + var _table$options$debugA; + return (_table$options$debugA = table.options.debugAll) != null ? _table$options$debugA : table.options.debugRows; + } + }), + _getAllCellsByColumnId: memo(() => [row.getAllCells()], (allCells) => { + return allCells.reduce((acc, cell) => { + acc[cell.column.id] = cell; + return acc; + }, {}); + }, { + key: false, + debug: () => { + var _table$options$debugA2; + return (_table$options$debugA2 = table.options.debugAll) != null ? _table$options$debugA2 : table.options.debugRows; + } + }) }; - 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 "'"; + 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)); + } + return row; +}; +function getCoreRowModel() { + return (table) => memo(() => [table.options.data], (data) => { + const rowModel = { + rows: [], + flatRows: [], + rowsById: {} + }; + const accessRows = function(originalRows, depth, parent) { + var _a2; + if (depth === void 0) { + depth = 0; + } + const rows = []; + for (let i4 = 0; i4 < originalRows.length; i4++) { + const row = createRow(table, table._getRowId(originalRows[i4], i4, parent), originalRows[i4], i4, depth); + rowModel.flatRows.push(row); + rowModel.rowsById[row.id] = row; + rows.push(row); + if (table.options.getSubRows) { + row.originalSubRows = table.options.getSubRows(originalRows[i4], i4); + if ((_a2 = row.originalSubRows) == null ? void 0 : _a2.length) { + row.subRows = accessRows(row.originalSubRows, depth + 1, row); + } + } + } + return rows; + }; + rowModel.rows = accessRows(data); + return rowModel; + }, { + key: "getRowModel", + debug: () => { + var _table$options$debugA; + return (_table$options$debugA = table.options.debugAll) != null ? _table$options$debugA : table.options.debugTable; + }, + onChange: () => { + table._autoResetPageIndex(); } - var firstCharacter = substring[0]; - if (firstCharacter === "'") { - return cleanEscapedString(substring); + }); +} +function getGroupedRowModel() { + return (table) => memo(() => [table.getState().grouping, table.getPreGroupedRowModel()], (grouping, rowModel) => { + if (!rowModel.rows.length || !grouping.length) { + return rowModel; } - var formatter = formatters_default[firstCharacter]; - if (formatter) { - if (!(options !== null && options !== void 0 && options.useAdditionalWeekYearTokens) && isProtectedWeekYearToken(substring)) { - throwProtectedError(substring, dirtyFormatStr, String(dirtyDate)); + const existingGrouping = grouping.filter((columnId) => table.getColumn(columnId)); + const groupedFlatRows = []; + const groupedRowsById = {}; + const groupUpRecursively = function(rows, depth, parentId) { + if (depth === void 0) { + depth = 0; } - if (!(options !== null && options !== void 0 && options.useAdditionalDayOfYearTokens) && isProtectedDayOfYearToken(substring)) { - throwProtectedError(substring, dirtyFormatStr, String(dirtyDate)); + if (depth >= existingGrouping.length) { + return rows.map((row) => { + row.depth = depth; + groupedFlatRows.push(row); + groupedRowsById[row.id] = row; + if (row.subRows) { + row.subRows = groupUpRecursively(row.subRows, depth + 1); + } + return row; + }); } - return formatter(utcDate, substring, locale2.localize, formatterOptions); - } - if (firstCharacter.match(unescapedLatinCharacterRegExp)) { - throw new RangeError("Format string contains an unescaped latin alphabet character `" + firstCharacter + "`"); + const columnId = existingGrouping[depth]; + const rowGroupsMap = groupBy(rows, columnId); + const aggregatedGroupedRows = Array.from(rowGroupsMap.entries()).map((_ref, index) => { + let [groupingValue, groupedRows2] = _ref; + let id2 = `${columnId}:${groupingValue}`; + id2 = parentId ? `${parentId}>${id2}` : id2; + const subRows = groupUpRecursively(groupedRows2, depth + 1, id2); + const leafRows = depth ? flattenBy(groupedRows2, (row2) => row2.subRows) : groupedRows2; + const row = createRow(table, id2, leafRows[0].original, index, depth); + Object.assign(row, { + groupingColumnId: columnId, + groupingValue, + subRows, + leafRows, + getValue: (columnId2) => { + if (existingGrouping.includes(columnId2)) { + if (row._valuesCache.hasOwnProperty(columnId2)) { + return row._valuesCache[columnId2]; + } + if (groupedRows2[0]) { + var _groupedRows$0$getVal; + row._valuesCache[columnId2] = (_groupedRows$0$getVal = groupedRows2[0].getValue(columnId2)) != null ? _groupedRows$0$getVal : void 0; + } + return row._valuesCache[columnId2]; + } + if (row._groupingValuesCache.hasOwnProperty(columnId2)) { + return row._groupingValuesCache[columnId2]; + } + const column = table.getColumn(columnId2); + const aggregateFn = column.getAggregationFn(); + if (aggregateFn) { + row._groupingValuesCache[columnId2] = aggregateFn(columnId2, leafRows, groupedRows2); + return row._groupingValuesCache[columnId2]; + } + } + }); + subRows.forEach((subRow) => { + groupedFlatRows.push(subRow); + groupedRowsById[subRow.id] = subRow; + }); + return row; + }); + return aggregatedGroupedRows; + }; + const groupedRows = groupUpRecursively(rowModel.rows, 0, ""); + groupedRows.forEach((subRow) => { + groupedFlatRows.push(subRow); + groupedRowsById[subRow.id] = subRow; + }); + return { + rows: groupedRows, + flatRows: groupedFlatRows, + rowsById: groupedRowsById + }; + }, { + key: "getGroupedRowModel", + debug: () => { + var _table$options$debugA; + return (_table$options$debugA = table.options.debugAll) != null ? _table$options$debugA : table.options.debugTable; + }, + onChange: () => { + table._queue(() => { + table._autoResetExpanded(); + table._autoResetPageIndex(); + }); } - return substring; - }).join(""); - return result; -} -function cleanEscapedString(input) { - var matched = input.match(escapedStringRegExp); - if (!matched) { - return input; - } - return matched[1].replace(doubleQuoteRegExp, "'"); -} - -// 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/startOfDay/index.js -function startOfDay(dirtyDate) { - requiredArgs(1, arguments); - var date = toDate(dirtyDate); - date.setHours(0, 0, 0, 0); - return date; -} - -// node_modules/date-fns/esm/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/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/getDaysInMonth/index.js -function getDaysInMonth(dirtyDate) { - requiredArgs(1, arguments); - var date = toDate(dirtyDate); - var year = date.getFullYear(); - var monthIndex = date.getMonth(); - var lastDayOfMonth2 = new Date(0); - lastDayOfMonth2.setFullYear(year, monthIndex + 1, 0); - lastDayOfMonth2.setHours(0, 0, 0, 0); - return lastDayOfMonth2.getDate(); -} - -// node_modules/date-fns/esm/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; -} - -// 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/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; - } -} - -// node_modules/date-fns/esm/isBefore/index.js -function isBefore(dirtyDate, dirtyDateToCompare) { - requiredArgs(2, arguments); - var date = toDate(dirtyDate); - var dateToCompare = toDate(dirtyDateToCompare); - return date.getTime() < dateToCompare.getTime(); + }); } - -// node_modules/date-fns/esm/isSameMonth/index.js -function isSameMonth(dirtyDateLeft, dirtyDateRight) { - requiredArgs(2, arguments); - var dateLeft = toDate(dirtyDateLeft); - var dateRight = toDate(dirtyDateRight); - return dateLeft.getFullYear() === dateRight.getFullYear() && dateLeft.getMonth() === dateRight.getMonth(); +function groupBy(rows, columnId) { + const groupMap = /* @__PURE__ */ new Map(); + return rows.reduce((map, row) => { + const resKey = `${row.getValue(columnId)}`; + const previous = map.get(resKey); + if (!previous) { + map.set(resKey, [row]); + } else { + previous.push(row); + } + return map; + }, groupMap); } - -// 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 getExpandedRowModel() { + return (table) => memo(() => [table.getState().expanded, table.getPreExpandedRowModel(), table.options.paginateExpandedRows], (expanded, rowModel, paginateExpandedRows) => { + if (!rowModel.rows.length || expanded !== true && !Object.keys(expanded != null ? expanded : {}).length) { + return rowModel; + } + if (!paginateExpandedRows) { + return rowModel; + } + return expandRows(rowModel); + }, { + key: "getExpandedRowModel", + debug: () => { + var _table$options$debugA; + return (_table$options$debugA = table.options.debugAll) != null ? _table$options$debugA : table.options.debugTable; + } + }); } - -// node_modules/date-fns/esm/addDays/index.js -function addDays(dirtyDate, dirtyAmount) { - requiredArgs(2, arguments); - var date = toDate(dirtyDate); - var amount = toInteger(dirtyAmount); - if (isNaN(amount)) { - return new Date(NaN); - } - if (!amount) { - return date; - } - date.setDate(date.getDate() + amount); - return date; +function expandRows(rowModel) { + const expandedRows = []; + const handleRow = (row) => { + var _a2; + expandedRows.push(row); + if (((_a2 = row.subRows) == null ? void 0 : _a2.length) && row.getIsExpanded()) { + row.subRows.forEach(handleRow); + } + }; + rowModel.rows.forEach(handleRow); + return { + rows: expandedRows, + flatRows: rowModel.flatRows, + rowsById: rowModel.rowsById + }; } -// 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; +// node_modules/@tanstack/react-table/build/lib/index.mjs +function flexRender(Comp, props2) { + return !Comp ? null : isReactComponent(Comp) ? /* @__PURE__ */ h(Comp, props2) : Comp; } - -// node_modules/date-fns/esm/startOfISOWeek/index.js -function startOfISOWeek(dirtyDate) { - requiredArgs(1, arguments); - return startOfWeek(dirtyDate, { - weekStartsOn: 1 - }); +function isReactComponent(component) { + return isClassComponent(component) || typeof component === "function" || isExoticComponent(component); } - -// 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 isClassComponent(component) { + return typeof component === "function" && (() => { + const proto = Object.getPrototypeOf(component); + return proto.prototype && proto.prototype.isReactComponent; + })(); } - -// node_modules/date-fns/esm/getUnixTime/index.js -function getUnixTime(dirtyDate) { - requiredArgs(1, arguments); - return Math.floor(getTime(dirtyDate) / 1e3); +function isExoticComponent(component) { + return typeof component === "object" && typeof component.$$typeof === "symbol" && ["react.memo", "react.forward_ref"].includes(component.$$typeof.description); } - -// node_modules/date-fns/esm/isSameDay/index.js -function isSameDay(dirtyDateLeft, dirtyDateRight) { - requiredArgs(2, arguments); - var dateLeftStartOfDay = startOfDay(dirtyDateLeft); - var dateRightStartOfDay = startOfDay(dirtyDateRight); - return dateLeftStartOfDay.getTime() === dateRightStartOfDay.getTime(); +function useReactTable(options) { + const resolvedOptions = { + state: {}, + onStateChange: () => { + }, + renderFallbackValue: null, + ...options + }; + const [tableRef] = p2(() => ({ + current: createTable(resolvedOptions) + })); + const [state, setState] = p2(() => tableRef.current.initialState); + tableRef.current.setOptions((prev) => ({ + ...prev, + ...options, + state: { + ...state, + ...options.state + }, + onStateChange: (updater) => { + var _a2; + setState(updater); + (_a2 = options.onStateChange) == null ? void 0 : _a2.call(options, updater); + } + })); + return tableRef.current; } -// 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/components/ui/menus/menuItems.tsx +var import_obsidian7 = require("obsidian"); + +// src/components/ui/menus/selectMenu/concerns/focusNextElement.js +function focusNextElement(scope, currentTarget) { + const interactiveEls = scope.querySelectorAll("a,button,input"); + const currentEl = Array.prototype.findIndex.call( + interactiveEls, + (element) => element === currentTarget + ); + const nextEl = interactiveEls[currentEl - 1] || interactiveEls[currentEl + 1]; + if (nextEl) { + nextEl.focus(); } } -// 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; -} +// src/components/ui/menus/selectMenu/SelectMenuInput.tsx +var SIZER_STYLES = { + position: "absolute", + width: 0, + height: 0, + visibility: "hidden", + overflow: "scroll", + whiteSpace: "pre" +}; +var STYLE_PROPS = [ + "fontSize", + "fontFamily", + "fontWeight", + "fontStyle", + "letterSpacing", + "textTransform" +]; +var SelectMenuInput = k3( + (props2, input) => { + const { classNames: classNames8, inputAttributes, inputEventHandlers, index } = props2; + const sizer = _2(null); + const [inputWidth, setInputWidth] = p2(null); + const [query, setQuery] = p2(""); + const [placeholderText, setPlaceholderText] = p2(""); + h2(() => { + copyInputStyles(); + updateInputWidth(); + setTimeout(() => { + input.current.focus(); + }, 50); + }, []); + h2(() => { + if (query !== props2.query || placeholderText !== props2.placeholderText) { + setQuery(props2.query); + setPlaceholderText(props2.placeholderText); + updateInputWidth(); + } + }, [props2.query, props2.placeholderText]); + const copyInputStyles = () => { + const inputStyle = window.getComputedStyle(input.current); + STYLE_PROPS.forEach((prop) => { + sizer.current.style[prop] = inputStyle[prop]; + }); + }; + const updateInputWidth = () => { + let _inputWidth; + _inputWidth = Math.ceil(sizer.current.scrollWidth) + 2; + if (_inputWidth !== inputWidth) { + setInputWidth(_inputWidth); + } + }; + return /* @__PURE__ */ bn.createElement("div", { + className: classNames8.searchWrapper + }, /* @__PURE__ */ bn.createElement("input", { + ...inputAttributes, + ...inputEventHandlers, + ref: input, + value: query, + placeholder: placeholderText, + className: classNames8.searchInput, + role: "combobox", + style: { width: "100%" } + }), /* @__PURE__ */ bn.createElement("div", { + ref: sizer, + style: SIZER_STYLES + }, query || placeholderText)); + } +); +var SelectMenuInput_default = SelectMenuInput; -// node_modules/date-fns/esm/differenceInCalendarDays/index.js -var MILLISECONDS_IN_DAY2 = 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_DAY2); +// src/components/ui/menus/selectMenu/SelectMenuSuggestions.tsx +function markIt(name, query) { + const regexp = matchAny(query); + return name.replace(regexp, "$&"); } +var SelectMenuSuggestionsComponent = (props2) => { + const ref = _2(null); + h2(() => { + 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", { + ref, + dangerouslySetInnerHTML: { + __html: markIt(props2.item.name, props2.query) + } + }), props2.item.description && /* @__PURE__ */ bn.createElement("span", { + className: "mk-description", + ref, + dangerouslySetInnerHTML: { + __html: markIt(props2.item.description, props2.query) + } + }), props2.item.removeable && /* @__PURE__ */ bn.createElement("div", null, "Remove")); +}; +var SelectMenuSuggestions = (props2) => { + const timer = _2(null); + const mouseOver = (e4, index) => { + if (!props2.hoverSelect) { + return; + } + timer.current && clearTimeout(timer.current); + timer.current = setTimeout(() => props2.setIndex(index), 300); + }; + const options = props2.options.map((item, index) => { + const key2 = `${props2.id}-${index}`; + const classNames8 = []; + if (props2.index === index) { + classNames8.push(props2.classNames.suggestionActive); + } + if (item.disabled) { + classNames8.push(props2.classNames.suggestionDisabled); + } + return /* @__PURE__ */ bn.createElement("li", { + id: key2, + key: key2, + role: "option", + className: classNames8.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, { + item, + query: props2.query, + active: index == props2.index + })); + }); + return /* @__PURE__ */ bn.createElement("div", { + className: props2.classNames.suggestions + }, /* @__PURE__ */ bn.createElement("ul", { + role: "listbox", + id: props2.id + }, options, props2.query && props2.allowNew && /* @__PURE__ */ bn.createElement("li", { + onMouseDown: (e4) => e4.preventDefault(), + onClick: () => props2.addTag({ name: props2.query, value: props2.query }) + }, "Add ", props2.query))); +}; +var SelectMenuSuggestions_default = SelectMenuSuggestions; -// 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); -} +// src/components/ui/menus/selectMenu/SelectMenuPill.tsx +var SelectMenuPillComponent = (props2) => { + return /* @__PURE__ */ bn.createElement("button", { + type: "button", + className: props2.classNames.selectedTag, + onClick: props2.onDelete + }, /* @__PURE__ */ bn.createElement("span", { + className: props2.classNames.selectedTagName + }, props2.tag.name)); +}; +var SelectMenuPill_default = SelectMenuPillComponent; -// node_modules/date-fns/esm/addYears/index.js -function addYears(dirtyDate, dirtyAmount) { - requiredArgs(2, arguments); - var amount = toInteger(dirtyAmount); - return addMonths(dirtyDate, amount * 12); +// src/components/ui/menus/selectMenu/SelectMenuComponent.tsx +var import_lodash3 = __toESM(require_lodash()); +var KEYS = { + ENTER: "Enter", + TAB: "Tab", + BACKSPACE: "Backspace", + UP_ARROW: "ArrowUp", + UP_ARROW_COMPAT: "Up", + DOWN_ARROW: "ArrowDown", + DOWN_ARROW_COMPAT: "Down" +}; +var CLASS_NAMES = { + root: "mk-options-menu", + rootFocused: "is-focused", + selected: "mk-options-menu__selected", + selectedTag: "mk-options-menu__selected-tag", + selectedTagName: "mk-options-menu__selected-tag-name", + search: "mk-options-menu__search", + searchWrapper: "mk-options-menu__search-wrapper", + searchInput: "mk-options-menu__search-input", + suggestions: "mk-options-menu__suggestions", + suggestionActive: "is-active", + suggestionDisabled: "is-disabled" +}; +var defaultProps = { + id: "SelectMenu", + tags: [], + suggestionsOnly: false, + placeholderText: i18n_default.labels.optionItemSelectPlaceholder, + noSuggestionsText: null, + newTagText: null, + suggestions: [], + suggestionsFilter: defaultSuggestionsFilter, + suggestionsTransform: null, + classNames: CLASS_NAMES, + delimiters: [KEYS.ENTER], + minQueryLength: 2, + maxSuggestionsLength: 8, + inputAttributes: {}, + hoverSelect: false +}; +var findMatchIndex = (options, query) => { + return options.findIndex((option) => matchExact(query).test(option.name)); +}; +var pressDelimiter = (props2, query, index, options, addTag) => { + if (query.length >= props2.minQueryLength) { + const match2 = findMatchIndex(options, query); + const _index = index === -1 ? match2 : index; + const tag = _index > -1 ? options[_index] : null; + if (tag) { + addTag(tag); + } else { + addTag({ name: query, value: query }); + } + } +}; +function defaultSuggestionsFilter(item, query) { + const regexp = matchAny(query); + return regexp.test(item.name); } - -// node_modules/date-fns/esm/max/index.js -function _typeof3(obj) { - "@babel/helpers - typeof"; - if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { - _typeof3 = function _typeof5(obj2) { - return typeof obj2; - }; +function getOptions(props2, query) { + let options; + if (props2.suggestionsTransform) { + options = props2.suggestionsTransform(query, props2.suggestions); } else { - _typeof3 = function _typeof5(obj2) { - return obj2 && typeof Symbol === "function" && obj2.constructor === Symbol && obj2 !== Symbol.prototype ? "symbol" : typeof obj2; - }; + options = props2.suggestions.filter( + (item) => props2.suggestionsFilter(item, query) + ); } - return _typeof3(obj); + options = options.slice(0, props2.maxSuggestionsLength); + if (props2.newTagText && findMatchIndex(options, query) === -1) { + options.push({ id: 0, name: query, value: query }); + } else if (props2.noSuggestionsText && options.length === 0) { + options.push({ + id: 0, + name: props2.noSuggestionsText, + value: "", + disabled: true + }); + } + return options; } -function max2(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 SelectMenuComponent = bn.forwardRef((_props, ref) => { + const props2 = { ...defaultProps, ..._props }; + const [options, setOptions] = p2([]); + const inputRef = _2(null); + const [query, setQuery] = p2(""); + const [focused, setFocused] = p2(false); + const [index, setIndex] = p2(0); + const onComposition = _2(false); + h2(() => { + if (ref) { + ref.current = () => { + var _a2; + if (!focused) { + (_a2 = inputRef == null ? void 0 : inputRef.current) == null ? void 0 : _a2.focus(); + setFocused(true); + return false; + } + return true; + }; + } + }, [focused]); + h2(() => { + 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_lodash3.debounce)(handleDebounceFn, 100), []); + function handleDebounceFn(inputValue) { + props2.onHover(inputValue); } - var result; - datesArray.forEach(function(dirtyDate) { - var currentDate = toDate(dirtyDate); - if (result === void 0 || result < currentDate || isNaN(Number(currentDate))) { - result = currentDate; + h2(() => { + if (query.length == 0 && props2.defaultSuggestions) { + setOptions(props2.defaultSuggestions); + return; + } + setOptions(getOptions(props2, query)); + }, [query, props2.suggestions]); + const container = _2(null); + const onInput = (e4) => { + if (e4.type === "compositionstart") { + onComposition.current = true; + return; + } + if (e4.type === "compositionend") { + onComposition.current = false; + } + if (onComposition.current) { + return; + } + const _query = e4.target.value; + if (props2.onInput) { + props2.onInput(_query); + } + if (_query.length === query.length + 1 && props2.delimiters.indexOf(query.slice(-1)) > -1) { + pressDelimiter(props2, query, index, options, addTag); + } else if (_query !== query) { + setQuery(_query); + } + }; + const onKeyDown = (e4) => { + if (props2.delimiters.indexOf(e4.key) > -1) { + if (query || index > -1) { + e4.preventDefault(); + } + pressDelimiter(props2, query, index, options, addTag); + } + if (e4.key === KEYS.BACKSPACE) { + pressBackspaceKey(); + } + if (e4.key === KEYS.UP_ARROW || e4.key === KEYS.UP_ARROW_COMPAT) { + pressUpKey(e4); + } + if (e4.key === KEYS.DOWN_ARROW || e4.key === KEYS.DOWN_ARROW_COMPAT) { + pressDownKey(e4); + } + }; + const onBlur = () => { + setFocused(false); + if (props2.onBlur) { + props2.onBlur(); + } + }; + const onFocus = () => { + setFocused(true); + if (props2.onFocus) { + props2.onFocus(); + } + }; + const onDeleteTag = (index2, event) => { + if (container.current) { + focusNextElement(container.current, event.currentTarget); } - }); - return result || new Date(NaN); -} - -// node_modules/date-fns/esm/min/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; - }; - } - return _typeof4(obj); -} -function min2(dirtyDatesArray) { - requiredArgs(1, arguments); - var datesArray; - if (dirtyDatesArray && typeof dirtyDatesArray.forEach === "function") { - datesArray = dirtyDatesArray; - } else if (_typeof4(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; + deleteTag(index2); + }; + const addTag = (tag) => { + if (tag.disabled) { + return; } - }); - 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; - } -} - -// node_modules/date-fns/esm/differenceInCalendarWeeks/index.js -var MILLISECONDS_IN_WEEK3 = 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_WEEK3); -} - -// 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); - } -}; -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/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); + if (props2.onValidate && !props2.onValidate(tag)) { + return; } - dateLeft.setMonth(dateLeft.getMonth() - sign * difference); - var isLastMonthNotFull = compareAsc(dateLeft, dateRight) === -sign; - if (isLastDayOfMonth(toDate(dirtyDateLeft)) && difference === 1 && compareAsc(dirtyDateLeft, dateRight) === 1) { - isLastMonthNotFull = false; + props2.onAddition(tag); + clearInput(); + }; + const deleteTag = (i4) => { + props2.onDelete(i4); + }; + const clearInput = () => { + setQuery(""); + setIndex(-1); + }; + const clearSelectedIndex = () => { + setIndex(-1); + }; + const pressUpKey = (e4) => { + e4.preventDefault(); + const size = options.length - 1; + setIndex(index <= 0 ? size : index - 1); + }; + const pressDownKey = (e4) => { + e4.preventDefault(); + const size = options.length - 1; + setIndex((i4) => i4 >= size ? 0 : i4 + 1); + }; + function pressBackspaceKey() { + if (!query.length) { + deleteTag(props2.tags.length - 1); } - 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); -} + const focusInput = () => { + inputRef.current.focus(); + }; + const inputEventHandlers = { + onChange: onInput, + onBlur, + onFocus, + onInput: () => { + }, + onKeyDown, + onCompositionEnd: onInput, + 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", { + ref: container, + className: rootClassNames.join(" ") + }, !props2.suggestionsOnly ? /* @__PURE__ */ bn.createElement("div", { + className: classNames8.selected, + "aria-relevant": "additions removals", + "aria-live": "polite" + }, /* @__PURE__ */ bn.createElement(bn.Fragment, null, props2.tags.map((tag, i4) => /* @__PURE__ */ bn.createElement(SelectMenuPill_default, { + key: i4, + tag, + classNames: classNames8, + onDelete: (e4) => onDeleteTag(i4, e4) + }))), /* @__PURE__ */ bn.createElement("div", { + className: classNames8.search + }, /* @__PURE__ */ bn.createElement(SelectMenuInput_default, { + ref: inputRef, + query, + index, + id: props2.id, + classNames: classNames8, + inputAttributes: props2.inputAttributes, + inputEventHandlers, + expanded, + placeholderText: props2.placeholderText + }))) : null, options.length || props2.allowNew ? /* @__PURE__ */ bn.createElement(SelectMenuSuggestions_default, { + options, + hoverSelect: props2.hoverSelect, + query, + setIndex, + index, + id: props2.id, + classNames: classNames8, + expanded, + addTag, + allowNew: props2.allowNew + }) : null, props2.previewComponent); +}); +var SelectMenuComponent_default = SelectMenuComponent; -// 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/components/ui/menus/selectMenu.tsx +var SelectMenu = bn.forwardRef( + (props2, ref) => { + var _a2; + const initialOptions = props2.options.map((o3, i4) => { + return { + ...o3, + id: i4 + 1 + }; + }); + h2(() => { + setSuggestions( + props2.options.map((o3, i4) => { + return { + ...o3, + id: i4 + 1 + }; + }) + ); + }, [props2.options]); + const [suggestions, setSuggestions] = p2(initialOptions); + const [tags, setTags] = p2( + props2.value.map( + (v3) => { + var _a3; + return (_a3 = initialOptions.find((f4) => f4.value == v3)) != null ? _a3 : { + id: 0, + name: v3, + value: v3 + }; + } + ) + ); + const onDelete = T2( + (tagIndex) => { + const newTags = tags.filter((_5, i4) => i4 !== tagIndex); + setTags(newTags); + props2.saveOptions( + suggestions.map((f4) => f4.value), + newTags.map((f4) => f4.value) + ); + }, + [suggestions, tags] + ); + const onAddition = T2( + (newTag) => { + let tag = newTag; + let newSuggestions = suggestions; + let newTags = tags; + if (!suggestions.find((s5) => s5.value == newTag.value)) { + tag = { + id: suggestions.length + 1, + name: newTag.name, + value: newTag.name + }; + newSuggestions = [...suggestions, tag]; + setSuggestions(newSuggestions); + } + if (props2.multi) { + if (!tags.find((t4) => t4.value == tag.value)) { + newTags = [...tags, tag]; + setTags(newTags); + } + } else { + newTags = [tag]; + setTags(newTags); + } + props2.saveOptions( + newSuggestions.map((f4) => f4.value), + newTags.map((f4) => f4.value) + ); + if (!props2.multi) { + props2.hide(); + } + }, + [tags, suggestions] + ); + const onValidation = T2( + (newTag) => { + if (!props2.editable && !suggestions.find((s5) => s5.value == newTag.value)) { + return false; + } + if (newTag.name.length == 0) { + return false; + } + return true; + }, + [suggestions] + ); + return /* @__PURE__ */ bn.createElement(SelectMenuComponent_default, { + tags: props2.multi ? tags : [], + suggestions, + ref, + onDelete, + onAddition, + onValidate: onValidation, + defaultSuggestions: props2.defaultOptions, + placeholderText: (_a2 = props2.placeholder) != null ? _a2 : "", + minQueryLength: 0, + onHover: props2.onHover, + hoverSelect: props2.onHover ? true : false, + maxSuggestionsLength: props2.showAll ? Math.min(50, props2.options.length) : 8, + suggestionsOnly: !props2.searchable && !props2.editable, + allowNew: props2.editable, + previewComponent: props2.previewComponent + }); } - 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 +// src/components/ui/menus/menuItems.tsx +var inputMenuItem = (menuItem, value, setValue) => { + const frag = document.createDocumentFragment(); + const spanEl = frag.createEl("span"); + const inputEl = frag.createEl("input"); + inputEl.type = "text"; + inputEl.value = value; + inputEl.addEventListener("click", (e4) => { + e4.stopImmediatePropagation(); }); -} - -// 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"); + inputEl.addEventListener("mousedown", (e4) => { + e4.stopImmediatePropagation(); + }); + inputEl.addEventListener("mouseup", (e4) => { + e4.stopImmediatePropagation(); + }); + inputEl.addEventListener("blur", (e4) => { + setValue(inputEl.value); + }); + menuItem.dom.toggleClass("mk-menu-input", true); + menuItem.setTitle(frag); + return menuItem; +}; +var showSelectMenu = (point, optionProps) => { + const menu = new import_obsidian7.Menu(); + menu.dom.toggleClass("mk-menu", true); + menu.setUseNativeMenu(false); + const frag = document.createDocumentFragment(); + const div = frag.createDiv("mk-options-container"); + div.style.minHeight = Math.min( + 200, + (optionProps.options.length + (optionProps.searchable ? 1 : 0)) * 28 + ).toString() + "px"; + div.addEventListener("click", (e4) => { + e4.stopImmediatePropagation(); + }); + div.addEventListener("mousedown", (e4) => { + e4.stopImmediatePropagation(); + }); + div.addEventListener("mouseup", (e4) => { + e4.stopImmediatePropagation(); + }); + div.addEventListener("keydown", (e4) => { + }); + menu.onHide(() => optionProps.onHide && optionProps.onHide()); + const root = createRoot(div); + root.render( + /* @__PURE__ */ bn.createElement(bn.Fragment, null, /* @__PURE__ */ bn.createElement(SelectMenu, { + hide: () => { + menu.hide(); + optionProps.onHide && optionProps.onHide(); + }, + ...optionProps + })) + ); + menu.addItem((item) => { + item.setTitle(frag); + }); + const keys = [...menu.scope.keys]; + for (let i4 = 0; i4 < keys.length; i4++) { + if (keys[i4].key != "Escape") { + menu.scope.unregister(keys[i4]); + } } - for (var property in object) { - if (Object.prototype.hasOwnProperty.call(object, property)) { - ; - target[property] = object[property]; + menu.showAtPosition(point); + return menu; +}; +var disclosureMenuItem = (menuItem, multi, editable, title, value, options, saveOptions) => { + const frag = document.createDocumentFragment(); + const div = frag.createDiv("title"); + div.textContent = title; + const div2 = frag.createDiv("disclosure"); + div2.textContent = value; + menuItem.setTitle(frag); + menuItem.onClick((ev) => { + var _a2; + ev.stopPropagation(); + const offset = menuItem.dom.getBoundingClientRect(); + showSelectMenu( + { x: offset.right + 10, y: offset.top }, + { + multi, + editable, + value: (_a2 = splitString(value)) != null ? _a2 : [], + options, + saveOptions, + searchable: true, + showAll: true + } + ); + }); + return menuItem; +}; + +// 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 initialOptions = [ + ...(_b2 = splitString(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(() => { + var _a3; + setValue( + (props2.multi ? (_a3 = splitString(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(",") + ); + }; + const saveOptions = (_options, _value) => { + if (!props2.multi) { + setOptions( + _options.filter((f4) => f4.length > 0).map((t4) => ({ name: t4, value: t4 })) + ); + setValue(_value); + props2.saveOptions(_options.filter((f4) => f4.length > 0).join(","), _value.join(",")); + } else { + setOptions(_options.map((t4) => ({ name: t4, value: t4 }))); + setValue(_value); + props2.saveOptions(_options.filter((f4) => f4.length > 0).join(","), _value.join(",")); + } + }; + const menuProps = () => ({ + multi: false, + editable: true, + value, + options: !props2.multi ? [{ name: i18n_default.menu.none, value: "" }, ...options] : options, + saveOptions, + placeholder: i18n_default.labels.optionItemSelectPlaceholder, + searchable: true, + showAll: true, + onHide: () => props2.setEditMode(null) + }); + return /* @__PURE__ */ bn.createElement(OptionCellBase, { + value, + menuProps, + multi: props2.multi, + editMode: props2.editMode, + removeValue + }); +}; +var OptionCellBase = (props2) => { + const { + value, + menuProps, + removeValue, + getLabelString, + openItem, + valueClass + } = props2; + const menuRef = _2(null); + h2(() => { + if (props2.editMode == 2) { + if (!menuRef.current) + showMenu(); + } + }, [props2.editMode]); + const ref = _2(null); + const showMenu = () => { + const offset = ref.current.getBoundingClientRect(); + menuRef.current = showSelectMenu( + { x: offset.left - 4, y: offset.bottom - 4 }, + menuProps() + ); + }; + const editable = props2.editMode > 0; + return /* @__PURE__ */ bn.createElement("div", { + className: "mk-cell-option", + ref + }, value.length > 0 ? value.map((o3) => /* @__PURE__ */ bn.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", { + className: valueClass && valueClass(o3), + onClick: () => openItem && openItem(o3) + }, getLabelString ? getLabelString(o3) : o3), editable && props2.multi ? /* @__PURE__ */ bn.createElement("div", { + className: "mk-icon-xsmall", + onClick: () => removeValue(o3), + dangerouslySetInnerHTML: { + __html: uiIconSet["mk-ui-close"] } - } - return target; -} - -// node_modules/date-fns/esm/_lib/cloneObject/index.js -function cloneObject(object) { - return assign({}, object); -} + }) : /* @__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", { + 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", { + className: "mk-cell-option-item" + }, /* @__PURE__ */ bn.createElement("div", { + onClick: (e4) => !props2.multi && showMenu() + }, i18n_default.labels.select)) : props2.editMode == -1 ? /* @__PURE__ */ bn.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", { + onClick: (e4) => editable && showMenu(), + className: "mk-cell-option-new mk-icon-small", + dangerouslySetInnerHTML: { __html: uiIconSet["mk-ui-plus"] } + }) : /* @__PURE__ */ bn.createElement(bn.Fragment, null)); +}; -// 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); - } +// 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 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 removeValue = (v3) => { + const newValues = value.filter((f4) => f4.path != v3.path); + setValue(newValues); + props2.saveValue(newValues.map((f4) => f4.path).join(",")); + }; + h2(() => { + 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)) + })) + ); + }, [props2.initialValue]); + const saveOptions = (_options, _value) => { + insertContextItems(props2.plugin, _options, props2.contextTag); + if (!props2.multi) { + setValue( + _value.map((f4) => ({ + path: f4, + label: fileNameToString(folderPathToString(f4)) + })) + ); + props2.saveValue(_value.join(",")); } else { - if (minutes === 0) { - return locale2.formatDistance("lessThanXMinutes", 1, localizeOptions); - } else { - return locale2.formatDistance("xMinutes", minutes, localizeOptions); + const newValue = _value[0]; + if (newValue) { + const newValues = uniq([...value.map((f4) => f4.path), newValue]); + setValue( + newValues.map((f4) => ({ + label: fileNameToString(folderPathToString(f4)), + path: f4 + })) + ); + props2.saveValue(newValues.join(",")); } } - } 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); + }; + const openLink = async (o3) => { + const file = getAbstractFileAtPath(app, o3.path); + if (file) { + openAFile(file, props2.plugin, false); } - } -} - -// 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; -} - -// node_modules/date-fns/esm/getWeekYear/index.js -function getWeekYear(dirtyDate, options) { - var _ref, _ref2, _ref3, _options$firstWeekCon, _options$locale, _options$locale$optio, _defaultOptions$local, _defaultOptions$local2; - requiredArgs(1, arguments); - var date = toDate(dirtyDate); - var year = date.getFullYear(); - var defaultOptions3 = getDefaultOptions(); - var firstWeekContainsDate = toInteger((_ref = (_ref2 = (_ref3 = (_options$firstWeekCon = options === null || options === void 0 ? void 0 : options.firstWeekContainsDate) !== null && _options$firstWeekCon !== void 0 ? _options$firstWeekCon : options === null || options === void 0 ? void 0 : (_options$locale = options.locale) === null || _options$locale === void 0 ? void 0 : (_options$locale$optio = _options$locale.options) === null || _options$locale$optio === void 0 ? void 0 : _options$locale$optio.firstWeekContainsDate) !== null && _ref3 !== void 0 ? _ref3 : defaultOptions3.firstWeekContainsDate) !== null && _ref2 !== void 0 ? _ref2 : (_defaultOptions$local = defaultOptions3.locale) === null || _defaultOptions$local === void 0 ? void 0 : (_defaultOptions$local2 = _defaultOptions$local.options) === null || _defaultOptions$local2 === void 0 ? void 0 : _defaultOptions$local2.firstWeekContainsDate) !== null && _ref !== void 0 ? _ref : 1); - if (!(firstWeekContainsDate >= 1 && firstWeekContainsDate <= 7)) { - throw new RangeError("firstWeekContainsDate must be between 1 and 7 inclusively"); - } - var firstWeekOfNextYear = new Date(0); - firstWeekOfNextYear.setFullYear(year + 1, 0, firstWeekContainsDate); - firstWeekOfNextYear.setHours(0, 0, 0, 0); - var startOfNextYear = startOfWeek(firstWeekOfNextYear, options); - var firstWeekOfThisYear = new Date(0); - firstWeekOfThisYear.setFullYear(year, 0, firstWeekContainsDate); - firstWeekOfThisYear.setHours(0, 0, 0, 0); - var startOfThisYear = startOfWeek(firstWeekOfThisYear, options); - if (date.getTime() >= startOfNextYear.getTime()) { - return year + 1; - } else if (date.getTime() >= startOfThisYear.getTime()) { - return year; - } else { - return year - 1; - } -} - -// 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(); -} + }; + const menuProps = () => { + const _options = !props2.multi ? [{ name: i18n_default.menu.none, value: "" }, ...options] : options; + return { + multi: false, + editable: true, + value: value.map((f4) => f4.path), + options: _options, + saveOptions, + placeholder: i18n_default.labels.contextItemSelectPlaceholder, + searchable: true, + showAll: true, + onHide: () => props2.setEditMode(null) + }; + }; + return /* @__PURE__ */ bn.createElement(OptionCellBase, { + menuProps, + openItem: openLink, + getLabelString: (o3) => o3.label, + value, + multi: props2.multi, + editMode: props2.editMode, + removeValue + }); +}; -// node_modules/date-fns/esm/subDays/index.js -function subDays(dirtyDate, dirtyAmount) { - requiredArgs(2, arguments); - var amount = toInteger(dirtyAmount); - return addDays(dirtyDate, -amount); -} +// src/components/ui/menus/datePickerMenu.tsx +var import_obsidian8 = require("obsidian"); // node_modules/react-day-picker/dist/index.esm.js var __assign2 = function() { @@ -24550,9 +24594,9 @@ function getNextFocus(focusedDay, options) { }; var newFocusedDay = moveFns[moveBy](focusedDay, direction === "after" ? 1 : -1); if (direction === "before" && fromDate) { - newFocusedDay = max2([fromDate, newFocusedDay]); + newFocusedDay = max([fromDate, newFocusedDay]); } else if (direction === "after" && toDate2) { - newFocusedDay = min2([toDate2, newFocusedDay]); + newFocusedDay = min([toDate2, newFocusedDay]); } var isFocusable = true; if (modifiers) { @@ -31931,7 +31975,7 @@ var triggerMultiFileMenu = (plugin, selectedFiles2, e4) => { { name: "None", value: "" }, ...colors.map((f4) => ({ name: f4[0], value: f4[1] })) ], - (_4, values) => { + (_5, values) => { saveFileColors(plugin, files, values[0]); } ); @@ -32073,7 +32117,7 @@ var triggerFileMenu = (plugin, file, isFolder, e4) => { { name: "None", value: "" }, ...colors.map((f4) => ({ name: f4[0], value: f4[1] })) ], - (_4, values) => { + (_5, values) => { saveFileColor(plugin, file.path, values[0]); } ); @@ -32295,9 +32339,8 @@ var FileCell = (props2) => { // src/components/ContextView/DataTypeView/FilePropertyCell.tsx var FilePropertyCell = (props2) => { const { property } = props2; - const file = getAbstractFileAtPath(app, props2.file); const [cache, setCache] = p2(null); - const initialValue = file ? appendFileMetaData(property, file) : ""; + const initialValue = props2.initialValue; if (property == "folder") { return /* @__PURE__ */ bn.createElement("div", { className: "mk-cell-fileprop", @@ -32326,7 +32369,7 @@ var FilePropertyCell = (props2) => { } return /* @__PURE__ */ bn.createElement("div", { className: "mk-cell-fileprop" - }); + }, initialValue); }; // src/components/ContextView/DataTypeView/NumberCell.tsx @@ -32420,19 +32463,19 @@ var TextCell = (props2) => { // src/components/ui/menus/propertyMenu.tsx var import_obsidian15 = require("obsidian"); var PropertyMenuComponent = (props2) => { - var _a2, _b2, _c2; + var _a2; const [field, setField] = p2(props2.field); - const selectedType = (_4, value) => { + const selectedType = (_5, value) => { const newField = { ...field, type: value[0], value: getNewValueForType(field, value) }; setField(newField); props2.saveField(newField); }; - const selectedValue = (_4, value) => { + const selectedValue = (_5, value) => { const newField = { ...field, value: value[0] }; setField(newField); props2.saveField(newField); }; - const selectedContext = (_4, value) => { + const selectedContext = (_5, value) => { const newField = { ...field, value: value[0] }; setField(newField); props2.saveContext(newField, value); @@ -32463,6 +32506,7 @@ var PropertyMenuComponent = (props2) => { searchable: false, saveOptions: selectedType, value: [], + showAll: true, options: fieldTypes.filter((f4) => !f4.restricted).map((f4, i4) => ({ id: i4 + 1, name: f4.label, @@ -32488,15 +32532,26 @@ var PropertyMenuComponent = (props2) => { ); }; const selectFileProp = (e4) => { + const properties2 = props2.fields.filter((f4) => f4.type == "file" || f4.type == "context").reduce((p3, c4) => { + var _a3, _b2; + return [...p3, ...c4.type == "file" ? filePropTypes.map((f4) => ({ + name: c4.name + "." + f4.name, + value: c4.name + "." + f4.value + })) : (_b2 = (_a3 = props2.context[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, + editable: true, searchable: false, saveOptions: selectedValue, value: [], - options: filePropTypes + options: properties2, + showAll: true } ); }; @@ -32509,7 +32564,7 @@ var PropertyMenuComponent = (props2) => { }, /* @__PURE__ */ bn.createElement("span", null, i18n_default.labels.propertyContext), /* @__PURE__ */ bn.createElement("span", null, field.value)) : fieldType.type == "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, (_c2 = (_b2 = filePropTypes.find((f4) => f4.value == field.value)) == null ? void 0 : _b2.name) != null ? _c2 : "")) : /* @__PURE__ */ bn.createElement(bn.Fragment, null), fieldType.multi ? /* @__PURE__ */ bn.createElement("div", { + }, /* @__PURE__ */ bn.createElement("span", null, i18n_default.labels.propertyFileProp), /* @__PURE__ */ bn.createElement("span", null, field.value)) : /* @__PURE__ */ bn.createElement(bn.Fragment, null), fieldType.multi ? /* @__PURE__ */ bn.createElement("div", { className: "menu-item" }, /* @__PURE__ */ bn.createElement("span", null, i18n_default.labels.multiple), /* @__PURE__ */ bn.createElement("input", { type: "checkbox", @@ -32517,7 +32572,7 @@ var PropertyMenuComponent = (props2) => { onChange: () => toggleMulti() })) : /* @__PURE__ */ bn.createElement(bn.Fragment, null)); }; -var showPropertyMenu = (plugin, position, editable, options, field, saveField, saveContext, hide, deleteColumn, sortColumn, hidden) => { +var showPropertyMenu = (plugin, position, editable, options, field, fields, contextTables, saveField, saveContext, hide, deleteColumn, sortColumn, hidden) => { const menu = new import_obsidian15.Menu(); menu.setUseNativeMenu(false); if (editable) { @@ -32543,6 +32598,8 @@ var showPropertyMenu = (plugin, position, editable, options, field, saveField, s /* @__PURE__ */ bn.createElement(bn.Fragment, null, /* @__PURE__ */ bn.createElement(PropertyMenuComponent, { plugin, field, + fields, + context: contextTables, options, saveField, saveContext @@ -32714,7 +32771,7 @@ var ColumnHeader = (props2) => { value: "type." + f4.type + "." + f4.label })) ]; - const saveOptions = (_4, values) => { + const saveOptions = (_5, values) => { const newValue = values[0]; const newType = newValue.split("."); if (newType[0] == "fm") { @@ -32762,7 +32819,7 @@ var ColumnHeader = (props2) => { field.name, field.table == "" ? tableData : contextTable[field.table] ); - showPropertyMenu(props2.plugin, { x: offset.left, y: offset.top + 30 }, props2.editable, options, field, saveField, saveContext, hideColumn, delColumn, sortColumn, predicate.colsHidden.includes(field.name + 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); @@ -32784,7 +32841,7 @@ var ColumnHeader = (props2) => { }; // src/components/ContextView/TableView/TableView.tsx -var import_lodash3 = __toESM(require_lodash()); +var import_lodash4 = __toESM(require_lodash()); var import_obsidian17 = require("obsidian"); // src/components/ContextView/DataTypeView/ImageCell.tsx @@ -32855,7 +32912,7 @@ var LinkCell = (props2) => { const resolveLinks = (links) => links.map((f4) => ({ value: f4.value, label: filePathToString(f4.value), - file: getFileFromString(f4.value, getFolderPathFromString(props2.file)) + file: getFileFromString2(f4.value, getFolderPathFromString(props2.file)) })); const ref = _2(null); const [value, setValue] = p2( @@ -32866,7 +32923,7 @@ var LinkCell = (props2) => { setValue(newValues); props2.saveValue(newValues.map((f4) => f4.value).join(",")); }; - const saveOptions = (_4, _value) => { + const saveOptions = (_5, _value) => { if (!props2.multi) { setValue(resolveLinks(stringValueToLink(_value))); props2.saveValue(_value.map((f4) => `[[${f4}]]`).join(",")); @@ -32887,14 +32944,13 @@ var LinkCell = (props2) => { const _options = !props2.multi ? [{ name: i18n_default.menu.none, value: "" }, ...options] : options; return { multi: false, - editable: false, + editable: true, value: value.map((f4) => f4.value), options: _options, saveOptions, placeholder: i18n_default.labels.linkItemSelectPlaceholder, detail: true, - searchable: true, - onHide: () => props2.setEditMode(null) + searchable: true }; }; const openLink = async (o3) => { @@ -32909,7 +32965,6 @@ var LinkCell = (props2) => { setValue(resolveLinks(value)); } }; - const editable = props2.editMode != 0; return /* @__PURE__ */ bn.createElement(OptionCellBase, { menuProps, getLabelString: (o3) => o3.label, @@ -33028,7 +33083,7 @@ var TableView = (props2) => { debouncedSavePredicate(newColSize); }; const debouncedSavePredicate = T2( - (0, import_lodash3.debounce)( + (0, import_lodash4.debounce)( (nextValue) => savePredicate({ ...predicate, colsSize: nextValue @@ -33184,7 +33239,7 @@ var TableView = (props2) => { cell: ({ getValue, row: { index }, - column: { id: id2 }, + column: { colId }, cell, table: table2 }) => { @@ -33257,8 +33312,7 @@ var TableView = (props2) => { } else if (fieldType.type == "fileprop") { return /* @__PURE__ */ bn.createElement(FilePropertyCell, { ...cellProps, - property: f4.value, - file: data[index]["File"] + property: f4.value }); } else if (fieldType.type == "tag") { return /* @__PURE__ */ bn.createElement(TagCell, { @@ -33523,14 +33577,7 @@ var TableView = (props2) => { onClick: () => { newRow(); } - }, "+ New")) : /* @__PURE__ */ bn.createElement(bn.Fragment, null), table.getFooterGroups().map((footerGroup) => /* @__PURE__ */ bn.createElement("tr", { - key: footerGroup.id - }, footerGroup.headers.map((header) => /* @__PURE__ */ bn.createElement("th", { - key: header.id - }, header.isPlaceholder ? null : flexRender( - header.column.columnDef.footer, - header.getContext() - ))))))), j3( + }, "+ New")) : /* @__PURE__ */ bn.createElement(bn.Fragment, null))), j3( /* @__PURE__ */ bn.createElement(DragOverlay, { dropAnimation: null, zIndex: 1600 @@ -33693,8 +33740,7 @@ var DataTypeView = (props2) => { } else if (fieldType.type == "fileprop") { return /* @__PURE__ */ bn.createElement(FilePropertyCell, { ...viewProps, - property: column.value, - file + property: column.value }); } else if (fieldType.type == "number") { return /* @__PURE__ */ bn.createElement(NumberCell, { @@ -34823,7 +34869,7 @@ var parseOutReferences = (ostr) => { const refIndex = str.lastIndexOf("#"); return refIndex != -1 ? [str.substring(0, refIndex), str.substring(refIndex + 1)] : [str, void 0]; }; -var getFileFromString = (url, source) => { +var getFileFromString2 = (url, source) => { return app.metadataCache.getFirstLinkpathDest(url, source != null ? source : ""); }; var getLineRangeFromRef = (file, ref, plugin) => { @@ -34946,7 +34992,7 @@ var loadFlowEditor = (cm, flowEditorInfo2, source, make) => { return; } } - const file = getFileFromString(link, source); + const file = getFileFromString2(link, source); const aFile = getAbstractFileAtPath(app, link); if (file) { const selectiveRange = getLineRangeFromRef(file, ref, make); @@ -35057,23 +35103,31 @@ var focusPortal = async (plugin, evt) => { var openFileFromPortal = (plugin, evt) => { const { file: fullLink, source } = evt.detail; const [link, ref] = parseOutReferences(fullLink); - const file = getFileFromString(link, source); + const file = getFileFromString2(link, source); openAFile(file, plugin, false); }; -var spawnLeafFromFile = async (plugin, file, el, type, ref) => { +var spawnLeafFromFile = async (plugin, file, el, type, ref, from, to) => { + var _a2; if (type == "context") { const newLeaf2 = spawnPortal(plugin, el); newLeaf2.setViewState({ type: INLINE_CONTEXT_VIEW_TYPE, - state: { file, ref } + 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) => { @@ -35335,7 +35389,7 @@ var SyncMetadataComponent = (props2) => { (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) => 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); } @@ -35345,12 +35399,12 @@ var SyncMetadataComponent = (props2) => { 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)); + setSyncColumns((s5) => s5.filter((f4) => !(f4.name == column.name && f4.type == column.type))); } else { setSyncColumns((s5) => [...s5, column]); } }; - const saveContexts = (_4, value) => { + const saveContexts = (_5, value) => { setTable(tagFromString(value[0])); }; const showContextMenu = (e4) => { @@ -35422,7 +35476,7 @@ var SyncMetadataComponent = (props2) => { }; // src/components/ContextView/FilterBar/TagSelector.tsx -var import_lodash4 = __toESM(require_lodash()); +var import_lodash5 = __toESM(require_lodash()); var import_obsidian25 = require("obsidian"); var TagSelector = (props2) => { const { @@ -35450,8 +35504,8 @@ var TagSelector = (props2) => { def: tags.join("&") }); }; - const saveContexts = async (_4, value) => { - const tags = (0, import_lodash4.uniq)([...tagContexts, ...value.map((f4) => tagFromString(f4))]); + const saveContexts = async (_5, value) => { + const tags = (0, import_lodash5.uniq)([...tagContexts, ...value.map((f4) => tagFromString(f4))]); tags.forEach((tag) => { initiateContextIfNotExists(props2.plugin, tag).then((f4) => { if (f4) { @@ -35545,7 +35599,7 @@ var TagSelector = (props2) => { } return { uniques: [], - cols: (0, import_lodash4.uniq)([...p3.cols, ...fmKeys]), + cols: (0, import_lodash5.uniq)([...p3.cols, ...fmKeys]), rows: [ ...p3.rows, { @@ -35570,8 +35624,8 @@ var TagSelector = (props2) => { 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_lodash4.uniq)([...yamlTableData.uniques, ...dvTableData.uniques]), - cols: (0, import_lodash4.uniq)([...yamlTableData.cols, ...dvTableData.cols]), + uniques: (0, import_lodash5.uniq)([...yamlTableData.uniques, ...dvTableData.uniques]), + cols: (0, import_lodash5.uniq)([...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 : {} }; @@ -35602,7 +35656,7 @@ var TagSelector = (props2) => { saveContextDB(newTable, table); saveSchema({ ...dbSchema, - def: (0, import_lodash4.uniq)([...tagContexts, table]).join("&") + def: (0, import_lodash5.uniq)([...tagContexts, table]).join("&") }); } else { consolidateRowsToTag( @@ -35619,7 +35673,7 @@ var TagSelector = (props2) => { }).then(() => { saveSchema({ ...dbSchema, - def: (0, import_lodash4.uniq)([...tagContexts, table]).join("&") + def: (0, import_lodash5.uniq)([...tagContexts, table]).join("&") }); }); } @@ -35709,7 +35763,7 @@ var FilterBar = (props2) => { editable: false, value: tagContexts, options: views.map((m5) => ({ name: m5.name, value: m5.id })), - saveOptions: (_4, value) => selectView(_dbschema, value[0]), + saveOptions: (_5, value) => selectView(_dbschema, value[0]), placeholder: i18n_default.labels.viewItemSelectPlaceholder, searchable: false, showAll: true @@ -35809,7 +35863,7 @@ var FilterBar = (props2) => { const offset = e4.target.getBoundingClientRect(); menu.showAtPosition({ x: offset.left, y: offset.top + 30 }); }; - const addSort = (_4, sort) => { + const addSort = (_5, sort) => { var _a2; const field = sort[0]; const fieldType = (_a2 = filteredCols.find((f4) => f4.name + f4.table == field)) == null ? void 0 : _a2.type; @@ -35828,7 +35882,7 @@ var FilterBar = (props2) => { }); } }; - const saveGroupBy = (_4, groupBy2) => { + const saveGroupBy = (_5, groupBy2) => { savePredicate({ ...predicate, groupBy: groupBy2 @@ -35841,7 +35895,7 @@ var FilterBar = (props2) => { sort: newSort }); }; - const addFilter = (_4, filter) => { + const addFilter = (_5, filter) => { var _a2; const field = filter[0]; const fieldType = (_a2 = filteredCols.find((f4) => f4.name + f4.table == field)) == null ? void 0 : _a2.type; @@ -35868,7 +35922,7 @@ var FilterBar = (props2) => { const changeSortMenu = (e4, sort) => { var _a2; const offset = e4.target.getBoundingClientRect(); - const saveSort = (_4, newType) => { + const saveSort = (_5, newType) => { const type = newType[0]; const newSort = { ...sort, @@ -35925,7 +35979,7 @@ var FilterBar = (props2) => { const changeFilterMenu = (e4, filter) => { var _a2; const offset = e4.target.getBoundingClientRect(); - const saveFilter = (_4, newType) => { + const saveFilter = (_5, newType) => { const type = newType[0]; const newFilter = { ...filter, @@ -35968,7 +36022,7 @@ var FilterBar = (props2) => { multi: false, editable: false, value: [], - options: filteredCols.map((f4) => ({ + options: filteredCols.filter((f4) => predicateFnsForType(f4.type, filterFnTypes).length > 0).map((f4) => ({ name: f4.name + f4.table, value: f4.name + f4.table })), @@ -36537,20 +36591,11 @@ var defaultConfigFile = async (app2) => { ); }; var fileExtensionForFile = (path) => path.split(".").pop(); -var appendFileMetadataForRow = (row, fields) => { - const file = getAbstractFileAtPath(app, row.File); - if (!file) { - return row; - } - return { - ...row, - ...fields.filter((f4) => f4.type == "fileprop").reduce( - (p3, c4) => ({ ...p3, [c4.name]: appendFileMetaData(c4.value, file) }), - {} - ) - }; +var appendFilesMetaData = (propType, filesString) => { + const files = splitString(filesString).map((f4) => getAbstractFileAtPath(app, f4)).filter((f4) => f4); + return files.map((f4) => appendFileMetaData3(propType, f4)).join(","); }; -var appendFileMetaData = (propType, file) => { +var appendFileMetaData3 = (propType, file) => { let value = ""; if (file) { if (propType == "folder") { @@ -36576,6 +36621,9 @@ var viewTypeByString = (file) => { if (file.charAt(0) == "#") { return "tag"; } + if (file.charAt(file.length - 1) == "/") { + return "folder"; + } const portalFile = app.vault.getAbstractFileByPath(file); if (portalFile instanceof import_obsidian28.TFolder) { return "folder"; @@ -36601,11 +36649,11 @@ function getAllAbstractFilesInVault(plugin, app2) { recursiveFx(rootFolder); return files; } +var removeTrailingSlashFromFolder = (path) => path.slice(-1) == "/" ? path.substring(0, path.length - 1) : path; var getFolderFromPath = (app2, path) => { if (!path) return null; - const file = path.slice(-1) == "/" ? path.substring(0, path.length - 1) : path; - const afile = getAbstractFileAtPath(app2, file); + const afile = getAbstractFileAtPath(app2, removeTrailingSlashFromFolder(path)); if (!afile) return null; return afile instanceof import_obsidian28.TFolder ? afile : afile.parent; @@ -36845,7 +36893,7 @@ var internalLinkHover = hoverTooltip((view, pos, side) => { const info = stateField.find((f4) => f4.to == to); if (info) { hovObject = { - pos: pos - 5, + pos, end: to, above: true, create(view2) { @@ -36911,43 +36959,44 @@ var flowEditorInfo = import_state5.StateField.define({ }; newValues.push(info); } - 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 existingInfo = existingLinks[offset]; - const id2 = existingInfo ? existingInfo.id : genId(); - usedContainers.push(link); - const info = { - id: id2, - link: match2[1], - startOfLineFix: false, - from: match2.index + 2, - to: match2.index + 2 + match2[1].length, - embed: 0, - height: existingInfo ? ((_e2 = tr.annotation(cacheFlowEditorHeight)) == null ? void 0 : _e2[0]) == id2 && ((_f = tr.annotation(cacheFlowEditorHeight)) == null ? void 0 : _f[1]) != 0 ? (_g = tr.annotation(cacheFlowEditorHeight)) == null ? void 0 : _g[1] : existingInfo.height : -1, - expandedState: existingInfo ? ((_h = tr.annotation(toggleFlowEditor)) == null ? void 0 : _h[0]) == id2 ? reverseExpandedState(existingInfo.expandedState) : existingInfo.expandedState : 0 - }; - newValues.push(info); - } - 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 existingInfo = existingLinks[offset]; - const id2 = existingInfo ? existingInfo.id : genId(); - usedContainers.push(link); - const info = { - id: id2, - link: match2[1], - startOfLineFix: false, - from: match2.index + 3, - to: match2.index + 3 + match2[1].length, - embed: 2, - height: existingInfo ? ((_i = tr.annotation(cacheFlowEditorHeight)) == null ? void 0 : _i[0]) == id2 && ((_j = tr.annotation(cacheFlowEditorHeight)) == null ? void 0 : _j[1]) != 0 ? (_k = tr.annotation(cacheFlowEditorHeight)) == null ? void 0 : _k[1] : existingInfo.height : -1, - expandedState: existingInfo ? ((_l = tr.annotation(toggleFlowEditor)) == null ? void 0 : _l[0]) == id2 ? reverseExpandedState(existingInfo.expandedState) : existingInfo.expandedState : 1 - }; - newValues.push(info); + 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 existingInfo = existingLinks[offset]; + const id2 = existingInfo ? existingInfo.id : genId(); + usedContainers.push(link); + const info = { + id: id2, + link: match2[1], + startOfLineFix: false, + from: match2.index + 2, + to: match2.index + 2 + match2[1].length, + embed: 0, + height: existingInfo ? ((_e2 = tr.annotation(cacheFlowEditorHeight)) == null ? void 0 : _e2[0]) == id2 && ((_f = tr.annotation(cacheFlowEditorHeight)) == null ? void 0 : _f[1]) != 0 ? (_g = tr.annotation(cacheFlowEditorHeight)) == null ? void 0 : _g[1] : existingInfo.height : -1, + expandedState: existingInfo ? ((_h = tr.annotation(toggleFlowEditor)) == null ? void 0 : _h[0]) == id2 ? reverseExpandedState(existingInfo.expandedState) : existingInfo.expandedState : 0 + }; + 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 existingInfo = existingLinks[offset]; + const id2 = existingInfo ? existingInfo.id : genId(); + usedContainers.push(link); + const info = { + id: id2, + link: match2[1], + startOfLineFix: false, + from: match2.index + 3, + to: match2.index + 3 + match2[1].length, + embed: 2, + height: existingInfo ? ((_i = tr.annotation(cacheFlowEditorHeight)) == null ? void 0 : _i[0]) == id2 && ((_j = tr.annotation(cacheFlowEditorHeight)) == null ? void 0 : _j[1]) != 0 ? (_k = tr.annotation(cacheFlowEditorHeight)) == null ? void 0 : _k[1] : existingInfo.height : -1, + expandedState: existingInfo ? ((_l = tr.annotation(toggleFlowEditor)) == null ? void 0 : _l[0]) == id2 ? reverseExpandedState(existingInfo.expandedState) : existingInfo.expandedState : 1 + }; + newValues.push(info); + } } newValues.sort(compareByField("from", true)); return newValues; @@ -37108,89 +37157,8 @@ var atomicSelect = import_state6.EditorState.transactionFilter.of( } ); -// src/cm-extensions/markSans/hr.ts -var import_state7 = require("@codemirror/state"); -var import_view5 = require("@codemirror/view"); -var resetLine = import_view5.Decoration.line({ class: "mk-reset" }); -var needsReset = (state, typeString, from, to) => { - const length = to - from; - if (typeString.contains("HyperMD-header")) { - if (parseInt(typeString.replace(/.*HyperMD-header-(\d+).*/, "$1")) == length) { - return true; - } - let truefalse = true; - iterateTreeInSelection({ from, to }, state, { - enter: ({ type, from: from2, to: to2 }) => { - if (type.name.contains("formatting-header")) { - truefalse = false; - } - } - }); - return truefalse; - } - return false; -}; -var hrResetFix = import_state7.StateField.define({ - create() { - return import_view5.Decoration.none; - }, - update(value, tr) { - let builder = new import_state7.RangeSetBuilder(); - iterateTreeInDocument(tr.state, { - enter: ({ type, from, to }) => { - if (needsReset(tr.state, type.name, from, to)) { - builder.add(from, from, resetLine); - } - } - }); - const dec = builder.finish(); - return dec; - }, - provide: (f4) => import_view5.EditorView.decorations.from(f4) -}); -var hrDecorations = (state) => { - let builder = new import_state7.RangeSetBuilder(); - let nodes2 = []; - iterateTreeInDocument(state, { - enter: ({ name, from, to }) => { - if (name.contains("formatting-header") && state.sliceDoc(from, to) == "---" && !(state.selection.main.from >= from && state.selection.main.to <= to)) { - builder.add(from, to, hr); - } - } - }); - const dec = builder.finish(); - return dec; -}; -var hrField = import_state7.StateField.define({ - create(state) { - return hrDecorations(state); - }, - update(value, tr) { - if (!tr.docChanged) - return value; - return hrDecorations(tr.state); - }, - provide: (f4) => import_view5.EditorView.decorations.from(f4) -}); -var HRWidget = class extends import_view5.WidgetType { - constructor() { - super(); - } - eq(other) { - return true; - } - toDOM() { - const div = document.createElement("hr"); - return div; - } -}; -var hr = import_view5.Decoration.replace({ - widget: new HRWidget(), - block: false -}); - // src/cm-extensions/inlineStylerView/marks.ts -var import_state8 = require("@codemirror/state"); +var import_state7 = require("@codemirror/state"); // src/cm-extensions/markSans/obsidianSyntax.ts var oMarks = [ @@ -37218,7 +37186,7 @@ var oMarks = [ ]; // src/cm-extensions/inlineStylerView/marks.ts -var toggleMark = import_state8.Annotation.define(); +var toggleMark = import_state7.Annotation.define(); var trimSpace = (pos, moveDirLeft, state) => { if (moveDirLeft && state.sliceDoc(pos, pos + 1) == " ") return pos + 1; @@ -37327,7 +37295,7 @@ var removeAllInternalMarks = (sel, state, mark) => { changes: returnTrans }; }; -var toggleMarkExtension = import_state8.EditorState.transactionFilter.of( +var toggleMarkExtension = import_state7.EditorState.transactionFilter.of( (tr) => { if (!tr.annotation(toggleMark)) return tr; @@ -37375,159 +37343,8 @@ var toggleMarkExtension = import_state8.EditorState.transactionFilter.of( } ); -// src/cm-extensions/markSans/selection.ts -var import_state9 = require("@codemirror/state"); -var makerDelete = import_state9.EditorState.transactionFilter.of( - (tr) => { - let newTrans = []; - if (tr.isUserEvent("delete.forward")) { - } - if (tr.isUserEvent("delete.backward") && !tr.isUserEvent("delete.selection") && !tr.isUserEvent("delete.selection.smart")) { - const selection = tr.newSelection.main; - iterateTreeInSelection(selection, tr.startState, { - enter: ({ type, from, to }) => { - const mark = positionMarkOffset(type.name, from, to, tr.startState); - if (mark) { - if (!hasReset(tr.startState, from, to)) { - newTrans.push( - pointDeletion(tr, mark.from, mark.to, selection.from) - ); - } - } - } - }); - } - return [tr, ...newTrans]; - } -); -var reverseSel = (t4) => { - const sel = t4.selection; - return { selection: import_state9.EditorSelection.single(sel.main.head, sel.main.anchor) }; -}; -var selFromTo = (from, to) => { - return { selection: import_state9.EditorSelection.single(from, to) }; -}; -var delFromTo = (tr, from, to) => { - return { - changes: { from, to }, - annotations: import_state9.Transaction.userEvent.of( - `${tr.annotation(import_state9.Transaction.userEvent)}.smart` - ) - }; -}; -var pointDeletion = (tr, from, to, pos) => checkMarkMiddle(from, to, pos) ? deleteMark(tr, from, pos) : null; -var deleteMark = (tr, from, pos) => from == 0 ? delFromTo(tr, from, pos) : delFromTo(tr, from, pos); -var changeSelectionToEndPrevLine = (from, head) => selFromTo(from, head - 1); -var changeSelectionToAfterMark = (head, to) => selFromTo(head, to); -var changeSelectionToMark = (to, head) => selFromTo(to, head); -var rangeBeginsInMark = (from, to, pos) => pos >= from && pos < to; -var rangeEndsAtMark = (from, to, pos) => pos == from; -var pointSelection = (from, to, pos, left) => checkLineStart(from, pos) ? to - from == 1 && left ? selectPreviousLine(from, pos) : selectLineStart(to) : checkMarkMiddle(from, to, pos) ? left && checkMarkMiddleRightMost(from, to, pos) ? selectPreviousLine(from, pos) : selectLineStart(to) : null; -var checkLineStart = (from, pos) => from == pos; -var checkMarkMiddle = (from, to, pos) => pos > from && pos < to; -var checkMarkMiddleRightMost = (from, to, pos) => pos == to - 1; -var selectPreviousLine = (from, pos) => from == 0 ? selFromTo(pos, pos) : selFromTo(from - 1, from - 1); -var selectLineStart = (to) => selFromTo(to, to); -var positionMarkOffset = (typeString, from, to, state) => { - if (typeString.contains("HyperMD-header")) { - return { - from, - to: from + parseInt(typeString.replace(/.*HyperMD-header-(\d+).*/, "$1")) + 1 - }; - } - if (typeString.contains("HyperMD-task-line")) { - return { - from, - to: from + parseInt(typeString.replace(/.*HyperMD-list-line-(\d+).*/, "$1")) + 5 - }; - } - if (typeString.contains("formatting-list-ol")) { - let returnMark = void 0; - iterateTreeInSelection({ from, to }, state, { - enter: ({ type, from: from2, to: to2 }) => { - if (type.name.contains("HyperMD-list-line")) { - returnMark = { - from: from2, - to: from2 + parseInt(type.name.replace(/.*HyperMD-list-line-(\d+).*/, "$1")) + 2 - }; - } - } - }); - return returnMark; - } - if (typeString.contains("HyperMD-list-line")) { - return { - from, - to: from + parseInt(typeString.replace(/.*HyperMD-list-line-(\d+).*/, "$1")) + 1 - }; - } - if (typeString.contains("HyperMD-quote") && !typeString.contains("HyperMD-quote-lazy")) { - return { from, to: from + 1 }; - } - return void 0; -}; -var rangeSelection = (from, to, anchor, head) => { - const minFrom = Math.min(anchor, head); - const maxTo = Math.max(anchor, head); - if (rangeEndsAtMark(from, to, maxTo)) { - const newSel = changeSelectionToAfterMark(minFrom, to); - return minFrom == anchor ? newSel : reverseSel(newSel); - } - if (rangeBeginsInMark(from, to, maxTo)) { - const newSel = changeSelectionToEndPrevLine(minFrom, from); - return minFrom == anchor ? newSel : reverseSel(newSel); - } - if (rangeBeginsInMark(from, to, minFrom)) { - const newSel = changeSelectionToMark(to, maxTo); - return minFrom == head ? newSel : reverseSel(newSel); - } - return null; -}; -var hasReset = (state, from, to) => { - var _a2; - let trueFalse = false; - (_a2 = state.field(hrResetFix, false)) == null ? void 0 : _a2.between(from, to, (f4, t4, v3) => { - trueFalse = true; - }); - return trueFalse; -}; -var makerSelect = import_state9.EditorState.transactionFilter.of( - (tr) => { - let newTrans = []; - if (tr.isUserEvent("delete") || tr.isUserEvent("input")) { - return tr; - } - const selection = tr.newSelection.main; - if (selection.from == 0 && selection.to == 0) - return tr; - iterateTreeInSelection(selection, tr.state, { - enter: ({ type, from, to }) => { - const mark = positionMarkOffset(type.name, from, to, tr.state); - if (mark) { - if (!hasReset(tr.state, from, to)) { - const newSel = selection.from != selection.to ? rangeSelection( - mark.from, - mark.to, - selection.from, - selection.to - ) : pointSelection( - mark.from, - mark.to, - selection.from, - tr.startState.selection.main.from == selection.from + 1 - ); - if (newSel) - newTrans.push(newSel); - } - } - } - }); - return [tr, ...newTrans]; - } -); - // src/cm-extensions/inlineStylerView/inlineStyler.tsx -var import_state10 = require("@codemirror/state"); +var import_state8 = require("@codemirror/state"); // src/cm-extensions/inlineStylerView/InlineMenu.tsx var import_classnames4 = __toESM(require_classnames()); @@ -37769,7 +37586,7 @@ var InlineMenuComponent = (props2) => { }; // src/cm-extensions/inlineStylerView/inlineStyler.tsx -var cursorTooltipField = (plugin) => import_state10.StateField.define({ +var cursorTooltipField = (plugin) => import_state8.StateField.define({ create: getCursorTooltips(plugin), update(tooltips2, tr) { if (!tr.docChanged && !tr.selection) @@ -37810,8 +37627,8 @@ function cursorTooltip(plugin) { } // src/cm-extensions/flowEditor/flowViewUpdates.ts -var import_view6 = require("@codemirror/view"); -var flowViewUpdates = import_view6.EditorView.updateListener.of((v3) => { +var import_view5 = require("@codemirror/view"); +var flowViewUpdates = import_view5.EditorView.updateListener.of((v3) => { if (v3.heightChanged) { app.workspace.iterateRootLeaves((leaf) => { var _a2, _b2; @@ -37852,25 +37669,25 @@ var flowViewUpdates = import_view6.EditorView.updateListener.of((v3) => { }); // src/cm-extensions/placeholder.ts -var import_view7 = require("@codemirror/view"); -var import_state11 = require("@codemirror/state"); -var placeholderLine = import_view7.Decoration.line({ +var import_view6 = require("@codemirror/view"); +var import_state9 = require("@codemirror/state"); +var placeholderLine = import_view6.Decoration.line({ attributes: { "data-ph": i18n_default.labels.placeholder }, class: "cm-placeholder" }); -var placeholder = import_state11.StateField.define({ +var placeholder = import_state9.StateField.define({ create() { - return import_view7.Decoration.none; + return import_view6.Decoration.none; }, update(value, tr) { - let builder = new import_state11.RangeSetBuilder(); + let builder = new import_state9.RangeSetBuilder(); const currentLine = tr.state.doc.lineAt(tr.state.selection.main.head); if ((currentLine == null ? void 0 : currentLine.length) == 0) builder.add(currentLine.from, currentLine.from, placeholderLine); const dec = builder.finish(); return dec; }, - provide: (f4) => import_view7.EditorView.decorations.from(f4) + provide: (f4) => import_view6.EditorView.decorations.from(f4) }); // src/cm-extensions/cmExtensions.ts @@ -37880,16 +37697,6 @@ var cmExtensions = (plugin, mobile) => { if (!mobile && plugin.settings.inlineStyler) { extensions.push(cursorTooltip(plugin)); } - if (plugin.settings.markSans) { - if (!mobile) { - extensions.push( - hrResetFix, - makerSelect, - makerDelete, - hrField - ); - } - } if (plugin.settings.makeMenuPlaceholder) extensions.push(placeholder); if (plugin.settings.editorFlow) { @@ -38201,6 +38008,21 @@ var getCMFromElement = (el) => { }, app.workspace["rootSplit"]); return rcm; }; +var replaceAllTables = (plugin, el, ctx) => { + el.querySelectorAll("p").forEach((element) => { + for (let match2 of element.textContent.matchAll(/(?:!\[!\[|!!\[\[)([^\]]+)\]\]/g)) { + const link = match2[1]; + const reactEl = createRoot(element.parentElement); + reactEl.render( + /* @__PURE__ */ bn.createElement(FlowView, { + plugin, + path: link, + load: true + }) + ); + } + }); +}; var replaceAllEmbed = (el, ctx) => { let dom = el; setTimeout(async () => { @@ -39818,7 +39640,7 @@ var hamt_1 = createCommonjsModule(function(module2) { return fold(f4, z5, this); }; var forEach = hamt.forEach = function(f4, map) { - return fold(function(_4, value, key2) { + return fold(function(_5, value, key2) { return f4(value, key2, map); }, null, map); }; @@ -40573,12 +40395,12 @@ function sendEndOfBatchNotifications(store) { if (dirtyAtoms.size) { for (const [key2, subscriptions] of storeState.nodeTransactionSubscriptions) { if (dirtyAtoms.has(key2)) { - for (const [_4, subscription] of subscriptions) { + for (const [_5, subscription] of subscriptions) { subscription(store); } } } - for (const [_4, subscription] of storeState.transactionSubscriptions) { + for (const [_5, subscription] of storeState.transactionSubscriptions) { subscription(store); } if (!Recoil_gkx_1("recoil_early_rendering_2021") || storeState.suspendedComponentResolvers.size) { @@ -40621,7 +40443,7 @@ function Batcher({ setNotifyBatcherOfChange }) { const storeRef = useStoreRef(); - const [_4, setState] = useState([]); + const [_5, setState] = useState([]); setNotifyBatcherOfChange(() => setState({})); useEffect(() => { Recoil_Queue.enqueueExecution("Batcher", () => { @@ -41138,7 +40960,7 @@ function validateRecoilValue(recoilValue, hookName) { } function useRecoilInterface_DEPRECATED() { const storeRef = useStoreRef$1(); - const [_4, forceUpdate] = useState$1([]); + const [_5, forceUpdate] = useState$1([]); const recoilValuesUsed = useRef$2(/* @__PURE__ */ new Set()); recoilValuesUsed.current = /* @__PURE__ */ new Set(); const previousSubscriptions = useRef$2(/* @__PURE__ */ new Set()); @@ -41184,7 +41006,7 @@ function useRecoilInterface_DEPRECATED() { }); useEffect$1(() => { const subs = subscriptions.current; - return () => subs.forEach((_5, key2) => unsubscribeFrom(key2)); + return () => subs.forEach((_6, key2) => unsubscribeFrom(key2)); }, [unsubscribeFrom]); return useMemo$1(() => { function useSetRecoilState2(recoilState) { @@ -41290,7 +41112,7 @@ function useRecoilValueLoadable_LEGACY(recoilValue) { validateRecoilValue(recoilValue, "useRecoilValueLoadable"); } const storeRef = useStoreRef$1(); - const [_4, forceUpdate] = useState$1([]); + const [_5, forceUpdate] = useState$1([]); const componentName = Recoil_useComponentName(); useEffect$1(() => { const store = storeRef.current; @@ -43425,7 +43247,7 @@ var HiddenFiles = (props2) => { ]; plugin.saveSettings(); }; - const saveFile = (_4, value) => { + const saveFile = (_5, value) => { plugin.settings.hiddenFiles = [...plugin.settings.hiddenFiles, ...value]; plugin.saveSettings(); }; @@ -45049,6 +44871,15 @@ var FileExplorerComponent = (props2) => { return; } if (parentId != activeTreeItem.parentId) { + if (overIsSection) { + updateFileRank( + plugin, + activeTreeItem.item, + vaultItems, + -1 + ); + return; + } const newParent = parentItem ? parentItem.item.folder == "true" ? parentItem.item.path : parentItem.item.parent : "/"; const newPath = newParent == "/" ? activeItem.file.name : `${newParent}/${activeItem.file.name}`; if (plugin.app.vault.getAbstractFileByPath(newPath)) { @@ -45259,7 +45090,7 @@ var SpaceSwitcher = (props2) => { }; // src/components/Spaces/TagContextList/TagContextList.tsx -var import_lodash5 = __toESM(require_lodash()); +var import_lodash6 = __toESM(require_lodash()); var import_obsidian37 = require("obsidian"); var TagContextList = (props2) => { const [tags, setTags] = p2([]); @@ -45281,7 +45112,7 @@ var TagContextList = (props2) => { const f4 = (_a2 = folder == null ? void 0 : folder.children.filter( (f5) => f5 instanceof import_obsidian37.TFile && f5.extension == "mdb" && f5.name.charAt(0) == "#" ).map((f5) => fileNameToString(f5.name))) != null ? _a2 : []; - Promise.all(f4.map((t4) => contextShouldExist(props2.plugin, t4).then((g4) => g4 ? t4 : null))).then((f5) => setTags((0, import_lodash5.uniq)([...f5.filter((g4) => g4), ...Object.keys(app.metadataCache.getTags())]))); + Promise.all(f4.map((t4) => contextShouldExist(props2.plugin, t4).then((g4) => g4 ? t4 : null))).then((f5) => setTags((0, import_lodash6.uniq)([...f5.filter((g4) => g4), ...Object.keys(app.metadataCache.getTags())]))); }; h2(() => { refreshTags(); @@ -45665,13 +45496,6 @@ var MakeMDPluginSettingsTab = class extends import_obsidian39.PluginSettingTab { this.refreshView(); }) ); - new import_obsidian39.Setting(containerEl).setName(i18n_default.settings.editorMarkSans.name).setDesc(i18n_default.settings.editorMarkSans.desc).addToggle( - (toggle) => toggle.setValue(this.plugin.settings.markSans).onChange((value) => { - this.plugin.settings.markSans = value; - this.plugin.saveSettings(); - this.refreshView(); - }) - ); } }; @@ -45720,19 +45544,26 @@ var BlinkComponent = bn.forwardRef( const type = viewTypeByString(item); if (type == "file" || type == "folder") { openAFile(getAbstractFileAtPath(app, item), props2.plugin, false); + return; } if (type == "tag") { openTag(item, props2.plugin, false); + return; } + createNewMarkdownFile( + props2.plugin, + defaultNoteFolder(props2.plugin, null), + item + ); }; const optionProps = { multi: false, - editable: false, + editable: true, onHover: hoverItem, value: [], options: allItems, defaultOptions: defaultOptions3, - saveOptions: (_4, items) => selectItem(items[0]), + saveOptions: (_5, items) => selectItem(items[0]), placeholder: i18n_default.labels.blinkPlaceholder, searchable: true, showAll: true @@ -45858,13 +45689,14 @@ var MDBFileViewer = class extends import_obsidian41.FileView { var import_obsidian43 = require("obsidian"); // src/components/FileContextView/FileContextList.tsx -var import_lodash6 = __toESM(require_lodash()); +var import_lodash7 = __toESM(require_lodash()); var import_obsidian42 = require("obsidian"); var FileContextList = (props2) => { const { path } = props2; const { tableData, newColumn, + cols, tagContexts, contextTable, folderPath, @@ -45922,7 +45754,7 @@ var FileContextList = (props2) => { const fmFields = files.reduce((p3, c4) => { const fm = frontMatterForFile(c4); const fmKeys = uniqCaseInsensitive(frontMatterKeys(fm)); - return (0, import_lodash6.uniq)([...p3, ...fmKeys]); + return (0, import_lodash7.uniq)([...p3, ...fmKeys]); }, []).filter((f4) => !tableData.cols.some((g4) => g4.name == f4)); const allTypes = [ ...fmFields.map((f4) => ({ @@ -45936,18 +45768,18 @@ var FileContextList = (props2) => { value: "type." + f4.type })) ]; - const uniqueNameFromString2 = (name, cols) => { + const uniqueNameFromString2 = (name, cols2) => { let newName = name; - if (cols.includes(newName)) { + if (cols2.includes(newName)) { let append = 1; - while (cols.includes(newName)) { + while (cols2.includes(newName)) { newName = name + append.toString(); append += 1; } } return newName; }; - const saveOptions = (_4, values) => { + const saveOptions = (_5, values) => { const newValue = values[0]; const newType = newValue.split("."); if (newType[0] == "fm") { @@ -46019,7 +45851,7 @@ var FileContextList = (props2) => { field.name, field.table == "" ? tableData : contextTable[field.table] ); - showPropertyMenu(props2.plugin, { x: offset.left, y: offset.top + 30 }, true, options, field, (newField) => saveField(newField, field), (newField, val) => saveContext(newField, field, val), hideColumn, delColumn, sortColumn, predicate.colsHidden.includes(field.name + field.table)); + showPropertyMenu(props2.plugin, { x: offset.left, y: offset.top + 30 }, true, options, field, cols, contextTable, (newField) => saveField(newField, field), (newField, val) => saveContext(newField, field, val), hideColumn, delColumn, sortColumn, predicate.colsHidden.includes(field.name + field.table)); }; return /* @__PURE__ */ bn.createElement(bn.Fragment, null, fileContext.folder && fileContext.folder.data && /* @__PURE__ */ bn.createElement("div", { className: "mk-file-context-section" @@ -46066,7 +45898,17 @@ var import_obsidian44 = require("obsidian"); // src/components/FileContextView/Backlinks.tsx var BacklinkItem = (props2) => { const file = F(() => getAbstractFileAtPath(app, props2.path), [props2.path]); - const [collapsed, setCollapsed] = p2(true); + const [block, setBlock] = p2([null, null]); + h2(() => { + var _a2, _b2; + const fCache = app.metadataCache.getCache(props2.path); + const link = [...(_a2 = fCache.links) != null ? _a2 : [], ...(_b2 = fCache.embeds) != null ? _b2 : []].find((f4) => props2.source.includes(f4.displayText)); + if (link) { + const block2 = fCache.sections.find((f4) => f4.position.start.offset <= link.position.start.offset && f4.position.end.offset >= link.position.end.offset); + setBlock([Math.max(1, block2.position.start.line), Math.max(block2.position.start.line + 1, block2.position.end.line + 1)]); + } + }, [props2.path]); + const [collapsed, setCollapsed] = p2(false); return /* @__PURE__ */ bn.createElement("div", { className: "mk-file-context-section" }, /* @__PURE__ */ bn.createElement("div", { @@ -46080,11 +45922,15 @@ var BacklinkItem = (props2) => { dangerouslySetInnerHTML: { __html: uiIconSet["mk-ui-collapse"] } - }), file.name), !collapsed ? /* @__PURE__ */ bn.createElement(FlowView, { + }), file.name), !collapsed ? /* @__PURE__ */ bn.createElement("div", { + className: "mk-file-context-backlink" + }, /* @__PURE__ */ bn.createElement(FlowView, { plugin: props2.plugin, load: true, - path: props2.path - }) : /* @__PURE__ */ bn.createElement(bn.Fragment, null)); + path: props2.path, + from: block[0], + to: block[1] + })) : /* @__PURE__ */ bn.createElement(bn.Fragment, null)); }; var Backlinks = (props2) => { const [backlinks, setBacklinks] = p2([]); @@ -46099,7 +45945,8 @@ var Backlinks = (props2) => { }, [props2.path]); return /* @__PURE__ */ bn.createElement("div", null, backlinks.map((f4) => /* @__PURE__ */ bn.createElement(BacklinkItem, { path: f4, - plugin: props2.plugin + plugin: props2.plugin, + source: props2.path }))); }; @@ -46339,7 +46186,7 @@ var FileContextView = (props2) => { window.removeEventListener(eventTypes.tagsChange, refreshTags); }; }, [file]); - const saveTag = (_4, values) => { + const saveTag = (_5, values) => { }; const showContextMenu = (e4) => { const offset = e4.target.getBoundingClientRect(); @@ -46862,6 +46709,7 @@ var MakeMDPlugin = class extends import_obsidian46.Plugin { } }; removeAllFlowMarks(element); + replaceAllTables(this, element, context); replaceAllEmbed(element, context); }); window.addEventListener( @@ -46884,7 +46732,6 @@ var MakeMDPlugin = class extends import_obsidian46.Plugin { } loadMakerMode() { if (this.settings.makerMode) { - document.body.classList.toggle("mk-mark-sans", this.settings.markSans); this.addCommand({ id: "mk-toggle-bold", name: i18n_default.commandPalette.toggleBold, diff --git a/manifest.json b/manifest.json index 2488083..392b258 100755 --- a/manifest.json +++ b/manifest.json @@ -1,7 +1,7 @@ { "id": "make-md", "name": "MAKE.md", - "version": "0.6.11", + "version": "0.6.12", "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 6e15c78..59042b3 100644 --- a/styles.css +++ b/styles.css @@ -382,7 +382,7 @@ body { .mk-td-group { background-color: var(--background-primary); padding: 0.5rem; - border-top: 0.5px solid var(--divider-color); + border-top: 0.5px solid var(--divider-color) !important; font-size: var(--font-ui-small); font-weight: var(--bold-weight); } @@ -412,7 +412,7 @@ body { } .mk-table table { border-spacing: 0; - border-bottom: 0.5px solid var(--divider-color); + border-bottom: 0.5px solid var(--divider-color) !important; } .mk-table table th:last-child { width: 100%; @@ -434,11 +434,11 @@ body { padding-left: calc(var(--context-padding) - 0.75rem) !important; } .mk-table td { - border-top: 0.5px solid var(--background-modifier-border); + border-top: 0.5px solid var(--background-modifier-border) !important; font-size: var(--font-ui-small); } .mk-table .mk-td:not(:last-child) { - border-right: 0.5px solid var(--background-modifier-border); + border-right: 0.5px solid var(--background-modifier-border) !important; } .mk-cell-text { padding: 4px; @@ -570,11 +570,15 @@ body { } .mk-row-new { text-align: left; - border-top: 0.5px solid var(--divider-color); - padding: 8px var(--context-padding); - font-weight: normal; - color: var(--text-faint); - font-size: var(--font-ui-small); + border-top: 0.5px solid var(--divider-color) !important; + padding: 8px var(--context-padding) !important; + font-weight: normal !important; + color: var(--text-faint) !important; + font-size: var(--font-ui-small) !important; +} +.markdown-rendered .mk-table td, +.markdown-rendered .mk-table th { + border: unset; } .mk-row-new:hover { background: var(--background-modifier-hover); @@ -604,6 +608,7 @@ body { } .mk-cell-link-item { color: var(--link-color); + display: flex; } .mk-cell-option span { flex-grow: 1; @@ -1138,6 +1143,7 @@ body { } .mk-flow-hover { margin-top: -34px; + margin-left: -34px; } .mk-flow-hover > div { display: flex; @@ -2335,3 +2341,7 @@ body:not(.is-mobile) .mk-tree-wrapper:not(.mk-section-wrapper):not(.mk-disable-i .mk-file-context .mk-tag-selector { padding: 0 !important; } +.mk-file-context-backlink { + border: thin solid var(--divider-color); + padding: 0px 8px; +}