Files
thpeetz-notes/.obsidian/plugins/task-list-kanban/main.js
T
2026-09-01 11:05:57 +02:00

34082 lines
1.2 MiB
Plaintext

/*
THIS IS A GENERATED/BUNDLED FILE BY ESBUILD
if you want to view the source, please visit the github repository of this plugin
*/
"use strict";
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __typeError = (msg) => {
throw TypeError(msg);
};
var __defNormalProp = (obj, key2, value) => key2 in obj ? __defProp(obj, key2, { enumerable: true, configurable: true, writable: true, value }) : obj[key2] = value;
var __commonJS = (cb, mod) => function __require() {
try {
return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
} catch (e) {
throw mod = 0, e;
}
};
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key2 of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key2) && key2 !== except)
__defProp(to, key2, { get: () => from[key2], enumerable: !(desc = __getOwnPropDesc(from, key2)) || desc.enumerable });
}
return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
// If the importer is in node compatibility mode or this is not an ESM
// file that has been converted to a CommonJS file using a Babel-
// compatible transform (i.e. "__esModule" has not been set), then set
// "default" to the CommonJS "module.exports" for node compatibility.
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var __publicField = (obj, key2, value) => __defNormalProp(obj, typeof key2 !== "symbol" ? key2 + "" : key2, value);
var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg);
var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj));
var __privateAdd = (obj, member, value) => member.has(obj) ? __typeError("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
var __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), setter ? setter.call(obj, value) : member.set(obj, value), value);
var __privateMethod = (obj, member, method) => (__accessCheck(obj, member, "access private method"), method);
// node_modules/crypto-js/core.js
var require_core = __commonJS({
"node_modules/crypto-js/core.js"(exports, module2) {
(function(root24, factory) {
if (typeof exports === "object") {
module2.exports = exports = factory();
} else if (typeof define === "function" && define.amd) {
define([], factory);
} else {
root24.CryptoJS = factory();
}
})(exports, function() {
var CryptoJS = CryptoJS || (function(Math2, undefined2) {
var crypto2;
if (typeof window !== "undefined" && window.crypto) {
crypto2 = window.crypto;
}
if (typeof self !== "undefined" && self.crypto) {
crypto2 = self.crypto;
}
if (typeof globalThis !== "undefined" && globalThis.crypto) {
crypto2 = globalThis.crypto;
}
if (!crypto2 && typeof window !== "undefined" && window.msCrypto) {
crypto2 = window.msCrypto;
}
if (!crypto2 && typeof global !== "undefined" && global.crypto) {
crypto2 = global.crypto;
}
if (!crypto2 && typeof require === "function") {
try {
crypto2 = require("crypto");
} catch (err) {
}
}
var cryptoSecureRandomInt = function() {
if (crypto2) {
if (typeof crypto2.getRandomValues === "function") {
try {
return crypto2.getRandomValues(new Uint32Array(1))[0];
} catch (err) {
}
}
if (typeof crypto2.randomBytes === "function") {
try {
return crypto2.randomBytes(4).readInt32LE();
} catch (err) {
}
}
}
throw new Error("Native crypto module could not be used to get secure random number.");
};
var create = Object.create || /* @__PURE__ */ (function() {
function F() {
}
return function(obj) {
var subtype;
F.prototype = obj;
subtype = new F();
F.prototype = null;
return subtype;
};
})();
var C = {};
var C_lib = C.lib = {};
var Base2 = C_lib.Base = /* @__PURE__ */ (function() {
return {
/**
* Creates a new object that inherits from this object.
*
* @param {Object} overrides Properties to copy into the new object.
*
* @return {Object} The new object.
*
* @static
*
* @example
*
* var MyType = CryptoJS.lib.Base.extend({
* field: 'value',
*
* method: function () {
* }
* });
*/
extend: function(overrides) {
var subtype = create(this);
if (overrides) {
subtype.mixIn(overrides);
}
if (!subtype.hasOwnProperty("init") || this.init === subtype.init) {
subtype.init = function() {
subtype.$super.init.apply(this, arguments);
};
}
subtype.init.prototype = subtype;
subtype.$super = this;
return subtype;
},
/**
* Extends this object and runs the init method.
* Arguments to create() will be passed to init().
*
* @return {Object} The new object.
*
* @static
*
* @example
*
* var instance = MyType.create();
*/
create: function() {
var instance = this.extend();
instance.init.apply(instance, arguments);
return instance;
},
/**
* Initializes a newly created object.
* Override this method to add some logic when your objects are created.
*
* @example
*
* var MyType = CryptoJS.lib.Base.extend({
* init: function () {
* // ...
* }
* });
*/
init: function() {
},
/**
* Copies properties into this object.
*
* @param {Object} properties The properties to mix in.
*
* @example
*
* MyType.mixIn({
* field: 'value'
* });
*/
mixIn: function(properties) {
for (var propertyName in properties) {
if (properties.hasOwnProperty(propertyName)) {
this[propertyName] = properties[propertyName];
}
}
if (properties.hasOwnProperty("toString")) {
this.toString = properties.toString;
}
},
/**
* Creates a copy of this object.
*
* @return {Object} The clone.
*
* @example
*
* var clone = instance.clone();
*/
clone: function() {
return this.init.prototype.extend(this);
}
};
})();
var WordArray = C_lib.WordArray = Base2.extend({
/**
* Initializes a newly created word array.
*
* @param {Array} words (Optional) An array of 32-bit words.
* @param {number} sigBytes (Optional) The number of significant bytes in the words.
*
* @example
*
* var wordArray = CryptoJS.lib.WordArray.create();
* var wordArray = CryptoJS.lib.WordArray.create([0x00010203, 0x04050607]);
* var wordArray = CryptoJS.lib.WordArray.create([0x00010203, 0x04050607], 6);
*/
init: function(words, sigBytes) {
words = this.words = words || [];
if (sigBytes != undefined2) {
this.sigBytes = sigBytes;
} else {
this.sigBytes = words.length * 4;
}
},
/**
* Converts this word array to a string.
*
* @param {Encoder} encoder (Optional) The encoding strategy to use. Default: CryptoJS.enc.Hex
*
* @return {string} The stringified word array.
*
* @example
*
* var string = wordArray + '';
* var string = wordArray.toString();
* var string = wordArray.toString(CryptoJS.enc.Utf8);
*/
toString: function(encoder) {
return (encoder || Hex).stringify(this);
},
/**
* Concatenates a word array to this word array.
*
* @param {WordArray} wordArray The word array to append.
*
* @return {WordArray} This word array.
*
* @example
*
* wordArray1.concat(wordArray2);
*/
concat: function(wordArray) {
var thisWords = this.words;
var thatWords = wordArray.words;
var thisSigBytes = this.sigBytes;
var thatSigBytes = wordArray.sigBytes;
this.clamp();
if (thisSigBytes % 4) {
for (var i = 0; i < thatSigBytes; i++) {
var thatByte = thatWords[i >>> 2] >>> 24 - i % 4 * 8 & 255;
thisWords[thisSigBytes + i >>> 2] |= thatByte << 24 - (thisSigBytes + i) % 4 * 8;
}
} else {
for (var j = 0; j < thatSigBytes; j += 4) {
thisWords[thisSigBytes + j >>> 2] = thatWords[j >>> 2];
}
}
this.sigBytes += thatSigBytes;
return this;
},
/**
* Removes insignificant bits.
*
* @example
*
* wordArray.clamp();
*/
clamp: function() {
var words = this.words;
var sigBytes = this.sigBytes;
words[sigBytes >>> 2] &= 4294967295 << 32 - sigBytes % 4 * 8;
words.length = Math2.ceil(sigBytes / 4);
},
/**
* Creates a copy of this word array.
*
* @return {WordArray} The clone.
*
* @example
*
* var clone = wordArray.clone();
*/
clone: function() {
var clone = Base2.clone.call(this);
clone.words = this.words.slice(0);
return clone;
},
/**
* Creates a word array filled with random bytes.
*
* @param {number} nBytes The number of random bytes to generate.
*
* @return {WordArray} The random word array.
*
* @static
*
* @example
*
* var wordArray = CryptoJS.lib.WordArray.random(16);
*/
random: function(nBytes) {
var words = [];
for (var i = 0; i < nBytes; i += 4) {
words.push(cryptoSecureRandomInt());
}
return new WordArray.init(words, nBytes);
}
});
var C_enc = C.enc = {};
var Hex = C_enc.Hex = {
/**
* Converts a word array to a hex string.
*
* @param {WordArray} wordArray The word array.
*
* @return {string} The hex string.
*
* @static
*
* @example
*
* var hexString = CryptoJS.enc.Hex.stringify(wordArray);
*/
stringify: function(wordArray) {
var words = wordArray.words;
var sigBytes = wordArray.sigBytes;
var hexChars = [];
for (var i = 0; i < sigBytes; i++) {
var bite = words[i >>> 2] >>> 24 - i % 4 * 8 & 255;
hexChars.push((bite >>> 4).toString(16));
hexChars.push((bite & 15).toString(16));
}
return hexChars.join("");
},
/**
* Converts a hex string to a word array.
*
* @param {string} hexStr The hex string.
*
* @return {WordArray} The word array.
*
* @static
*
* @example
*
* var wordArray = CryptoJS.enc.Hex.parse(hexString);
*/
parse: function(hexStr) {
var hexStrLength = hexStr.length;
var words = [];
for (var i = 0; i < hexStrLength; i += 2) {
words[i >>> 3] |= parseInt(hexStr.substr(i, 2), 16) << 24 - i % 8 * 4;
}
return new WordArray.init(words, hexStrLength / 2);
}
};
var Latin1 = C_enc.Latin1 = {
/**
* Converts a word array to a Latin1 string.
*
* @param {WordArray} wordArray The word array.
*
* @return {string} The Latin1 string.
*
* @static
*
* @example
*
* var latin1String = CryptoJS.enc.Latin1.stringify(wordArray);
*/
stringify: function(wordArray) {
var words = wordArray.words;
var sigBytes = wordArray.sigBytes;
var latin1Chars = [];
for (var i = 0; i < sigBytes; i++) {
var bite = words[i >>> 2] >>> 24 - i % 4 * 8 & 255;
latin1Chars.push(String.fromCharCode(bite));
}
return latin1Chars.join("");
},
/**
* Converts a Latin1 string to a word array.
*
* @param {string} latin1Str The Latin1 string.
*
* @return {WordArray} The word array.
*
* @static
*
* @example
*
* var wordArray = CryptoJS.enc.Latin1.parse(latin1String);
*/
parse: function(latin1Str) {
var latin1StrLength = latin1Str.length;
var words = [];
for (var i = 0; i < latin1StrLength; i++) {
words[i >>> 2] |= (latin1Str.charCodeAt(i) & 255) << 24 - i % 4 * 8;
}
return new WordArray.init(words, latin1StrLength);
}
};
var Utf8 = C_enc.Utf8 = {
/**
* Converts a word array to a UTF-8 string.
*
* @param {WordArray} wordArray The word array.
*
* @return {string} The UTF-8 string.
*
* @static
*
* @example
*
* var utf8String = CryptoJS.enc.Utf8.stringify(wordArray);
*/
stringify: function(wordArray) {
try {
return decodeURIComponent(escape(Latin1.stringify(wordArray)));
} catch (e) {
throw new Error("Malformed UTF-8 data");
}
},
/**
* Converts a UTF-8 string to a word array.
*
* @param {string} utf8Str The UTF-8 string.
*
* @return {WordArray} The word array.
*
* @static
*
* @example
*
* var wordArray = CryptoJS.enc.Utf8.parse(utf8String);
*/
parse: function(utf8Str) {
return Latin1.parse(unescape(encodeURIComponent(utf8Str)));
}
};
var BufferedBlockAlgorithm = C_lib.BufferedBlockAlgorithm = Base2.extend({
/**
* Resets this block algorithm's data buffer to its initial state.
*
* @example
*
* bufferedBlockAlgorithm.reset();
*/
reset: function() {
this._data = new WordArray.init();
this._nDataBytes = 0;
},
/**
* Adds new data to this block algorithm's buffer.
*
* @param {WordArray|string} data The data to append. Strings are converted to a WordArray using UTF-8.
*
* @example
*
* bufferedBlockAlgorithm._append('data');
* bufferedBlockAlgorithm._append(wordArray);
*/
_append: function(data) {
if (typeof data == "string") {
data = Utf8.parse(data);
}
this._data.concat(data);
this._nDataBytes += data.sigBytes;
},
/**
* Processes available data blocks.
*
* This method invokes _doProcessBlock(offset), which must be implemented by a concrete subtype.
*
* @param {boolean} doFlush Whether all blocks and partial blocks should be processed.
*
* @return {WordArray} The processed data.
*
* @example
*
* var processedData = bufferedBlockAlgorithm._process();
* var processedData = bufferedBlockAlgorithm._process(!!'flush');
*/
_process: function(doFlush) {
var processedWords;
var data = this._data;
var dataWords = data.words;
var dataSigBytes = data.sigBytes;
var blockSize = this.blockSize;
var blockSizeBytes = blockSize * 4;
var nBlocksReady = dataSigBytes / blockSizeBytes;
if (doFlush) {
nBlocksReady = Math2.ceil(nBlocksReady);
} else {
nBlocksReady = Math2.max((nBlocksReady | 0) - this._minBufferSize, 0);
}
var nWordsReady = nBlocksReady * blockSize;
var nBytesReady = Math2.min(nWordsReady * 4, dataSigBytes);
if (nWordsReady) {
for (var offset = 0; offset < nWordsReady; offset += blockSize) {
this._doProcessBlock(dataWords, offset);
}
processedWords = dataWords.splice(0, nWordsReady);
data.sigBytes -= nBytesReady;
}
return new WordArray.init(processedWords, nBytesReady);
},
/**
* Creates a copy of this object.
*
* @return {Object} The clone.
*
* @example
*
* var clone = bufferedBlockAlgorithm.clone();
*/
clone: function() {
var clone = Base2.clone.call(this);
clone._data = this._data.clone();
return clone;
},
_minBufferSize: 0
});
var Hasher = C_lib.Hasher = BufferedBlockAlgorithm.extend({
/**
* Configuration options.
*/
cfg: Base2.extend(),
/**
* Initializes a newly created hasher.
*
* @param {Object} cfg (Optional) The configuration options to use for this hash computation.
*
* @example
*
* var hasher = CryptoJS.algo.SHA256.create();
*/
init: function(cfg) {
this.cfg = this.cfg.extend(cfg);
this.reset();
},
/**
* Resets this hasher to its initial state.
*
* @example
*
* hasher.reset();
*/
reset: function() {
BufferedBlockAlgorithm.reset.call(this);
this._doReset();
},
/**
* Updates this hasher with a message.
*
* @param {WordArray|string} messageUpdate The message to append.
*
* @return {Hasher} This hasher.
*
* @example
*
* hasher.update('message');
* hasher.update(wordArray);
*/
update: function(messageUpdate) {
this._append(messageUpdate);
this._process();
return this;
},
/**
* Finalizes the hash computation.
* Note that the finalize operation is effectively a destructive, read-once operation.
*
* @param {WordArray|string} messageUpdate (Optional) A final message update.
*
* @return {WordArray} The hash.
*
* @example
*
* var hash = hasher.finalize();
* var hash = hasher.finalize('message');
* var hash = hasher.finalize(wordArray);
*/
finalize: function(messageUpdate) {
if (messageUpdate) {
this._append(messageUpdate);
}
var hash2 = this._doFinalize();
return hash2;
},
blockSize: 512 / 32,
/**
* Creates a shortcut function to a hasher's object interface.
*
* @param {Hasher} hasher The hasher to create a helper for.
*
* @return {Function} The shortcut function.
*
* @static
*
* @example
*
* var SHA256 = CryptoJS.lib.Hasher._createHelper(CryptoJS.algo.SHA256);
*/
_createHelper: function(hasher) {
return function(message, cfg) {
return new hasher.init(cfg).finalize(message);
};
},
/**
* Creates a shortcut function to the HMAC's object interface.
*
* @param {Hasher} hasher The hasher to use in this HMAC helper.
*
* @return {Function} The shortcut function.
*
* @static
*
* @example
*
* var HmacSHA256 = CryptoJS.lib.Hasher._createHmacHelper(CryptoJS.algo.SHA256);
*/
_createHmacHelper: function(hasher) {
return function(message, key2) {
return new C_algo.HMAC.init(hasher, key2).finalize(message);
};
}
});
var C_algo = C.algo = {};
return C;
})(Math);
return CryptoJS;
});
}
});
// node_modules/crypto-js/sha256.js
var require_sha256 = __commonJS({
"node_modules/crypto-js/sha256.js"(exports, module2) {
(function(root24, factory) {
if (typeof exports === "object") {
module2.exports = exports = factory(require_core());
} else if (typeof define === "function" && define.amd) {
define(["./core"], factory);
} else {
factory(root24.CryptoJS);
}
})(exports, function(CryptoJS) {
(function(Math2) {
var C = CryptoJS;
var C_lib = C.lib;
var WordArray = C_lib.WordArray;
var Hasher = C_lib.Hasher;
var C_algo = C.algo;
var H = [];
var K = [];
(function() {
function isPrime(n2) {
var sqrtN = Math2.sqrt(n2);
for (var factor = 2; factor <= sqrtN; factor++) {
if (!(n2 % factor)) {
return false;
}
}
return true;
}
function getFractionalBits(n2) {
return (n2 - (n2 | 0)) * 4294967296 | 0;
}
var n = 2;
var nPrime = 0;
while (nPrime < 64) {
if (isPrime(n)) {
if (nPrime < 8) {
H[nPrime] = getFractionalBits(Math2.pow(n, 1 / 2));
}
K[nPrime] = getFractionalBits(Math2.pow(n, 1 / 3));
nPrime++;
}
n++;
}
})();
var W = [];
var SHA256 = C_algo.SHA256 = Hasher.extend({
_doReset: function() {
this._hash = new WordArray.init(H.slice(0));
},
_doProcessBlock: function(M, offset) {
var H2 = this._hash.words;
var a = H2[0];
var b = H2[1];
var c = H2[2];
var d = H2[3];
var e = H2[4];
var f = H2[5];
var g = H2[6];
var h = H2[7];
for (var i = 0; i < 64; i++) {
if (i < 16) {
W[i] = M[offset + i] | 0;
} else {
var gamma0x = W[i - 15];
var gamma0 = (gamma0x << 25 | gamma0x >>> 7) ^ (gamma0x << 14 | gamma0x >>> 18) ^ gamma0x >>> 3;
var gamma1x = W[i - 2];
var gamma1 = (gamma1x << 15 | gamma1x >>> 17) ^ (gamma1x << 13 | gamma1x >>> 19) ^ gamma1x >>> 10;
W[i] = gamma0 + W[i - 7] + gamma1 + W[i - 16];
}
var ch = e & f ^ ~e & g;
var maj = a & b ^ a & c ^ b & c;
var sigma0 = (a << 30 | a >>> 2) ^ (a << 19 | a >>> 13) ^ (a << 10 | a >>> 22);
var sigma1 = (e << 26 | e >>> 6) ^ (e << 21 | e >>> 11) ^ (e << 7 | e >>> 25);
var t1 = h + sigma1 + ch + K[i] + W[i];
var t2 = sigma0 + maj;
h = g;
g = f;
f = e;
e = d + t1 | 0;
d = c;
c = b;
b = a;
a = t1 + t2 | 0;
}
H2[0] = H2[0] + a | 0;
H2[1] = H2[1] + b | 0;
H2[2] = H2[2] + c | 0;
H2[3] = H2[3] + d | 0;
H2[4] = H2[4] + e | 0;
H2[5] = H2[5] + f | 0;
H2[6] = H2[6] + g | 0;
H2[7] = H2[7] + h | 0;
},
_doFinalize: function() {
var data = this._data;
var dataWords = data.words;
var nBitsTotal = this._nDataBytes * 8;
var nBitsLeft = data.sigBytes * 8;
dataWords[nBitsLeft >>> 5] |= 128 << 24 - nBitsLeft % 32;
dataWords[(nBitsLeft + 64 >>> 9 << 4) + 14] = Math2.floor(nBitsTotal / 4294967296);
dataWords[(nBitsLeft + 64 >>> 9 << 4) + 15] = nBitsTotal;
data.sigBytes = dataWords.length * 4;
this._process();
return this._hash;
},
clone: function() {
var clone = Hasher.clone.call(this);
clone._hash = this._hash.clone();
return clone;
}
});
C.SHA256 = Hasher._createHelper(SHA256);
C.HmacSHA256 = Hasher._createHmacHelper(SHA256);
})(Math);
return CryptoJS.SHA256;
});
}
});
// src/entry.ts
var entry_exports = {};
__export(entry_exports, {
default: () => Base
});
module.exports = __toCommonJS(entry_exports);
var import_obsidian22 = require("obsidian");
// node_modules/esm-env/true.js
var true_default = true;
// node_modules/esm-env/dev-fallback.js
var _a, _b;
var node_env = (_b = (_a = globalThis.process) == null ? void 0 : _a.env) == null ? void 0 : _b.NODE_ENV;
var dev_fallback_default = node_env && !node_env.toLowerCase().startsWith("prod");
// node_modules/svelte/src/internal/shared/utils.js
var is_array = Array.isArray;
var index_of = Array.prototype.indexOf;
var includes = Array.prototype.includes;
var array_from = Array.from;
var object_keys = Object.keys;
var define_property = Object.defineProperty;
var get_descriptor = Object.getOwnPropertyDescriptor;
var get_descriptors = Object.getOwnPropertyDescriptors;
var object_prototype = Object.prototype;
var array_prototype = Array.prototype;
var get_prototype_of = Object.getPrototypeOf;
var is_extensible = Object.isExtensible;
function is_function(thing) {
return typeof thing === "function";
}
var noop = () => {
};
function run(fn) {
return fn();
}
function run_all(arr) {
for (var i = 0; i < arr.length; i++) {
arr[i]();
}
}
function deferred() {
var resolve;
var reject;
var promise = new Promise((res, rej) => {
resolve = res;
reject = rej;
});
return { promise, resolve, reject };
}
function fallback(value, fallback2, lazy = false) {
return value === void 0 ? lazy ? (
/** @type {() => V} */
fallback2()
) : (
/** @type {V} */
fallback2
) : value;
}
// node_modules/svelte/src/internal/client/constants.js
var DERIVED = 1 << 1;
var EFFECT = 1 << 2;
var RENDER_EFFECT = 1 << 3;
var MANAGED_EFFECT = 1 << 24;
var BLOCK_EFFECT = 1 << 4;
var BRANCH_EFFECT = 1 << 5;
var ROOT_EFFECT = 1 << 6;
var BOUNDARY_EFFECT = 1 << 7;
var CONNECTED = 1 << 9;
var CLEAN = 1 << 10;
var DIRTY = 1 << 11;
var MAYBE_DIRTY = 1 << 12;
var INERT = 1 << 13;
var DESTROYED = 1 << 14;
var REACTION_RAN = 1 << 15;
var DESTROYING = 1 << 25;
var EFFECT_TRANSPARENT = 1 << 16;
var EAGER_EFFECT = 1 << 17;
var HEAD_EFFECT = 1 << 18;
var EFFECT_PRESERVED = 1 << 19;
var USER_EFFECT = 1 << 20;
var EFFECT_OFFSCREEN = 1 << 25;
var WAS_MARKED = 1 << 16;
var REACTION_IS_UPDATING = 1 << 21;
var ASYNC = 1 << 22;
var ERROR_VALUE = 1 << 23;
var STATE_SYMBOL = /* @__PURE__ */ Symbol("$state");
var LEGACY_PROPS = /* @__PURE__ */ Symbol("legacy props");
var LOADING_ATTR_SYMBOL = /* @__PURE__ */ Symbol("");
var PROXY_PATH_SYMBOL = /* @__PURE__ */ Symbol("proxy path");
var ATTRIBUTES_CACHE = /* @__PURE__ */ Symbol("attributes");
var CLASS_CACHE = /* @__PURE__ */ Symbol("class");
var STYLE_CACHE = /* @__PURE__ */ Symbol("style");
var TEXT_CACHE = /* @__PURE__ */ Symbol("text");
var FORM_RESET_HANDLER = /* @__PURE__ */ Symbol("form reset");
var HMR_ANCHOR = /* @__PURE__ */ Symbol("hmr anchor");
var STALE_REACTION = new class StaleReactionError extends Error {
constructor() {
super(...arguments);
__publicField(this, "name", "StaleReactionError");
__publicField(this, "message", "The reaction that called `getAbortSignal()` was re-run or destroyed");
}
}();
var _a2;
var IS_XHTML = (
// We gotta write it like this because after downleveling the pure comment may end up in the wrong location
!!((_a2 = globalThis.document) == null ? void 0 : _a2.contentType) && /* @__PURE__ */ globalThis.document.contentType.includes("xml")
);
var TEXT_NODE = 3;
var COMMENT_NODE = 8;
// node_modules/svelte/src/internal/client/reactivity/equality.js
function equals(value) {
return value === this.v;
}
function safe_not_equal(a, b) {
return a != a ? b == b : a !== b || a !== null && typeof a === "object" || typeof a === "function";
}
function safe_equals(value) {
return !safe_not_equal(value, this.v);
}
// node_modules/svelte/src/internal/shared/errors.js
function invariant_violation(message) {
if (dev_fallback_default) {
const error = new Error(`invariant_violation
An invariant violation occurred, meaning Svelte's internal assumptions were flawed. This is a bug in Svelte, not your app \u2014 please open an issue at https://github.com/sveltejs/svelte, citing the following message: "${message}"
https://svelte.dev/e/invariant_violation`);
error.name = "Svelte error";
throw error;
} else {
throw new Error(`https://svelte.dev/e/invariant_violation`);
}
}
function lifecycle_outside_component(name) {
if (dev_fallback_default) {
const error = new Error(`lifecycle_outside_component
\`${name}(...)\` can only be used during component initialisation
https://svelte.dev/e/lifecycle_outside_component`);
error.name = "Svelte error";
throw error;
} else {
throw new Error(`https://svelte.dev/e/lifecycle_outside_component`);
}
}
// node_modules/svelte/src/internal/client/errors.js
function async_derived_orphan() {
if (dev_fallback_default) {
const error = new Error(`async_derived_orphan
Cannot create a \`$derived(...)\` with an \`await\` expression outside of an effect tree
https://svelte.dev/e/async_derived_orphan`);
error.name = "Svelte error";
throw error;
} else {
throw new Error(`https://svelte.dev/e/async_derived_orphan`);
}
}
function bind_invalid_checkbox_value() {
if (dev_fallback_default) {
const error = new Error(`bind_invalid_checkbox_value
Using \`bind:value\` together with a checkbox input is not allowed. Use \`bind:checked\` instead
https://svelte.dev/e/bind_invalid_checkbox_value`);
error.name = "Svelte error";
throw error;
} else {
throw new Error(`https://svelte.dev/e/bind_invalid_checkbox_value`);
}
}
function derived_references_self() {
if (dev_fallback_default) {
const error = new Error(`derived_references_self
A derived value cannot reference itself recursively
https://svelte.dev/e/derived_references_self`);
error.name = "Svelte error";
throw error;
} else {
throw new Error(`https://svelte.dev/e/derived_references_self`);
}
}
function each_key_duplicate(a, b, value) {
if (dev_fallback_default) {
const error = new Error(`each_key_duplicate
${value ? `Keyed each block has duplicate key \`${value}\` at indexes ${a} and ${b}` : `Keyed each block has duplicate key at indexes ${a} and ${b}`}
https://svelte.dev/e/each_key_duplicate`);
error.name = "Svelte error";
throw error;
} else {
throw new Error(`https://svelte.dev/e/each_key_duplicate`);
}
}
function each_key_volatile(index2, a, b) {
if (dev_fallback_default) {
const error = new Error(`each_key_volatile
Keyed each block has key that is not idempotent \u2014 the key for item at index ${index2} was \`${a}\` but is now \`${b}\`. Keys must be the same each time for a given item
https://svelte.dev/e/each_key_volatile`);
error.name = "Svelte error";
throw error;
} else {
throw new Error(`https://svelte.dev/e/each_key_volatile`);
}
}
function effect_in_teardown(rune) {
if (dev_fallback_default) {
const error = new Error(`effect_in_teardown
\`${rune}\` cannot be used inside an effect cleanup function
https://svelte.dev/e/effect_in_teardown`);
error.name = "Svelte error";
throw error;
} else {
throw new Error(`https://svelte.dev/e/effect_in_teardown`);
}
}
function effect_in_unowned_derived() {
if (dev_fallback_default) {
const error = new Error(`effect_in_unowned_derived
Effect cannot be created inside a \`$derived\` value that was not itself created inside an effect
https://svelte.dev/e/effect_in_unowned_derived`);
error.name = "Svelte error";
throw error;
} else {
throw new Error(`https://svelte.dev/e/effect_in_unowned_derived`);
}
}
function effect_orphan(rune) {
if (dev_fallback_default) {
const error = new Error(`effect_orphan
\`${rune}\` can only be used inside an effect (e.g. during component initialisation)
https://svelte.dev/e/effect_orphan`);
error.name = "Svelte error";
throw error;
} else {
throw new Error(`https://svelte.dev/e/effect_orphan`);
}
}
function effect_update_depth_exceeded() {
if (dev_fallback_default) {
const error = new Error(`effect_update_depth_exceeded
Maximum update depth exceeded. This typically indicates that an effect reads and writes the same piece of state
https://svelte.dev/e/effect_update_depth_exceeded`);
error.name = "Svelte error";
throw error;
} else {
throw new Error(`https://svelte.dev/e/effect_update_depth_exceeded`);
}
}
function hydration_failed() {
if (dev_fallback_default) {
const error = new Error(`hydration_failed
Failed to hydrate the application
https://svelte.dev/e/hydration_failed`);
error.name = "Svelte error";
throw error;
} else {
throw new Error(`https://svelte.dev/e/hydration_failed`);
}
}
function props_invalid_value(key2) {
if (dev_fallback_default) {
const error = new Error(`props_invalid_value
Cannot do \`bind:${key2}={undefined}\` when \`${key2}\` has a fallback value
https://svelte.dev/e/props_invalid_value`);
error.name = "Svelte error";
throw error;
} else {
throw new Error(`https://svelte.dev/e/props_invalid_value`);
}
}
function rune_outside_svelte(rune) {
if (dev_fallback_default) {
const error = new Error(`rune_outside_svelte
The \`${rune}\` rune is only available inside \`.svelte\` and \`.svelte.js/ts\` files
https://svelte.dev/e/rune_outside_svelte`);
error.name = "Svelte error";
throw error;
} else {
throw new Error(`https://svelte.dev/e/rune_outside_svelte`);
}
}
function state_descriptors_fixed() {
if (dev_fallback_default) {
const error = new Error(`state_descriptors_fixed
Property descriptors defined on \`$state\` objects must contain \`value\` and always be \`enumerable\`, \`configurable\` and \`writable\`.
https://svelte.dev/e/state_descriptors_fixed`);
error.name = "Svelte error";
throw error;
} else {
throw new Error(`https://svelte.dev/e/state_descriptors_fixed`);
}
}
function state_prototype_fixed() {
if (dev_fallback_default) {
const error = new Error(`state_prototype_fixed
Cannot set prototype of \`$state\` object
https://svelte.dev/e/state_prototype_fixed`);
error.name = "Svelte error";
throw error;
} else {
throw new Error(`https://svelte.dev/e/state_prototype_fixed`);
}
}
function state_unsafe_mutation() {
if (dev_fallback_default) {
const error = new Error(`state_unsafe_mutation
Updating state inside \`$derived(...)\`, \`$inspect(...)\` or a template expression is forbidden. If the value should not be reactive, declare it without \`$state\`
https://svelte.dev/e/state_unsafe_mutation`);
error.name = "Svelte error";
throw error;
} else {
throw new Error(`https://svelte.dev/e/state_unsafe_mutation`);
}
}
function svelte_boundary_reset_onerror() {
if (dev_fallback_default) {
const error = new Error(`svelte_boundary_reset_onerror
A \`<svelte:boundary>\` \`reset\` function cannot be called while an error is still being handled
https://svelte.dev/e/svelte_boundary_reset_onerror`);
error.name = "Svelte error";
throw error;
} else {
throw new Error(`https://svelte.dev/e/svelte_boundary_reset_onerror`);
}
}
// node_modules/svelte/src/internal/flags/index.js
var async_mode_flag = false;
var legacy_mode_flag = false;
var tracing_mode_flag = false;
function enable_legacy_mode_flag() {
legacy_mode_flag = true;
}
// node_modules/svelte/src/constants.js
var EACH_ITEM_REACTIVE = 1;
var EACH_INDEX_REACTIVE = 1 << 1;
var EACH_IS_CONTROLLED = 1 << 2;
var EACH_IS_ANIMATED = 1 << 3;
var EACH_ITEM_IMMUTABLE = 1 << 4;
var PROPS_IS_IMMUTABLE = 1;
var PROPS_IS_RUNES = 1 << 1;
var PROPS_IS_UPDATED = 1 << 2;
var PROPS_IS_BINDABLE = 1 << 3;
var PROPS_IS_LAZY_INITIAL = 1 << 4;
var TRANSITION_IN = 1;
var TRANSITION_OUT = 1 << 1;
var TRANSITION_GLOBAL = 1 << 2;
var TEMPLATE_FRAGMENT = 1;
var TEMPLATE_USE_IMPORT_NODE = 1 << 1;
var TEMPLATE_USE_SVG = 1 << 2;
var TEMPLATE_USE_MATHML = 1 << 3;
var HYDRATION_START = "[";
var HYDRATION_START_ELSE = "[!";
var HYDRATION_START_FAILED = "[?";
var HYDRATION_END = "]";
var HYDRATION_ERROR = {};
var ELEMENT_PRESERVE_ATTRIBUTE_CASE = 1 << 1;
var ELEMENT_IS_INPUT = 1 << 2;
var UNINITIALIZED = /* @__PURE__ */ Symbol("uninitialized");
var FILENAME = /* @__PURE__ */ Symbol("filename");
var NAMESPACE_HTML = "http://www.w3.org/1999/xhtml";
var ATTACHMENT_KEY = "@attach";
// node_modules/svelte/src/internal/client/dev/tracing.js
var tracing_expressions = null;
function tag(source2, label) {
source2.label = label;
tag_proxy(source2.v, label);
return source2;
}
function tag_proxy(value, label) {
var _a5;
(_a5 = value == null ? void 0 : value[PROXY_PATH_SYMBOL]) == null ? void 0 : _a5.call(value, label);
return value;
}
// node_modules/svelte/src/internal/shared/dev.js
function get_error(label) {
const error = new Error();
const stack2 = get_stack();
if (stack2.length === 0) {
return null;
}
stack2.unshift("\n");
define_property(error, "stack", {
value: stack2.join("\n")
});
define_property(error, "name", {
value: label
});
return (
/** @type {Error & { stack: string }} */
error
);
}
function get_stack() {
const limit = Error.stackTraceLimit;
Error.stackTraceLimit = Infinity;
const stack2 = new Error().stack;
Error.stackTraceLimit = limit;
if (!stack2) return [];
const lines = stack2.split("\n");
const new_lines = [];
for (let i = 0; i < lines.length; i++) {
const line = lines[i];
const posixified = line.replaceAll("\\", "/");
if (line.trim() === "Error") {
continue;
}
if (line.includes("validate_each_keys")) {
return [];
}
if (posixified.includes("svelte/src/internal") || posixified.includes("node_modules/.vite")) {
continue;
}
new_lines.push(line);
}
return new_lines;
}
function invariant(condition, message) {
if (!dev_fallback_default) {
throw new Error("invariant(...) was not guarded by if (DEV)");
}
if (!condition) invariant_violation(message);
}
// node_modules/svelte/src/internal/client/context.js
var component_context = null;
function set_component_context(context) {
component_context = context;
}
var dev_stack = null;
function set_dev_stack(stack2) {
dev_stack = stack2;
}
var dev_current_component_function = null;
function set_dev_current_component_function(fn) {
dev_current_component_function = fn;
}
function push(props, runes = false, fn) {
component_context = {
p: component_context,
i: false,
c: null,
e: null,
s: props,
x: null,
r: (
/** @type {Effect} */
active_effect
),
l: legacy_mode_flag && !runes ? { s: null, u: null, $: [] } : null
};
if (dev_fallback_default) {
component_context.function = fn;
dev_current_component_function = fn;
}
}
function pop(component2) {
var _a5;
var context = (
/** @type {ComponentContext} */
component_context
);
var effects = context.e;
if (effects !== null) {
context.e = null;
for (var fn of effects) {
create_user_effect(fn);
}
}
if (component2 !== void 0) {
context.x = component2;
}
context.i = true;
component_context = context.p;
if (dev_fallback_default) {
dev_current_component_function = (_a5 = component_context == null ? void 0 : component_context.function) != null ? _a5 : null;
}
return component2 != null ? component2 : (
/** @type {T} */
{}
);
}
function is_runes() {
return !legacy_mode_flag || component_context !== null && component_context.l === null;
}
// node_modules/svelte/src/internal/client/dom/task.js
var micro_tasks = [];
function run_micro_tasks() {
var tasks = micro_tasks;
micro_tasks = [];
run_all(tasks);
}
function queue_micro_task(fn) {
if (micro_tasks.length === 0 && !is_flushing_sync) {
var tasks = micro_tasks;
queueMicrotask(() => {
if (tasks === micro_tasks) run_micro_tasks();
});
}
micro_tasks.push(fn);
}
function flush_tasks() {
while (micro_tasks.length > 0) {
run_micro_tasks();
}
}
// node_modules/svelte/src/internal/client/warnings.js
var bold = "font-weight: bold";
var normal = "font-weight: normal";
function await_reactivity_loss(name) {
if (dev_fallback_default) {
console.warn(`%c[svelte] await_reactivity_loss
%cDetected reactivity loss when reading \`${name}\`. This happens when state is read in an async function after an earlier \`await\`
https://svelte.dev/e/await_reactivity_loss`, bold, normal);
} else {
console.warn(`https://svelte.dev/e/await_reactivity_loss`);
}
}
function await_waterfall(name, location) {
if (dev_fallback_default) {
console.warn(`%c[svelte] await_waterfall
%cAn async derived, \`${name}\` (${location}) was not read immediately after it resolved. This often indicates an unnecessary waterfall, which can slow down your app
https://svelte.dev/e/await_waterfall`, bold, normal);
} else {
console.warn(`https://svelte.dev/e/await_waterfall`);
}
}
function derived_inert() {
if (dev_fallback_default) {
console.warn(`%c[svelte] derived_inert
%cReading a derived belonging to a now-destroyed effect may result in stale values
https://svelte.dev/e/derived_inert`, bold, normal);
} else {
console.warn(`https://svelte.dev/e/derived_inert`);
}
}
function hydration_attribute_changed(attribute, html2, value) {
if (dev_fallback_default) {
console.warn(`%c[svelte] hydration_attribute_changed
%cThe \`${attribute}\` attribute on \`${html2}\` changed its value between server and client renders. The client value, \`${value}\`, will be ignored in favour of the server value
https://svelte.dev/e/hydration_attribute_changed`, bold, normal);
} else {
console.warn(`https://svelte.dev/e/hydration_attribute_changed`);
}
}
function hydration_mismatch(location) {
if (dev_fallback_default) {
console.warn(
`%c[svelte] hydration_mismatch
%c${location ? `Hydration failed because the initial UI does not match what was rendered on the server. The error occurred near ${location}` : "Hydration failed because the initial UI does not match what was rendered on the server"}
https://svelte.dev/e/hydration_mismatch`,
bold,
normal
);
} else {
console.warn(`https://svelte.dev/e/hydration_mismatch`);
}
}
function lifecycle_double_unmount() {
if (dev_fallback_default) {
console.warn(`%c[svelte] lifecycle_double_unmount
%cTried to unmount a component that was not mounted
https://svelte.dev/e/lifecycle_double_unmount`, bold, normal);
} else {
console.warn(`https://svelte.dev/e/lifecycle_double_unmount`);
}
}
function select_multiple_invalid_value() {
if (dev_fallback_default) {
console.warn(`%c[svelte] select_multiple_invalid_value
%cThe \`value\` property of a \`<select multiple>\` element should be an array, but it received a non-array value. The selection will be kept as is.
https://svelte.dev/e/select_multiple_invalid_value`, bold, normal);
} else {
console.warn(`https://svelte.dev/e/select_multiple_invalid_value`);
}
}
function state_proxy_equality_mismatch(operator) {
if (dev_fallback_default) {
console.warn(`%c[svelte] state_proxy_equality_mismatch
%cReactive \`$state(...)\` proxies and the values they proxy have different identities. Because of this, comparisons with \`${operator}\` will produce unexpected results
https://svelte.dev/e/state_proxy_equality_mismatch`, bold, normal);
} else {
console.warn(`https://svelte.dev/e/state_proxy_equality_mismatch`);
}
}
function state_proxy_unmount() {
if (dev_fallback_default) {
console.warn(`%c[svelte] state_proxy_unmount
%cTried to unmount a state proxy, rather than a component
https://svelte.dev/e/state_proxy_unmount`, bold, normal);
} else {
console.warn(`https://svelte.dev/e/state_proxy_unmount`);
}
}
function svelte_boundary_reset_noop() {
if (dev_fallback_default) {
console.warn(`%c[svelte] svelte_boundary_reset_noop
%cA \`<svelte:boundary>\` \`reset\` function only resets the boundary the first time it is called
https://svelte.dev/e/svelte_boundary_reset_noop`, bold, normal);
} else {
console.warn(`https://svelte.dev/e/svelte_boundary_reset_noop`);
}
}
// node_modules/svelte/src/internal/client/dom/hydration.js
var hydrating = false;
function set_hydrating(value) {
hydrating = value;
}
var hydrate_node;
function set_hydrate_node(node) {
if (node === null) {
hydration_mismatch();
throw HYDRATION_ERROR;
}
return hydrate_node = node;
}
function hydrate_next() {
return set_hydrate_node(get_next_sibling(hydrate_node));
}
function reset(node) {
if (!hydrating) return;
if (get_next_sibling(hydrate_node) !== null) {
hydration_mismatch();
throw HYDRATION_ERROR;
}
hydrate_node = node;
}
function next(count = 1) {
if (hydrating) {
var i = count;
var node = hydrate_node;
while (i--) {
node = /** @type {TemplateNode} */
get_next_sibling(node);
}
hydrate_node = node;
}
}
function skip_nodes(remove = true) {
var depth = 0;
var node = hydrate_node;
while (true) {
if (node.nodeType === COMMENT_NODE) {
var data = (
/** @type {Comment} */
node.data
);
if (data === HYDRATION_END) {
if (depth === 0) return node;
depth -= 1;
} else if (data === HYDRATION_START || data === HYDRATION_START_ELSE || // "[1", "[2", etc. for if blocks
data[0] === "[" && !isNaN(Number(data.slice(1)))) {
depth += 1;
}
}
var next2 = (
/** @type {TemplateNode} */
get_next_sibling(node)
);
if (remove) node.remove();
node = next2;
}
}
function read_hydration_instruction(node) {
if (!node || node.nodeType !== COMMENT_NODE) {
hydration_mismatch();
throw HYDRATION_ERROR;
}
return (
/** @type {Comment} */
node.data
);
}
// node_modules/svelte/src/internal/client/proxy.js
var regex_is_valid_identifier = /^[a-zA-Z_$][a-zA-Z_$0-9]*$/;
function proxy(value) {
if (typeof value !== "object" || value === null || STATE_SYMBOL in value) {
return value;
}
const prototype = get_prototype_of(value);
if (prototype !== object_prototype && prototype !== array_prototype) {
return value;
}
var sources = /* @__PURE__ */ new Map();
var is_proxied_array = is_array(value);
var version = state(0);
var stack2 = dev_fallback_default && tracing_mode_flag ? get_error("created at") : null;
var parent_version = update_version;
var with_parent = (fn) => {
if (update_version === parent_version) {
return fn();
}
var reaction = active_reaction;
var version2 = update_version;
set_active_reaction(null);
set_update_version(parent_version);
var result = fn();
set_active_reaction(reaction);
set_update_version(version2);
return result;
};
if (is_proxied_array) {
sources.set("length", state(
/** @type {any[]} */
value.length,
stack2
));
if (dev_fallback_default) {
value = /** @type {any} */
inspectable_array(
/** @type {any[]} */
value
);
}
}
var path = "";
let updating = false;
function update_path(new_path) {
if (updating) return;
updating = true;
path = new_path;
tag(version, `${path} version`);
for (const [prop2, source2] of sources) {
tag(source2, get_label(path, prop2));
}
updating = false;
}
return new Proxy(
/** @type {any} */
value,
{
defineProperty(_, prop2, descriptor) {
if (!("value" in descriptor) || descriptor.configurable === false || descriptor.enumerable === false || descriptor.writable === false) {
state_descriptors_fixed();
}
var s = sources.get(prop2);
if (s === void 0) {
with_parent(() => {
var s2 = state(descriptor.value, stack2);
sources.set(prop2, s2);
if (dev_fallback_default && typeof prop2 === "string") {
tag(s2, get_label(path, prop2));
}
return s2;
});
} else {
set(s, descriptor.value, true);
}
return true;
},
deleteProperty(target, prop2) {
var s = sources.get(prop2);
if (s === void 0) {
if (prop2 in target) {
const s2 = with_parent(() => state(UNINITIALIZED, stack2));
sources.set(prop2, s2);
increment(version);
if (dev_fallback_default) {
tag(s2, get_label(path, prop2));
}
}
} else {
set(s, UNINITIALIZED);
increment(version);
}
return true;
},
get(target, prop2, receiver) {
var _a5;
if (prop2 === STATE_SYMBOL) {
return value;
}
if (dev_fallback_default && prop2 === PROXY_PATH_SYMBOL) {
return update_path;
}
var s = sources.get(prop2);
var exists = prop2 in target;
if (s === void 0 && (!exists || ((_a5 = get_descriptor(target, prop2)) == null ? void 0 : _a5.writable))) {
s = with_parent(() => {
var p = proxy(exists ? target[prop2] : UNINITIALIZED);
var s2 = state(p, stack2);
if (dev_fallback_default) {
tag(s2, get_label(path, prop2));
}
return s2;
});
sources.set(prop2, s);
}
if (s !== void 0) {
var v = get(s);
return v === UNINITIALIZED ? void 0 : v;
}
return Reflect.get(target, prop2, receiver);
},
getOwnPropertyDescriptor(target, prop2) {
var descriptor = Reflect.getOwnPropertyDescriptor(target, prop2);
if (descriptor && "value" in descriptor) {
var s = sources.get(prop2);
if (s) descriptor.value = get(s);
} else if (descriptor === void 0) {
var source2 = sources.get(prop2);
var value2 = source2 == null ? void 0 : source2.v;
if (source2 !== void 0 && value2 !== UNINITIALIZED) {
return {
enumerable: true,
configurable: true,
value: value2,
writable: true
};
}
}
return descriptor;
},
has(target, prop2) {
var _a5;
if (prop2 === STATE_SYMBOL) {
return true;
}
var s = sources.get(prop2);
var has = s !== void 0 && s.v !== UNINITIALIZED || Reflect.has(target, prop2);
if (s !== void 0 || active_effect !== null && (!has || ((_a5 = get_descriptor(target, prop2)) == null ? void 0 : _a5.writable))) {
if (s === void 0) {
s = with_parent(() => {
var p = has ? proxy(target[prop2]) : UNINITIALIZED;
var s2 = state(p, stack2);
if (dev_fallback_default) {
tag(s2, get_label(path, prop2));
}
return s2;
});
sources.set(prop2, s);
}
var value2 = get(s);
if (value2 === UNINITIALIZED) {
return false;
}
}
return has;
},
set(target, prop2, value2, receiver) {
var _a5;
var s = sources.get(prop2);
var has = prop2 in target;
if (is_proxied_array && prop2 === "length") {
for (var i = value2; i < /** @type {Source<number>} */
s.v; i += 1) {
var other_s = sources.get(i + "");
if (other_s !== void 0) {
set(other_s, UNINITIALIZED);
} else if (i in target) {
other_s = with_parent(() => state(UNINITIALIZED, stack2));
sources.set(i + "", other_s);
if (dev_fallback_default) {
tag(other_s, get_label(path, i));
}
}
}
}
if (s === void 0) {
if (!has || ((_a5 = get_descriptor(target, prop2)) == null ? void 0 : _a5.writable)) {
s = with_parent(() => state(void 0, stack2));
if (dev_fallback_default) {
tag(s, get_label(path, prop2));
}
set(s, proxy(value2));
sources.set(prop2, s);
}
} else {
has = s.v !== UNINITIALIZED;
var p = with_parent(() => proxy(value2));
set(s, p);
}
var descriptor = Reflect.getOwnPropertyDescriptor(target, prop2);
if (descriptor == null ? void 0 : descriptor.set) {
descriptor.set.call(receiver, value2);
}
if (!has) {
if (is_proxied_array && typeof prop2 === "string") {
var ls = (
/** @type {Source<number>} */
sources.get("length")
);
var n = Number(prop2);
if (Number.isInteger(n) && n >= ls.v) {
set(ls, n + 1);
}
}
increment(version);
}
return true;
},
ownKeys(target) {
get(version);
var own_keys = Reflect.ownKeys(target).filter((key3) => {
var source3 = sources.get(key3);
return source3 === void 0 || source3.v !== UNINITIALIZED;
});
for (var [key2, source2] of sources) {
if (source2.v !== UNINITIALIZED && !(key2 in target)) {
own_keys.push(key2);
}
}
return own_keys;
},
setPrototypeOf() {
state_prototype_fixed();
}
}
);
}
function get_label(path, prop2) {
var _a5;
if (typeof prop2 === "symbol") return `${path}[Symbol(${(_a5 = prop2.description) != null ? _a5 : ""})]`;
if (regex_is_valid_identifier.test(prop2)) return `${path}.${prop2}`;
return /^\d+$/.test(prop2) ? `${path}[${prop2}]` : `${path}['${prop2}']`;
}
function get_proxied_value(value) {
try {
if (value !== null && typeof value === "object" && STATE_SYMBOL in value) {
return value[STATE_SYMBOL];
}
} catch (e) {
}
return value;
}
function is(a, b) {
return Object.is(get_proxied_value(a), get_proxied_value(b));
}
var ARRAY_MUTATING_METHODS = /* @__PURE__ */ new Set([
"copyWithin",
"fill",
"pop",
"push",
"reverse",
"shift",
"sort",
"splice",
"unshift"
]);
function inspectable_array(array) {
return new Proxy(array, {
get(target, prop2, receiver) {
var value = Reflect.get(target, prop2, receiver);
if (!ARRAY_MUTATING_METHODS.has(
/** @type {string} */
prop2
)) {
return value;
}
return function(...args) {
set_eager_effects_deferred();
var result = value.apply(this, args);
flush_eager_effects();
return result;
};
}
});
}
// node_modules/svelte/src/internal/client/dev/equality.js
function init_array_prototype_warnings() {
const array_prototype2 = Array.prototype;
const cleanup = Array.__svelte_cleanup;
if (cleanup) {
cleanup();
}
const { indexOf, lastIndexOf, includes: includes2 } = array_prototype2;
array_prototype2.indexOf = function(item, from_index) {
const index2 = indexOf.call(this, item, from_index);
if (index2 === -1) {
for (let i = from_index != null ? from_index : 0; i < this.length; i += 1) {
if (get_proxied_value(this[i]) === item) {
state_proxy_equality_mismatch("array.indexOf(...)");
break;
}
}
}
return index2;
};
array_prototype2.lastIndexOf = function(item, from_index) {
const index2 = lastIndexOf.call(this, item, from_index != null ? from_index : this.length - 1);
if (index2 === -1) {
for (let i = 0; i <= (from_index != null ? from_index : this.length - 1); i += 1) {
if (get_proxied_value(this[i]) === item) {
state_proxy_equality_mismatch("array.lastIndexOf(...)");
break;
}
}
}
return index2;
};
array_prototype2.includes = function(item, from_index) {
const has = includes2.call(this, item, from_index);
if (!has) {
for (let i = 0; i < this.length; i += 1) {
if (get_proxied_value(this[i]) === item) {
state_proxy_equality_mismatch("array.includes(...)");
break;
}
}
}
return has;
};
Array.__svelte_cleanup = () => {
array_prototype2.indexOf = indexOf;
array_prototype2.lastIndexOf = lastIndexOf;
array_prototype2.includes = includes2;
};
}
// node_modules/svelte/src/internal/client/dom/operations.js
var $window;
var $document;
var is_firefox;
var first_child_getter;
var next_sibling_getter;
function init_operations() {
if ($window !== void 0) {
return;
}
$window = window;
$document = document;
is_firefox = /Firefox/.test(navigator.userAgent);
var element_prototype = Element.prototype;
var node_prototype = Node.prototype;
var text_prototype = Text.prototype;
first_child_getter = get_descriptor(node_prototype, "firstChild").get;
next_sibling_getter = get_descriptor(node_prototype, "nextSibling").get;
if (is_extensible(element_prototype)) {
element_prototype[CLASS_CACHE] = void 0;
element_prototype[ATTRIBUTES_CACHE] = null;
element_prototype[STYLE_CACHE] = void 0;
element_prototype.__e = void 0;
}
if (is_extensible(text_prototype)) {
text_prototype[TEXT_CACHE] = void 0;
}
if (dev_fallback_default) {
element_prototype.__svelte_meta = null;
init_array_prototype_warnings();
}
}
function create_text(value = "") {
return document.createTextNode(value);
}
// @__NO_SIDE_EFFECTS__
function get_first_child(node) {
return (
/** @type {TemplateNode | null} */
first_child_getter.call(node)
);
}
// @__NO_SIDE_EFFECTS__
function get_next_sibling(node) {
return (
/** @type {TemplateNode | null} */
next_sibling_getter.call(node)
);
}
function child(node, is_text) {
if (!hydrating) {
return /* @__PURE__ */ get_first_child(node);
}
var child2 = /* @__PURE__ */ get_first_child(hydrate_node);
if (child2 === null) {
child2 = hydrate_node.appendChild(create_text());
} else if (is_text && child2.nodeType !== TEXT_NODE) {
var text2 = create_text();
child2 == null ? void 0 : child2.before(text2);
set_hydrate_node(text2);
return text2;
}
if (is_text) {
merge_text_nodes(
/** @type {Text} */
child2
);
}
set_hydrate_node(child2);
return child2;
}
function first_child(node, is_text = false) {
var _a5, _b3;
if (!hydrating) {
var first = /* @__PURE__ */ get_first_child(node);
if (first instanceof Comment && first.data === "") return /* @__PURE__ */ get_next_sibling(first);
return first;
}
if (is_text) {
if (((_a5 = hydrate_node) == null ? void 0 : _a5.nodeType) !== TEXT_NODE) {
var text2 = create_text();
(_b3 = hydrate_node) == null ? void 0 : _b3.before(text2);
set_hydrate_node(text2);
return text2;
}
merge_text_nodes(
/** @type {Text} */
hydrate_node
);
}
return hydrate_node;
}
function sibling(node, count = 1, is_text = false) {
let next_sibling = hydrating ? hydrate_node : node;
var last_sibling;
while (count--) {
last_sibling = next_sibling;
next_sibling = /** @type {TemplateNode} */
/* @__PURE__ */ get_next_sibling(next_sibling);
}
if (!hydrating) {
return next_sibling;
}
if (is_text) {
if ((next_sibling == null ? void 0 : next_sibling.nodeType) !== TEXT_NODE) {
var text2 = create_text();
if (next_sibling === null) {
last_sibling == null ? void 0 : last_sibling.after(text2);
} else {
next_sibling.before(text2);
}
set_hydrate_node(text2);
return text2;
}
merge_text_nodes(
/** @type {Text} */
next_sibling
);
}
set_hydrate_node(next_sibling);
return next_sibling;
}
function clear_text_content(node) {
node.textContent = "";
}
function should_defer_append() {
if (!async_mode_flag) return false;
if (eager_block_effects !== null) return false;
var flags2 = (
/** @type {Effect} */
active_effect.f
);
return (flags2 & REACTION_RAN) !== 0;
}
function create_element(tag2, namespace, is2) {
if (namespace == null || namespace === NAMESPACE_HTML) {
return (
/** @type {T extends keyof HTMLElementTagNameMap ? HTMLElementTagNameMap[T] : Element} */
is2 ? document.createElement(tag2, { is: is2 }) : document.createElement(tag2)
);
}
return (
/** @type {T extends keyof HTMLElementTagNameMap ? HTMLElementTagNameMap[T] : Element} */
is2 ? document.createElementNS(namespace, tag2, { is: is2 }) : document.createElementNS(namespace, tag2)
);
}
function merge_text_nodes(text2) {
if (
/** @type {string} */
text2.nodeValue.length < 65536
) {
return;
}
let next2 = text2.nextSibling;
while (next2 !== null && next2.nodeType === TEXT_NODE) {
next2.remove();
text2.nodeValue += /** @type {string} */
next2.nodeValue;
next2 = text2.nextSibling;
}
}
// node_modules/svelte/src/internal/client/error-handling.js
var adjustments = /* @__PURE__ */ new WeakMap();
function handle_error(error) {
var effect2 = active_effect;
if (effect2 === null) {
active_reaction.f |= ERROR_VALUE;
return error;
}
if (dev_fallback_default && error instanceof Error && !adjustments.has(error)) {
adjustments.set(error, get_adjustments(error, effect2));
}
if ((effect2.f & REACTION_RAN) === 0 && (effect2.f & EFFECT) === 0) {
if (dev_fallback_default && !effect2.parent && error instanceof Error) {
apply_adjustments(error);
}
throw error;
}
invoke_error_boundary(error, effect2);
}
function invoke_error_boundary(error, effect2) {
while (effect2 !== null) {
if ((effect2.f & BOUNDARY_EFFECT) !== 0) {
if ((effect2.f & REACTION_RAN) === 0) {
throw error;
}
try {
effect2.b.error(error);
return;
} catch (e) {
error = e;
}
}
effect2 = effect2.parent;
}
if (dev_fallback_default && error instanceof Error) {
apply_adjustments(error);
}
throw error;
}
function get_adjustments(error, effect2) {
var _a5, _b3, _c2;
const message_descriptor = get_descriptor(error, "message");
if (message_descriptor && !message_descriptor.configurable) return;
var indent = is_firefox ? " " : " ";
var component_stack = `
${indent}in ${((_a5 = effect2.fn) == null ? void 0 : _a5.name) || "<unknown>"}`;
var context = effect2.ctx;
while (context !== null) {
component_stack += `
${indent}in ${(_b3 = context.function) == null ? void 0 : _b3[FILENAME].split("/").pop()}`;
context = context.p;
}
return {
message: error.message + `
${component_stack}
`,
stack: (_c2 = error.stack) == null ? void 0 : _c2.split("\n").filter((line) => !line.includes("svelte/src/internal")).join("\n")
};
}
function apply_adjustments(error) {
const adjusted = adjustments.get(error);
if (adjusted) {
define_property(error, "message", {
value: adjusted.message
});
define_property(error, "stack", {
value: adjusted.stack
});
}
}
// node_modules/svelte/src/internal/client/reactivity/status.js
var STATUS_MASK = ~(DIRTY | MAYBE_DIRTY | CLEAN);
function set_signal_status(signal, status) {
signal.f = signal.f & STATUS_MASK | status;
}
function update_derived_status(derived3) {
if ((derived3.f & CONNECTED) !== 0 || derived3.deps === null) {
set_signal_status(derived3, CLEAN);
} else {
set_signal_status(derived3, MAYBE_DIRTY);
}
}
// node_modules/svelte/src/internal/client/reactivity/utils.js
function clear_marked(deps) {
if (deps === null) return;
for (const dep of deps) {
if ((dep.f & DERIVED) === 0 || (dep.f & WAS_MARKED) === 0) {
continue;
}
dep.f ^= WAS_MARKED;
clear_marked(
/** @type {Derived} */
dep.deps
);
}
}
function defer_effect(effect2, dirty_effects, maybe_dirty_effects) {
if ((effect2.f & DIRTY) !== 0) {
dirty_effects.add(effect2);
} else if ((effect2.f & MAYBE_DIRTY) !== 0) {
maybe_dirty_effects.add(effect2);
}
clear_marked(effect2.deps);
set_signal_status(effect2, CLEAN);
}
// node_modules/svelte/src/store/utils.js
function subscribe_to_store(store, run3, invalidate) {
if (store == null) {
run3(void 0);
if (invalidate) invalidate(void 0);
return noop;
}
const unsub = untrack(
() => store.subscribe(
run3,
// @ts-expect-error
invalidate
)
);
return unsub.unsubscribe ? () => unsub.unsubscribe() : unsub;
}
// node_modules/svelte/src/store/shared/index.js
var subscriber_queue = [];
function readable(value, start) {
return {
subscribe: writable(value, start).subscribe
};
}
function writable(value, start = noop) {
let stop = null;
const subscribers = /* @__PURE__ */ new Set();
function set3(new_value) {
if (safe_not_equal(value, new_value)) {
value = new_value;
if (stop) {
const run_queue = !subscriber_queue.length;
for (const subscriber of subscribers) {
subscriber[1]();
subscriber_queue.push(subscriber, value);
}
if (run_queue) {
for (let i = 0; i < subscriber_queue.length; i += 2) {
subscriber_queue[i][0](subscriber_queue[i + 1]);
}
subscriber_queue.length = 0;
}
}
}
}
function update2(fn) {
set3(fn(
/** @type {T} */
value
));
}
function subscribe(run3, invalidate = noop) {
const subscriber = [run3, invalidate];
subscribers.add(subscriber);
if (subscribers.size === 1) {
stop = start(set3, update2) || noop;
}
run3(
/** @type {T} */
value
);
return () => {
subscribers.delete(subscriber);
if (subscribers.size === 0 && stop) {
stop();
stop = null;
}
};
}
return { set: set3, update: update2, subscribe };
}
function derived(stores, fn, initial_value) {
const single = !Array.isArray(stores);
const stores_array = single ? [stores] : stores;
if (!stores_array.every(Boolean)) {
throw new Error("derived() expects stores as input, got a falsy value");
}
const auto = fn.length < 2;
return readable(initial_value, (set3, update2) => {
let started = false;
const values = [];
let pending2 = 0;
let cleanup = noop;
const sync = () => {
if (pending2) {
return;
}
cleanup();
const result = fn(single ? values[0] : values, set3, update2);
if (auto) {
set3(result);
} else {
cleanup = typeof result === "function" ? result : noop;
}
};
const unsubscribers = stores_array.map(
(store, i) => subscribe_to_store(
store,
(value) => {
values[i] = value;
pending2 &= ~(1 << i);
if (started) {
sync();
}
},
() => {
pending2 |= 1 << i;
}
)
);
started = true;
sync();
return function stop() {
run_all(unsubscribers);
cleanup();
started = false;
};
});
}
function get2(store) {
let value;
subscribe_to_store(store, (_) => value = _)();
return value;
}
// node_modules/svelte/src/internal/client/reactivity/store.js
var legacy_is_updating_store = false;
var is_store_binding = false;
var IS_UNMOUNTED = /* @__PURE__ */ Symbol("unmounted");
function store_get(store, store_name, stores) {
var _a5;
const entry = (_a5 = stores[store_name]) != null ? _a5 : stores[store_name] = {
store: null,
source: mutable_source(void 0),
unsubscribe: noop
};
if (dev_fallback_default) {
entry.source.label = store_name;
}
if (entry.store !== store && !(IS_UNMOUNTED in stores)) {
entry.unsubscribe();
entry.store = store != null ? store : null;
if (store == null) {
entry.source.v = void 0;
entry.unsubscribe = noop;
} else {
var is_synchronous_callback = true;
entry.unsubscribe = subscribe_to_store(store, (v) => {
if (is_synchronous_callback) {
entry.source.v = v;
} else {
set(entry.source, v);
}
});
is_synchronous_callback = false;
}
}
if (store && IS_UNMOUNTED in stores) {
return get2(store);
}
return get(entry.source);
}
function setup_stores() {
const stores = {};
function cleanup() {
teardown(() => {
for (var store_name in stores) {
const ref = stores[store_name];
ref.unsubscribe();
}
define_property(stores, IS_UNMOUNTED, {
enumerable: false,
value: true
});
});
}
return [stores, cleanup];
}
function update_with_flag(store, value) {
legacy_is_updating_store = true;
try {
store.set(value);
} finally {
legacy_is_updating_store = false;
}
}
function store_mutate(store, expression, new_value) {
update_with_flag(store, new_value);
return expression;
}
function capture_store_binding(fn) {
var previous_is_store_binding = is_store_binding;
try {
is_store_binding = false;
return [fn(), is_store_binding];
} finally {
is_store_binding = previous_is_store_binding;
}
}
// node_modules/svelte/src/internal/client/reactivity/batch.js
var first_batch = null;
var last_batch = null;
var current_batch = null;
var previous_batch = null;
var batch_values = null;
var last_scheduled_effect = null;
var is_flushing_sync = false;
var is_processing = false;
var collected_effects = null;
var legacy_updates = null;
var flush_count = 0;
var source_stacks = /* @__PURE__ */ new Set();
var uid = 1;
var _started, _prev, _next, _commit_callbacks, _discard_callbacks, _pending, _blocking_pending, _deferred, _roots, _new_effects, _dirty_effects, _maybe_dirty_effects, _skipped_branches, _unskipped_branches, _decrement_queued, _Batch_instances, is_deferred_fn, process_fn, traverse_fn, find_earlier_batch_fn, merge_fn, defer_effects_fn, commit_fn, unlink_fn;
var _Batch = class _Batch {
constructor() {
__privateAdd(this, _Batch_instances);
__publicField(this, "id", uid++);
/** True as soon as `#process` was called */
__privateAdd(this, _started, false);
__publicField(this, "linked", true);
/** @type {Batch | null} */
__privateAdd(this, _prev, null);
/** @type {Batch | null} */
__privateAdd(this, _next, null);
/** @type {Map<Effect, ReturnType<typeof deferred<any>>>} */
__publicField(this, "async_deriveds", /* @__PURE__ */ new Map());
/**
* The current values of any signals that are updated in this batch.
* Tuple format: [value, is_derived] (note: is_derived is false for deriveds, too, if they were overridden via assignment)
* They keys of this map are identical to `this.#previous`
* @type {Map<Value, [any, boolean]>}
*/
__publicField(this, "current", /* @__PURE__ */ new Map());
/**
* The values of any signals (sources and deriveds) that are updated in this batch _before_ those updates took place.
* They keys of this map are identical to `this.#current`
* @type {Map<Value, any>}
*/
__publicField(this, "previous", /* @__PURE__ */ new Map());
/**
* When the batch is committed (and the DOM is updated), we need to remove old branches
* and append new ones by calling the functions added inside (if/each/key/etc) blocks
* @type {Set<(batch: Batch) => void>}
*/
__privateAdd(this, _commit_callbacks, /* @__PURE__ */ new Set());
/**
* If a fork is discarded, we need to destroy any effects that are no longer needed
* @type {Set<(batch: Batch) => void>}
*/
__privateAdd(this, _discard_callbacks, /* @__PURE__ */ new Set());
/**
* The number of async effects that are currently in flight
*/
__privateAdd(this, _pending, 0);
/**
* Async effects that are currently in flight, _not_ inside a pending boundary
* @type {Map<Effect, number>}
*/
__privateAdd(this, _blocking_pending, /* @__PURE__ */ new Map());
/**
* A deferred that resolves when the batch is committed, used with `settled()`
* TODO replace with Promise.withResolvers once supported widely enough
* @type {{ promise: Promise<void>, resolve: (value?: any) => void, reject: (reason: unknown) => void } | null}
*/
__privateAdd(this, _deferred, null);
/**
* The root effects that need to be flushed
* @type {Effect[]}
*/
__privateAdd(this, _roots, []);
/**
* Effects created while this batch was active.
* @type {Effect[]}
*/
__privateAdd(this, _new_effects, []);
/**
* Deferred effects (which run after async work has completed) that are DIRTY
* @type {Set<Effect>}
*/
__privateAdd(this, _dirty_effects, /* @__PURE__ */ new Set());
/**
* Deferred effects that are MAYBE_DIRTY
* @type {Set<Effect>}
*/
__privateAdd(this, _maybe_dirty_effects, /* @__PURE__ */ new Set());
/**
* A map of branches that still exist, but will be destroyed when this batch
* is committed — we skip over these during `process`.
* The value contains child effects that were dirty/maybe_dirty before being reset,
* so they can be rescheduled if the branch survives.
* @type {Map<Effect, { d: Effect[], m: Effect[] }>}
*/
__privateAdd(this, _skipped_branches, /* @__PURE__ */ new Map());
/**
* Inverse of #skipped_branches which we need to tell prior batches to unskip them when committing
* @type {Set<Effect>}
*/
__privateAdd(this, _unskipped_branches, /* @__PURE__ */ new Set());
__publicField(this, "is_fork", false);
__privateAdd(this, _decrement_queued, false);
if (last_batch === null) {
first_batch = last_batch = this;
} else {
__privateSet(last_batch, _next, this);
__privateSet(this, _prev, last_batch);
}
last_batch = this;
}
/**
* Add an effect to the #skipped_branches map and reset its children
* @param {Effect} effect
*/
skip_effect(effect2) {
if (!__privateGet(this, _skipped_branches).has(effect2)) {
__privateGet(this, _skipped_branches).set(effect2, { d: [], m: [] });
}
__privateGet(this, _unskipped_branches).delete(effect2);
}
/**
* Remove an effect from the #skipped_branches map and reschedule
* any tracked dirty/maybe_dirty child effects
* @param {Effect} effect
* @param {(e: Effect) => void} callback
*/
unskip_effect(effect2, callback = (e) => this.schedule(e)) {
var tracked = __privateGet(this, _skipped_branches).get(effect2);
if (tracked) {
__privateGet(this, _skipped_branches).delete(effect2);
for (var e of tracked.d) {
set_signal_status(e, DIRTY);
callback(e);
}
for (e of tracked.m) {
set_signal_status(e, MAYBE_DIRTY);
callback(e);
}
}
__privateGet(this, _unskipped_branches).add(effect2);
}
/**
* Associate a change to a given source with the current
* batch, noting its previous and current values
* @param {Value} source
* @param {any} value
* @param {boolean} [is_derived]
*/
capture(source2, value, is_derived = false) {
if (source2.v !== UNINITIALIZED && !this.previous.has(source2)) {
this.previous.set(source2, source2.v);
}
if ((source2.f & ERROR_VALUE) === 0) {
this.current.set(source2, [value, is_derived]);
batch_values == null ? void 0 : batch_values.set(source2, value);
}
if (!this.is_fork) {
source2.v = value;
}
}
activate() {
current_batch = this;
}
deactivate() {
current_batch = null;
batch_values = null;
}
flush() {
try {
if (dev_fallback_default) {
source_stacks.clear();
}
is_processing = true;
current_batch = this;
__privateMethod(this, _Batch_instances, process_fn).call(this);
} finally {
flush_count = 0;
last_scheduled_effect = null;
collected_effects = null;
legacy_updates = null;
is_processing = false;
current_batch = null;
batch_values = null;
old_values.clear();
if (dev_fallback_default) {
for (const source2 of source_stacks) {
source2.updated = null;
}
}
}
}
discard() {
var _a5;
for (const fn of __privateGet(this, _discard_callbacks)) fn(this);
__privateGet(this, _discard_callbacks).clear();
__privateMethod(this, _Batch_instances, unlink_fn).call(this);
(_a5 = __privateGet(this, _deferred)) == null ? void 0 : _a5.resolve();
}
/**
* @param {Effect} effect
*/
register_created_effect(effect2) {
__privateGet(this, _new_effects).push(effect2);
}
/**
* @param {boolean} blocking
* @param {Effect} effect
*/
increment(blocking, effect2) {
var _a5;
__privateSet(this, _pending, __privateGet(this, _pending) + 1);
if (blocking) {
let blocking_pending_count = (_a5 = __privateGet(this, _blocking_pending).get(effect2)) != null ? _a5 : 0;
__privateGet(this, _blocking_pending).set(effect2, blocking_pending_count + 1);
}
}
/**
* @param {boolean} blocking
* @param {Effect} effect
*/
decrement(blocking, effect2) {
var _a5;
__privateSet(this, _pending, __privateGet(this, _pending) - 1);
if (blocking) {
let blocking_pending_count = (_a5 = __privateGet(this, _blocking_pending).get(effect2)) != null ? _a5 : 0;
if (blocking_pending_count === 1) {
__privateGet(this, _blocking_pending).delete(effect2);
} else {
__privateGet(this, _blocking_pending).set(effect2, blocking_pending_count - 1);
}
}
if (__privateGet(this, _decrement_queued)) return;
__privateSet(this, _decrement_queued, true);
queue_micro_task(() => {
__privateSet(this, _decrement_queued, false);
if (this.linked) {
this.flush();
}
});
}
/**
* @param {Set<Effect>} dirty_effects
* @param {Set<Effect>} maybe_dirty_effects
*/
transfer_effects(dirty_effects, maybe_dirty_effects) {
for (const e of dirty_effects) {
__privateGet(this, _dirty_effects).add(e);
}
for (const e of maybe_dirty_effects) {
__privateGet(this, _maybe_dirty_effects).add(e);
}
dirty_effects.clear();
maybe_dirty_effects.clear();
}
/** @param {(batch: Batch) => void} fn */
oncommit(fn) {
__privateGet(this, _commit_callbacks).add(fn);
}
/** @param {(batch: Batch) => void} fn */
ondiscard(fn) {
__privateGet(this, _discard_callbacks).add(fn);
}
settled() {
var _a5;
return ((_a5 = __privateGet(this, _deferred)) != null ? _a5 : __privateSet(this, _deferred, deferred())).promise;
}
static ensure() {
if (current_batch === null) {
const batch = current_batch = new _Batch();
if (!is_processing && !is_flushing_sync) {
queue_micro_task(() => {
if (!__privateGet(batch, _started)) {
batch.flush();
}
});
}
}
return current_batch;
}
apply() {
if (!async_mode_flag || !this.is_fork && __privateGet(this, _prev) === null && __privateGet(this, _next) === null) {
batch_values = null;
return;
}
batch_values = /* @__PURE__ */ new Map();
for (const [source2, [value]] of this.current) {
batch_values.set(source2, value);
}
for (let batch = first_batch; batch !== null; batch = __privateGet(batch, _next)) {
if (batch === this || batch.is_fork) continue;
var intersects = false;
if (batch.id < this.id) {
for (const [source2, [, is_derived]] of batch.current) {
if (is_derived) continue;
if (this.current.has(source2)) {
intersects = true;
break;
}
}
}
if (!intersects) {
for (const [source2, previous] of batch.previous) {
if (!batch_values.has(source2)) {
batch_values.set(source2, previous);
}
}
}
}
}
/**
*
* @param {Effect} effect
*/
schedule(effect2) {
var _a5;
last_scheduled_effect = effect2;
if (((_a5 = effect2.b) == null ? void 0 : _a5.is_pending) && (effect2.f & (EFFECT | RENDER_EFFECT | MANAGED_EFFECT)) !== 0 && (effect2.f & REACTION_RAN) === 0) {
effect2.b.defer_effect(effect2);
return;
}
var e = effect2;
while (e.parent !== null) {
e = e.parent;
var flags2 = e.f;
if (collected_effects !== null && e === active_effect) {
if (async_mode_flag) return;
if ((active_reaction === null || (active_reaction.f & DERIVED) === 0) && !legacy_is_updating_store) {
return;
}
}
if ((flags2 & (ROOT_EFFECT | BRANCH_EFFECT)) !== 0) {
if ((flags2 & CLEAN) === 0) {
return;
}
e.f ^= CLEAN;
}
}
__privateGet(this, _roots).push(e);
}
};
_started = new WeakMap();
_prev = new WeakMap();
_next = new WeakMap();
_commit_callbacks = new WeakMap();
_discard_callbacks = new WeakMap();
_pending = new WeakMap();
_blocking_pending = new WeakMap();
_deferred = new WeakMap();
_roots = new WeakMap();
_new_effects = new WeakMap();
_dirty_effects = new WeakMap();
_maybe_dirty_effects = new WeakMap();
_skipped_branches = new WeakMap();
_unskipped_branches = new WeakMap();
_decrement_queued = new WeakMap();
_Batch_instances = new WeakSet();
is_deferred_fn = function() {
if (this.is_fork) return true;
for (const effect2 of __privateGet(this, _blocking_pending).keys()) {
var e = effect2;
var skipped = false;
while (e.parent !== null) {
if (__privateGet(this, _skipped_branches).has(e)) {
skipped = true;
break;
}
e = e.parent;
}
if (!skipped) {
return true;
}
}
return false;
};
process_fn = function() {
var _a5, _b3, _c2, _d;
__privateSet(this, _started, true);
if (flush_count++ > 1e3) {
__privateMethod(this, _Batch_instances, unlink_fn).call(this);
infinite_loop_guard();
}
if (dev_fallback_default) {
for (const value of this.current.keys()) {
source_stacks.add(value);
}
}
for (const e of __privateGet(this, _dirty_effects)) {
__privateGet(this, _maybe_dirty_effects).delete(e);
set_signal_status(e, DIRTY);
this.schedule(e);
}
for (const e of __privateGet(this, _maybe_dirty_effects)) {
set_signal_status(e, MAYBE_DIRTY);
this.schedule(e);
}
const roots = __privateGet(this, _roots);
__privateSet(this, _roots, []);
this.apply();
var effects = collected_effects = [];
var render_effects = [];
var updates = legacy_updates = [];
for (const root24 of roots) {
try {
__privateMethod(this, _Batch_instances, traverse_fn).call(this, root24, effects, render_effects);
} catch (e) {
reset_all(root24);
if (!__privateMethod(this, _Batch_instances, is_deferred_fn).call(this)) this.discard();
throw e;
}
}
current_batch = null;
if (updates.length > 0) {
var batch = _Batch.ensure();
for (const e of updates) {
batch.schedule(e);
}
}
collected_effects = null;
legacy_updates = null;
if (__privateMethod(this, _Batch_instances, is_deferred_fn).call(this)) {
__privateMethod(this, _Batch_instances, defer_effects_fn).call(this, render_effects);
__privateMethod(this, _Batch_instances, defer_effects_fn).call(this, effects);
for (const [e, t] of __privateGet(this, _skipped_branches)) {
reset_branch(e, t);
}
if (updates.length > 0) {
/** @type {unknown} */
__privateMethod(_a5 = current_batch, _Batch_instances, process_fn).call(_a5);
}
return;
}
const earlier_batch = __privateMethod(this, _Batch_instances, find_earlier_batch_fn).call(this);
if (earlier_batch) {
__privateMethod(this, _Batch_instances, defer_effects_fn).call(this, render_effects);
__privateMethod(this, _Batch_instances, defer_effects_fn).call(this, effects);
__privateMethod(_b3 = earlier_batch, _Batch_instances, merge_fn).call(_b3, this);
return;
}
__privateGet(this, _dirty_effects).clear();
__privateGet(this, _maybe_dirty_effects).clear();
for (const fn of __privateGet(this, _commit_callbacks)) fn(this);
__privateGet(this, _commit_callbacks).clear();
previous_batch = this;
flush_queued_effects(render_effects);
flush_queued_effects(effects);
previous_batch = null;
(_c2 = __privateGet(this, _deferred)) == null ? void 0 : _c2.resolve();
var next_batch = (
/** @type {Batch | null} */
/** @type {unknown} */
current_batch
);
if (__privateGet(this, _pending) === 0 && (__privateGet(this, _roots).length === 0 || next_batch !== null)) {
__privateMethod(this, _Batch_instances, unlink_fn).call(this);
if (async_mode_flag) {
__privateMethod(this, _Batch_instances, commit_fn).call(this);
current_batch = next_batch;
}
}
if (__privateGet(this, _roots).length > 0) {
if (next_batch !== null) {
const batch2 = next_batch;
__privateGet(batch2, _roots).push(...__privateGet(this, _roots).filter((r2) => !__privateGet(batch2, _roots).includes(r2)));
} else {
next_batch = this;
}
}
if (next_batch !== null) {
__privateMethod(_d = next_batch, _Batch_instances, process_fn).call(_d);
}
};
/**
* Traverse the effect tree, executing effects or stashing
* them for later execution as appropriate
* @param {Effect} root
* @param {Effect[]} effects
* @param {Effect[]} render_effects
*/
traverse_fn = function(root24, effects, render_effects) {
root24.f ^= CLEAN;
var effect2 = root24.first;
while (effect2 !== null) {
var flags2 = effect2.f;
var is_branch = (flags2 & (BRANCH_EFFECT | ROOT_EFFECT)) !== 0;
var is_skippable_branch = is_branch && (flags2 & CLEAN) !== 0;
var skip = is_skippable_branch || (flags2 & INERT) !== 0 || __privateGet(this, _skipped_branches).has(effect2);
if (!skip && effect2.fn !== null) {
if (is_branch) {
effect2.f ^= CLEAN;
} else if ((flags2 & EFFECT) !== 0) {
effects.push(effect2);
} else if (async_mode_flag && (flags2 & (RENDER_EFFECT | MANAGED_EFFECT)) !== 0) {
render_effects.push(effect2);
} else if (is_dirty(effect2)) {
if ((flags2 & BLOCK_EFFECT) !== 0) __privateGet(this, _maybe_dirty_effects).add(effect2);
update_effect(effect2);
}
var child2 = effect2.first;
if (child2 !== null) {
effect2 = child2;
continue;
}
}
while (effect2 !== null) {
var next2 = effect2.next;
if (next2 !== null) {
effect2 = next2;
break;
}
effect2 = effect2.parent;
}
}
};
find_earlier_batch_fn = function() {
var batch = __privateGet(this, _prev);
while (batch !== null) {
if (!batch.is_fork) {
for (const [value, [, is_derived]] of this.current) {
if (batch.current.has(value) && !is_derived) {
return batch;
}
}
}
batch = __privateGet(batch, _prev);
}
return null;
};
/**
* @param {Batch} batch
*/
merge_fn = function(batch) {
var _a5;
for (const [source2, value] of batch.current) {
if (!this.previous.has(source2) && batch.previous.has(source2)) {
this.previous.set(source2, batch.previous.get(source2));
}
this.current.set(source2, value);
}
for (const [effect2, deferred2] of batch.async_deriveds) {
const d = this.async_deriveds.get(effect2);
if (d) deferred2.promise.then(d.resolve).catch(d.reject);
}
this.transfer_effects(__privateGet(batch, _dirty_effects), __privateGet(batch, _maybe_dirty_effects));
const mark = (value) => {
var reactions = value.reactions;
if (reactions === null) return;
for (const reaction of reactions) {
var flags2 = reaction.f;
if ((flags2 & DERIVED) !== 0) {
mark(
/** @type {Derived} */
reaction
);
} else {
var effect2 = (
/** @type {Effect} */
reaction
);
if (flags2 & (ASYNC | BLOCK_EFFECT) && !this.async_deriveds.has(effect2)) {
__privateGet(this, _maybe_dirty_effects).delete(effect2);
set_signal_status(effect2, DIRTY);
this.schedule(effect2);
}
}
}
};
for (const source2 of this.current.keys()) {
mark(source2);
}
this.oncommit(() => batch.discard());
__privateMethod(_a5 = batch, _Batch_instances, unlink_fn).call(_a5);
current_batch = this;
__privateMethod(this, _Batch_instances, process_fn).call(this);
};
/**
* @param {Effect[]} effects
*/
defer_effects_fn = function(effects) {
for (var i = 0; i < effects.length; i += 1) {
defer_effect(effects[i], __privateGet(this, _dirty_effects), __privateGet(this, _maybe_dirty_effects));
}
};
commit_fn = function() {
var _a5;
for (let batch = first_batch; batch !== null; batch = __privateGet(batch, _next)) {
var is_earlier = batch.id < this.id;
var sources = [];
for (const [source3, [value, is_derived]] of this.current) {
if (batch.current.has(source3)) {
var batch_value = (
/** @type {[any, boolean]} */
batch.current.get(source3)[0]
);
if (is_earlier && value !== batch_value) {
batch.current.set(source3, [value, is_derived]);
} else {
continue;
}
}
sources.push(source3);
}
if (is_earlier) {
for (const [effect2, deferred2] of this.async_deriveds) {
const d = batch.async_deriveds.get(effect2);
if (d) deferred2.promise.then(d.resolve).catch(d.reject);
}
}
if (!__privateGet(batch, _started)) continue;
var others = [...batch.current.keys()].filter(
(s) => !/** @type {[any, boolean]} */
batch.current.get(s)[1] && !this.current.has(s)
);
if (others.length === 0) {
if (is_earlier) {
batch.discard();
}
} else if (sources.length > 0) {
if (dev_fallback_default && !__privateGet(batch, _decrement_queued)) {
invariant(__privateGet(batch, _roots).length === 0, "Batch has scheduled roots");
}
if (is_earlier) {
for (const unskipped of __privateGet(this, _unskipped_branches)) {
batch.unskip_effect(unskipped, (e) => {
var _a6;
if ((e.f & (BLOCK_EFFECT | ASYNC)) !== 0) {
batch.schedule(e);
} else {
__privateMethod(_a6 = batch, _Batch_instances, defer_effects_fn).call(_a6, [e]);
}
});
}
}
batch.activate();
var marked = /* @__PURE__ */ new Set();
var checked = /* @__PURE__ */ new Map();
for (var source2 of sources) {
mark_effects(source2, others, marked, checked);
}
checked = /* @__PURE__ */ new Map();
var current_unequal = [...batch.current].filter(([c, v1]) => {
const v2 = this.current.get(c);
if (!v2) return true;
return v2[0] !== v1[0] || v2[1] !== v1[1];
}).map(([c]) => c);
if (current_unequal.length > 0) {
for (const effect2 of __privateGet(this, _new_effects)) {
if ((effect2.f & (DESTROYED | INERT | EAGER_EFFECT)) === 0 && depends_on(effect2, current_unequal, checked)) {
if ((effect2.f & (ASYNC | BLOCK_EFFECT)) !== 0) {
set_signal_status(effect2, DIRTY);
batch.schedule(effect2);
} else {
__privateGet(batch, _dirty_effects).add(effect2);
}
}
}
}
if (__privateGet(batch, _roots).length > 0 && !__privateGet(batch, _decrement_queued)) {
batch.apply();
for (var root24 of __privateGet(batch, _roots)) {
__privateMethod(_a5 = batch, _Batch_instances, traverse_fn).call(_a5, root24, [], []);
}
__privateSet(batch, _roots, []);
}
batch.deactivate();
}
}
};
unlink_fn = function() {
if (!this.linked) return;
var prev = __privateGet(this, _prev);
var next2 = __privateGet(this, _next);
if (prev === null) {
first_batch = next2;
} else {
__privateSet(prev, _next, next2);
}
if (next2 === null) {
last_batch = prev;
} else {
__privateSet(next2, _prev, prev);
}
this.linked = false;
};
var Batch = _Batch;
function flushSync(fn) {
var was_flushing_sync = is_flushing_sync;
is_flushing_sync = true;
try {
var result;
if (fn) {
if (current_batch !== null && !current_batch.is_fork) {
current_batch.flush();
}
result = fn();
}
while (true) {
flush_tasks();
if (current_batch === null) {
return (
/** @type {T} */
result
);
}
current_batch.flush();
}
} finally {
is_flushing_sync = was_flushing_sync;
}
}
function infinite_loop_guard() {
var _a5;
if (dev_fallback_default) {
var updates = /* @__PURE__ */ new Map();
for (
const source2 of
/** @type {Batch} */
current_batch.current.keys()
) {
for (const [stack2, update2] of (_a5 = source2.updated) != null ? _a5 : []) {
var entry = updates.get(stack2);
if (!entry) {
entry = { error: update2.error, count: 0 };
updates.set(stack2, entry);
}
entry.count += update2.count;
}
}
for (const update2 of updates.values()) {
if (update2.error) {
console.error(update2.error);
}
}
}
try {
effect_update_depth_exceeded();
} catch (error) {
if (dev_fallback_default) {
define_property(error, "stack", { value: "" });
}
invoke_error_boundary(error, last_scheduled_effect);
}
}
var eager_block_effects = null;
function flush_queued_effects(effects) {
var length = effects.length;
if (length === 0) return;
var i = 0;
while (i < length) {
var effect2 = effects[i++];
if ((effect2.f & (DESTROYED | INERT)) === 0 && is_dirty(effect2)) {
eager_block_effects = /* @__PURE__ */ new Set();
update_effect(effect2);
if (effect2.deps === null && effect2.first === null && effect2.nodes === null && effect2.teardown === null && effect2.ac === null) {
unlink_effect(effect2);
}
if ((eager_block_effects == null ? void 0 : eager_block_effects.size) > 0) {
old_values.clear();
for (const e of eager_block_effects) {
if ((e.f & (DESTROYED | INERT)) !== 0) continue;
const ordered_effects = [e];
let ancestor = e.parent;
while (ancestor !== null) {
if (eager_block_effects.has(ancestor)) {
eager_block_effects.delete(ancestor);
ordered_effects.push(ancestor);
}
ancestor = ancestor.parent;
}
for (let j = ordered_effects.length - 1; j >= 0; j--) {
const e2 = ordered_effects[j];
if ((e2.f & (DESTROYED | INERT)) !== 0) continue;
update_effect(e2);
}
}
eager_block_effects.clear();
}
}
}
eager_block_effects = null;
}
function mark_effects(value, sources, marked, checked) {
if (marked.has(value)) return;
marked.add(value);
if (value.reactions !== null) {
for (const reaction of value.reactions) {
const flags2 = reaction.f;
if ((flags2 & DERIVED) !== 0) {
mark_effects(
/** @type {Derived} */
reaction,
sources,
marked,
checked
);
} else if ((flags2 & (ASYNC | BLOCK_EFFECT)) !== 0 && (flags2 & DIRTY) === 0 && depends_on(reaction, sources, checked)) {
set_signal_status(reaction, DIRTY);
schedule_effect(
/** @type {Effect} */
reaction
);
}
}
}
}
function depends_on(reaction, sources, checked) {
const depends = checked.get(reaction);
if (depends !== void 0) return depends;
if (reaction.deps !== null) {
for (const dep of reaction.deps) {
if (includes.call(sources, dep)) {
return true;
}
if ((dep.f & DERIVED) !== 0 && depends_on(
/** @type {Derived} */
dep,
sources,
checked
)) {
checked.set(
/** @type {Derived} */
dep,
true
);
return true;
}
}
}
checked.set(reaction, false);
return false;
}
function schedule_effect(effect2) {
current_batch.schedule(effect2);
}
function reset_branch(effect2, tracked) {
if ((effect2.f & BRANCH_EFFECT) !== 0 && (effect2.f & CLEAN) !== 0) {
return;
}
if ((effect2.f & DIRTY) !== 0) {
tracked.d.push(effect2);
} else if ((effect2.f & MAYBE_DIRTY) !== 0) {
tracked.m.push(effect2);
}
set_signal_status(effect2, CLEAN);
var e = effect2.first;
while (e !== null) {
reset_branch(e, tracked);
e = e.next;
}
}
function reset_all(effect2) {
set_signal_status(effect2, CLEAN);
var e = effect2.first;
while (e !== null) {
reset_all(e);
e = e.next;
}
}
// node_modules/svelte/src/reactivity/create-subscriber.js
function createSubscriber(start) {
let subscribers = 0;
let version = source(0);
let stop;
if (dev_fallback_default) {
tag(version, "createSubscriber version");
}
return () => {
if (effect_tracking()) {
get(version);
render_effect(() => {
if (subscribers === 0) {
stop = untrack(() => start(() => increment(version)));
}
subscribers += 1;
return () => {
queue_micro_task(() => {
subscribers -= 1;
if (subscribers === 0) {
stop == null ? void 0 : stop();
stop = void 0;
increment(version);
}
});
};
});
}
};
}
// node_modules/svelte/src/internal/client/dom/blocks/boundary.js
var flags = EFFECT_TRANSPARENT | EFFECT_PRESERVED;
function boundary(node, props, children, transform_error) {
new Boundary(node, props, children, transform_error);
}
var _anchor, _hydrate_open, _props, _children, _effect, _main_effect, _pending_effect, _failed_effect, _offscreen_fragment, _local_pending_count, _pending_count, _pending_count_update_queued, _dirty_effects2, _maybe_dirty_effects2, _effect_pending, _effect_pending_subscriber, _Boundary_instances, hydrate_resolved_content_fn, hydrate_failed_content_fn, hydrate_pending_content_fn, render_fn, resolve_fn, run_fn, update_pending_count_fn, handle_error_fn;
var Boundary = class {
/**
* @param {TemplateNode} node
* @param {BoundaryProps} props
* @param {((anchor: Node) => void)} children
* @param {((error: unknown) => unknown) | undefined} [transform_error]
*/
constructor(node, props, children, transform_error) {
__privateAdd(this, _Boundary_instances);
/** @type {Boundary | null} */
__publicField(this, "parent");
__publicField(this, "is_pending", false);
/**
* API-level transformError transform function. Transforms errors before they reach the `failed` snippet.
* Inherited from parent boundary, or defaults to identity.
* @type {(error: unknown) => unknown}
*/
__publicField(this, "transform_error");
/** @type {TemplateNode} */
__privateAdd(this, _anchor);
/** @type {TemplateNode | null} */
__privateAdd(this, _hydrate_open, hydrating ? hydrate_node : null);
/** @type {BoundaryProps} */
__privateAdd(this, _props);
/** @type {((anchor: Node) => void)} */
__privateAdd(this, _children);
/** @type {Effect} */
__privateAdd(this, _effect);
/** @type {Effect | null} */
__privateAdd(this, _main_effect, null);
/** @type {Effect | null} */
__privateAdd(this, _pending_effect, null);
/** @type {Effect | null} */
__privateAdd(this, _failed_effect, null);
/** @type {DocumentFragment | null} */
__privateAdd(this, _offscreen_fragment, null);
__privateAdd(this, _local_pending_count, 0);
__privateAdd(this, _pending_count, 0);
__privateAdd(this, _pending_count_update_queued, false);
/** @type {Set<Effect>} */
__privateAdd(this, _dirty_effects2, /* @__PURE__ */ new Set());
/** @type {Set<Effect>} */
__privateAdd(this, _maybe_dirty_effects2, /* @__PURE__ */ new Set());
/**
* A source containing the number of pending async deriveds/expressions.
* Only created if `$effect.pending()` is used inside the boundary,
* otherwise updating the source results in needless `Batch.ensure()`
* calls followed by no-op flushes
* @type {Source<number> | null}
*/
__privateAdd(this, _effect_pending, null);
__privateAdd(this, _effect_pending_subscriber, createSubscriber(() => {
__privateSet(this, _effect_pending, source(__privateGet(this, _local_pending_count)));
if (dev_fallback_default) {
tag(__privateGet(this, _effect_pending), "$effect.pending()");
}
return () => {
__privateSet(this, _effect_pending, null);
};
}));
var _a5, _b3;
__privateSet(this, _anchor, node);
__privateSet(this, _props, props);
__privateSet(this, _children, (anchor) => {
var effect2 = (
/** @type {Effect} */
active_effect
);
effect2.b = this;
effect2.f |= BOUNDARY_EFFECT;
children(anchor);
});
this.parent = /** @type {Effect} */
active_effect.b;
this.transform_error = (_b3 = transform_error != null ? transform_error : (_a5 = this.parent) == null ? void 0 : _a5.transform_error) != null ? _b3 : ((e) => e);
__privateSet(this, _effect, block(() => {
if (hydrating) {
const comment2 = (
/** @type {Comment} */
__privateGet(this, _hydrate_open)
);
hydrate_next();
const server_rendered_pending = comment2.data === HYDRATION_START_ELSE;
const server_rendered_failed = comment2.data.startsWith(HYDRATION_START_FAILED);
if (server_rendered_failed) {
const serialized_error = JSON.parse(comment2.data.slice(HYDRATION_START_FAILED.length));
__privateMethod(this, _Boundary_instances, hydrate_failed_content_fn).call(this, serialized_error);
} else if (server_rendered_pending) {
__privateMethod(this, _Boundary_instances, hydrate_pending_content_fn).call(this);
} else {
__privateMethod(this, _Boundary_instances, hydrate_resolved_content_fn).call(this);
}
} else {
__privateMethod(this, _Boundary_instances, render_fn).call(this);
}
}, flags));
if (hydrating) {
__privateSet(this, _anchor, hydrate_node);
}
}
/**
* Defer an effect inside a pending boundary until the boundary resolves
* @param {Effect} effect
*/
defer_effect(effect2) {
defer_effect(effect2, __privateGet(this, _dirty_effects2), __privateGet(this, _maybe_dirty_effects2));
}
/**
* Returns `false` if the effect exists inside a boundary whose pending snippet is shown
* @returns {boolean}
*/
is_rendered() {
return !this.is_pending && (!this.parent || this.parent.is_rendered());
}
has_pending_snippet() {
return !!__privateGet(this, _props).pending;
}
/**
* Update the source that powers `$effect.pending()` inside this boundary,
* and controls when the current `pending` snippet (if any) is removed.
* Do not call from inside the class
* @param {1 | -1} d
* @param {Batch} batch
*/
update_pending_count(d, batch) {
__privateMethod(this, _Boundary_instances, update_pending_count_fn).call(this, d, batch);
__privateSet(this, _local_pending_count, __privateGet(this, _local_pending_count) + d);
if (!__privateGet(this, _effect_pending) || __privateGet(this, _pending_count_update_queued)) return;
__privateSet(this, _pending_count_update_queued, true);
queue_micro_task(() => {
__privateSet(this, _pending_count_update_queued, false);
if (__privateGet(this, _effect_pending)) {
internal_set(__privateGet(this, _effect_pending), __privateGet(this, _local_pending_count));
}
});
}
get_effect_pending() {
__privateGet(this, _effect_pending_subscriber).call(this);
return get(
/** @type {Source<number>} */
__privateGet(this, _effect_pending)
);
}
/** @param {unknown} error */
error(error) {
var _a5;
if (!__privateGet(this, _props).onerror && !__privateGet(this, _props).failed) {
throw error;
}
if ((_a5 = current_batch) == null ? void 0 : _a5.is_fork) {
if (__privateGet(this, _main_effect)) current_batch.skip_effect(__privateGet(this, _main_effect));
if (__privateGet(this, _pending_effect)) current_batch.skip_effect(__privateGet(this, _pending_effect));
if (__privateGet(this, _failed_effect)) current_batch.skip_effect(__privateGet(this, _failed_effect));
current_batch.oncommit(() => {
__privateMethod(this, _Boundary_instances, handle_error_fn).call(this, error);
});
} else {
__privateMethod(this, _Boundary_instances, handle_error_fn).call(this, error);
}
}
};
_anchor = new WeakMap();
_hydrate_open = new WeakMap();
_props = new WeakMap();
_children = new WeakMap();
_effect = new WeakMap();
_main_effect = new WeakMap();
_pending_effect = new WeakMap();
_failed_effect = new WeakMap();
_offscreen_fragment = new WeakMap();
_local_pending_count = new WeakMap();
_pending_count = new WeakMap();
_pending_count_update_queued = new WeakMap();
_dirty_effects2 = new WeakMap();
_maybe_dirty_effects2 = new WeakMap();
_effect_pending = new WeakMap();
_effect_pending_subscriber = new WeakMap();
_Boundary_instances = new WeakSet();
hydrate_resolved_content_fn = function() {
try {
__privateSet(this, _main_effect, branch(() => __privateGet(this, _children).call(this, __privateGet(this, _anchor))));
} catch (error) {
this.error(error);
}
};
/**
* @param {unknown} error The deserialized error from the server's hydration comment
*/
hydrate_failed_content_fn = function(error) {
const failed = __privateGet(this, _props).failed;
if (!failed) return;
__privateSet(this, _failed_effect, branch(() => {
failed(
__privateGet(this, _anchor),
() => error,
() => () => {
}
);
}));
};
hydrate_pending_content_fn = function() {
const pending2 = __privateGet(this, _props).pending;
if (!pending2) return;
this.is_pending = true;
__privateSet(this, _pending_effect, branch(() => pending2(__privateGet(this, _anchor))));
queue_micro_task(() => {
var fragment = __privateSet(this, _offscreen_fragment, document.createDocumentFragment());
var anchor = create_text();
fragment.append(anchor);
__privateSet(this, _main_effect, __privateMethod(this, _Boundary_instances, run_fn).call(this, () => {
return branch(() => __privateGet(this, _children).call(this, anchor));
}));
if (__privateGet(this, _pending_count) === 0) {
__privateGet(this, _anchor).before(fragment);
__privateSet(this, _offscreen_fragment, null);
pause_effect(
/** @type {Effect} */
__privateGet(this, _pending_effect),
() => {
__privateSet(this, _pending_effect, null);
}
);
__privateMethod(this, _Boundary_instances, resolve_fn).call(
this,
/** @type {Batch} */
current_batch
);
}
});
};
render_fn = function() {
try {
this.is_pending = this.has_pending_snippet();
__privateSet(this, _pending_count, 0);
__privateSet(this, _local_pending_count, 0);
__privateSet(this, _main_effect, branch(() => {
__privateGet(this, _children).call(this, __privateGet(this, _anchor));
}));
if (__privateGet(this, _pending_count) > 0) {
var fragment = __privateSet(this, _offscreen_fragment, document.createDocumentFragment());
move_effect(__privateGet(this, _main_effect), fragment);
const pending2 = (
/** @type {(anchor: Node) => void} */
__privateGet(this, _props).pending
);
__privateSet(this, _pending_effect, branch(() => pending2(__privateGet(this, _anchor))));
} else {
__privateMethod(this, _Boundary_instances, resolve_fn).call(
this,
/** @type {Batch} */
current_batch
);
}
} catch (error) {
this.error(error);
}
};
/**
* @param {Batch} batch
*/
resolve_fn = function(batch) {
this.is_pending = false;
batch.transfer_effects(__privateGet(this, _dirty_effects2), __privateGet(this, _maybe_dirty_effects2));
};
/**
* @template T
* @param {() => T} fn
*/
run_fn = function(fn) {
var previous_effect = active_effect;
var previous_reaction = active_reaction;
var previous_ctx = component_context;
set_active_effect(__privateGet(this, _effect));
set_active_reaction(__privateGet(this, _effect));
set_component_context(__privateGet(this, _effect).ctx);
try {
Batch.ensure();
return fn();
} catch (e) {
handle_error(e);
return null;
} finally {
set_active_effect(previous_effect);
set_active_reaction(previous_reaction);
set_component_context(previous_ctx);
}
};
/**
* Updates the pending count associated with the currently visible pending snippet,
* if any, such that we can replace the snippet with content once work is done
* @param {1 | -1} d
* @param {Batch} batch
*/
update_pending_count_fn = function(d, batch) {
var _a5;
if (!this.has_pending_snippet()) {
if (this.parent) {
__privateMethod(_a5 = this.parent, _Boundary_instances, update_pending_count_fn).call(_a5, d, batch);
}
return;
}
__privateSet(this, _pending_count, __privateGet(this, _pending_count) + d);
if (__privateGet(this, _pending_count) === 0) {
__privateMethod(this, _Boundary_instances, resolve_fn).call(this, batch);
if (__privateGet(this, _pending_effect)) {
pause_effect(__privateGet(this, _pending_effect), () => {
__privateSet(this, _pending_effect, null);
});
}
if (__privateGet(this, _offscreen_fragment)) {
__privateGet(this, _anchor).before(__privateGet(this, _offscreen_fragment));
__privateSet(this, _offscreen_fragment, null);
}
}
};
/**
* @param {unknown} error
*/
handle_error_fn = function(error) {
if (__privateGet(this, _main_effect)) {
destroy_effect(__privateGet(this, _main_effect));
__privateSet(this, _main_effect, null);
}
if (__privateGet(this, _pending_effect)) {
destroy_effect(__privateGet(this, _pending_effect));
__privateSet(this, _pending_effect, null);
}
if (__privateGet(this, _failed_effect)) {
destroy_effect(__privateGet(this, _failed_effect));
__privateSet(this, _failed_effect, null);
}
if (hydrating) {
set_hydrate_node(
/** @type {TemplateNode} */
__privateGet(this, _hydrate_open)
);
next();
set_hydrate_node(skip_nodes());
}
var onerror = __privateGet(this, _props).onerror;
let failed = __privateGet(this, _props).failed;
var did_reset = false;
var calling_on_error = false;
const reset2 = () => {
if (did_reset) {
svelte_boundary_reset_noop();
return;
}
did_reset = true;
if (calling_on_error) {
svelte_boundary_reset_onerror();
}
if (__privateGet(this, _failed_effect) !== null) {
pause_effect(__privateGet(this, _failed_effect), () => {
__privateSet(this, _failed_effect, null);
});
}
__privateMethod(this, _Boundary_instances, run_fn).call(this, () => {
__privateMethod(this, _Boundary_instances, render_fn).call(this);
});
};
const handle_error_result = (transformed_error) => {
try {
calling_on_error = true;
onerror == null ? void 0 : onerror(transformed_error, reset2);
calling_on_error = false;
} catch (error2) {
invoke_error_boundary(error2, __privateGet(this, _effect) && __privateGet(this, _effect).parent);
}
if (failed) {
__privateSet(this, _failed_effect, __privateMethod(this, _Boundary_instances, run_fn).call(this, () => {
try {
return branch(() => {
var effect2 = (
/** @type {Effect} */
active_effect
);
effect2.b = this;
effect2.f |= BOUNDARY_EFFECT;
failed(
__privateGet(this, _anchor),
() => transformed_error,
() => reset2
);
});
} catch (error2) {
invoke_error_boundary(
error2,
/** @type {Effect} */
__privateGet(this, _effect).parent
);
return null;
}
}));
}
};
queue_micro_task(() => {
var result;
try {
result = this.transform_error(error);
} catch (e) {
invoke_error_boundary(e, __privateGet(this, _effect) && __privateGet(this, _effect).parent);
return;
}
if (result !== null && typeof result === "object" && typeof /** @type {any} */
result.then === "function") {
result.then(
handle_error_result,
/** @param {unknown} e */
(e) => invoke_error_boundary(e, __privateGet(this, _effect) && __privateGet(this, _effect).parent)
);
} else {
handle_error_result(result);
}
});
};
// node_modules/svelte/src/internal/client/reactivity/async.js
function flatten(blockers, sync, async2, fn) {
const d = is_runes() ? derived2 : derived_safe_equal;
var pending2 = blockers.filter((b) => !b.settled);
if (async2.length === 0 && pending2.length === 0) {
fn(sync.map(d));
return;
}
var parent = (
/** @type {Effect} */
active_effect
);
var restore = capture();
var blocker_promise = pending2.length === 1 ? pending2[0].promise : pending2.length > 1 ? Promise.all(pending2.map((b) => b.promise)) : null;
function finish(values) {
if ((parent.f & DESTROYED) !== 0) {
return;
}
restore();
try {
fn(values);
} catch (error) {
invoke_error_boundary(error, parent);
}
unset_context();
}
var decrement_pending = increment_pending();
if (async2.length === 0) {
blocker_promise.then(() => finish(sync.map(d))).finally(decrement_pending);
return;
}
function run3() {
Promise.all(async2.map((expression) => async_derived(expression))).then((result) => finish([...sync.map(d), ...result])).catch((error) => invoke_error_boundary(error, parent)).finally(decrement_pending);
}
if (blocker_promise) {
blocker_promise.then(() => {
restore();
run3();
unset_context();
});
} else {
run3();
}
}
function capture() {
var previous_effect = (
/** @type {Effect} */
active_effect
);
var previous_reaction = active_reaction;
var previous_component_context = component_context;
var previous_batch2 = (
/** @type {Batch} */
current_batch
);
if (dev_fallback_default) {
var previous_dev_stack = dev_stack;
}
return function restore(activate_batch = true) {
set_active_effect(previous_effect);
set_active_reaction(previous_reaction);
set_component_context(previous_component_context);
if (activate_batch && (previous_effect.f & DESTROYED) === 0) {
previous_batch2 == null ? void 0 : previous_batch2.activate();
previous_batch2 == null ? void 0 : previous_batch2.apply();
}
if (dev_fallback_default) {
set_reactivity_loss_tracker(null);
set_dev_stack(previous_dev_stack);
}
};
}
function unset_context(deactivate_batch = true) {
var _a5;
set_active_effect(null);
set_active_reaction(null);
set_component_context(null);
if (deactivate_batch) (_a5 = current_batch) == null ? void 0 : _a5.deactivate();
if (dev_fallback_default) {
set_reactivity_loss_tracker(null);
set_dev_stack(null);
}
}
function increment_pending() {
var effect2 = (
/** @type {Effect} */
active_effect
);
var boundary2 = effect2.b;
var batch = (
/** @type {Batch} */
current_batch
);
var blocking = !!(boundary2 == null ? void 0 : boundary2.is_rendered());
boundary2 == null ? void 0 : boundary2.update_pending_count(1, batch);
batch.increment(blocking, effect2);
return () => {
boundary2 == null ? void 0 : boundary2.update_pending_count(-1, batch);
batch.decrement(blocking, effect2);
};
}
// node_modules/svelte/src/internal/client/reactivity/deriveds.js
var reactivity_loss_tracker = null;
function set_reactivity_loss_tracker(v) {
reactivity_loss_tracker = v;
}
var recent_async_deriveds = /* @__PURE__ */ new Set();
// @__NO_SIDE_EFFECTS__
function derived2(fn) {
var flags2 = DERIVED | DIRTY;
if (active_effect !== null) {
active_effect.f |= EFFECT_PRESERVED;
}
const signal = {
ctx: component_context,
deps: null,
effects: null,
equals,
f: flags2,
fn,
reactions: null,
rv: 0,
v: (
/** @type {V} */
UNINITIALIZED
),
wv: 0,
parent: active_effect,
ac: null
};
if (dev_fallback_default && tracing_mode_flag) {
signal.created = get_error("created at");
}
return signal;
}
var OBSOLETE = /* @__PURE__ */ Symbol("obsolete");
// @__NO_SIDE_EFFECTS__
function async_derived(fn, label, location) {
let parent = (
/** @type {Effect | null} */
active_effect
);
if (parent === null) {
async_derived_orphan();
}
var promise = (
/** @type {Promise<V>} */
/** @type {unknown} */
void 0
);
var signal = source(
/** @type {V} */
UNINITIALIZED
);
if (dev_fallback_default) signal.label = label != null ? label : fn.toString();
var should_suspend = !active_reaction;
var deferreds = /* @__PURE__ */ new Set();
async_effect(() => {
var _a5, _b3;
var effect2 = (
/** @type {Effect} */
active_effect
);
if (dev_fallback_default) {
reactivity_loss_tracker = { effect: effect2, effect_deps: /* @__PURE__ */ new Set(), warned: false };
}
var d = deferred();
promise = d.promise;
try {
Promise.resolve(fn()).then(d.resolve, (e) => {
if (e !== STALE_REACTION) d.reject(e);
}).finally(unset_context);
} catch (error) {
d.reject(error);
unset_context();
}
if (dev_fallback_default) {
if (reactivity_loss_tracker) {
if (effect2.deps !== null) {
for (let i = 0; i < skipped_deps; i += 1) {
reactivity_loss_tracker.effect_deps.add(effect2.deps[i]);
}
}
if (new_deps !== null) {
for (let i = 0; i < new_deps.length; i += 1) {
reactivity_loss_tracker.effect_deps.add(new_deps[i]);
}
}
}
reactivity_loss_tracker = null;
}
var batch = (
/** @type {Batch} */
current_batch
);
if (should_suspend) {
if ((effect2.f & REACTION_RAN) !== 0) {
var decrement_pending = increment_pending();
}
if (
// boundary can be null if the async derived is inside an $effect.root not connected to the component render tree
(_a5 = parent.b) == null ? void 0 : _a5.is_rendered()
) {
(_b3 = batch.async_deriveds.get(effect2)) == null ? void 0 : _b3.reject(OBSOLETE);
} else {
for (const d2 of deferreds.values()) {
d2.reject(OBSOLETE);
}
}
deferreds.add(d);
batch.async_deriveds.set(effect2, d);
}
const handler = (value, error = void 0) => {
if (dev_fallback_default) {
reactivity_loss_tracker = null;
}
decrement_pending == null ? void 0 : decrement_pending();
deferreds.delete(d);
if (error === OBSOLETE) return;
batch.activate();
if (error) {
signal.f |= ERROR_VALUE;
internal_set(signal, error);
} else {
if ((signal.f & ERROR_VALUE) !== 0) {
signal.f ^= ERROR_VALUE;
}
if (dev_fallback_default && location !== void 0 && !signal.equals(value)) {
recent_async_deriveds.add(signal);
setTimeout(() => {
if (recent_async_deriveds.has(signal) && (effect2.f & DESTROYED) === 0) {
await_waterfall(
/** @type {string} */
signal.label,
location
);
recent_async_deriveds.delete(signal);
}
});
}
internal_set(signal, value);
}
batch.deactivate();
};
d.promise.then(handler, (e) => handler(null, e || "unknown"));
});
teardown(() => {
for (const d of deferreds) {
d.reject(OBSOLETE);
}
});
if (dev_fallback_default) {
signal.f |= ASYNC;
}
return new Promise((fulfil) => {
function next2(p) {
function go() {
if (p === promise) {
fulfil(signal);
} else {
next2(promise);
}
}
p.then(go, go);
}
next2(promise);
});
}
// @__NO_SIDE_EFFECTS__
function user_derived(fn) {
const d = /* @__PURE__ */ derived2(fn);
if (!async_mode_flag) push_reaction_value(d);
return d;
}
// @__NO_SIDE_EFFECTS__
function derived_safe_equal(fn) {
const signal = /* @__PURE__ */ derived2(fn);
signal.equals = safe_equals;
return signal;
}
function destroy_derived_effects(derived3) {
var effects = derived3.effects;
if (effects !== null) {
derived3.effects = null;
for (var i = 0; i < effects.length; i += 1) {
destroy_effect(
/** @type {Effect} */
effects[i]
);
}
}
}
var stack = [];
function execute_derived(derived3) {
var value;
var prev_active_effect = active_effect;
var parent = derived3.parent;
if (!is_destroying_effect && parent !== null && derived3.v !== UNINITIALIZED && // if it was never evaluated before, it's guaranteed to fail downstream, so we try to execute instead
(parent.f & (DESTROYED | INERT)) !== 0) {
derived_inert();
return derived3.v;
}
set_active_effect(parent);
if (dev_fallback_default) {
let prev_eager_effects = eager_effects;
set_eager_effects(/* @__PURE__ */ new Set());
try {
if (includes.call(stack, derived3)) {
derived_references_self();
}
stack.push(derived3);
derived3.f &= ~WAS_MARKED;
destroy_derived_effects(derived3);
value = update_reaction(derived3);
} finally {
set_active_effect(prev_active_effect);
set_eager_effects(prev_eager_effects);
stack.pop();
}
} else {
try {
derived3.f &= ~WAS_MARKED;
destroy_derived_effects(derived3);
value = update_reaction(derived3);
} finally {
set_active_effect(prev_active_effect);
}
}
return value;
}
function update_derived(derived3) {
var _a5, _b3, _c2;
var value = execute_derived(derived3);
if (!derived3.equals(value)) {
derived3.wv = increment_write_version();
if (!((_a5 = current_batch) == null ? void 0 : _a5.is_fork) || derived3.deps === null) {
if (current_batch !== null) {
current_batch.capture(derived3, value, true);
(_b3 = previous_batch) == null ? void 0 : _b3.capture(derived3, value, true);
} else {
derived3.v = value;
}
if (derived3.deps === null) {
set_signal_status(derived3, CLEAN);
return;
}
}
}
if (is_destroying_effect) {
return;
}
if (batch_values !== null) {
if (effect_tracking() || ((_c2 = current_batch) == null ? void 0 : _c2.is_fork)) {
batch_values.set(derived3, value);
}
} else {
update_derived_status(derived3);
}
}
function freeze_derived_effects(derived3) {
var _a5, _b3;
if (derived3.effects === null) return;
for (const e of derived3.effects) {
if (e.teardown || e.ac) {
(_a5 = e.teardown) == null ? void 0 : _a5.call(e);
(_b3 = e.ac) == null ? void 0 : _b3.abort(STALE_REACTION);
if (e.fn !== null) e.teardown = noop;
e.ac = null;
remove_reactions(e, 0);
destroy_effect_children(e);
}
}
}
function unfreeze_derived_effects(derived3) {
if (derived3.effects === null) return;
for (const e of derived3.effects) {
if (e.teardown && e.fn !== null) {
update_effect(e);
}
}
}
// node_modules/svelte/src/internal/client/reactivity/sources.js
var eager_effects = /* @__PURE__ */ new Set();
var old_values = /* @__PURE__ */ new Map();
function set_eager_effects(v) {
eager_effects = v;
}
var eager_effects_deferred = false;
function set_eager_effects_deferred() {
eager_effects_deferred = true;
}
function source(v, stack2) {
var signal = {
f: 0,
// TODO ideally we could skip this altogether, but it causes type errors
v,
reactions: null,
equals,
rv: 0,
wv: 0
};
if (dev_fallback_default && tracing_mode_flag) {
signal.created = stack2 != null ? stack2 : get_error("created at");
signal.updated = null;
signal.set_during_effect = false;
signal.trace = null;
}
return signal;
}
// @__NO_SIDE_EFFECTS__
function state(v, stack2) {
const s = source(v, stack2);
push_reaction_value(s);
return s;
}
// @__NO_SIDE_EFFECTS__
function mutable_source(initial_value, immutable = false, trackable = true) {
var _a5, _b3;
const s = source(initial_value);
if (!immutable) {
s.equals = safe_equals;
}
if (legacy_mode_flag && trackable && component_context !== null && component_context.l !== null) {
((_b3 = (_a5 = component_context.l).s) != null ? _b3 : _a5.s = []).push(s);
}
return s;
}
function mutate(source2, value) {
set(
source2,
untrack(() => get(source2))
);
return value;
}
function set(source2, value, should_proxy = false) {
if (active_reaction !== null && // since we are untracking the function inside `$inspect.with` we need to add this check
// to ensure we error if state is set inside an inspect effect
(!untracking || (active_reaction.f & EAGER_EFFECT) !== 0) && is_runes() && (active_reaction.f & (DERIVED | BLOCK_EFFECT | ASYNC | EAGER_EFFECT)) !== 0 && (current_sources === null || !current_sources.has(source2))) {
state_unsafe_mutation();
}
let new_value = should_proxy ? proxy(value) : value;
if (dev_fallback_default) {
tag_proxy(
new_value,
/** @type {string} */
source2.label
);
}
return internal_set(source2, new_value, legacy_updates);
}
function internal_set(source2, value, updated_during_traversal = null) {
var _a5, _b3, _c2;
if (!source2.equals(value)) {
old_values.set(source2, is_destroying_effect ? value : source2.v);
var batch = Batch.ensure();
batch.capture(source2, value);
if (dev_fallback_default) {
if (tracing_mode_flag || active_effect !== null) {
(_a5 = source2.updated) != null ? _a5 : source2.updated = /* @__PURE__ */ new Map();
const count = ((_c2 = (_b3 = source2.updated.get("")) == null ? void 0 : _b3.count) != null ? _c2 : 0) + 1;
source2.updated.set("", { error: (
/** @type {any} */
null
), count });
if (tracing_mode_flag || count > 5) {
const error = get_error("updated at");
if (error !== null) {
let entry = source2.updated.get(error.stack);
if (!entry) {
entry = { error, count: 0 };
source2.updated.set(error.stack, entry);
}
entry.count++;
}
}
}
if (active_effect !== null) {
source2.set_during_effect = true;
}
}
if ((source2.f & DERIVED) !== 0) {
const derived3 = (
/** @type {Derived} */
source2
);
if ((source2.f & DIRTY) !== 0) {
execute_derived(derived3);
}
if (batch_values === null) {
update_derived_status(derived3);
}
}
source2.wv = increment_write_version();
mark_reactions(source2, DIRTY, updated_during_traversal);
if (is_runes() && active_effect !== null && (active_effect.f & CLEAN) !== 0 && (active_effect.f & (BRANCH_EFFECT | ROOT_EFFECT)) === 0) {
if (untracked_writes === null) {
set_untracked_writes([source2]);
} else {
untracked_writes.push(source2);
}
}
if (!batch.is_fork && eager_effects.size > 0 && !eager_effects_deferred) {
flush_eager_effects();
}
}
return value;
}
function flush_eager_effects() {
eager_effects_deferred = false;
for (const effect2 of eager_effects) {
if ((effect2.f & CLEAN) !== 0) {
set_signal_status(effect2, MAYBE_DIRTY);
}
let dirty;
try {
dirty = is_dirty(effect2);
} catch (e) {
dirty = true;
}
if (dirty) {
update_effect(effect2);
}
}
eager_effects.clear();
}
function update(source2, d = 1) {
var value = get(source2);
var result = d === 1 ? value++ : value--;
set(source2, value);
return result;
}
function increment(source2) {
set(source2, source2.v + 1);
}
function mark_reactions(signal, status, updated_during_traversal) {
var _a5;
var reactions = signal.reactions;
if (reactions === null) return;
var runes = is_runes();
var length = reactions.length;
for (var i = 0; i < length; i++) {
var reaction = reactions[i];
var flags2 = reaction.f;
if (!runes && reaction === active_effect) continue;
var not_dirty = (flags2 & DIRTY) === 0;
if (not_dirty) {
set_signal_status(reaction, status);
}
if ((flags2 & EAGER_EFFECT) !== 0) {
eager_effects.add(
/** @type {Effect} */
reaction
);
} else if ((flags2 & DERIVED) !== 0) {
var derived3 = (
/** @type {Derived} */
reaction
);
(_a5 = batch_values) == null ? void 0 : _a5.delete(derived3);
if ((flags2 & WAS_MARKED) === 0) {
if (flags2 & CONNECTED && (active_effect === null || (active_effect.f & REACTION_IS_UPDATING) === 0)) {
reaction.f |= WAS_MARKED;
}
mark_reactions(derived3, MAYBE_DIRTY, updated_during_traversal);
}
} else if (not_dirty) {
var effect2 = (
/** @type {Effect} */
reaction
);
if ((flags2 & BLOCK_EFFECT) !== 0 && eager_block_effects !== null) {
eager_block_effects.add(effect2);
}
if (updated_during_traversal !== null) {
updated_during_traversal.push(effect2);
} else {
schedule_effect(effect2);
}
}
}
}
// node_modules/svelte/src/internal/client/legacy.js
var captured_signals = null;
// node_modules/svelte/src/internal/client/dom/elements/misc.js
function autofocus(dom, value) {
if (value) {
const body = document.body;
dom.autofocus = true;
queue_micro_task(() => {
if (document.activeElement === body) {
dom.focus();
}
});
}
}
function remove_textarea_child(dom) {
if (hydrating && get_first_child(dom) !== null) {
clear_text_content(dom);
}
}
var listening_to_form_reset = false;
function add_form_reset_listener() {
if (!listening_to_form_reset) {
listening_to_form_reset = true;
document.addEventListener(
"reset",
(evt) => {
Promise.resolve().then(() => {
var _a5;
if (!evt.defaultPrevented) {
for (
const e of
/**@type {HTMLFormElement} */
evt.target.elements
) {
(_a5 = e[FORM_RESET_HANDLER]) == null ? void 0 : _a5.call(e);
}
}
});
},
// In the capture phase to guarantee we get noticed of it (no possibility of stopPropagation)
{ capture: true }
);
}
}
// node_modules/svelte/src/internal/client/dom/elements/bindings/shared.js
function without_reactive_context(fn) {
var previous_reaction = active_reaction;
var previous_effect = active_effect;
set_active_reaction(null);
set_active_effect(null);
try {
return fn();
} finally {
set_active_reaction(previous_reaction);
set_active_effect(previous_effect);
}
}
function listen_to_event_and_reset_event(element2, event2, handler, on_reset = handler) {
element2.addEventListener(event2, () => without_reactive_context(handler));
const prev = (
/** @type {any} */
element2[FORM_RESET_HANDLER]
);
if (prev) {
element2[FORM_RESET_HANDLER] = () => {
prev();
on_reset(true);
};
} else {
element2[FORM_RESET_HANDLER] = () => on_reset(true);
}
add_form_reset_listener();
}
// node_modules/svelte/src/internal/client/runtime.js
var is_updating_effect = false;
var is_destroying_effect = false;
function set_is_destroying_effect(value) {
is_destroying_effect = value;
}
var active_reaction = null;
var untracking = false;
function set_active_reaction(reaction) {
active_reaction = reaction;
}
var active_effect = null;
function set_active_effect(effect2) {
active_effect = effect2;
}
var current_sources = null;
function push_reaction_value(value) {
if (active_reaction !== null && (!async_mode_flag || (active_reaction.f & DERIVED) !== 0)) {
(current_sources != null ? current_sources : current_sources = /* @__PURE__ */ new Set()).add(value);
}
}
var new_deps = null;
var skipped_deps = 0;
var untracked_writes = null;
function set_untracked_writes(value) {
untracked_writes = value;
}
var write_version = 1;
var read_version = 0;
var update_version = read_version;
function set_update_version(value) {
update_version = value;
}
function increment_write_version() {
return ++write_version;
}
function is_dirty(reaction) {
var flags2 = reaction.f;
if ((flags2 & DIRTY) !== 0) {
return true;
}
if (flags2 & DERIVED) {
reaction.f &= ~WAS_MARKED;
}
if ((flags2 & MAYBE_DIRTY) !== 0) {
var dependencies = (
/** @type {Value[]} */
reaction.deps
);
var length = dependencies.length;
for (var i = 0; i < length; i++) {
var dependency = dependencies[i];
if (is_dirty(
/** @type {Derived} */
dependency
)) {
update_derived(
/** @type {Derived} */
dependency
);
}
if (dependency.wv > reaction.wv) {
return true;
}
}
if ((flags2 & CONNECTED) !== 0 && // During time traveling we don't want to reset the status so that
// traversal of the graph in the other batches still happens
batch_values === null) {
set_signal_status(reaction, CLEAN);
}
}
return false;
}
function schedule_possible_effect_self_invalidation(signal, effect2, root24 = true) {
var reactions = signal.reactions;
if (reactions === null) return;
if (!async_mode_flag && current_sources !== null && current_sources.has(signal)) {
return;
}
for (var i = 0; i < reactions.length; i++) {
var reaction = reactions[i];
if ((reaction.f & DERIVED) !== 0) {
schedule_possible_effect_self_invalidation(
/** @type {Derived} */
reaction,
effect2,
false
);
} else if (effect2 === reaction) {
if (root24) {
set_signal_status(reaction, DIRTY);
} else if ((reaction.f & CLEAN) !== 0) {
set_signal_status(reaction, MAYBE_DIRTY);
}
schedule_effect(
/** @type {Effect} */
reaction
);
}
}
}
function update_reaction(reaction) {
var _a5, _b3, _c2;
var previous_deps = new_deps;
var previous_skipped_deps = skipped_deps;
var previous_untracked_writes = untracked_writes;
var previous_reaction = active_reaction;
var previous_sources = current_sources;
var previous_component_context = component_context;
var previous_untracking = untracking;
var previous_update_version = update_version;
var flags2 = reaction.f;
new_deps = /** @type {null | Value[]} */
null;
skipped_deps = 0;
untracked_writes = null;
active_reaction = (flags2 & (BRANCH_EFFECT | ROOT_EFFECT)) === 0 ? reaction : null;
current_sources = null;
set_component_context(reaction.ctx);
untracking = false;
update_version = ++read_version;
if (reaction.ac !== null) {
without_reactive_context(() => {
reaction.ac.abort(STALE_REACTION);
});
reaction.ac = null;
}
try {
reaction.f |= REACTION_IS_UPDATING;
var fn = (
/** @type {Function} */
reaction.fn
);
var result = fn();
reaction.f |= REACTION_RAN;
var deps = reaction.deps;
var is_fork = (_a5 = current_batch) == null ? void 0 : _a5.is_fork;
if (new_deps !== null) {
var i;
if (!is_fork) {
remove_reactions(reaction, skipped_deps);
}
if (deps !== null && skipped_deps > 0) {
deps.length = skipped_deps + new_deps.length;
for (i = 0; i < new_deps.length; i++) {
deps[skipped_deps + i] = new_deps[i];
}
} else {
reaction.deps = deps = new_deps;
}
if (effect_tracking() && (reaction.f & CONNECTED) !== 0) {
for (i = skipped_deps; i < deps.length; i++) {
((_c2 = (_b3 = deps[i]).reactions) != null ? _c2 : _b3.reactions = []).push(reaction);
}
}
} else if (!is_fork && deps !== null && skipped_deps < deps.length) {
remove_reactions(reaction, skipped_deps);
deps.length = skipped_deps;
}
if (is_runes() && untracked_writes !== null && !untracking && deps !== null && (reaction.f & (DERIVED | MAYBE_DIRTY | DIRTY)) === 0) {
for (i = 0; i < /** @type {Source[]} */
untracked_writes.length; i++) {
schedule_possible_effect_self_invalidation(
untracked_writes[i],
/** @type {Effect} */
reaction
);
}
}
if (previous_reaction !== null && previous_reaction !== reaction) {
read_version++;
if (previous_reaction.deps !== null) {
for (let i2 = 0; i2 < previous_skipped_deps; i2 += 1) {
previous_reaction.deps[i2].rv = read_version;
}
}
if (previous_deps !== null) {
for (const dep of previous_deps) {
dep.rv = read_version;
}
}
if (untracked_writes !== null) {
if (previous_untracked_writes === null) {
previous_untracked_writes = untracked_writes;
} else {
previous_untracked_writes.push(.../** @type {Source[]} */
untracked_writes);
}
}
}
if ((reaction.f & ERROR_VALUE) !== 0) {
reaction.f ^= ERROR_VALUE;
}
return result;
} catch (error) {
return handle_error(error);
} finally {
reaction.f ^= REACTION_IS_UPDATING;
new_deps = previous_deps;
skipped_deps = previous_skipped_deps;
untracked_writes = previous_untracked_writes;
active_reaction = previous_reaction;
current_sources = previous_sources;
set_component_context(previous_component_context);
untracking = previous_untracking;
update_version = previous_update_version;
}
}
function remove_reaction(signal, dependency) {
let reactions = dependency.reactions;
if (reactions !== null) {
var index2 = index_of.call(reactions, signal);
if (index2 !== -1) {
var new_length = reactions.length - 1;
if (new_length === 0) {
reactions = dependency.reactions = null;
} else {
reactions[index2] = reactions[new_length];
reactions.pop();
}
}
}
if (reactions === null && (dependency.f & DERIVED) !== 0 && // Destroying a child effect while updating a parent effect can cause a dependency to appear
// to be unused, when in fact it is used by the currently-updating parent. Checking `new_deps`
// allows us to skip the expensive work of disconnecting and immediately reconnecting it
(new_deps === null || !includes.call(new_deps, dependency))) {
var derived3 = (
/** @type {Derived} */
dependency
);
if ((derived3.f & CONNECTED) !== 0) {
derived3.f ^= CONNECTED;
derived3.f &= ~WAS_MARKED;
}
if (derived3.v !== UNINITIALIZED) {
update_derived_status(derived3);
}
freeze_derived_effects(derived3);
remove_reactions(derived3, 0);
}
}
function remove_reactions(signal, start_index) {
var dependencies = signal.deps;
if (dependencies === null) return;
for (var i = start_index; i < dependencies.length; i++) {
remove_reaction(signal, dependencies[i]);
}
}
function update_effect(effect2) {
var _a5;
var flags2 = effect2.f;
if ((flags2 & DESTROYED) !== 0) {
return;
}
set_signal_status(effect2, CLEAN);
var previous_effect = active_effect;
var was_updating_effect = is_updating_effect;
active_effect = effect2;
is_updating_effect = true;
if (dev_fallback_default) {
var previous_component_fn = dev_current_component_function;
set_dev_current_component_function(effect2.component_function);
var previous_stack = (
/** @type {any} */
dev_stack
);
set_dev_stack((_a5 = effect2.dev_stack) != null ? _a5 : dev_stack);
}
try {
if ((flags2 & (BLOCK_EFFECT | MANAGED_EFFECT)) !== 0) {
destroy_block_effect_children(effect2);
} else {
destroy_effect_children(effect2);
}
execute_effect_teardown(effect2);
var teardown2 = update_reaction(effect2);
effect2.teardown = typeof teardown2 === "function" ? teardown2 : null;
effect2.wv = write_version;
if (dev_fallback_default && tracing_mode_flag && (effect2.f & DIRTY) !== 0 && effect2.deps !== null) {
for (var dep of effect2.deps) {
if (dep.set_during_effect) {
dep.wv = increment_write_version();
dep.set_during_effect = false;
}
}
}
} finally {
is_updating_effect = was_updating_effect;
active_effect = previous_effect;
if (dev_fallback_default) {
set_dev_current_component_function(previous_component_fn);
set_dev_stack(previous_stack);
}
}
}
async function tick() {
if (async_mode_flag) {
return new Promise((f) => {
requestAnimationFrame(() => f());
setTimeout(() => f());
});
}
await Promise.resolve();
flushSync();
}
function get(signal) {
var _a5, _b3, _c2;
var flags2 = signal.f;
var is_derived = (flags2 & DERIVED) !== 0;
(_a5 = captured_signals) == null ? void 0 : _a5.add(signal);
if (active_reaction !== null && !untracking) {
var destroyed = active_effect !== null && (active_effect.f & DESTROYED) !== 0;
if (!destroyed && (current_sources === null || !current_sources.has(signal))) {
var deps = active_reaction.deps;
if ((active_reaction.f & REACTION_IS_UPDATING) !== 0) {
if (signal.rv < read_version) {
signal.rv = read_version;
if (new_deps === null && deps !== null && deps[skipped_deps] === signal) {
skipped_deps++;
} else if (new_deps === null) {
new_deps = [signal];
} else {
new_deps.push(signal);
}
}
} else {
(_b3 = active_reaction.deps) != null ? _b3 : active_reaction.deps = [];
if (!includes.call(active_reaction.deps, signal)) {
active_reaction.deps.push(signal);
}
var reactions = signal.reactions;
if (reactions === null) {
signal.reactions = [active_reaction];
} else if (!includes.call(reactions, active_reaction)) {
reactions.push(active_reaction);
}
}
}
}
if (dev_fallback_default) {
if (!untracking && reactivity_loss_tracker && !reactivity_loss_tracker.warned && (reactivity_loss_tracker.effect.f & REACTION_IS_UPDATING) === 0 && !reactivity_loss_tracker.effect_deps.has(signal)) {
reactivity_loss_tracker.warned = true;
await_reactivity_loss(
/** @type {string} */
signal.label
);
var trace2 = get_error("traced at");
if (trace2) console.warn(trace2);
}
recent_async_deriveds.delete(signal);
if (tracing_mode_flag && !untracking && tracing_expressions !== null && active_reaction !== null && tracing_expressions.reaction === active_reaction) {
if (signal.trace) {
signal.trace();
} else {
trace2 = get_error("traced at");
if (trace2) {
var entry = tracing_expressions.entries.get(signal);
if (entry === void 0) {
entry = { traces: [] };
tracing_expressions.entries.set(signal, entry);
}
var last = entry.traces[entry.traces.length - 1];
if (trace2.stack !== (last == null ? void 0 : last.stack)) {
entry.traces.push(trace2);
}
}
}
}
}
if (is_destroying_effect && old_values.has(signal)) {
return old_values.get(signal);
}
if (is_derived) {
var derived3 = (
/** @type {Derived} */
signal
);
if (is_destroying_effect) {
var value = derived3.v;
if ((derived3.f & CLEAN) === 0 && derived3.reactions !== null || depends_on_old_values(derived3)) {
value = execute_derived(derived3);
}
old_values.set(derived3, value);
return value;
}
var should_connect = (derived3.f & CONNECTED) === 0 && !untracking && active_reaction !== null && (is_updating_effect || (active_reaction.f & CONNECTED) !== 0);
var is_new = (derived3.f & REACTION_RAN) === 0;
if (is_dirty(derived3)) {
if (should_connect) {
derived3.f |= CONNECTED;
}
update_derived(derived3);
}
if (should_connect && !is_new) {
unfreeze_derived_effects(derived3);
reconnect(derived3);
}
}
if ((_c2 = batch_values) == null ? void 0 : _c2.has(signal)) {
return batch_values.get(signal);
}
if ((signal.f & ERROR_VALUE) !== 0) {
throw signal.v;
}
return signal.v;
}
function reconnect(derived3) {
var _a5;
derived3.f |= CONNECTED;
if (derived3.deps === null) return;
for (const dep of derived3.deps) {
((_a5 = dep.reactions) != null ? _a5 : dep.reactions = []).push(derived3);
if ((dep.f & DERIVED) !== 0 && (dep.f & CONNECTED) === 0) {
unfreeze_derived_effects(
/** @type {Derived} */
dep
);
reconnect(
/** @type {Derived} */
dep
);
}
}
}
function depends_on_old_values(derived3) {
if (derived3.v === UNINITIALIZED) return true;
if (derived3.deps === null) return false;
for (const dep of derived3.deps) {
if (old_values.has(dep)) {
return true;
}
if ((dep.f & DERIVED) !== 0 && depends_on_old_values(
/** @type {Derived} */
dep
)) {
return true;
}
}
return false;
}
function untrack(fn) {
var previous_untracking = untracking;
try {
untracking = true;
return fn();
} finally {
untracking = previous_untracking;
}
}
function deep_read_state(value) {
if (typeof value !== "object" || !value || value instanceof EventTarget) {
return;
}
if (STATE_SYMBOL in value) {
deep_read(value);
} else if (!Array.isArray(value)) {
for (let key2 in value) {
const prop2 = value[key2];
if (typeof prop2 === "object" && prop2 && STATE_SYMBOL in prop2) {
deep_read(prop2);
}
}
}
}
function deep_read(value, visited = /* @__PURE__ */ new Set()) {
if (typeof value === "object" && value !== null && // We don't want to traverse DOM elements
!(value instanceof EventTarget) && !visited.has(value)) {
visited.add(value);
if (value instanceof Date) {
value.getTime();
}
for (let key2 in value) {
try {
deep_read(value[key2], visited);
} catch (e) {
}
}
const proto = get_prototype_of(value);
if (proto !== Object.prototype && proto !== Array.prototype && proto !== Map.prototype && proto !== Set.prototype && proto !== Date.prototype) {
const descriptors = get_descriptors(proto);
for (let key2 in descriptors) {
const get3 = descriptors[key2].get;
if (get3) {
try {
get3.call(value);
} catch (e) {
}
}
}
}
}
}
// node_modules/svelte/src/internal/client/reactivity/effects.js
function validate_effect(rune) {
if (active_effect === null) {
if (active_reaction === null) {
effect_orphan(rune);
}
effect_in_unowned_derived();
}
if (is_destroying_effect) {
effect_in_teardown(rune);
}
}
function push_effect(effect2, parent_effect) {
var parent_last = parent_effect.last;
if (parent_last === null) {
parent_effect.last = parent_effect.first = effect2;
} else {
parent_last.next = effect2;
effect2.prev = parent_last;
parent_effect.last = effect2;
}
}
function create_effect(type2, fn) {
var _a5, _b3;
var parent = active_effect;
if (dev_fallback_default) {
while (parent !== null && (parent.f & EAGER_EFFECT) !== 0) {
parent = parent.parent;
}
}
if (parent !== null && (parent.f & INERT) !== 0) {
type2 |= INERT;
}
var effect2 = {
ctx: component_context,
deps: null,
nodes: null,
f: type2 | DIRTY | CONNECTED,
first: null,
fn,
last: null,
next: null,
parent,
b: parent && parent.b,
prev: null,
teardown: null,
wv: 0,
ac: null
};
if (dev_fallback_default) {
effect2.component_function = dev_current_component_function;
}
(_a5 = current_batch) == null ? void 0 : _a5.register_created_effect(effect2);
var e = effect2;
if ((type2 & EFFECT) !== 0) {
if (collected_effects !== null) {
collected_effects.push(effect2);
} else {
Batch.ensure().schedule(effect2);
}
} else if (fn !== null) {
try {
update_effect(effect2);
} catch (e2) {
destroy_effect(effect2);
throw e2;
}
if (e.deps === null && e.teardown === null && e.nodes === null && e.first === e.last && // either `null`, or a singular child
(e.f & EFFECT_PRESERVED) === 0) {
e = e.first;
if ((type2 & BLOCK_EFFECT) !== 0 && (type2 & EFFECT_TRANSPARENT) !== 0 && e !== null) {
e.f |= EFFECT_TRANSPARENT;
}
}
}
if (e !== null) {
e.parent = parent;
if (parent !== null) {
push_effect(e, parent);
}
if (active_reaction !== null && (active_reaction.f & DERIVED) !== 0 && (type2 & ROOT_EFFECT) === 0) {
var derived3 = (
/** @type {Derived} */
active_reaction
);
((_b3 = derived3.effects) != null ? _b3 : derived3.effects = []).push(e);
}
}
return effect2;
}
function effect_tracking() {
return active_reaction !== null && !untracking;
}
function teardown(fn) {
const effect2 = create_effect(RENDER_EFFECT, null);
set_signal_status(effect2, CLEAN);
effect2.teardown = fn;
return effect2;
}
function user_effect(fn) {
var _a5;
validate_effect("$effect");
if (dev_fallback_default) {
define_property(fn, "name", {
value: "$effect"
});
}
var flags2 = (
/** @type {Effect} */
active_effect.f
);
var defer = !active_reaction && (flags2 & BRANCH_EFFECT) !== 0 && component_context !== null && !component_context.i;
if (defer) {
var context = (
/** @type {ComponentContext} */
component_context
);
((_a5 = context.e) != null ? _a5 : context.e = []).push(fn);
} else {
return create_user_effect(fn);
}
}
function create_user_effect(fn) {
return create_effect(EFFECT | USER_EFFECT, fn);
}
function user_pre_effect(fn) {
validate_effect("$effect.pre");
if (dev_fallback_default) {
define_property(fn, "name", {
value: "$effect.pre"
});
}
return create_effect(RENDER_EFFECT | USER_EFFECT, fn);
}
function effect_root(fn) {
Batch.ensure();
const effect2 = create_effect(ROOT_EFFECT | EFFECT_PRESERVED, fn);
return () => {
destroy_effect(effect2);
};
}
function component_root(fn) {
Batch.ensure();
const effect2 = create_effect(ROOT_EFFECT | EFFECT_PRESERVED, fn);
return (options = {}) => {
return new Promise((fulfil) => {
if (options.outro) {
pause_effect(effect2, () => {
destroy_effect(effect2);
fulfil(void 0);
});
} else {
destroy_effect(effect2);
fulfil(void 0);
}
});
};
}
function effect(fn) {
return create_effect(EFFECT, fn);
}
function legacy_pre_effect(deps, fn) {
var context = (
/** @type {ComponentContextLegacy} */
component_context
);
var token = { effect: null, ran: false, deps };
context.l.$.push(token);
token.effect = render_effect(() => {
deps();
if (token.ran) return;
token.ran = true;
var effect2 = (
/** @type {Effect} */
active_effect
);
try {
set_active_effect(effect2.parent);
untrack(fn);
} finally {
set_active_effect(effect2);
}
});
}
function legacy_pre_effect_reset() {
var context = (
/** @type {ComponentContextLegacy} */
component_context
);
render_effect(() => {
for (var token of context.l.$) {
token.deps();
var effect2 = token.effect;
if ((effect2.f & CLEAN) !== 0 && effect2.deps !== null) {
set_signal_status(effect2, MAYBE_DIRTY);
}
if (is_dirty(effect2)) {
update_effect(effect2);
}
token.ran = false;
}
});
}
function async_effect(fn) {
return create_effect(ASYNC | EFFECT_PRESERVED, fn);
}
function render_effect(fn, flags2 = 0) {
return create_effect(RENDER_EFFECT | flags2, fn);
}
function template_effect(fn, sync = [], async2 = [], blockers = []) {
flatten(blockers, sync, async2, (values) => {
create_effect(RENDER_EFFECT, () => fn(...values.map(get)));
});
}
function block(fn, flags2 = 0) {
var effect2 = create_effect(BLOCK_EFFECT | flags2, fn);
if (dev_fallback_default) {
effect2.dev_stack = dev_stack;
}
return effect2;
}
function managed(fn, flags2 = 0) {
var effect2 = create_effect(MANAGED_EFFECT | flags2, fn);
if (dev_fallback_default) {
effect2.dev_stack = dev_stack;
}
return effect2;
}
function branch(fn) {
return create_effect(BRANCH_EFFECT | EFFECT_PRESERVED, fn);
}
function execute_effect_teardown(effect2) {
var teardown2 = effect2.teardown;
if (teardown2 !== null) {
const previously_destroying_effect = is_destroying_effect;
const previous_reaction = active_reaction;
set_is_destroying_effect(true);
set_active_reaction(null);
try {
teardown2.call(null);
} finally {
set_is_destroying_effect(previously_destroying_effect);
set_active_reaction(previous_reaction);
}
}
}
function destroy_effect_children(signal, remove_dom = false) {
var effect2 = signal.first;
signal.first = signal.last = null;
while (effect2 !== null) {
const controller = effect2.ac;
if (controller !== null) {
without_reactive_context(() => {
controller.abort(STALE_REACTION);
});
}
var next2 = effect2.next;
if ((effect2.f & ROOT_EFFECT) !== 0) {
effect2.parent = null;
} else {
destroy_effect(effect2, remove_dom);
}
effect2 = next2;
}
}
function destroy_block_effect_children(signal) {
var effect2 = signal.first;
while (effect2 !== null) {
var next2 = effect2.next;
if ((effect2.f & BRANCH_EFFECT) === 0) {
destroy_effect(effect2);
}
effect2 = next2;
}
}
function destroy_effect(effect2, remove_dom = true) {
var removed = false;
if ((remove_dom || (effect2.f & HEAD_EFFECT) !== 0) && effect2.nodes !== null && effect2.nodes.end !== null) {
remove_effect_dom(
effect2.nodes.start,
/** @type {TemplateNode} */
effect2.nodes.end
);
removed = true;
}
set_signal_status(effect2, DESTROYING);
destroy_effect_children(effect2, remove_dom && !removed);
remove_reactions(effect2, 0);
var transitions = effect2.nodes && effect2.nodes.t;
if (transitions !== null) {
for (const transition2 of transitions) {
transition2.stop();
}
}
execute_effect_teardown(effect2);
effect2.f ^= DESTROYING;
effect2.f |= DESTROYED;
var parent = effect2.parent;
if (parent !== null && parent.first !== null) {
unlink_effect(effect2);
}
if (dev_fallback_default) {
effect2.component_function = null;
}
effect2.next = effect2.prev = effect2.teardown = effect2.ctx = effect2.deps = effect2.fn = effect2.nodes = effect2.ac = effect2.b = null;
}
function remove_effect_dom(node, end) {
while (node !== null) {
var next2 = node === end ? null : get_next_sibling(node);
node.remove();
node = next2;
}
}
function unlink_effect(effect2) {
var parent = effect2.parent;
var prev = effect2.prev;
var next2 = effect2.next;
if (prev !== null) prev.next = next2;
if (next2 !== null) next2.prev = prev;
if (parent !== null) {
if (parent.first === effect2) parent.first = next2;
if (parent.last === effect2) parent.last = prev;
}
}
function pause_effect(effect2, callback, destroy = true) {
var transitions = [];
pause_children(effect2, transitions, true);
var fn = () => {
if (destroy) destroy_effect(effect2);
if (callback) callback();
};
var remaining = transitions.length;
if (remaining > 0) {
var check = () => --remaining || fn();
for (var transition2 of transitions) {
transition2.out(check);
}
} else {
fn();
}
}
function pause_children(effect2, transitions, local) {
if ((effect2.f & INERT) !== 0) return;
effect2.f ^= INERT;
var t = effect2.nodes && effect2.nodes.t;
if (t !== null) {
for (const transition2 of t) {
if (transition2.is_global || local) {
transitions.push(transition2);
}
}
}
var child2 = effect2.first;
while (child2 !== null) {
var sibling2 = child2.next;
if ((child2.f & ROOT_EFFECT) === 0) {
var transparent = (child2.f & EFFECT_TRANSPARENT) !== 0 || // If this is a branch effect without a block effect parent,
// it means the parent block effect was pruned. In that case,
// transparency information was transferred to the branch effect.
(child2.f & BRANCH_EFFECT) !== 0 && (effect2.f & BLOCK_EFFECT) !== 0;
pause_children(child2, transitions, transparent ? local : false);
}
child2 = sibling2;
}
}
function resume_effect(effect2) {
resume_children(effect2, true);
}
function resume_children(effect2, local) {
if ((effect2.f & INERT) === 0) return;
effect2.f ^= INERT;
if ((effect2.f & CLEAN) === 0) {
set_signal_status(effect2, DIRTY);
Batch.ensure().schedule(effect2);
}
var child2 = effect2.first;
while (child2 !== null) {
var sibling2 = child2.next;
var transparent = (child2.f & EFFECT_TRANSPARENT) !== 0 || (child2.f & BRANCH_EFFECT) !== 0;
resume_children(child2, transparent ? local : false);
child2 = sibling2;
}
var t = effect2.nodes && effect2.nodes.t;
if (t !== null) {
for (const transition2 of t) {
if (transition2.is_global || local) {
transition2.in();
}
}
}
}
function move_effect(effect2, fragment) {
if (!effect2.nodes) return;
var node = effect2.nodes.start;
var end = effect2.nodes.end;
while (node !== null) {
var next2 = node === end ? null : get_next_sibling(node);
fragment.append(node);
node = next2;
}
}
// src/ui/text_view.ts
var import_obsidian17 = require("obsidian");
// node_modules/svelte/src/internal/client/dom/elements/events.js
var event_symbol = /* @__PURE__ */ Symbol("events");
var all_registered_events = /* @__PURE__ */ new Set();
var root_event_handles = /* @__PURE__ */ new Set();
function create_event(event_name, dom, handler, options = {}) {
function target_handler(event2) {
if (!options.capture) {
handle_event_propagation.call(dom, event2);
}
if (!event2.cancelBubble) {
return without_reactive_context(() => {
return handler == null ? void 0 : handler.call(this, event2);
});
}
}
if (event_name.startsWith("pointer") || event_name.startsWith("touch") || event_name === "wheel") {
queue_micro_task(() => {
dom.addEventListener(event_name, target_handler, options);
});
} else {
dom.addEventListener(event_name, target_handler, options);
}
return target_handler;
}
function event(event_name, dom, handler, capture2, passive2) {
var options = { capture: capture2, passive: passive2 };
var target_handler = create_event(event_name, dom, handler, options);
if (dom === document.body || // @ts-ignore
dom === window || // @ts-ignore
dom === document || // Firefox has quirky behavior, it can happen that we still get "canplay" events when the element is already removed
dom instanceof HTMLMediaElement) {
teardown(() => {
dom.removeEventListener(event_name, target_handler, options);
});
}
}
function delegated(event_name, element2, handler) {
var _a5;
((_a5 = element2[event_symbol]) != null ? _a5 : element2[event_symbol] = {})[event_name] = handler;
}
function delegate(events) {
for (var i = 0; i < events.length; i++) {
all_registered_events.add(events[i]);
}
for (var fn of root_event_handles) {
fn(events);
}
}
var last_propagated_event = null;
function handle_event_propagation(event2) {
var _a5, _b3;
var handler_element = this;
var owner_document = (
/** @type {Node} */
handler_element.ownerDocument
);
var event_name = event2.type;
var path = ((_a5 = event2.composedPath) == null ? void 0 : _a5.call(event2)) || [];
var current_target = (
/** @type {null | Element} */
path[0] || event2.target
);
last_propagated_event = event2;
var path_idx = 0;
var handled_at = last_propagated_event === event2 && event2[event_symbol];
if (handled_at) {
var at_idx = path.indexOf(handled_at);
if (at_idx !== -1 && (handler_element === document || handler_element === /** @type {any} */
window)) {
event2[event_symbol] = handler_element;
return;
}
var handler_idx = path.indexOf(handler_element);
if (handler_idx === -1) {
return;
}
if (at_idx <= handler_idx) {
path_idx = at_idx;
}
}
current_target = /** @type {Element} */
path[path_idx] || event2.target;
if (current_target === handler_element) return;
define_property(event2, "currentTarget", {
configurable: true,
get() {
return current_target || owner_document;
}
});
var previous_reaction = active_reaction;
var previous_effect = active_effect;
set_active_reaction(null);
set_active_effect(null);
try {
var throw_error;
var other_errors = [];
while (current_target !== null) {
if (current_target === handler_element) break;
try {
var delegated2 = (_b3 = current_target[event_symbol]) == null ? void 0 : _b3[event_name];
if (delegated2 != null && (!/** @type {any} */
current_target.disabled || // DOM could've been updated already by the time this is reached, so we check this as well
// -> the target could not have been disabled because it emits the event in the first place
event2.target === current_target)) {
delegated2.call(current_target, event2);
}
} catch (error) {
if (throw_error) {
other_errors.push(error);
} else {
throw_error = error;
}
}
if (event2.cancelBubble) break;
path_idx++;
current_target = path_idx < path.length ? (
/** @type {Element} */
path[path_idx]
) : null;
}
if (throw_error) {
for (let error of other_errors) {
queueMicrotask(() => {
throw error;
});
}
throw throw_error;
}
} finally {
event2[event_symbol] = handler_element;
delete event2.currentTarget;
set_active_reaction(previous_reaction);
set_active_effect(previous_effect);
}
}
// node_modules/svelte/src/internal/client/dom/reconciler.js
var _a3;
var policy = (
// We gotta write it like this because after downleveling the pure comment may end up in the wrong location
((_a3 = globalThis == null ? void 0 : globalThis.window) == null ? void 0 : _a3.trustedTypes) && /* @__PURE__ */ globalThis.window.trustedTypes.createPolicy("svelte-trusted-html", {
/** @param {string} html */
createHTML: (html2) => {
return html2;
}
})
);
function create_trusted_html(html2) {
var _a5;
return (
/** @type {string} */
(_a5 = policy == null ? void 0 : policy.createHTML(html2)) != null ? _a5 : html2
);
}
function create_fragment_from_html(html2) {
var elem = create_element("template");
elem.innerHTML = create_trusted_html(html2.replaceAll("<!>", "<!---->"));
return elem.content;
}
// node_modules/svelte/src/internal/client/dom/template.js
function assign_nodes(start, end) {
var effect2 = (
/** @type {Effect} */
active_effect
);
if (effect2.nodes === null) {
effect2.nodes = { start, end, a: null, t: null };
}
}
// @__NO_SIDE_EFFECTS__
function from_html(content, flags2) {
var is_fragment = (flags2 & TEMPLATE_FRAGMENT) !== 0;
var use_import_node = (flags2 & TEMPLATE_USE_IMPORT_NODE) !== 0;
var node;
var has_start = !content.startsWith("<!>");
return () => {
if (hydrating) {
assign_nodes(hydrate_node, null);
return hydrate_node;
}
if (node === void 0) {
node = create_fragment_from_html(has_start ? content : "<!>" + content);
if (!is_fragment) node = /** @type {TemplateNode} */
get_first_child(node);
}
var clone = (
/** @type {TemplateNode} */
use_import_node || is_firefox ? document.importNode(node, true) : node.cloneNode(true)
);
if (is_fragment) {
var start = (
/** @type {TemplateNode} */
get_first_child(clone)
);
var end = (
/** @type {TemplateNode} */
clone.lastChild
);
assign_nodes(start, end);
} else {
assign_nodes(clone, clone);
}
return clone;
};
}
function text(value = "") {
if (!hydrating) {
var t = create_text(value + "");
assign_nodes(t, t);
return t;
}
var node = hydrate_node;
if (node.nodeType !== TEXT_NODE) {
node.before(node = create_text());
set_hydrate_node(node);
} else {
merge_text_nodes(
/** @type {Text} */
node
);
}
assign_nodes(node, node);
return node;
}
function comment() {
if (hydrating) {
assign_nodes(hydrate_node, null);
return hydrate_node;
}
var frag = document.createDocumentFragment();
var start = document.createComment("");
var anchor = create_text();
frag.append(start, anchor);
assign_nodes(start, anchor);
return frag;
}
function append(anchor, dom) {
if (hydrating) {
var effect2 = (
/** @type {Effect & { nodes: EffectNodes }} */
active_effect
);
if ((effect2.f & REACTION_RAN) === 0 || effect2.nodes.end === null) {
effect2.nodes.end = hydrate_node;
}
hydrate_next();
return;
}
if (anchor === null) {
return;
}
anchor.before(
/** @type {Node} */
dom
);
}
// node_modules/svelte/src/utils.js
function is_capture_event(name) {
return name.endsWith("capture") && name !== "gotpointercapture" && name !== "lostpointercapture";
}
var DELEGATED_EVENTS = [
"beforeinput",
"click",
"change",
"dblclick",
"contextmenu",
"focusin",
"focusout",
"input",
"keydown",
"keyup",
"mousedown",
"mousemove",
"mouseout",
"mouseover",
"mouseup",
"pointerdown",
"pointermove",
"pointerout",
"pointerover",
"pointerup",
"touchend",
"touchmove",
"touchstart"
];
function can_delegate_event(event_name) {
return DELEGATED_EVENTS.includes(event_name);
}
var DOM_BOOLEAN_ATTRIBUTES = [
"allowfullscreen",
"async",
"autofocus",
"autoplay",
"checked",
"controls",
"default",
"disabled",
"formnovalidate",
"indeterminate",
"inert",
"ismap",
"loop",
"multiple",
"muted",
"nomodule",
"novalidate",
"open",
"playsinline",
"readonly",
"required",
"reversed",
"seamless",
"selected",
"webkitdirectory",
"defer",
"disablepictureinpicture",
"disableremoteplayback"
];
var ATTRIBUTE_ALIASES = {
// no `class: 'className'` because we handle that separately
formnovalidate: "formNoValidate",
ismap: "isMap",
nomodule: "noModule",
playsinline: "playsInline",
readonly: "readOnly",
defaultvalue: "defaultValue",
defaultchecked: "defaultChecked",
srcobject: "srcObject",
novalidate: "noValidate",
allowfullscreen: "allowFullscreen",
disablepictureinpicture: "disablePictureInPicture",
disableremoteplayback: "disableRemotePlayback"
};
function normalize_attribute(name) {
var _a5;
name = name.toLowerCase();
return (_a5 = ATTRIBUTE_ALIASES[name]) != null ? _a5 : name;
}
var DOM_PROPERTIES = [
...DOM_BOOLEAN_ATTRIBUTES,
"formNoValidate",
"isMap",
"noModule",
"playsInline",
"readOnly",
"value",
"volume",
"defaultValue",
"defaultChecked",
"srcObject",
"noValidate",
"allowFullscreen",
"disablePictureInPicture",
"disableRemotePlayback"
];
var PASSIVE_EVENTS = ["touchstart", "touchmove"];
function is_passive_event(name) {
return PASSIVE_EVENTS.includes(name);
}
var STATE_CREATION_RUNES = (
/** @type {const} */
[
"$state",
"$state.raw",
"$derived",
"$derived.by"
]
);
var RUNES = (
/** @type {const} */
[
...STATE_CREATION_RUNES,
"$state.eager",
"$state.snapshot",
"$props",
"$props.id",
"$bindable",
"$effect",
"$effect.pre",
"$effect.tracking",
"$effect.root",
"$effect.pending",
"$inspect",
"$inspect().with",
"$inspect.trace",
"$host"
]
);
// node_modules/svelte/src/internal/client/render.js
var should_intro = true;
function set_text(text2, value) {
var _a5, _b3;
var str2 = value == null ? "" : typeof value === "object" ? `${value}` : value;
if (str2 !== /** @type {any} */
((_b3 = text2[_a5 = TEXT_CACHE]) != null ? _b3 : text2[_a5] = text2.nodeValue)) {
text2[TEXT_CACHE] = str2;
text2.nodeValue = `${str2}`;
}
}
function mount(component2, options) {
return _mount(component2, options);
}
function hydrate(component2, options) {
var _a5;
init_operations();
options.intro = (_a5 = options.intro) != null ? _a5 : false;
const target = options.target;
const was_hydrating = hydrating;
const previous_hydrate_node = hydrate_node;
try {
var anchor = get_first_child(target);
while (anchor && (anchor.nodeType !== COMMENT_NODE || /** @type {Comment} */
anchor.data !== HYDRATION_START)) {
anchor = get_next_sibling(anchor);
}
if (!anchor) {
throw HYDRATION_ERROR;
}
set_hydrating(true);
set_hydrate_node(
/** @type {Comment} */
anchor
);
const instance = _mount(component2, { ...options, anchor });
set_hydrating(false);
return (
/** @type {Exports} */
instance
);
} catch (error) {
if (error instanceof Error && error.message.split("\n").some((line) => line.startsWith("https://svelte.dev/e/"))) {
throw error;
}
if (error !== HYDRATION_ERROR) {
console.warn("Failed to hydrate: ", error);
}
if (options.recover === false) {
hydration_failed();
}
init_operations();
clear_text_content(target);
set_hydrating(false);
return mount(component2, options);
} finally {
set_hydrating(was_hydrating);
set_hydrate_node(previous_hydrate_node);
}
}
var listeners = /* @__PURE__ */ new Map();
function _mount(Component3, { target, anchor, props = {}, events, context, intro = true, transformError }) {
init_operations();
var component2 = void 0;
var unmount2 = component_root(() => {
var anchor_node = anchor != null ? anchor : target.appendChild(create_text());
boundary(
/** @type {TemplateNode} */
anchor_node,
{
pending: () => {
}
},
(anchor_node2) => {
push({});
var ctx = (
/** @type {ComponentContext} */
component_context
);
if (context) ctx.c = context;
if (events) {
props.$$events = events;
}
if (hydrating) {
assign_nodes(
/** @type {TemplateNode} */
anchor_node2,
null
);
}
should_intro = intro;
component2 = Component3(anchor_node2, props) || {};
should_intro = true;
if (hydrating) {
active_effect.nodes.end = hydrate_node;
if (hydrate_node === null || hydrate_node.nodeType !== COMMENT_NODE || /** @type {Comment} */
hydrate_node.data !== HYDRATION_END) {
hydration_mismatch();
throw HYDRATION_ERROR;
}
}
pop();
},
transformError
);
var registered_events = /* @__PURE__ */ new Set();
var event_handle = (events2) => {
for (var i = 0; i < events2.length; i++) {
var event_name = events2[i];
if (registered_events.has(event_name)) continue;
registered_events.add(event_name);
var passive2 = is_passive_event(event_name);
for (const node of [target, document]) {
var counts = listeners.get(node);
if (counts === void 0) {
counts = /* @__PURE__ */ new Map();
listeners.set(node, counts);
}
var count = counts.get(event_name);
if (count === void 0) {
node.addEventListener(event_name, handle_event_propagation, { passive: passive2 });
counts.set(event_name, 1);
} else {
counts.set(event_name, count + 1);
}
}
}
};
event_handle(array_from(all_registered_events));
root_event_handles.add(event_handle);
return () => {
var _a5;
for (var event_name of registered_events) {
for (const node of [target, document]) {
var counts = (
/** @type {Map<string, number>} */
listeners.get(node)
);
var count = (
/** @type {number} */
counts.get(event_name)
);
if (--count == 0) {
node.removeEventListener(event_name, handle_event_propagation);
counts.delete(event_name);
if (counts.size === 0) {
listeners.delete(node);
}
} else {
counts.set(event_name, count);
}
}
}
root_event_handles.delete(event_handle);
if (anchor_node !== anchor) {
(_a5 = anchor_node.parentNode) == null ? void 0 : _a5.removeChild(anchor_node);
}
};
});
mounted_components.set(component2, unmount2);
return component2;
}
var mounted_components = /* @__PURE__ */ new WeakMap();
function unmount(component2, options) {
const fn = mounted_components.get(component2);
if (fn) {
mounted_components.delete(component2);
return fn(options);
}
if (dev_fallback_default) {
if (STATE_SYMBOL in component2) {
state_proxy_unmount();
} else {
lifecycle_double_unmount();
}
}
return Promise.resolve();
}
// node_modules/svelte/src/internal/client/dom/legacy/event-modifiers.js
function stopPropagation(fn) {
return function(...args) {
var event2 = (
/** @type {Event} */
args[0]
);
event2.stopPropagation();
return fn == null ? void 0 : fn.apply(this, args);
};
}
function preventDefault(fn) {
return function(...args) {
var event2 = (
/** @type {Event} */
args[0]
);
event2.preventDefault();
return fn == null ? void 0 : fn.apply(this, args);
};
}
// node_modules/svelte/src/legacy/legacy-client.js
function createClassComponent(options) {
return new Svelte4Component(options);
}
var _events, _instance;
var Svelte4Component = class {
/**
* @param {ComponentConstructorOptions & {
* component: any;
* }} options
*/
constructor(options) {
/** @type {any} */
__privateAdd(this, _events);
/** @type {Record<string, any>} */
__privateAdd(this, _instance);
var _a5, _b3;
var sources = /* @__PURE__ */ new Map();
var add_source = (key2, value) => {
var s = mutable_source(value, false, false);
sources.set(key2, s);
return s;
};
const props = new Proxy(
{ ...options.props || {}, $$events: {} },
{
get(target, prop2) {
var _a6;
return get((_a6 = sources.get(prop2)) != null ? _a6 : add_source(prop2, Reflect.get(target, prop2)));
},
has(target, prop2) {
var _a6;
if (prop2 === LEGACY_PROPS) return true;
get((_a6 = sources.get(prop2)) != null ? _a6 : add_source(prop2, Reflect.get(target, prop2)));
return Reflect.has(target, prop2);
},
set(target, prop2, value) {
var _a6;
set((_a6 = sources.get(prop2)) != null ? _a6 : add_source(prop2, value), value);
return Reflect.set(target, prop2, value);
}
}
);
__privateSet(this, _instance, (options.hydrate ? hydrate : mount)(options.component, {
target: options.target,
anchor: options.anchor,
props,
context: options.context,
intro: (_a5 = options.intro) != null ? _a5 : false,
recover: options.recover,
transformError: options.transformError
}));
if (!async_mode_flag && (!((_b3 = options == null ? void 0 : options.props) == null ? void 0 : _b3.$$host) || options.sync === false)) {
flushSync();
}
__privateSet(this, _events, props.$$events);
for (const key2 of Object.keys(__privateGet(this, _instance))) {
if (key2 === "$set" || key2 === "$destroy" || key2 === "$on") continue;
define_property(this, key2, {
get() {
return __privateGet(this, _instance)[key2];
},
/** @param {any} value */
set(value) {
__privateGet(this, _instance)[key2] = value;
},
enumerable: true
});
}
__privateGet(this, _instance).$set = /** @param {Record<string, any>} next */
(next2) => {
Object.assign(props, next2);
};
__privateGet(this, _instance).$destroy = () => {
unmount(__privateGet(this, _instance));
};
}
/** @param {Record<string, any>} props */
$set(props) {
__privateGet(this, _instance).$set(props);
}
/**
* @param {string} event
* @param {(...args: any[]) => any} callback
* @returns {any}
*/
$on(event2, callback) {
__privateGet(this, _events)[event2] = __privateGet(this, _events)[event2] || [];
const cb = (...args) => callback.call(this, ...args);
__privateGet(this, _events)[event2].push(cb);
return () => {
__privateGet(this, _events)[event2] = __privateGet(this, _events)[event2].filter(
/** @param {any} fn */
(fn) => fn !== cb
);
};
}
$destroy() {
__privateGet(this, _instance).$destroy();
}
};
_events = new WeakMap();
_instance = new WeakMap();
// node_modules/svelte/src/version.js
var PUBLIC_VERSION = "5";
// node_modules/svelte/src/internal/disclose-version.js
var _a4, _b2, _c;
if (typeof window !== "undefined") {
((_c = (_b2 = (_a4 = window.__svelte) != null ? _a4 : window.__svelte = {}).v) != null ? _c : _b2.v = /* @__PURE__ */ new Set()).add(PUBLIC_VERSION);
}
// node_modules/svelte/src/internal/flags/legacy.js
enable_legacy_mode_flag();
// node_modules/svelte/src/internal/client/dom/blocks/branches.js
var _batches, _onscreen, _offscreen, _outroing, _transition, _commit, _discard;
var BranchManager = class {
/**
* @param {TemplateNode} anchor
* @param {boolean} transition
*/
constructor(anchor, transition2 = true) {
/** @type {TemplateNode} */
__publicField(this, "anchor");
/** @type {Map<Batch, Key>} */
__privateAdd(this, _batches, /* @__PURE__ */ new Map());
/**
* Map of keys to effects that are currently rendered in the DOM.
* These effects are visible and actively part of the document tree.
* Example:
* ```
* {#if condition}
* foo
* {:else}
* bar
* {/if}
* ```
* Can result in the entries `true->Effect` and `false->Effect`
* @type {Map<Key, Effect>}
*/
__privateAdd(this, _onscreen, /* @__PURE__ */ new Map());
/**
* Similar to #onscreen with respect to the keys, but contains branches that are not yet
* in the DOM, because their insertion is deferred.
* @type {Map<Key, Branch>}
*/
__privateAdd(this, _offscreen, /* @__PURE__ */ new Map());
/**
* Keys of effects that are currently outroing
* @type {Set<Key>}
*/
__privateAdd(this, _outroing, /* @__PURE__ */ new Set());
/**
* Whether to pause (i.e. outro) on change, or destroy immediately.
* This is necessary for `<svelte:element>`
*/
__privateAdd(this, _transition, true);
/**
* @param {Batch} batch
*/
__privateAdd(this, _commit, (batch) => {
if (!__privateGet(this, _batches).has(batch)) return;
var key2 = (
/** @type {Key} */
__privateGet(this, _batches).get(batch)
);
var onscreen = __privateGet(this, _onscreen).get(key2);
if (onscreen) {
resume_effect(onscreen);
__privateGet(this, _outroing).delete(key2);
} else {
var offscreen = __privateGet(this, _offscreen).get(key2);
if (offscreen) {
resume_effect(offscreen.effect);
__privateGet(this, _onscreen).set(key2, offscreen.effect);
__privateGet(this, _offscreen).delete(key2);
if (dev_fallback_default) {
offscreen.fragment.lastChild[HMR_ANCHOR] = this.anchor;
}
offscreen.fragment.lastChild.remove();
this.anchor.before(offscreen.fragment);
onscreen = offscreen.effect;
}
}
for (const [b, k] of __privateGet(this, _batches)) {
__privateGet(this, _batches).delete(b);
if (b === batch) {
break;
}
const offscreen2 = __privateGet(this, _offscreen).get(k);
if (offscreen2) {
destroy_effect(offscreen2.effect);
__privateGet(this, _offscreen).delete(k);
}
}
for (const [k, effect2] of __privateGet(this, _onscreen)) {
if (k === key2 || __privateGet(this, _outroing).has(k)) continue;
const on_destroy = () => {
const keys = Array.from(__privateGet(this, _batches).values());
if (keys.includes(k)) {
var fragment = document.createDocumentFragment();
move_effect(effect2, fragment);
fragment.append(create_text());
__privateGet(this, _offscreen).set(k, { effect: effect2, fragment });
} else {
destroy_effect(effect2);
}
__privateGet(this, _outroing).delete(k);
__privateGet(this, _onscreen).delete(k);
};
if (__privateGet(this, _transition) || !onscreen) {
__privateGet(this, _outroing).add(k);
pause_effect(effect2, on_destroy, false);
} else {
on_destroy();
}
}
});
/**
* @param {Batch} batch
*/
__privateAdd(this, _discard, (batch) => {
__privateGet(this, _batches).delete(batch);
const keys = Array.from(__privateGet(this, _batches).values());
for (const [k, branch2] of __privateGet(this, _offscreen)) {
if (!keys.includes(k)) {
destroy_effect(branch2.effect);
__privateGet(this, _offscreen).delete(k);
}
}
});
this.anchor = anchor;
__privateSet(this, _transition, transition2);
}
/**
*
* @param {any} key
* @param {null | ((target: TemplateNode) => void)} fn
*/
ensure(key2, fn) {
var batch = (
/** @type {Batch} */
current_batch
);
var defer = should_defer_append();
if (fn && !__privateGet(this, _onscreen).has(key2) && !__privateGet(this, _offscreen).has(key2)) {
if (defer) {
var fragment = document.createDocumentFragment();
var target = create_text();
fragment.append(target);
__privateGet(this, _offscreen).set(key2, {
effect: branch(() => fn(target)),
fragment
});
} else {
__privateGet(this, _onscreen).set(
key2,
branch(() => fn(this.anchor))
);
}
}
__privateGet(this, _batches).set(batch, key2);
if (defer) {
for (const [k, effect2] of __privateGet(this, _onscreen)) {
if (k === key2) {
batch.unskip_effect(effect2);
} else {
batch.skip_effect(effect2);
}
}
for (const [k, branch2] of __privateGet(this, _offscreen)) {
if (k === key2) {
batch.unskip_effect(branch2.effect);
} else {
batch.skip_effect(branch2.effect);
}
}
batch.oncommit(__privateGet(this, _commit));
batch.ondiscard(__privateGet(this, _discard));
} else {
if (hydrating) {
this.anchor = hydrate_node;
}
__privateGet(this, _commit).call(this, batch);
}
}
};
_batches = new WeakMap();
_onscreen = new WeakMap();
_offscreen = new WeakMap();
_outroing = new WeakMap();
_transition = new WeakMap();
_commit = new WeakMap();
_discard = new WeakMap();
// node_modules/svelte/src/index-client.js
if (dev_fallback_default) {
let throw_rune_error = function(rune) {
if (!(rune in globalThis)) {
let value;
Object.defineProperty(globalThis, rune, {
configurable: true,
// eslint-disable-next-line getter-return
get: () => {
if (value !== void 0) {
return value;
}
rune_outside_svelte(rune);
},
set: (v) => {
value = v;
}
});
}
};
throw_rune_error("$state");
throw_rune_error("$effect");
throw_rune_error("$derived");
throw_rune_error("$inspect");
throw_rune_error("$props");
throw_rune_error("$bindable");
}
function onMount(fn) {
if (component_context === null) {
lifecycle_outside_component("onMount");
}
if (legacy_mode_flag && component_context.l !== null) {
init_update_callbacks(component_context).m.push(fn);
} else {
user_effect(() => {
const cleanup = untrack(fn);
if (typeof cleanup === "function") return (
/** @type {() => void} */
cleanup
);
});
}
}
function onDestroy(fn) {
if (component_context === null) {
lifecycle_outside_component("onDestroy");
}
onMount(() => () => untrack(fn));
}
function create_custom_event(type2, detail, { bubbles = false, cancelable = false } = {}) {
return new CustomEvent(type2, { detail, bubbles, cancelable });
}
function createEventDispatcher() {
const active_component_context = component_context;
if (active_component_context === null) {
lifecycle_outside_component("createEventDispatcher");
}
return (type2, detail, options) => {
var _a5;
const events = (
/** @type {Record<string, Function | Function[]>} */
(_a5 = active_component_context.s.$$events) == null ? void 0 : _a5[
/** @type {string} */
type2
]
);
if (events) {
const callbacks = is_array(events) ? events.slice() : [events];
const event2 = create_custom_event(
/** @type {string} */
type2,
detail,
options
);
for (const fn of callbacks) {
fn.call(active_component_context.x, event2);
}
return !event2.defaultPrevented;
}
return true;
};
}
function init_update_callbacks(context) {
var _a5;
var l = (
/** @type {ComponentContextLegacy} */
context.l
);
return (_a5 = l.u) != null ? _a5 : l.u = { a: [], b: [], m: [] };
}
// node_modules/svelte/src/internal/client/dev/css.js
var all_styles = /* @__PURE__ */ new Map();
function register_style(hash2, style) {
var styles = all_styles.get(hash2);
if (!styles) {
styles = /* @__PURE__ */ new Set();
all_styles.set(hash2, styles);
}
styles.add(style);
}
// node_modules/svelte/src/internal/client/dom/blocks/if.js
function if_block(node, fn, elseif = false) {
var marker;
if (hydrating) {
marker = hydrate_node;
hydrate_next();
}
var branches = new BranchManager(node);
var flags2 = elseif ? EFFECT_TRANSPARENT : 0;
function update_branch(key2, fn2) {
if (hydrating) {
var data = read_hydration_instruction(
/** @type {TemplateNode} */
marker
);
if (key2 !== parseInt(data.substring(1))) {
var anchor = skip_nodes();
set_hydrate_node(anchor);
branches.anchor = anchor;
set_hydrating(false);
branches.ensure(key2, fn2);
set_hydrating(true);
return;
}
}
branches.ensure(key2, fn2);
}
block(() => {
var has_branch = false;
fn((fn2, key2 = 0) => {
has_branch = true;
update_branch(key2, fn2);
});
if (!has_branch) {
update_branch(-1, null);
}
}, flags2);
}
// node_modules/svelte/src/internal/client/dom/blocks/each.js
function index(_, i) {
return i;
}
function pause_effects(state2, to_destroy, controlled_anchor) {
var _a5;
var transitions = [];
var length = to_destroy.length;
var group;
var remaining = to_destroy.length;
for (var i = 0; i < length; i++) {
let effect2 = to_destroy[i];
pause_effect(
effect2,
() => {
if (group) {
group.pending.delete(effect2);
group.done.add(effect2);
if (group.pending.size === 0) {
var groups = (
/** @type {Set<EachOutroGroup>} */
state2.outrogroups
);
destroy_effects(state2, array_from(group.done));
groups.delete(group);
if (groups.size === 0) {
state2.outrogroups = null;
}
}
} else {
remaining -= 1;
}
},
false
);
}
if (remaining === 0) {
var fast_path = transitions.length === 0 && controlled_anchor !== null;
if (fast_path) {
var anchor = (
/** @type {Element} */
controlled_anchor
);
var parent_node = (
/** @type {Element} */
anchor.parentNode
);
clear_text_content(parent_node);
parent_node.append(anchor);
state2.items.clear();
}
destroy_effects(state2, to_destroy, !fast_path);
} else {
group = {
pending: new Set(to_destroy),
done: /* @__PURE__ */ new Set()
};
((_a5 = state2.outrogroups) != null ? _a5 : state2.outrogroups = /* @__PURE__ */ new Set()).add(group);
}
}
function destroy_effects(state2, to_destroy, remove_dom = true) {
var preserved_effects;
if (state2.pending.size > 0) {
preserved_effects = /* @__PURE__ */ new Set();
for (const keys of state2.pending.values()) {
for (const key2 of keys) {
preserved_effects.add(
/** @type {EachItem} */
state2.items.get(key2).e
);
}
}
}
for (var i = 0; i < to_destroy.length; i++) {
var e = to_destroy[i];
if (preserved_effects == null ? void 0 : preserved_effects.has(e)) {
e.f |= EFFECT_OFFSCREEN;
const fragment = document.createDocumentFragment();
move_effect(e, fragment);
} else {
destroy_effect(to_destroy[i], remove_dom);
}
}
}
var offscreen_anchor;
function each(node, flags2, get_collection, get_key, render_fn2, fallback_fn = null) {
var anchor = node;
var items = /* @__PURE__ */ new Map();
var is_controlled = (flags2 & EACH_IS_CONTROLLED) !== 0;
if (is_controlled) {
var parent_node = (
/** @type {Element} */
node
);
anchor = hydrating ? set_hydrate_node(get_first_child(parent_node)) : parent_node.appendChild(create_text());
}
if (hydrating) {
hydrate_next();
}
var fallback2 = null;
var each_array = derived_safe_equal(() => {
var collection = get_collection();
return is_array(collection) ? collection : collection == null ? [] : array_from(collection);
});
if (dev_fallback_default) {
tag(each_array, "{#each ...}");
}
var array;
var pending2 = /* @__PURE__ */ new Map();
var first_run = true;
function commit(batch) {
if ((state2.effect.f & DESTROYED) !== 0) {
return;
}
state2.pending.delete(batch);
state2.fallback = fallback2;
reconcile(state2, array, anchor, flags2, get_key);
if (fallback2 !== null) {
if (array.length === 0) {
if ((fallback2.f & EFFECT_OFFSCREEN) === 0) {
resume_effect(fallback2);
} else {
fallback2.f ^= EFFECT_OFFSCREEN;
move(fallback2, null, anchor);
}
} else {
pause_effect(fallback2, () => {
fallback2 = null;
});
}
}
}
function discard(batch) {
state2.pending.delete(batch);
}
var effect2 = block(() => {
array = /** @type {V[]} */
get(each_array);
var length = array.length;
let mismatch = false;
if (hydrating) {
var is_else = read_hydration_instruction(anchor) === HYDRATION_START_ELSE;
if (is_else !== (length === 0)) {
anchor = skip_nodes();
set_hydrate_node(anchor);
set_hydrating(false);
mismatch = true;
}
}
var keys = /* @__PURE__ */ new Set();
var batch = (
/** @type {Batch} */
current_batch
);
var defer = should_defer_append();
for (var index2 = 0; index2 < length; index2 += 1) {
if (hydrating && hydrate_node.nodeType === COMMENT_NODE && /** @type {Comment} */
hydrate_node.data === HYDRATION_END) {
anchor = /** @type {Comment} */
hydrate_node;
mismatch = true;
set_hydrating(false);
}
var value = array[index2];
var key2 = get_key(value, index2);
if (dev_fallback_default) {
var key_again = get_key(value, index2);
if (key2 !== key_again) {
each_key_volatile(String(index2), String(key2), String(key_again));
}
}
var item = first_run ? null : items.get(key2);
if (item) {
if (item.v) internal_set(item.v, value);
if (item.i) internal_set(item.i, index2);
if (defer) {
batch.unskip_effect(item.e);
}
} else {
item = create_item(
items,
first_run ? anchor : offscreen_anchor != null ? offscreen_anchor : offscreen_anchor = create_text(),
value,
key2,
index2,
render_fn2,
flags2,
get_collection
);
if (!first_run) {
item.e.f |= EFFECT_OFFSCREEN;
}
items.set(key2, item);
}
keys.add(key2);
}
if (length === 0 && fallback_fn && !fallback2) {
if (first_run) {
fallback2 = branch(() => fallback_fn(anchor));
} else {
fallback2 = branch(() => fallback_fn(offscreen_anchor != null ? offscreen_anchor : offscreen_anchor = create_text()));
fallback2.f |= EFFECT_OFFSCREEN;
}
}
if (length > keys.size) {
if (dev_fallback_default) {
validate_each_keys(array, get_key);
} else {
each_key_duplicate("", "", "");
}
}
if (hydrating && length > 0) {
set_hydrate_node(skip_nodes());
}
if (!first_run) {
pending2.set(batch, keys);
if (defer) {
for (const [key3, item2] of items) {
if (!keys.has(key3)) {
batch.skip_effect(item2.e);
}
}
batch.oncommit(commit);
batch.ondiscard(discard);
} else {
commit(batch);
}
}
if (mismatch) {
set_hydrating(true);
}
get(each_array);
});
var state2 = { effect: effect2, flags: flags2, items, pending: pending2, outrogroups: null, fallback: fallback2 };
first_run = false;
if (hydrating) {
anchor = hydrate_node;
}
}
function skip_to_branch(effect2) {
while (effect2 !== null && (effect2.f & BRANCH_EFFECT) === 0) {
effect2 = effect2.next;
}
return effect2;
}
function reconcile(state2, array, anchor, flags2, get_key) {
var _a5, _b3, _c2, _d, _e, _f, _g, _h, _i;
var is_animated = (flags2 & EACH_IS_ANIMATED) !== 0;
var length = array.length;
var items = state2.items;
var current = skip_to_branch(state2.effect.first);
var seen;
var prev = null;
var to_animate;
var matched = [];
var stashed = [];
var value;
var key2;
var effect2;
var i;
if (is_animated) {
for (i = 0; i < length; i += 1) {
value = array[i];
key2 = get_key(value, i);
effect2 = /** @type {EachItem} */
items.get(key2).e;
if ((effect2.f & EFFECT_OFFSCREEN) === 0) {
(_b3 = (_a5 = effect2.nodes) == null ? void 0 : _a5.a) == null ? void 0 : _b3.measure();
(to_animate != null ? to_animate : to_animate = /* @__PURE__ */ new Set()).add(effect2);
}
}
}
for (i = 0; i < length; i += 1) {
value = array[i];
key2 = get_key(value, i);
effect2 = /** @type {EachItem} */
items.get(key2).e;
if (state2.outrogroups !== null) {
for (const group of state2.outrogroups) {
group.pending.delete(effect2);
group.done.delete(effect2);
}
}
if ((effect2.f & INERT) !== 0) {
resume_effect(effect2);
if (is_animated) {
(_d = (_c2 = effect2.nodes) == null ? void 0 : _c2.a) == null ? void 0 : _d.unfix();
(to_animate != null ? to_animate : to_animate = /* @__PURE__ */ new Set()).delete(effect2);
}
}
if ((effect2.f & EFFECT_OFFSCREEN) !== 0) {
effect2.f ^= EFFECT_OFFSCREEN;
if (effect2 === current) {
move(effect2, null, anchor);
} else {
var next2 = prev ? prev.next : current;
if (effect2 === state2.effect.last) {
state2.effect.last = effect2.prev;
}
if (effect2.prev) effect2.prev.next = effect2.next;
if (effect2.next) effect2.next.prev = effect2.prev;
link(state2, prev, effect2);
link(state2, effect2, next2);
move(effect2, next2, anchor);
prev = effect2;
matched = [];
stashed = [];
current = skip_to_branch(prev.next);
continue;
}
}
if (effect2 !== current) {
if (seen !== void 0 && seen.has(effect2)) {
if (matched.length < stashed.length) {
var start = stashed[0];
var j;
prev = start.prev;
var a = matched[0];
var b = matched[matched.length - 1];
for (j = 0; j < matched.length; j += 1) {
move(matched[j], start, anchor);
}
for (j = 0; j < stashed.length; j += 1) {
seen.delete(stashed[j]);
}
link(state2, a.prev, b.next);
link(state2, prev, a);
link(state2, b, start);
current = start;
prev = b;
i -= 1;
matched = [];
stashed = [];
} else {
seen.delete(effect2);
move(effect2, current, anchor);
link(state2, effect2.prev, effect2.next);
link(state2, effect2, prev === null ? state2.effect.first : prev.next);
link(state2, prev, effect2);
prev = effect2;
}
continue;
}
matched = [];
stashed = [];
while (current !== null && current !== effect2) {
(seen != null ? seen : seen = /* @__PURE__ */ new Set()).add(current);
stashed.push(current);
current = skip_to_branch(current.next);
}
if (current === null) {
continue;
}
}
if ((effect2.f & EFFECT_OFFSCREEN) === 0) {
matched.push(effect2);
}
prev = effect2;
current = skip_to_branch(effect2.next);
}
if (state2.outrogroups !== null) {
for (const group of state2.outrogroups) {
if (group.pending.size === 0) {
destroy_effects(state2, array_from(group.done));
(_e = state2.outrogroups) == null ? void 0 : _e.delete(group);
}
}
if (state2.outrogroups.size === 0) {
state2.outrogroups = null;
}
}
if (current !== null || seen !== void 0) {
var to_destroy = [];
if (seen !== void 0) {
for (effect2 of seen) {
if ((effect2.f & INERT) === 0) {
to_destroy.push(effect2);
}
}
}
while (current !== null) {
if ((current.f & INERT) === 0 && current !== state2.fallback) {
to_destroy.push(current);
}
current = skip_to_branch(current.next);
}
var destroy_length = to_destroy.length;
if (destroy_length > 0) {
var controlled_anchor = (flags2 & EACH_IS_CONTROLLED) !== 0 && length === 0 ? anchor : null;
if (is_animated) {
for (i = 0; i < destroy_length; i += 1) {
(_g = (_f = to_destroy[i].nodes) == null ? void 0 : _f.a) == null ? void 0 : _g.measure();
}
for (i = 0; i < destroy_length; i += 1) {
(_i = (_h = to_destroy[i].nodes) == null ? void 0 : _h.a) == null ? void 0 : _i.fix();
}
}
pause_effects(state2, to_destroy, controlled_anchor);
}
}
if (is_animated) {
queue_micro_task(() => {
var _a6, _b4;
if (to_animate === void 0) return;
for (effect2 of to_animate) {
(_b4 = (_a6 = effect2.nodes) == null ? void 0 : _a6.a) == null ? void 0 : _b4.apply();
}
});
}
}
function create_item(items, anchor, value, key2, index2, render_fn2, flags2, get_collection) {
var v = (flags2 & EACH_ITEM_REACTIVE) !== 0 ? (flags2 & EACH_ITEM_IMMUTABLE) === 0 ? mutable_source(value, false, false) : source(value) : null;
var i = (flags2 & EACH_INDEX_REACTIVE) !== 0 ? source(index2) : null;
if (dev_fallback_default && v) {
v.trace = () => {
var _a5;
get_collection()[(_a5 = i == null ? void 0 : i.v) != null ? _a5 : index2];
};
}
return {
v,
i,
e: branch(() => {
render_fn2(anchor, v != null ? v : value, i != null ? i : index2, get_collection);
return () => {
items.delete(key2);
};
})
};
}
function move(effect2, next2, anchor) {
if (!effect2.nodes) return;
var node = effect2.nodes.start;
var end = effect2.nodes.end;
var dest = next2 && (next2.f & EFFECT_OFFSCREEN) === 0 ? (
/** @type {EffectNodes} */
next2.nodes.start
) : anchor;
while (node !== null) {
var next_node = (
/** @type {TemplateNode} */
get_next_sibling(node)
);
dest.before(node);
if (node === end) {
return;
}
node = next_node;
}
}
function link(state2, prev, next2) {
if (prev === null) {
state2.effect.first = next2;
} else {
prev.next = next2;
}
if (next2 === null) {
state2.effect.last = prev;
} else {
next2.prev = prev;
}
}
function validate_each_keys(array, key_fn) {
const keys = /* @__PURE__ */ new Map();
const length = array.length;
for (let i = 0; i < length; i++) {
const key2 = key_fn(array[i], i);
if (keys.has(key2)) {
const a = String(keys.get(key2));
const b = String(i);
let k = String(key2);
if (k.startsWith("[object ")) k = null;
each_key_duplicate(a, b, k);
}
keys.set(key2, i);
}
}
// node_modules/svelte/src/internal/client/dom/blocks/slot.js
function slot(anchor, $$props, name, slot_props, fallback_fn) {
var _a5;
if (hydrating) {
hydrate_next();
}
var slot_fn = (_a5 = $$props.$$slots) == null ? void 0 : _a5[name];
var is_interop = false;
if (slot_fn === true) {
slot_fn = $$props[name === "default" ? "children" : name];
is_interop = true;
}
if (slot_fn === void 0) {
if (fallback_fn !== null) {
fallback_fn(anchor);
}
} else {
slot_fn(anchor, is_interop ? () => slot_props : slot_props);
}
}
// node_modules/svelte/src/internal/client/timing.js
var now = true_default ? () => performance.now() : () => Date.now();
var raf = {
// don't access requestAnimationFrame eagerly outside method
// this allows basic testing of user code without JSDOM
// bunder will eval and remove ternary when the user's app is built
tick: (
/** @param {any} _ */
(_) => (true_default ? requestAnimationFrame : noop)(_)
),
now: () => now(),
tasks: /* @__PURE__ */ new Set()
};
// node_modules/svelte/src/internal/client/loop.js
function run_tasks() {
const now2 = raf.now();
raf.tasks.forEach((task) => {
if (!task.c(now2)) {
raf.tasks.delete(task);
task.f();
}
});
if (raf.tasks.size !== 0) {
raf.tick(run_tasks);
}
}
function loop(callback) {
let task;
if (raf.tasks.size === 0) {
raf.tick(run_tasks);
}
return {
promise: new Promise((fulfill) => {
raf.tasks.add(task = { c: callback, f: fulfill });
}),
abort() {
raf.tasks.delete(task);
}
};
}
// node_modules/svelte/src/internal/client/dom/elements/transitions.js
function dispatch_event(element2, type2) {
without_reactive_context(() => {
element2.dispatchEvent(new CustomEvent(type2));
});
}
function css_property_to_camelcase(style) {
if (style === "float") return "cssFloat";
if (style === "offset") return "cssOffset";
if (style.startsWith("--")) return style;
const parts = style.split("-");
if (parts.length === 1) return parts[0];
return parts[0] + parts.slice(1).map(
/** @param {any} word */
(word) => word[0].toUpperCase() + word.slice(1)
).join("");
}
function css_to_keyframe(css) {
const keyframe = {};
const parts = css.split(";");
for (const part of parts) {
const [property, value] = part.split(":");
if (!property || value === void 0) break;
const formatted_property = css_property_to_camelcase(property.trim());
keyframe[formatted_property] = value.trim();
}
return keyframe;
}
var linear = (t) => t;
function transition(flags2, element2, get_fn, get_params) {
var _a5, _b3;
var is_intro = (flags2 & TRANSITION_IN) !== 0;
var is_outro = (flags2 & TRANSITION_OUT) !== 0;
var is_both = is_intro && is_outro;
var is_global = (flags2 & TRANSITION_GLOBAL) !== 0;
var direction = is_both ? "both" : is_intro ? "in" : "out";
var current_options;
var inert = element2.inert;
var overflow = element2.style.overflow;
var intro;
var outro;
function get_options() {
return without_reactive_context(() => {
var _a6;
return current_options != null ? current_options : current_options = get_fn()(element2, (_a6 = get_params == null ? void 0 : get_params()) != null ? _a6 : (
/** @type {P} */
{}
), {
direction
});
});
}
var transition2 = {
is_global,
in() {
var _a6;
element2.inert = inert;
if (!is_intro) {
outro == null ? void 0 : outro.abort();
(_a6 = outro == null ? void 0 : outro.reset) == null ? void 0 : _a6.call(outro);
return;
}
if (!is_outro) {
intro == null ? void 0 : intro.abort();
}
intro = animate(
element2,
get_options(),
outro,
1,
() => {
dispatch_event(element2, "introstart");
},
() => {
dispatch_event(element2, "introend");
intro == null ? void 0 : intro.abort();
intro = current_options = void 0;
element2.style.overflow = overflow;
}
);
},
out(fn) {
if (!is_outro) {
fn == null ? void 0 : fn();
current_options = void 0;
return;
}
element2.inert = true;
outro = animate(
element2,
get_options(),
intro,
0,
() => {
dispatch_event(element2, "outrostart");
},
() => {
dispatch_event(element2, "outroend");
fn == null ? void 0 : fn();
}
);
},
stop: () => {
intro == null ? void 0 : intro.abort();
outro == null ? void 0 : outro.abort();
}
};
var e = (
/** @type {Effect & { nodes: EffectNodes }} */
active_effect
);
((_b3 = (_a5 = e.nodes).t) != null ? _b3 : _a5.t = []).push(transition2);
if (is_intro && should_intro) {
var run3 = is_global;
if (!run3) {
var block2 = (
/** @type {Effect | null} */
e.parent
);
while (block2 && (block2.f & EFFECT_TRANSPARENT) !== 0) {
while (block2 = block2.parent) {
if ((block2.f & BLOCK_EFFECT) !== 0) break;
}
}
run3 = !block2 || (block2.f & REACTION_RAN) !== 0;
}
if (run3) {
effect(() => {
untrack(() => transition2.in());
});
}
}
}
function animate(element2, options, counterpart, t2, on_begin, on_finish) {
var is_intro = t2 === 1;
if (is_function(options)) {
var a;
var aborted2 = false;
queue_micro_task(() => {
if (aborted2) return;
var o = options({ direction: is_intro ? "in" : "out" });
a = animate(element2, o, counterpart, t2, on_begin, on_finish);
});
return {
abort: () => {
aborted2 = true;
a == null ? void 0 : a.abort();
},
deactivate: () => a.deactivate(),
reset: () => a.reset(),
t: () => a.t()
};
}
counterpart == null ? void 0 : counterpart.deactivate();
if (!(options == null ? void 0 : options.duration) && !(options == null ? void 0 : options.delay)) {
on_begin();
on_finish();
return {
abort: noop,
deactivate: noop,
reset: noop,
t: () => t2
};
}
const { delay = 0, css, tick: tick2, easing = linear } = options;
var keyframes = [];
if (is_intro && counterpart === void 0) {
if (tick2) {
tick2(0, 1);
}
if (css) {
var styles = css_to_keyframe(css(0, 1));
keyframes.push(styles, styles);
}
}
var get_t = () => 1 - t2;
var animation2 = element2.animate(keyframes, { duration: delay, fill: "forwards" });
animation2.onfinish = () => {
var _a5;
animation2.cancel();
on_begin();
var t1 = (_a5 = counterpart == null ? void 0 : counterpart.t()) != null ? _a5 : 1 - t2;
counterpart == null ? void 0 : counterpart.abort();
var delta = t2 - t1;
var duration = (
/** @type {number} */
options.duration * Math.abs(delta)
);
var keyframes2 = [];
if (duration > 0) {
var needs_overflow_hidden = false;
if (css) {
var n = Math.ceil(duration / (1e3 / 60));
for (var i = 0; i <= n; i += 1) {
var t = t1 + delta * easing(i / n);
var styles2 = css_to_keyframe(css(t, 1 - t));
keyframes2.push(styles2);
needs_overflow_hidden || (needs_overflow_hidden = styles2.overflow === "hidden");
}
}
if (needs_overflow_hidden) {
element2.style.overflow = "hidden";
}
get_t = () => {
var time = (
/** @type {number} */
/** @type {globalThis.Animation} */
animation2.currentTime
);
return t1 + delta * easing(time / duration);
};
if (tick2) {
loop(() => {
if (animation2.playState !== "running") return false;
var t3 = get_t();
tick2(t3, 1 - t3);
return true;
});
}
}
animation2 = element2.animate(keyframes2, { duration, fill: "forwards" });
animation2.onfinish = () => {
get_t = () => t2;
tick2 == null ? void 0 : tick2(t2, 1 - t2);
on_finish();
};
};
return {
abort: () => {
if (animation2) {
animation2.cancel();
animation2.effect = null;
animation2.onfinish = noop;
}
},
deactivate: () => {
on_finish = noop;
},
reset: () => {
if (t2 === 0) {
tick2 == null ? void 0 : tick2(1, 0);
}
},
t: () => get_t()
};
}
// node_modules/svelte/src/internal/client/dom/css.js
function append_styles(anchor, css) {
effect(() => {
var _a5;
var root24 = anchor.getRootNode();
var target = (
/** @type {ShadowRoot} */
root24.host ? (
/** @type {ShadowRoot} */
root24
) : (
/** @type {Document} */
(_a5 = root24.head) != null ? _a5 : (
/** @type {Document} */
root24.ownerDocument.head
)
)
);
if (!target.querySelector("#" + css.hash)) {
const style = create_element("style");
style.id = css.hash;
style.textContent = css.code;
target.appendChild(style);
if (dev_fallback_default) {
register_style(css.hash, style);
}
}
});
}
// node_modules/svelte/src/internal/client/dom/elements/actions.js
function action(dom, action2, get_value) {
effect(() => {
var payload = untrack(() => action2(dom, get_value == null ? void 0 : get_value()) || {});
if (get_value && (payload == null ? void 0 : payload.update)) {
var inited = false;
var prev = (
/** @type {any} */
{}
);
render_effect(() => {
var value = get_value();
deep_read_state(value);
if (inited && safe_not_equal(prev, value)) {
prev = value;
payload.update(value);
}
});
inited = true;
}
if (payload == null ? void 0 : payload.destroy) {
return () => (
/** @type {Function} */
payload.destroy()
);
}
});
}
// node_modules/svelte/src/internal/client/dom/elements/attachments.js
function attach(node, get_fn) {
var fn = void 0;
var e;
managed(() => {
if (fn !== (fn = get_fn())) {
if (e) {
destroy_effect(e);
e = null;
}
if (fn) {
e = branch(() => {
effect(() => (
/** @type {(node: Element) => void} */
fn(node)
));
});
}
}
});
}
// node_modules/clsx/dist/clsx.mjs
function r(e) {
var t, f, n = "";
if ("string" == typeof e || "number" == typeof e) n += e;
else if ("object" == typeof e) if (Array.isArray(e)) {
var o = e.length;
for (t = 0; t < o; t++) e[t] && (f = r(e[t])) && (n && (n += " "), n += f);
} else for (f in e) e[f] && (n && (n += " "), n += f);
return n;
}
function clsx() {
for (var e, t, f = 0, n = "", o = arguments.length; f < o; f++) (e = arguments[f]) && (t = r(e)) && (n && (n += " "), n += t);
return n;
}
// node_modules/svelte/src/internal/shared/attributes.js
function clsx2(value) {
if (typeof value === "object") {
return clsx(value);
} else {
return value != null ? value : "";
}
}
var whitespace = [..." \n\r\f\xA0\v\uFEFF"];
function to_class(value, hash2, directives) {
var classname = value == null ? "" : "" + value;
if (hash2) {
classname = classname ? classname + " " + hash2 : hash2;
}
if (directives) {
for (var key2 of Object.keys(directives)) {
if (directives[key2]) {
classname = classname ? classname + " " + key2 : key2;
} else if (classname.length) {
var len = key2.length;
var a = 0;
while ((a = classname.indexOf(key2, a)) >= 0) {
var b = a + len;
if ((a === 0 || whitespace.includes(classname[a - 1])) && (b === classname.length || whitespace.includes(classname[b]))) {
classname = (a === 0 ? "" : classname.substring(0, a)) + classname.substring(b + 1);
} else {
a = b;
}
}
}
}
}
return classname === "" ? null : classname;
}
function append_styles2(styles, important = false) {
var separator = important ? " !important;" : ";";
var css = "";
for (var key2 of Object.keys(styles)) {
var value = styles[key2];
if (value != null && value !== "") {
css += " " + key2 + ": " + value + separator;
}
}
return css;
}
function to_css_name(name) {
if (name[0] !== "-" || name[1] !== "-") {
return name.toLowerCase();
}
return name;
}
function to_style(value, styles) {
if (styles) {
var new_style = "";
var normal_styles;
var important_styles;
if (Array.isArray(styles)) {
normal_styles = styles[0];
important_styles = styles[1];
} else {
normal_styles = styles;
}
if (value) {
value = String(value).replaceAll(/\s*\/\*.*?\*\/\s*/g, "").trim();
var in_str = false;
var in_apo = 0;
var in_comment = false;
var reserved_names = [];
if (normal_styles) {
reserved_names.push(...Object.keys(normal_styles).map(to_css_name));
}
if (important_styles) {
reserved_names.push(...Object.keys(important_styles).map(to_css_name));
}
var start_index = 0;
var name_index = -1;
const len = value.length;
for (var i = 0; i < len; i++) {
var c = value[i];
if (in_comment) {
if (c === "/" && value[i - 1] === "*") {
in_comment = false;
}
} else if (in_str) {
if (in_str === c) {
in_str = false;
}
} else if (c === "/" && value[i + 1] === "*") {
in_comment = true;
} else if (c === '"' || c === "'") {
in_str = c;
} else if (c === "(") {
in_apo++;
} else if (c === ")") {
in_apo--;
}
if (!in_comment && in_str === false && in_apo === 0) {
if (c === ":" && name_index === -1) {
name_index = i;
} else if (c === ";" || i === len - 1) {
if (name_index !== -1) {
var name = to_css_name(value.substring(start_index, name_index).trim());
if (!reserved_names.includes(name)) {
if (c !== ";") {
i++;
}
var property = value.substring(start_index, i).trim();
new_style += " " + property + ";";
}
}
start_index = i + 1;
name_index = -1;
}
}
}
}
if (normal_styles) {
new_style += append_styles2(normal_styles);
}
if (important_styles) {
new_style += append_styles2(important_styles, true);
}
new_style = new_style.trim();
return new_style === "" ? null : new_style;
}
return value == null ? null : String(value);
}
// node_modules/svelte/src/internal/client/dom/elements/class.js
function set_class(dom, is_html, value, hash2, prev_classes, next_classes) {
var prev = (
/** @type {any} */
dom[CLASS_CACHE]
);
if (hydrating || prev !== value || prev === void 0) {
var next_class_name = to_class(value, hash2, next_classes);
if (!hydrating || next_class_name !== dom.getAttribute("class")) {
if (next_class_name == null) {
dom.removeAttribute("class");
} else if (is_html) {
dom.className = next_class_name;
} else {
dom.setAttribute("class", next_class_name);
}
}
dom[CLASS_CACHE] = value;
} else if (next_classes && prev_classes !== next_classes) {
for (var key2 in next_classes) {
var is_present = !!next_classes[key2];
if (prev_classes == null || is_present !== !!prev_classes[key2]) {
dom.classList.toggle(key2, is_present);
}
}
}
return next_classes;
}
// node_modules/svelte/src/internal/client/dom/elements/style.js
function update_styles(dom, prev = {}, next2, priority) {
for (var key2 in next2) {
var value = next2[key2];
if (prev[key2] !== value) {
if (next2[key2] == null) {
dom.style.removeProperty(key2);
} else {
dom.style.setProperty(key2, value, priority);
}
}
}
}
function set_style(dom, value, prev_styles, next_styles) {
var prev = (
/** @type {any} */
dom[STYLE_CACHE]
);
if (hydrating || prev !== value) {
var next_style_attr = to_style(value, next_styles);
if (!hydrating || next_style_attr !== dom.getAttribute("style")) {
if (next_style_attr == null) {
dom.removeAttribute("style");
} else {
dom.style.cssText = next_style_attr;
}
}
dom[STYLE_CACHE] = value;
} else if (next_styles) {
if (Array.isArray(next_styles)) {
update_styles(dom, prev_styles == null ? void 0 : prev_styles[0], next_styles[0]);
update_styles(dom, prev_styles == null ? void 0 : prev_styles[1], next_styles[1], "important");
} else {
update_styles(dom, prev_styles, next_styles);
}
}
return next_styles;
}
// node_modules/svelte/src/internal/client/dom/elements/bindings/select.js
function select_option(select, value, mounting = false) {
if (select.multiple) {
if (value == void 0) {
return;
}
if (!is_array(value)) {
return select_multiple_invalid_value();
}
for (var option of select.options) {
option.selected = value.includes(get_option_value(option));
}
return;
}
for (option of select.options) {
var option_value = get_option_value(option);
if (is(option_value, value)) {
option.selected = true;
return;
}
}
if (!mounting || value !== void 0) {
select.selectedIndex = -1;
}
}
function init_select(select) {
var observer = new MutationObserver(() => {
select_option(select, select.__value);
});
observer.observe(select, {
// Listen to option element changes
childList: true,
subtree: true,
// because of <optgroup>
// Listen to option element value attribute changes
// (doesn't get notified of select value changes,
// because that property is not reflected as an attribute)
attributes: true,
attributeFilter: ["value"]
});
teardown(() => {
observer.disconnect();
});
}
function get_option_value(option) {
if ("__value" in option) {
return option.__value;
} else {
return option.value;
}
}
// node_modules/svelte/src/internal/client/dom/elements/attributes.js
var CLASS = /* @__PURE__ */ Symbol("class");
var STYLE = /* @__PURE__ */ Symbol("style");
var IS_CUSTOM_ELEMENT = /* @__PURE__ */ Symbol("is custom element");
var IS_HTML = /* @__PURE__ */ Symbol("is html");
var LINK_TAG = IS_XHTML ? "link" : "LINK";
var INPUT_TAG = IS_XHTML ? "input" : "INPUT";
var OPTION_TAG = IS_XHTML ? "option" : "OPTION";
var SELECT_TAG = IS_XHTML ? "select" : "SELECT";
var PROGRESS_TAG = IS_XHTML ? "progress" : "PROGRESS";
function remove_input_defaults(input) {
if (!hydrating) return;
var already_removed = false;
var remove_defaults = () => {
if (already_removed) return;
already_removed = true;
if (input.hasAttribute("value")) {
var value = input.value;
set_attribute2(input, "value", null);
input.value = value;
}
if (input.hasAttribute("checked")) {
var checked = input.checked;
set_attribute2(input, "checked", null);
input.checked = checked;
}
};
input[FORM_RESET_HANDLER] = remove_defaults;
queue_micro_task(remove_defaults);
add_form_reset_listener();
}
function set_value(element2, value) {
var attributes = get_attributes(element2);
if (attributes.value === (attributes.value = // treat null and undefined the same for the initial value
value != null ? value : void 0) || // @ts-expect-error
// `progress` elements always need their value set when it's `0`
element2.value === value && (value !== 0 || element2.nodeName !== PROGRESS_TAG)) {
return;
}
element2.value = value != null ? value : "";
}
function set_checked(element2, checked) {
var attributes = get_attributes(element2);
if (attributes.checked === (attributes.checked = // treat null and undefined the same for the initial value
checked != null ? checked : void 0)) {
return;
}
element2.checked = checked;
}
function set_selected(element2, selected) {
if (selected) {
if (!element2.hasAttribute("selected")) {
element2.setAttribute("selected", "");
}
} else {
element2.removeAttribute("selected");
}
}
function set_attribute2(element2, attribute, value, skip_warning) {
var attributes = get_attributes(element2);
if (hydrating) {
attributes[attribute] = element2.getAttribute(attribute);
if (attribute === "src" || attribute === "srcset" || attribute === "href" && element2.nodeName === LINK_TAG) {
if (!skip_warning) {
check_src_in_dev_hydration(element2, attribute, value != null ? value : "");
}
return;
}
}
if (attributes[attribute] === (attributes[attribute] = value)) return;
if (attribute === "loading") {
element2[LOADING_ATTR_SYMBOL] = value;
}
if (value == null) {
element2.removeAttribute(attribute);
} else if (typeof value !== "string" && get_setters(element2).includes(attribute)) {
element2[attribute] = value;
} else {
element2.setAttribute(attribute, value);
}
}
function set_attributes(element2, prev, next2, css_hash, should_remove_defaults = false, skip_warning = false) {
var _a5;
if (hydrating && should_remove_defaults && element2.nodeName === INPUT_TAG) {
var input = (
/** @type {HTMLInputElement} */
element2
);
var attribute = input.type === "checkbox" ? "defaultChecked" : "defaultValue";
if (!(attribute in next2)) {
remove_input_defaults(input);
}
}
var attributes = get_attributes(element2);
var is_custom_element = attributes[IS_CUSTOM_ELEMENT];
var preserve_attribute_case = !attributes[IS_HTML];
let is_hydrating_custom_element = hydrating && is_custom_element;
if (is_hydrating_custom_element) {
set_hydrating(false);
}
var current = prev || {};
var is_option_element = element2.nodeName === OPTION_TAG;
for (var key2 in prev) {
if (!(key2 in next2)) {
next2[key2] = null;
}
}
if (next2.class) {
next2.class = clsx2(next2.class);
} else if (css_hash || next2[CLASS]) {
next2.class = null;
}
if (next2[STYLE]) {
(_a5 = next2.style) != null ? _a5 : next2.style = null;
}
var setters = get_setters(element2);
for (const key3 in next2) {
let value = next2[key3];
if (is_option_element && key3 === "value" && value == null) {
element2.value = element2.__value = "";
current[key3] = value;
continue;
}
if (key3 === "class") {
var is_html = element2.namespaceURI === "http://www.w3.org/1999/xhtml";
set_class(element2, is_html, value, css_hash, prev == null ? void 0 : prev[CLASS], next2[CLASS]);
current[key3] = value;
current[CLASS] = next2[CLASS];
continue;
}
if (key3 === "style") {
set_style(element2, value, prev == null ? void 0 : prev[STYLE], next2[STYLE]);
current[key3] = value;
current[STYLE] = next2[STYLE];
continue;
}
var prev_value = current[key3];
if (value === prev_value && !(value === void 0 && element2.hasAttribute(key3))) {
continue;
}
current[key3] = value;
var prefix = key3[0] + key3[1];
if (prefix === "$$") continue;
if (prefix === "on") {
const opts = {};
const event_handle_key = "$$" + key3;
let event_name = key3.slice(2);
var is_delegated = can_delegate_event(event_name);
if (is_capture_event(event_name)) {
event_name = event_name.slice(0, -7);
opts.capture = true;
}
if (!is_delegated && prev_value) {
if (value != null) continue;
element2.removeEventListener(event_name, current[event_handle_key], opts);
current[event_handle_key] = null;
}
if (is_delegated) {
delegated(event_name, element2, value);
delegate([event_name]);
} else if (value != null) {
let handle = function(evt) {
current[key3].call(this, evt);
};
current[event_handle_key] = create_event(event_name, element2, handle, opts);
}
} else if (key3 === "style") {
set_attribute2(element2, key3, value);
} else if (key3 === "autofocus") {
autofocus(
/** @type {HTMLElement} */
element2,
Boolean(value)
);
} else if (!is_custom_element && (key3 === "__value" || key3 === "value" && value != null)) {
element2.value = element2.__value = value;
} else if (key3 === "selected" && is_option_element) {
set_selected(
/** @type {HTMLOptionElement} */
element2,
value
);
} else {
var name = key3;
if (!preserve_attribute_case) {
name = normalize_attribute(name);
}
var is_default = name === "defaultValue" || name === "defaultChecked";
if (value == null && !is_custom_element && !is_default) {
attributes[key3] = null;
if (name === "value" || name === "checked") {
let input2 = (
/** @type {HTMLInputElement} */
element2
);
const use_default = prev === void 0;
if (name === "value") {
let previous = input2.defaultValue;
input2.removeAttribute(name);
input2.defaultValue = previous;
input2.value = input2.__value = use_default ? previous : null;
} else {
let previous = input2.defaultChecked;
input2.removeAttribute(name);
input2.defaultChecked = previous;
input2.checked = use_default ? previous : false;
}
} else {
element2.removeAttribute(key3);
}
} else if (is_default || setters.includes(name) && (is_custom_element || typeof value !== "string")) {
element2[name] = value;
if (name in attributes) attributes[name] = UNINITIALIZED;
} else if (typeof value !== "function") {
set_attribute2(element2, name, value, skip_warning);
}
}
}
if (is_hydrating_custom_element) {
set_hydrating(true);
}
return current;
}
function attribute_effect(element2, fn, sync = [], async2 = [], blockers = [], css_hash, should_remove_defaults = false, skip_warning = false) {
flatten(blockers, sync, async2, (values) => {
var prev = void 0;
var effects = {};
var is_select = element2.nodeName === SELECT_TAG;
var inited = false;
managed(() => {
var next2 = fn(...values.map(get));
var current = set_attributes(
element2,
prev,
next2,
css_hash,
should_remove_defaults,
skip_warning
);
if (inited && is_select && "value" in next2) {
select_option(
/** @type {HTMLSelectElement} */
element2,
next2.value
);
}
for (let symbol of Object.getOwnPropertySymbols(effects)) {
if (!next2[symbol]) destroy_effect(effects[symbol]);
}
for (let symbol of Object.getOwnPropertySymbols(next2)) {
var n = next2[symbol];
if (symbol.description === ATTACHMENT_KEY && (!prev || n !== prev[symbol])) {
if (effects[symbol]) destroy_effect(effects[symbol]);
effects[symbol] = branch(() => attach(element2, () => n));
}
current[symbol] = n;
}
prev = current;
});
if (is_select) {
var select = (
/** @type {HTMLSelectElement} */
element2
);
effect(() => {
select_option(
select,
/** @type {Record<string | symbol, any>} */
prev.value,
true
);
init_select(select);
});
}
inited = true;
});
}
function get_attributes(element2) {
var _a5, _b3;
return (
/** @type {Record<string | symbol, unknown>} **/
/** @type {any} */
(_b3 = element2[_a5 = ATTRIBUTES_CACHE]) != null ? _b3 : element2[_a5] = {
[IS_CUSTOM_ELEMENT]: element2.nodeName.includes("-"),
[IS_HTML]: element2.namespaceURI === NAMESPACE_HTML
}
);
}
var setters_cache = /* @__PURE__ */ new Map();
function get_setters(element2) {
var cache_key = element2.getAttribute("is") || element2.nodeName;
var setters = setters_cache.get(cache_key);
if (setters) return setters;
setters_cache.set(cache_key, setters = []);
var descriptors;
var proto = element2;
var element_proto = Element.prototype;
while (element_proto !== proto) {
descriptors = get_descriptors(proto);
for (var key2 in descriptors) {
if (descriptors[key2].set && // better safe than sorry, we don't want spread attributes to mess with HTML content
key2 !== "innerHTML" && key2 !== "textContent" && key2 !== "innerText") {
setters.push(key2);
}
}
proto = get_prototype_of(proto);
}
return setters;
}
function check_src_in_dev_hydration(element2, attribute, value) {
var _a5;
if (!dev_fallback_default) return;
if (attribute === "srcset" && srcset_url_equal(element2, value)) return;
if (src_url_equal((_a5 = element2.getAttribute(attribute)) != null ? _a5 : "", value)) return;
hydration_attribute_changed(
attribute,
element2.outerHTML.replace(element2.innerHTML, element2.innerHTML && "..."),
String(value)
);
}
function src_url_equal(element_src, url) {
if (element_src === url) return true;
return new URL(element_src, document.baseURI).href === new URL(url, document.baseURI).href;
}
function split_srcset(srcset) {
return srcset.split(",").map((src) => src.trim().split(" ").filter(Boolean));
}
function srcset_url_equal(element2, srcset) {
var element_urls = split_srcset(element2.srcset);
var urls = split_srcset(srcset);
return urls.length === element_urls.length && urls.every(
([url, width], i) => width === element_urls[i][1] && // We need to test both ways because Vite will create an a full URL with
// `new URL(asset, import.meta.url).href` for the client when `base: './'`, and the
// relative URLs inside srcset are not automatically resolved to absolute URLs by
// browsers (in contrast to img.src). This means both SSR and DOM code could
// contain relative or absolute URLs.
(src_url_equal(element_urls[i][0], url) || src_url_equal(url, element_urls[i][0]))
);
}
// node_modules/svelte/src/internal/client/dom/elements/bindings/input.js
function bind_value(input, get3, set3 = get3) {
var batches = /* @__PURE__ */ new WeakSet();
listen_to_event_and_reset_event(input, "input", async (is_reset) => {
if (dev_fallback_default && input.type === "checkbox") {
bind_invalid_checkbox_value();
}
var value = is_reset ? input.defaultValue : input.value;
value = is_numberlike_input(input) ? to_number(value) : value;
set3(value);
if (current_batch !== null) {
batches.add(current_batch);
}
await tick();
if (value !== (value = get3())) {
var start = input.selectionStart;
var end = input.selectionEnd;
var length = input.value.length;
input.value = value != null ? value : "";
if (end !== null) {
var new_length = input.value.length;
if (start === end && end === length && new_length > length) {
input.selectionStart = new_length;
input.selectionEnd = new_length;
} else {
input.selectionStart = start;
input.selectionEnd = Math.min(end, new_length);
}
}
}
});
if (
// If we are hydrating and the value has since changed,
// then use the updated value from the input instead.
hydrating && input.defaultValue !== input.value || // If defaultValue is set, then value == defaultValue
// TODO Svelte 6: remove input.value check and set to empty string?
untrack(get3) == null && input.value
) {
set3(is_numberlike_input(input) ? to_number(input.value) : input.value);
if (current_batch !== null) {
batches.add(current_batch);
}
}
render_effect(() => {
if (dev_fallback_default && input.type === "checkbox") {
bind_invalid_checkbox_value();
}
var value = get3();
if (input === document.activeElement) {
var batch = (
/** @type {Batch} */
async_mode_flag ? previous_batch : current_batch
);
if (batches.has(batch)) {
return;
}
}
if (is_numberlike_input(input) && value === to_number(input.value)) {
return;
}
if (input.type === "date" && !value && !input.value) {
return;
}
if (value !== input.value) {
input.value = value != null ? value : "";
}
});
}
function is_numberlike_input(input) {
var type2 = input.type;
return type2 === "number" || type2 === "range";
}
function to_number(value) {
return value === "" ? null : +value;
}
// node_modules/svelte/src/internal/client/dom/elements/bindings/props.js
function bind_prop(props, prop2, value) {
var desc = get_descriptor(props, prop2);
if (desc && desc.set) {
props[prop2] = value;
teardown(() => {
props[prop2] = null;
});
}
}
// node_modules/svelte/src/internal/client/dom/elements/bindings/size.js
var _listeners, _observer, _options, _ResizeObserverSingleton_instances, getObserver_fn;
var _ResizeObserverSingleton = class _ResizeObserverSingleton {
/** @param {ResizeObserverOptions} options */
constructor(options) {
__privateAdd(this, _ResizeObserverSingleton_instances);
/** */
__privateAdd(this, _listeners, /* @__PURE__ */ new WeakMap());
/** @type {ResizeObserver | undefined} */
__privateAdd(this, _observer);
/** @type {ResizeObserverOptions} */
__privateAdd(this, _options);
__privateSet(this, _options, options);
}
/**
* @param {Element} element
* @param {(entry: ResizeObserverEntry) => any} listener
*/
observe(element2, listener) {
var listeners2 = __privateGet(this, _listeners).get(element2) || /* @__PURE__ */ new Set();
listeners2.add(listener);
__privateGet(this, _listeners).set(element2, listeners2);
__privateMethod(this, _ResizeObserverSingleton_instances, getObserver_fn).call(this).observe(element2, __privateGet(this, _options));
return () => {
var listeners3 = __privateGet(this, _listeners).get(element2);
listeners3.delete(listener);
if (listeners3.size === 0) {
__privateGet(this, _listeners).delete(element2);
__privateGet(this, _observer).unobserve(element2);
}
};
}
};
_listeners = new WeakMap();
_observer = new WeakMap();
_options = new WeakMap();
_ResizeObserverSingleton_instances = new WeakSet();
getObserver_fn = function() {
var _a5;
return (_a5 = __privateGet(this, _observer)) != null ? _a5 : __privateSet(this, _observer, new ResizeObserver(
/** @param {any} entries */
(entries) => {
for (var entry of entries) {
_ResizeObserverSingleton.entries.set(entry.target, entry);
for (var listener of __privateGet(this, _listeners).get(entry.target) || []) {
listener(entry);
}
}
}
));
};
/** @static */
__publicField(_ResizeObserverSingleton, "entries", /* @__PURE__ */ new WeakMap());
var ResizeObserverSingleton = _ResizeObserverSingleton;
var resize_observer_border_box = /* @__PURE__ */ new ResizeObserverSingleton({
box: "border-box"
});
function bind_element_size(element2, type2, set3) {
var unsub = resize_observer_border_box.observe(element2, () => set3(element2[type2]));
effect(() => {
untrack(() => set3(element2[type2]));
return unsub;
});
}
// node_modules/svelte/src/internal/client/dom/elements/bindings/this.js
function is_bound_this(bound_value, element_or_component) {
return bound_value === element_or_component || (bound_value == null ? void 0 : bound_value[STATE_SYMBOL]) === element_or_component;
}
function bind_this(element_or_component = {}, update2, get_value, get_parts) {
var component_effect = (
/** @type {ComponentContext} */
component_context.r
);
var parent = (
/** @type {Effect} */
active_effect
);
effect(() => {
var old_parts;
var parts;
render_effect(() => {
old_parts = parts;
parts = (get_parts == null ? void 0 : get_parts()) || [];
untrack(() => {
if (!is_bound_this(get_value(...parts), element_or_component)) {
update2(element_or_component, ...parts);
if (old_parts && is_bound_this(get_value(...old_parts), element_or_component)) {
update2(null, ...old_parts);
}
}
});
});
return () => {
let p = parent;
while (p !== component_effect && p.parent !== null && p.parent.f & DESTROYING) {
p = p.parent;
}
const teardown2 = () => {
if (parts && is_bound_this(get_value(...parts), element_or_component)) {
update2(null, ...parts);
}
};
const original_teardown = p.teardown;
p.teardown = () => {
teardown2();
original_teardown == null ? void 0 : original_teardown();
};
};
});
return element_or_component;
}
// node_modules/svelte/src/internal/client/dom/legacy/lifecycle.js
function init(immutable = false) {
const context = (
/** @type {ComponentContextLegacy} */
component_context
);
const callbacks = context.l.u;
if (!callbacks) return;
let props = () => deep_read_state(context.s);
if (immutable) {
let version = 0;
let prev = (
/** @type {Record<string, any>} */
{}
);
const d = derived2(() => {
let changed = false;
const props2 = context.s;
for (const key2 in props2) {
if (props2[key2] !== prev[key2]) {
prev[key2] = props2[key2];
changed = true;
}
}
if (changed) version++;
return version;
});
props = () => get(d);
}
if (callbacks.b.length) {
user_pre_effect(() => {
observe_all(context, props);
run_all(callbacks.b);
});
}
user_effect(() => {
const fns = untrack(() => callbacks.m.map(run));
return () => {
for (const fn of fns) {
if (typeof fn === "function") {
fn();
}
}
};
});
if (callbacks.a.length) {
user_effect(() => {
observe_all(context, props);
run_all(callbacks.a);
});
}
}
function observe_all(context, props) {
if (context.l.s) {
for (const signal of context.l.s) get(signal);
}
props();
}
// node_modules/svelte/src/internal/client/dom/legacy/misc.js
function bubble_event($$props, event2) {
var _a5;
var events = (
/** @type {Record<string, Function[] | Function>} */
(_a5 = $$props.$$events) == null ? void 0 : _a5[event2.type]
);
var callbacks = is_array(events) ? events.slice() : events == null ? [] : [events];
for (var fn of callbacks) {
fn.call(this, event2);
}
}
function add_legacy_event_listener($$props, event_name, event_callback) {
var _a5;
$$props.$$events || ($$props.$$events = {});
(_a5 = $$props.$$events)[event_name] || (_a5[event_name] = []);
$$props.$$events[event_name].push(event_callback);
}
function update_legacy_props($$new_props) {
for (var key2 in $$new_props) {
if (key2 in this) {
this[key2] = $$new_props[key2];
}
}
}
// node_modules/svelte/src/internal/client/reactivity/props.js
var legacy_rest_props_handler = {
get(target, key2) {
if (target.exclude.includes(key2)) return;
get(target.version);
return key2 in target.special ? target.special[key2]() : target.props[key2];
},
set(target, key2, value) {
if (!(key2 in target.special)) {
var previous_effect = active_effect;
try {
set_active_effect(target.parent_effect);
target.special[key2] = prop(
{
get [key2]() {
return target.props[key2];
}
},
/** @type {string} */
key2,
PROPS_IS_UPDATED
);
} finally {
set_active_effect(previous_effect);
}
}
target.special[key2](value);
update(target.version);
return true;
},
getOwnPropertyDescriptor(target, key2) {
if (target.exclude.includes(key2)) return;
if (key2 in target.props) {
return {
enumerable: true,
configurable: true,
value: target.props[key2]
};
}
},
deleteProperty(target, key2) {
if (target.exclude.includes(key2)) return true;
target.exclude.push(key2);
update(target.version);
return true;
},
has(target, key2) {
if (target.exclude.includes(key2)) return false;
return key2 in target.props;
},
ownKeys(target) {
return Reflect.ownKeys(target.props).filter((key2) => !target.exclude.includes(key2));
}
};
function legacy_rest_props(props, exclude) {
return new Proxy(
{
props,
exclude,
special: {},
version: source(0),
// TODO this is only necessary because we need to track component
// destruction inside `prop`, because of `bind:this`, but it
// seems likely that we can simplify `bind:this` instead
parent_effect: (
/** @type {Effect} */
active_effect
)
},
legacy_rest_props_handler
);
}
function prop(props, key2, flags2, fallback2) {
var _a5, _b3;
var runes = !legacy_mode_flag || (flags2 & PROPS_IS_RUNES) !== 0;
var bindable = (flags2 & PROPS_IS_BINDABLE) !== 0;
var lazy = (flags2 & PROPS_IS_LAZY_INITIAL) !== 0;
var fallback_value = (
/** @type {V} */
fallback2
);
var fallback_dirty = true;
var fallback_signal = (
/** @type {Derived<V> | undefined} */
void 0
);
var get_fallback = () => {
if (lazy && runes) {
fallback_signal != null ? fallback_signal : fallback_signal = derived2(
/** @type {() => V} */
fallback2
);
return get(fallback_signal);
}
if (fallback_dirty) {
fallback_dirty = false;
fallback_value = lazy ? untrack(
/** @type {() => V} */
fallback2
) : (
/** @type {V} */
fallback2
);
}
return fallback_value;
};
let setter;
if (bindable) {
var is_entry_props = STATE_SYMBOL in props || LEGACY_PROPS in props;
setter = (_b3 = (_a5 = get_descriptor(props, key2)) == null ? void 0 : _a5.set) != null ? _b3 : is_entry_props && key2 in props ? (v) => props[key2] = v : void 0;
}
var initial_value;
var is_store_sub = false;
if (bindable) {
[initial_value, is_store_sub] = capture_store_binding(() => (
/** @type {V} */
props[key2]
));
} else {
initial_value = /** @type {V} */
props[key2];
}
if (initial_value === void 0 && fallback2 !== void 0) {
initial_value = get_fallback();
if (setter) {
if (runes) props_invalid_value(key2);
setter(initial_value);
}
}
var getter;
if (runes) {
getter = () => {
var value = (
/** @type {V} */
props[key2]
);
if (value === void 0) return get_fallback();
fallback_dirty = true;
return value;
};
} else {
getter = () => {
var value = (
/** @type {V} */
props[key2]
);
if (value !== void 0) {
fallback_value = /** @type {V} */
void 0;
}
return value === void 0 ? fallback_value : value;
};
}
if (runes && (flags2 & PROPS_IS_UPDATED) === 0) {
return getter;
}
if (setter) {
var legacy_parent = props.$$legacy;
return (
/** @type {() => V} */
(function(value, mutation) {
if (arguments.length > 0) {
if (!runes || !mutation || legacy_parent || is_store_sub) {
setter(mutation ? getter() : value);
}
return value;
}
return getter();
})
);
}
var overridden = false;
var d = ((flags2 & PROPS_IS_IMMUTABLE) !== 0 ? derived2 : derived_safe_equal)(() => {
overridden = false;
return getter();
});
if (dev_fallback_default) {
d.label = key2;
}
if (bindable) get(d);
var parent_effect = (
/** @type {Effect} */
active_effect
);
return (
/** @type {() => V} */
(function(value, mutation) {
if (arguments.length > 0) {
const new_value = mutation ? get(d) : runes && bindable ? proxy(value) : value;
set(d, new_value);
overridden = true;
if (fallback_value !== void 0) {
fallback_value = new_value;
}
return value;
}
if (is_destroying_effect && overridden || (parent_effect.f & DESTROYED) !== 0) {
return d.v;
}
return get(d);
})
);
}
// node_modules/svelte/src/internal/client/dom/elements/custom-element.js
var SvelteElement;
if (typeof HTMLElement === "function") {
SvelteElement = class extends HTMLElement {
/**
* @param {*} $$componentCtor
* @param {*} $$slots
* @param {ShadowRootInit | undefined} shadow_root_init
*/
constructor($$componentCtor, $$slots, shadow_root_init) {
super();
/** The Svelte component constructor */
__publicField(this, "$$ctor");
/** Slots */
__publicField(this, "$$s");
/** @type {any} The Svelte component instance */
__publicField(this, "$$c");
/** Whether or not the custom element is connected */
__publicField(this, "$$cn", false);
/** @type {Record<string, any>} Component props data */
__publicField(this, "$$d", {});
/** `true` if currently in the process of reflecting component props back to attributes */
__publicField(this, "$$r", false);
/** @type {Record<string, CustomElementPropDefinition>} Props definition (name, reflected, type etc) */
__publicField(this, "$$p_d", {});
/** @type {Record<string, EventListenerOrEventListenerObject[]>} Event listeners */
__publicField(this, "$$l", {});
/** @type {Map<EventListenerOrEventListenerObject, Function>} Event listener unsubscribe functions */
__publicField(this, "$$l_u", /* @__PURE__ */ new Map());
/** @type {any} The managed render effect for reflecting attributes */
__publicField(this, "$$me");
/** @type {ShadowRoot | null} The ShadowRoot of the custom element */
__publicField(this, "$$shadowRoot", null);
this.$$ctor = $$componentCtor;
this.$$s = $$slots;
if (shadow_root_init) {
this.$$shadowRoot = this.attachShadow(shadow_root_init);
}
}
/**
* @param {string} type
* @param {EventListenerOrEventListenerObject} listener
* @param {boolean | AddEventListenerOptions} [options]
*/
addEventListener(type2, listener, options) {
this.$$l[type2] = this.$$l[type2] || [];
this.$$l[type2].push(listener);
if (this.$$c) {
const unsub = this.$$c.$on(type2, listener);
this.$$l_u.set(listener, unsub);
}
super.addEventListener(type2, listener, options);
}
/**
* @param {string} type
* @param {EventListenerOrEventListenerObject} listener
* @param {boolean | AddEventListenerOptions} [options]
*/
removeEventListener(type2, listener, options) {
super.removeEventListener(type2, listener, options);
if (this.$$c) {
const unsub = this.$$l_u.get(listener);
if (unsub) {
unsub();
this.$$l_u.delete(listener);
}
}
}
async connectedCallback() {
this.$$cn = true;
if (!this.$$c) {
let create_slot = function(name) {
return (anchor) => {
const slot2 = create_element("slot");
if (name !== "default") slot2.name = name;
append(anchor, slot2);
};
};
await Promise.resolve();
if (!this.$$cn || this.$$c) {
return;
}
const $$slots = {};
const existing_slots = get_custom_elements_slots(this);
for (const name of this.$$s) {
if (name in existing_slots) {
if (name === "default" && !this.$$d.children) {
this.$$d.children = create_slot(name);
$$slots.default = true;
} else {
$$slots[name] = create_slot(name);
}
}
}
for (const attribute of this.attributes) {
const name = this.$$g_p(attribute.name);
if (!(name in this.$$d)) {
this.$$d[name] = get_custom_element_value(name, attribute.value, this.$$p_d, "toProp");
}
}
for (const key2 in this.$$p_d) {
if (!(key2 in this.$$d) && this[key2] !== void 0) {
this.$$d[key2] = this[key2];
delete this[key2];
}
}
this.$$c = createClassComponent({
component: this.$$ctor,
target: this.$$shadowRoot || this,
props: {
...this.$$d,
$$slots,
$$host: this
}
});
this.$$me = effect_root(() => {
render_effect(() => {
var _a5;
this.$$r = true;
for (const key2 of object_keys(this.$$c)) {
if (!((_a5 = this.$$p_d[key2]) == null ? void 0 : _a5.reflect)) continue;
this.$$d[key2] = this.$$c[key2];
const attribute_value = get_custom_element_value(
key2,
this.$$d[key2],
this.$$p_d,
"toAttribute"
);
if (attribute_value == null) {
this.removeAttribute(this.$$p_d[key2].attribute || key2);
} else {
this.setAttribute(this.$$p_d[key2].attribute || key2, attribute_value);
}
}
this.$$r = false;
});
});
for (const type2 in this.$$l) {
for (const listener of this.$$l[type2]) {
const unsub = this.$$c.$on(type2, listener);
this.$$l_u.set(listener, unsub);
}
}
this.$$l = {};
}
}
// We don't need this when working within Svelte code, but for compatibility of people using this outside of Svelte
// and setting attributes through setAttribute etc, this is helpful
/**
* @param {string} attr
* @param {string} _oldValue
* @param {string} newValue
*/
attributeChangedCallback(attr2, _oldValue, newValue) {
var _a5;
if (this.$$r) return;
attr2 = this.$$g_p(attr2);
this.$$d[attr2] = get_custom_element_value(attr2, newValue, this.$$p_d, "toProp");
(_a5 = this.$$c) == null ? void 0 : _a5.$set({ [attr2]: this.$$d[attr2] });
}
disconnectedCallback() {
this.$$cn = false;
Promise.resolve().then(() => {
if (!this.$$cn && this.$$c) {
this.$$c.$destroy();
this.$$me();
this.$$c = void 0;
}
});
}
/**
* @param {string} attribute_name
*/
$$g_p(attribute_name) {
return object_keys(this.$$p_d).find(
(key2) => this.$$p_d[key2].attribute === attribute_name || !this.$$p_d[key2].attribute && key2.toLowerCase() === attribute_name
) || attribute_name;
}
};
}
function get_custom_element_value(prop2, value, props_definition, transform) {
var _a5;
const type2 = (_a5 = props_definition[prop2]) == null ? void 0 : _a5.type;
value = type2 === "Boolean" && typeof value !== "boolean" ? value != null : value;
if (!transform || !props_definition[prop2]) {
return value;
} else if (transform === "toAttribute") {
switch (type2) {
case "Object":
case "Array":
return value == null ? null : JSON.stringify(value);
case "Boolean":
return value ? "" : null;
case "Number":
return value == null ? null : value;
default:
return value;
}
} else {
switch (type2) {
case "Object":
case "Array":
return value && JSON.parse(value);
case "Boolean":
return value;
// conversion already handled above
case "Number":
return value != null ? +value : value;
default:
return value;
}
}
}
function get_custom_elements_slots(element2) {
const result = {};
element2.childNodes.forEach((node) => {
result[
/** @type {Element} node */
node.slot || "default"
] = true;
});
return result;
}
// src/parsing/kebab/kebab.ts
function kebab(input) {
return input.replaceAll(/\p{Lu}/gu, (match) => `-${match.toLowerCase()}`).replaceAll(/\p{Z}/gu, "-").replaceAll(/[^\p{L}\p{N}\/-]/gu, "-").replaceAll(/-+/g, "-").replace(/^-/, "").replace(/-$/, "");
}
// src/parsing/properties/property_schema.ts
var PropertySchemaOption = /* @__PURE__ */ ((PropertySchemaOption3) => {
PropertySchemaOption3["None"] = "none";
PropertySchemaOption3["TasksPlugin"] = "tasks";
PropertySchemaOption3["Dataview"] = "dataview";
return PropertySchemaOption3;
})(PropertySchemaOption || {});
var UNIVERSAL_STATUS_PROPERTY_KEY = "status";
function findStatusRange(statusMatch) {
var _a5, _b3;
if (!(statusMatch == null ? void 0 : statusMatch[0])) {
return { startIndex: -1, endIndex: -1 };
}
const bracketIndex = statusMatch[0].indexOf("[");
const startIndex = bracketIndex >= 0 ? bracketIndex + 1 : -1;
const endIndex = startIndex >= 0 ? startIndex + ((_b3 = (_a5 = statusMatch[1]) == null ? void 0 : _a5.length) != null ? _b3 : 0) : -1;
return { startIndex, endIndex };
}
function parseUniversalStatus(rawLine) {
var _a5, _b3;
const match = rawLine.match(/^\s*[-*+]\s\[([^\[\]]*)\]/);
const statusChar = match ? (_a5 = match[1]) != null ? _a5 : " " : " ";
const { startIndex, endIndex } = findStatusRange(match);
const value = statusChar === "" ? " " : (_b3 = Array.from(statusChar)[0]) != null ? _b3 : " ";
return {
key: UNIVERSAL_STATUS_PROPERTY_KEY,
rawValue: value,
value,
startIndex,
endIndex
};
}
function createPropertyMapWithStatus(rawLine) {
const properties = /* @__PURE__ */ new Map();
const statusProp = parseUniversalStatus(rawLine);
properties.set(UNIVERSAL_STATUS_PROPERTY_KEY, statusProp);
return properties;
}
// src/parsing/properties/normalization.ts
var PROPERTY_KEY_ALIASES = {
completion: "done",
repeat: "recurrence"
};
function normalizePropertyKey(key2) {
var _a5;
return (_a5 = PROPERTY_KEY_ALIASES[key2]) != null ? _a5 : key2;
}
function getPropertyAliases(key2) {
const canonicalKey = normalizePropertyKey(key2);
const aliases = Object.entries(PROPERTY_KEY_ALIASES).filter(([, canonical]) => canonical === canonicalKey).map(([alias]) => alias);
return [
...canonicalKey !== key2 ? [canonicalKey] : [],
...aliases.filter((alias) => alias !== key2)
];
}
function getPropertyByKey(properties, key2) {
const exactMatch = properties.get(key2);
if (exactMatch) return exactMatch;
const canonicalKey = normalizePropertyKey(key2);
for (const [propertyKey, property] of properties) {
if (normalizePropertyKey(propertyKey) === canonicalKey) {
return property;
}
}
return void 0;
}
// src/parsing/properties/value_parsers.ts
var DATE_ONLY_PATTERN = "\\d{4}-\\d{2}-\\d{2}";
function parseDateOnly(value) {
const match = value.match(/^(\d{4})-(\d{2})-(\d{2})$/);
if (!match) return null;
const year = Number(match[1]);
const month = Number(match[2]);
const day = Number(match[3]);
const parsed = new Date(Date.UTC(year, month - 1, day));
return parsed.getUTCFullYear() === year && parsed.getUTCMonth() === month - 1 && parsed.getUTCDate() === day ? parsed : null;
}
function parseIsoDate(value) {
const trimmed = value.trim();
const dateOnly = parseDateOnly(trimmed);
if (dateOnly) return dateOnly;
if (/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d{3})?(Z|[+-]\d{2}:\d{2})?$/.test(trimmed)) {
const parsed = new Date(trimmed);
return isNaN(parsed.getTime()) ? null : parsed;
}
return null;
}
function parseNumber(value) {
const trimmed = value.trim();
if (!/^-?\d+(\.\d+)?$/.test(trimmed)) return null;
const parsed = Number(trimmed);
return isNaN(parsed) ? null : parsed;
}
function escapeRegExp(input) {
return input.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}
// src/parsing/properties/tasks_schema.ts
var DATE_FIELDS = [
{ key: "due", label: "Due", emojis: ["\u{1F4C5}"] },
{ key: "scheduled", label: "Scheduled", emojis: ["\u23F3", "\u23F0"] },
{ key: "start", label: "Start", emojis: ["\u{1F6EB}"] },
{ key: "done", label: "Done", emojis: ["\u2705", "\u{1F3C1}"] },
{ key: "created", label: "Created", emojis: ["\u2795"] }
];
var TASKS_PRIORITY_OPTIONS = [
{ value: "highest", label: "Highest", emoji: "\u{1F53A}", weight: 5 },
{ value: "high", label: "High", emoji: "\u23EB", weight: 4 },
{ value: "medium", label: "Medium", emoji: "\u{1F53C}", weight: 3 },
{ value: "low", label: "Low", emoji: "\u{1F53D}", weight: 2 },
{ value: "lowest", label: "Lowest", emoji: "\u23EC", weight: 1 }
];
var PRIORITY_VALUES = new Map(
TASKS_PRIORITY_OPTIONS.map((option) => [option.emoji, option.weight])
);
var METADATA_EMOJIS = [
...DATE_FIELDS.flatMap((field) => field.emojis),
...PRIORITY_VALUES.keys(),
"\u{1F501}"
];
var RECURRENCE_EMOJI = "\u{1F501}";
var TASKS_PROPERTY_ICONS = {
...Object.fromEntries(DATE_FIELDS.map((field) => [field.key, field.emojis[0]])),
recurrence: RECURRENCE_EMOJI
};
function getTasksPriorityEmoji(value) {
for (const [emoji, weight] of PRIORITY_VALUES) {
if (weight === value) return emoji;
}
return void 0;
}
function getTasksPriorityOption(value) {
return TASKS_PRIORITY_OPTIONS.find((option) => option.value === value);
}
function getTasksPriorityValueFromWeight(weight) {
var _a5;
return (_a5 = TASKS_PRIORITY_OPTIONS.find((option) => option.weight === weight)) == null ? void 0 : _a5.value;
}
function parseDateFields(rawLine) {
return DATE_FIELDS.flatMap(
(field) => field.emojis.flatMap((emoji) => {
const regex = new RegExp(`${escapeRegExp(emoji)}\\s*(${DATE_ONLY_PATTERN})`, "gu");
return [...rawLine.matchAll(regex)].map((match) => {
var _a5, _b3;
return {
index: (_a5 = match.index) != null ? _a5 : Number.MAX_SAFE_INTEGER,
endIndex: ((_b3 = match.index) != null ? _b3 : 0) + match[0].length,
key: field.key,
rawValue: match[0],
value: match[1] ? parseDateOnly(match[1]) : null
};
});
})
);
}
function parsePriorityFields(rawLine) {
const priorityPattern = Array.from(PRIORITY_VALUES.keys()).map(escapeRegExp).join("|");
const regex = new RegExp(priorityPattern, "gu");
return [...rawLine.matchAll(regex)].map((match) => {
var _a5, _b3, _c2;
return {
index: (_a5 = match.index) != null ? _a5 : Number.MAX_SAFE_INTEGER,
endIndex: ((_b3 = match.index) != null ? _b3 : 0) + match[0].length,
key: "priority",
rawValue: match[0],
value: (_c2 = PRIORITY_VALUES.get(match[0])) != null ? _c2 : null
};
});
}
function parseRecurrenceFields(rawLine) {
const metadataPattern = METADATA_EMOJIS.map(escapeRegExp).join("|");
const regex = new RegExp(`\u{1F501}\\s*(.+?)(?=\\s*(?:${metadataPattern})(?:\\s*${DATE_ONLY_PATTERN})?|$)`, "gu");
return [...rawLine.matchAll(regex)].map((match) => {
var _a5, _b3, _c2;
const value = (_b3 = (_a5 = match[1]) == null ? void 0 : _a5.trim()) != null ? _b3 : "";
const rawValue = match[0].trimEnd();
const index2 = (_c2 = match.index) != null ? _c2 : Number.MAX_SAFE_INTEGER;
return {
index: index2,
endIndex: index2 + rawValue.length,
key: "recurrence",
rawValue,
value
};
}).filter((field) => field.value !== "");
}
var TasksPluginSchema = class {
constructor() {
this.id = "tasks" /* TasksPlugin */;
this.label = "Tasks Plugin";
}
parseProperties(rawLine) {
const properties = createPropertyMapWithStatus(rawLine);
const parsedFields = [
...parseDateFields(rawLine),
...parsePriorityFields(rawLine),
...parseRecurrenceFields(rawLine)
].sort((a, b) => a.index - b.index);
for (const field of parsedFields) {
if (!properties.has(field.key)) {
properties.set(field.key, {
key: field.key,
rawValue: field.rawValue,
value: field.value,
startIndex: field.index,
endIndex: field.endIndex
});
}
}
return properties;
}
knownKeys() {
return [
{ key: UNIVERSAL_STATUS_PROPERTY_KEY, label: "Status", type: "text" },
{ key: "due", label: "Due", type: "date" },
{ key: "scheduled", label: "Scheduled", type: "date" },
{ key: "start", label: "Start", type: "date" },
{ key: "done", label: "Done", type: "date", aliases: getPropertyAliases("done") },
{ key: "created", label: "Created", type: "date" },
{ key: "priority", label: "Priority", type: "priority" },
{ key: "recurrence", label: "Recurrence", type: "text", aliases: getPropertyAliases("recurrence") }
];
}
};
// src/parsing/properties/display.ts
var PRIORITY_LABELS = {
5: "Highest",
4: "High",
3: "Medium",
2: "Low",
1: "Lowest"
};
function formatPriorityColumnLabel(value) {
var _a5, _b3;
return (_b3 = (_a5 = getTasksPriorityOption(value)) == null ? void 0 : _a5.label) != null ? _b3 : value ? formatPropertyLabel(value) : "";
}
function formatPropertyLabel(key2) {
if (!key2) return key2;
return key2.charAt(0).toUpperCase() + key2.slice(1);
}
function formatPropertyValue(prop2) {
var _a5;
if (prop2.value instanceof Date) {
return prop2.value.toLocaleDateString(void 0, {
month: "short",
day: "numeric",
timeZone: "UTC"
});
}
if (prop2.key === "priority" && typeof prop2.value === "number") {
return (_a5 = PRIORITY_LABELS[prop2.value]) != null ? _a5 : String(prop2.value);
}
if (prop2.value === null) {
return prop2.rawValue;
}
return String(prop2.value);
}
function tasksIconFor(prop2) {
if (prop2.key === "priority" && typeof prop2.value === "number") {
return getTasksPriorityEmoji(prop2.value);
}
return TASKS_PROPERTY_ICONS[prop2.key];
}
function stripDisplayedPropertiesFromContent(content, properties) {
let result = content;
for (const [key2, prop2] of properties) {
if (key2 === UNIVERSAL_STATUS_PROPERTY_KEY) continue;
if (!prop2.rawValue) continue;
result = result.split(prop2.rawValue).join(" ");
}
return result.replace(/[ \t]{2,}/g, " ").trim();
}
function toDisplayProperties(properties) {
const result = [];
for (const [key2, prop2] of properties) {
if (key2 === UNIVERSAL_STATUS_PROPERTY_KEY) continue;
result.push({
key: key2,
label: formatPropertyLabel(key2),
value: formatPropertyValue(prop2),
icon: tasksIconFor(prop2)
});
}
return result;
}
// src/ui/columns/definitions.ts
var RESERVED_COLUMN_KEYS = /* @__PURE__ */ new Set(["uncategorised", "done"]);
function parseColumnSpec(columnSpec) {
const hashMatch = columnSpec.match(/^(.+?)\(#([0-9a-fA-F]{6})\)$/);
const oxMatch = columnSpec.match(/^(.+?)\(0x([0-9a-fA-F]{6})\)$/);
const match = hashMatch || oxMatch;
if ((match == null ? void 0 : match[1]) && (match == null ? void 0 : match[2])) {
return {
raw: columnSpec,
label: match[1],
color: `#${match[2]}`
};
}
return {
raw: columnSpec,
label: columnSpec
};
}
function sanitizeIdBase(label) {
const normalized = kebab(label).replace(/[^a-z0-9-]/g, "");
return normalized.length > 0 ? normalized : "column";
}
function createColumnId(label, usedIds) {
const base = `column-${sanitizeIdBase(label)}`;
let candidate = base;
let suffix = 2;
while (usedIds.has(candidate) || RESERVED_COLUMN_KEYS.has(candidate)) {
candidate = `${base}-${suffix}`;
suffix += 1;
}
usedIds.add(candidate);
return candidate;
}
function normalizeMatchTags(tags) {
const normalized = tags.map((tag2) => tag2.trim().replace(/^#/, "")).filter((tag2) => tag2.length > 0);
return [...new Set(normalized)];
}
function getNameModeWriteTag(column) {
return kebab(column.label);
}
function usesTagMatching(column) {
return column.matchMode === "tags";
}
function usesStatusMatching(column) {
return column.matchMode === "status";
}
function usesPriorityMatching(column) {
return column.matchMode === "priority";
}
function getColumnWriteTags(column) {
return usesStatusMatching(column) || usesPriorityMatching(column) ? [] : usesTagMatching(column) ? column.matchTags : [getNameModeWriteTag(column)];
}
function columnRuleSignature(column) {
var _a5, _b3, _c2;
return usesStatusMatching(column) ? `status:${(_a5 = column.matchStatus) != null ? _a5 : ""}` : usesPriorityMatching(column) ? `priority:${(_b3 = getColumnPrioritySchema(column)) != null ? _b3 : ""}:${(_c2 = normalizePriorityMatchValue(column.matchPriority, getColumnPrioritySchema(column))) != null ? _c2 : ""}` : usesTagMatching(column) ? `tags:${[...getColumnWriteTags(column)].sort().join(",")}` : `name:${getNameModeWriteTag(column)}`;
}
function normalizeColumnMatchContext(context) {
return context instanceof Set ? { tags: context } : context;
}
function getColumnStatus(column) {
return column && usesStatusMatching(column) ? column.matchStatus : void 0;
}
function getColumnPriority(column) {
return column && usesPriorityMatching(column) ? column.matchPriority : void 0;
}
function getColumnPrioritySchema(column) {
var _a5;
return column && usesPriorityMatching(column) ? (_a5 = column.matchPropertySchema) != null ? _a5 : "tasks" /* TasksPlugin */ : void 0;
}
function getStatusColumnLabel(status) {
return status === " " ? "unchecked" : status != null ? status : "";
}
function getPriorityColumnLabel(priority) {
return formatPriorityColumnLabel(priority);
}
function normalizePriorityMatchValue(priority, schema2) {
const trimmed = priority == null ? void 0 : priority.trim();
if (!trimmed) {
return void 0;
}
return schema2 === "dataview" /* Dataview */ ? trimmed.toLowerCase() : trimmed;
}
function matchesColumnDefinition(column, context) {
const { tags: taskTags, status, priority, prioritySchema, priorities } = normalizeColumnMatchContext(context);
if (usesStatusMatching(column)) {
return !!column.matchStatus && status === column.matchStatus;
}
if (usesPriorityMatching(column)) {
const columnPrioritySchema = getColumnPrioritySchema(column);
const priorityForSchema = columnPrioritySchema ? priorities == null ? void 0 : priorities[columnPrioritySchema] : void 0;
return !!column.matchPriority && (priorityForSchema !== void 0 ? normalizePriorityMatchValue(priorityForSchema, columnPrioritySchema) === normalizePriorityMatchValue(column.matchPriority, columnPrioritySchema) : normalizePriorityMatchValue(priority, prioritySchema) === normalizePriorityMatchValue(column.matchPriority, columnPrioritySchema) && prioritySchema === columnPrioritySchema);
}
if (usesTagMatching(column)) {
const explicitTags = getColumnWriteTags(column);
return explicitTags.length > 0 && explicitTags.every((tag2) => taskTags.has(tag2));
}
const derivedTag = getNameModeWriteTag(column);
for (const tag2 of taskTags) {
if (kebab(tag2) === derivedTag) {
return true;
}
}
return false;
}
function getColumnMatchSpecificity(column) {
return usesTagMatching(column) ? getColumnWriteTags(column).length : 1;
}
function usesTagBasedPlacement(column) {
return !usesStatusMatching(column) && !usesPriorityMatching(column);
}
function resolveMatchedColumnDefinition(columns, context) {
let matchedColumn;
let matchedSpecificity = -1;
for (const column of columns) {
if (!matchesColumnDefinition(column, context)) {
continue;
}
const specificity = getColumnMatchSpecificity(column);
if (!matchedColumn) {
matchedColumn = column;
matchedSpecificity = specificity;
continue;
}
if (usesTagBasedPlacement(matchedColumn) && usesTagBasedPlacement(column) && specificity > matchedSpecificity) {
matchedColumn = column;
matchedSpecificity = specificity;
}
}
return matchedColumn;
}
function isPlacementTag(column, tag2) {
if (usesStatusMatching(column) || usesPriorityMatching(column)) {
return false;
}
if (usesTagMatching(column)) {
return getColumnWriteTags(column).includes(tag2);
}
return kebab(tag2) === getNameModeWriteTag(column);
}
function getColumnHeaderTags(column) {
return usesTagMatching(column) ? column.matchTags : [];
}
function getColumnHeaderSubtitle(column) {
var _a5;
if (usesStatusMatching(column)) {
return column.matchStatus ? { kind: "status", value: column.matchStatus, label: getStatusColumnLabel(column.matchStatus) } : void 0;
}
if (usesPriorityMatching(column)) {
const priority = getTasksPriorityOption(column.matchPriority);
return column.matchPriority ? {
kind: "priority",
value: column.matchPriority,
label: (_a5 = priority == null ? void 0 : priority.label) != null ? _a5 : getPriorityColumnLabel(column.matchPriority),
icon: priority == null ? void 0 : priority.emoji
} : void 0;
}
return void 0;
}
function migrateColumnDefinitions(columns) {
const usedIds = /* @__PURE__ */ new Set();
return columns.flatMap((column) => {
if (typeof column === "string") {
const parsed = parseColumnSpec(column);
return [
{
id: createColumnId(parsed.label, usedIds),
label: parsed.label,
color: parsed.color,
matchMode: "name",
matchTags: [],
matchStatus: void 0,
matchPriority: void 0,
matchPropertySchema: void 0
}
];
}
if (!column || typeof column !== "object") {
return [];
}
const label = typeof column.label === "string" ? column.label : "";
const idCandidate = typeof column.id === "string" ? column.id : "";
const id = idCandidate && !usedIds.has(idCandidate) && !RESERVED_COLUMN_KEYS.has(idCandidate) ? (usedIds.add(idCandidate), idCandidate) : createColumnId(label, usedIds);
const matchMode = column.matchMode === "tags" || column.matchMode === "status" || column.matchMode === "priority" ? column.matchMode : "name";
const matchStatus = typeof column.matchStatus === "string" ? column.matchStatus : void 0;
const matchPriority = typeof column.matchPriority === "string" ? column.matchPriority : void 0;
const matchPropertySchema = column.matchPropertySchema === "dataview" /* Dataview */ || column.matchPropertySchema === "tasks" /* TasksPlugin */ ? column.matchPropertySchema : matchMode === "priority" ? "tasks" /* TasksPlugin */ : void 0;
return [
{
id,
label,
color: typeof column.color === "string" && column.color.length > 0 ? column.color : void 0,
matchMode,
matchTags: normalizeMatchTags(Array.isArray(column.matchTags) ? column.matchTags : []),
matchStatus,
matchPriority,
matchPropertySchema
}
];
});
}
function migrateCollapsedColumns(collapsedColumns, columns) {
if (!collapsedColumns || collapsedColumns.length === 0) {
return [];
}
const placementTagToId = /* @__PURE__ */ new Map();
for (const column of columns) {
placementTagToId.set(getNameModeWriteTag(column), column.id);
}
const migrated = /* @__PURE__ */ new Set();
for (const value of collapsedColumns) {
if (value === "done" || value === "uncategorised") {
migrated.add(value);
continue;
}
const matchedColumn = columns.find((column) => column.id === value);
if (matchedColumn) {
migrated.add(matchedColumn.id);
continue;
}
const mappedId = placementTagToId.get(value);
if (mappedId) {
migrated.add(mappedId);
}
}
return [...migrated];
}
// src/ui/columns/columns.ts
var createColumnStores = (settingsStore) => {
const columnDefinitions = derived([settingsStore], ([settings]) => {
var _a5;
return (_a5 = settings.columns) != null ? _a5 : [];
});
const columnData = derived([columnDefinitions], ([columns]) => createColumnData(columns));
const columnTagTable = derived([columnData], ([data]) => data.columnTagTable);
const columnColourTable = derived([columnData], ([data]) => data.columnColourTable);
const columnPlacementTagTable = derived([columnData], ([data]) => data.columnPlacementTagTable);
const columnMatchTagTable = derived([columnData], ([data]) => data.columnMatchTagTable);
const columnSubtitleTable = derived([columnData], ([data]) => data.columnSubtitleTable);
return {
columnDefinitions,
columnTagTable,
columnColourTable,
columnPlacementTagTable,
columnMatchTagTable,
columnSubtitleTable
};
};
function isColumnTag(input, columnTagTableStore) {
return input in get2(columnTagTableStore);
}
var DEFAULT_UNCATEGORIZED_LABEL = "Uncategorized";
var DEFAULT_DONE_LABEL = "Done";
function resolveDefaultColumnName(column, uncategorizedColumnName, doneColumnName) {
switch (column) {
case "uncategorised":
return uncategorizedColumnName || DEFAULT_UNCATEGORIZED_LABEL;
case "done":
return doneColumnName || DEFAULT_DONE_LABEL;
}
}
var createCollapsedColumnsStore = (settingsStore) => {
return derived([settingsStore], ([settings]) => {
var _a5;
return new Set((_a5 = settings.collapsedColumns) != null ? _a5 : []);
});
};
function createColumnData(columns) {
const columnTagTable = {};
const columnColourTable = {};
const columnPlacementTagTable = {};
const columnMatchTagTable = {};
const columnSubtitleTable = {};
for (const column of columns) {
if (RESERVED_COLUMN_KEYS.has(column.id)) continue;
columnTagTable[column.id] = column.label;
if (column.color) {
columnColourTable[column.id] = column.color;
}
columnPlacementTagTable[column.id] = getColumnWriteTags(column);
columnMatchTagTable[column.id] = getColumnHeaderTags(column);
const subtitle = getColumnHeaderSubtitle(column);
if (subtitle) {
columnSubtitleTable[column.id] = subtitle;
}
}
return {
columnTagTable,
columnColourTable,
columnPlacementTagTable,
columnMatchTagTable,
columnSubtitleTable
};
}
// node_modules/zod/lib/index.mjs
var util;
(function(util2) {
util2.assertEqual = (val) => val;
function assertIs(_arg) {
}
util2.assertIs = assertIs;
function assertNever(_x) {
throw new Error();
}
util2.assertNever = assertNever;
util2.arrayToEnum = (items) => {
const obj = {};
for (const item of items) {
obj[item] = item;
}
return obj;
};
util2.getValidEnumValues = (obj) => {
const validKeys = util2.objectKeys(obj).filter((k) => typeof obj[obj[k]] !== "number");
const filtered = {};
for (const k of validKeys) {
filtered[k] = obj[k];
}
return util2.objectValues(filtered);
};
util2.objectValues = (obj) => {
return util2.objectKeys(obj).map(function(e) {
return obj[e];
});
};
util2.objectKeys = typeof Object.keys === "function" ? (obj) => Object.keys(obj) : (object) => {
const keys = [];
for (const key2 in object) {
if (Object.prototype.hasOwnProperty.call(object, key2)) {
keys.push(key2);
}
}
return keys;
};
util2.find = (arr, checker) => {
for (const item of arr) {
if (checker(item))
return item;
}
return void 0;
};
util2.isInteger = typeof Number.isInteger === "function" ? (val) => Number.isInteger(val) : (val) => typeof val === "number" && isFinite(val) && Math.floor(val) === val;
function joinValues(array, separator = " | ") {
return array.map((val) => typeof val === "string" ? `'${val}'` : val).join(separator);
}
util2.joinValues = joinValues;
util2.jsonStringifyReplacer = (_, value) => {
if (typeof value === "bigint") {
return value.toString();
}
return value;
};
})(util || (util = {}));
var objectUtil;
(function(objectUtil2) {
objectUtil2.mergeShapes = (first, second) => {
return {
...first,
...second
// second overwrites first
};
};
})(objectUtil || (objectUtil = {}));
var ZodParsedType = util.arrayToEnum([
"string",
"nan",
"number",
"integer",
"float",
"boolean",
"date",
"bigint",
"symbol",
"function",
"undefined",
"null",
"array",
"object",
"unknown",
"promise",
"void",
"never",
"map",
"set"
]);
var getParsedType = (data) => {
const t = typeof data;
switch (t) {
case "undefined":
return ZodParsedType.undefined;
case "string":
return ZodParsedType.string;
case "number":
return isNaN(data) ? ZodParsedType.nan : ZodParsedType.number;
case "boolean":
return ZodParsedType.boolean;
case "function":
return ZodParsedType.function;
case "bigint":
return ZodParsedType.bigint;
case "symbol":
return ZodParsedType.symbol;
case "object":
if (Array.isArray(data)) {
return ZodParsedType.array;
}
if (data === null) {
return ZodParsedType.null;
}
if (data.then && typeof data.then === "function" && data.catch && typeof data.catch === "function") {
return ZodParsedType.promise;
}
if (typeof Map !== "undefined" && data instanceof Map) {
return ZodParsedType.map;
}
if (typeof Set !== "undefined" && data instanceof Set) {
return ZodParsedType.set;
}
if (typeof Date !== "undefined" && data instanceof Date) {
return ZodParsedType.date;
}
return ZodParsedType.object;
default:
return ZodParsedType.unknown;
}
};
var ZodIssueCode = util.arrayToEnum([
"invalid_type",
"invalid_literal",
"custom",
"invalid_union",
"invalid_union_discriminator",
"invalid_enum_value",
"unrecognized_keys",
"invalid_arguments",
"invalid_return_type",
"invalid_date",
"invalid_string",
"too_small",
"too_big",
"invalid_intersection_types",
"not_multiple_of",
"not_finite"
]);
var quotelessJson = (obj) => {
const json2 = JSON.stringify(obj, null, 2);
return json2.replace(/"([^"]+)":/g, "$1:");
};
var ZodError = class _ZodError extends Error {
constructor(issues) {
super();
this.issues = [];
this.addIssue = (sub) => {
this.issues = [...this.issues, sub];
};
this.addIssues = (subs = []) => {
this.issues = [...this.issues, ...subs];
};
const actualProto = new.target.prototype;
if (Object.setPrototypeOf) {
Object.setPrototypeOf(this, actualProto);
} else {
this.__proto__ = actualProto;
}
this.name = "ZodError";
this.issues = issues;
}
get errors() {
return this.issues;
}
format(_mapper) {
const mapper = _mapper || function(issue) {
return issue.message;
};
const fieldErrors = { _errors: [] };
const processError = (error) => {
for (const issue of error.issues) {
if (issue.code === "invalid_union") {
issue.unionErrors.map(processError);
} else if (issue.code === "invalid_return_type") {
processError(issue.returnTypeError);
} else if (issue.code === "invalid_arguments") {
processError(issue.argumentsError);
} else if (issue.path.length === 0) {
fieldErrors._errors.push(mapper(issue));
} else {
let curr = fieldErrors;
let i = 0;
while (i < issue.path.length) {
const el = issue.path[i];
const terminal = i === issue.path.length - 1;
if (!terminal) {
curr[el] = curr[el] || { _errors: [] };
} else {
curr[el] = curr[el] || { _errors: [] };
curr[el]._errors.push(mapper(issue));
}
curr = curr[el];
i++;
}
}
}
};
processError(this);
return fieldErrors;
}
static assert(value) {
if (!(value instanceof _ZodError)) {
throw new Error(`Not a ZodError: ${value}`);
}
}
toString() {
return this.message;
}
get message() {
return JSON.stringify(this.issues, util.jsonStringifyReplacer, 2);
}
get isEmpty() {
return this.issues.length === 0;
}
flatten(mapper = (issue) => issue.message) {
const fieldErrors = {};
const formErrors = [];
for (const sub of this.issues) {
if (sub.path.length > 0) {
fieldErrors[sub.path[0]] = fieldErrors[sub.path[0]] || [];
fieldErrors[sub.path[0]].push(mapper(sub));
} else {
formErrors.push(mapper(sub));
}
}
return { formErrors, fieldErrors };
}
get formErrors() {
return this.flatten();
}
};
ZodError.create = (issues) => {
const error = new ZodError(issues);
return error;
};
var errorMap = (issue, _ctx) => {
let message;
switch (issue.code) {
case ZodIssueCode.invalid_type:
if (issue.received === ZodParsedType.undefined) {
message = "Required";
} else {
message = `Expected ${issue.expected}, received ${issue.received}`;
}
break;
case ZodIssueCode.invalid_literal:
message = `Invalid literal value, expected ${JSON.stringify(issue.expected, util.jsonStringifyReplacer)}`;
break;
case ZodIssueCode.unrecognized_keys:
message = `Unrecognized key(s) in object: ${util.joinValues(issue.keys, ", ")}`;
break;
case ZodIssueCode.invalid_union:
message = `Invalid input`;
break;
case ZodIssueCode.invalid_union_discriminator:
message = `Invalid discriminator value. Expected ${util.joinValues(issue.options)}`;
break;
case ZodIssueCode.invalid_enum_value:
message = `Invalid enum value. Expected ${util.joinValues(issue.options)}, received '${issue.received}'`;
break;
case ZodIssueCode.invalid_arguments:
message = `Invalid function arguments`;
break;
case ZodIssueCode.invalid_return_type:
message = `Invalid function return type`;
break;
case ZodIssueCode.invalid_date:
message = `Invalid date`;
break;
case ZodIssueCode.invalid_string:
if (typeof issue.validation === "object") {
if ("includes" in issue.validation) {
message = `Invalid input: must include "${issue.validation.includes}"`;
if (typeof issue.validation.position === "number") {
message = `${message} at one or more positions greater than or equal to ${issue.validation.position}`;
}
} else if ("startsWith" in issue.validation) {
message = `Invalid input: must start with "${issue.validation.startsWith}"`;
} else if ("endsWith" in issue.validation) {
message = `Invalid input: must end with "${issue.validation.endsWith}"`;
} else {
util.assertNever(issue.validation);
}
} else if (issue.validation !== "regex") {
message = `Invalid ${issue.validation}`;
} else {
message = "Invalid";
}
break;
case ZodIssueCode.too_small:
if (issue.type === "array")
message = `Array must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `more than`} ${issue.minimum} element(s)`;
else if (issue.type === "string")
message = `String must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `over`} ${issue.minimum} character(s)`;
else if (issue.type === "number")
message = `Number must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${issue.minimum}`;
else if (issue.type === "date")
message = `Date must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${new Date(Number(issue.minimum))}`;
else
message = "Invalid input";
break;
case ZodIssueCode.too_big:
if (issue.type === "array")
message = `Array must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `less than`} ${issue.maximum} element(s)`;
else if (issue.type === "string")
message = `String must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `under`} ${issue.maximum} character(s)`;
else if (issue.type === "number")
message = `Number must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`;
else if (issue.type === "bigint")
message = `BigInt must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`;
else if (issue.type === "date")
message = `Date must be ${issue.exact ? `exactly` : issue.inclusive ? `smaller than or equal to` : `smaller than`} ${new Date(Number(issue.maximum))}`;
else
message = "Invalid input";
break;
case ZodIssueCode.custom:
message = `Invalid input`;
break;
case ZodIssueCode.invalid_intersection_types:
message = `Intersection results could not be merged`;
break;
case ZodIssueCode.not_multiple_of:
message = `Number must be a multiple of ${issue.multipleOf}`;
break;
case ZodIssueCode.not_finite:
message = "Number must be finite";
break;
default:
message = _ctx.defaultError;
util.assertNever(issue);
}
return { message };
};
var overrideErrorMap = errorMap;
function setErrorMap(map2) {
overrideErrorMap = map2;
}
function getErrorMap() {
return overrideErrorMap;
}
var makeIssue = (params) => {
const { data, path, errorMaps, issueData } = params;
const fullPath = [...path, ...issueData.path || []];
const fullIssue = {
...issueData,
path: fullPath
};
if (issueData.message !== void 0) {
return {
...issueData,
path: fullPath,
message: issueData.message
};
}
let errorMessage = "";
const maps = errorMaps.filter((m) => !!m).slice().reverse();
for (const map2 of maps) {
errorMessage = map2(fullIssue, { data, defaultError: errorMessage }).message;
}
return {
...issueData,
path: fullPath,
message: errorMessage
};
};
var EMPTY_PATH = [];
function addIssueToContext(ctx, issueData) {
const overrideMap = getErrorMap();
const issue = makeIssue({
issueData,
data: ctx.data,
path: ctx.path,
errorMaps: [
ctx.common.contextualErrorMap,
ctx.schemaErrorMap,
overrideMap,
overrideMap === errorMap ? void 0 : errorMap
// then global default map
].filter((x) => !!x)
});
ctx.common.issues.push(issue);
}
var ParseStatus = class _ParseStatus {
constructor() {
this.value = "valid";
}
dirty() {
if (this.value === "valid")
this.value = "dirty";
}
abort() {
if (this.value !== "aborted")
this.value = "aborted";
}
static mergeArray(status, results) {
const arrayValue = [];
for (const s of results) {
if (s.status === "aborted")
return INVALID;
if (s.status === "dirty")
status.dirty();
arrayValue.push(s.value);
}
return { status: status.value, value: arrayValue };
}
static async mergeObjectAsync(status, pairs2) {
const syncPairs = [];
for (const pair of pairs2) {
const key2 = await pair.key;
const value = await pair.value;
syncPairs.push({
key: key2,
value
});
}
return _ParseStatus.mergeObjectSync(status, syncPairs);
}
static mergeObjectSync(status, pairs2) {
const finalObject = {};
for (const pair of pairs2) {
const { key: key2, value } = pair;
if (key2.status === "aborted")
return INVALID;
if (value.status === "aborted")
return INVALID;
if (key2.status === "dirty")
status.dirty();
if (value.status === "dirty")
status.dirty();
if (key2.value !== "__proto__" && (typeof value.value !== "undefined" || pair.alwaysSet)) {
finalObject[key2.value] = value.value;
}
}
return { status: status.value, value: finalObject };
}
};
var INVALID = Object.freeze({
status: "aborted"
});
var DIRTY2 = (value) => ({ status: "dirty", value });
var OK = (value) => ({ status: "valid", value });
var isAborted = (x) => x.status === "aborted";
var isDirty = (x) => x.status === "dirty";
var isValid = (x) => x.status === "valid";
var isAsync = (x) => typeof Promise !== "undefined" && x instanceof Promise;
function __classPrivateFieldGet(receiver, state2, kind, f) {
if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
if (typeof state2 === "function" ? receiver !== state2 || !f : !state2.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state2.get(receiver);
}
function __classPrivateFieldSet(receiver, state2, value, kind, f) {
if (kind === "m") throw new TypeError("Private method is not writable");
if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
if (typeof state2 === "function" ? receiver !== state2 || !f : !state2.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
return kind === "a" ? f.call(receiver, value) : f ? f.value = value : state2.set(receiver, value), value;
}
var errorUtil;
(function(errorUtil2) {
errorUtil2.errToObj = (message) => typeof message === "string" ? { message } : message || {};
errorUtil2.toString = (message) => typeof message === "string" ? message : message === null || message === void 0 ? void 0 : message.message;
})(errorUtil || (errorUtil = {}));
var _ZodEnum_cache;
var _ZodNativeEnum_cache;
var ParseInputLazyPath = class {
constructor(parent, value, path, key2) {
this._cachedPath = [];
this.parent = parent;
this.data = value;
this._path = path;
this._key = key2;
}
get path() {
if (!this._cachedPath.length) {
if (this._key instanceof Array) {
this._cachedPath.push(...this._path, ...this._key);
} else {
this._cachedPath.push(...this._path, this._key);
}
}
return this._cachedPath;
}
};
var handleResult = (ctx, result) => {
if (isValid(result)) {
return { success: true, data: result.value };
} else {
if (!ctx.common.issues.length) {
throw new Error("Validation failed but no issues detected.");
}
return {
success: false,
get error() {
if (this._error)
return this._error;
const error = new ZodError(ctx.common.issues);
this._error = error;
return this._error;
}
};
}
};
function processCreateParams(params) {
if (!params)
return {};
const { errorMap: errorMap2, invalid_type_error, required_error, description } = params;
if (errorMap2 && (invalid_type_error || required_error)) {
throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);
}
if (errorMap2)
return { errorMap: errorMap2, description };
const customMap = (iss, ctx) => {
var _a5, _b3;
const { message } = params;
if (iss.code === "invalid_enum_value") {
return { message: message !== null && message !== void 0 ? message : ctx.defaultError };
}
if (typeof ctx.data === "undefined") {
return { message: (_a5 = message !== null && message !== void 0 ? message : required_error) !== null && _a5 !== void 0 ? _a5 : ctx.defaultError };
}
if (iss.code !== "invalid_type")
return { message: ctx.defaultError };
return { message: (_b3 = message !== null && message !== void 0 ? message : invalid_type_error) !== null && _b3 !== void 0 ? _b3 : ctx.defaultError };
};
return { errorMap: customMap, description };
}
var ZodType = class {
constructor(def) {
this.spa = this.safeParseAsync;
this._def = def;
this.parse = this.parse.bind(this);
this.safeParse = this.safeParse.bind(this);
this.parseAsync = this.parseAsync.bind(this);
this.safeParseAsync = this.safeParseAsync.bind(this);
this.spa = this.spa.bind(this);
this.refine = this.refine.bind(this);
this.refinement = this.refinement.bind(this);
this.superRefine = this.superRefine.bind(this);
this.optional = this.optional.bind(this);
this.nullable = this.nullable.bind(this);
this.nullish = this.nullish.bind(this);
this.array = this.array.bind(this);
this.promise = this.promise.bind(this);
this.or = this.or.bind(this);
this.and = this.and.bind(this);
this.transform = this.transform.bind(this);
this.brand = this.brand.bind(this);
this.default = this.default.bind(this);
this.catch = this.catch.bind(this);
this.describe = this.describe.bind(this);
this.pipe = this.pipe.bind(this);
this.readonly = this.readonly.bind(this);
this.isNullable = this.isNullable.bind(this);
this.isOptional = this.isOptional.bind(this);
}
get description() {
return this._def.description;
}
_getType(input) {
return getParsedType(input.data);
}
_getOrReturnCtx(input, ctx) {
return ctx || {
common: input.parent.common,
data: input.data,
parsedType: getParsedType(input.data),
schemaErrorMap: this._def.errorMap,
path: input.path,
parent: input.parent
};
}
_processInputParams(input) {
return {
status: new ParseStatus(),
ctx: {
common: input.parent.common,
data: input.data,
parsedType: getParsedType(input.data),
schemaErrorMap: this._def.errorMap,
path: input.path,
parent: input.parent
}
};
}
_parseSync(input) {
const result = this._parse(input);
if (isAsync(result)) {
throw new Error("Synchronous parse encountered promise.");
}
return result;
}
_parseAsync(input) {
const result = this._parse(input);
return Promise.resolve(result);
}
parse(data, params) {
const result = this.safeParse(data, params);
if (result.success)
return result.data;
throw result.error;
}
safeParse(data, params) {
var _a5;
const ctx = {
common: {
issues: [],
async: (_a5 = params === null || params === void 0 ? void 0 : params.async) !== null && _a5 !== void 0 ? _a5 : false,
contextualErrorMap: params === null || params === void 0 ? void 0 : params.errorMap
},
path: (params === null || params === void 0 ? void 0 : params.path) || [],
schemaErrorMap: this._def.errorMap,
parent: null,
data,
parsedType: getParsedType(data)
};
const result = this._parseSync({ data, path: ctx.path, parent: ctx });
return handleResult(ctx, result);
}
async parseAsync(data, params) {
const result = await this.safeParseAsync(data, params);
if (result.success)
return result.data;
throw result.error;
}
async safeParseAsync(data, params) {
const ctx = {
common: {
issues: [],
contextualErrorMap: params === null || params === void 0 ? void 0 : params.errorMap,
async: true
},
path: (params === null || params === void 0 ? void 0 : params.path) || [],
schemaErrorMap: this._def.errorMap,
parent: null,
data,
parsedType: getParsedType(data)
};
const maybeAsyncResult = this._parse({ data, path: ctx.path, parent: ctx });
const result = await (isAsync(maybeAsyncResult) ? maybeAsyncResult : Promise.resolve(maybeAsyncResult));
return handleResult(ctx, result);
}
refine(check, message) {
const getIssueProperties = (val) => {
if (typeof message === "string" || typeof message === "undefined") {
return { message };
} else if (typeof message === "function") {
return message(val);
} else {
return message;
}
};
return this._refinement((val, ctx) => {
const result = check(val);
const setError = () => ctx.addIssue({
code: ZodIssueCode.custom,
...getIssueProperties(val)
});
if (typeof Promise !== "undefined" && result instanceof Promise) {
return result.then((data) => {
if (!data) {
setError();
return false;
} else {
return true;
}
});
}
if (!result) {
setError();
return false;
} else {
return true;
}
});
}
refinement(check, refinementData) {
return this._refinement((val, ctx) => {
if (!check(val)) {
ctx.addIssue(typeof refinementData === "function" ? refinementData(val, ctx) : refinementData);
return false;
} else {
return true;
}
});
}
_refinement(refinement) {
return new ZodEffects({
schema: this,
typeName: ZodFirstPartyTypeKind.ZodEffects,
effect: { type: "refinement", refinement }
});
}
superRefine(refinement) {
return this._refinement(refinement);
}
optional() {
return ZodOptional.create(this, this._def);
}
nullable() {
return ZodNullable.create(this, this._def);
}
nullish() {
return this.nullable().optional();
}
array() {
return ZodArray.create(this, this._def);
}
promise() {
return ZodPromise.create(this, this._def);
}
or(option) {
return ZodUnion.create([this, option], this._def);
}
and(incoming) {
return ZodIntersection.create(this, incoming, this._def);
}
transform(transform) {
return new ZodEffects({
...processCreateParams(this._def),
schema: this,
typeName: ZodFirstPartyTypeKind.ZodEffects,
effect: { type: "transform", transform }
});
}
default(def) {
const defaultValueFunc = typeof def === "function" ? def : () => def;
return new ZodDefault({
...processCreateParams(this._def),
innerType: this,
defaultValue: defaultValueFunc,
typeName: ZodFirstPartyTypeKind.ZodDefault
});
}
brand() {
return new ZodBranded({
typeName: ZodFirstPartyTypeKind.ZodBranded,
type: this,
...processCreateParams(this._def)
});
}
catch(def) {
const catchValueFunc = typeof def === "function" ? def : () => def;
return new ZodCatch({
...processCreateParams(this._def),
innerType: this,
catchValue: catchValueFunc,
typeName: ZodFirstPartyTypeKind.ZodCatch
});
}
describe(description) {
const This = this.constructor;
return new This({
...this._def,
description
});
}
pipe(target) {
return ZodPipeline.create(this, target);
}
readonly() {
return ZodReadonly.create(this);
}
isOptional() {
return this.safeParse(void 0).success;
}
isNullable() {
return this.safeParse(null).success;
}
};
var cuidRegex = /^c[^\s-]{8,}$/i;
var cuid2Regex = /^[0-9a-z]+$/;
var ulidRegex = /^[0-9A-HJKMNP-TV-Z]{26}$/;
var uuidRegex = /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i;
var nanoidRegex = /^[a-z0-9_-]{21}$/i;
var durationRegex = /^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/;
var emailRegex = /^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;
var _emojiRegex = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`;
var emojiRegex;
var ipv4Regex = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/;
var ipv6Regex = /^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/;
var base64Regex = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/;
var dateRegexSource = `((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))`;
var dateRegex = new RegExp(`^${dateRegexSource}$`);
function timeRegexSource(args) {
let regex = `([01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d`;
if (args.precision) {
regex = `${regex}\\.\\d{${args.precision}}`;
} else if (args.precision == null) {
regex = `${regex}(\\.\\d+)?`;
}
return regex;
}
function timeRegex(args) {
return new RegExp(`^${timeRegexSource(args)}$`);
}
function datetimeRegex(args) {
let regex = `${dateRegexSource}T${timeRegexSource(args)}`;
const opts = [];
opts.push(args.local ? `Z?` : `Z`);
if (args.offset)
opts.push(`([+-]\\d{2}:?\\d{2})`);
regex = `${regex}(${opts.join("|")})`;
return new RegExp(`^${regex}$`);
}
function isValidIP(ip, version) {
if ((version === "v4" || !version) && ipv4Regex.test(ip)) {
return true;
}
if ((version === "v6" || !version) && ipv6Regex.test(ip)) {
return true;
}
return false;
}
var ZodString = class _ZodString extends ZodType {
_parse(input) {
if (this._def.coerce) {
input.data = String(input.data);
}
const parsedType = this._getType(input);
if (parsedType !== ZodParsedType.string) {
const ctx2 = this._getOrReturnCtx(input);
addIssueToContext(ctx2, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.string,
received: ctx2.parsedType
});
return INVALID;
}
const status = new ParseStatus();
let ctx = void 0;
for (const check of this._def.checks) {
if (check.kind === "min") {
if (input.data.length < check.value) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.too_small,
minimum: check.value,
type: "string",
inclusive: true,
exact: false,
message: check.message
});
status.dirty();
}
} else if (check.kind === "max") {
if (input.data.length > check.value) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.too_big,
maximum: check.value,
type: "string",
inclusive: true,
exact: false,
message: check.message
});
status.dirty();
}
} else if (check.kind === "length") {
const tooBig = input.data.length > check.value;
const tooSmall = input.data.length < check.value;
if (tooBig || tooSmall) {
ctx = this._getOrReturnCtx(input, ctx);
if (tooBig) {
addIssueToContext(ctx, {
code: ZodIssueCode.too_big,
maximum: check.value,
type: "string",
inclusive: true,
exact: true,
message: check.message
});
} else if (tooSmall) {
addIssueToContext(ctx, {
code: ZodIssueCode.too_small,
minimum: check.value,
type: "string",
inclusive: true,
exact: true,
message: check.message
});
}
status.dirty();
}
} else if (check.kind === "email") {
if (!emailRegex.test(input.data)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
validation: "email",
code: ZodIssueCode.invalid_string,
message: check.message
});
status.dirty();
}
} else if (check.kind === "emoji") {
if (!emojiRegex) {
emojiRegex = new RegExp(_emojiRegex, "u");
}
if (!emojiRegex.test(input.data)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
validation: "emoji",
code: ZodIssueCode.invalid_string,
message: check.message
});
status.dirty();
}
} else if (check.kind === "uuid") {
if (!uuidRegex.test(input.data)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
validation: "uuid",
code: ZodIssueCode.invalid_string,
message: check.message
});
status.dirty();
}
} else if (check.kind === "nanoid") {
if (!nanoidRegex.test(input.data)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
validation: "nanoid",
code: ZodIssueCode.invalid_string,
message: check.message
});
status.dirty();
}
} else if (check.kind === "cuid") {
if (!cuidRegex.test(input.data)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
validation: "cuid",
code: ZodIssueCode.invalid_string,
message: check.message
});
status.dirty();
}
} else if (check.kind === "cuid2") {
if (!cuid2Regex.test(input.data)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
validation: "cuid2",
code: ZodIssueCode.invalid_string,
message: check.message
});
status.dirty();
}
} else if (check.kind === "ulid") {
if (!ulidRegex.test(input.data)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
validation: "ulid",
code: ZodIssueCode.invalid_string,
message: check.message
});
status.dirty();
}
} else if (check.kind === "url") {
try {
new URL(input.data);
} catch (_a5) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
validation: "url",
code: ZodIssueCode.invalid_string,
message: check.message
});
status.dirty();
}
} else if (check.kind === "regex") {
check.regex.lastIndex = 0;
const testResult = check.regex.test(input.data);
if (!testResult) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
validation: "regex",
code: ZodIssueCode.invalid_string,
message: check.message
});
status.dirty();
}
} else if (check.kind === "trim") {
input.data = input.data.trim();
} else if (check.kind === "includes") {
if (!input.data.includes(check.value, check.position)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_string,
validation: { includes: check.value, position: check.position },
message: check.message
});
status.dirty();
}
} else if (check.kind === "toLowerCase") {
input.data = input.data.toLowerCase();
} else if (check.kind === "toUpperCase") {
input.data = input.data.toUpperCase();
} else if (check.kind === "startsWith") {
if (!input.data.startsWith(check.value)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_string,
validation: { startsWith: check.value },
message: check.message
});
status.dirty();
}
} else if (check.kind === "endsWith") {
if (!input.data.endsWith(check.value)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_string,
validation: { endsWith: check.value },
message: check.message
});
status.dirty();
}
} else if (check.kind === "datetime") {
const regex = datetimeRegex(check);
if (!regex.test(input.data)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_string,
validation: "datetime",
message: check.message
});
status.dirty();
}
} else if (check.kind === "date") {
const regex = dateRegex;
if (!regex.test(input.data)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_string,
validation: "date",
message: check.message
});
status.dirty();
}
} else if (check.kind === "time") {
const regex = timeRegex(check);
if (!regex.test(input.data)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_string,
validation: "time",
message: check.message
});
status.dirty();
}
} else if (check.kind === "duration") {
if (!durationRegex.test(input.data)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
validation: "duration",
code: ZodIssueCode.invalid_string,
message: check.message
});
status.dirty();
}
} else if (check.kind === "ip") {
if (!isValidIP(input.data, check.version)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
validation: "ip",
code: ZodIssueCode.invalid_string,
message: check.message
});
status.dirty();
}
} else if (check.kind === "base64") {
if (!base64Regex.test(input.data)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
validation: "base64",
code: ZodIssueCode.invalid_string,
message: check.message
});
status.dirty();
}
} else {
util.assertNever(check);
}
}
return { status: status.value, value: input.data };
}
_regex(regex, validation, message) {
return this.refinement((data) => regex.test(data), {
validation,
code: ZodIssueCode.invalid_string,
...errorUtil.errToObj(message)
});
}
_addCheck(check) {
return new _ZodString({
...this._def,
checks: [...this._def.checks, check]
});
}
email(message) {
return this._addCheck({ kind: "email", ...errorUtil.errToObj(message) });
}
url(message) {
return this._addCheck({ kind: "url", ...errorUtil.errToObj(message) });
}
emoji(message) {
return this._addCheck({ kind: "emoji", ...errorUtil.errToObj(message) });
}
uuid(message) {
return this._addCheck({ kind: "uuid", ...errorUtil.errToObj(message) });
}
nanoid(message) {
return this._addCheck({ kind: "nanoid", ...errorUtil.errToObj(message) });
}
cuid(message) {
return this._addCheck({ kind: "cuid", ...errorUtil.errToObj(message) });
}
cuid2(message) {
return this._addCheck({ kind: "cuid2", ...errorUtil.errToObj(message) });
}
ulid(message) {
return this._addCheck({ kind: "ulid", ...errorUtil.errToObj(message) });
}
base64(message) {
return this._addCheck({ kind: "base64", ...errorUtil.errToObj(message) });
}
ip(options) {
return this._addCheck({ kind: "ip", ...errorUtil.errToObj(options) });
}
datetime(options) {
var _a5, _b3;
if (typeof options === "string") {
return this._addCheck({
kind: "datetime",
precision: null,
offset: false,
local: false,
message: options
});
}
return this._addCheck({
kind: "datetime",
precision: typeof (options === null || options === void 0 ? void 0 : options.precision) === "undefined" ? null : options === null || options === void 0 ? void 0 : options.precision,
offset: (_a5 = options === null || options === void 0 ? void 0 : options.offset) !== null && _a5 !== void 0 ? _a5 : false,
local: (_b3 = options === null || options === void 0 ? void 0 : options.local) !== null && _b3 !== void 0 ? _b3 : false,
...errorUtil.errToObj(options === null || options === void 0 ? void 0 : options.message)
});
}
date(message) {
return this._addCheck({ kind: "date", message });
}
time(options) {
if (typeof options === "string") {
return this._addCheck({
kind: "time",
precision: null,
message: options
});
}
return this._addCheck({
kind: "time",
precision: typeof (options === null || options === void 0 ? void 0 : options.precision) === "undefined" ? null : options === null || options === void 0 ? void 0 : options.precision,
...errorUtil.errToObj(options === null || options === void 0 ? void 0 : options.message)
});
}
duration(message) {
return this._addCheck({ kind: "duration", ...errorUtil.errToObj(message) });
}
regex(regex, message) {
return this._addCheck({
kind: "regex",
regex,
...errorUtil.errToObj(message)
});
}
includes(value, options) {
return this._addCheck({
kind: "includes",
value,
position: options === null || options === void 0 ? void 0 : options.position,
...errorUtil.errToObj(options === null || options === void 0 ? void 0 : options.message)
});
}
startsWith(value, message) {
return this._addCheck({
kind: "startsWith",
value,
...errorUtil.errToObj(message)
});
}
endsWith(value, message) {
return this._addCheck({
kind: "endsWith",
value,
...errorUtil.errToObj(message)
});
}
min(minLength, message) {
return this._addCheck({
kind: "min",
value: minLength,
...errorUtil.errToObj(message)
});
}
max(maxLength, message) {
return this._addCheck({
kind: "max",
value: maxLength,
...errorUtil.errToObj(message)
});
}
length(len, message) {
return this._addCheck({
kind: "length",
value: len,
...errorUtil.errToObj(message)
});
}
/**
* @deprecated Use z.string().min(1) instead.
* @see {@link ZodString.min}
*/
nonempty(message) {
return this.min(1, errorUtil.errToObj(message));
}
trim() {
return new _ZodString({
...this._def,
checks: [...this._def.checks, { kind: "trim" }]
});
}
toLowerCase() {
return new _ZodString({
...this._def,
checks: [...this._def.checks, { kind: "toLowerCase" }]
});
}
toUpperCase() {
return new _ZodString({
...this._def,
checks: [...this._def.checks, { kind: "toUpperCase" }]
});
}
get isDatetime() {
return !!this._def.checks.find((ch) => ch.kind === "datetime");
}
get isDate() {
return !!this._def.checks.find((ch) => ch.kind === "date");
}
get isTime() {
return !!this._def.checks.find((ch) => ch.kind === "time");
}
get isDuration() {
return !!this._def.checks.find((ch) => ch.kind === "duration");
}
get isEmail() {
return !!this._def.checks.find((ch) => ch.kind === "email");
}
get isURL() {
return !!this._def.checks.find((ch) => ch.kind === "url");
}
get isEmoji() {
return !!this._def.checks.find((ch) => ch.kind === "emoji");
}
get isUUID() {
return !!this._def.checks.find((ch) => ch.kind === "uuid");
}
get isNANOID() {
return !!this._def.checks.find((ch) => ch.kind === "nanoid");
}
get isCUID() {
return !!this._def.checks.find((ch) => ch.kind === "cuid");
}
get isCUID2() {
return !!this._def.checks.find((ch) => ch.kind === "cuid2");
}
get isULID() {
return !!this._def.checks.find((ch) => ch.kind === "ulid");
}
get isIP() {
return !!this._def.checks.find((ch) => ch.kind === "ip");
}
get isBase64() {
return !!this._def.checks.find((ch) => ch.kind === "base64");
}
get minLength() {
let min = null;
for (const ch of this._def.checks) {
if (ch.kind === "min") {
if (min === null || ch.value > min)
min = ch.value;
}
}
return min;
}
get maxLength() {
let max = null;
for (const ch of this._def.checks) {
if (ch.kind === "max") {
if (max === null || ch.value < max)
max = ch.value;
}
}
return max;
}
};
ZodString.create = (params) => {
var _a5;
return new ZodString({
checks: [],
typeName: ZodFirstPartyTypeKind.ZodString,
coerce: (_a5 = params === null || params === void 0 ? void 0 : params.coerce) !== null && _a5 !== void 0 ? _a5 : false,
...processCreateParams(params)
});
};
function floatSafeRemainder(val, step) {
const valDecCount = (val.toString().split(".")[1] || "").length;
const stepDecCount = (step.toString().split(".")[1] || "").length;
const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount;
const valInt = parseInt(val.toFixed(decCount).replace(".", ""));
const stepInt = parseInt(step.toFixed(decCount).replace(".", ""));
return valInt % stepInt / Math.pow(10, decCount);
}
var ZodNumber = class _ZodNumber extends ZodType {
constructor() {
super(...arguments);
this.min = this.gte;
this.max = this.lte;
this.step = this.multipleOf;
}
_parse(input) {
if (this._def.coerce) {
input.data = Number(input.data);
}
const parsedType = this._getType(input);
if (parsedType !== ZodParsedType.number) {
const ctx2 = this._getOrReturnCtx(input);
addIssueToContext(ctx2, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.number,
received: ctx2.parsedType
});
return INVALID;
}
let ctx = void 0;
const status = new ParseStatus();
for (const check of this._def.checks) {
if (check.kind === "int") {
if (!util.isInteger(input.data)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: "integer",
received: "float",
message: check.message
});
status.dirty();
}
} else if (check.kind === "min") {
const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value;
if (tooSmall) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.too_small,
minimum: check.value,
type: "number",
inclusive: check.inclusive,
exact: false,
message: check.message
});
status.dirty();
}
} else if (check.kind === "max") {
const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value;
if (tooBig) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.too_big,
maximum: check.value,
type: "number",
inclusive: check.inclusive,
exact: false,
message: check.message
});
status.dirty();
}
} else if (check.kind === "multipleOf") {
if (floatSafeRemainder(input.data, check.value) !== 0) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.not_multiple_of,
multipleOf: check.value,
message: check.message
});
status.dirty();
}
} else if (check.kind === "finite") {
if (!Number.isFinite(input.data)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.not_finite,
message: check.message
});
status.dirty();
}
} else {
util.assertNever(check);
}
}
return { status: status.value, value: input.data };
}
gte(value, message) {
return this.setLimit("min", value, true, errorUtil.toString(message));
}
gt(value, message) {
return this.setLimit("min", value, false, errorUtil.toString(message));
}
lte(value, message) {
return this.setLimit("max", value, true, errorUtil.toString(message));
}
lt(value, message) {
return this.setLimit("max", value, false, errorUtil.toString(message));
}
setLimit(kind, value, inclusive, message) {
return new _ZodNumber({
...this._def,
checks: [
...this._def.checks,
{
kind,
value,
inclusive,
message: errorUtil.toString(message)
}
]
});
}
_addCheck(check) {
return new _ZodNumber({
...this._def,
checks: [...this._def.checks, check]
});
}
int(message) {
return this._addCheck({
kind: "int",
message: errorUtil.toString(message)
});
}
positive(message) {
return this._addCheck({
kind: "min",
value: 0,
inclusive: false,
message: errorUtil.toString(message)
});
}
negative(message) {
return this._addCheck({
kind: "max",
value: 0,
inclusive: false,
message: errorUtil.toString(message)
});
}
nonpositive(message) {
return this._addCheck({
kind: "max",
value: 0,
inclusive: true,
message: errorUtil.toString(message)
});
}
nonnegative(message) {
return this._addCheck({
kind: "min",
value: 0,
inclusive: true,
message: errorUtil.toString(message)
});
}
multipleOf(value, message) {
return this._addCheck({
kind: "multipleOf",
value,
message: errorUtil.toString(message)
});
}
finite(message) {
return this._addCheck({
kind: "finite",
message: errorUtil.toString(message)
});
}
safe(message) {
return this._addCheck({
kind: "min",
inclusive: true,
value: Number.MIN_SAFE_INTEGER,
message: errorUtil.toString(message)
})._addCheck({
kind: "max",
inclusive: true,
value: Number.MAX_SAFE_INTEGER,
message: errorUtil.toString(message)
});
}
get minValue() {
let min = null;
for (const ch of this._def.checks) {
if (ch.kind === "min") {
if (min === null || ch.value > min)
min = ch.value;
}
}
return min;
}
get maxValue() {
let max = null;
for (const ch of this._def.checks) {
if (ch.kind === "max") {
if (max === null || ch.value < max)
max = ch.value;
}
}
return max;
}
get isInt() {
return !!this._def.checks.find((ch) => ch.kind === "int" || ch.kind === "multipleOf" && util.isInteger(ch.value));
}
get isFinite() {
let max = null, min = null;
for (const ch of this._def.checks) {
if (ch.kind === "finite" || ch.kind === "int" || ch.kind === "multipleOf") {
return true;
} else if (ch.kind === "min") {
if (min === null || ch.value > min)
min = ch.value;
} else if (ch.kind === "max") {
if (max === null || ch.value < max)
max = ch.value;
}
}
return Number.isFinite(min) && Number.isFinite(max);
}
};
ZodNumber.create = (params) => {
return new ZodNumber({
checks: [],
typeName: ZodFirstPartyTypeKind.ZodNumber,
coerce: (params === null || params === void 0 ? void 0 : params.coerce) || false,
...processCreateParams(params)
});
};
var ZodBigInt = class _ZodBigInt extends ZodType {
constructor() {
super(...arguments);
this.min = this.gte;
this.max = this.lte;
}
_parse(input) {
if (this._def.coerce) {
input.data = BigInt(input.data);
}
const parsedType = this._getType(input);
if (parsedType !== ZodParsedType.bigint) {
const ctx2 = this._getOrReturnCtx(input);
addIssueToContext(ctx2, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.bigint,
received: ctx2.parsedType
});
return INVALID;
}
let ctx = void 0;
const status = new ParseStatus();
for (const check of this._def.checks) {
if (check.kind === "min") {
const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value;
if (tooSmall) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.too_small,
type: "bigint",
minimum: check.value,
inclusive: check.inclusive,
message: check.message
});
status.dirty();
}
} else if (check.kind === "max") {
const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value;
if (tooBig) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.too_big,
type: "bigint",
maximum: check.value,
inclusive: check.inclusive,
message: check.message
});
status.dirty();
}
} else if (check.kind === "multipleOf") {
if (input.data % check.value !== BigInt(0)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.not_multiple_of,
multipleOf: check.value,
message: check.message
});
status.dirty();
}
} else {
util.assertNever(check);
}
}
return { status: status.value, value: input.data };
}
gte(value, message) {
return this.setLimit("min", value, true, errorUtil.toString(message));
}
gt(value, message) {
return this.setLimit("min", value, false, errorUtil.toString(message));
}
lte(value, message) {
return this.setLimit("max", value, true, errorUtil.toString(message));
}
lt(value, message) {
return this.setLimit("max", value, false, errorUtil.toString(message));
}
setLimit(kind, value, inclusive, message) {
return new _ZodBigInt({
...this._def,
checks: [
...this._def.checks,
{
kind,
value,
inclusive,
message: errorUtil.toString(message)
}
]
});
}
_addCheck(check) {
return new _ZodBigInt({
...this._def,
checks: [...this._def.checks, check]
});
}
positive(message) {
return this._addCheck({
kind: "min",
value: BigInt(0),
inclusive: false,
message: errorUtil.toString(message)
});
}
negative(message) {
return this._addCheck({
kind: "max",
value: BigInt(0),
inclusive: false,
message: errorUtil.toString(message)
});
}
nonpositive(message) {
return this._addCheck({
kind: "max",
value: BigInt(0),
inclusive: true,
message: errorUtil.toString(message)
});
}
nonnegative(message) {
return this._addCheck({
kind: "min",
value: BigInt(0),
inclusive: true,
message: errorUtil.toString(message)
});
}
multipleOf(value, message) {
return this._addCheck({
kind: "multipleOf",
value,
message: errorUtil.toString(message)
});
}
get minValue() {
let min = null;
for (const ch of this._def.checks) {
if (ch.kind === "min") {
if (min === null || ch.value > min)
min = ch.value;
}
}
return min;
}
get maxValue() {
let max = null;
for (const ch of this._def.checks) {
if (ch.kind === "max") {
if (max === null || ch.value < max)
max = ch.value;
}
}
return max;
}
};
ZodBigInt.create = (params) => {
var _a5;
return new ZodBigInt({
checks: [],
typeName: ZodFirstPartyTypeKind.ZodBigInt,
coerce: (_a5 = params === null || params === void 0 ? void 0 : params.coerce) !== null && _a5 !== void 0 ? _a5 : false,
...processCreateParams(params)
});
};
var ZodBoolean = class extends ZodType {
_parse(input) {
if (this._def.coerce) {
input.data = Boolean(input.data);
}
const parsedType = this._getType(input);
if (parsedType !== ZodParsedType.boolean) {
const ctx = this._getOrReturnCtx(input);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.boolean,
received: ctx.parsedType
});
return INVALID;
}
return OK(input.data);
}
};
ZodBoolean.create = (params) => {
return new ZodBoolean({
typeName: ZodFirstPartyTypeKind.ZodBoolean,
coerce: (params === null || params === void 0 ? void 0 : params.coerce) || false,
...processCreateParams(params)
});
};
var ZodDate = class _ZodDate extends ZodType {
_parse(input) {
if (this._def.coerce) {
input.data = new Date(input.data);
}
const parsedType = this._getType(input);
if (parsedType !== ZodParsedType.date) {
const ctx2 = this._getOrReturnCtx(input);
addIssueToContext(ctx2, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.date,
received: ctx2.parsedType
});
return INVALID;
}
if (isNaN(input.data.getTime())) {
const ctx2 = this._getOrReturnCtx(input);
addIssueToContext(ctx2, {
code: ZodIssueCode.invalid_date
});
return INVALID;
}
const status = new ParseStatus();
let ctx = void 0;
for (const check of this._def.checks) {
if (check.kind === "min") {
if (input.data.getTime() < check.value) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.too_small,
message: check.message,
inclusive: true,
exact: false,
minimum: check.value,
type: "date"
});
status.dirty();
}
} else if (check.kind === "max") {
if (input.data.getTime() > check.value) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.too_big,
message: check.message,
inclusive: true,
exact: false,
maximum: check.value,
type: "date"
});
status.dirty();
}
} else {
util.assertNever(check);
}
}
return {
status: status.value,
value: new Date(input.data.getTime())
};
}
_addCheck(check) {
return new _ZodDate({
...this._def,
checks: [...this._def.checks, check]
});
}
min(minDate, message) {
return this._addCheck({
kind: "min",
value: minDate.getTime(),
message: errorUtil.toString(message)
});
}
max(maxDate, message) {
return this._addCheck({
kind: "max",
value: maxDate.getTime(),
message: errorUtil.toString(message)
});
}
get minDate() {
let min = null;
for (const ch of this._def.checks) {
if (ch.kind === "min") {
if (min === null || ch.value > min)
min = ch.value;
}
}
return min != null ? new Date(min) : null;
}
get maxDate() {
let max = null;
for (const ch of this._def.checks) {
if (ch.kind === "max") {
if (max === null || ch.value < max)
max = ch.value;
}
}
return max != null ? new Date(max) : null;
}
};
ZodDate.create = (params) => {
return new ZodDate({
checks: [],
coerce: (params === null || params === void 0 ? void 0 : params.coerce) || false,
typeName: ZodFirstPartyTypeKind.ZodDate,
...processCreateParams(params)
});
};
var ZodSymbol = class extends ZodType {
_parse(input) {
const parsedType = this._getType(input);
if (parsedType !== ZodParsedType.symbol) {
const ctx = this._getOrReturnCtx(input);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.symbol,
received: ctx.parsedType
});
return INVALID;
}
return OK(input.data);
}
};
ZodSymbol.create = (params) => {
return new ZodSymbol({
typeName: ZodFirstPartyTypeKind.ZodSymbol,
...processCreateParams(params)
});
};
var ZodUndefined = class extends ZodType {
_parse(input) {
const parsedType = this._getType(input);
if (parsedType !== ZodParsedType.undefined) {
const ctx = this._getOrReturnCtx(input);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.undefined,
received: ctx.parsedType
});
return INVALID;
}
return OK(input.data);
}
};
ZodUndefined.create = (params) => {
return new ZodUndefined({
typeName: ZodFirstPartyTypeKind.ZodUndefined,
...processCreateParams(params)
});
};
var ZodNull = class extends ZodType {
_parse(input) {
const parsedType = this._getType(input);
if (parsedType !== ZodParsedType.null) {
const ctx = this._getOrReturnCtx(input);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.null,
received: ctx.parsedType
});
return INVALID;
}
return OK(input.data);
}
};
ZodNull.create = (params) => {
return new ZodNull({
typeName: ZodFirstPartyTypeKind.ZodNull,
...processCreateParams(params)
});
};
var ZodAny = class extends ZodType {
constructor() {
super(...arguments);
this._any = true;
}
_parse(input) {
return OK(input.data);
}
};
ZodAny.create = (params) => {
return new ZodAny({
typeName: ZodFirstPartyTypeKind.ZodAny,
...processCreateParams(params)
});
};
var ZodUnknown = class extends ZodType {
constructor() {
super(...arguments);
this._unknown = true;
}
_parse(input) {
return OK(input.data);
}
};
ZodUnknown.create = (params) => {
return new ZodUnknown({
typeName: ZodFirstPartyTypeKind.ZodUnknown,
...processCreateParams(params)
});
};
var ZodNever = class extends ZodType {
_parse(input) {
const ctx = this._getOrReturnCtx(input);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.never,
received: ctx.parsedType
});
return INVALID;
}
};
ZodNever.create = (params) => {
return new ZodNever({
typeName: ZodFirstPartyTypeKind.ZodNever,
...processCreateParams(params)
});
};
var ZodVoid = class extends ZodType {
_parse(input) {
const parsedType = this._getType(input);
if (parsedType !== ZodParsedType.undefined) {
const ctx = this._getOrReturnCtx(input);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.void,
received: ctx.parsedType
});
return INVALID;
}
return OK(input.data);
}
};
ZodVoid.create = (params) => {
return new ZodVoid({
typeName: ZodFirstPartyTypeKind.ZodVoid,
...processCreateParams(params)
});
};
var ZodArray = class _ZodArray extends ZodType {
_parse(input) {
const { ctx, status } = this._processInputParams(input);
const def = this._def;
if (ctx.parsedType !== ZodParsedType.array) {
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.array,
received: ctx.parsedType
});
return INVALID;
}
if (def.exactLength !== null) {
const tooBig = ctx.data.length > def.exactLength.value;
const tooSmall = ctx.data.length < def.exactLength.value;
if (tooBig || tooSmall) {
addIssueToContext(ctx, {
code: tooBig ? ZodIssueCode.too_big : ZodIssueCode.too_small,
minimum: tooSmall ? def.exactLength.value : void 0,
maximum: tooBig ? def.exactLength.value : void 0,
type: "array",
inclusive: true,
exact: true,
message: def.exactLength.message
});
status.dirty();
}
}
if (def.minLength !== null) {
if (ctx.data.length < def.minLength.value) {
addIssueToContext(ctx, {
code: ZodIssueCode.too_small,
minimum: def.minLength.value,
type: "array",
inclusive: true,
exact: false,
message: def.minLength.message
});
status.dirty();
}
}
if (def.maxLength !== null) {
if (ctx.data.length > def.maxLength.value) {
addIssueToContext(ctx, {
code: ZodIssueCode.too_big,
maximum: def.maxLength.value,
type: "array",
inclusive: true,
exact: false,
message: def.maxLength.message
});
status.dirty();
}
}
if (ctx.common.async) {
return Promise.all([...ctx.data].map((item, i) => {
return def.type._parseAsync(new ParseInputLazyPath(ctx, item, ctx.path, i));
})).then((result2) => {
return ParseStatus.mergeArray(status, result2);
});
}
const result = [...ctx.data].map((item, i) => {
return def.type._parseSync(new ParseInputLazyPath(ctx, item, ctx.path, i));
});
return ParseStatus.mergeArray(status, result);
}
get element() {
return this._def.type;
}
min(minLength, message) {
return new _ZodArray({
...this._def,
minLength: { value: minLength, message: errorUtil.toString(message) }
});
}
max(maxLength, message) {
return new _ZodArray({
...this._def,
maxLength: { value: maxLength, message: errorUtil.toString(message) }
});
}
length(len, message) {
return new _ZodArray({
...this._def,
exactLength: { value: len, message: errorUtil.toString(message) }
});
}
nonempty(message) {
return this.min(1, message);
}
};
ZodArray.create = (schema2, params) => {
return new ZodArray({
type: schema2,
minLength: null,
maxLength: null,
exactLength: null,
typeName: ZodFirstPartyTypeKind.ZodArray,
...processCreateParams(params)
});
};
function deepPartialify(schema2) {
if (schema2 instanceof ZodObject) {
const newShape = {};
for (const key2 in schema2.shape) {
const fieldSchema = schema2.shape[key2];
newShape[key2] = ZodOptional.create(deepPartialify(fieldSchema));
}
return new ZodObject({
...schema2._def,
shape: () => newShape
});
} else if (schema2 instanceof ZodArray) {
return new ZodArray({
...schema2._def,
type: deepPartialify(schema2.element)
});
} else if (schema2 instanceof ZodOptional) {
return ZodOptional.create(deepPartialify(schema2.unwrap()));
} else if (schema2 instanceof ZodNullable) {
return ZodNullable.create(deepPartialify(schema2.unwrap()));
} else if (schema2 instanceof ZodTuple) {
return ZodTuple.create(schema2.items.map((item) => deepPartialify(item)));
} else {
return schema2;
}
}
var ZodObject = class _ZodObject extends ZodType {
constructor() {
super(...arguments);
this._cached = null;
this.nonstrict = this.passthrough;
this.augment = this.extend;
}
_getCached() {
if (this._cached !== null)
return this._cached;
const shape = this._def.shape();
const keys = util.objectKeys(shape);
return this._cached = { shape, keys };
}
_parse(input) {
const parsedType = this._getType(input);
if (parsedType !== ZodParsedType.object) {
const ctx2 = this._getOrReturnCtx(input);
addIssueToContext(ctx2, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.object,
received: ctx2.parsedType
});
return INVALID;
}
const { status, ctx } = this._processInputParams(input);
const { shape, keys: shapeKeys } = this._getCached();
const extraKeys = [];
if (!(this._def.catchall instanceof ZodNever && this._def.unknownKeys === "strip")) {
for (const key2 in ctx.data) {
if (!shapeKeys.includes(key2)) {
extraKeys.push(key2);
}
}
}
const pairs2 = [];
for (const key2 of shapeKeys) {
const keyValidator = shape[key2];
const value = ctx.data[key2];
pairs2.push({
key: { status: "valid", value: key2 },
value: keyValidator._parse(new ParseInputLazyPath(ctx, value, ctx.path, key2)),
alwaysSet: key2 in ctx.data
});
}
if (this._def.catchall instanceof ZodNever) {
const unknownKeys = this._def.unknownKeys;
if (unknownKeys === "passthrough") {
for (const key2 of extraKeys) {
pairs2.push({
key: { status: "valid", value: key2 },
value: { status: "valid", value: ctx.data[key2] }
});
}
} else if (unknownKeys === "strict") {
if (extraKeys.length > 0) {
addIssueToContext(ctx, {
code: ZodIssueCode.unrecognized_keys,
keys: extraKeys
});
status.dirty();
}
} else if (unknownKeys === "strip") ;
else {
throw new Error(`Internal ZodObject error: invalid unknownKeys value.`);
}
} else {
const catchall = this._def.catchall;
for (const key2 of extraKeys) {
const value = ctx.data[key2];
pairs2.push({
key: { status: "valid", value: key2 },
value: catchall._parse(
new ParseInputLazyPath(ctx, value, ctx.path, key2)
//, ctx.child(key), value, getParsedType(value)
),
alwaysSet: key2 in ctx.data
});
}
}
if (ctx.common.async) {
return Promise.resolve().then(async () => {
const syncPairs = [];
for (const pair of pairs2) {
const key2 = await pair.key;
const value = await pair.value;
syncPairs.push({
key: key2,
value,
alwaysSet: pair.alwaysSet
});
}
return syncPairs;
}).then((syncPairs) => {
return ParseStatus.mergeObjectSync(status, syncPairs);
});
} else {
return ParseStatus.mergeObjectSync(status, pairs2);
}
}
get shape() {
return this._def.shape();
}
strict(message) {
errorUtil.errToObj;
return new _ZodObject({
...this._def,
unknownKeys: "strict",
...message !== void 0 ? {
errorMap: (issue, ctx) => {
var _a5, _b3, _c2, _d;
const defaultError = (_c2 = (_b3 = (_a5 = this._def).errorMap) === null || _b3 === void 0 ? void 0 : _b3.call(_a5, issue, ctx).message) !== null && _c2 !== void 0 ? _c2 : ctx.defaultError;
if (issue.code === "unrecognized_keys")
return {
message: (_d = errorUtil.errToObj(message).message) !== null && _d !== void 0 ? _d : defaultError
};
return {
message: defaultError
};
}
} : {}
});
}
strip() {
return new _ZodObject({
...this._def,
unknownKeys: "strip"
});
}
passthrough() {
return new _ZodObject({
...this._def,
unknownKeys: "passthrough"
});
}
// const AugmentFactory =
// <Def extends ZodObjectDef>(def: Def) =>
// <Augmentation extends ZodRawShape>(
// augmentation: Augmentation
// ): ZodObject<
// extendShape<ReturnType<Def["shape"]>, Augmentation>,
// Def["unknownKeys"],
// Def["catchall"]
// > => {
// return new ZodObject({
// ...def,
// shape: () => ({
// ...def.shape(),
// ...augmentation,
// }),
// }) as any;
// };
extend(augmentation) {
return new _ZodObject({
...this._def,
shape: () => ({
...this._def.shape(),
...augmentation
})
});
}
/**
* Prior to zod@1.0.12 there was a bug in the
* inferred type of merged objects. Please
* upgrade if you are experiencing issues.
*/
merge(merging) {
const merged = new _ZodObject({
unknownKeys: merging._def.unknownKeys,
catchall: merging._def.catchall,
shape: () => ({
...this._def.shape(),
...merging._def.shape()
}),
typeName: ZodFirstPartyTypeKind.ZodObject
});
return merged;
}
// merge<
// Incoming extends AnyZodObject,
// Augmentation extends Incoming["shape"],
// NewOutput extends {
// [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation
// ? Augmentation[k]["_output"]
// : k extends keyof Output
// ? Output[k]
// : never;
// },
// NewInput extends {
// [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation
// ? Augmentation[k]["_input"]
// : k extends keyof Input
// ? Input[k]
// : never;
// }
// >(
// merging: Incoming
// ): ZodObject<
// extendShape<T, ReturnType<Incoming["_def"]["shape"]>>,
// Incoming["_def"]["unknownKeys"],
// Incoming["_def"]["catchall"],
// NewOutput,
// NewInput
// > {
// const merged: any = new ZodObject({
// unknownKeys: merging._def.unknownKeys,
// catchall: merging._def.catchall,
// shape: () =>
// objectUtil.mergeShapes(this._def.shape(), merging._def.shape()),
// typeName: ZodFirstPartyTypeKind.ZodObject,
// }) as any;
// return merged;
// }
setKey(key2, schema2) {
return this.augment({ [key2]: schema2 });
}
// merge<Incoming extends AnyZodObject>(
// merging: Incoming
// ): //ZodObject<T & Incoming["_shape"], UnknownKeys, Catchall> = (merging) => {
// ZodObject<
// extendShape<T, ReturnType<Incoming["_def"]["shape"]>>,
// Incoming["_def"]["unknownKeys"],
// Incoming["_def"]["catchall"]
// > {
// // const mergedShape = objectUtil.mergeShapes(
// // this._def.shape(),
// // merging._def.shape()
// // );
// const merged: any = new ZodObject({
// unknownKeys: merging._def.unknownKeys,
// catchall: merging._def.catchall,
// shape: () =>
// objectUtil.mergeShapes(this._def.shape(), merging._def.shape()),
// typeName: ZodFirstPartyTypeKind.ZodObject,
// }) as any;
// return merged;
// }
catchall(index2) {
return new _ZodObject({
...this._def,
catchall: index2
});
}
pick(mask) {
const shape = {};
util.objectKeys(mask).forEach((key2) => {
if (mask[key2] && this.shape[key2]) {
shape[key2] = this.shape[key2];
}
});
return new _ZodObject({
...this._def,
shape: () => shape
});
}
omit(mask) {
const shape = {};
util.objectKeys(this.shape).forEach((key2) => {
if (!mask[key2]) {
shape[key2] = this.shape[key2];
}
});
return new _ZodObject({
...this._def,
shape: () => shape
});
}
/**
* @deprecated
*/
deepPartial() {
return deepPartialify(this);
}
partial(mask) {
const newShape = {};
util.objectKeys(this.shape).forEach((key2) => {
const fieldSchema = this.shape[key2];
if (mask && !mask[key2]) {
newShape[key2] = fieldSchema;
} else {
newShape[key2] = fieldSchema.optional();
}
});
return new _ZodObject({
...this._def,
shape: () => newShape
});
}
required(mask) {
const newShape = {};
util.objectKeys(this.shape).forEach((key2) => {
if (mask && !mask[key2]) {
newShape[key2] = this.shape[key2];
} else {
const fieldSchema = this.shape[key2];
let newField = fieldSchema;
while (newField instanceof ZodOptional) {
newField = newField._def.innerType;
}
newShape[key2] = newField;
}
});
return new _ZodObject({
...this._def,
shape: () => newShape
});
}
keyof() {
return createZodEnum(util.objectKeys(this.shape));
}
};
ZodObject.create = (shape, params) => {
return new ZodObject({
shape: () => shape,
unknownKeys: "strip",
catchall: ZodNever.create(),
typeName: ZodFirstPartyTypeKind.ZodObject,
...processCreateParams(params)
});
};
ZodObject.strictCreate = (shape, params) => {
return new ZodObject({
shape: () => shape,
unknownKeys: "strict",
catchall: ZodNever.create(),
typeName: ZodFirstPartyTypeKind.ZodObject,
...processCreateParams(params)
});
};
ZodObject.lazycreate = (shape, params) => {
return new ZodObject({
shape,
unknownKeys: "strip",
catchall: ZodNever.create(),
typeName: ZodFirstPartyTypeKind.ZodObject,
...processCreateParams(params)
});
};
var ZodUnion = class extends ZodType {
_parse(input) {
const { ctx } = this._processInputParams(input);
const options = this._def.options;
function handleResults(results) {
for (const result of results) {
if (result.result.status === "valid") {
return result.result;
}
}
for (const result of results) {
if (result.result.status === "dirty") {
ctx.common.issues.push(...result.ctx.common.issues);
return result.result;
}
}
const unionErrors = results.map((result) => new ZodError(result.ctx.common.issues));
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_union,
unionErrors
});
return INVALID;
}
if (ctx.common.async) {
return Promise.all(options.map(async (option) => {
const childCtx = {
...ctx,
common: {
...ctx.common,
issues: []
},
parent: null
};
return {
result: await option._parseAsync({
data: ctx.data,
path: ctx.path,
parent: childCtx
}),
ctx: childCtx
};
})).then(handleResults);
} else {
let dirty = void 0;
const issues = [];
for (const option of options) {
const childCtx = {
...ctx,
common: {
...ctx.common,
issues: []
},
parent: null
};
const result = option._parseSync({
data: ctx.data,
path: ctx.path,
parent: childCtx
});
if (result.status === "valid") {
return result;
} else if (result.status === "dirty" && !dirty) {
dirty = { result, ctx: childCtx };
}
if (childCtx.common.issues.length) {
issues.push(childCtx.common.issues);
}
}
if (dirty) {
ctx.common.issues.push(...dirty.ctx.common.issues);
return dirty.result;
}
const unionErrors = issues.map((issues2) => new ZodError(issues2));
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_union,
unionErrors
});
return INVALID;
}
}
get options() {
return this._def.options;
}
};
ZodUnion.create = (types2, params) => {
return new ZodUnion({
options: types2,
typeName: ZodFirstPartyTypeKind.ZodUnion,
...processCreateParams(params)
});
};
var getDiscriminator = (type2) => {
if (type2 instanceof ZodLazy) {
return getDiscriminator(type2.schema);
} else if (type2 instanceof ZodEffects) {
return getDiscriminator(type2.innerType());
} else if (type2 instanceof ZodLiteral) {
return [type2.value];
} else if (type2 instanceof ZodEnum) {
return type2.options;
} else if (type2 instanceof ZodNativeEnum) {
return util.objectValues(type2.enum);
} else if (type2 instanceof ZodDefault) {
return getDiscriminator(type2._def.innerType);
} else if (type2 instanceof ZodUndefined) {
return [void 0];
} else if (type2 instanceof ZodNull) {
return [null];
} else if (type2 instanceof ZodOptional) {
return [void 0, ...getDiscriminator(type2.unwrap())];
} else if (type2 instanceof ZodNullable) {
return [null, ...getDiscriminator(type2.unwrap())];
} else if (type2 instanceof ZodBranded) {
return getDiscriminator(type2.unwrap());
} else if (type2 instanceof ZodReadonly) {
return getDiscriminator(type2.unwrap());
} else if (type2 instanceof ZodCatch) {
return getDiscriminator(type2._def.innerType);
} else {
return [];
}
};
var ZodDiscriminatedUnion = class _ZodDiscriminatedUnion extends ZodType {
_parse(input) {
const { ctx } = this._processInputParams(input);
if (ctx.parsedType !== ZodParsedType.object) {
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.object,
received: ctx.parsedType
});
return INVALID;
}
const discriminator = this.discriminator;
const discriminatorValue = ctx.data[discriminator];
const option = this.optionsMap.get(discriminatorValue);
if (!option) {
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_union_discriminator,
options: Array.from(this.optionsMap.keys()),
path: [discriminator]
});
return INVALID;
}
if (ctx.common.async) {
return option._parseAsync({
data: ctx.data,
path: ctx.path,
parent: ctx
});
} else {
return option._parseSync({
data: ctx.data,
path: ctx.path,
parent: ctx
});
}
}
get discriminator() {
return this._def.discriminator;
}
get options() {
return this._def.options;
}
get optionsMap() {
return this._def.optionsMap;
}
/**
* The constructor of the discriminated union schema. Its behaviour is very similar to that of the normal z.union() constructor.
* However, it only allows a union of objects, all of which need to share a discriminator property. This property must
* have a different value for each object in the union.
* @param discriminator the name of the discriminator property
* @param types an array of object schemas
* @param params
*/
static create(discriminator, options, params) {
const optionsMap = /* @__PURE__ */ new Map();
for (const type2 of options) {
const discriminatorValues = getDiscriminator(type2.shape[discriminator]);
if (!discriminatorValues.length) {
throw new Error(`A discriminator value for key \`${discriminator}\` could not be extracted from all schema options`);
}
for (const value of discriminatorValues) {
if (optionsMap.has(value)) {
throw new Error(`Discriminator property ${String(discriminator)} has duplicate value ${String(value)}`);
}
optionsMap.set(value, type2);
}
}
return new _ZodDiscriminatedUnion({
typeName: ZodFirstPartyTypeKind.ZodDiscriminatedUnion,
discriminator,
options,
optionsMap,
...processCreateParams(params)
});
}
};
function mergeValues(a, b) {
const aType = getParsedType(a);
const bType = getParsedType(b);
if (a === b) {
return { valid: true, data: a };
} else if (aType === ZodParsedType.object && bType === ZodParsedType.object) {
const bKeys = util.objectKeys(b);
const sharedKeys = util.objectKeys(a).filter((key2) => bKeys.indexOf(key2) !== -1);
const newObj = { ...a, ...b };
for (const key2 of sharedKeys) {
const sharedValue = mergeValues(a[key2], b[key2]);
if (!sharedValue.valid) {
return { valid: false };
}
newObj[key2] = sharedValue.data;
}
return { valid: true, data: newObj };
} else if (aType === ZodParsedType.array && bType === ZodParsedType.array) {
if (a.length !== b.length) {
return { valid: false };
}
const newArray = [];
for (let index2 = 0; index2 < a.length; index2++) {
const itemA = a[index2];
const itemB = b[index2];
const sharedValue = mergeValues(itemA, itemB);
if (!sharedValue.valid) {
return { valid: false };
}
newArray.push(sharedValue.data);
}
return { valid: true, data: newArray };
} else if (aType === ZodParsedType.date && bType === ZodParsedType.date && +a === +b) {
return { valid: true, data: a };
} else {
return { valid: false };
}
}
var ZodIntersection = class extends ZodType {
_parse(input) {
const { status, ctx } = this._processInputParams(input);
const handleParsed = (parsedLeft, parsedRight) => {
if (isAborted(parsedLeft) || isAborted(parsedRight)) {
return INVALID;
}
const merged = mergeValues(parsedLeft.value, parsedRight.value);
if (!merged.valid) {
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_intersection_types
});
return INVALID;
}
if (isDirty(parsedLeft) || isDirty(parsedRight)) {
status.dirty();
}
return { status: status.value, value: merged.data };
};
if (ctx.common.async) {
return Promise.all([
this._def.left._parseAsync({
data: ctx.data,
path: ctx.path,
parent: ctx
}),
this._def.right._parseAsync({
data: ctx.data,
path: ctx.path,
parent: ctx
})
]).then(([left, right]) => handleParsed(left, right));
} else {
return handleParsed(this._def.left._parseSync({
data: ctx.data,
path: ctx.path,
parent: ctx
}), this._def.right._parseSync({
data: ctx.data,
path: ctx.path,
parent: ctx
}));
}
}
};
ZodIntersection.create = (left, right, params) => {
return new ZodIntersection({
left,
right,
typeName: ZodFirstPartyTypeKind.ZodIntersection,
...processCreateParams(params)
});
};
var ZodTuple = class _ZodTuple extends ZodType {
_parse(input) {
const { status, ctx } = this._processInputParams(input);
if (ctx.parsedType !== ZodParsedType.array) {
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.array,
received: ctx.parsedType
});
return INVALID;
}
if (ctx.data.length < this._def.items.length) {
addIssueToContext(ctx, {
code: ZodIssueCode.too_small,
minimum: this._def.items.length,
inclusive: true,
exact: false,
type: "array"
});
return INVALID;
}
const rest = this._def.rest;
if (!rest && ctx.data.length > this._def.items.length) {
addIssueToContext(ctx, {
code: ZodIssueCode.too_big,
maximum: this._def.items.length,
inclusive: true,
exact: false,
type: "array"
});
status.dirty();
}
const items = [...ctx.data].map((item, itemIndex) => {
const schema2 = this._def.items[itemIndex] || this._def.rest;
if (!schema2)
return null;
return schema2._parse(new ParseInputLazyPath(ctx, item, ctx.path, itemIndex));
}).filter((x) => !!x);
if (ctx.common.async) {
return Promise.all(items).then((results) => {
return ParseStatus.mergeArray(status, results);
});
} else {
return ParseStatus.mergeArray(status, items);
}
}
get items() {
return this._def.items;
}
rest(rest) {
return new _ZodTuple({
...this._def,
rest
});
}
};
ZodTuple.create = (schemas, params) => {
if (!Array.isArray(schemas)) {
throw new Error("You must pass an array of schemas to z.tuple([ ... ])");
}
return new ZodTuple({
items: schemas,
typeName: ZodFirstPartyTypeKind.ZodTuple,
rest: null,
...processCreateParams(params)
});
};
var ZodRecord = class _ZodRecord extends ZodType {
get keySchema() {
return this._def.keyType;
}
get valueSchema() {
return this._def.valueType;
}
_parse(input) {
const { status, ctx } = this._processInputParams(input);
if (ctx.parsedType !== ZodParsedType.object) {
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.object,
received: ctx.parsedType
});
return INVALID;
}
const pairs2 = [];
const keyType = this._def.keyType;
const valueType = this._def.valueType;
for (const key2 in ctx.data) {
pairs2.push({
key: keyType._parse(new ParseInputLazyPath(ctx, key2, ctx.path, key2)),
value: valueType._parse(new ParseInputLazyPath(ctx, ctx.data[key2], ctx.path, key2)),
alwaysSet: key2 in ctx.data
});
}
if (ctx.common.async) {
return ParseStatus.mergeObjectAsync(status, pairs2);
} else {
return ParseStatus.mergeObjectSync(status, pairs2);
}
}
get element() {
return this._def.valueType;
}
static create(first, second, third) {
if (second instanceof ZodType) {
return new _ZodRecord({
keyType: first,
valueType: second,
typeName: ZodFirstPartyTypeKind.ZodRecord,
...processCreateParams(third)
});
}
return new _ZodRecord({
keyType: ZodString.create(),
valueType: first,
typeName: ZodFirstPartyTypeKind.ZodRecord,
...processCreateParams(second)
});
}
};
var ZodMap = class extends ZodType {
get keySchema() {
return this._def.keyType;
}
get valueSchema() {
return this._def.valueType;
}
_parse(input) {
const { status, ctx } = this._processInputParams(input);
if (ctx.parsedType !== ZodParsedType.map) {
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.map,
received: ctx.parsedType
});
return INVALID;
}
const keyType = this._def.keyType;
const valueType = this._def.valueType;
const pairs2 = [...ctx.data.entries()].map(([key2, value], index2) => {
return {
key: keyType._parse(new ParseInputLazyPath(ctx, key2, ctx.path, [index2, "key"])),
value: valueType._parse(new ParseInputLazyPath(ctx, value, ctx.path, [index2, "value"]))
};
});
if (ctx.common.async) {
const finalMap = /* @__PURE__ */ new Map();
return Promise.resolve().then(async () => {
for (const pair of pairs2) {
const key2 = await pair.key;
const value = await pair.value;
if (key2.status === "aborted" || value.status === "aborted") {
return INVALID;
}
if (key2.status === "dirty" || value.status === "dirty") {
status.dirty();
}
finalMap.set(key2.value, value.value);
}
return { status: status.value, value: finalMap };
});
} else {
const finalMap = /* @__PURE__ */ new Map();
for (const pair of pairs2) {
const key2 = pair.key;
const value = pair.value;
if (key2.status === "aborted" || value.status === "aborted") {
return INVALID;
}
if (key2.status === "dirty" || value.status === "dirty") {
status.dirty();
}
finalMap.set(key2.value, value.value);
}
return { status: status.value, value: finalMap };
}
}
};
ZodMap.create = (keyType, valueType, params) => {
return new ZodMap({
valueType,
keyType,
typeName: ZodFirstPartyTypeKind.ZodMap,
...processCreateParams(params)
});
};
var ZodSet = class _ZodSet extends ZodType {
_parse(input) {
const { status, ctx } = this._processInputParams(input);
if (ctx.parsedType !== ZodParsedType.set) {
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.set,
received: ctx.parsedType
});
return INVALID;
}
const def = this._def;
if (def.minSize !== null) {
if (ctx.data.size < def.minSize.value) {
addIssueToContext(ctx, {
code: ZodIssueCode.too_small,
minimum: def.minSize.value,
type: "set",
inclusive: true,
exact: false,
message: def.minSize.message
});
status.dirty();
}
}
if (def.maxSize !== null) {
if (ctx.data.size > def.maxSize.value) {
addIssueToContext(ctx, {
code: ZodIssueCode.too_big,
maximum: def.maxSize.value,
type: "set",
inclusive: true,
exact: false,
message: def.maxSize.message
});
status.dirty();
}
}
const valueType = this._def.valueType;
function finalizeSet(elements2) {
const parsedSet = /* @__PURE__ */ new Set();
for (const element2 of elements2) {
if (element2.status === "aborted")
return INVALID;
if (element2.status === "dirty")
status.dirty();
parsedSet.add(element2.value);
}
return { status: status.value, value: parsedSet };
}
const elements = [...ctx.data.values()].map((item, i) => valueType._parse(new ParseInputLazyPath(ctx, item, ctx.path, i)));
if (ctx.common.async) {
return Promise.all(elements).then((elements2) => finalizeSet(elements2));
} else {
return finalizeSet(elements);
}
}
min(minSize, message) {
return new _ZodSet({
...this._def,
minSize: { value: minSize, message: errorUtil.toString(message) }
});
}
max(maxSize, message) {
return new _ZodSet({
...this._def,
maxSize: { value: maxSize, message: errorUtil.toString(message) }
});
}
size(size, message) {
return this.min(size, message).max(size, message);
}
nonempty(message) {
return this.min(1, message);
}
};
ZodSet.create = (valueType, params) => {
return new ZodSet({
valueType,
minSize: null,
maxSize: null,
typeName: ZodFirstPartyTypeKind.ZodSet,
...processCreateParams(params)
});
};
var ZodFunction = class _ZodFunction extends ZodType {
constructor() {
super(...arguments);
this.validate = this.implement;
}
_parse(input) {
const { ctx } = this._processInputParams(input);
if (ctx.parsedType !== ZodParsedType.function) {
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.function,
received: ctx.parsedType
});
return INVALID;
}
function makeArgsIssue(args, error) {
return makeIssue({
data: args,
path: ctx.path,
errorMaps: [
ctx.common.contextualErrorMap,
ctx.schemaErrorMap,
getErrorMap(),
errorMap
].filter((x) => !!x),
issueData: {
code: ZodIssueCode.invalid_arguments,
argumentsError: error
}
});
}
function makeReturnsIssue(returns, error) {
return makeIssue({
data: returns,
path: ctx.path,
errorMaps: [
ctx.common.contextualErrorMap,
ctx.schemaErrorMap,
getErrorMap(),
errorMap
].filter((x) => !!x),
issueData: {
code: ZodIssueCode.invalid_return_type,
returnTypeError: error
}
});
}
const params = { errorMap: ctx.common.contextualErrorMap };
const fn = ctx.data;
if (this._def.returns instanceof ZodPromise) {
const me = this;
return OK(async function(...args) {
const error = new ZodError([]);
const parsedArgs = await me._def.args.parseAsync(args, params).catch((e) => {
error.addIssue(makeArgsIssue(args, e));
throw error;
});
const result = await Reflect.apply(fn, this, parsedArgs);
const parsedReturns = await me._def.returns._def.type.parseAsync(result, params).catch((e) => {
error.addIssue(makeReturnsIssue(result, e));
throw error;
});
return parsedReturns;
});
} else {
const me = this;
return OK(function(...args) {
const parsedArgs = me._def.args.safeParse(args, params);
if (!parsedArgs.success) {
throw new ZodError([makeArgsIssue(args, parsedArgs.error)]);
}
const result = Reflect.apply(fn, this, parsedArgs.data);
const parsedReturns = me._def.returns.safeParse(result, params);
if (!parsedReturns.success) {
throw new ZodError([makeReturnsIssue(result, parsedReturns.error)]);
}
return parsedReturns.data;
});
}
}
parameters() {
return this._def.args;
}
returnType() {
return this._def.returns;
}
args(...items) {
return new _ZodFunction({
...this._def,
args: ZodTuple.create(items).rest(ZodUnknown.create())
});
}
returns(returnType) {
return new _ZodFunction({
...this._def,
returns: returnType
});
}
implement(func) {
const validatedFunc = this.parse(func);
return validatedFunc;
}
strictImplement(func) {
const validatedFunc = this.parse(func);
return validatedFunc;
}
static create(args, returns, params) {
return new _ZodFunction({
args: args ? args : ZodTuple.create([]).rest(ZodUnknown.create()),
returns: returns || ZodUnknown.create(),
typeName: ZodFirstPartyTypeKind.ZodFunction,
...processCreateParams(params)
});
}
};
var ZodLazy = class extends ZodType {
get schema() {
return this._def.getter();
}
_parse(input) {
const { ctx } = this._processInputParams(input);
const lazySchema = this._def.getter();
return lazySchema._parse({ data: ctx.data, path: ctx.path, parent: ctx });
}
};
ZodLazy.create = (getter, params) => {
return new ZodLazy({
getter,
typeName: ZodFirstPartyTypeKind.ZodLazy,
...processCreateParams(params)
});
};
var ZodLiteral = class extends ZodType {
_parse(input) {
if (input.data !== this._def.value) {
const ctx = this._getOrReturnCtx(input);
addIssueToContext(ctx, {
received: ctx.data,
code: ZodIssueCode.invalid_literal,
expected: this._def.value
});
return INVALID;
}
return { status: "valid", value: input.data };
}
get value() {
return this._def.value;
}
};
ZodLiteral.create = (value, params) => {
return new ZodLiteral({
value,
typeName: ZodFirstPartyTypeKind.ZodLiteral,
...processCreateParams(params)
});
};
function createZodEnum(values, params) {
return new ZodEnum({
values,
typeName: ZodFirstPartyTypeKind.ZodEnum,
...processCreateParams(params)
});
}
var ZodEnum = class _ZodEnum extends ZodType {
constructor() {
super(...arguments);
_ZodEnum_cache.set(this, void 0);
}
_parse(input) {
if (typeof input.data !== "string") {
const ctx = this._getOrReturnCtx(input);
const expectedValues = this._def.values;
addIssueToContext(ctx, {
expected: util.joinValues(expectedValues),
received: ctx.parsedType,
code: ZodIssueCode.invalid_type
});
return INVALID;
}
if (!__classPrivateFieldGet(this, _ZodEnum_cache, "f")) {
__classPrivateFieldSet(this, _ZodEnum_cache, new Set(this._def.values), "f");
}
if (!__classPrivateFieldGet(this, _ZodEnum_cache, "f").has(input.data)) {
const ctx = this._getOrReturnCtx(input);
const expectedValues = this._def.values;
addIssueToContext(ctx, {
received: ctx.data,
code: ZodIssueCode.invalid_enum_value,
options: expectedValues
});
return INVALID;
}
return OK(input.data);
}
get options() {
return this._def.values;
}
get enum() {
const enumValues = {};
for (const val of this._def.values) {
enumValues[val] = val;
}
return enumValues;
}
get Values() {
const enumValues = {};
for (const val of this._def.values) {
enumValues[val] = val;
}
return enumValues;
}
get Enum() {
const enumValues = {};
for (const val of this._def.values) {
enumValues[val] = val;
}
return enumValues;
}
extract(values, newDef = this._def) {
return _ZodEnum.create(values, {
...this._def,
...newDef
});
}
exclude(values, newDef = this._def) {
return _ZodEnum.create(this.options.filter((opt) => !values.includes(opt)), {
...this._def,
...newDef
});
}
};
_ZodEnum_cache = /* @__PURE__ */ new WeakMap();
ZodEnum.create = createZodEnum;
var ZodNativeEnum = class extends ZodType {
constructor() {
super(...arguments);
_ZodNativeEnum_cache.set(this, void 0);
}
_parse(input) {
const nativeEnumValues = util.getValidEnumValues(this._def.values);
const ctx = this._getOrReturnCtx(input);
if (ctx.parsedType !== ZodParsedType.string && ctx.parsedType !== ZodParsedType.number) {
const expectedValues = util.objectValues(nativeEnumValues);
addIssueToContext(ctx, {
expected: util.joinValues(expectedValues),
received: ctx.parsedType,
code: ZodIssueCode.invalid_type
});
return INVALID;
}
if (!__classPrivateFieldGet(this, _ZodNativeEnum_cache, "f")) {
__classPrivateFieldSet(this, _ZodNativeEnum_cache, new Set(util.getValidEnumValues(this._def.values)), "f");
}
if (!__classPrivateFieldGet(this, _ZodNativeEnum_cache, "f").has(input.data)) {
const expectedValues = util.objectValues(nativeEnumValues);
addIssueToContext(ctx, {
received: ctx.data,
code: ZodIssueCode.invalid_enum_value,
options: expectedValues
});
return INVALID;
}
return OK(input.data);
}
get enum() {
return this._def.values;
}
};
_ZodNativeEnum_cache = /* @__PURE__ */ new WeakMap();
ZodNativeEnum.create = (values, params) => {
return new ZodNativeEnum({
values,
typeName: ZodFirstPartyTypeKind.ZodNativeEnum,
...processCreateParams(params)
});
};
var ZodPromise = class extends ZodType {
unwrap() {
return this._def.type;
}
_parse(input) {
const { ctx } = this._processInputParams(input);
if (ctx.parsedType !== ZodParsedType.promise && ctx.common.async === false) {
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.promise,
received: ctx.parsedType
});
return INVALID;
}
const promisified = ctx.parsedType === ZodParsedType.promise ? ctx.data : Promise.resolve(ctx.data);
return OK(promisified.then((data) => {
return this._def.type.parseAsync(data, {
path: ctx.path,
errorMap: ctx.common.contextualErrorMap
});
}));
}
};
ZodPromise.create = (schema2, params) => {
return new ZodPromise({
type: schema2,
typeName: ZodFirstPartyTypeKind.ZodPromise,
...processCreateParams(params)
});
};
var ZodEffects = class extends ZodType {
innerType() {
return this._def.schema;
}
sourceType() {
return this._def.schema._def.typeName === ZodFirstPartyTypeKind.ZodEffects ? this._def.schema.sourceType() : this._def.schema;
}
_parse(input) {
const { status, ctx } = this._processInputParams(input);
const effect2 = this._def.effect || null;
const checkCtx = {
addIssue: (arg) => {
addIssueToContext(ctx, arg);
if (arg.fatal) {
status.abort();
} else {
status.dirty();
}
},
get path() {
return ctx.path;
}
};
checkCtx.addIssue = checkCtx.addIssue.bind(checkCtx);
if (effect2.type === "preprocess") {
const processed = effect2.transform(ctx.data, checkCtx);
if (ctx.common.async) {
return Promise.resolve(processed).then(async (processed2) => {
if (status.value === "aborted")
return INVALID;
const result = await this._def.schema._parseAsync({
data: processed2,
path: ctx.path,
parent: ctx
});
if (result.status === "aborted")
return INVALID;
if (result.status === "dirty")
return DIRTY2(result.value);
if (status.value === "dirty")
return DIRTY2(result.value);
return result;
});
} else {
if (status.value === "aborted")
return INVALID;
const result = this._def.schema._parseSync({
data: processed,
path: ctx.path,
parent: ctx
});
if (result.status === "aborted")
return INVALID;
if (result.status === "dirty")
return DIRTY2(result.value);
if (status.value === "dirty")
return DIRTY2(result.value);
return result;
}
}
if (effect2.type === "refinement") {
const executeRefinement = (acc) => {
const result = effect2.refinement(acc, checkCtx);
if (ctx.common.async) {
return Promise.resolve(result);
}
if (result instanceof Promise) {
throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");
}
return acc;
};
if (ctx.common.async === false) {
const inner = this._def.schema._parseSync({
data: ctx.data,
path: ctx.path,
parent: ctx
});
if (inner.status === "aborted")
return INVALID;
if (inner.status === "dirty")
status.dirty();
executeRefinement(inner.value);
return { status: status.value, value: inner.value };
} else {
return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((inner) => {
if (inner.status === "aborted")
return INVALID;
if (inner.status === "dirty")
status.dirty();
return executeRefinement(inner.value).then(() => {
return { status: status.value, value: inner.value };
});
});
}
}
if (effect2.type === "transform") {
if (ctx.common.async === false) {
const base = this._def.schema._parseSync({
data: ctx.data,
path: ctx.path,
parent: ctx
});
if (!isValid(base))
return base;
const result = effect2.transform(base.value, checkCtx);
if (result instanceof Promise) {
throw new Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`);
}
return { status: status.value, value: result };
} else {
return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((base) => {
if (!isValid(base))
return base;
return Promise.resolve(effect2.transform(base.value, checkCtx)).then((result) => ({ status: status.value, value: result }));
});
}
}
util.assertNever(effect2);
}
};
ZodEffects.create = (schema2, effect2, params) => {
return new ZodEffects({
schema: schema2,
typeName: ZodFirstPartyTypeKind.ZodEffects,
effect: effect2,
...processCreateParams(params)
});
};
ZodEffects.createWithPreprocess = (preprocess, schema2, params) => {
return new ZodEffects({
schema: schema2,
effect: { type: "preprocess", transform: preprocess },
typeName: ZodFirstPartyTypeKind.ZodEffects,
...processCreateParams(params)
});
};
var ZodOptional = class extends ZodType {
_parse(input) {
const parsedType = this._getType(input);
if (parsedType === ZodParsedType.undefined) {
return OK(void 0);
}
return this._def.innerType._parse(input);
}
unwrap() {
return this._def.innerType;
}
};
ZodOptional.create = (type2, params) => {
return new ZodOptional({
innerType: type2,
typeName: ZodFirstPartyTypeKind.ZodOptional,
...processCreateParams(params)
});
};
var ZodNullable = class extends ZodType {
_parse(input) {
const parsedType = this._getType(input);
if (parsedType === ZodParsedType.null) {
return OK(null);
}
return this._def.innerType._parse(input);
}
unwrap() {
return this._def.innerType;
}
};
ZodNullable.create = (type2, params) => {
return new ZodNullable({
innerType: type2,
typeName: ZodFirstPartyTypeKind.ZodNullable,
...processCreateParams(params)
});
};
var ZodDefault = class extends ZodType {
_parse(input) {
const { ctx } = this._processInputParams(input);
let data = ctx.data;
if (ctx.parsedType === ZodParsedType.undefined) {
data = this._def.defaultValue();
}
return this._def.innerType._parse({
data,
path: ctx.path,
parent: ctx
});
}
removeDefault() {
return this._def.innerType;
}
};
ZodDefault.create = (type2, params) => {
return new ZodDefault({
innerType: type2,
typeName: ZodFirstPartyTypeKind.ZodDefault,
defaultValue: typeof params.default === "function" ? params.default : () => params.default,
...processCreateParams(params)
});
};
var ZodCatch = class extends ZodType {
_parse(input) {
const { ctx } = this._processInputParams(input);
const newCtx = {
...ctx,
common: {
...ctx.common,
issues: []
}
};
const result = this._def.innerType._parse({
data: newCtx.data,
path: newCtx.path,
parent: {
...newCtx
}
});
if (isAsync(result)) {
return result.then((result2) => {
return {
status: "valid",
value: result2.status === "valid" ? result2.value : this._def.catchValue({
get error() {
return new ZodError(newCtx.common.issues);
},
input: newCtx.data
})
};
});
} else {
return {
status: "valid",
value: result.status === "valid" ? result.value : this._def.catchValue({
get error() {
return new ZodError(newCtx.common.issues);
},
input: newCtx.data
})
};
}
}
removeCatch() {
return this._def.innerType;
}
};
ZodCatch.create = (type2, params) => {
return new ZodCatch({
innerType: type2,
typeName: ZodFirstPartyTypeKind.ZodCatch,
catchValue: typeof params.catch === "function" ? params.catch : () => params.catch,
...processCreateParams(params)
});
};
var ZodNaN = class extends ZodType {
_parse(input) {
const parsedType = this._getType(input);
if (parsedType !== ZodParsedType.nan) {
const ctx = this._getOrReturnCtx(input);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.nan,
received: ctx.parsedType
});
return INVALID;
}
return { status: "valid", value: input.data };
}
};
ZodNaN.create = (params) => {
return new ZodNaN({
typeName: ZodFirstPartyTypeKind.ZodNaN,
...processCreateParams(params)
});
};
var BRAND = /* @__PURE__ */ Symbol("zod_brand");
var ZodBranded = class extends ZodType {
_parse(input) {
const { ctx } = this._processInputParams(input);
const data = ctx.data;
return this._def.type._parse({
data,
path: ctx.path,
parent: ctx
});
}
unwrap() {
return this._def.type;
}
};
var ZodPipeline = class _ZodPipeline extends ZodType {
_parse(input) {
const { status, ctx } = this._processInputParams(input);
if (ctx.common.async) {
const handleAsync = async () => {
const inResult = await this._def.in._parseAsync({
data: ctx.data,
path: ctx.path,
parent: ctx
});
if (inResult.status === "aborted")
return INVALID;
if (inResult.status === "dirty") {
status.dirty();
return DIRTY2(inResult.value);
} else {
return this._def.out._parseAsync({
data: inResult.value,
path: ctx.path,
parent: ctx
});
}
};
return handleAsync();
} else {
const inResult = this._def.in._parseSync({
data: ctx.data,
path: ctx.path,
parent: ctx
});
if (inResult.status === "aborted")
return INVALID;
if (inResult.status === "dirty") {
status.dirty();
return {
status: "dirty",
value: inResult.value
};
} else {
return this._def.out._parseSync({
data: inResult.value,
path: ctx.path,
parent: ctx
});
}
}
}
static create(a, b) {
return new _ZodPipeline({
in: a,
out: b,
typeName: ZodFirstPartyTypeKind.ZodPipeline
});
}
};
var ZodReadonly = class extends ZodType {
_parse(input) {
const result = this._def.innerType._parse(input);
const freeze = (data) => {
if (isValid(data)) {
data.value = Object.freeze(data.value);
}
return data;
};
return isAsync(result) ? result.then((data) => freeze(data)) : freeze(result);
}
unwrap() {
return this._def.innerType;
}
};
ZodReadonly.create = (type2, params) => {
return new ZodReadonly({
innerType: type2,
typeName: ZodFirstPartyTypeKind.ZodReadonly,
...processCreateParams(params)
});
};
function custom(check, params = {}, fatal) {
if (check)
return ZodAny.create().superRefine((data, ctx) => {
var _a5, _b3;
if (!check(data)) {
const p = typeof params === "function" ? params(data) : typeof params === "string" ? { message: params } : params;
const _fatal = (_b3 = (_a5 = p.fatal) !== null && _a5 !== void 0 ? _a5 : fatal) !== null && _b3 !== void 0 ? _b3 : true;
const p2 = typeof p === "string" ? { message: p } : p;
ctx.addIssue({ code: "custom", ...p2, fatal: _fatal });
}
});
return ZodAny.create();
}
var late = {
object: ZodObject.lazycreate
};
var ZodFirstPartyTypeKind;
(function(ZodFirstPartyTypeKind2) {
ZodFirstPartyTypeKind2["ZodString"] = "ZodString";
ZodFirstPartyTypeKind2["ZodNumber"] = "ZodNumber";
ZodFirstPartyTypeKind2["ZodNaN"] = "ZodNaN";
ZodFirstPartyTypeKind2["ZodBigInt"] = "ZodBigInt";
ZodFirstPartyTypeKind2["ZodBoolean"] = "ZodBoolean";
ZodFirstPartyTypeKind2["ZodDate"] = "ZodDate";
ZodFirstPartyTypeKind2["ZodSymbol"] = "ZodSymbol";
ZodFirstPartyTypeKind2["ZodUndefined"] = "ZodUndefined";
ZodFirstPartyTypeKind2["ZodNull"] = "ZodNull";
ZodFirstPartyTypeKind2["ZodAny"] = "ZodAny";
ZodFirstPartyTypeKind2["ZodUnknown"] = "ZodUnknown";
ZodFirstPartyTypeKind2["ZodNever"] = "ZodNever";
ZodFirstPartyTypeKind2["ZodVoid"] = "ZodVoid";
ZodFirstPartyTypeKind2["ZodArray"] = "ZodArray";
ZodFirstPartyTypeKind2["ZodObject"] = "ZodObject";
ZodFirstPartyTypeKind2["ZodUnion"] = "ZodUnion";
ZodFirstPartyTypeKind2["ZodDiscriminatedUnion"] = "ZodDiscriminatedUnion";
ZodFirstPartyTypeKind2["ZodIntersection"] = "ZodIntersection";
ZodFirstPartyTypeKind2["ZodTuple"] = "ZodTuple";
ZodFirstPartyTypeKind2["ZodRecord"] = "ZodRecord";
ZodFirstPartyTypeKind2["ZodMap"] = "ZodMap";
ZodFirstPartyTypeKind2["ZodSet"] = "ZodSet";
ZodFirstPartyTypeKind2["ZodFunction"] = "ZodFunction";
ZodFirstPartyTypeKind2["ZodLazy"] = "ZodLazy";
ZodFirstPartyTypeKind2["ZodLiteral"] = "ZodLiteral";
ZodFirstPartyTypeKind2["ZodEnum"] = "ZodEnum";
ZodFirstPartyTypeKind2["ZodEffects"] = "ZodEffects";
ZodFirstPartyTypeKind2["ZodNativeEnum"] = "ZodNativeEnum";
ZodFirstPartyTypeKind2["ZodOptional"] = "ZodOptional";
ZodFirstPartyTypeKind2["ZodNullable"] = "ZodNullable";
ZodFirstPartyTypeKind2["ZodDefault"] = "ZodDefault";
ZodFirstPartyTypeKind2["ZodCatch"] = "ZodCatch";
ZodFirstPartyTypeKind2["ZodPromise"] = "ZodPromise";
ZodFirstPartyTypeKind2["ZodBranded"] = "ZodBranded";
ZodFirstPartyTypeKind2["ZodPipeline"] = "ZodPipeline";
ZodFirstPartyTypeKind2["ZodReadonly"] = "ZodReadonly";
})(ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {}));
var instanceOfType = (cls, params = {
message: `Input not instance of ${cls.name}`
}) => custom((data) => data instanceof cls, params);
var stringType = ZodString.create;
var numberType = ZodNumber.create;
var nanType = ZodNaN.create;
var bigIntType = ZodBigInt.create;
var booleanType = ZodBoolean.create;
var dateType = ZodDate.create;
var symbolType = ZodSymbol.create;
var undefinedType = ZodUndefined.create;
var nullType = ZodNull.create;
var anyType = ZodAny.create;
var unknownType = ZodUnknown.create;
var neverType = ZodNever.create;
var voidType = ZodVoid.create;
var arrayType = ZodArray.create;
var objectType = ZodObject.create;
var strictObjectType = ZodObject.strictCreate;
var unionType = ZodUnion.create;
var discriminatedUnionType = ZodDiscriminatedUnion.create;
var intersectionType = ZodIntersection.create;
var tupleType = ZodTuple.create;
var recordType = ZodRecord.create;
var mapType = ZodMap.create;
var setType = ZodSet.create;
var functionType = ZodFunction.create;
var lazyType = ZodLazy.create;
var literalType = ZodLiteral.create;
var enumType = ZodEnum.create;
var nativeEnumType = ZodNativeEnum.create;
var promiseType = ZodPromise.create;
var effectsType = ZodEffects.create;
var optionalType = ZodOptional.create;
var nullableType = ZodNullable.create;
var preprocessType = ZodEffects.createWithPreprocess;
var pipelineType = ZodPipeline.create;
var ostring = () => stringType().optional();
var onumber = () => numberType().optional();
var oboolean = () => booleanType().optional();
var coerce = {
string: ((arg) => ZodString.create({ ...arg, coerce: true })),
number: ((arg) => ZodNumber.create({ ...arg, coerce: true })),
boolean: ((arg) => ZodBoolean.create({
...arg,
coerce: true
})),
bigint: ((arg) => ZodBigInt.create({ ...arg, coerce: true })),
date: ((arg) => ZodDate.create({ ...arg, coerce: true }))
};
var NEVER = INVALID;
var z = /* @__PURE__ */ Object.freeze({
__proto__: null,
defaultErrorMap: errorMap,
setErrorMap,
getErrorMap,
makeIssue,
EMPTY_PATH,
addIssueToContext,
ParseStatus,
INVALID,
DIRTY: DIRTY2,
OK,
isAborted,
isDirty,
isValid,
isAsync,
get util() {
return util;
},
get objectUtil() {
return objectUtil;
},
ZodParsedType,
getParsedType,
ZodType,
datetimeRegex,
ZodString,
ZodNumber,
ZodBigInt,
ZodBoolean,
ZodDate,
ZodSymbol,
ZodUndefined,
ZodNull,
ZodAny,
ZodUnknown,
ZodNever,
ZodVoid,
ZodArray,
ZodObject,
ZodUnion,
ZodDiscriminatedUnion,
ZodIntersection,
ZodTuple,
ZodRecord,
ZodMap,
ZodSet,
ZodFunction,
ZodLazy,
ZodLiteral,
ZodEnum,
ZodNativeEnum,
ZodPromise,
ZodEffects,
ZodTransformer: ZodEffects,
ZodOptional,
ZodNullable,
ZodDefault,
ZodCatch,
ZodNaN,
BRAND,
ZodBranded,
ZodPipeline,
ZodReadonly,
custom,
Schema: ZodType,
ZodSchema: ZodType,
late,
get ZodFirstPartyTypeKind() {
return ZodFirstPartyTypeKind;
},
coerce,
any: anyType,
array: arrayType,
bigint: bigIntType,
boolean: booleanType,
date: dateType,
discriminatedUnion: discriminatedUnionType,
effect: effectsType,
"enum": enumType,
"function": functionType,
"instanceof": instanceOfType,
intersection: intersectionType,
lazy: lazyType,
literal: literalType,
map: mapType,
nan: nanType,
nativeEnum: nativeEnumType,
never: neverType,
"null": nullType,
nullable: nullableType,
number: numberType,
object: objectType,
oboolean,
onumber,
optional: optionalType,
ostring,
pipeline: pipelineType,
preprocess: preprocessType,
promise: promiseType,
record: recordType,
set: setType,
strictObject: strictObjectType,
string: stringType,
symbol: symbolType,
transformer: effectsType,
tuple: tupleType,
"undefined": undefinedType,
union: unionType,
unknown: unknownType,
"void": voidType,
NEVER,
ZodIssueCode,
quotelessJson,
ZodError
});
// src/ui/tasks/task.ts
var import_sha256 = __toESM(require_sha256());
// src/parsing/tags/tags.ts
function getTagsFromContent(content) {
const tags = /* @__PURE__ */ new Set();
const matches = content.matchAll(tagsRegex);
for (const match of matches) {
if (match[1] && tagNonNumericTest.test(match[1])) {
tags.add(match[1]);
}
}
return tags;
}
function isValidTag(tag2) {
return /^[-_/\p{L}\p{N}]+$/u.test(tag2);
}
var tagsRegex = /#([-_/\p{L}\p{N}]+)/gu;
var tagNonNumericTest = /\p{L}/u;
// src/parsing/properties/none_schema.ts
var NoneSchema = class {
constructor() {
this.id = "none" /* None */;
this.label = "None";
}
parseProperties(rawLine) {
return createPropertyMapWithStatus(rawLine);
}
knownKeys() {
return [
{
key: UNIVERSAL_STATUS_PROPERTY_KEY,
label: "Status",
type: "text"
}
];
}
};
// src/parsing/properties/dataview_schema.ts
var DATAVIEW_KEY_PATTERN = "[a-zA-Z0-9_-]+";
var ENCLOSED_DATAVIEW_REGEX = /\[\s*([a-zA-Z0-9_-]+)\s*::\s*([^\]]*?)\s*\]|\(\s*([a-zA-Z0-9_-]+)\s*::\s*([^\)]*?)\s*\)/g;
var BARE_DATAVIEW_MARKER_REGEX = new RegExp(`(^|\\s)(${DATAVIEW_KEY_PATTERN})\\s*::\\s*`, "g");
function parseDataviewValue(value) {
const trimmed = value.trim();
const parsedDate = parseIsoDate(trimmed);
if (parsedDate) {
return parsedDate;
}
const parsedNumber = parseNumber(trimmed);
if (parsedNumber !== null) {
return parsedNumber;
}
return trimmed;
}
function isInsideRange(index2, ranges) {
return ranges.some((range) => index2 >= range.start && index2 < range.end);
}
function parseEnclosedFields(rawLine) {
return [...rawLine.matchAll(ENCLOSED_DATAVIEW_REGEX)].flatMap((match) => {
var _a5, _b3, _c2;
const index2 = (_a5 = match.index) != null ? _a5 : Number.MAX_SAFE_INTEGER;
const key2 = (_b3 = match[1]) != null ? _b3 : match[3];
const rawValueText = (_c2 = match[2]) != null ? _c2 : match[4];
if (!key2 || rawValueText === void 0) return [];
return [{
index: index2,
endIndex: index2 + match[0].length,
key: key2,
rawValue: match[0],
rawValueText
}];
});
}
function parseBareFields(rawLine, enclosedFields) {
const enclosedRanges = enclosedFields.map((field) => ({ start: field.index, end: field.endIndex }));
const markers = [...rawLine.matchAll(BARE_DATAVIEW_MARKER_REGEX)].map((match) => {
var _a5, _b3, _c2;
const prefix = (_a5 = match[1]) != null ? _a5 : "";
const index2 = ((_b3 = match.index) != null ? _b3 : 0) + prefix.length;
return {
index: index2,
valueStart: ((_c2 = match.index) != null ? _c2 : 0) + match[0].length,
key: match[2]
};
}).filter((marker) => marker.key && !isInsideRange(marker.index, enclosedRanges));
return markers.flatMap((marker, markerIndex) => {
var _a5, _b3, _c2;
if (!marker.key) return [];
const nextMarkerIndex = (_b3 = (_a5 = markers[markerIndex + 1]) == null ? void 0 : _a5.index) != null ? _b3 : Number.MAX_SAFE_INTEGER;
const nextEnclosedIndex = (_c2 = enclosedFields.map((field) => field.index).filter((index2) => index2 > marker.valueStart).sort((a, b) => a - b)[0]) != null ? _c2 : Number.MAX_SAFE_INTEGER;
const endIndex = Math.min(nextMarkerIndex, nextEnclosedIndex, rawLine.length);
const rawValueText = rawLine.slice(marker.valueStart, endIndex).trim();
const rawValue = rawLine.slice(marker.index, endIndex).trimEnd();
if (!rawValueText) return [];
return [{
index: marker.index,
endIndex: marker.index + rawValue.length,
key: marker.key,
rawValue,
rawValueText
}];
});
}
var DataviewSchema = class {
constructor() {
this.id = "dataview" /* Dataview */;
this.label = "Dataview";
}
parseProperties(rawLine) {
const properties = createPropertyMapWithStatus(rawLine);
const enclosedFields = parseEnclosedFields(rawLine);
const fields = [
...enclosedFields,
...parseBareFields(rawLine, enclosedFields)
].sort((a, b) => a.index - b.index);
for (const field of fields) {
if (!properties.has(field.key)) {
properties.set(field.key, {
key: field.key,
rawValue: field.rawValue,
value: parseDataviewValue(field.rawValueText),
startIndex: field.index,
endIndex: field.endIndex
});
}
}
return properties;
}
knownKeys() {
return [
{ key: UNIVERSAL_STATUS_PROPERTY_KEY, label: "Status", type: "text" },
{ key: "due", label: "Due", type: "date" },
{ key: "scheduled", label: "Scheduled", type: "date" },
{ key: "start", label: "Start", type: "date" },
{ key: "done", label: "Done", type: "date", aliases: getPropertyAliases("done") },
{ key: "completion", label: "Completion", type: "date" },
{ key: "created", label: "Created", type: "date" },
{ key: "priority", label: "Priority", type: "text" },
{ key: "repeat", label: "Repeat", type: "text", aliases: getPropertyAliases("repeat") }
];
}
};
// src/parsing/properties/write.ts
var EDITABLE_DATE_PROPERTY_KEY_SET = {
due: true,
scheduled: true,
start: true
};
var EDITABLE_DATE_PROPERTY_KEYS = Object.keys(
EDITABLE_DATE_PROPERTY_KEY_SET
);
function getWritablePropertyTarget(key2) {
if (key2 in EDITABLE_DATE_PROPERTY_KEY_SET) {
return { kind: "date", key: key2 };
}
if (key2 === "priority") {
return { kind: "priority" };
}
return null;
}
var TASKS_WRITERS = {
due: "\u{1F4C5}",
scheduled: "\u23F3",
start: "\u{1F6EB}",
done: "\u2705"
};
var DATAVIEW_WRITERS = {
due: "due",
scheduled: "scheduled",
start: "start",
completion: "completion"
};
var DATAVIEW_PRIORITY_KEY = "priority";
var TRAILING_BLOCK_LINK_REGEX = /(\s\^[a-zA-Z0-9-]+)$/;
var TasksPluginWriteAdapter = class {
constructor() {
this.schema = "tasks" /* TasksPlugin */;
this.propertySchema = new TasksPluginSchema();
}
addCompletionDateIfMissing(rawLine, date) {
if (this.propertySchema.parseProperties(rawLine).has("done")) {
return rawLine;
}
return appendBeforeBlockLink(rawLine, `${TASKS_WRITERS.done} ${date}`);
}
upsertDate(rawLine, key2, date) {
var _a5;
const marker = (_a5 = markerForExistingTasksProperty(rawLine, key2)) != null ? _a5 : TASKS_WRITERS[key2];
const property = this.propertySchema.parseProperties(rawLine).get(key2);
return upsertProperty(rawLine, property, `${marker} ${date}`);
}
removeDate(rawLine, key2) {
const propertyKey = key2 === "completion" ? "done" : key2;
const property = this.propertySchema.parseProperties(rawLine).get(propertyKey);
return property ? removeProperty(rawLine, property) : rawLine;
}
upsertPriority(rawLine, priority) {
const option = getTasksPriorityOption(priority);
if (!option) {
return rawLine;
}
const property = this.propertySchema.parseProperties(rawLine).get("priority");
return upsertProperty(rawLine, property, option.emoji);
}
removePriority(rawLine) {
const property = this.propertySchema.parseProperties(rawLine).get("priority");
return property ? removeProperty(rawLine, property) : rawLine;
}
};
var DataviewWriteAdapter = class {
constructor() {
this.schema = "dataview" /* Dataview */;
this.propertySchema = new DataviewSchema();
}
addCompletionDateIfMissing(rawLine, date) {
if (hasDataviewCompletionProperty(rawLine, this.propertySchema)) {
return rawLine;
}
return appendBeforeBlockLink(rawLine, formatDataviewField("completion", date));
}
upsertDate(rawLine, key2, date) {
const property = this.propertySchema.parseProperties(rawLine).get(key2);
return upsertProperty(rawLine, property, formatDataviewField(DATAVIEW_WRITERS[key2], date));
}
removeDate(rawLine, key2) {
const property = this.propertySchema.parseProperties(rawLine).get(key2);
return property ? removeProperty(rawLine, property) : rawLine;
}
upsertPriority(rawLine, priority) {
const normalizedPriority = priority.trim();
if (!normalizedPriority) {
return rawLine;
}
const property = this.propertySchema.parseProperties(rawLine).get(DATAVIEW_PRIORITY_KEY);
return upsertProperty(rawLine, property, formatDataviewField(DATAVIEW_PRIORITY_KEY, normalizedPriority));
}
removePriority(rawLine) {
const property = this.propertySchema.parseProperties(rawLine).get(DATAVIEW_PRIORITY_KEY);
return property ? removeProperty(rawLine, property) : rawLine;
}
};
var WRITE_ADAPTERS = {
["tasks" /* TasksPlugin */]: new TasksPluginWriteAdapter(),
["dataview" /* Dataview */]: new DataviewWriteAdapter()
};
function getPropertyWriteAdapter(schema2) {
if (schema2 === "tasks" /* TasksPlugin */ || schema2 === "dataview" /* Dataview */) {
return WRITE_ADAPTERS[schema2];
}
return null;
}
function formatLocalDate(date = /* @__PURE__ */ new Date()) {
const year = date.getFullYear();
const month = `${date.getMonth() + 1}`.padStart(2, "0");
const day = `${date.getDate()}`.padStart(2, "0");
return `${year}-${month}-${day}`;
}
function formatDataviewField(key2, date) {
return `[${key2}:: ${date}]`;
}
function upsertProperty(rawLine, property, replacement) {
if (!property) {
return appendBeforeBlockLink(rawLine, replacement);
}
return replaceProperty(rawLine, property, replacement);
}
function replaceProperty(rawLine, property, replacement) {
return `${rawLine.slice(0, property.startIndex)}${replacement}${rawLine.slice(property.endIndex)}`;
}
function removeProperty(rawLine, property) {
const next2 = `${rawLine.slice(0, property.startIndex)}${rawLine.slice(property.endIndex)}`;
return normalizeWhitespaceAroundIndex(next2, property.startIndex);
}
function appendBeforeBlockLink(rawLine, metadata) {
const match = rawLine.match(TRAILING_BLOCK_LINK_REGEX);
if (!(match == null ? void 0 : match.index)) {
return `${rawLine.trimEnd()} ${metadata}`;
}
const body = rawLine.slice(0, match.index).trimEnd();
return `${body} ${metadata}${match[0]}`;
}
function normalizeWhitespaceAroundIndex(rawLine, index2) {
var _a5, _b3;
let start = Math.max(0, index2);
while (start > 0 && /[ \t]/.test((_a5 = rawLine[start - 1]) != null ? _a5 : "")) {
start -= 1;
}
let end = Math.min(rawLine.length, index2);
while (end < rawLine.length && /[ \t]/.test((_b3 = rawLine[end]) != null ? _b3 : "")) {
end += 1;
}
const before = rawLine.slice(0, start);
const after = rawLine.slice(end);
const separator = before && after ? " " : "";
return `${before}${separator}${after}`.trimEnd();
}
function markerForExistingTasksProperty(rawLine, key2) {
const property = new TasksPluginSchema().parseProperties(rawLine).get(key2);
if (!property) return void 0;
const marker = Array.from(property.rawValue.trim())[0];
return marker;
}
function hasDataviewCompletionProperty(rawLine, schema2) {
const properties = schema2.parseProperties(rawLine);
return properties.has("completion") || properties.has("done");
}
// src/parsing/properties/comparators.ts
var ColumnOrderMode = /* @__PURE__ */ ((ColumnOrderMode2) => {
ColumnOrderMode2["FileOrder"] = "file";
ColumnOrderMode2["TaskName"] = "task-name";
ColumnOrderMode2["Property"] = "property";
ColumnOrderMode2["Manual"] = "manual";
return ColumnOrderMode2;
})(ColumnOrderMode || {});
function compareValues(a, b) {
if (a instanceof Date && b instanceof Date) {
return a.getTime() - b.getTime();
}
if (typeof a === "number" && typeof b === "number") {
return a - b;
}
return String(a).localeCompare(String(b));
}
function getPriorityWeight(value) {
if (typeof value === "number") {
return value;
}
if (typeof value === "string") {
const lower = value.toLowerCase().trim();
switch (lower) {
case "highest":
return 5;
case "high":
return 4;
case "medium":
return 3;
case "low":
return 2;
case "lowest":
return 1;
}
}
return null;
}
function compareByProperty(a, b, key2, direction, options = {}) {
var _a5, _b3, _c2, _d, _e, _f;
const aValue = (_b3 = (_a5 = a.properties.get(key2)) == null ? void 0 : _a5.value) != null ? _b3 : null;
const bValue = (_d = (_c2 = b.properties.get(key2)) == null ? void 0 : _c2.value) != null ? _d : null;
if (key2 === "priority") {
return comparePriorityValues(aValue, bValue, direction, options.propertySchema);
}
if (aValue === null && bValue === null) return 0;
if (aValue === null) return direction === "desc" ? -1 : 1;
if (bValue === null) return direction === "desc" ? 1 : -1;
if (key2 === UNIVERSAL_STATUS_PROPERTY_KEY) {
return compareStatusMarkerValues(
aValue,
bValue,
(_e = options.statusMarkerOrder) != null ? _e : "",
(_f = options.doneStatusMarkers) != null ? _f : "",
direction
);
}
const result = compareValues(aValue, bValue);
return direction === "desc" ? -result : result;
}
function comparePriorityValues(a, b, direction, propertySchema) {
var _a5, _b3, _c2, _d;
const schema2 = propertySchema != null ? propertySchema : inferPrioritySchema(a, b);
if (a === null && b === null) return 0;
if (schema2 === "dataview" /* Dataview */) {
if (a === null) return 1;
if (b === null) return -1;
} else {
const aWeight2 = a === null ? 2.5 : (_a5 = getPriorityWeight(a)) != null ? _a5 : 0;
const bWeight2 = b === null ? 2.5 : (_b3 = getPriorityWeight(b)) != null ? _b3 : 0;
const result2 = aWeight2 - bWeight2;
return direction === "desc" ? -result2 : result2;
}
const aWeight = (_c2 = getPriorityWeight(a)) != null ? _c2 : 0;
const bWeight = (_d = getPriorityWeight(b)) != null ? _d : 0;
const result = aWeight - bWeight;
return direction === "desc" ? -result : result;
}
function inferPrioritySchema(a, b) {
return typeof a === "number" || typeof b === "number" ? "tasks" /* TasksPlugin */ : "dataview" /* Dataview */;
}
function compareStatusMarkerValues(a, b, statusMarkerOrder, doneStatusMarkers = "", direction = "asc") {
const aMarker = String(a);
const bMarker = String(b);
const doneRankByMarker = createMarkerRankMap(doneStatusMarkers);
const aDoneRank = doneRankByMarker.get(aMarker);
const bDoneRank = doneRankByMarker.get(bMarker);
if (aDoneRank !== void 0 && bDoneRank !== void 0) {
return aDoneRank - bDoneRank;
}
if (aDoneRank !== void 0) return 1;
if (bDoneRank !== void 0) return -1;
const rankByMarker = createStatusMarkerRankMap(statusMarkerOrder);
const aRank = rankByMarker.get(aMarker);
const bRank = rankByMarker.get(bMarker);
let result;
if (aRank !== void 0 && bRank !== void 0) {
result = aRank - bRank;
} else if (aRank !== void 0) {
result = -1;
} else if (bRank !== void 0) {
result = 1;
} else {
result = aMarker.localeCompare(bMarker);
}
return direction === "desc" ? -result : result;
}
function createStatusMarkerRankMap(statusMarkerOrder) {
return createMarkerRankMap(getOrderedStatusMarkers(statusMarkerOrder).join(""));
}
function getOrderedStatusMarkers(statusMarkerOrder) {
const orderedMarkers = Array.from(statusMarkerOrder);
if (!orderedMarkers.includes(" ")) {
orderedMarkers.unshift(" ");
}
return orderedMarkers;
}
function createMarkerRankMap(markers) {
const rankByMarker = /* @__PURE__ */ new Map();
for (const marker of Array.from(markers)) {
if (!rankByMarker.has(marker)) {
rankByMarker.set(marker, rankByMarker.size);
}
}
return rankByMarker;
}
// src/parsing/properties/index.ts
var SCHEMA_IMPLS = {
["none" /* None */]: new NoneSchema(),
["tasks" /* TasksPlugin */]: new TasksPluginSchema(),
["dataview" /* Dataview */]: new DataviewSchema()
};
function getSchemaImpl(option) {
var _a5;
return (_a5 = SCHEMA_IMPLS[option]) != null ? _a5 : SCHEMA_IMPLS["none" /* None */];
}
// src/ui/tasks/source_block.ts
function parseSourceTaskLine(input) {
const match = input.match(sourceTaskLineRegex);
if (!match) {
return null;
}
const [, indentation, bullet, status, content] = match;
if (indentation == null || bullet == null || status == null || content == null) {
return null;
}
return { indentation, bullet, status, content };
}
function getSourceNodeText(node) {
return node.kind === "task" ? node.content : node.rawLine.slice(node.indentation.length);
}
function getRawListItemText(node) {
var _a5;
const match = node.rawLine.slice(node.indentation.length).match(/^[-*+]\s+(.+)$/);
return (_a5 = match == null ? void 0 : match[1]) != null ? _a5 : null;
}
function getVisibleSourceTaskDescendants(nodes) {
return flattenSourceBlockNodes(nodes).filter(
(node) => node.kind === "task" && node.taskVisibility === "visible"
);
}
function flattenSourceBlockNodes(nodes) {
return nodes.flatMap((node) => [
node,
...flattenSourceBlockNodes(node.sourceChildren)
]);
}
var sourceTaskLineRegex = /^(\s*)([-*+])\s\[([^\[\]]*)\]\s(.+)/;
// src/ui/tasks/task.ts
var DEFAULT_DONE_STATUS_MARKERS = "xX";
var DEFAULT_IGNORED_STATUS_MARKERS = "";
var DEFAULT_CANCELLED_STATUS_MARKERS = "-";
function validateStatusMarkers(markers) {
const errors = [];
const chars = Array.from(markers);
const seen = /* @__PURE__ */ new Set();
for (let i = 0; i < chars.length; i++) {
const char = chars[i];
if (!char) continue;
if (seen.has(char)) {
errors.push(`Duplicate marker '${char}' at position ${i + 1}`);
continue;
}
seen.add(char);
if (/\s/.test(char)) {
errors.push(`Marker at position ${i + 1} is whitespace`);
}
if (char.charCodeAt(0) < 32 || char.charCodeAt(0) === 127) {
errors.push(`Marker at position ${i + 1} is a control character`);
}
}
return errors;
}
function validateTypedStatusMarkers(markers, label, allowEmpty) {
if (!markers || markers.length === 0) {
return allowEmpty ? [] : [`${label} status markers cannot be empty`];
}
return validateStatusMarkers(markers);
}
function validateDoneStatusMarkers(markers) {
return validateTypedStatusMarkers(markers, "Done", false);
}
function validateIgnoredStatusMarkers(markers) {
return validateTypedStatusMarkers(markers, "Ignored", true);
}
function validateCancelledStatusMarkers(markers) {
return validateTypedStatusMarkers(markers, "Cancelled", false);
}
function validateStatusMarkerOrder(markers) {
const errors = [];
const chars = Array.from(markers);
const seen = /* @__PURE__ */ new Set();
for (let i = 0; i < chars.length; i++) {
const char = chars[i];
if (char !== " " && /\s/.test(char)) {
errors.push(`Marker at position ${i + 1} is whitespace`);
}
if (seen.has(char)) {
errors.push(`Duplicate marker '${char}' at position ${i + 1}`);
}
seen.add(char);
}
return errors;
}
function isStatusMatch(statusContent, markers) {
if (!statusContent || !markers) return false;
const contentChars = Array.from(statusContent);
const markersChars = Array.from(markers);
if (contentChars.length !== 1) {
return false;
}
const singleChar = contentChars[0];
if (!singleChar) return false;
return markersChars.includes(singleChar);
}
function getNextStatusMarker(currentStatus, doneStatusMarkers, statusMarkerOrder) {
var _a5;
if (isStatusMatch(currentStatus, doneStatusMarkers)) {
return { status: " ", done: false };
}
const orderedMarkers = getOrderedStatusMarkers(statusMarkerOrder);
const currentIndex = orderedMarkers.indexOf(currentStatus);
const nextMarker = currentIndex >= 0 ? orderedMarkers[currentIndex + 1] : void 0;
if (!nextMarker || isStatusMatch(nextMarker, doneStatusMarkers)) {
return {
status: (_a5 = Array.from(doneStatusMarkers)[0]) != null ? _a5 : "x",
done: true
};
}
return { status: nextMarker, done: false };
}
var Task = class {
constructor(rawContent, fileHandle, rowIndex, context, sourceChildren = []) {
this.rowIndex = rowIndex;
this._deleted = false;
var _a5, _b3;
const [, blockLink] = (_a5 = rawContent.match(blockLinkRegexp)) != null ? _a5 : [];
this.blockLink = blockLink;
const match = (blockLink ? rawContent.replace(blockLinkRegexp, "") : rawContent).match(taskStringRegex);
if (!match) {
throw new Error(
"Attempted to create a task from invalid raw content"
);
}
const [, indentation, status, content] = match;
if (!content) {
throw new Error("Content not found in raw content");
}
this.sourceChildren = sourceChildren;
const tags = getTagsFromContent(content);
this._id = (0, import_sha256.default)(content + fileHandle.path + rowIndex).toString();
this.content = content;
this._displayStatus = status || " ";
this._done = isStatusMatch(this._displayStatus, context.doneStatusMarkers);
this._path = fileHandle.path;
this._indentation = indentation || "";
this.properties = context.propertySchema.parseProperties(rawContent);
this.propertySchemaOption = context.propertySchema.id;
const priorityMatches = getTaskPriorityMatchValues(rawContent);
const matchedColumn = resolveMatchedColumnDefinition(context.columnDefinitions, {
tags,
status: this._displayStatus,
priority: getTaskPriorityMatchValue(this.propertySchemaOption, this.properties),
prioritySchema: this.propertySchemaOption === "tasks" /* TasksPlugin */ ? "tasks" /* TasksPlugin */ : this.propertySchemaOption === "dataview" /* Dataview */ ? "dataview" /* Dataview */ : void 0,
priorities: priorityMatches
});
for (const tag2 of tags) {
if (tag2 === "done") {
if (!this._column) {
this._column = "done";
}
tags.delete(tag2);
if (!context.consolidateTags) {
this.content = this.stripTagFromContent(this.content, tag2);
}
continue;
}
if (matchedColumn && isPlacementTag(matchedColumn, tag2)) {
if (!this._column) {
this._column = matchedColumn.id;
}
tags.delete(tag2);
if (!context.consolidateTags) {
this.content = this.stripTagFromContent(this.content, tag2);
}
}
if (context.consolidateTags) {
this.content = this.stripTagFromContent(this.content, tag2);
}
}
if (matchedColumn && usesStatusMatching(matchedColumn) && !this._column) {
this._column = matchedColumn.id;
}
if (matchedColumn && usesPriorityMatching(matchedColumn) && !this._column) {
this._column = matchedColumn.id;
}
this._tags = tags;
this.blockLink = blockLink;
this.consolidateTags = context.consolidateTags;
this.sourceColumnDefinitions = context.columnDefinitions;
this.columnDefinitions = (_b3 = context.columnWriteDefinitions) != null ? _b3 : context.columnDefinitions;
this.columnPlacementTagTable = context.columnPlacementTagTable;
this.doneStatusMarkers = context.doneStatusMarkers;
this.cancelledStatusMarkers = context.cancelledStatusMarkers;
this.ignoredStatusMarkers = context.ignoredStatusMarkers;
if (this._done) {
this._column = void 0;
}
}
get id() {
return this._id;
}
get done() {
return this._done;
}
set done(done) {
var _a5;
this._done = done;
this._column = void 0;
this._displayStatus = (_a5 = Array.from(this.doneStatusMarkers)[0]) != null ? _a5 : "x";
}
get isCancelled() {
return isStatusMatch(this._displayStatus, this.cancelledStatusMarkers);
}
undone() {
this._done = false;
this._displayStatus = " ";
}
cycleStatus(statusMarkerOrder) {
const next2 = getNextStatusMarker(
this._displayStatus,
this.doneStatusMarkers,
statusMarkerOrder
);
if (next2.done) {
this.done = true;
return true;
}
this._done = false;
this._displayStatus = next2.status;
return false;
}
get displayStatus() {
return this._displayStatus;
}
get path() {
return this._path;
}
get indentation() {
return this._indentation;
}
get column() {
return this._column;
}
set column(column) {
if (column === "done") {
this.done = true;
return;
}
const wasDone = this._done;
if (column === "uncategorised") {
this.moveToUncategorised();
if (wasDone) {
this._displayStatus = " ";
}
return;
}
this._done = false;
if (wasDone) {
this._displayStatus = " ";
}
this.moveToColumn(column);
}
get tags() {
return this._tags;
}
getPlacementTagsForColumn(column) {
var _a5;
return ((_a5 = this.columnPlacementTagTable[column]) != null ? _a5 : []).filter((tag2) => isValidTag(tag2));
}
getCurrentPlacementTags() {
if (!this.column || this.column === "archived" || this.column === "done" || this.column === "uncategorised") {
return [];
}
return this.getPlacementTagsForColumn(this.column);
}
getColumnDefinition(column, definitions = this.columnDefinitions) {
if (!column) return void 0;
return definitions.find((definition) => definition.id === column);
}
moveToColumn(column) {
const sourceColumn = this.getColumnDefinition(
this._column && this._column !== "archived" && this._column !== "done" && this._column !== "uncategorised" ? this._column : void 0,
this.sourceColumnDefinitions
);
const destinationColumn = this.getColumnDefinition(column);
if (sourceColumn && usesStatusMatching(sourceColumn)) {
this._displayStatus = " ";
}
const sourcePrioritySchema = getColumnPrioritySchema(sourceColumn);
if (sourceColumn && sourcePrioritySchema) {
this.removePriorityPlacement(sourcePrioritySchema);
}
const destinationStatus = destinationColumn ? getColumnStatus(destinationColumn) : void 0;
if (destinationStatus) {
this._displayStatus = destinationStatus;
}
const destinationPriority = getColumnPriority(destinationColumn);
if (destinationPriority && destinationColumn) {
this.writePriorityPlacement(destinationPriority, getColumnPrioritySchema(destinationColumn));
}
this._column = column;
}
moveToUncategorised() {
const sourceColumn = this.getColumnDefinition(
this._column && this._column !== "archived" && this._column !== "done" && this._column !== "uncategorised" ? this._column : void 0,
this.sourceColumnDefinitions
);
if (sourceColumn && usesStatusMatching(sourceColumn)) {
this._displayStatus = " ";
}
const sourcePrioritySchema = getColumnPrioritySchema(sourceColumn);
if (sourceColumn && sourcePrioritySchema) {
this.removePriorityPlacement(sourcePrioritySchema);
}
this._column = void 0;
this._done = false;
}
stripTagFromContent(value, tag2) {
const escapedTag = escapeRegExp2(tag2);
return value.replace(new RegExp(`(^|\\s)#${escapedTag}(?=$|\\s|[^-_/\\p{L}\\p{N}])`, "gu"), "$1").replace(/[ \t]{2,}/g, " ").trim();
}
replaceTag(oldTag, newTag) {
if (oldTag) {
this._tags.delete(oldTag);
this.content = this.stripTagFromContent(this.content, oldTag);
}
if (newTag) {
this._tags.add(newTag);
const contentTags = Array.from(getTagsFromContent(this.content)).map((tag2) => tag2.toLowerCase());
if (!this.consolidateTags && !contentTags.includes(newTag.toLowerCase())) {
this.content = `${this.content.trim()} #${newTag}`.trim();
}
}
}
stripPlacementTags(value, placementTags) {
return placementTags.reduce((nextValue, tag2) => this.stripTagFromContent(nextValue, tag2), value);
}
transformContentWithPropertyWriter(transform) {
const rawLine = `- [ ] ${this.content.trim()}`;
const transformed = transform(rawLine);
const match = transformed.match(taskStringRegex);
if (match == null ? void 0 : match[3]) {
this.content = match[3];
}
}
removePriorityPlacement(schema2 = getPriorityColumnContextSchema(this.propertySchemaOption)) {
if (!schema2) return;
const adapter = getPropertyWriteAdapter(schema2);
if (!adapter) return;
this.transformContentWithPropertyWriter((rawLine) => adapter.removePriority(rawLine));
}
writePriorityPlacement(priority, schema2 = getPriorityColumnContextSchema(this.propertySchemaOption)) {
if (!schema2) return;
const adapter = getPropertyWriteAdapter(schema2);
if (!adapter) return;
this.transformContentWithPropertyWriter((rawLine) => adapter.upsertPriority(rawLine, priority));
}
serialise() {
if (this._deleted) {
return "";
}
const placementTags = this.getCurrentPlacementTags();
const currentColumnDefinition = this.getColumnDefinition(
this.column && this.column !== "archived" && this.column !== "done" && this.column !== "uncategorised" ? this.column : void 0
);
const usesStatusPlacement = !!currentColumnDefinition && usesStatusMatching(currentColumnDefinition);
const usesPriorityPlacement = !!currentColumnDefinition && usesPriorityMatching(currentColumnDefinition);
const serialisedContent = placementTags.length > 0 ? this.stripPlacementTags(this.content.trim(), placementTags) : this.content.trim();
const serialisedTags = this.consolidateTags ? Array.from(this.tags).filter((tag2) => !placementTags.includes(tag2)) : [];
return [
this.indentation,
`- [${this._displayStatus}] `,
serialisedContent,
this.consolidateTags && serialisedTags.length > 0 ? ` ${serialisedTags.map((tag2) => `#${tag2}`).join(" ")}` : "",
this.column ? this.column === "archived" ? ` #${this.column}` : usesStatusPlacement || usesPriorityPlacement ? "" : placementTags.length > 0 ? ` ${placementTags.map((tag2) => `#${tag2}`).join(" ")}` : ` #${this.column}` : "",
this.blockLink ? ` ^${this.blockLink}` : ""
].join("").trimEnd();
}
get sourceBlockLineCount() {
return 1 + flattenSourceBlockNodes(this.sourceChildren).length;
}
sourceBlockRows(serializedParent = this.serialise()) {
return [
serializedParent,
...flattenSourceBlockNodes(this.sourceChildren).map((node) => node.rawLine)
];
}
updateSourceBlockRowContent(rowIndex, content) {
const node = this.findSourceBlockNode(rowIndex);
if (!node) {
return null;
}
if (node.kind === "raw") {
if (content === "") {
return "";
}
const rawListItemMatch = node.rawLine.slice(node.indentation.length).match(/^([-*+]\s+)(.+)$/);
if (rawListItemMatch && !/^[-*+]\s+/.test(content)) {
return `${node.indentation}${rawListItemMatch[1]}${content}`;
}
return `${node.indentation}${content}`;
}
const parsed = parseSourceTaskLine(node.rawLine);
if (!parsed) {
return null;
}
return `${parsed.indentation}${parsed.bullet} [${parsed.status}] ${content}`;
}
cycleSourceTaskRowStatus(rowIndex, statusMarkerOrder) {
const node = this.findSourceBlockNode(rowIndex);
if (!node || node.kind !== "task") {
return null;
}
const parsed = parseSourceTaskLine(node.rawLine);
if (!parsed) {
return null;
}
const next2 = getNextStatusMarker(
parsed.status || " ",
this.doneStatusMarkers,
statusMarkerOrder
);
return `${parsed.indentation}${parsed.bullet} [${next2.status}] ${parsed.content}`;
}
isSourceTaskStatusDone(status) {
return isStatusMatch(status, this.doneStatusMarkers);
}
findSourceBlockNode(rowIndex) {
var _a5;
return (_a5 = flattenSourceBlockNodes(this.sourceChildren).find((node) => node.rowIndex === rowIndex)) != null ? _a5 : null;
}
serialiseForColumn(column) {
const originalColumn = this._column;
const originalDone = this._done;
const originalDisplayStatus = this._displayStatus;
const originalContent = this.content;
if (column === "done") {
this.done = true;
} else if (column === "uncategorised") {
this.moveToUncategorised();
} else {
this.column = column;
}
try {
return this.serialise();
} finally {
this._column = originalColumn;
this._done = originalDone;
this._displayStatus = originalDisplayStatus;
this.content = originalContent;
}
}
archive() {
const sourceColumn = this.getColumnDefinition(
this._column && this._column !== "archived" && this._column !== "done" && this._column !== "uncategorised" ? this._column : void 0,
this.sourceColumnDefinitions
);
const sourcePrioritySchema = getColumnPrioritySchema(sourceColumn);
if (sourceColumn && sourcePrioritySchema) {
this.removePriorityPlacement(sourcePrioritySchema);
}
if (!this._done) {
this._displayStatus = "x";
}
this._done = true;
this._column = "archived";
}
cancel() {
var _a5;
this._displayStatus = (_a5 = Array.from(this.cancelledStatusMarkers)[0]) != null ? _a5 : "-";
}
restore() {
this._displayStatus = " ";
}
delete() {
this._deleted = true;
}
};
function isTrackedTaskString(input, ignoredStatusMarkers = DEFAULT_IGNORED_STATUS_MARKERS) {
if (input.includes("#archived")) {
return false;
}
const parsed = parseSourceTaskLine(input);
if (!parsed) {
return false;
}
if (isStatusMatch(parsed.status, ignoredStatusMarkers)) {
return false;
}
return true;
}
var taskStringRegex = /^(\s*)[-*+]\s\[([^\[\]]*)\]\s(.+)/;
var blockLinkRegexp = /\s\^([a-zA-Z0-9-]+)$/;
function escapeRegExp2(input) {
return input.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}
function getTaskPriorityMatchValue(propertySchemaOption, properties) {
const priority = properties.get("priority");
if (propertySchemaOption === "tasks" /* TasksPlugin */ && typeof (priority == null ? void 0 : priority.value) === "number") {
return getTasksPriorityValueFromWeight(priority.value);
}
if (propertySchemaOption === "dataview" /* Dataview */ && typeof (priority == null ? void 0 : priority.value) === "string") {
return priority.value.trim();
}
return void 0;
}
function getPriorityColumnContextSchema(propertySchemaOption) {
return propertySchemaOption === "tasks" /* TasksPlugin */ || propertySchemaOption === "dataview" /* Dataview */ ? propertySchemaOption : void 0;
}
function getTaskPriorityMatchValues(rawLine) {
return {
["tasks" /* TasksPlugin */]: getTaskPriorityMatchValue(
"tasks" /* TasksPlugin */,
getSchemaImpl("tasks" /* TasksPlugin */).parseProperties(rawLine)
),
["dataview" /* Dataview */]: getTaskPriorityMatchValue(
"dataview" /* Dataview */,
getSchemaImpl("dataview" /* Dataview */).parseProperties(rawLine)
)
};
}
// src/ui/filters/date_filter.ts
var TODAY_FILTER_VALUE = "$TODAY";
var DATE_FILTER_OPERATORS = [
{ value: "before", label: "before" },
{ value: "on-or-before", label: "on or before" },
{ value: "on", label: "on" },
{ value: "on-or-after", label: "on or after" },
{ value: "after", label: "after" }
];
function getToday() {
const now2 = /* @__PURE__ */ new Date();
return new Date(Date.UTC(now2.getFullYear(), now2.getMonth(), now2.getDate()));
}
function resolveConditionDate(condition, today) {
if (condition.value === TODAY_FILTER_VALUE) {
return today;
}
return parseDateOnly(condition.value);
}
function toCalendarDay(value) {
const isDateOnlyEncoding = value.getUTCHours() === 0 && value.getUTCMinutes() === 0 && value.getUTCSeconds() === 0 && value.getUTCMilliseconds() === 0;
if (isDateOnlyEncoding) {
return value;
}
return new Date(Date.UTC(value.getFullYear(), value.getMonth(), value.getDate()));
}
function matchesOperator(taskDay, conditionDay, operator) {
switch (operator) {
case "before":
return taskDay < conditionDay;
case "on-or-before":
return taskDay <= conditionDay;
case "on":
return taskDay === conditionDay;
case "on-or-after":
return taskDay >= conditionDay;
case "after":
return taskDay > conditionDay;
}
}
function taskMatchesDateConditions(task, conditions, today) {
var _a5;
for (const condition of conditions) {
const conditionDate = resolveConditionDate(condition, today);
if (!conditionDate) {
continue;
}
const value = (_a5 = task.properties.get(condition.property)) == null ? void 0 : _a5.value;
if (!(value instanceof Date)) {
continue;
}
if (!matchesOperator(
toCalendarDay(value).getTime(),
conditionDate.getTime(),
condition.operator
)) {
return false;
}
}
return true;
}
// src/ui/tasks/task_grouping.ts
var DEFAULT_GROUP_BUCKET_ID = "__default__";
function deriveGroupBuckets(tasks, source2, excludedTags = [], statusMarkerOrder = "", doneStatusMarkers = "", groupDirection = "asc", today = getToday()) {
var _a5;
if (source2.kind === "file") {
const paths = [...new Set(tasks.map((task) => task.path))].sort(
(a, b) => a.localeCompare(b)
);
if (paths.length === 0) {
return [
{
id: DEFAULT_GROUP_BUCKET_ID,
label: "No files",
value: null,
source: source2,
isDefault: true
}
];
}
const buckets = paths.map((path) => ({
id: createFileGroupBucketId(path),
label: path,
value: path,
source: source2,
isDefault: false
}));
return applyGroupDirection(buckets, groupDirection);
}
if (source2.kind === "tag-prefix") {
const prefix = normalizeTagPrefix(source2.prefix);
const excludeSet = createNormalizedTagSet(excludedTags);
const includedTags = normalizeTagIncludeList(source2.includeTags, prefix).filter((tag2) => !isTagExcluded(tag2, excludeSet));
if (includedTags.length > 0) {
const buckets2 = includedTags.map((fullTag) => {
const label = prefix && fullTag.toLowerCase().startsWith(prefix) ? fullTag.slice(prefix.length) : fullTag;
return {
id: createTagPrefixGroupBucketId(prefix, fullTag.toLowerCase()),
label,
value: fullTag,
source: { kind: "tag-prefix", prefix, includeTags: includedTags },
isDefault: false
};
});
buckets2.push({
id: createTagPrefixUnassignedGroupBucketId(prefix),
label: "Unassigned",
value: null,
source: { kind: "tag-prefix", prefix, includeTags: includedTags },
isDefault: true
});
return applyGroupDirection(buckets2, groupDirection);
}
const tagMap = /* @__PURE__ */ new Map();
for (const task of tasks) {
for (const tag2 of task.tags) {
if (isTagExcluded(tag2, excludeSet)) continue;
if (prefix) {
if (tag2.toLowerCase().startsWith(prefix)) {
const suffix = tag2.slice(prefix.length);
const key2 = suffix.toLowerCase();
if (suffix && !tagMap.has(key2)) {
tagMap.set(key2, tag2);
}
}
} else {
const key2 = tag2.toLowerCase();
if (!tagMap.has(key2)) {
tagMap.set(key2, tag2);
}
}
}
}
const sortedFullTags = Array.from(tagMap.entries()).sort((a, b) => a[0].localeCompare(b[0])).map((entry) => entry[1]);
const buckets = sortedFullTags.map((fullTag) => {
const label = prefix ? fullTag.slice(prefix.length) : fullTag;
return {
id: createTagPrefixGroupBucketId(prefix, label.toLowerCase()),
label,
value: fullTag,
source: { kind: "tag-prefix", prefix },
isDefault: false
};
});
buckets.push({
id: createTagPrefixUnassignedGroupBucketId(prefix),
label: "Unassigned",
value: null,
source: { kind: "tag-prefix", prefix },
isDefault: true
});
return applyGroupDirection(buckets, groupDirection);
}
if (source2.kind === "property") {
const valueMap = /* @__PURE__ */ new Map();
let hasMissingValue = false;
let hasOverdueValue = false;
for (const task of tasks) {
const property = task.properties.get(source2.key);
const value = (_a5 = property == null ? void 0 : property.value) != null ? _a5 : null;
if (value === null) {
hasMissingValue = true;
continue;
}
if (source2.collapsePastDates && isOverdueValue(value, today)) {
hasOverdueValue = true;
continue;
}
const key2 = propertyValueKey(value);
if (!valueMap.has(key2)) {
valueMap.set(key2, {
value,
label: property ? formatPropertyGroupLabel(property) : formatPropertyValueLabel(value)
});
}
}
const buckets = Array.from(valueMap.values()).sort((a, b) => comparePropertyGroupValues(
source2.key,
a.value,
b.value,
statusMarkerOrder,
doneStatusMarkers
)).map((entry) => ({
id: createPropertyGroupBucketId(source2.key, entry.value),
label: entry.label,
value: entry.value,
source: source2,
isDefault: false
}));
if (hasOverdueValue) {
buckets.unshift({
id: createPropertyOverdueGroupBucketId(source2.key),
label: "Overdue",
value: null,
source: source2,
isDefault: false
});
}
if (hasMissingValue || buckets.length === 0) {
buckets.push({
id: createPropertyMissingGroupBucketId(source2.key),
label: "Unassigned",
value: null,
source: source2,
isDefault: true
});
}
return applyGroupDirection(buckets, groupDirection);
}
return [
{
id: DEFAULT_GROUP_BUCKET_ID,
label: "Default",
value: null,
source: source2,
isDefault: true
}
];
}
function applyGroupDirection(buckets, groupDirection) {
return groupDirection === "desc" ? [...buckets].reverse() : buckets;
}
function getTaskTagGroupValue(task, source2, excludedTags = []) {
const prefix = normalizeTagPrefix(source2.prefix);
return resolveTaskGroupTag(
task,
prefix,
createNormalizedTagSet(excludedTags),
normalizeTagIncludeList(source2.includeTags, prefix)
);
}
function resolveTaskGroupTag(task, prefix, excludeSet, includeTags = []) {
var _a5;
const candidateTags = Array.from(task.tags).filter((tag2) => !isTagExcluded(tag2, excludeSet)).filter((tag2) => {
if (!prefix) return true;
return tag2.toLowerCase().startsWith(prefix) && tag2.slice(prefix.length).length > 0;
});
if (includeTags.length > 0) {
const candidateByLowercase = new Map(candidateTags.map((tag2) => [tag2.toLowerCase(), tag2]));
for (const includeTag of includeTags) {
const matchedTag = candidateByLowercase.get(includeTag.toLowerCase());
if (matchedTag) return matchedTag;
}
return null;
}
return (_a5 = candidateTags.sort((a, b) => a.toLowerCase().localeCompare(b.toLowerCase()))[0]) != null ? _a5 : null;
}
function createGroupAssigner(buckets, source2, excludedTags = [], today = getToday()) {
var _a5, _b3;
const defaultBucketId = (_a5 = buckets.find((bucket) => bucket.isDefault)) == null ? void 0 : _a5.id;
if (source2.kind === "tag-prefix") {
const prefix = normalizeTagPrefix(source2.prefix);
const excludeSet = createNormalizedTagSet(excludedTags);
const includedTags = normalizeTagIncludeList(source2.includeTags, prefix);
const idByValue = /* @__PURE__ */ new Map();
for (const bucket of buckets) {
if (!bucket.isDefault && typeof bucket.value === "string") {
idByValue.set(bucket.value.toLowerCase(), bucket.id);
}
}
return (task) => {
var _a6;
const groupTag = resolveTaskGroupTag(task, prefix, excludeSet, includedTags);
if (groupTag === null) return defaultBucketId;
return (_a6 = idByValue.get(groupTag.toLowerCase())) != null ? _a6 : defaultBucketId;
};
}
if (source2.kind === "file") {
const idByPath = /* @__PURE__ */ new Map();
for (const bucket of buckets) {
if (typeof bucket.value === "string") idByPath.set(bucket.value, bucket.id);
}
return (task) => {
var _a6;
return (_a6 = idByPath.get(task.path)) != null ? _a6 : defaultBucketId;
};
}
if (source2.kind === "property") {
const idByValue = /* @__PURE__ */ new Map();
for (const bucket of buckets) {
if (!bucket.isDefault && bucket.value !== null) {
idByValue.set(propertyValueKey(bucket.value), bucket.id);
}
}
const overdueBucketId = (_b3 = buckets.find(isPropertyOverdueBucket)) == null ? void 0 : _b3.id;
return (task) => {
var _a6, _b4, _c2;
const value = (_b4 = (_a6 = task.properties.get(source2.key)) == null ? void 0 : _a6.value) != null ? _b4 : null;
if (value === null) return defaultBucketId;
if (overdueBucketId !== void 0 && isOverdueValue(value, today)) {
return overdueBucketId;
}
return (_c2 = idByValue.get(propertyValueKey(value))) != null ? _c2 : defaultBucketId;
};
}
return () => defaultBucketId;
}
function createFileGroupBucketId(path) {
return `file:${path}`;
}
function createTagPrefixGroupBucketId(prefix, label) {
return `tag-prefix:${prefix}:${label}`;
}
function createTagPrefixUnassignedGroupBucketId(prefix) {
return createTagPrefixGroupBucketId(prefix, "__unassigned__");
}
function createPropertyGroupBucketId(key2, value) {
return `property:${key2}:${propertyValueKey(value)}`;
}
function createPropertyMissingGroupBucketId(key2) {
return `property:${key2}:__missing__`;
}
function createPropertyOverdueGroupBucketId(key2) {
return `property:${key2}:__overdue__`;
}
function isPropertyOverdueBucket(bucket) {
return bucket.source.kind === "property" && bucket.id === createPropertyOverdueGroupBucketId(bucket.source.key);
}
function isOverdueValue(value, today) {
return value instanceof Date && toCalendarDay(value).getTime() < today.getTime();
}
function propertyValueKey(value) {
if (value instanceof Date) {
return `date:${value.getTime()}`;
}
return `${typeof value}:${String(value).toLowerCase()}`;
}
function comparePropertyGroupValues(key2, a, b, statusMarkerOrder, doneStatusMarkers) {
if (key2 === "priority") {
return comparePriorityGroupValues(a, b);
}
if (key2 === UNIVERSAL_STATUS_PROPERTY_KEY) {
return compareStatusMarkerValues(a, b, statusMarkerOrder, doneStatusMarkers);
}
return compareValues(a, b);
}
function comparePriorityGroupValues(a, b) {
const aRank = getPriorityWeight(a);
const bRank = getPriorityWeight(b);
if (aRank !== null && bRank !== null && aRank !== bRank) {
return bRank - aRank;
}
if (aRank !== null && bRank === null) return -1;
if (aRank === null && bRank !== null) return 1;
return compareValues(a, b);
}
function formatPropertyGroupLabel(property) {
if (property.key === "priority") {
if (typeof property.value === "number") {
return property.rawValue || formatPropertyValueLabel(property.value);
}
if (property.value !== null) {
return String(property.value);
}
return property.rawValue;
}
return property.value === null ? property.rawValue : formatPropertyValueLabel(property.value);
}
function formatPropertyValueLabel(value) {
if (value instanceof Date) {
return value.toISOString().slice(0, 10);
}
return String(value);
}
function normalizeTagPrefix(prefix) {
var _a5;
return (_a5 = prefix == null ? void 0 : prefix.trim().replace(/^#/, "").toLowerCase()) != null ? _a5 : "";
}
function normalizeTagName(tag2) {
return tag2.trim().replace(/^#/, "");
}
function normalizeTagIncludeList(tags, normalizedPrefix = "") {
const seen = /* @__PURE__ */ new Set();
const normalized = [];
for (const rawTag of tags != null ? tags : []) {
const tag2 = normalizeTagName(rawTag);
if (!tag2) continue;
const fullTag = normalizedPrefix && !tag2.toLowerCase().startsWith(normalizedPrefix) ? `${normalizedPrefix}${tag2}` : tag2;
const key2 = fullTag.toLowerCase();
if (seen.has(key2)) continue;
seen.add(key2);
normalized.push(fullTag);
}
return normalized;
}
function createNormalizedTagSet(tags) {
return new Set(tags.map((tag2) => normalizeTagName(tag2).toLowerCase()).filter(Boolean));
}
function isTagExcluded(tag2, excludeSet) {
return excludeSet.has(tag2.toLowerCase());
}
// src/ui/filters/filter_query.ts
var OPERATORS_BY_TEXT = [
// Two-character operators must be tried before their one-character prefixes.
["<=", "on-or-before"],
[">=", "on-or-after"],
["<", "before"],
[">", "after"],
["=", "on"]
];
var TEXT_BY_OPERATOR = {
before: "<",
"on-or-before": "<=",
on: "=",
"on-or-after": ">=",
after: ">"
};
function emptyFilterQuery() {
return { contentTerms: [], tagGroups: [], filePaths: [], dateConditions: [] };
}
function isEmptyFilterQuery(query) {
return query.contentTerms.length === 0 && query.tagGroups.length === 0 && query.filePaths.length === 0 && query.dateConditions.length === 0;
}
function tokenize(text2) {
const tokens = [];
let segments = [];
let current = "";
let quoted = false;
const endSegment = () => {
if (current !== "" || quoted) {
segments.push({ text: current, quoted });
}
current = "";
};
const endToken = () => {
endSegment();
if (segments.length > 0) {
tokens.push(segments);
}
segments = [];
};
for (const char of text2) {
if (char === '"') {
endSegment();
quoted = !quoted;
} else if (!quoted && /\s/.test(char)) {
endToken();
} else {
current += char;
}
}
endToken();
return tokens;
}
function segmentsText(segments) {
return segments.map((segment) => segment.text).join("");
}
function parseDateToken(property, rest) {
const operatorEntry = OPERATORS_BY_TEXT.find(
([text2]) => rest.startsWith(text2)
);
if (!operatorEntry) {
return null;
}
const rawValue = rest.slice(operatorEntry[0].length);
if (/^\$?today$/i.test(rawValue)) {
return { property, operator: operatorEntry[1], value: TODAY_FILTER_VALUE };
}
if (parseDateOnly(rawValue)) {
return { property, operator: operatorEntry[1], value: rawValue };
}
return null;
}
function parseFilterQuery(text2, dateKeys) {
const query = emptyFilterQuery();
for (const segments of tokenize(text2)) {
const first = segments[0];
const colonIndex = first.quoted ? -1 : first.text.indexOf(":");
if (colonIndex <= 0) {
const term = segmentsText(segments);
if (term !== "") {
query.contentTerms.push(term);
}
continue;
}
const prefix = first.text.slice(0, colonIndex).toLowerCase();
const rest = first.text.slice(colonIndex + 1) + segmentsText(segments.slice(1));
if (prefix === "tag") {
const tags = rest.split(",").filter((tag2) => tag2 !== "");
if (tags.length > 0) {
query.tagGroups.push(tags);
}
continue;
}
if (prefix === "file") {
query.filePaths.push(
...rest.split(",").filter((path) => path !== "")
);
continue;
}
const dateKey = dateKeys.find((key2) => key2.toLowerCase() === prefix);
if (dateKey) {
const condition = parseDateToken(dateKey, rest);
if (condition) {
query.dateConditions.push(condition);
continue;
}
}
query.contentTerms.push(segmentsText(segments));
}
return query;
}
function serializeContentTerm(term) {
const needsQuoting = /\s/.test(term) || /^[^\s:"]+:/.test(term) || term.startsWith('"');
return needsQuoting ? `"${term}"` : term;
}
function serializeFileEntry(path) {
return /\s/.test(path) ? `"${path}"` : path;
}
function parseContentTerms(text2) {
return tokenize(text2).map(segmentsText).filter((term) => term !== "");
}
function serializeContentTerms(terms) {
return terms.map(serializeContentTerm).join(" ");
}
function serializeFilterQuery(query) {
return [
...query.contentTerms.map(serializeContentTerm),
...query.tagGroups.map((group) => `tag:${group.join(",")}`),
...query.filePaths.length > 0 ? [`file:${query.filePaths.map(serializeFileEntry).join(",")}`] : [],
...query.dateConditions.map(
(condition) => `${condition.property}:${TEXT_BY_OPERATOR[condition.operator]}${condition.value}`
)
].join(" ");
}
function taskMatchesFilterQuery(task, query, today) {
var _a5;
const descendants = ((_a5 = task.sourceChildren) == null ? void 0 : _a5.length) ? flattenSourceBlockNodes(task.sourceChildren) : [];
if (query.contentTerms.length > 0) {
const texts = [
task.content,
...descendants.map(getSourceNodeText)
].map((text2) => text2.toLowerCase());
const matchesEveryTerm = query.contentTerms.every((term) => {
const needle = term.toLowerCase();
return texts.some((text2) => text2.includes(needle));
});
if (!matchesEveryTerm) {
return false;
}
}
if (query.tagGroups.length > 0) {
const tags = new Set(task.tags);
for (const node of descendants) {
for (const tag2 of getTagsFromContent(getSourceNodeText(node))) {
tags.add(tag2);
}
}
if (!query.tagGroups.every((group) => group.some((tag2) => tags.has(tag2)))) {
return false;
}
}
if (query.filePaths.length > 0) {
const path = task.path.toLowerCase();
if (!query.filePaths.some((term) => path.includes(term.toLowerCase()))) {
return false;
}
}
return taskMatchesDateConditions(task, query.dateConditions, today);
}
// src/ui/filters/filter_state.ts
function legacyFilterSettingsToQuery(settings) {
var _a5, _b3, _c2, _d, _e;
const query = emptyFilterQuery();
const contentText = (_a5 = settings.lastContentFilter) == null ? void 0 : _a5.replace(/"/g, "").trim();
if (contentText) {
query.contentTerms.push(contentText);
}
const tags = ((_b3 = settings.lastTagFilter) != null ? _b3 : []).filter((tag2) => tag2 !== "");
if (tags.length > 0) {
query.tagGroups.push(tags);
}
const filePath = (_d = (_c2 = settings.lastFileFilter) == null ? void 0 : _c2[0]) == null ? void 0 : _d.replace(/"/g, "").trim();
if (filePath) {
query.filePaths.push(filePath);
}
query.dateConditions = ((_e = settings.lastDateFilter) != null ? _e : []).map((condition) => ({
...condition
}));
return serializeFilterQuery(query);
}
function savedFilterToQuery(filter) {
var _a5, _b3, _c2, _d, _e, _f, _g;
if (filter.query !== void 0) {
return filter.query;
}
const query = emptyFilterQuery();
const contentText = (_a5 = filter.content) == null ? void 0 : _a5.text.replace(/"/g, "").trim();
if (contentText) {
query.contentTerms.push(contentText);
}
const tags = ((_c2 = (_b3 = filter.tag) == null ? void 0 : _b3.tags) != null ? _c2 : []).filter((tag2) => tag2 !== "");
if (tags.length > 0) {
query.tagGroups.push(tags);
}
const filePath = (_e = (_d = filter.file) == null ? void 0 : _d.filepaths[0]) == null ? void 0 : _e.replace(/"/g, "").trim();
if (filePath) {
query.filePaths.push(filePath);
}
query.dateConditions = ((_g = (_f = filter.date) == null ? void 0 : _f.conditions) != null ? _g : []).map((condition) => ({
...condition
}));
return serializeFilterQuery(query);
}
function readBoardFilterState(settings) {
if (settings.lastFilter !== void 0) {
return settings.lastFilter;
}
return legacyFilterSettingsToQuery(settings);
}
function writeBoardFilterState(settings, query) {
const next2 = { ...settings, lastFilter: query };
delete next2.lastContentFilter;
delete next2.lastTagFilter;
delete next2.lastFileFilter;
delete next2.lastDateFilter;
return next2;
}
function shouldApplyIncomingBoardFilterState(currentQuery, incomingQuery, lastPersistedQuery, hydrated) {
if (!hydrated) {
return true;
}
return currentQuery === lastPersistedQuery && incomingQuery !== lastPersistedQuery;
}
// src/ui/settings/settings_store.ts
var VisibilityOption = /* @__PURE__ */ ((VisibilityOption2) => {
VisibilityOption2["Auto"] = "auto";
VisibilityOption2["NeverShow"] = "never";
VisibilityOption2["AlwaysShow"] = "always";
return VisibilityOption2;
})(VisibilityOption || {});
var ScopeOption = /* @__PURE__ */ ((ScopeOption2) => {
ScopeOption2["Folder"] = "folder";
ScopeOption2["Everywhere"] = "everywhere";
ScopeOption2["SelectedFolders"] = "selectedFolders";
return ScopeOption2;
})(ScopeOption || {});
var FlowDirection = /* @__PURE__ */ ((FlowDirection2) => {
FlowDirection2["LeftToRight"] = "ltr";
FlowDirection2["RightToLeft"] = "rtl";
FlowDirection2["TopToBottom"] = "ttb";
FlowDirection2["BottomToTop"] = "btt";
return FlowDirection2;
})(FlowDirection || {});
function isFlowDirection(value) {
return Object.values(FlowDirection).includes(value);
}
var PropertyDisplayMode = /* @__PURE__ */ ((PropertyDisplayMode2) => {
PropertyDisplayMode2["None"] = "none";
PropertyDisplayMode2["Pretty"] = "pretty";
PropertyDisplayMode2["Debug"] = "debug";
return PropertyDisplayMode2;
})(PropertyDisplayMode || {});
var contentValueSchema = z.object({
text: z.string()
});
var tagValueSchema = z.object({
tags: z.array(z.string())
});
var fileValueSchema = z.object({
filepaths: z.array(z.string())
});
var dateFilterConditionSchema = z.object({
property: z.string(),
operator: z.enum(["before", "on-or-before", "on", "on-or-after", "after"]),
value: z.string()
});
var dateValueSchema = z.object({
conditions: z.array(dateFilterConditionSchema)
});
var savedFilterSchema = z.object({
id: z.string(),
name: z.string().optional(),
query: z.string().optional(),
content: contentValueSchema.optional(),
tag: tagValueSchema.optional(),
file: fileValueSchema.optional(),
date: dateValueSchema.optional()
});
var groupSourceSchema = z.union([
z.object({ kind: z.literal("none") }),
z.object({ kind: z.literal("file") }),
z.object({
kind: z.literal("tag-prefix"),
prefix: z.string().optional(),
includeTags: z.array(z.string()).optional()
}),
z.object({
kind: z.literal("property"),
key: z.string(),
collapsePastDates: z.boolean().optional()
})
]).catch({ kind: "none" });
var savedGroupingSchema = z.object({
id: z.string(),
name: z.string(),
source: groupSourceSchema
});
var savedViewSchema = z.object({
id: z.string(),
name: z.string(),
query: z.string().optional(),
sort: z.object({
mode: z.nativeEnum(ColumnOrderMode).catch("file" /* FileOrder */),
property: z.string().nullable().optional(),
direction: z.enum(["asc", "desc"]).catch("asc")
}).optional(),
group: z.object({
source: groupSourceSchema,
direction: z.enum(["asc", "desc"]).catch("asc")
}).optional(),
flowDirection: z.nativeEnum(FlowDirection).catch("ltr" /* LeftToRight */).optional(),
columnWidth: z.number().min(200).max(600).catch(300).optional()
});
var savedViewPropertiesSchema = savedViewSchema.omit({ id: true, name: true });
var columnDefinitionSchema = z.object({
id: z.string(),
label: z.string(),
color: z.string().optional(),
matchMode: z.enum(["name", "tags", "status", "priority"]).default("name"),
matchTags: z.array(z.string()).default([]),
matchStatus: z.string().optional(),
matchPriority: z.string().optional(),
matchPropertySchema: z.enum(["tasks" /* TasksPlugin */, "dataview" /* Dataview */]).optional()
});
var manualOrderEntriesSchema = z.array(z.string());
var manualOrderCellSchema = z.record(z.string(), manualOrderEntriesSchema);
var manualOrderSchema = z.preprocess((value) => {
if (!value || typeof value !== "object" || Array.isArray(value)) {
return {};
}
const record = value;
const hasFlatEntries = Object.values(record).some((entry) => Array.isArray(entry));
if (hasFlatEntries) {
const migrated = {};
for (const [columnTag, entries] of Object.entries(record)) {
if (Array.isArray(entries)) {
migrated[columnTag] = entries;
}
}
return { [DEFAULT_GROUP_BUCKET_ID]: migrated };
}
return value;
}, z.record(z.string(), manualOrderCellSchema));
var settingsObject = z.object({
columns: z.array(z.union([z.string(), columnDefinitionSchema])),
scope: z.nativeEnum(ScopeOption).catch("folder" /* Folder */),
showFilepath: z.boolean().default(true).optional(),
consolidateTags: z.boolean().default(false).optional(),
uncategorizedVisibility: z.nativeEnum(VisibilityOption).catch("auto" /* Auto */).optional(),
doneVisibility: z.nativeEnum(VisibilityOption).catch("always" /* AlwaysShow */).optional(),
doneStatusMarkers: z.string().default(DEFAULT_DONE_STATUS_MARKERS).optional(),
cancelledStatusMarkers: z.string().default(DEFAULT_CANCELLED_STATUS_MARKERS).optional(),
ignoredStatusMarkers: z.string().default(DEFAULT_IGNORED_STATUS_MARKERS).optional(),
statusMarkerOrder: z.string().default("").optional(),
savedFilters: z.array(savedFilterSchema).default([]).optional(),
savedGroupings: z.array(savedGroupingSchema).default([]).optional(),
savedViews: z.array(savedViewSchema).default([]).optional(),
// The unified filter query string (SPEC 0029). The four last*Filter
// fields below are its legacy predecessors: still parsed so old
// frontmatter validates (and migrates at read time), never written.
lastFilter: z.string().optional(),
lastContentFilter: z.string().optional(),
lastTagFilter: z.array(z.string()).optional(),
lastFileFilter: z.array(z.string()).optional(),
lastDateFilter: z.array(dateFilterConditionSchema).catch([]).optional(),
// The retired sidebar's filtersExpanded / filtersSidebarExpanded /
// filtersSidebarWidth fields are gone entirely: the schema strips
// unknown keys, so old frontmatter still validates, and dropping them
// here keeps them out of every future write.
columnWidth: z.number().min(200).max(600).catch(300).optional(),
flowDirection: z.nativeEnum(FlowDirection).catch("ltr" /* LeftToRight */).optional(),
collapsedColumns: z.array(z.string()).default([]).optional(),
defaultTaskFile: z.string().default("").optional(),
lastUsedTaskFile: z.string().default("").optional(),
scopeFolders: z.array(z.string()).default([]).optional(),
excludePaths: z.array(z.string()).default([]).optional(),
excludedTags: z.array(z.string()).default([]).optional(),
excludedTaskTags: z.array(z.string()).default([]).optional(),
uncategorizedColumnName: z.string().default("Uncategorized").optional(),
doneColumnName: z.string().default("Done").optional(),
groupSource: groupSourceSchema.default({ kind: "none" }).optional(),
propertySchema: z.nativeEnum(PropertySchemaOption).catch("none" /* None */).optional(),
propertyDisplay: z.nativeEnum(PropertyDisplayMode).catch("none" /* None */).optional(),
treatNestedTasksAsSubtasks: z.boolean().default(false).optional(),
columnOrderMode: z.nativeEnum(ColumnOrderMode).catch("file" /* FileOrder */).optional(),
sortProperty: z.string().nullable().default(null).optional(),
sortDirection: z.enum(["asc", "desc"]).catch("asc").optional(),
groupDirection: z.enum(["asc", "desc"]).catch("asc").optional(),
// Cell-local manual ordering: group bucket id -> column id -> `path::blockLink`.
// Stored alongside display settings in the board's frontmatter (the plugin has
// no separate data file), but kept as its own field so it is never conflated
// with display configuration. Legacy column-local records are migrated under
// the default group bucket id at parse time.
manualOrder: manualOrderSchema.default({}).optional()
});
var defaultSettings = {
columns: createDefaultColumns(["Later", "Soonish", "Next week", "This week", "Today", "Pending"]),
scope: "folder" /* Folder */,
showFilepath: true,
consolidateTags: false,
uncategorizedVisibility: "auto" /* Auto */,
doneVisibility: "always" /* AlwaysShow */,
doneStatusMarkers: DEFAULT_DONE_STATUS_MARKERS,
cancelledStatusMarkers: DEFAULT_CANCELLED_STATUS_MARKERS,
ignoredStatusMarkers: DEFAULT_IGNORED_STATUS_MARKERS,
statusMarkerOrder: "",
savedFilters: [],
savedViews: [],
columnWidth: 300,
flowDirection: "ltr" /* LeftToRight */,
collapsedColumns: [],
defaultTaskFile: "",
lastUsedTaskFile: "",
scopeFolders: [],
excludePaths: [],
excludedTags: [],
excludedTaskTags: [],
uncategorizedColumnName: "Uncategorized",
doneColumnName: "Done",
groupSource: { kind: "none" },
propertySchema: "none" /* None */,
propertyDisplay: "none" /* None */,
treatNestedTasksAsSubtasks: false,
columnOrderMode: "file" /* FileOrder */,
sortProperty: null,
sortDirection: "asc",
groupDirection: "asc",
manualOrder: {}
};
var createSettingsStore = (inheritedSettingsStore) => {
let overrides = {};
let inheritedSettings = {};
let snapshot2 = /* @__PURE__ */ new Map();
const resolve = () => ({ ...defaultSettings, ...inheritedSettings, ...overrides });
const resolveBase = () => ({ ...defaultSettings, ...inheritedSettings });
const takeSnapshot = (resolved) => {
snapshot2 = new Map(
Object.entries(resolved).map(([key2, value]) => [key2, JSON.stringify(value)])
);
};
const initial = resolve();
takeSnapshot(initial);
const inner = writable(initial);
const commit = () => {
const resolved = resolve();
takeSnapshot(resolved);
inner.set(resolved);
};
const unsubscribeInherited = inheritedSettingsStore == null ? void 0 : inheritedSettingsStore.subscribe((nextInheritedSettings) => {
inheritedSettings = { ...nextInheritedSettings };
commit();
});
const set3 = (next2) => {
const record = next2;
const overridesRecord = overrides;
for (const key2 of /* @__PURE__ */ new Set([...Object.keys(record), ...snapshot2.keys()])) {
const nextJson = JSON.stringify(record[key2]);
if (nextJson === snapshot2.get(key2)) {
continue;
}
if (nextJson === void 0) {
delete overridesRecord[key2];
} else {
overridesRecord[key2] = JSON.parse(nextJson);
}
}
commit();
};
return {
subscribe: inner.subscribe,
set: set3,
update: (updater) => set3(updater(resolve())),
load: (nextOverrides) => {
overrides = { ...nextOverrides };
commit();
},
getOverrides: () => ({ ...overrides }),
getBaseSettings: () => structuredClone(resolveBase()),
pinOverrides: (keys) => {
const resolved = resolve();
const overridesRecord = overrides;
for (const key2 of keys) {
const json2 = JSON.stringify(resolved[key2]);
if (json2 !== void 0) {
overridesRecord[key2] = JSON.parse(json2);
}
}
commit();
},
clearOverrides: (keys) => {
for (const key2 of keys) {
delete overrides[key2];
}
commit();
},
pruneOverridesMatchingDefaults: () => {
const base = resolveBase();
const overridesRecord = overrides;
const pruned = [];
for (const key2 of Object.keys(overridesRecord)) {
if (JSON.stringify(overridesRecord[key2]) === JSON.stringify(base[key2])) {
delete overridesRecord[key2];
pruned.push(key2);
}
}
if (pruned.length > 0) {
commit();
}
return pruned;
},
destroy: () => unsubscribeInherited == null ? void 0 : unsubscribeInherited()
};
};
function migrateLegacySavedViews(savedFilters, savedGroupings) {
return [
...(savedFilters != null ? savedFilters : []).map((filter) => {
var _a5;
const query = savedFilterToQuery(filter);
if (query === "") {
return void 0;
}
return {
id: `filter:${filter.id}`,
name: (_a5 = filter.name) != null ? _a5 : query,
query
};
}).filter((view) => view !== void 0),
...(savedGroupings != null ? savedGroupings : []).map((group) => ({
id: `group:${group.id}`,
name: group.name,
group: {
source: group.source,
direction: "asc"
}
}))
];
}
function parseSettingsOverrides(str2) {
var _a5;
try {
const parsed = JSON.parse(str2);
const partial = settingsObject.partial().parse(parsed);
const {
columns: rawColumns,
collapsedColumns: rawCollapsed,
savedFilters: rawSavedFilters,
savedGroupings: rawSavedGroupings,
savedViews: rawSavedViews,
...rest
} = partial;
const overrides = { ...rest };
const migratedViews = migrateLegacySavedViews(rawSavedFilters, rawSavedGroupings);
if (rawSavedViews !== void 0 || migratedViews.length > 0) {
const existingIds = new Set((rawSavedViews != null ? rawSavedViews : []).map((view) => view.id));
overrides.savedViews = [
...rawSavedViews != null ? rawSavedViews : [],
...migratedViews.filter((view) => !existingIds.has(view.id))
];
}
if (rawColumns !== void 0) {
overrides.columns = migrateColumnDefinitions(
rawColumns
);
}
if (partial.propertyDisplay === void 0 && typeof (parsed == null ? void 0 : parsed.showProperties) === "boolean") {
overrides.propertyDisplay = parsed.showProperties ? "debug" /* Debug */ : "none" /* None */;
}
if (rawCollapsed !== void 0) {
overrides.collapsedColumns = migrateCollapsedColumns(
rawCollapsed,
(_a5 = overrides.columns) != null ? _a5 : defaultSettings.columns
);
}
return overrides;
} catch (e) {
return {};
}
}
function resolveSettings(overrides, inheritedSettings = {}) {
return { ...defaultSettings, ...inheritedSettings, ...overrides };
}
function parseSavedViewProperties(value) {
const parsed = savedViewPropertiesSchema.safeParse(value != null ? value : {});
return parsed.success ? parsed.data : {};
}
function toSettingsString(settings) {
return JSON.stringify(settings);
}
function createDefaultColumns(labels) {
const usedIds = /* @__PURE__ */ new Set();
return labels.map((label) => ({
id: createColumnId(label, usedIds),
label,
matchMode: "name",
matchTags: [],
matchStatus: void 0,
matchPriority: void 0,
matchPropertySchema: void 0
}));
}
// src/ui/tasks/manual_order.ts
function manualOrderKey(path, blockLink) {
return `${path}::${blockLink}`;
}
function taskKey(task) {
return task.blockLink ? manualOrderKey(task.path, task.blockLink) : null;
}
function computeDisplayOrder(tasks, entries) {
if (!entries || entries.length === 0) {
return tasks;
}
const byKey = /* @__PURE__ */ new Map();
for (const task of tasks) {
const key2 = taskKey(task);
if (key2 !== null && !byKey.has(key2)) {
byKey.set(key2, task);
}
}
const pinned = [];
const pinnedIds = /* @__PURE__ */ new Set();
for (const entry of entries) {
const task = byKey.get(entry);
if (task && !pinnedIds.has(task.id)) {
pinned.push(task);
pinnedIds.add(task.id);
}
}
const tail = tasks.filter((task) => !pinnedIds.has(task.id));
return [...pinned, ...tail];
}
function computePinnedIds(tasks, entries) {
const pinned = /* @__PURE__ */ new Set();
if (!entries || entries.length === 0) {
return pinned;
}
const present = /* @__PURE__ */ new Set();
for (const task of tasks) {
const key2 = taskKey(task);
if (key2 !== null) present.add(key2);
}
const entrySet = new Set(entries);
for (const task of tasks) {
const key2 = taskKey(task);
if (key2 !== null && entrySet.has(key2) && present.has(key2)) {
pinned.add(task.id);
}
}
return pinned;
}
function arrayMove(items, fromIndex, targetIndex) {
if (fromIndex < 0 || fromIndex >= items.length) {
return [...items];
}
const next2 = [...items];
const [moved] = next2.splice(fromIndex, 1);
if (moved === void 0) {
return next2;
}
const clamped = Math.max(0, Math.min(targetIndex, next2.length));
next2.splice(clamped, 0, moved);
return next2;
}
function computeDropPlan(displayOrder, draggedId, targetIndex) {
const fromIndex = displayOrder.findIndex((task) => task.id === draggedId);
if (fromIndex === -1) {
return { prefixTasks: [], tasksNeedingBlockLink: [] };
}
const reordered = arrayMove(displayOrder, fromIndex, targetIndex);
const landedIndex = reordered.findIndex((task) => task.id === draggedId);
const prefixTasks = reordered.slice(0, landedIndex + 1);
const tasksNeedingBlockLink = prefixTasks.filter((task) => !task.blockLink);
return { prefixTasks, tasksNeedingBlockLink };
}
function buildOrderEntries(prefixTasks, resolveBlockLink) {
return prefixTasks.map((task) => manualOrderKey(task.path, resolveBlockLink(task)));
}
function removeEntry(entries, key2) {
if (!entries || entries.length === 0) {
return entries != null ? entries : [];
}
const next2 = entries.filter((entry) => entry !== key2);
return next2.length === entries.length ? entries : next2;
}
function collectPresentManualOrderKeys(tasks, assignGroupId) {
var _a5, _b3, _c2;
const presentKeysByGroupAndColumn = {};
for (const task of tasks) {
if (!task.blockLink || task.column === "archived") {
continue;
}
const groupId = assignGroupId(task);
if (!groupId) {
continue;
}
const columnTag = task.done || task.column === "done" ? "done" : (_a5 = task.column) != null ? _a5 : "uncategorised";
const keysByColumn = (_b3 = presentKeysByGroupAndColumn[groupId]) != null ? _b3 : {};
const keys = (_c2 = keysByColumn[columnTag]) != null ? _c2 : /* @__PURE__ */ new Set();
keys.add(manualOrderKey(task.path, task.blockLink));
keysByColumn[columnTag] = keys;
presentKeysByGroupAndColumn[groupId] = keysByColumn;
}
return presentKeysByGroupAndColumn;
}
var BLOCK_LINK_ALPHABET = "abcdefghijklmnopqrstuvwxyz0123456789";
function generateBlockLinkId(existing) {
for (let attempt = 0; attempt < 100; attempt++) {
let id = "";
for (let i = 0; i < 6; i++) {
id += BLOCK_LINK_ALPHABET[Math.floor(Math.random() * BLOCK_LINK_ALPHABET.length)];
}
if (!existing.has(id)) {
return id;
}
}
return `t${Date.now().toString(36)}`;
}
var blockLinkRegexp2 = /\s\^([a-zA-Z0-9-]+)\s*$/;
function ensureRowBlockLink(row, existing) {
const existingMatch = row.match(blockLinkRegexp2);
if (existingMatch == null ? void 0 : existingMatch[1]) {
existing.add(existingMatch[1]);
return { row, blockLink: existingMatch[1], changed: false };
}
const blockLink = generateBlockLinkId(existing);
existing.add(blockLink);
return {
row: `${row.trimEnd()} ^${blockLink}`,
blockLink,
changed: true
};
}
// src/ui/board/board_matrix.ts
function deriveBoardMatrix(tasks, columns, settings, today = getToday()) {
var _a5, _b3, _c2, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p, _q;
const tasksByPrimary = {
uncategorised: [],
done: []
};
for (const column of columns) {
tasksByPrimary[column.id] = [];
}
for (const task of tasks) {
if (task.done || task.column === "done") {
tasksByPrimary["done"].push(task);
} else if (task.column === "archived") {
} else if (task.column) {
if (!tasksByPrimary[task.column]) {
tasksByPrimary[task.column] = [];
}
tasksByPrimary[task.column].push(task);
} else {
tasksByPrimary["uncategorised"].push(task);
}
}
const orderMode = (_a5 = settings.columnOrderMode) != null ? _a5 : "file" /* FileOrder */;
const sortProperty = (_b3 = settings.sortProperty) != null ? _b3 : null;
const sortDirection = (_c2 = settings.sortDirection) != null ? _c2 : "asc";
const useProperty = orderMode === "property" /* Property */ && !!sortProperty;
const useManual = orderMode === "manual" /* Manual */;
const manualOrder = (_d = settings.manualOrder) != null ? _d : {};
for (const bucketTasks of Object.values(tasksByPrimary)) {
if (orderMode === "task-name" /* TaskName */) {
sortTasksByTaskName(bucketTasks, sortDirection);
} else if (useProperty && sortProperty) {
sortTasksByProperty(
bucketTasks,
sortProperty,
sortDirection,
(_e = settings.statusMarkerOrder) != null ? _e : "",
(_f = settings.doneStatusMarkers) != null ? _f : "",
settings.propertySchema
);
} else {
sortTasksByFile(bucketTasks);
}
}
const collapsedColumns = new Set((_g = settings.collapsedColumns) != null ? _g : []);
const uncategorizedVisibility = (_h = settings.uncategorizedVisibility) != null ? _h : "auto" /* Auto */;
const showUncategorizedColumn = uncategorizedVisibility === "always" /* AlwaysShow */ || uncategorizedVisibility === "auto" /* Auto */ && tasksByPrimary["uncategorised"].length > 0;
const doneVisibility = (_i = settings.doneVisibility) != null ? _i : "always" /* AlwaysShow */;
const showDoneColumn = doneVisibility === "always" /* AlwaysShow */ || doneVisibility === "auto" /* Auto */ && tasksByPrimary["done"].length > 0;
const allColumns = [];
if (showUncategorizedColumn) allColumns.push("uncategorised");
for (const column of columns) {
allColumns.push(column.id);
}
if (showDoneColumn) allColumns.push("done");
const flowDirection = (_j = settings.flowDirection) != null ? _j : "ltr" /* LeftToRight */;
const shouldReverse = flowDirection === "rtl" /* RightToLeft */ || flowDirection === "btt" /* BottomToTop */;
if (shouldReverse) {
allColumns.reverse();
}
const primaryAxis = allColumns.map((id) => {
let label = id;
let color = void 0;
const colDef = columns.find((c) => c.id === id);
if (id === "uncategorised") {
label = settings.uncategorizedColumnName || "Uncategorized";
} else if (id === "done") {
label = settings.doneColumnName || "Done";
} else {
if (colDef) {
label = colDef.label;
color = colDef.color;
}
}
return {
id,
label,
kind: "column",
collapsed: collapsedColumns.has(id),
meta: { color }
};
});
const groupSource = (_k = settings.groupSource) != null ? _k : { kind: "none" };
const groupBuckets = deriveGroupBuckets(
Object.values(tasksByPrimary).flat(),
groupSource,
settings.excludedTags,
(_l = settings.statusMarkerOrder) != null ? _l : "",
(_m = settings.doneStatusMarkers) != null ? _m : "",
(_n = settings.groupDirection) != null ? _n : "asc",
today
);
const assignTaskToBucket = createGroupAssigner(groupBuckets, groupSource, settings.excludedTags, today);
const secondaryAxis = groupBuckets.map((bucket) => ({
id: bucket.id,
label: bucket.label,
kind: "group",
collapsed: false,
meta: {
value: bucket.value,
source: bucket.source,
isDefault: bucket.isDefault
}
}));
const cells = {};
for (const primaryBucket of primaryAxis) {
const pId = primaryBucket.id;
cells[pId] = {};
const cellTasksByPrimary = (_o = tasksByPrimary[pId]) != null ? _o : [];
const cellTasksBySecondary = /* @__PURE__ */ new Map();
for (const task of cellTasksByPrimary) {
const sId = assignTaskToBucket(task);
if (sId === void 0) continue;
let bucketTasks = cellTasksBySecondary.get(sId);
if (!bucketTasks) {
bucketTasks = [];
cellTasksBySecondary.set(sId, bucketTasks);
}
bucketTasks.push(task);
}
for (const groupBucket of groupBuckets) {
const sId = groupBucket.id;
const cellTasks = (_p = cellTasksBySecondary.get(sId)) != null ? _p : [];
const orderedCellTasks = useManual ? computeDisplayOrder(cellTasks, (_q = manualOrder[sId]) == null ? void 0 : _q[pId]) : cellTasks;
cells[pId][sId] = {
primaryId: pId,
secondaryId: sId,
tasks: orderedCellTasks,
isEmpty: orderedCellTasks.length === 0
};
}
}
return {
primaryAxis,
secondaryAxis,
cells
};
}
function getBoardCell(matrix, primaryId, secondaryId) {
var _a5, _b3;
return (_b3 = (_a5 = matrix.cells[primaryId]) == null ? void 0 : _a5[secondaryId]) != null ? _b3 : {
primaryId,
secondaryId,
tasks: [],
isEmpty: true
};
}
function sortTasksByFile(tasks) {
tasks.sort(compareByFile);
}
function compareByFile(a, b) {
if (a.path === b.path) {
return a.rowIndex - b.rowIndex;
}
return a.path.localeCompare(b.path);
}
function sortTasksByProperty(tasks, key2, direction, statusMarkerOrder, doneStatusMarkers, propertySchema) {
tasks.sort((a, b) => {
const result = compareByProperty(a, b, key2, direction, { statusMarkerOrder, doneStatusMarkers, propertySchema });
return result !== 0 ? result : compareByFile(a, b);
});
}
function sortTasksByTaskName(tasks, direction) {
tasks.sort((a, b) => {
const result = a.content.trim().localeCompare(b.content.trim());
if (result !== 0) {
return direction === "desc" ? -result : result;
}
return compareByFile(a, b);
});
}
// src/ui/components/ColumnHeader.svelte
var import_obsidian3 = require("obsidian");
// src/ui/components/icon_button.svelte
var import_obsidian = require("obsidian");
var root = from_html(`<div></div>`);
var $$css = {
hash: "svelte-1igl4u1",
code: "div.svelte-1igl4u1 {width:24px;height:24px;display:flex;justify-content:center;align-items:center;border-radius:var(--radius-s);transition:background linear 100ms;cursor:pointer;background:transparent;border:none;box-shadow:none;padding:0;margin:0;}div.svelte-1igl4u1:hover {background-color:var(--background-modifier-hover);}div.svelte-1igl4u1:focus-visible {outline:2px solid var(--background-modifier-border-focus);outline-offset:2px;}"
};
function Icon_button($$anchor, $$props) {
if (new.target) return createClassComponent({ component: Icon_button, ...$$anchor });
const $$sanitized_props = legacy_rest_props($$props, ["children", "$$slots", "$$events", "$$legacy"]);
const $$restProps = legacy_rest_props($$sanitized_props, ["icon"]);
push($$props, false);
append_styles($$anchor, $$css);
let icon = prop($$props, "icon", 12);
let element2 = mutable_source();
function handleKeydown(e) {
var _a5;
if (e.key === "Enter" || e.key === " ") {
e.preventDefault();
(_a5 = get(element2)) == null ? void 0 : _a5.click();
}
}
legacy_pre_effect(() => (get(element2), import_obsidian.setIcon, deep_read_state(icon())), () => {
if (get(element2)) {
(0, import_obsidian.setIcon)(get(element2), icon());
}
});
legacy_pre_effect_reset();
var $$exports = {
get icon() {
return icon();
},
set icon($$value) {
icon($$value);
flushSync();
},
$set: update_legacy_props,
$on: ($$event_name, $$event_cb) => add_legacy_event_listener($$props, $$event_name, $$event_cb)
};
init();
var div = root();
attribute_effect(
div,
() => ({
class: "clickable-icon",
role: "button",
tabindex: "0",
...$$restProps
}),
void 0,
void 0,
void 0,
"svelte-1igl4u1"
);
bind_this(div, ($$value) => set(element2, $$value), () => get(element2));
event("click", div, function($$arg) {
bubble_event.call(this, $$props, $$arg);
});
event("keydown", div, handleKeydown);
append($$anchor, div);
return pop($$exports);
}
// src/ui/selection/task_selection_store.ts
var taskSelectionStore = writable(/* @__PURE__ */ new Map());
function toggleTaskSelection(taskId) {
taskSelectionStore.update((map2) => {
const current = map2.get(taskId) || false;
map2.set(taskId, !current);
return new Map(map2);
});
}
function isTaskSelected(taskId, selectionMap) {
return selectionMap.get(taskId) || false;
}
function getSelectedTaskCount(taskIds, selectionMap) {
return taskIds.filter((id) => selectionMap.get(id) || false).length;
}
function clearColumnSelections(columnTaskIds) {
taskSelectionStore.update((map2) => {
for (const id of columnTaskIds) {
map2.delete(id);
}
return new Map(map2);
});
}
function clearTaskIdSelections(taskIds) {
taskSelectionStore.update((map2) => {
for (const id of taskIds) {
map2.delete(id);
}
return new Map(map2);
});
}
// src/ui/selection/selection_mode_store.ts
var selectionModeStore = writable(/* @__PURE__ */ new Map());
function toggleSelectionMode(column) {
selectionModeStore.update((map2) => {
const current = map2.get(column) || false;
const newMode = !current;
map2.set(column, newMode);
if (current && !newMode) {
taskSelectionStore.set(/* @__PURE__ */ new Map());
}
return new Map(map2);
});
}
function isInSelectionMode(column, modeMap) {
return modeMap.get(column) || false;
}
// src/ui/components/icon.svelte
var import_obsidian2 = require("obsidian");
var root2 = from_html(`<span class="icon svelte-1cj3qcy"></span>`);
var $$css2 = {
hash: "svelte-1cj3qcy",
code: ".icon.svelte-1cj3qcy {display:inline-flex;justify-content:center;align-items:center;flex-shrink:0;}.icon.svelte-1cj3qcy svg {width:100%;height:100%;}"
};
function Icon($$anchor, $$props) {
if (new.target) return createClassComponent({ component: Icon, ...$$anchor });
push($$props, false);
append_styles($$anchor, $$css2);
let name = prop($$props, "name", 12);
let size = prop(
$$props,
"size",
12,
16
// Default icon size in pixels
);
let opacity = prop($$props, "opacity", 12, 1);
let ariaLabel = prop($$props, "ariaLabel", 12, void 0);
let element2 = mutable_source();
onMount(() => {
if (get(element2)) {
(0, import_obsidian2.setIcon)(get(element2), name());
}
});
legacy_pre_effect(() => (get(element2), deep_read_state(name()), import_obsidian2.setIcon), () => {
if (get(element2) && name()) {
(0, import_obsidian2.setIcon)(get(element2), name());
}
});
legacy_pre_effect_reset();
var $$exports = {
get name() {
return name();
},
set name($$value) {
name($$value);
flushSync();
},
get size() {
return size();
},
set size($$value) {
size($$value);
flushSync();
},
get opacity() {
return opacity();
},
set opacity($$value) {
opacity($$value);
flushSync();
},
get ariaLabel() {
return ariaLabel();
},
set ariaLabel($$value) {
ariaLabel($$value);
flushSync();
},
$set: update_legacy_props,
$on: ($$event_name, $$event_cb) => add_legacy_event_listener($$props, $$event_name, $$event_cb)
};
init();
var span = root2();
let styles;
bind_this(span, ($$value) => set(element2, $$value), () => get(element2));
template_effect(() => {
var _a5, _b3;
set_attribute2(span, "aria-label", ariaLabel());
set_attribute2(span, "role", ariaLabel() ? "img" : void 0);
styles = set_style(span, "", styles, {
width: `${(_a5 = size()) != null ? _a5 : ""}px`,
height: `${(_b3 = size()) != null ? _b3 : ""}px`,
opacity: opacity()
});
});
append($$anchor, span);
return pop($$exports);
}
// src/ui/components/task_status_display.ts
function shouldRenderStatusAsText(status) {
return status.length > 1 || /\p{Extended_Pictographic}/u.test(status);
}
// src/ui/components/TaskStatusMarker.svelte
var root3 = from_html(`<span class="status-text-marker svelte-48e5ji"> </span>`);
var root_1 = from_html(`<input type="checkbox" class="task-list-item-checkbox source-status-checkbox svelte-48e5ji" tabindex="-1" aria-hidden="true" style="pointer-events: none;"/>`);
var root_2 = from_html(`<span class="task-status-marker markdown-rendered markdown-preview-view markdown-source-view mod-cm6 svelte-48e5ji"><span><!></span></span>`);
var $$css3 = {
hash: "svelte-48e5ji",
code: ".task-status-marker.svelte-48e5ji {display:inline-flex !important;align-items:center;justify-content:center;width:var(--task-status-marker-size);height:var(--task-status-marker-size);min-width:var(--task-status-marker-size);min-height:var(--task-status-marker-size);overflow:visible;margin:0 !important;padding:0 !important;text-indent:0 !important;line-height:1 !important;list-style:none !important;vertical-align:middle;}.task-status-marker.svelte-48e5ji .task-list-item.HyperMD-task-line:where(.svelte-48e5ji) {display:contents !important;}.task-status-marker.svelte-48e5ji .source-status-checkbox:where(.svelte-48e5ji),\n.task-status-marker.svelte-48e5ji .status-text-marker:where(.svelte-48e5ji) {display:inline-flex !important;align-items:center !important;justify-content:center !important;box-sizing:border-box;width:var(--task-status-marker-size) !important;height:var(--task-status-marker-size) !important;min-width:var(--task-status-marker-size) !important;min-height:var(--task-status-marker-size) !important;margin:0 !important;padding:0 !important;pointer-events:none;text-indent:0 !important;line-height:1 !important;vertical-align:middle !important;}.task-status-marker.svelte-48e5ji .status-text-marker:where(.svelte-48e5ji) {font-size:calc(var(--task-status-marker-size) - 3px);}.task-status-marker.svelte-48e5ji .source-status-checkbox:where(.svelte-48e5ji) {position:relative !important;top:0 !important;left:0 !important;transform:none !important;margin:0 !important;padding:0 !important;appearance:none !important;-webkit-appearance:none !important;box-sizing:border-box !important;}"
};
function TaskStatusMarker($$anchor, $$props) {
if (new.target) return createClassComponent({ component: TaskStatusMarker, ...$$anchor });
push($$props, false);
append_styles($$anchor, $$css3);
const isCustom = mutable_source();
const markerSize = mutable_source();
const resolvedIsChecked = mutable_source();
let status = prop($$props, "status", 12);
let isDone = prop($$props, "isDone", 12, false);
let isChecked = prop($$props, "isChecked", 12, void 0);
let size = prop($$props, "size", 12, 16);
legacy_pre_effect(() => deep_read_state(status()), () => {
set(isCustom, status() !== " ");
});
legacy_pre_effect(() => deep_read_state(size()), () => {
set(markerSize, `${size()}px`);
});
legacy_pre_effect(
() => (deep_read_state(isChecked()), get(isCustom), deep_read_state(isDone())),
() => {
var _a5;
set(resolvedIsChecked, (_a5 = isChecked()) != null ? _a5 : get(isCustom) || isDone());
}
);
legacy_pre_effect_reset();
var $$exports = {
get status() {
return status();
},
set status($$value) {
status($$value);
flushSync();
},
get isDone() {
return isDone();
},
set isDone($$value) {
isDone($$value);
flushSync();
},
get isChecked() {
return isChecked();
},
set isChecked($$value) {
isChecked($$value);
flushSync();
},
get size() {
return size();
},
set size($$value) {
size($$value);
flushSync();
},
$set: update_legacy_props,
$on: ($$event_name, $$event_cb) => add_legacy_event_listener($$props, $$event_name, $$event_cb)
};
init();
var fragment = comment();
var node = first_child(fragment);
{
var consequent_1 = ($$anchor2) => {
var span = root_2();
let styles;
var span_1 = child(span);
let classes;
var node_1 = child(span_1);
{
var consequent = ($$anchor3) => {
var span_2 = root3();
var text2 = child(span_2, true);
reset(span_2);
template_effect(() => set_text(text2, status()));
append($$anchor3, span_2);
};
var d = user_derived(() => (deep_read_state(shouldRenderStatusAsText), deep_read_state(status()), untrack(() => shouldRenderStatusAsText(status()))));
var alternate = ($$anchor3) => {
var input = root_1();
remove_input_defaults(input);
template_effect(() => {
set_attribute2(input, "data-task", status());
set_checked(input, get(resolvedIsChecked));
});
append($$anchor3, input);
};
if_block(node_1, ($$render) => {
if (get(d)) $$render(consequent);
else $$render(alternate, -1);
});
}
reset(span_1);
reset(span);
template_effect(() => {
styles = set_style(span, "", styles, { "--task-status-marker-size": get(markerSize) });
classes = set_class(span_1, 1, "task-list-item HyperMD-task-line svelte-48e5ji", null, classes, { "is-checked": get(resolvedIsChecked) });
set_attribute2(span_1, "data-task", status());
});
append($$anchor2, span);
};
var alternate_1 = ($$anchor2) => {
{
let $0 = derived_safe_equal(() => isDone() ? "lucide-check-square" : "lucide-square");
let $1 = derived_safe_equal(() => isDone() ? 1 : 0.5);
Icon($$anchor2, {
get name() {
return get($0);
},
get size() {
return size();
},
get opacity() {
return get($1);
}
});
}
};
if_block(node, ($$render) => {
if (get(isCustom)) $$render(consequent_1);
else $$render(alternate_1, -1);
});
}
append($$anchor, fragment);
return pop($$exports);
}
// src/ui/components/ColumnHeader.svelte
var root4 = from_html(`<span class="task-count svelte-1q9xxoc" aria-live="polite"> </span>`);
var root_12 = from_html(`<div class="column-match-tags svelte-1q9xxoc"> </div>`);
var root_22 = from_html(`<div class="column-match-status svelte-1q9xxoc"><span class="column-match-status-label svelte-1q9xxoc">Status</span> <span class="column-status-preview svelte-1q9xxoc"><!></span></div>`);
var root_3 = from_html(`<span class="column-priority-icon svelte-1q9xxoc" aria-hidden="true"> </span>`);
var root_4 = from_html(`<div class="column-match-priority svelte-1q9xxoc"><span class="column-match-status-label svelte-1q9xxoc">Priority</span> <span class="column-priority-preview svelte-1q9xxoc"><!> <span> </span></span></div>`);
var root_5 = from_html(`<div class="column-meta svelte-1q9xxoc"><div class="column-meta-line svelte-1q9xxoc"><!> <!> <!> <span class="task-count svelte-1q9xxoc" aria-live="polite"> </span> <div class="mode-toggle svelte-1q9xxoc" role="toolbar" aria-label="Column interaction mode"><button aria-label="Done mode: click tasks to mark complete">Done</button> <button aria-label="Select mode: click tasks to select for bulk actions">Select</button></div></div></div>`);
var root_6 = from_html(`<div class="selection-info svelte-1q9xxoc" aria-live="polite"> </div>`);
var root_7 = from_html(`<div><div class="header svelte-1q9xxoc"><span class="collapse-btn svelte-1q9xxoc" role="button" tabindex="0"> </span> <div class="column-title-group svelte-1q9xxoc"><h2 class="svelte-1q9xxoc"> </h2></div> <!> <div class="header-menu svelte-1q9xxoc"><!></div></div> <!> <!></div>`);
var $$css4 = {
hash: "svelte-1q9xxoc",
code: '.column-header.svelte-1q9xxoc {width:100%;--header-accent: var(--column-color, var(--background-modifier-border-hover));--column-header-x-padding: var(--column-header-x-padding-override, var(--size-4-4));--column-header-y-padding: var(--column-header-y-padding-override, var(--size-4-4));display:flex;flex-direction:column;gap:var(--size-2-3);}.column-header.svelte-1q9xxoc::before {content:"";display:block;width:calc(100% + 2 * var(--column-header-x-padding));height:12px;margin:calc(-1 * var(--column-header-y-padding)) calc(-1 * var(--column-header-x-padding)) 0;border-radius:2px;background:var(--header-accent);box-shadow:inset 0 0 0 1px color-mix(in srgb, var(--text-normal) 10%, transparent);flex:0 0 auto;}.column-header.row-header.svelte-1q9xxoc {position:relative;display:flex;align-items:stretch;margin-bottom:0;}.column-header.row-header.svelte-1q9xxoc::before {position:absolute;top:calc(-1 * var(--column-header-y-padding));bottom:calc(-1 * var(--column-header-y-padding));left:calc(-1 * var(--column-header-x-padding));width:12px;height:auto;margin:0;z-index:3;}.column-header.row-header.svelte-1q9xxoc .header:where(.svelte-1q9xxoc) {margin:calc(-1 * var(--size-4-2)) calc(-1 * var(--size-4-3)) calc(-1 * var(--size-2-2));padding:var(--size-4-2) var(--size-4-3) var(--size-2-2);width:calc(100% + 2 * var(--size-4-3));box-sizing:border-box;position:sticky;top:var(--header-height, 0px);z-index:2;background:color-mix(in srgb, var(--background-secondary) 72%, var(--background-primary));}.column-header.row-header.svelte-1q9xxoc .column-meta:where(.svelte-1q9xxoc),\n.column-header.row-header.svelte-1q9xxoc .selection-info:where(.svelte-1q9xxoc) {padding-left:var(--size-4-3);box-sizing:border-box;}.column-header.row-header.svelte-1q9xxoc .column-meta:where(.svelte-1q9xxoc) {margin-top:var(--size-2-2);}.column-header.row-header.svelte-1q9xxoc .column-meta:where(.svelte-1q9xxoc) .column-meta-line:where(.svelte-1q9xxoc) {justify-content:flex-start;flex-wrap:wrap;gap:var(--size-2-2) var(--size-4-2);}.column-header.row-header.svelte-1q9xxoc .column-meta:where(.svelte-1q9xxoc) .column-meta-line:where(.svelte-1q9xxoc) .column-match-tags:where(.svelte-1q9xxoc),\n.column-header.row-header.svelte-1q9xxoc .column-meta:where(.svelte-1q9xxoc) .column-meta-line:where(.svelte-1q9xxoc) .column-match-status:where(.svelte-1q9xxoc),\n.column-header.row-header.svelte-1q9xxoc .column-meta:where(.svelte-1q9xxoc) .column-meta-line:where(.svelte-1q9xxoc) .column-match-priority:where(.svelte-1q9xxoc) {order:1;flex:0 0 100%;}.column-header.row-header.svelte-1q9xxoc .column-meta:where(.svelte-1q9xxoc) .column-meta-line:where(.svelte-1q9xxoc) .task-count:where(.svelte-1q9xxoc) {order:2;flex:0 0 100%;margin-left:0;}.column-header.row-header.svelte-1q9xxoc .column-meta:where(.svelte-1q9xxoc) .column-meta-line:where(.svelte-1q9xxoc) .mode-toggle:where(.svelte-1q9xxoc) {order:3;flex:0 0 auto;}.column-header.collapsed.svelte-1q9xxoc {position:sticky;top:0;align-self:flex-start;z-index:1;}.column-header.collapsed.svelte-1q9xxoc .header:where(.svelte-1q9xxoc) {flex-direction:column;align-items:center;min-height:unset;gap:var(--size-4-2);}.column-header.collapsed.svelte-1q9xxoc .header:where(.svelte-1q9xxoc) .column-title-group:where(.svelte-1q9xxoc) {order:2;}.column-header.collapsed.svelte-1q9xxoc .header:where(.svelte-1q9xxoc) .column-title-group:where(.svelte-1q9xxoc) h2:where(.svelte-1q9xxoc) {writing-mode:vertical-rl;text-orientation:mixed;white-space:nowrap;overflow:visible;text-overflow:unset;flex:0 0 auto;line-height:normal;}.column-header.collapsed.svelte-1q9xxoc .header:where(.svelte-1q9xxoc) .task-count:where(.svelte-1q9xxoc) {order:3;writing-mode:horizontal-tb;align-self:center;line-height:normal;}.column-header.collapsed.svelte-1q9xxoc .header:where(.svelte-1q9xxoc) .header-menu:where(.svelte-1q9xxoc) {display:flex;margin-left:0;order:4;}.column-header.collapsed.svelte-1q9xxoc .header:where(.svelte-1q9xxoc) .header-menu button {width:20px;height:20px;}.column-header.collapsed.svelte-1q9xxoc .header:where(.svelte-1q9xxoc) .collapse-btn:where(.svelte-1q9xxoc) {order:1;}.column-header.vertical-collapsed.row-header.svelte-1q9xxoc {margin-bottom:0;}.column-header.vertical-collapsed.row-header.svelte-1q9xxoc .header-menu:where(.svelte-1q9xxoc) {display:flex;}.header.svelte-1q9xxoc {display:flex;align-items:center;min-height:22px;width:100%;flex-shrink:0;gap:var(--size-4-2);}.header.svelte-1q9xxoc .column-title-group:where(.svelte-1q9xxoc) {min-width:0;display:flex;flex-direction:column;align-items:flex-start;gap:2px;flex:1 1 auto;}.header.svelte-1q9xxoc h2:where(.svelte-1q9xxoc) {font-size:var(--font-ui-medium);font-weight:var(--font-bold);margin:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;line-height:1.2;position:sticky;left:calc(var(--sticky-left-offset, 0px) + var(--column-header-x-padding, var(--size-4-4)));max-width:100%;}.header.svelte-1q9xxoc .task-count:where(.svelte-1q9xxoc) {font-size:var(--font-ui-small);color:var(--text-muted);white-space:nowrap;align-self:flex-start;line-height:28px;}.header.svelte-1q9xxoc .header-menu:where(.svelte-1q9xxoc) {margin-left:auto;flex-shrink:0;display:flex;align-items:center;gap:var(--size-2-1);height:24px;}.header.svelte-1q9xxoc .collapse-btn:where(.svelte-1q9xxoc) {background:transparent;border:none;box-shadow:none;cursor:pointer;color:var(--text-muted);padding:0;width:14px;height:24px;display:flex;align-items:center;justify-content:center;font-size:10px;line-height:1;flex-shrink:0;transition:color 0.15s ease;}.header.svelte-1q9xxoc .collapse-btn:where(.svelte-1q9xxoc):hover {color:var(--text-normal);background:transparent;}.header.svelte-1q9xxoc .collapse-btn:where(.svelte-1q9xxoc):focus-visible {outline:2px solid var(--background-modifier-border-focus);outline-offset:2px;}.mode-toggle.svelte-1q9xxoc {display:flex;align-items:center;background:var(--background-modifier-form-field, var(--background-secondary));border-radius:var(--radius-s);padding:2px;gap:0;width:fit-content;max-width:100%;flex:0 0 auto;}.mode-toggle.svelte-1q9xxoc .mode-btn:where(.svelte-1q9xxoc) {font-size:var(--font-ui-smaller);padding:1px 5px;min-width:0;width:auto;border:none;background:transparent;color:var(--text-muted);border-radius:calc(var(--radius-s) - 2px);cursor:pointer;transition:background 0.15s ease, color 0.15s ease;white-space:nowrap;box-shadow:none;line-height:1.2;}.mode-toggle.svelte-1q9xxoc .mode-btn:where(.svelte-1q9xxoc):hover {background:transparent;color:var(--text-normal);box-shadow:none;}.mode-toggle.svelte-1q9xxoc .mode-btn.active:where(.svelte-1q9xxoc) {background:var(--background-primary);color:var(--text-normal);box-shadow:var(--input-shadow);font-weight:var(--font-medium);}.mode-toggle.svelte-1q9xxoc .mode-btn:where(.svelte-1q9xxoc):focus-visible {outline:2px solid var(--background-modifier-border-focus);outline-offset:1px;}.column-meta.svelte-1q9xxoc {display:flex;flex-direction:column;gap:var(--size-2-1);width:100%;align-items:flex-start;}.column-meta.svelte-1q9xxoc .column-meta-line:where(.svelte-1q9xxoc) {display:flex;align-items:center;justify-content:space-between;width:100%;gap:var(--size-2-3);min-width:0;}.column-meta.svelte-1q9xxoc .column-meta-line:where(.svelte-1q9xxoc) .task-count:where(.svelte-1q9xxoc) {font-size:var(--font-ui-small);color:var(--text-muted);white-space:nowrap;line-height:1.3;margin-left:auto;flex:0 0 auto;}.column-match-tags.svelte-1q9xxoc,\n.column-match-status.svelte-1q9xxoc,\n.column-match-priority.svelte-1q9xxoc {font-size:var(--font-ui-small);color:var(--text-muted);overflow:hidden;text-overflow:ellipsis;white-space:nowrap;line-height:1.3;min-width:0;flex:1 1 auto;}.column-match-status.svelte-1q9xxoc,\n.column-match-priority.svelte-1q9xxoc {display:inline-flex;align-items:center;gap:var(--size-2-2);flex:0 0 auto;overflow:visible;}.column-match-status-label.svelte-1q9xxoc {font-weight:var(--font-medium);}.column-priority-preview.svelte-1q9xxoc {display:inline-flex;align-items:center;gap:3px;min-width:0;}.column-priority-icon.svelte-1q9xxoc {line-height:1;}.column-status-preview.svelte-1q9xxoc {display:inline-flex !important;align-items:center !important;justify-content:center !important;width:18px !important;height:18px !important;min-width:18px !important;min-height:18px !important;max-width:18px !important;max-height:18px !important;margin:0 !important;padding:0 !important;text-indent:0 !important;line-height:1 !important;list-style:none !important;color:var(--text-normal);vertical-align:middle;}.selection-info.svelte-1q9xxoc {font-size:var(--font-ui-smaller);color:var(--text-muted);margin-top:var(--size-2-1);}'
};
function ColumnHeader($$anchor, $$props) {
if (new.target) return createClassComponent({ component: ColumnHeader, ...$$anchor });
push($$props, false);
append_styles($$anchor, $$css4);
const $columnTagTableStore = () => store_get(columnTagTableStore(), "$columnTagTableStore", $$stores);
const $columnColourTableStore = () => store_get(columnColourTableStore(), "$columnColourTableStore", $$stores);
const $columnMatchTagTableStore = () => store_get(columnMatchTagTableStore(), "$columnMatchTagTableStore", $$stores);
const $columnSubtitleTableStore = () => store_get(columnSubtitleTableStore(), "$columnSubtitleTableStore", $$stores);
const $selectionModeStore = () => store_get(selectionModeStore, "$selectionModeStore", $$stores);
const $taskSelectionStore = () => store_get(taskSelectionStore, "$taskSelectionStore", $$stores);
const [$$stores, $$cleanup] = setup_stores();
const columnTitle = mutable_source();
const columnColor = mutable_source();
const columnMatchTags = mutable_source();
const columnStatusMarker = mutable_source();
const columnStatusLabel = mutable_source();
const columnPriorityLabel = mutable_source();
const columnPriorityIcon = mutable_source();
const taskCountLabel = mutable_source();
const collapseIcon = mutable_source();
const isHorizontalCollapsed = mutable_source();
const isVerticalCollapsed = mutable_source();
const displayTaskCount = mutable_source();
const showColumnMatchTags = mutable_source();
const showColumnStatus = mutable_source();
const showColumnPriority = mutable_source();
const isSelectMode = mutable_source();
const columnTaskIds = mutable_source();
const selectedCount = mutable_source();
const selectedIds = mutable_source();
const showContextMenu = mutable_source();
let column = prop($$props, "column", 12);
let tasks = prop($$props, "tasks", 12);
let taskActions = prop($$props, "taskActions", 12);
let columnTagTableStore = prop($$props, "columnTagTableStore", 12);
let columnColourTableStore = prop($$props, "columnColourTableStore", 12);
let columnMatchTagTableStore = prop($$props, "columnMatchTagTableStore", 12);
let columnSubtitleTableStore = prop($$props, "columnSubtitleTableStore", 12);
let isVerticalFlow = prop($$props, "isVerticalFlow", 12, false);
let isCollapsed = prop($$props, "isCollapsed", 12, false);
let onToggleCollapse = prop($$props, "onToggleCollapse", 12);
let uncategorizedColumnName = prop($$props, "uncategorizedColumnName", 12, void 0);
let doneColumnName = prop($$props, "doneColumnName", 12, void 0);
let columnSubtitle = mutable_source();
function getColumnTitle(col, columnTagTable) {
switch (col) {
case "done":
case "uncategorised":
return resolveDefaultColumnName(col, uncategorizedColumnName(), doneColumnName());
default:
return columnTagTable[col];
}
}
function showMenu(e) {
const menu = new import_obsidian3.Menu();
if (get(isSelectMode) && get(selectedCount) > 0) {
if (column() !== "done") {
menu.addItem((i) => {
i.setTitle(`Move ${get(selectedCount)} selected to ${resolveDefaultColumnName("done", uncategorizedColumnName(), doneColumnName())}`).onClick(async () => {
await taskActions().moveTasksToColumn(get(selectedIds), "done");
clearColumnSelections(get(columnTaskIds));
});
});
}
for (const [tag2, label] of Object.entries($columnTagTableStore())) {
const tagAsColumn = tag2;
if (tagAsColumn === column()) continue;
menu.addItem((i) => {
i.setTitle(`Move ${get(selectedCount)} selected to ${label}`).onClick(async () => {
await taskActions().moveTasksToColumn(get(selectedIds), tagAsColumn);
clearColumnSelections(get(columnTaskIds));
});
});
}
menu.addSeparator();
const selectedTasks = get(selectedIds).map((id) => tasks().find((t) => t.id === id)).filter(Boolean);
const allCancelled = selectedTasks.length > 0 && selectedTasks.every((t) => t.isCancelled);
if (allCancelled) {
menu.addItem((i) => {
i.setTitle(`Restore ${get(selectedCount)} selected`).onClick(async () => {
await taskActions().restoreTasks(get(selectedIds));
clearColumnSelections(get(columnTaskIds));
});
});
} else {
menu.addItem((i) => {
i.setTitle(`Cancel ${get(selectedCount)} selected`).onClick(async () => {
await taskActions().cancelTasks(get(selectedIds));
clearColumnSelections(get(columnTaskIds));
});
});
}
menu.addSeparator();
menu.addItem((i) => {
i.setTitle(`Archive ${get(selectedCount)} selected`).onClick(async () => {
await taskActions().archiveTasks(get(selectedIds));
clearColumnSelections(get(columnTaskIds));
});
});
}
if (column() === "done") {
menu.addItem((i) => {
i.setTitle(`Archive all`).onClick(() => taskActions().archiveTasks(tasks().map(({ id }) => id)));
});
}
menu.showAtMouseEvent(e);
}
legacy_pre_effect(
() => (deep_read_state(uncategorizedColumnName()), deep_read_state(doneColumnName()), deep_read_state(column()), $columnTagTableStore()),
() => {
set(columnTitle, (() => {
void uncategorizedColumnName();
void doneColumnName();
return getColumnTitle(column(), $columnTagTableStore());
})());
}
);
legacy_pre_effect(
() => (isColumnTag, deep_read_state(column()), deep_read_state(columnTagTableStore()), $columnColourTableStore()),
() => {
set(columnColor, isColumnTag(column(), columnTagTableStore()) ? $columnColourTableStore()[column()] : void 0);
}
);
legacy_pre_effect(
() => (isColumnTag, deep_read_state(column()), deep_read_state(columnTagTableStore()), $columnMatchTagTableStore()),
() => {
var _a5;
set(columnMatchTags, isColumnTag(column(), columnTagTableStore()) ? (_a5 = $columnMatchTagTableStore()[column()]) != null ? _a5 : [] : []);
}
);
legacy_pre_effect(
() => (isColumnTag, deep_read_state(column()), deep_read_state(columnTagTableStore()), $columnSubtitleTableStore()),
() => {
set(columnSubtitle, isColumnTag(column(), columnTagTableStore()) ? $columnSubtitleTableStore()[column()] : void 0);
}
);
legacy_pre_effect(() => get(columnSubtitle), () => {
var _a5;
set(columnStatusMarker, ((_a5 = get(columnSubtitle)) == null ? void 0 : _a5.kind) === "status" ? get(columnSubtitle).value : void 0);
});
legacy_pre_effect(() => get(columnSubtitle), () => {
var _a5;
set(columnStatusLabel, ((_a5 = get(columnSubtitle)) == null ? void 0 : _a5.kind) === "status" ? get(columnSubtitle).label : "");
});
legacy_pre_effect(() => get(columnSubtitle), () => {
var _a5;
set(columnPriorityLabel, ((_a5 = get(columnSubtitle)) == null ? void 0 : _a5.kind) === "priority" ? get(columnSubtitle).label : "");
});
legacy_pre_effect(() => get(columnSubtitle), () => {
var _a5;
set(columnPriorityIcon, ((_a5 = get(columnSubtitle)) == null ? void 0 : _a5.kind) === "priority" ? get(columnSubtitle).icon : void 0);
});
legacy_pre_effect(() => deep_read_state(tasks()), () => {
set(taskCountLabel, tasks().length === 1 ? "1 task" : `${tasks().length} tasks`);
});
legacy_pre_effect(() => deep_read_state(isCollapsed()), () => {
set(collapseIcon, isCollapsed() ? "\u25B6" : "\u25BC");
});
legacy_pre_effect(
() => (deep_read_state(isCollapsed()), deep_read_state(isVerticalFlow())),
() => {
set(isHorizontalCollapsed, isCollapsed() && !isVerticalFlow());
}
);
legacy_pre_effect(
() => (deep_read_state(isCollapsed()), deep_read_state(isVerticalFlow())),
() => {
set(isVerticalCollapsed, isCollapsed() && isVerticalFlow());
}
);
legacy_pre_effect(
() => (deep_read_state(isCollapsed()), deep_read_state(tasks()), get(taskCountLabel)),
() => {
set(displayTaskCount, isCollapsed() ? `${tasks().length}` : get(taskCountLabel));
}
);
legacy_pre_effect(() => (get(columnMatchTags), deep_read_state(isCollapsed())), () => {
set(showColumnMatchTags, get(columnMatchTags).length > 0 && !isCollapsed());
});
legacy_pre_effect(() => (get(columnStatusMarker), deep_read_state(isCollapsed())), () => {
set(showColumnStatus, get(columnStatusMarker) !== void 0 && !isCollapsed());
});
legacy_pre_effect(() => (get(columnSubtitle), deep_read_state(isCollapsed())), () => {
var _a5;
set(showColumnPriority, ((_a5 = get(columnSubtitle)) == null ? void 0 : _a5.kind) === "priority" && !isCollapsed());
});
legacy_pre_effect(
() => (isInSelectionMode, deep_read_state(column()), $selectionModeStore()),
() => {
set(isSelectMode, isInSelectionMode(column(), $selectionModeStore()));
}
);
legacy_pre_effect(() => deep_read_state(tasks()), () => {
set(columnTaskIds, tasks().map((t) => t.id));
});
legacy_pre_effect(
() => (getSelectedTaskCount, get(columnTaskIds), $taskSelectionStore()),
() => {
set(selectedCount, getSelectedTaskCount(get(columnTaskIds), $taskSelectionStore()));
}
);
legacy_pre_effect(() => (get(columnTaskIds), isTaskSelected, $taskSelectionStore()), () => {
set(selectedIds, get(columnTaskIds).filter((id) => isTaskSelected(id, $taskSelectionStore())));
});
legacy_pre_effect(
() => (deep_read_state(column()), get(isSelectMode), get(selectedCount)),
() => {
set(showContextMenu, column() === "done" || get(isSelectMode) && get(selectedCount) > 0);
}
);
legacy_pre_effect_reset();
var $$exports = {
get column() {
return column();
},
set column($$value) {
column($$value);
flushSync();
},
get tasks() {
return tasks();
},
set tasks($$value) {
tasks($$value);
flushSync();
},
get taskActions() {
return taskActions();
},
set taskActions($$value) {
taskActions($$value);
flushSync();
},
get columnTagTableStore() {
return columnTagTableStore();
},
set columnTagTableStore($$value) {
columnTagTableStore($$value);
flushSync();
},
get columnColourTableStore() {
return columnColourTableStore();
},
set columnColourTableStore($$value) {
columnColourTableStore($$value);
flushSync();
},
get columnMatchTagTableStore() {
return columnMatchTagTableStore();
},
set columnMatchTagTableStore($$value) {
columnMatchTagTableStore($$value);
flushSync();
},
get columnSubtitleTableStore() {
return columnSubtitleTableStore();
},
set columnSubtitleTableStore($$value) {
columnSubtitleTableStore($$value);
flushSync();
},
get isVerticalFlow() {
return isVerticalFlow();
},
set isVerticalFlow($$value) {
isVerticalFlow($$value);
flushSync();
},
get isCollapsed() {
return isCollapsed();
},
set isCollapsed($$value) {
isCollapsed($$value);
flushSync();
},
get onToggleCollapse() {
return onToggleCollapse();
},
set onToggleCollapse($$value) {
onToggleCollapse($$value);
flushSync();
},
get uncategorizedColumnName() {
return uncategorizedColumnName();
},
set uncategorizedColumnName($$value) {
uncategorizedColumnName($$value);
flushSync();
},
get doneColumnName() {
return doneColumnName();
},
set doneColumnName($$value) {
doneColumnName($$value);
flushSync();
},
$set: update_legacy_props,
$on: ($$event_name, $$event_cb) => add_legacy_event_listener($$props, $$event_name, $$event_cb)
};
init();
var div = root_7();
let classes;
let styles;
var div_1 = child(div);
var span = child(div_1);
var text2 = child(span, true);
reset(span);
var div_2 = sibling(span, 2);
var h2 = child(div_2);
var text_1 = child(h2, true);
reset(h2);
reset(div_2);
var node = sibling(div_2, 2);
{
var consequent = ($$anchor2) => {
var span_1 = root4();
var text_2 = child(span_1, true);
reset(span_1);
template_effect(() => {
set_attribute2(span_1, "aria-label", get(taskCountLabel));
set_text(text_2, get(displayTaskCount));
});
append($$anchor2, span_1);
};
if_block(node, ($$render) => {
if (isCollapsed()) $$render(consequent);
});
}
var div_3 = sibling(node, 2);
var node_1 = child(div_3);
{
var consequent_1 = ($$anchor2) => {
Icon_button($$anchor2, {
icon: "lucide-more-vertical",
get "aria-label"() {
var _a5;
return `Column options for ${(_a5 = get(columnTitle)) != null ? _a5 : ""}`;
},
$$events: { click: showMenu }
});
};
if_block(node_1, ($$render) => {
if (get(showContextMenu)) $$render(consequent_1);
});
}
reset(div_3);
reset(div_1);
var node_2 = sibling(div_1, 2);
{
var consequent_6 = ($$anchor2) => {
var div_4 = root_5();
var div_5 = child(div_4);
var node_3 = child(div_5);
{
var consequent_2 = ($$anchor3) => {
var div_6 = root_12();
var text_3 = child(div_6, true);
reset(div_6);
template_effect(
($0, $1) => {
set_attribute2(div_6, "title", $0);
set_text(text_3, $1);
},
[
() => (get(columnMatchTags), untrack(() => get(columnMatchTags).map((tag2) => `#${tag2}`).join(" "))),
() => (get(columnMatchTags), untrack(() => get(columnMatchTags).map((tag2) => `#${tag2}`).join(" ")))
]
);
append($$anchor3, div_6);
};
if_block(node_3, ($$render) => {
if (get(showColumnMatchTags)) $$render(consequent_2);
});
}
var node_4 = sibling(node_3, 2);
{
var consequent_3 = ($$anchor3) => {
var div_7 = root_22();
var span_2 = sibling(child(div_7), 2);
var node_5 = child(span_2);
{
let $0 = derived_safe_equal(() => {
var _a5;
return (_a5 = get(columnStatusMarker)) != null ? _a5 : " ";
});
TaskStatusMarker(node_5, {
get status() {
return get($0);
},
size: 18
});
}
reset(span_2);
reset(div_7);
template_effect(() => {
var _a5, _b3;
set_attribute2(div_7, "title", `Status: ${(_a5 = get(columnStatusLabel)) != null ? _a5 : ""}`);
set_attribute2(span_2, "aria-label", `Status: ${(_b3 = get(columnStatusLabel)) != null ? _b3 : ""}`);
});
append($$anchor3, div_7);
};
if_block(node_4, ($$render) => {
if (get(showColumnStatus)) $$render(consequent_3);
});
}
var node_6 = sibling(node_4, 2);
{
var consequent_5 = ($$anchor3) => {
var div_8 = root_4();
var span_3 = sibling(child(div_8), 2);
var node_7 = child(span_3);
{
var consequent_4 = ($$anchor4) => {
var span_4 = root_3();
var text_4 = child(span_4, true);
reset(span_4);
template_effect(() => set_text(text_4, get(columnPriorityIcon)));
append($$anchor4, span_4);
};
if_block(node_7, ($$render) => {
if (get(columnPriorityIcon)) $$render(consequent_4);
});
}
var span_5 = sibling(node_7, 2);
var text_5 = child(span_5, true);
reset(span_5);
reset(span_3);
reset(div_8);
template_effect(() => {
var _a5, _b3;
set_attribute2(div_8, "title", `Priority: ${(_a5 = get(columnPriorityLabel)) != null ? _a5 : ""}`);
set_attribute2(span_3, "aria-label", `Priority: ${(_b3 = get(columnPriorityLabel)) != null ? _b3 : ""}`);
set_text(text_5, get(columnPriorityLabel));
});
append($$anchor3, div_8);
};
if_block(node_6, ($$render) => {
if (get(showColumnPriority)) $$render(consequent_5);
});
}
var span_6 = sibling(node_6, 2);
var text_6 = child(span_6, true);
reset(span_6);
var div_9 = sibling(span_6, 2);
var button = child(div_9);
let classes_1;
var button_1 = sibling(button, 2);
let classes_2;
reset(div_9);
reset(div_5);
reset(div_4);
template_effect(() => {
set_attribute2(span_6, "aria-label", get(taskCountLabel));
set_text(text_6, get(displayTaskCount));
classes_1 = set_class(button, 1, "mode-btn svelte-1q9xxoc", null, classes_1, { active: !get(isSelectMode) });
set_attribute2(button, "aria-pressed", !get(isSelectMode));
classes_2 = set_class(button_1, 1, "mode-btn svelte-1q9xxoc", null, classes_2, { active: get(isSelectMode) });
set_attribute2(button_1, "aria-pressed", get(isSelectMode));
});
event("click", button, () => {
if (get(isSelectMode)) toggleSelectionMode(column());
});
event("click", button_1, () => {
if (!get(isSelectMode)) toggleSelectionMode(column());
});
append($$anchor2, div_4);
};
if_block(node_2, ($$render) => {
if (!isCollapsed()) $$render(consequent_6);
});
}
var node_8 = sibling(node_2, 2);
{
var consequent_7 = ($$anchor2) => {
var div_10 = root_6();
var text_7 = child(div_10);
reset(div_10);
template_effect(() => {
var _a5;
return set_text(text_7, `${(_a5 = get(selectedCount)) != null ? _a5 : ""} selected`);
});
append($$anchor2, div_10);
};
if_block(node_8, ($$render) => {
if (get(isSelectMode) && get(selectedCount) > 0) $$render(consequent_7);
});
}
reset(div);
template_effect(() => {
var _a5, _b3;
classes = set_class(div, 1, "column-header svelte-1q9xxoc", null, classes, {
"row-header": isVerticalFlow(),
collapsed: get(isHorizontalCollapsed),
"vertical-collapsed": get(isVerticalCollapsed)
});
styles = set_style(div, "", styles, { "--column-color": get(columnColor) });
set_attribute2(span, "aria-expanded", !isCollapsed());
set_attribute2(span, "aria-label", `${isCollapsed() ? "Expand" : "Collapse"} ${(_a5 = get(columnTitle)) != null ? _a5 : ""} column`);
set_text(text2, get(collapseIcon));
set_attribute2(h2, "id", `column-title-${(_b3 = column()) != null ? _b3 : ""}`);
set_attribute2(h2, "title", get(columnTitle));
set_text(text_1, get(columnTitle));
});
event("click", span, function(...$$args) {
var _a5;
(_a5 = onToggleCollapse()) == null ? void 0 : _a5.apply(this, $$args);
});
event("keydown", span, (e) => {
if (e.key === "Enter" || e.key === " ") {
e.preventDefault();
onToggleCollapse()();
}
});
append($$anchor, div);
var $$pop = pop($$exports);
$$cleanup();
return $$pop;
}
// src/ui/board/BoardCell.svelte
var import_obsidian7 = require("obsidian");
// src/ui/board/cell_creation.ts
function deriveCellCreationMetadata(secondaryAxisBucket) {
var _a5, _b3, _c2;
const value = (_a5 = secondaryAxisBucket.meta) == null ? void 0 : _a5.value;
switch ((_c2 = (_b3 = secondaryAxisBucket.meta) == null ? void 0 : _b3.source) == null ? void 0 : _c2.kind) {
case "file":
return {
targetFilePath: typeof value === "string" ? value : null,
additionalTags: []
};
case "tag-prefix":
return {
targetFilePath: null,
additionalTags: typeof value === "string" ? [value] : []
};
case "none":
default:
return {
targetFilePath: null,
additionalTags: []
};
}
}
// src/ui/tasks/swimlane_property.ts
function isWritableSwimlanePropertyKey(key2) {
return getWritablePropertyTarget(key2) !== null;
}
function createSwimlanePropertyTransform(adapter, key2, value) {
const target = getWritablePropertyTarget(key2);
if (!target) {
return null;
}
if (target.kind === "date") {
if (value === null) {
return (row) => adapter.removeDate(row, target.key);
}
const date = formatSwimlaneDateValue(value);
return date === null ? null : (row) => adapter.upsertDate(row, target.key, date);
}
if (value === null) {
return (row) => adapter.removePriority(row);
}
const priority = formatSwimlanePriorityValue(adapter, value);
return priority === null ? null : (row) => adapter.upsertPriority(row, priority);
}
function formatSwimlaneDateValue(value) {
if (value instanceof Date) {
return value.toISOString().slice(0, 10);
}
if (typeof value === "string" && parseDateOnly(value)) {
return value;
}
return null;
}
function formatSwimlanePriorityValue(adapter, value) {
var _a5, _b3, _c2;
if (adapter.schema === "tasks" /* TasksPlugin */) {
if (typeof value === "number") {
return (_a5 = getTasksPriorityValueFromWeight(value)) != null ? _a5 : null;
}
return typeof value === "string" ? (_c2 = (_b3 = getTasksPriorityOption(value)) == null ? void 0 : _b3.value) != null ? _c2 : null : null;
}
return value instanceof Date ? null : String(value);
}
// src/ui/board/drop_plan.ts
function deriveDropPlan({
dragging,
column,
secondaryId,
bucketMeta,
fileGroupTargetFilePath,
canWriteProperties
}) {
var _a5, _b3;
if (!dragging) return null;
const crossLane = dragging.fromSecondaryId !== secondaryId;
const changeColumn = dragging.fromColumn !== column;
const source2 = bucketMeta == null ? void 0 : bucketMeta.source;
if (source2 && source2.kind !== "none") {
switch (source2.kind) {
case "file": {
if (fileGroupTargetFilePath === null) break;
const hasTaskOutsideTargetFile = dragging.draggedTaskIds.some(
(id) => dragging.taskSecondaryIds[id] !== fileGroupTargetFilePath
);
if (crossLane || hasTaskOutsideTargetFile) {
return {
kind: "move-to-file",
targetFilePath: fileGroupTargetFilePath,
changeColumn
};
}
break;
}
case "tag-prefix": {
if (!crossLane) break;
const value = bucketMeta == null ? void 0 : bucketMeta.value;
return {
kind: "set-tag",
tag: typeof value === "string" ? value : null,
prefix: (_a5 = source2.prefix) != null ? _a5 : "",
includeTags: source2.includeTags,
changeColumn
};
}
case "property": {
if (!crossLane) break;
if (!canWriteProperties || !isWritableSwimlanePropertyKey(source2.key)) {
return null;
}
return {
kind: "set-property",
key: source2.key,
value: (_b3 = bucketMeta == null ? void 0 : bucketMeta.value) != null ? _b3 : null,
changeColumn
};
}
default: {
const unhandled = source2;
return unhandled;
}
}
}
return changeColumn && !crossLane ? { kind: "column-only", changeColumn: true } : null;
}
// src/ui/dnd/store.ts
var isDraggingStore = writable(null);
var subtaskDraggingStore = writable(null);
// src/ui/components/TaskLineRow.svelte
var root5 = from_html(`<div class="task-line-actions svelte-1y3uj64"><!></div>`);
var root_13 = from_html(`<div><div class="task-line-marker svelte-1y3uj64"><!></div> <div class="task-line-content svelte-1y3uj64"><!></div> <!></div>`);
var $$css5 = {
hash: "svelte-1y3uj64",
code: ".task-line-row.svelte-1y3uj64 {--task-line-base-padding-left: calc(var(--size-4-2) + 8px);--task-line-indent-step: 1.65rem;--task-line-marker-size: 20px;--task-line-row-height: 1.3em;--task-line-column-gap: var(--size-2-2);--task-line-block-padding: 0 var(--size-4-2) var(--size-2-1)\n calc(\n var(--task-line-base-padding-left) +\n (var(--task-line-depth) * var(--task-line-indent-step))\n );display:grid;grid-template-columns:var(--task-line-marker-size) minmax(0, 1fr);column-gap:var(--task-line-column-gap);align-items:start;padding:var(--task-line-block-padding);}.task-line-row.has-actions.svelte-1y3uj64 {grid-template-columns:var(--task-line-marker-size) minmax(0, 1fr) auto;}.task-line-row.card-variant.svelte-1y3uj64 {--task-line-column-gap: var(--size-2-3);--task-line-row-height: var(--task-content-line-height, 1.5rem);--task-line-block-padding: var(--size-4-2) var(--size-4-2)\n var(--size-4-2)\n calc(\n var(--task-line-base-padding-left) +\n (var(--task-line-depth) * var(--task-line-indent-step))\n );}.task-line-marker.svelte-1y3uj64,\n.task-line-actions.svelte-1y3uj64 {display:flex;align-items:center;justify-content:center;min-width:0;height:var(--task-line-row-height);}.task-line-content.svelte-1y3uj64 {display:block;min-width:0;min-height:var(--task-line-row-height);}.task-line-actions.svelte-1y3uj64 {justify-content:flex-end;}"
};
function TaskLineRow($$anchor, $$props) {
if (new.target) return createClassComponent({ component: TaskLineRow, ...$$anchor });
push($$props, false);
append_styles($$anchor, $$css5);
let depth = prop($$props, "depth", 12, 0);
let hasActions = prop($$props, "hasActions", 12, false);
let variant = prop($$props, "variant", 12, "source");
var $$exports = {
get depth() {
return depth();
},
set depth($$value) {
depth($$value);
flushSync();
},
get hasActions() {
return hasActions();
},
set hasActions($$value) {
hasActions($$value);
flushSync();
},
get variant() {
return variant();
},
set variant($$value) {
variant($$value);
flushSync();
},
$set: update_legacy_props,
$on: ($$event_name, $$event_cb) => add_legacy_event_listener($$props, $$event_name, $$event_cb)
};
var div = root_13();
let classes;
let styles;
var div_1 = child(div);
var node = child(div_1);
slot(node, $$props, "marker", {}, null);
reset(div_1);
var div_2 = sibling(div_1, 2);
var node_1 = child(div_2);
slot(node_1, $$props, "default", {}, null);
reset(div_2);
var node_2 = sibling(div_2, 2);
{
var consequent = ($$anchor2) => {
var div_3 = root5();
var node_3 = child(div_3);
slot(node_3, $$props, "actions", {}, null);
reset(div_3);
append($$anchor2, div_3);
};
if_block(node_2, ($$render) => {
if (hasActions()) $$render(consequent);
});
}
reset(div);
template_effect(() => {
classes = set_class(div, 1, "task-line-row svelte-1y3uj64", null, classes, {
"has-actions": hasActions(),
"card-variant": variant() === "card"
});
styles = set_style(div, "", styles, { "--task-line-depth": depth() });
});
append($$anchor, div);
return pop($$exports);
}
// src/ui/components/TaskSourceRow.svelte
var import_obsidian4 = require("obsidian");
// src/ui/components/TaskSourceStatusButton.svelte
var root6 = from_html(`<button role="checkbox" aria-label="Advance subtask status"><!></button>`);
var $$css6 = {
hash: "svelte-74sw79",
code: ".icon-button.source-row-status.svelte-74sw79 {display:flex;justify-content:center;align-items:center;width:20px;height:20px;padding:0;border:none;background:transparent;cursor:pointer;border-radius:var(--radius-s);box-shadow:none;overflow:visible;}.icon-button.source-row-status.svelte-74sw79:hover, .icon-button.source-row-status.svelte-74sw79:active {background:transparent;box-shadow:none;}.icon-button.source-row-status.svelte-74sw79:disabled {cursor:default;opacity:0.35;}.icon-button.source-row-status.usesStatusMarker.svelte-74sw79 {color:var(--text-normal);}.icon-button.source-row-status.is-done.svelte-74sw79 svg {color:var(--interactive-accent);}"
};
function TaskSourceStatusButton($$anchor, $$props) {
if (new.target) return createClassComponent({ component: TaskSourceStatusButton, ...$$anchor });
push($$props, false);
append_styles($$anchor, $$css6);
const isDone = mutable_source();
const isIgnored = mutable_source();
const isChecked = mutable_source();
const displayStatusIsCustom = mutable_source();
let task = prop($$props, "task", 12);
let taskActions = prop($$props, "taskActions", 12);
let node = prop($$props, "node", 12);
let isSelectionMode = prop($$props, "isSelectionMode", 12, false);
function toggleStatus() {
void taskActions().toggleSourceTaskStatus(task().id, node().rowIndex);
}
function handleKeydown(e) {
if (e.key === "Enter" || e.key === " ") {
e.preventDefault();
toggleStatus();
}
}
legacy_pre_effect(() => (deep_read_state(task()), deep_read_state(node())), () => {
set(isDone, task().isSourceTaskStatusDone(node().status));
});
legacy_pre_effect(() => deep_read_state(node()), () => {
set(isIgnored, node().taskVisibility === "ignored");
});
legacy_pre_effect(() => (get(isDone), get(isIgnored)), () => {
set(isChecked, get(isDone) || get(isIgnored));
});
legacy_pre_effect(() => deep_read_state(node()), () => {
set(displayStatusIsCustom, node().status !== " ");
});
legacy_pre_effect_reset();
var $$exports = {
get task() {
return task();
},
set task($$value) {
task($$value);
flushSync();
},
get taskActions() {
return taskActions();
},
set taskActions($$value) {
taskActions($$value);
flushSync();
},
get node() {
return node();
},
set node($$value) {
node($$value);
flushSync();
},
get isSelectionMode() {
return isSelectionMode();
},
set isSelectionMode($$value) {
isSelectionMode($$value);
flushSync();
},
$set: update_legacy_props,
$on: ($$event_name, $$event_cb) => add_legacy_event_listener($$props, $$event_name, $$event_cb)
};
init();
var button = root6();
let classes;
var node_1 = child(button);
TaskStatusMarker(node_1, {
get status() {
return deep_read_state(node()), untrack(() => node().status);
},
get isDone() {
return get(isDone);
},
size: 16
});
reset(button);
template_effect(() => {
classes = set_class(button, 1, "icon-button source-row-status svelte-74sw79", null, classes, {
"is-done": get(isDone),
usesStatusMarker: get(displayStatusIsCustom)
});
set_attribute2(button, "aria-checked", get(isChecked));
button.disabled = isSelectionMode();
set_attribute2(button, "tabindex", isSelectionMode() ? -1 : 0);
});
event("click", button, stopPropagation(toggleStatus));
event("keydown", button, stopPropagation(handleKeydown));
append($$anchor, button);
return pop($$exports);
}
// src/ui/components/TaskSourceRow.svelte
var root7 = from_html(`<textarea class="svelte-smkg1f"></textarea>`);
var root_14 = from_html(`<div role="button" tabindex="0" class="source-row-preview markdown-rendered svelte-smkg1f"></div>`);
var root_23 = from_html(`<span class="source-row-bullet svelte-smkg1f" aria-hidden="true"></span>`);
var root_32 = from_html(`<button type="button" class="delete-subtask-btn svelte-smkg1f" aria-label="Delete subtask" title="Delete subtask"><!></button>`);
var root_42 = from_html(`<div><!> <!></div>`);
var $$css7 = {
hash: "svelte-smkg1f",
code: '.source-row.svelte-smkg1f {--source-row-line-height: 1.3;position:relative;}.source-row.is-dragging.svelte-smkg1f {opacity:0.4;}.source-row.drop-before.svelte-smkg1f::before, .source-row.drop-after.svelte-smkg1f::before {content:"";position:absolute;left:calc(var(--task-line-base-padding-left, 20px) + var(--drag-indicator-depth, 0) * var(--task-line-indent-step, 26px));right:8px;height:2px;background:var(--interactive-accent);pointer-events:none;}.source-row.drop-before.svelte-smkg1f::after, .source-row.drop-after.svelte-smkg1f::after {content:"";position:absolute;left:calc(var(--task-line-base-padding-left, 20px) + var(--drag-indicator-depth, 0) * var(--task-line-indent-step, 26px) - 8px);width:10px;height:10px;border-radius:999px;background:var(--interactive-accent);pointer-events:none;}.source-row.drop-before.svelte-smkg1f::before {top:-1px;}.source-row.drop-before.svelte-smkg1f::after {top:-5px;}.source-row.drop-after.svelte-smkg1f::before {bottom:-1px;}.source-row.drop-after.svelte-smkg1f::after {bottom:-5px;}.delete-subtask-btn.svelte-smkg1f {display:flex;justify-content:center;align-items:center;width:20px;height:20px;padding:0;border:none;background:transparent;cursor:pointer;color:var(--text-muted);opacity:0;transition:opacity 0.15s ease, color 0.15s ease;box-shadow:none;}.delete-subtask-btn.svelte-smkg1f:hover {color:var(--text-error, var(--text-accent));background:transparent;box-shadow:none;}.source-row.svelte-smkg1f:hover .delete-subtask-btn:where(.svelte-smkg1f) {opacity:0.8;}.delete-subtask-btn.svelte-smkg1f:hover {opacity:1 !important;}.source-row-preview.svelte-smkg1f {display:block;width:100%;height:auto;min-height:var(--task-line-row-height, 1.5rem);appearance:none;padding:0;border:none;background:transparent;box-shadow:none;color:var(--text-normal);font:inherit;line-height:var(--source-row-line-height);text-align:left;white-space:pre-wrap;overflow-wrap:anywhere;cursor:text;}.source-row-preview.svelte-smkg1f:hover, .source-row-preview.svelte-smkg1f:active {background:transparent;box-shadow:none;}.source-row-preview.svelte-smkg1f:focus-visible {outline:2px solid var(--background-modifier-border-focus);outline-offset:2px;}.source-row-preview.svelte-smkg1f p {margin:0;}textarea.svelte-smkg1f {cursor:text;background-color:var(--color-base-25);width:100%;min-height:1.6rem;resize:none;}.source-row-bullet.svelte-smkg1f {display:block;width:8px;height:8px;border-radius:50%;background:var(--text-muted);}.is-ignored-task.svelte-smkg1f .source-row-preview:where(.svelte-smkg1f) {color:var(--text-normal);}'
};
function TaskSourceRow($$anchor, $$props) {
if (new.target) return createClassComponent({ component: TaskSourceRow, ...$$anchor });
push($$props, false);
append_styles($$anchor, $$css7);
const $subtaskDraggingStore = () => store_get(subtaskDraggingStore, "$subtaskDraggingStore", $$stores);
const [$$stores, $$cleanup] = setup_stores();
const rawListItemText = mutable_source();
const editText = mutable_source();
const previewText = mutable_source();
let app = prop($$props, "app", 12);
let task = prop($$props, "task", 12);
let taskActions = prop($$props, "taskActions", 12);
let node = prop($$props, "node", 12);
let isSelectionMode = prop($$props, "isSelectionMode", 12, false);
let depth = prop($$props, "depth", 12, 0);
let isEditing = mutable_source(false);
let isDragging = mutable_source(false);
let isDraggedOver = mutable_source(false);
let dropBefore = mutable_source(false);
let dropAfter = mutable_source(false);
let dragIndicatorDepth = mutable_source(depth());
let previewContainerEl = mutable_source();
let markdownComponent;
const interactiveTagNames = /* @__PURE__ */ new Set([
"a",
"button",
"input",
"select",
"textarea",
"label",
"summary",
"details"
]);
function eventHasInteractiveTarget(e) {
const path = (e == null ? void 0 : e.composedPath()) || [];
const currentTarget = e == null ? void 0 : e.currentTarget;
for (const element2 of path) {
if (!(element2 instanceof HTMLElement)) {
continue;
}
if (currentTarget instanceof HTMLElement && element2 === currentTarget) {
continue;
}
if (interactiveTagNames.has(element2.tagName.toLowerCase())) {
return true;
}
if (element2.isContentEditable) {
return true;
}
const role = element2.getAttribute("role");
if (role === "button" || role === "checkbox" || role === "link") {
return true;
}
}
return false;
}
function handleFocus(e) {
if (eventHasInteractiveTarget(e)) {
return;
}
startEditing();
}
async function renderMarkdown() {
if (!get(previewContainerEl)) return;
if (markdownComponent) {
markdownComponent.unload();
}
get(previewContainerEl).empty();
markdownComponent = new import_obsidian4.Component();
await import_obsidian4.MarkdownRenderer.render(app(), get(previewText), get(previewContainerEl), task().path, markdownComponent);
setupLinkHandlers();
postProcessRenderedContent();
}
function setupLinkHandlers() {
if (!get(previewContainerEl)) return;
const internalLinks = get(previewContainerEl).querySelectorAll("a.internal-link");
internalLinks.forEach((link2) => {
const anchorEl = link2;
anchorEl.addEventListener("click", (e) => {
e.preventDefault();
e.stopPropagation();
const linkTarget = anchorEl.getAttribute("data-href");
if (linkTarget && app()) {
app().workspace.openLinkText(linkTarget, task().path, import_obsidian4.Keymap.isModEvent(e));
}
});
anchorEl.addEventListener("mouseover", (e) => {
const linkTarget = anchorEl.getAttribute("data-href");
if (linkTarget && app() && get(previewContainerEl)) {
app().workspace.trigger("hover-link", {
event: e,
source: "kanban-view",
hoverParent: get(previewContainerEl),
targetEl: anchorEl,
linktext: linkTarget,
sourcePath: task().path
});
}
});
});
}
function postProcessRenderedContent() {
if (!get(previewContainerEl)) return;
function stopPropagation2(e) {
e.stopPropagation();
}
get(previewContainerEl).querySelectorAll("a:not(.internal-link)").forEach((a) => {
const anchor = a;
anchor.target = "_blank";
anchor.rel = "noopener noreferrer";
anchor.addEventListener("click", stopPropagation2);
anchor.addEventListener("keypress", stopPropagation2);
});
get(previewContainerEl).querySelectorAll("iframe, audio, video").forEach((el) => {
el.remove();
});
}
let lastRenderedMarkdownKey = mutable_source("");
onDestroy(() => {
if (markdownComponent) {
markdownComponent.unload();
}
});
function startEditing() {
set(isEditing, true);
}
function finishEditing(e) {
const next2 = e.currentTarget.value;
set(isEditing, false);
if (next2 !== get(editText)) {
void taskActions().updateSourceBlockRow(task().id, node().rowIndex, next2);
}
}
function handleTextareaKeydown(e) {
var _a5;
if (e.key === "Enter" && !e.shiftKey || e.key === "Escape") {
e.preventDefault();
(_a5 = e.currentTarget) == null ? void 0 : _a5.blur();
if (e.key === "Escape") {
set(isEditing, false);
}
}
}
function handlePreviewKeydown(e) {
if (e.key === "Enter" || e.key === " ") {
if (eventHasInteractiveTarget(e)) {
return;
}
e.preventDefault();
startEditing();
}
}
function focusAndAutosize(node2) {
function resize() {
node2.style.height = "0px";
node2.style.height = `${node2.scrollHeight}px`;
}
const focusTimer = setTimeout(() => node2.focus(), 0);
node2.addEventListener("input", resize);
resize();
return {
destroy() {
clearTimeout(focusTimer);
node2.removeEventListener("input", resize);
}
};
}
class ConfirmDeleteSubtaskModal extends import_obsidian4.Modal {
constructor(app2, subtaskText, onConfirm) {
super(app2);
this.subtaskText = subtaskText;
this.onConfirm = onConfirm;
}
onOpen() {
this.contentEl.addClass("task-list-kanban-confirm-modal");
this.contentEl.createEl("h2", { text: "Delete subtask?" });
this.contentEl.createEl("p", {
text: `Are you sure you want to delete "${this.subtaskText}" and all its nested items? This action cannot be undone.`
});
const actions = this.contentEl.createDiv({ cls: "confirm-modal-actions" });
const cancelButton = actions.createEl("button", { text: "Cancel" });
cancelButton.addEventListener("click", () => this.close());
const deleteButton = actions.createEl("button", { text: "Delete", cls: "mod-warning" });
deleteButton.addEventListener("click", () => {
this.onConfirm();
this.close();
});
window.requestAnimationFrame(() => cancelButton.focus());
}
onClose() {
this.contentEl.empty();
}
}
function handleDeleteClick() {
const text2 = node().kind === "task" ? node().content : node().rawLine.trim();
new ConfirmDeleteSubtaskModal(app(), text2, () => {
void taskActions().deleteSourceBlockRow(task().id, node().rowIndex);
}).open();
}
function handleDragStart(e) {
e.stopPropagation();
set(isDragging, true);
subtaskDraggingStore.set({
taskId: task().id,
draggedRowIndex: node().rowIndex,
draggedIndentation: node().indentation
});
if (e.dataTransfer) {
e.dataTransfer.setData("text/plain", `${task().id}:${node().rowIndex}`);
e.dataTransfer.dropEffect = "move";
}
}
function handleDragEnd(e) {
e.stopPropagation();
set(isDragging, false);
subtaskDraggingStore.set(null);
}
function handleDragOver(e) {
if (!$subtaskDraggingStore() || $subtaskDraggingStore().taskId !== task().id) return;
if ($subtaskDraggingStore().draggedRowIndex === node().rowIndex) return;
e.preventDefault();
e.stopPropagation();
set(isDraggedOver, true);
const rect = e.currentTarget.getBoundingClientRect();
const relativeY = e.clientY - rect.top;
set(dropBefore, relativeY < rect.height / 2);
set(dropAfter, !get(dropBefore));
const mouseX = e.clientX - rect.left;
const hoveredRowDepth = depth();
const maxDepth = get(dropBefore) ? hoveredRowDepth : hoveredRowDepth + 1;
set(dragIndicatorDepth, Math.min(maxDepth, Math.max(1, Math.floor((mouseX - 20) / 26))));
}
function handleDragLeave(e) {
e.stopPropagation();
set(isDraggedOver, false);
set(dropBefore, false);
set(dropAfter, false);
}
function handleDrop(e) {
if (!$subtaskDraggingStore() || $subtaskDraggingStore().taskId !== task().id) return;
e.preventDefault();
e.stopPropagation();
set(isDraggedOver, false);
const draggedRowIndex = $subtaskDraggingStore().draggedRowIndex;
subtaskDraggingStore.set(null);
const position = get(dropBefore) ? "before" : "after";
void taskActions().moveSourceBlockRow(task().id, draggedRowIndex, node().rowIndex, position, get(dragIndicatorDepth));
set(dropBefore, false);
set(dropAfter, false);
}
legacy_pre_effect(() => (deep_read_state(node()), getRawListItemText), () => {
set(rawListItemText, node().kind === "raw" ? getRawListItemText(node()) : null);
});
legacy_pre_effect(
() => (get(rawListItemText), getSourceNodeText, deep_read_state(node())),
() => {
var _a5;
set(editText, ((_a5 = get(rawListItemText)) != null ? _a5 : getSourceNodeText(node())).replaceAll("<br />", "\n"));
}
);
legacy_pre_effect(() => (get(rawListItemText), get(editText)), () => {
var _a5;
set(previewText, ((_a5 = get(rawListItemText)) != null ? _a5 : get(editText)).replaceAll("<br />", "\n"));
});
legacy_pre_effect(() => $subtaskDraggingStore(), () => {
if (!$subtaskDraggingStore()) {
set(isDraggedOver, false);
set(dropBefore, false);
set(dropAfter, false);
}
});
legacy_pre_effect(() => get(isEditing), () => {
if (get(isEditing)) {
set(lastRenderedMarkdownKey, "");
}
});
legacy_pre_effect(
() => (get(previewText), get(previewContainerEl), get(isEditing), deep_read_state(task()), get(lastRenderedMarkdownKey)),
() => {
if (get(previewText) && get(previewContainerEl) && !get(isEditing)) {
const markdownKey = JSON.stringify({ source: get(previewText), path: task().path });
if (markdownKey !== get(lastRenderedMarkdownKey)) {
set(lastRenderedMarkdownKey, markdownKey);
void renderMarkdown();
}
}
}
);
legacy_pre_effect_reset();
var $$exports = {
get app() {
return app();
},
set app($$value) {
app($$value);
flushSync();
},
get task() {
return task();
},
set task($$value) {
task($$value);
flushSync();
},
get taskActions() {
return taskActions();
},
set taskActions($$value) {
taskActions($$value);
flushSync();
},
get node() {
return node();
},
set node($$value) {
node($$value);
flushSync();
},
get isSelectionMode() {
return isSelectionMode();
},
set isSelectionMode($$value) {
isSelectionMode($$value);
flushSync();
},
get depth() {
return depth();
},
set depth($$value) {
depth($$value);
flushSync();
},
$set: update_legacy_props,
$on: ($$event_name, $$event_cb) => add_legacy_event_listener($$props, $$event_name, $$event_cb)
};
init();
var div = root_42();
let classes;
let styles;
var node_1 = child(div);
TaskLineRow(node_1, {
get depth() {
return depth();
},
hasActions: true,
children: ($$anchor2, $$slotProps) => {
var fragment = comment();
var node_2 = first_child(fragment);
{
var consequent = ($$anchor3) => {
var textarea = root7();
remove_textarea_child(textarea);
action(textarea, ($$node) => focusAndAutosize == null ? void 0 : focusAndAutosize($$node));
effect(() => event("keydown", textarea, handleTextareaKeydown));
effect(() => event("blur", textarea, finishEditing));
template_effect(() => set_value(textarea, get(editText)));
append($$anchor3, textarea);
};
var alternate = ($$anchor3) => {
var div_1 = root_14();
bind_this(div_1, ($$value) => set(previewContainerEl, $$value), () => get(previewContainerEl));
event("mouseup", div_1, handleFocus);
event("keydown", div_1, handlePreviewKeydown);
append($$anchor3, div_1);
};
if_block(node_2, ($$render) => {
if (get(isEditing)) $$render(consequent);
else $$render(alternate, -1);
});
}
append($$anchor2, fragment);
},
$$slots: {
default: true,
marker: ($$anchor2, $$slotProps) => {
var fragment_1 = comment();
var node_3 = first_child(fragment_1);
{
var consequent_1 = ($$anchor3) => {
TaskSourceStatusButton($$anchor3, {
get task() {
return task();
},
get taskActions() {
return taskActions();
},
get node() {
return node();
},
get isSelectionMode() {
return isSelectionMode();
}
});
};
var consequent_2 = ($$anchor3) => {
var span = root_23();
append($$anchor3, span);
};
if_block(node_3, ($$render) => {
if (deep_read_state(node()), untrack(() => node().kind === "task")) $$render(consequent_1);
else if (get(rawListItemText) !== null) $$render(consequent_2, 1);
});
}
append($$anchor2, fragment_1);
},
actions: ($$anchor2, $$slotProps) => {
var fragment_3 = comment();
var node_4 = first_child(fragment_3);
{
var consequent_3 = ($$anchor3) => {
var button = root_32();
var node_5 = child(button);
Icon(node_5, { name: "lucide-x", size: 14, opacity: 0.6 });
reset(button);
event("click", button, stopPropagation(handleDeleteClick));
append($$anchor3, button);
};
if_block(node_4, ($$render) => {
if (!isSelectionMode()) $$render(consequent_3);
});
}
append($$anchor2, fragment_3);
}
}
});
var node_6 = sibling(node_1, 2);
slot(node_6, $$props, "default", {}, null);
reset(div);
template_effect(() => {
classes = set_class(div, 1, "source-row svelte-smkg1f", null, classes, {
"is-ignored-task": node().kind === "task" && node().taskVisibility === "ignored",
"is-raw-list-item": get(rawListItemText) !== null,
"is-dragging": get(isDragging),
"is-dragged-over": get(isDraggedOver),
"drop-before": get(isDraggedOver) && get(dropBefore),
"drop-after": get(isDraggedOver) && get(dropAfter)
});
set_attribute2(div, "draggable", !get(isEditing));
styles = set_style(div, "", styles, { "--drag-indicator-depth": get(dragIndicatorDepth) });
});
event("dragstart", div, handleDragStart);
event("dragend", div, handleDragEnd);
event("dragover", div, handleDragOver);
event("dragleave", div, handleDragLeave);
event("drop", div, handleDrop);
append($$anchor, div);
var $$pop = pop($$exports);
$$cleanup();
return $$pop;
}
// src/ui/components/TaskSourceRows.svelte
function TaskSourceRows($$anchor, $$props) {
if (new.target) return createClassComponent({ component: TaskSourceRows, ...$$anchor });
push($$props, false);
let app = prop($$props, "app", 12);
let task = prop($$props, "task", 12);
let taskActions = prop($$props, "taskActions", 12);
let nodes = prop($$props, "nodes", 28, () => []);
let isSelectionMode = prop($$props, "isSelectionMode", 12, false);
let depth = prop($$props, "depth", 12, 0);
var $$exports = {
get app() {
return app();
},
set app($$value) {
app($$value);
flushSync();
},
get task() {
return task();
},
set task($$value) {
task($$value);
flushSync();
},
get taskActions() {
return taskActions();
},
set taskActions($$value) {
taskActions($$value);
flushSync();
},
get nodes() {
return nodes();
},
set nodes($$value) {
nodes($$value);
flushSync();
},
get isSelectionMode() {
return isSelectionMode();
},
set isSelectionMode($$value) {
isSelectionMode($$value);
flushSync();
},
get depth() {
return depth();
},
set depth($$value) {
depth($$value);
flushSync();
},
$set: update_legacy_props,
$on: ($$event_name, $$event_cb) => add_legacy_event_listener($$props, $$event_name, $$event_cb)
};
var fragment = comment();
var node_1 = first_child(fragment);
each(node_1, 1, nodes, (node) => node.rowIndex, ($$anchor2, node) => {
TaskSourceRow($$anchor2, {
get app() {
return app();
},
get task() {
return task();
},
get taskActions() {
return taskActions();
},
get node() {
return get(node);
},
get isSelectionMode() {
return isSelectionMode();
},
get depth() {
return depth();
},
children: ($$anchor3, $$slotProps) => {
var fragment_2 = comment();
var node_2 = first_child(fragment_2);
{
var consequent = ($$anchor4) => {
var fragment_3 = comment();
var node_3 = first_child(fragment_3);
{
let $0 = derived_safe_equal(() => depth() + 1);
TaskSourceRows(node_3, {
get app() {
return app();
},
get task() {
return task();
},
get taskActions() {
return taskActions();
},
get nodes() {
return get(node), untrack(() => get(node).sourceChildren);
},
get isSelectionMode() {
return isSelectionMode();
},
get depth() {
return get($0);
}
});
}
append($$anchor4, fragment_3);
};
if_block(node_2, ($$render) => {
if (get(node), untrack(() => get(node).sourceChildren.length > 0)) $$render(consequent);
});
}
append($$anchor3, fragment_2);
},
$$slots: { default: true }
});
});
append($$anchor, fragment);
return pop($$exports);
}
// src/ui/components/task_menu.svelte
var import_obsidian5 = require("obsidian");
function Task_menu($$anchor, $$props) {
if (new.target) return createClassComponent({ component: Task_menu, ...$$anchor });
push($$props, false);
const $columnTagTableStore = () => store_get(columnTagTableStore(), "$columnTagTableStore", $$stores);
const [$$stores, $$cleanup] = setup_stores();
let task = prop($$props, "task", 12);
let taskActions = prop($$props, "taskActions", 12);
let columnTagTableStore = prop($$props, "columnTagTableStore", 12);
let doneColumnName = prop($$props, "doneColumnName", 12, void 0);
function showMenu(e) {
const menu = new import_obsidian5.Menu();
const target = e.target;
if (!target) {
return;
}
const boundingRect = target.getBoundingClientRect();
const y = boundingRect.top + boundingRect.height / 2;
const x = boundingRect.left + boundingRect.width / 2;
menu.addItem((i) => {
i.setTitle(`Go to file`).onClick(() => taskActions().viewFile(task().id));
});
menu.addSeparator();
for (const [tag2, label] of Object.entries($columnTagTableStore())) {
menu.addItem((i) => {
i.setTitle(`Move to ${label}`).onClick(() => taskActions().changeColumn(task().id, tag2));
if (task().column === tag2) {
i.setDisabled(true);
}
});
}
menu.addItem((i) => {
i.setTitle(`Move to ${resolveDefaultColumnName("done", void 0, doneColumnName())}`).onClick(() => taskActions().markDone(task().id));
if (task().done) {
i.setDisabled(true);
}
});
menu.addSeparator();
menu.addItem((i) => {
i.setTitle(`Duplicate task`).onClick(() => taskActions().duplicateTask(task().id));
});
menu.addItem((i) => {
if (task().isCancelled) {
i.setTitle(`Restore task`).onClick(() => taskActions().restoreTasks([task().id]));
} else {
i.setTitle(`Cancel task`).onClick(() => taskActions().cancelTasks([task().id]));
}
});
menu.addItem((i) => {
i.setTitle(`Archive task`).onClick(() => taskActions().archiveTasks([task().id]));
});
menu.addItem((i) => {
i.setTitle(`Delete task`).onClick(() => taskActions().deleteTask(task().id));
});
menu.showAtPosition({ x, y });
}
var $$exports = {
get task() {
return task();
},
set task($$value) {
task($$value);
flushSync();
},
get taskActions() {
return taskActions();
},
set taskActions($$value) {
taskActions($$value);
flushSync();
},
get columnTagTableStore() {
return columnTagTableStore();
},
set columnTagTableStore($$value) {
columnTagTableStore($$value);
flushSync();
},
get doneColumnName() {
return doneColumnName();
},
set doneColumnName($$value) {
doneColumnName($$value);
flushSync();
},
$set: update_legacy_props,
$on: ($$event_name, $$event_cb) => add_legacy_event_listener($$props, $$event_name, $$event_cb)
};
init();
Icon_button($$anchor, { icon: "lucide-more-vertical", $$events: { click: showMenu } });
var $$pop = pop($$exports);
$$cleanup();
return $$pop;
}
// src/ui/components/DateInputFields.svelte
var dateFieldLabels = { due: "Due", scheduled: "Scheduled", start: "Start" };
var root8 = from_html(`<label class="date-input-field svelte-4hxhuo"><span> </span> <input type="date" class="svelte-4hxhuo"/></label>`);
var root_15 = from_html(`<button class="done-date-editing svelte-4hxhuo" type="button">Done</button>`);
var root_24 = from_html(`<div class="date-input-fields svelte-4hxhuo" role="group" aria-label="Edit task dates" draggable="false"><!> <!></div>`);
var $$css8 = {
hash: "svelte-4hxhuo",
code: ".date-input-fields.svelte-4hxhuo {display:flex;flex-wrap:wrap;align-items:end;gap:var(--size-2-2);width:100%;}.date-input-field.svelte-4hxhuo {display:flex;flex-direction:column;gap:2px;min-width:116px;flex:1 1 116px;color:var(--text-muted);font-size:var(--font-smallest);text-transform:uppercase;}.date-input-field.svelte-4hxhuo input:where(.svelte-4hxhuo) {width:100%;min-height:28px;font-size:var(--font-ui-smaller);text-transform:none;}.done-date-editing.svelte-4hxhuo {display:inline-flex;align-items:center;gap:var(--size-2-1);min-height:28px;padding:1px var(--size-2-2);border:var(--border-width) solid var(--background-modifier-border);border-radius:var(--radius-s);background:var(--background-secondary-alt);color:var(--text-muted);box-shadow:none;line-height:var(--line-height-tight);}.done-date-editing.svelte-4hxhuo:hover {border-color:var(--text-muted);color:var(--text-normal);background:var(--background-secondary);box-shadow:none;}"
};
function DateInputFields($$anchor, $$props) {
if (new.target) return createClassComponent({ component: DateInputFields, ...$$anchor });
push($$props, false);
append_styles($$anchor, $$css8);
let values = prop($$props, "values", 12);
let onDateChange = prop($$props, "onDateChange", 12);
let showDoneButton = prop($$props, "showDoneButton", 12, false);
let onDone = prop($$props, "onDone", 12, () => {
});
var $$exports = {
get values() {
return values();
},
set values($$value) {
values($$value);
flushSync();
},
get onDateChange() {
return onDateChange();
},
set onDateChange($$value) {
onDateChange($$value);
flushSync();
},
get showDoneButton() {
return showDoneButton();
},
set showDoneButton($$value) {
showDoneButton($$value);
flushSync();
},
get onDone() {
return onDone();
},
set onDone($$value) {
onDone($$value);
flushSync();
},
$set: update_legacy_props,
$on: ($$event_name, $$event_cb) => add_legacy_event_listener($$props, $$event_name, $$event_cb)
};
init();
var div = root_24();
var node = child(div);
each(node, 1, () => EDITABLE_DATE_PROPERTY_KEYS, (key2) => key2, ($$anchor2, key2) => {
var label = root8();
var span = child(label);
var text2 = child(span, true);
reset(span);
var input = sibling(span, 2);
remove_input_defaults(input);
reset(label);
template_effect(() => {
set_text(text2, (get(key2), untrack(() => dateFieldLabels[get(key2)])));
set_value(input, (deep_read_state(values()), get(key2), untrack(() => values()[get(key2)])));
});
event("mousedown", input, stopPropagation(function($$arg) {
bubble_event.call(this, $$props, $$arg);
}));
event("mouseup", input, stopPropagation(function($$arg) {
bubble_event.call(this, $$props, $$arg);
}));
event("click", input, stopPropagation(function($$arg) {
bubble_event.call(this, $$props, $$arg);
}));
event("change", input, (event2) => onDateChange()(get(key2), event2.currentTarget.value));
event("keydown", input, stopPropagation(function($$arg) {
bubble_event.call(this, $$props, $$arg);
}));
append($$anchor2, label);
});
var node_1 = sibling(node, 2);
{
var consequent = ($$anchor2) => {
var button = root_15();
event("mousedown", button, stopPropagation(function($$arg) {
bubble_event.call(this, $$props, $$arg);
}));
event("mouseup", button, stopPropagation(function($$arg) {
bubble_event.call(this, $$props, $$arg);
}));
event("click", button, function(...$$args) {
var _a5;
(_a5 = onDone()) == null ? void 0 : _a5.apply(this, $$args);
});
event("keydown", button, stopPropagation(function($$arg) {
bubble_event.call(this, $$props, $$arg);
}));
append($$anchor2, button);
};
if_block(node_1, ($$render) => {
if (showDoneButton()) $$render(consequent);
});
}
reset(div);
append($$anchor, div);
return pop($$exports);
}
// src/ui/components/TaskDateFields.svelte
var root9 = from_html(`<div class="task-date-fields read-mode svelte-1ml44qr" role="group" aria-label="Task dates" draggable="false"><button class="add-date-button svelte-1ml44qr" type="button" title="Edit task dates"><span aria-hidden="true" class="svelte-1ml44qr">+</span> Date</button></div>`);
var root_16 = from_html(`<div class="task-date-fields edit-mode svelte-1ml44qr" role="group" aria-label="Edit task dates"><!></div>`);
var $$css9 = {
hash: "svelte-1ml44qr",
code: ".task-date-fields.svelte-1ml44qr {display:contents;font-size:var(--font-ui-smaller);}.add-date-button.svelte-1ml44qr {display:inline-flex;align-items:center;gap:var(--size-2-1);height:auto;min-height:0;padding:0 var(--size-2-2);margin:0;border:none;border-radius:var(--radius-s);background:transparent;color:var(--text-accent);box-shadow:none;font-size:inherit;font-weight:var(--font-medium);line-height:inherit;}.add-date-button.svelte-1ml44qr span:where(.svelte-1ml44qr) {font-size:inherit;line-height:1;}.add-date-button.svelte-1ml44qr:hover {background:transparent;color:var(--text-accent-hover);box-shadow:none;}.edit-mode.svelte-1ml44qr {display:flex;width:100%;padding-top:var(--size-2-1);border-top:var(--border-width) solid var(--background-modifier-border);}"
};
function TaskDateFields($$anchor, $$props) {
if (new.target) return createClassComponent({ component: TaskDateFields, ...$$anchor });
push($$props, false);
append_styles($$anchor, $$css9);
const dateEditingEnabled = mutable_source();
const dateValues = mutable_source();
const showDateInputs = mutable_source();
const showReadChips = mutable_source();
let task = prop($$props, "task", 12);
let taskActions = prop($$props, "taskActions", 12);
let propertySchemaOption = prop($$props, "propertySchemaOption", 28, () => "none" /* None */);
let isTaskEditing = prop($$props, "isTaskEditing", 12, false);
let onEditingDatesChange = prop($$props, "onEditingDatesChange", 12, () => {
});
let isDateEditing = mutable_source(false);
let draftDateValues = mutable_source({ due: "", scheduled: "", start: "" });
let wasShowingDateInputs = mutable_source(false);
function getDateValue(key2) {
const property = getPropertyByKey(task().properties, key2);
return (property == null ? void 0 : property.value) instanceof Date ? formatLocalDate(property.value) : "";
}
function openDateEditor() {
set(isDateEditing, true);
}
function pinDateEditing() {
set(isDateEditing, true);
}
function handleDraftDateChange(key2, value) {
set(draftDateValues, { ...get(draftDateValues), [key2]: value });
}
async function saveDraftDates() {
const edits = EDITABLE_DATE_PROPERTY_KEYS.map((key2) => {
var _a5;
return { key: key2, value: (_a5 = get(draftDateValues)[key2]) != null ? _a5 : "" };
}).filter(({ key: key2, value }) => value !== get(dateValues)[key2]);
set(isDateEditing, false);
if (edits.length > 0) {
await taskActions().applyDateEdits(task().id, edits);
}
}
legacy_pre_effect(
() => (getPropertyWriteAdapter, deep_read_state(propertySchemaOption())),
() => {
set(dateEditingEnabled, getPropertyWriteAdapter(propertySchemaOption()) !== null);
}
);
legacy_pre_effect(() => EDITABLE_DATE_PROPERTY_KEYS, () => {
set(dateValues, Object.fromEntries(EDITABLE_DATE_PROPERTY_KEYS.map((key2) => [key2, getDateValue(key2)])));
});
legacy_pre_effect(
() => (get(dateEditingEnabled), deep_read_state(isTaskEditing()), get(isDateEditing)),
() => {
set(showDateInputs, get(dateEditingEnabled) && (isTaskEditing() || get(isDateEditing)));
}
);
legacy_pre_effect(() => (get(dateEditingEnabled), get(showDateInputs)), () => {
set(showReadChips, get(dateEditingEnabled) && !get(showDateInputs));
});
legacy_pre_effect(
() => (deep_read_state(onEditingDatesChange()), get(showDateInputs)),
() => {
onEditingDatesChange()(get(showDateInputs));
}
);
legacy_pre_effect(
() => (get(showDateInputs), get(wasShowingDateInputs), get(dateValues)),
() => {
if (get(showDateInputs) && !get(wasShowingDateInputs)) {
set(draftDateValues, { ...get(dateValues) });
}
set(wasShowingDateInputs, get(showDateInputs));
}
);
legacy_pre_effect_reset();
var $$exports = {
get task() {
return task();
},
set task($$value) {
task($$value);
flushSync();
},
get taskActions() {
return taskActions();
},
set taskActions($$value) {
taskActions($$value);
flushSync();
},
get propertySchemaOption() {
return propertySchemaOption();
},
set propertySchemaOption($$value) {
propertySchemaOption($$value);
flushSync();
},
get isTaskEditing() {
return isTaskEditing();
},
set isTaskEditing($$value) {
isTaskEditing($$value);
flushSync();
},
get onEditingDatesChange() {
return onEditingDatesChange();
},
set onEditingDatesChange($$value) {
onEditingDatesChange($$value);
flushSync();
},
$set: update_legacy_props,
$on: ($$event_name, $$event_cb) => add_legacy_event_listener($$props, $$event_name, $$event_cb)
};
init();
var fragment = comment();
var node = first_child(fragment);
{
var consequent = ($$anchor2) => {
var div = root9();
var button = child(div);
reset(div);
event("mousedown", button, stopPropagation(function($$arg) {
bubble_event.call(this, $$props, $$arg);
}));
event("mouseup", button, stopPropagation(function($$arg) {
bubble_event.call(this, $$props, $$arg);
}));
event("click", button, openDateEditor);
event("keydown", button, stopPropagation(function($$arg) {
bubble_event.call(this, $$props, $$arg);
}));
append($$anchor2, div);
};
var consequent_1 = ($$anchor2) => {
var div_1 = root_16();
var node_1 = child(div_1);
DateInputFields(node_1, {
get values() {
return get(draftDateValues);
},
onDateChange: handleDraftDateChange,
showDoneButton: true,
onDone: saveDraftDates
});
reset(div_1);
event("mousedown", div_1, pinDateEditing, true);
event("focusin", div_1, pinDateEditing);
append($$anchor2, div_1);
};
if_block(node, ($$render) => {
if (get(showReadChips)) $$render(consequent);
else if (get(showDateInputs)) $$render(consequent_1, 1);
});
}
append($$anchor, fragment);
return pop($$exports);
}
// src/ui/components/task.svelte
var import_obsidian6 = require("obsidian");
// src/ui/components/task_markdown.ts
function renderTaskMarkdownSource({
content,
displayStatus,
blockLink,
excludedTags = []
}) {
let contentWithBlockLink = (content + (blockLink ? ` ^${blockLink}` : "")).replaceAll("<br />", "\n");
for (const tag2 of excludedTags) {
contentWithBlockLink = stripTagFromRenderedContent(contentWithBlockLink, tag2);
}
const indentedContinuationLines = contentWithBlockLink.replaceAll("\n", "\n ");
return `- [${displayStatus || " "}] ${indentedContinuationLines}`;
}
function stripTagFromRenderedContent(content, tag2) {
const normalizedTag = tag2.trim().replace(/^#/, "");
if (!normalizedTag) return content;
const escapedTag = normalizedTag.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
return content.replace(new RegExp(`(^|\\s)#${escapedTag}(?=$|\\s|[^-_/\\p{L}\\p{N}])`, "giu"), "$1").trim();
}
// src/ui/components/task.svelte
var root10 = from_html(`<textarea></textarea>`);
var root_17 = from_html(`<div role="button" class="content-preview markdown-rendered svelte-1fvsaoa" tabindex="0"></div>`);
var root_25 = from_html(`<div><span role="button" tabindex="0"> </span> <div class="task-progress-bar-container svelte-1fvsaoa"><div class="task-progress-bar svelte-1fvsaoa"></div></div> <span class="task-progress-text svelte-1fvsaoa"> </span></div>`);
var root_33 = from_html(`<div class="task-row-content svelte-1fvsaoa"><!> <!></div>`);
var root_43 = from_html(`<button role="checkbox" tabindex="0"><!></button>`);
var root_52 = from_html(`<button role="checkbox" aria-label="Advance status" tabindex="0"><!></button>`);
var root_62 = from_html(`<button class="icon-button pin-marker svelte-1fvsaoa" aria-label="Unpin task (return to file order)" title="Pinned \u2014 click to unpin" tabindex="0"><!></button>`);
var root_72 = from_html(`<span class="drag-handle svelte-1fvsaoa" title="Drag to reorder" aria-hidden="true"><!></span>`);
var root_8 = from_html(`<!> <!> <!>`, 1);
var root_9 = from_html(`<div class="add-subtask-container svelte-1fvsaoa"><div class="add-subtask-btn svelte-1fvsaoa" role="button" tabindex="0"><span aria-hidden="true" class="svelte-1fvsaoa">+</span> Subtask</div></div>`);
var root_10 = from_html(`<!> <!>`, 1);
var root_11 = from_html(`<span class="svelte-1fvsaoa"><span class="cm-formatting cm-formatting-hashtag cm-hashtag cm-hashtag-begin cm-list-1 svelte-1fvsaoa">#</span><span class="cm-hashtag cm-hashtag-end cm-list-1 svelte-1fvsaoa"> </span></span>`);
var root_122 = from_html(`<div class="task-tags svelte-1fvsaoa"></div>`);
var root_132 = from_html(`<div class="task-properties-debug svelte-1fvsaoa"><pre class="svelte-1fvsaoa"><code> </code></pre></div>`);
var root_142 = from_html(`<span class="task-property-icon svelte-1fvsaoa"> </span>`);
var root_152 = from_html(`<span class="task-property-label svelte-1fvsaoa"> </span>`);
var root_162 = from_html(`<span class="task-property svelte-1fvsaoa"><!> <span class="task-property-value svelte-1fvsaoa"> </span></span>`);
var root_172 = from_html(`<div class="task-properties svelte-1fvsaoa"></div>`);
var root_18 = from_html(`<span><!> <span class="task-property-value svelte-1fvsaoa"> </span></span>`);
var root_19 = from_html(`<div class="task-properties task-date-properties svelte-1fvsaoa"><!> <!></div>`);
var root_20 = from_html(`<div class="task-footer svelte-1fvsaoa"><button class="go-to-file-button svelte-1fvsaoa" aria-label="Go to file" title="Go to file" tabindex="0"><!> <span class="file-path svelte-1fvsaoa"> </span></button></div>`);
var root_21 = from_html(`<div role="group"><!> <!> <!> <!> <!> <!></div>`);
var $$css10 = {
hash: "svelte-1fvsaoa",
code: '.task.svelte-1fvsaoa {--task-accent: var(--task-accent-color, var(--background-modifier-border-hover));--task-content-line-height: 1.5rem;--task-footer-line-height: 1.15;--task-footer-block-padding: 2px;position:relative;overflow:hidden;background:var(--background-primary);border-radius:var(--radius-s);border:var(--border-width) solid var(--background-modifier-border);cursor:grab;box-shadow:0 1px 2px rgba(0, 0, 0, 0.06);transition:border-color 0.15s ease, box-shadow 0.15s ease, transform 0.15s ease;}.task.svelte-1fvsaoa::before {content:"";position:absolute;inset:0 auto 0 0;width:8px;background:var(--task-accent);}.task.svelte-1fvsaoa:hover {border-color:color-mix(in srgb, var(--text-muted) 45%, var(--background-modifier-border));box-shadow:0 8px 22px rgba(0, 0, 0, 0.08);transform:translateY(-1px);}.task.is-dragging.svelte-1fvsaoa {opacity:0.15;}.task.is-selected.svelte-1fvsaoa {border-color:var(--interactive-accent);background:color-mix(in srgb, var(--interactive-accent) 8%, var(--background-primary));}.task.svelte-1fvsaoa .task-row-content:where(.svelte-1fvsaoa) {min-width:0;}.task.svelte-1fvsaoa .task-row-content:where(.svelte-1fvsaoa) textarea:where(.svelte-1fvsaoa) {cursor:text;background-color:var(--color-base-25);width:100%;}.task.svelte-1fvsaoa .task-row-content:where(.svelte-1fvsaoa) .content-preview:where(.svelte-1fvsaoa) {min-height:var(--task-content-line-height);}.task.svelte-1fvsaoa .task-row-content:where(.svelte-1fvsaoa) .content-preview:where(.svelte-1fvsaoa):focus {box-shadow:0 0 0 3px var(--background-modifier-border-focus);}.task.svelte-1fvsaoa .icon-button:where(.svelte-1fvsaoa) {display:flex;justify-content:center;align-items:center;width:20px;height:20px;padding:0;border:none;background:transparent;cursor:pointer;border-radius:var(--radius-s);transition:opacity 0.2s ease;box-shadow:none;overflow:visible;}.task.svelte-1fvsaoa .icon-button:where(.svelte-1fvsaoa):hover, .task.svelte-1fvsaoa .icon-button:where(.svelte-1fvsaoa):active {background:transparent;box-shadow:none;}.task.svelte-1fvsaoa .icon-button:where(.svelte-1fvsaoa):focus-visible {outline:2px solid var(--background-modifier-border-focus);outline-offset:2px;}.task.svelte-1fvsaoa .icon-button.select-task:where(.svelte-1fvsaoa):hover svg {opacity:0.8 !important;color:var(--interactive-accent);}.task.svelte-1fvsaoa .icon-button.select-task.is-selected:where(.svelte-1fvsaoa) svg {color:var(--interactive-accent);}.task.svelte-1fvsaoa .icon-button.pin-marker:where(.svelte-1fvsaoa) svg {color:var(--interactive-accent);}.task.svelte-1fvsaoa .icon-button.pin-marker:where(.svelte-1fvsaoa):hover svg {opacity:1 !important;}.task.svelte-1fvsaoa .icon-button.usesStatusMarker:where(.svelte-1fvsaoa) {color:var(--text-normal);}.task.svelte-1fvsaoa .drag-handle:where(.svelte-1fvsaoa) {display:flex;align-items:center;justify-content:center;width:22px;height:22px;cursor:grab;}.task.svelte-1fvsaoa .task-footer:where(.svelte-1fvsaoa) {border-top:var(--border-width) solid var(--background-modifier-border);padding:var(--task-footer-block-padding) var(--size-4-2) var(--task-footer-block-padding) calc(var(--size-4-2) + 8px);font-size:var(--font-ui-smaller);line-height:var(--task-footer-line-height);display:flex;align-items:center;min-height:0;}.task.svelte-1fvsaoa .task-footer:where(.svelte-1fvsaoa) .go-to-file-button:where(.svelte-1fvsaoa) {display:inline-flex;align-items:center;justify-content:flex-start;gap:var(--size-2-1);width:auto;max-width:100%;padding:0;min-height:0;height:auto;border:none;background:transparent;cursor:pointer;text-align:left;box-shadow:none;transition:opacity 0.2s ease;border-radius:var(--radius-s);font:inherit;line-height:inherit;}.task.svelte-1fvsaoa .task-footer:where(.svelte-1fvsaoa) .go-to-file-button:where(.svelte-1fvsaoa):hover {background:transparent;box-shadow:none;}.task.svelte-1fvsaoa .task-footer:where(.svelte-1fvsaoa) .go-to-file-button:where(.svelte-1fvsaoa):hover svg {opacity:1 !important;color:var(--interactive-accent);}.task.svelte-1fvsaoa .task-footer:where(.svelte-1fvsaoa) .go-to-file-button:where(.svelte-1fvsaoa):hover .file-path:where(.svelte-1fvsaoa) {color:var(--interactive-accent);}.task.svelte-1fvsaoa .task-footer:where(.svelte-1fvsaoa) .go-to-file-button:where(.svelte-1fvsaoa):focus-visible {outline:2px solid var(--background-modifier-border-focus);outline-offset:2px;}.task.svelte-1fvsaoa .task-footer:where(.svelte-1fvsaoa) .go-to-file-button:where(.svelte-1fvsaoa) .file-path:where(.svelte-1fvsaoa) {margin:0;color:var(--text-muted);transition:color 0.2s ease;overflow-wrap:anywhere;white-space:normal;min-width:0;line-height:inherit;}.task.svelte-1fvsaoa .task-footer:where(.svelte-1fvsaoa) .go-to-file-button:where(.svelte-1fvsaoa) svg {width:1em;height:1em;}.task.svelte-1fvsaoa .task-tags:where(.svelte-1fvsaoa) {display:flex;flex-wrap:wrap;gap:var(--size-2-1);padding:0 var(--size-4-2) var(--size-4-2) calc(var(--size-4-2) + 8px);margin-top:calc(-1 * var(--size-2-2));}.task.svelte-1fvsaoa .task-tags:where(.svelte-1fvsaoa) span:where(.svelte-1fvsaoa) {background-color:var(--background-secondary);color:var(--text-muted);border:1px solid var(--background-modifier-border);border-radius:var(--radius-s);padding:1px 5px;font-size:var(--font-ui-smaller);line-height:1.1;display:inline-flex;align-items:center;transition:color 0.15s ease, border-color 0.15s ease;}.task.svelte-1fvsaoa .task-tags:where(.svelte-1fvsaoa) span:where(.svelte-1fvsaoa):hover {color:var(--text-normal);border-color:var(--text-muted);}.task.svelte-1fvsaoa .task-tags:where(.svelte-1fvsaoa) span:where(.svelte-1fvsaoa) .cm-formatting-hashtag {color:var(--text-accent) !important;font-weight:var(--font-medium);margin-right:1px;}.task.svelte-1fvsaoa .task-tags:where(.svelte-1fvsaoa) span:where(.svelte-1fvsaoa) .cm-hashtag-end {color:inherit !important;}.task.svelte-1fvsaoa .task-properties-debug:where(.svelte-1fvsaoa) {padding:var(--size-2-3) var(--size-4-2) var(--size-2-3) calc(var(--size-4-2) + 8px);border-top:var(--border-width) solid var(--background-modifier-border);background-color:var(--background-secondary-alt);font-size:var(--font-ui-smaller);overflow-x:auto;}.task.svelte-1fvsaoa .task-properties-debug:where(.svelte-1fvsaoa) pre:where(.svelte-1fvsaoa) {margin:0;}.task.svelte-1fvsaoa .task-properties:where(.svelte-1fvsaoa) {display:flex;flex-wrap:wrap;gap:var(--size-2-2);padding:var(--task-footer-block-padding) var(--size-4-2) var(--task-footer-block-padding) calc(var(--size-4-2) + 8px);border-top:var(--border-width) solid var(--background-modifier-border);font-size:var(--font-ui-smaller);line-height:var(--task-footer-line-height);}.task.svelte-1fvsaoa .task-date-properties:where(.svelte-1fvsaoa) {align-items:center;}.task.svelte-1fvsaoa .task-date-properties:where(.svelte-1fvsaoa) .edit-mode {flex-basis:100%;}.task.svelte-1fvsaoa .task-property:where(.svelte-1fvsaoa) {display:inline-flex;align-items:baseline;gap:var(--size-2-1);padding:0 var(--size-2-2);border-radius:var(--radius-s);background-color:var(--background-secondary-alt);line-height:inherit;}.task.svelte-1fvsaoa .task-property-label:where(.svelte-1fvsaoa) {color:var(--text-muted);text-transform:uppercase;font-size:var(--font-smallest);letter-spacing:0.02em;}.task.svelte-1fvsaoa .task-property.dataview-property:where(.svelte-1fvsaoa) .task-property-label:where(.svelte-1fvsaoa) {text-transform:none;letter-spacing:0;}.task.svelte-1fvsaoa .task-property-icon:where(.svelte-1fvsaoa) {font-size:inherit;line-height:1;}.task.svelte-1fvsaoa .task-property-value:where(.svelte-1fvsaoa) {color:var(--text-normal);}.task-row-content img {max-width:100%;max-height:160px;object-fit:contain;}.task-row-content code {white-space:pre-wrap;}.task-row-content .content-preview,\n.task-row-content .content-preview > ul,\n.task-row-content .content-preview > ul > li,\n.task-row-content .content-preview > ul > li > p {margin:0;}.task .task-row-content .content-preview > ul {padding-left:0 !important;margin:0 !important;list-style:none !important;}.task-row-content .content-preview .task-list-item {min-width:0;word-break:break-word;padding-left:0 !important;list-style-type:none !important;}.task-row-content input.task-nested-checkbox {pointer-events:none;}.task-row-content .content-preview .task-list-item > input[type="checkbox"].task-primary-checkbox {display:none !important;}.task-row-content .content-preview .task-list-item > *:not(input[type="checkbox"]) {min-width:0;}.task-progress-wrapper.svelte-1fvsaoa {display:flex;align-items:center;gap:var(--size-4-2);margin-top:var(--size-2-2);margin-bottom:var(--size-2-1);}.task-progress-wrapper.is-complete.svelte-1fvsaoa .task-progress-bar:where(.svelte-1fvsaoa) {background-color:hsl(140, 75%, 45%);background-image:linear-gradient(90deg, hsl(140, 75%, 40%) 0%, hsl(140, 75%, 50%) 100%);box-shadow:0 0 6px hsla(140, 75%, 45%, 0.3);}.task-progress-wrapper.is-complete.svelte-1fvsaoa .task-progress-text:where(.svelte-1fvsaoa) {color:hsl(140, 75%, 45%);font-weight:var(--font-bold);}.task-progress-bar-container.svelte-1fvsaoa {flex:1;height:6px;background-color:var(--background-modifier-border);border-radius:3px;overflow:hidden;box-shadow:inset 0 1px 2px rgba(0, 0, 0, 0.05);}.task-progress-bar.svelte-1fvsaoa {height:100%;background-color:var(--interactive-accent);background-image:linear-gradient(90deg, hsla(var(--accent-h, 210), var(--accent-s, 75%), calc(var(--accent-l, 50%) - 5%), 0.95) 0%, var(--interactive-accent) 100%);border-radius:3px;transition:width 0.4s cubic-bezier(0.4, 0, 0.2, 1), background-color 0.3s ease, background-image 0.3s ease;box-shadow:0 1px 2px rgba(0, 0, 0, 0.1);}.task-progress-text.svelte-1fvsaoa {font-size:var(--font-ui-smaller);color:var(--text-muted);font-weight:var(--font-medium);white-space:nowrap;transition:color 0.3s ease;}.subtask-collapse-btn.svelte-1fvsaoa {background:transparent;border:none;box-shadow:none;padding:0;color:var(--text-muted);font-size:10px;cursor:pointer;display:flex;align-items:center;justify-content:center;width:var(--task-line-marker-size, 20px);height:14px;line-height:1;flex-shrink:0;transition:color 0.15s ease;\n /* Shift to the left under the checkbox */margin-left:calc(-1 * (var(--task-line-marker-size, 20px) + var(--task-line-column-gap, var(--size-2-3))));margin-right:var(--task-line-column-gap, var(--size-2-3));}.subtask-collapse-btn.svelte-1fvsaoa:hover {color:var(--text-normal);background:transparent;}.add-subtask-container.svelte-1fvsaoa {padding:var(--size-2-2) var(--size-4-2) var(--size-2-2) calc(var(--size-4-2) + 8px);}.add-subtask-btn.svelte-1fvsaoa {display:inline-flex;align-items:center;gap:var(--size-2-1);align-self:flex-start;cursor:pointer;border:0;border-radius:var(--radius-s);box-shadow:none;margin:0;min-height:22px;padding:0;background:transparent;background-color:transparent;color:var(--text-accent);font-size:var(--font-ui-smaller);font-weight:var(--font-medium);line-height:1.2;}.add-subtask-btn.svelte-1fvsaoa span:where(.svelte-1fvsaoa) {display:inline-flex;align-items:center;justify-content:center;font-size:var(--font-ui-small);line-height:1;}.add-subtask-btn.svelte-1fvsaoa:hover {color:var(--text-accent-hover);background:transparent;background-color:transparent;}.add-subtask-btn.svelte-1fvsaoa:active {color:var(--text-accent-hover);background:transparent;background-color:transparent;}'
};
function Task2($$anchor, $$props) {
if (new.target) return createClassComponent({ component: Task2, ...$$anchor });
push($$props, false);
append_styles($$anchor, $$css10);
const displayStatusIsCustom = mutable_source();
const excludedTagNames = mutable_source();
const visibleTags = mutable_source();
const shouldconsolidateTags = mutable_source();
const dateEditingEnabled = mutable_source();
const displayProperties = mutable_source();
const dateDisplayProperties = mutable_source();
const nonDateDisplayProperties = mutable_source();
const dateProperties = mutable_source();
const visibleSubtasks = mutable_source();
const totalSubtasksCount = mutable_source();
const completedSubtasksCount = mutable_source();
const completionPercentage = mutable_source();
let app = prop($$props, "app", 12);
let task = prop($$props, "task", 12);
let taskActions = prop($$props, "taskActions", 12);
let columnTagTableStore = prop($$props, "columnTagTableStore", 12);
let showFilepath = prop($$props, "showFilepath", 12);
let propertyDisplay = prop($$props, "propertyDisplay", 28, () => "none" /* None */);
let propertySchemaOption = prop($$props, "propertySchemaOption", 28, () => "none" /* None */);
let consolidateTags = prop($$props, "consolidateTags", 12);
let excludedTags = prop($$props, "excludedTags", 28, () => []);
let displayColumn = prop($$props, "displayColumn", 12);
let displaySecondaryId = prop($$props, "displaySecondaryId", 12);
let isSelectionMode = prop($$props, "isSelectionMode", 12, false);
let isSelected = prop($$props, "isSelected", 12, false);
let onToggleSelection = prop($$props, "onToggleSelection", 12, () => {
});
let selectedTaskIds = prop($$props, "selectedTaskIds", 28, () => []);
let taskSecondaryIds = prop($$props, "taskSecondaryIds", 28, () => ({}));
let doneColumnName = prop($$props, "doneColumnName", 12, void 0);
let accentColor = prop($$props, "accentColor", 12, void 0);
let isManualOrder = prop($$props, "isManualOrder", 12, false);
let isPinned = prop($$props, "isPinned", 12, false);
let showDragHandle = prop($$props, "showDragHandle", 12, false);
let onUnpin = prop($$props, "onUnpin", 12, () => {
});
let treatNestedTasksAsSubtasks = prop($$props, "treatNestedTasksAsSubtasks", 12, false);
function handleContentBlur() {
var _a5;
set(isEditing, false);
const content = (_a5 = get(textAreaEl)) == null ? void 0 : _a5.value;
if (!content) return;
const updatedContent = content.replaceAll("\n", "<br />");
taskActions().updateContent(task().id, updatedContent);
}
function handleKeypress(e) {
var _a5;
if (e.key === "Enter" && !e.shiftKey || e.key === "Escape") {
(_a5 = get(textAreaEl)) == null ? void 0 : _a5.blur();
}
}
function handleOpenKeypress(e) {
if (e.key === "Enter" || e.key === " ") {
handleFocus(e);
}
}
let isEditing = mutable_source(false);
let isDragging = mutable_source(false);
let isSubtasksCollapsed = mutable_source(false);
function toggleSubtasksCollapse() {
set(isSubtasksCollapsed, !get(isSubtasksCollapsed));
}
function handleDragStart(e) {
handleContentBlur();
set(isDragging, true);
const taskIds = isSelectionMode() && isSelected() && selectedTaskIds().length > 0 ? selectedTaskIds() : [task().id];
isDraggingStore.set({
fromColumn: displayColumn(),
fromSecondaryId: displaySecondaryId(),
draggedTaskIds: taskIds,
taskSecondaryIds: taskSecondaryIds()
});
if (e.dataTransfer) {
e.dataTransfer.setData("text/plain", task().id);
e.dataTransfer.dropEffect = "move";
}
if (taskIds.length > 1 && e.dataTransfer) {
const ghost = document.createElement("div");
ghost.textContent = `Moving ${taskIds.length} tasks`;
ghost.style.cssText = [
"position:fixed",
"top:-9999px",
"left:-9999px",
"padding:6px 12px",
"background:var(--background-secondary-alt)",
"border:1px solid var(--background-modifier-border)",
"border-radius:var(--radius-m)",
"font-size:var(--font-ui-small)",
"color:var(--text-normal)",
"box-shadow:var(--shadow-s)",
"white-space:nowrap"
].join(";");
document.body.appendChild(ghost);
e.dataTransfer.setDragImage(ghost, 0, 0);
setTimeout(() => document.body.removeChild(ghost), 0);
}
}
function handleDragEnd() {
set(isDragging, false);
isDraggingStore.set(null);
}
let textAreaEl = mutable_source();
let previewContainerEl = mutable_source();
let markdownComponent;
let isEditingDates = mutable_source(false);
const editableDatePropertyKeys = new Set(EDITABLE_DATE_PROPERTY_KEYS);
const interactiveTagNames = /* @__PURE__ */ new Set([
"a",
"button",
"input",
"select",
"textarea",
"label",
"summary",
"details"
]);
function eventHasInteractiveTarget(e) {
if (e instanceof MouseEvent && get(previewContainerEl)) {
const rect = get(previewContainerEl).getBoundingClientRect();
const relativeX = e.clientX - rect.left;
if (relativeX >= 0 && relativeX < 28) {
return true;
}
}
const path = (e == null ? void 0 : e.composedPath()) || [];
const currentTarget = e == null ? void 0 : e.currentTarget;
for (const element2 of path) {
if (!(element2 instanceof HTMLElement)) {
continue;
}
if (currentTarget instanceof HTMLElement && element2 === currentTarget) {
continue;
}
if (interactiveTagNames.has(element2.tagName.toLowerCase())) {
return true;
}
if (element2.isContentEditable) {
return true;
}
const role = element2.getAttribute("role");
if (role === "button" || role === "checkbox" || role === "link") {
return true;
}
}
return false;
}
function handleFocus(e) {
if (eventHasInteractiveTarget(e)) {
return;
}
set(isEditing, true);
setTimeout(
() => {
var _a5;
(_a5 = get(textAreaEl)) == null ? void 0 : _a5.focus();
},
100
);
}
function renderTaskMarkdown() {
let body = task().content;
if (task().properties) {
if (propertyDisplay() === "pretty" /* Pretty */) {
body = stripDisplayedPropertiesFromContent(body, task().properties);
} else if (get(dateEditingEnabled)) {
body = stripDisplayedPropertiesFromContent(body, get(dateProperties));
}
}
return renderTaskMarkdownSource({
content: body,
displayStatus: task().displayStatus,
blockLink: task().blockLink,
excludedTags: excludedTags()
});
}
async function renderMarkdown(selectionMode) {
if (!get(previewContainerEl)) return;
if (markdownComponent) {
markdownComponent.unload();
}
get(previewContainerEl).empty();
markdownComponent = new import_obsidian6.Component();
const contentToRender = renderTaskMarkdown();
await import_obsidian6.MarkdownRenderer.render(app(), contentToRender, get(previewContainerEl), task().path, markdownComponent);
setupLinkHandlers();
postProcessRenderedContent(selectionMode);
}
function setupLinkHandlers() {
if (!get(previewContainerEl)) return;
const internalLinks = get(previewContainerEl).querySelectorAll("a.internal-link");
internalLinks.forEach((link2) => {
const anchorEl = link2;
anchorEl.addEventListener("click", (e) => {
e.preventDefault();
e.stopPropagation();
const linkTarget = anchorEl.getAttribute("data-href");
if (linkTarget && app()) {
app().workspace.openLinkText(linkTarget, task().path, import_obsidian6.Keymap.isModEvent(e));
}
});
anchorEl.addEventListener("mouseover", (e) => {
const linkTarget = anchorEl.getAttribute("data-href");
if (linkTarget && app() && get(previewContainerEl)) {
app().workspace.trigger("hover-link", {
event: e,
source: "kanban-view",
hoverParent: get(previewContainerEl),
targetEl: anchorEl,
linktext: linkTarget,
sourcePath: task().path
});
}
});
});
}
function postProcessRenderedContent(selectionMode) {
if (!get(previewContainerEl)) return;
function stopPropagation2(e) {
e.stopPropagation();
}
function handlePrimaryCheckboxClick(e) {
e.preventDefault();
e.stopPropagation();
void taskActions().toggleDone(task().id);
}
get(previewContainerEl).querySelectorAll("a:not(.internal-link)").forEach((a) => {
const anchor = a;
anchor.target = "_blank";
anchor.rel = "noopener noreferrer";
anchor.addEventListener("click", stopPropagation2);
anchor.addEventListener("keypress", stopPropagation2);
});
const checkboxes = Array.from(get(previewContainerEl).querySelectorAll('input[type="checkbox"]'));
const [primaryCheckbox, ...nestedCheckboxes] = checkboxes;
if (primaryCheckbox) {
primaryCheckbox.classList.add("task-primary-checkbox");
primaryCheckbox.addEventListener("mousedown", stopPropagation2);
primaryCheckbox.addEventListener("mouseup", stopPropagation2);
primaryCheckbox.addEventListener("keypress", stopPropagation2);
if (selectionMode) {
primaryCheckbox.disabled = true;
primaryCheckbox.tabIndex = -1;
primaryCheckbox.style.visibility = "hidden";
primaryCheckbox.setAttribute("aria-hidden", "true");
primaryCheckbox.addEventListener("click", stopPropagation2);
} else {
primaryCheckbox.disabled = false;
primaryCheckbox.style.removeProperty("visibility");
primaryCheckbox.removeAttribute("aria-hidden");
primaryCheckbox.setAttribute("aria-label", "Advance status");
primaryCheckbox.addEventListener("click", handlePrimaryCheckboxClick);
}
}
nestedCheckboxes.forEach((checkbox) => {
checkbox.classList.add("task-nested-checkbox");
checkbox.disabled = true;
checkbox.tabIndex = -1;
checkbox.addEventListener("click", stopPropagation2);
checkbox.addEventListener("keypress", stopPropagation2);
});
get(previewContainerEl).querySelectorAll("iframe, audio, video").forEach((el) => {
el.remove();
});
}
let lastRenderedMarkdownKey = mutable_source("");
onDestroy(() => {
if (markdownComponent) {
markdownComponent.unload();
}
});
function onInput(e) {
e.currentTarget.style.height = `0px`;
e.currentTarget.style.height = `${e.currentTarget.scrollHeight}px`;
}
legacy_pre_effect(() => deep_read_state(task()), () => {
set(displayStatusIsCustom, task().displayStatus !== " ");
});
legacy_pre_effect(() => get(isEditing), () => {
if (get(isEditing)) {
set(lastRenderedMarkdownKey, "");
}
});
legacy_pre_effect(
() => (deep_read_state(task()), deep_read_state(propertyDisplay()), get(isEditing), get(previewContainerEl), deep_read_state(isSelectionMode()), get(lastRenderedMarkdownKey)),
() => {
if (task() && task().content && task().displayStatus && propertyDisplay() && !get(isEditing) && get(previewContainerEl)) {
const markdownKey = JSON.stringify({
source: renderTaskMarkdown(),
path: task().path,
selectionMode: isSelectionMode()
});
if (markdownKey !== get(lastRenderedMarkdownKey)) {
set(lastRenderedMarkdownKey, markdownKey);
void renderMarkdown(isSelectionMode());
}
}
}
);
legacy_pre_effect(() => get(textAreaEl), () => {
if (get(textAreaEl)) {
mutate(textAreaEl, get(textAreaEl).style.height = `0px`);
mutate(textAreaEl, get(textAreaEl).style.height = `${get(textAreaEl).scrollHeight}px`);
}
});
legacy_pre_effect(() => deep_read_state(excludedTags()), () => {
set(excludedTagNames, excludedTags().map((tag2) => tag2.trim().replace(/^#/, "").toLowerCase()));
});
legacy_pre_effect(() => (deep_read_state(task()), get(excludedTagNames)), () => {
set(visibleTags, Array.from(task().tags).filter((t) => !get(excludedTagNames).includes(t.toLowerCase())));
});
legacy_pre_effect(() => (deep_read_state(consolidateTags()), get(visibleTags)), () => {
set(shouldconsolidateTags, consolidateTags() && get(visibleTags).length > 0);
});
legacy_pre_effect(
() => (getPropertyWriteAdapter, deep_read_state(propertySchemaOption())),
() => {
set(dateEditingEnabled, getPropertyWriteAdapter(propertySchemaOption()) !== null);
}
);
legacy_pre_effect(() => (deep_read_state(task()), toDisplayProperties), () => {
set(displayProperties, task().properties ? toDisplayProperties(task().properties) : []);
});
legacy_pre_effect(
() => (get(dateEditingEnabled), get(displayProperties), deep_read_state(propertySchemaOption()), PropertySchemaOption),
() => {
set(dateDisplayProperties, get(dateEditingEnabled) ? get(displayProperties).filter((prop2) => editableDatePropertyKeys.has(prop2.key)).map((prop2) => propertySchemaOption() === "dataview" /* Dataview */ ? { ...prop2, icon: void 0, label: `${prop2.key}::` } : prop2) : []);
}
);
legacy_pre_effect(() => get(displayProperties), () => {
set(nonDateDisplayProperties, get(displayProperties).filter((prop2) => !editableDatePropertyKeys.has(prop2.key)));
});
legacy_pre_effect(() => deep_read_state(task()), () => {
var _a5, _b3;
set(dateProperties, new Map(Array.from((_b3 = (_a5 = task().properties) == null ? void 0 : _a5.entries()) != null ? _b3 : []).filter(([key2]) => editableDatePropertyKeys.has(key2))));
});
legacy_pre_effect(() => (getVisibleSourceTaskDescendants, deep_read_state(task())), () => {
set(visibleSubtasks, getVisibleSourceTaskDescendants(task().sourceChildren));
});
legacy_pre_effect(() => get(visibleSubtasks), () => {
set(totalSubtasksCount, get(visibleSubtasks).length);
});
legacy_pre_effect(() => (get(visibleSubtasks), deep_read_state(task())), () => {
set(completedSubtasksCount, get(visibleSubtasks).filter((node) => task().isSourceTaskStatusDone(node.status)).length);
});
legacy_pre_effect(() => (get(totalSubtasksCount), get(completedSubtasksCount)), () => {
set(completionPercentage, get(totalSubtasksCount) > 0 ? Math.round(get(completedSubtasksCount) / get(totalSubtasksCount) * 100) : 0);
});
legacy_pre_effect_reset();
var $$exports = {
get app() {
return app();
},
set app($$value) {
app($$value);
flushSync();
},
get task() {
return task();
},
set task($$value) {
task($$value);
flushSync();
},
get taskActions() {
return taskActions();
},
set taskActions($$value) {
taskActions($$value);
flushSync();
},
get columnTagTableStore() {
return columnTagTableStore();
},
set columnTagTableStore($$value) {
columnTagTableStore($$value);
flushSync();
},
get showFilepath() {
return showFilepath();
},
set showFilepath($$value) {
showFilepath($$value);
flushSync();
},
get propertyDisplay() {
return propertyDisplay();
},
set propertyDisplay($$value) {
propertyDisplay($$value);
flushSync();
},
get propertySchemaOption() {
return propertySchemaOption();
},
set propertySchemaOption($$value) {
propertySchemaOption($$value);
flushSync();
},
get consolidateTags() {
return consolidateTags();
},
set consolidateTags($$value) {
consolidateTags($$value);
flushSync();
},
get excludedTags() {
return excludedTags();
},
set excludedTags($$value) {
excludedTags($$value);
flushSync();
},
get displayColumn() {
return displayColumn();
},
set displayColumn($$value) {
displayColumn($$value);
flushSync();
},
get displaySecondaryId() {
return displaySecondaryId();
},
set displaySecondaryId($$value) {
displaySecondaryId($$value);
flushSync();
},
get isSelectionMode() {
return isSelectionMode();
},
set isSelectionMode($$value) {
isSelectionMode($$value);
flushSync();
},
get isSelected() {
return isSelected();
},
set isSelected($$value) {
isSelected($$value);
flushSync();
},
get onToggleSelection() {
return onToggleSelection();
},
set onToggleSelection($$value) {
onToggleSelection($$value);
flushSync();
},
get selectedTaskIds() {
return selectedTaskIds();
},
set selectedTaskIds($$value) {
selectedTaskIds($$value);
flushSync();
},
get taskSecondaryIds() {
return taskSecondaryIds();
},
set taskSecondaryIds($$value) {
taskSecondaryIds($$value);
flushSync();
},
get doneColumnName() {
return doneColumnName();
},
set doneColumnName($$value) {
doneColumnName($$value);
flushSync();
},
get accentColor() {
return accentColor();
},
set accentColor($$value) {
accentColor($$value);
flushSync();
},
get isManualOrder() {
return isManualOrder();
},
set isManualOrder($$value) {
isManualOrder($$value);
flushSync();
},
get isPinned() {
return isPinned();
},
set isPinned($$value) {
isPinned($$value);
flushSync();
},
get showDragHandle() {
return showDragHandle();
},
set showDragHandle($$value) {
showDragHandle($$value);
flushSync();
},
get onUnpin() {
return onUnpin();
},
set onUnpin($$value) {
onUnpin($$value);
flushSync();
},
get treatNestedTasksAsSubtasks() {
return treatNestedTasksAsSubtasks();
},
set treatNestedTasksAsSubtasks($$value) {
treatNestedTasksAsSubtasks($$value);
flushSync();
},
$set: update_legacy_props,
$on: ($$event_name, $$event_cb) => add_legacy_event_listener($$props, $$event_name, $$event_cb)
};
init();
var div = root_21();
let classes;
let styles;
var node_1 = child(div);
TaskLineRow(node_1, {
variant: "card",
hasActions: true,
children: ($$anchor2, $$slotProps) => {
var div_1 = root_33();
var node_2 = child(div_1);
{
var consequent = ($$anchor3) => {
var textarea = root10();
remove_textarea_child(textarea);
let classes_1;
bind_this(textarea, ($$value) => set(textAreaEl, $$value), () => get(textAreaEl));
template_effect(
($0) => {
set_value(textarea, $0);
classes_1 = set_class(textarea, 1, "svelte-1fvsaoa", null, classes_1, { editing: get(isEditing) });
},
[
() => (deep_read_state(task()), untrack(() => task().content.replaceAll("<br />", "\n")))
]
);
event("keypress", textarea, handleKeypress);
event("blur", textarea, handleContentBlur);
event("input", textarea, onInput);
append($$anchor3, textarea);
};
var alternate = ($$anchor3) => {
var div_2 = root_17();
bind_this(div_2, ($$value) => set(previewContainerEl, $$value), () => get(previewContainerEl));
event("mouseup", div_2, handleFocus);
event("keypress", div_2, handleOpenKeypress);
append($$anchor3, div_2);
};
if_block(node_2, ($$render) => {
if (get(isEditing)) $$render(consequent);
else $$render(alternate, -1);
});
}
var node_3 = sibling(node_2, 2);
{
var consequent_1 = ($$anchor3) => {
var div_3 = root_25();
let classes_2;
var span = child(div_3);
let classes_3;
var text2 = child(span, true);
reset(span);
var div_4 = sibling(span, 2);
var div_5 = child(div_4);
reset(div_4);
var span_1 = sibling(div_4, 2);
var text_1 = child(span_1);
reset(span_1);
reset(div_3);
template_effect(() => {
var _a5, _b3, _c2, _d;
classes_2 = set_class(div_3, 1, "task-progress-wrapper svelte-1fvsaoa", null, classes_2, { "is-complete": get(completionPercentage) === 100 });
classes_3 = set_class(span, 1, "subtask-collapse-btn svelte-1fvsaoa", null, classes_3, { collapsed: get(isSubtasksCollapsed) });
set_attribute2(span, "aria-label", get(isSubtasksCollapsed) ? "Expand subtasks" : "Collapse subtasks");
set_text(text2, get(isSubtasksCollapsed) ? "\u25B6" : "\u25BC");
set_style(div_5, `width: ${(_a5 = get(completionPercentage)) != null ? _a5 : ""}%`);
set_text(text_1, `${(_b3 = get(completedSubtasksCount)) != null ? _b3 : ""}/${(_c2 = get(totalSubtasksCount)) != null ? _c2 : ""} (${(_d = get(completionPercentage)) != null ? _d : ""}%)`);
});
event("click", span, stopPropagation(toggleSubtasksCollapse));
event("keydown", span, stopPropagation((e) => {
if (e.key === "Enter" || e.key === " ") {
e.preventDefault();
toggleSubtasksCollapse();
}
}));
append($$anchor3, div_3);
};
if_block(node_3, ($$render) => {
if (treatNestedTasksAsSubtasks() && get(totalSubtasksCount) > 0) $$render(consequent_1);
});
}
reset(div_1);
append($$anchor2, div_1);
},
$$slots: {
default: true,
marker: ($$anchor2, $$slotProps) => {
var fragment = comment();
var node_4 = first_child(fragment);
{
var consequent_2 = ($$anchor3) => {
var button = root_43();
let classes_4;
var node_5 = child(button);
{
let $0 = derived_safe_equal(() => isSelected() ? "lucide-check-circle" : "lucide-circle");
let $1 = derived_safe_equal(() => isSelected() ? 1 : 0.5);
Icon(node_5, {
get name() {
return get($0);
},
size: 18,
get opacity() {
return get($1);
}
});
}
reset(button);
template_effect(() => {
classes_4 = set_class(button, 1, "icon-button select-task svelte-1fvsaoa", null, classes_4, { "is-selected": isSelected() });
set_attribute2(button, "aria-label", isSelected() ? "Deselect for bulk actions" : "Select for bulk actions");
set_attribute2(button, "aria-checked", isSelected());
});
event("click", button, function(...$$args) {
var _a5;
(_a5 = onToggleSelection()) == null ? void 0 : _a5.apply(this, $$args);
});
event("keydown", button, (e) => {
if (e.key === "Enter" || e.key === " ") {
e.preventDefault();
onToggleSelection()();
}
});
append($$anchor3, button);
};
var alternate_1 = ($$anchor3) => {
var button_1 = root_52();
let classes_5;
var node_6 = child(button_1);
TaskStatusMarker(node_6, {
get status() {
return deep_read_state(task()), untrack(() => task().displayStatus);
},
get isDone() {
return deep_read_state(task()), untrack(() => task().done);
},
size: 16
});
reset(button_1);
template_effect(() => {
classes_5 = set_class(button_1, 1, "icon-button toggle-done-task svelte-1fvsaoa", null, classes_5, {
"is-done": task().done,
usesStatusMarker: get(displayStatusIsCustom)
});
set_attribute2(button_1, "aria-checked", (deep_read_state(task()), untrack(() => task().done)));
});
event("click", button_1, () => void taskActions().toggleDone(task().id));
event("keydown", button_1, (e) => {
if (e.key === "Enter" || e.key === " ") {
e.preventDefault();
void taskActions().toggleDone(task().id);
}
});
append($$anchor3, button_1);
};
if_block(node_4, ($$render) => {
if (isSelectionMode()) $$render(consequent_2);
else $$render(alternate_1, -1);
});
}
append($$anchor2, fragment);
},
actions: ($$anchor2, $$slotProps) => {
var fragment_1 = root_8();
var node_7 = first_child(fragment_1);
{
var consequent_3 = ($$anchor3) => {
var button_2 = root_62();
var node_8 = child(button_2);
Icon(node_8, { name: "lucide-pin", size: 16, opacity: 0.9 });
reset(button_2);
event("click", button_2, stopPropagation(function(...$$args) {
var _a5;
(_a5 = onUnpin()) == null ? void 0 : _a5.apply(this, $$args);
}));
event("keydown", button_2, (e) => {
if (e.key === "Enter" || e.key === " ") {
e.preventDefault();
e.stopPropagation();
onUnpin()();
}
});
append($$anchor3, button_2);
};
if_block(node_7, ($$render) => {
if (isManualOrder() && isPinned()) $$render(consequent_3);
});
}
var node_9 = sibling(node_7, 2);
{
var consequent_4 = ($$anchor3) => {
var span_2 = root_72();
var node_10 = child(span_2);
Icon(node_10, { name: "lucide-grip-vertical", size: 16, opacity: 0.5 });
reset(span_2);
append($$anchor3, span_2);
};
if_block(node_9, ($$render) => {
if (isManualOrder() && showDragHandle()) $$render(consequent_4);
});
}
var node_11 = sibling(node_9, 2);
Task_menu(node_11, {
get task() {
return task();
},
get taskActions() {
return taskActions();
},
get columnTagTableStore() {
return columnTagTableStore();
},
get doneColumnName() {
return doneColumnName();
}
});
append($$anchor2, fragment_1);
}
}
});
var node_12 = sibling(node_1, 2);
{
var consequent_7 = ($$anchor2) => {
var fragment_2 = root_10();
var node_13 = first_child(fragment_2);
{
var consequent_5 = ($$anchor3) => {
TaskSourceRows($$anchor3, {
get app() {
return app();
},
get task() {
return task();
},
get taskActions() {
return taskActions();
},
get nodes() {
return deep_read_state(task()), untrack(() => task().sourceChildren);
},
get isSelectionMode() {
return isSelectionMode();
},
depth: 1
});
};
if_block(node_13, ($$render) => {
if (deep_read_state(task()), untrack(() => task().sourceChildren.length > 0)) $$render(consequent_5);
});
}
var node_14 = sibling(node_13, 2);
{
var consequent_6 = ($$anchor3) => {
var div_6 = root_9();
var div_7 = child(div_6);
reset(div_6);
event("click", div_7, stopPropagation(() => void taskActions().addSourceBlockRow(task().id, task().rowIndex, "child", "task")));
event("keydown", div_7, stopPropagation((e) => {
if (e.key === "Enter" || e.key === " ") {
e.preventDefault();
void taskActions().addSourceBlockRow(task().id, task().rowIndex, "child", "task");
}
}));
append($$anchor3, div_6);
};
if_block(node_14, ($$render) => {
if (treatNestedTasksAsSubtasks()) $$render(consequent_6);
});
}
append($$anchor2, fragment_2);
};
if_block(node_12, ($$render) => {
if (!get(isSubtasksCollapsed)) $$render(consequent_7);
});
}
var node_15 = sibling(node_12, 2);
{
var consequent_8 = ($$anchor2) => {
var div_8 = root_122();
each(div_8, 5, () => get(visibleTags), index, ($$anchor3, tag2) => {
var span_3 = root_11();
var span_4 = sibling(child(span_3));
var text_2 = child(span_4, true);
reset(span_4);
reset(span_3);
template_effect(() => set_text(text_2, get(tag2)));
append($$anchor3, span_3);
});
reset(div_8);
append($$anchor2, div_8);
};
if_block(node_15, ($$render) => {
if (get(shouldconsolidateTags)) $$render(consequent_8);
});
}
var node_16 = sibling(node_15, 2);
{
var consequent_9 = ($$anchor2) => {
var div_9 = root_132();
var pre = child(div_9);
var code = child(pre);
var text_3 = child(code, true);
reset(code);
reset(pre);
reset(div_9);
template_effect(($0) => set_text(text_3, $0), [
() => (deep_read_state(task()), untrack(() => JSON.stringify(Array.from(task().properties.entries()), null, 2)))
]);
append($$anchor2, div_9);
};
var consequent_12 = ($$anchor2) => {
var fragment_4 = comment();
var node_17 = first_child(fragment_4);
{
var consequent_11 = ($$anchor3) => {
var div_10 = root_172();
each(div_10, 5, () => get(nonDateDisplayProperties), (prop2) => prop2.key, ($$anchor4, prop2) => {
var span_5 = root_162();
var node_18 = child(span_5);
{
var consequent_10 = ($$anchor5) => {
var span_6 = root_142();
var text_4 = child(span_6, true);
reset(span_6);
template_effect(() => {
set_attribute2(span_6, "title", (get(prop2), untrack(() => get(prop2).label)));
set_attribute2(span_6, "aria-label", (get(prop2), untrack(() => get(prop2).label)));
set_text(text_4, (get(prop2), untrack(() => get(prop2).icon)));
});
append($$anchor5, span_6);
};
var alternate_2 = ($$anchor5) => {
var span_7 = root_152();
var text_5 = child(span_7, true);
reset(span_7);
template_effect(() => set_text(text_5, (get(prop2), untrack(() => get(prop2).label))));
append($$anchor5, span_7);
};
if_block(node_18, ($$render) => {
if (get(prop2), untrack(() => get(prop2).icon)) $$render(consequent_10);
else $$render(alternate_2, -1);
});
}
var span_8 = sibling(node_18, 2);
var text_6 = child(span_8, true);
reset(span_8);
reset(span_5);
template_effect(() => set_text(text_6, (get(prop2), untrack(() => get(prop2).value))));
append($$anchor4, span_5);
});
reset(div_10);
append($$anchor3, div_10);
};
if_block(node_17, ($$render) => {
if (get(nonDateDisplayProperties), untrack(() => get(nonDateDisplayProperties).length > 0)) $$render(consequent_11);
});
}
append($$anchor2, fragment_4);
};
if_block(node_16, ($$render) => {
if (deep_read_state(propertyDisplay()), deep_read_state(PropertyDisplayMode), deep_read_state(task()), untrack(() => propertyDisplay() === "debug" /* Debug */ && task().properties && task().properties.size > 0)) $$render(consequent_9);
else if (deep_read_state(propertyDisplay()), deep_read_state(PropertyDisplayMode), deep_read_state(task()), untrack(() => propertyDisplay() === "pretty" /* Pretty */ && task().properties)) $$render(consequent_12, 1);
});
}
var node_19 = sibling(node_16, 2);
{
var consequent_15 = ($$anchor2) => {
var div_11 = root_19();
var node_20 = child(div_11);
TaskDateFields(node_20, {
get task() {
return task();
},
get taskActions() {
return taskActions();
},
get propertySchemaOption() {
return propertySchemaOption();
},
get isTaskEditing() {
return get(isEditing);
},
onEditingDatesChange: (editing) => set(isEditingDates, editing)
});
var node_21 = sibling(node_20, 2);
{
var consequent_14 = ($$anchor3) => {
var fragment_5 = comment();
var node_22 = first_child(fragment_5);
each(node_22, 1, () => get(dateDisplayProperties), (prop2) => prop2.key, ($$anchor4, prop2) => {
var span_9 = root_18();
let classes_6;
var node_23 = child(span_9);
{
var consequent_13 = ($$anchor5) => {
var span_10 = root_142();
var text_7 = child(span_10, true);
reset(span_10);
template_effect(() => {
set_attribute2(span_10, "title", (get(prop2), untrack(() => get(prop2).label)));
set_attribute2(span_10, "aria-label", (get(prop2), untrack(() => get(prop2).label)));
set_text(text_7, (get(prop2), untrack(() => get(prop2).icon)));
});
append($$anchor5, span_10);
};
var alternate_3 = ($$anchor5) => {
var span_11 = root_152();
var text_8 = child(span_11, true);
reset(span_11);
template_effect(() => set_text(text_8, (get(prop2), untrack(() => get(prop2).label))));
append($$anchor5, span_11);
};
if_block(node_23, ($$render) => {
if (get(prop2), untrack(() => get(prop2).icon)) $$render(consequent_13);
else $$render(alternate_3, -1);
});
}
var span_12 = sibling(node_23, 2);
var text_9 = child(span_12, true);
reset(span_12);
reset(span_9);
template_effect(() => {
classes_6 = set_class(span_9, 1, "task-property svelte-1fvsaoa", null, classes_6, {
"dataview-property": propertySchemaOption() === "dataview" /* Dataview */
});
set_text(text_9, (get(prop2), untrack(() => get(prop2).value)));
});
append($$anchor4, span_9);
});
append($$anchor3, fragment_5);
};
if_block(node_21, ($$render) => {
if (!get(isEditingDates)) $$render(consequent_14);
});
}
reset(div_11);
append($$anchor2, div_11);
};
if_block(node_19, ($$render) => {
if (get(dateEditingEnabled)) $$render(consequent_15);
});
}
var node_24 = sibling(node_19, 2);
{
var consequent_16 = ($$anchor2) => {
var div_12 = root_20();
var button_3 = child(div_12);
var node_25 = child(button_3);
Icon(node_25, { name: "lucide-arrow-up-right", size: 18, opacity: 0.5 });
var span_13 = sibling(node_25, 2);
var text_10 = child(span_13, true);
reset(span_13);
reset(button_3);
reset(div_12);
template_effect(() => set_text(text_10, (deep_read_state(task()), untrack(() => task().path))));
event("click", button_3, (e) => taskActions().viewFile(task().id, e));
event("keydown", button_3, (e) => {
if (e.key === "Enter" || e.key === " ") {
e.preventDefault();
taskActions().viewFile(task().id, e);
}
});
append($$anchor2, div_12);
};
if_block(node_24, ($$render) => {
if (showFilepath()) $$render(consequent_16);
});
}
reset(div);
template_effect(() => {
classes = set_class(div, 1, "task svelte-1fvsaoa", null, classes, {
"is-dragging": get(isDragging),
"is-selected": isSelectionMode() && isSelected(),
"is-selection-mode": isSelectionMode()
});
set_attribute2(div, "draggable", !get(isEditing));
styles = set_style(div, "", styles, { "--task-accent-color": accentColor() });
});
event("dragstart", div, handleDragStart);
event("dragend", div, handleDragEnd);
append($$anchor, div);
return pop($$exports);
}
// src/ui/board/NewTaskControls.svelte
var root11 = from_html(`<span class="file-indicator-label svelte-1f00z8">(default)</span>`);
var root_110 = from_html(`<div><span class="file-indicator-arrow svelte-1f00z8">\u2192</span> <span class="file-indicator-name svelte-1f00z8"> </span> <!></div>`);
var root_26 = from_html(`<div><div role="button"><span aria-hidden="true" class="svelte-1f00z8">+</span> Task</div> <!></div> <!>`, 1);
var root_34 = from_html(`<div class="new-task-date-fields svelte-1f00z8"><!></div>`);
var root_44 = from_html(`<div><textarea placeholder="Task name..." class="svelte-1f00z8"></textarea> <!></div>`);
var root_53 = from_html(`<!> <!>`, 1);
var $$css11 = {
hash: "svelte-1f00z8",
code: "/*\n * These elements are direct flex children of BoardCell's .tasks-wrapper\n * (Svelte components do not add a wrapper element). In vertical flow the\n * wrapper reorders its children; the order values here must stay in sync\n * with .tasks (order 1) in BoardCell.\n */.add-new-controls.vertical-flow.svelte-1f00z8 {order:2;}.file-indicator.vertical-flow.svelte-1f00z8 {order:3;}.new-task-input.vertical-flow.svelte-1f00z8 {order:4;width:var(--column-width, 300px);box-sizing:border-box;}.new-task-input.svelte-1f00z8 {margin-top:var(--size-4-3);background-color:var(--background-primary);border-radius:var(--radius-s);border:var(--border-width) solid var(--background-modifier-border);padding:var(--size-4-2);}.new-task-input.svelte-1f00z8 textarea:where(.svelte-1f00z8) {cursor:text;background-color:var(--color-base-25);width:100%;}.new-task-date-fields.svelte-1f00z8 {margin-top:var(--size-2-3);}.add-new-btn.svelte-1f00z8 {display:inline-flex;align-items:center;gap:var(--size-2-1);align-self:flex-start;cursor:pointer;border:0;border-radius:var(--radius-s);box-shadow:none;margin:0;min-height:26px;padding:0;background:transparent;background-color:transparent;color:var(--text-accent);font-size:var(--font-ui-small);font-weight:var(--font-medium);line-height:1.2;}.add-new-btn.svelte-1f00z8 span:where(.svelte-1f00z8) {display:inline-flex;align-items:center;justify-content:center;font-size:var(--font-ui-medium);line-height:1;}.add-new-btn.disabled.svelte-1f00z8 {cursor:not-allowed;opacity:0.5;color:var(--text-muted);pointer-events:none;}.add-new-controls.svelte-1f00z8 {display:inline-flex;align-items:center;gap:var(--size-2-1);align-self:flex-start;border:0;background:transparent;box-shadow:none;}.add-new-controls.svelte-1f00z8 .add-new-picker-btn {flex-shrink:0;width:22px;height:26px;border:0;border-radius:var(--radius-s);box-shadow:none;margin:0;background-color:transparent;color:var(--text-accent);}.add-new-controls.svelte-1f00z8 .add-new-picker-btn.disabled:where(.svelte-1f00z8) {cursor:not-allowed;opacity:0.5;color:var(--text-muted);pointer-events:none;}.add-new-btn.svelte-1f00z8,\n.add-new-controls.svelte-1f00z8 .add-new-picker-btn {background-color:transparent;}.add-new-btn.svelte-1f00z8:hover:not(.disabled),\n.add-new-controls.svelte-1f00z8 .add-new-picker-btn:hover:not(.disabled) {background-color:transparent;color:var(--text-accent-hover);}.add-new-btn.svelte-1f00z8:active:not(.disabled),\n.add-new-controls.svelte-1f00z8 .add-new-picker-btn:active:not(.disabled) {background-color:transparent;color:var(--text-accent-hover);}.file-indicator.svelte-1f00z8 {display:flex;align-items:center;gap:var(--size-2-1);font-size:var(--font-ui-small);color:var(--text-muted);margin-top:var(--size-2-1);}.file-indicator.svelte-1f00z8 .file-indicator-arrow:where(.svelte-1f00z8) {flex-shrink:0;}.file-indicator.svelte-1f00z8 .file-indicator-name:where(.svelte-1f00z8) {overflow:hidden;text-overflow:ellipsis;white-space:nowrap;}.file-indicator.svelte-1f00z8 .file-indicator-label:where(.svelte-1f00z8) {white-space:nowrap;}"
};
function NewTaskControls($$anchor, $$props) {
if (new.target) return createClassComponent({ component: NewTaskControls, ...$$anchor });
push($$props, false);
append_styles($$anchor, $$css11);
const canEditNewTaskDates = mutable_source();
const isColTag = mutable_source();
let taskActions = prop($$props, "taskActions", 12);
let column = prop($$props, "column", 12);
let columnTagTableStore = prop($$props, "columnTagTableStore", 12);
let columnTitle = prop($$props, "columnTitle", 12);
let additionalTags = prop($$props, "additionalTags", 28, () => []);
let fileGroupTargetFile = prop($$props, "fileGroupTargetFile", 12, null);
let targetTaskFile = prop($$props, "targetTaskFile", 12, null);
let targetFileIsDefault = prop($$props, "targetFileIsDefault", 12, false);
let propertySchemaOption = prop($$props, "propertySchemaOption", 28, () => "none" /* None */);
let isVerticalFlow = prop($$props, "isVerticalFlow", 12, false);
let pendingNewTask = mutable_source(null);
let pendingCancelled = false;
let newTaskTextAreaEl = mutable_source();
let newTaskInputEl = mutable_source();
const emptyDateValues = { due: "", scheduled: "", start: "" };
let newTaskDateValues = mutable_source({ ...emptyDateValues });
async function handleNewTaskSave(event2) {
var _a5, _b3, _c2;
const nextTarget = event2 == null ? void 0 : event2.relatedTarget;
if (nextTarget instanceof Node && ((_a5 = get(newTaskInputEl)) == null ? void 0 : _a5.contains(nextTarget))) {
return;
}
if (pendingCancelled) {
pendingCancelled = false;
set(pendingNewTask, null);
set(newTaskDateValues, { ...emptyDateValues });
return;
}
const content = (_c2 = (_b3 = get(newTaskTextAreaEl)) == null ? void 0 : _b3.value) == null ? void 0 : _c2.trim();
const file = get(pendingNewTask);
const targetColumn = column();
set(pendingNewTask, null);
if (!content || !file || !isColumnTag(targetColumn, columnTagTableStore())) {
set(newTaskDateValues, { ...emptyDateValues });
return;
}
await taskActions().createTask(file, content, targetColumn, additionalTags(), get(newTaskDateValues));
set(newTaskDateValues, { ...emptyDateValues });
}
function handleNewTaskKeydown(e) {
var _a5, _b3;
if (e.key === "Escape") {
e.preventDefault();
pendingCancelled = true;
(_a5 = get(newTaskTextAreaEl)) == null ? void 0 : _a5.blur();
} else if (e.key === "Enter" && !e.shiftKey) {
e.preventDefault();
(_b3 = get(newTaskTextAreaEl)) == null ? void 0 : _b3.blur();
}
}
function handleAddNewClick(e) {
const targetColumn = column();
if (!isColumnTag(targetColumn, columnTagTableStore())) {
return;
}
set(newTaskDateValues, { ...emptyDateValues });
if (fileGroupTargetFile()) {
set(pendingNewTask, fileGroupTargetFile());
return;
}
taskActions().pickFileForNewTask(targetColumn, e, (file) => {
set(newTaskDateValues, { ...emptyDateValues });
set(pendingNewTask, file);
});
}
function handleChooseTaskFileClick(e) {
const targetColumn = column();
if (!isColumnTag(targetColumn, columnTagTableStore())) {
return;
}
taskActions().pickFileForNewTask(
targetColumn,
e,
(file) => {
set(newTaskDateValues, { ...emptyDateValues });
set(pendingNewTask, file);
},
true
);
}
function handleNewTaskDateChange(key2, value) {
set(newTaskDateValues, { ...get(newTaskDateValues), [key2]: value });
}
legacy_pre_effect(
() => (getPropertyWriteAdapter, deep_read_state(propertySchemaOption())),
() => {
set(canEditNewTaskDates, getPropertyWriteAdapter(propertySchemaOption()) !== null);
}
);
legacy_pre_effect(
() => (isColumnTag, deep_read_state(column()), deep_read_state(columnTagTableStore())),
() => {
set(isColTag, isColumnTag(column(), columnTagTableStore()));
}
);
legacy_pre_effect(() => (get(pendingNewTask), get(newTaskTextAreaEl)), () => {
if (get(pendingNewTask) && get(newTaskTextAreaEl)) {
get(newTaskTextAreaEl).focus();
}
});
legacy_pre_effect_reset();
var $$exports = {
get taskActions() {
return taskActions();
},
set taskActions($$value) {
taskActions($$value);
flushSync();
},
get column() {
return column();
},
set column($$value) {
column($$value);
flushSync();
},
get columnTagTableStore() {
return columnTagTableStore();
},
set columnTagTableStore($$value) {
columnTagTableStore($$value);
flushSync();
},
get columnTitle() {
return columnTitle();
},
set columnTitle($$value) {
columnTitle($$value);
flushSync();
},
get additionalTags() {
return additionalTags();
},
set additionalTags($$value) {
additionalTags($$value);
flushSync();
},
get fileGroupTargetFile() {
return fileGroupTargetFile();
},
set fileGroupTargetFile($$value) {
fileGroupTargetFile($$value);
flushSync();
},
get targetTaskFile() {
return targetTaskFile();
},
set targetTaskFile($$value) {
targetTaskFile($$value);
flushSync();
},
get targetFileIsDefault() {
return targetFileIsDefault();
},
set targetFileIsDefault($$value) {
targetFileIsDefault($$value);
flushSync();
},
get propertySchemaOption() {
return propertySchemaOption();
},
set propertySchemaOption($$value) {
propertySchemaOption($$value);
flushSync();
},
get isVerticalFlow() {
return isVerticalFlow();
},
set isVerticalFlow($$value) {
isVerticalFlow($$value);
flushSync();
},
$set: update_legacy_props,
$on: ($$event_name, $$event_cb) => add_legacy_event_listener($$props, $$event_name, $$event_cb)
};
init();
var fragment = root_53();
var node = first_child(fragment);
{
var consequent_2 = ($$anchor2) => {
var fragment_1 = root_26();
var div = first_child(fragment_1);
let classes;
var div_1 = child(div);
let classes_1;
var node_1 = sibling(div_1, 2);
{
let $0 = derived_safe_equal(() => get(pendingNewTask) ? "disabled" : "");
let $1 = derived_safe_equal(() => !!get(pendingNewTask));
Icon_button(node_1, {
get class() {
var _a5;
return `add-new-picker-btn ${(_a5 = get($0)) != null ? _a5 : ""}`;
},
icon: "lucide-chevron-down",
get "aria-label"() {
var _a5;
return `Choose file for new task in ${(_a5 = columnTitle()) != null ? _a5 : ""}`;
},
get disabled() {
return get($1);
},
$$events: {
click: (e) => {
if (!get(pendingNewTask)) handleChooseTaskFileClick(e);
}
}
});
}
reset(div);
var node_2 = sibling(div, 2);
{
var consequent_1 = ($$anchor3) => {
var div_2 = root_110();
let classes_2;
var span = sibling(child(div_2), 2);
var text2 = child(span, true);
reset(span);
var node_3 = sibling(span, 2);
{
var consequent = ($$anchor4) => {
var span_1 = root11();
append($$anchor4, span_1);
};
if_block(node_3, ($$render) => {
if (targetFileIsDefault()) $$render(consequent);
});
}
reset(div_2);
template_effect(() => {
classes_2 = set_class(div_2, 1, "file-indicator svelte-1f00z8", null, classes_2, { "vertical-flow": isVerticalFlow() });
set_attribute2(span, "title", (deep_read_state(targetTaskFile()), untrack(() => targetTaskFile().path)));
set_text(text2, (deep_read_state(targetTaskFile()), untrack(() => targetTaskFile().name)));
});
append($$anchor3, div_2);
};
if_block(node_2, ($$render) => {
if (targetTaskFile()) $$render(consequent_1);
});
}
template_effect(() => {
var _a5;
classes = set_class(div, 1, "add-new-controls svelte-1f00z8", null, classes, { "vertical-flow": isVerticalFlow() });
classes_1 = set_class(div_1, 1, "add-new-btn svelte-1f00z8", null, classes_1, { disabled: !!get(pendingNewTask) });
set_attribute2(div_1, "tabindex", get(pendingNewTask) ? -1 : 0);
set_attribute2(div_1, "aria-label", `Add new task to ${(_a5 = columnTitle()) != null ? _a5 : ""}`);
set_attribute2(div_1, "aria-disabled", !!get(pendingNewTask));
});
event("click", div_1, function(...$$args) {
var _a5;
(_a5 = !get(pendingNewTask) ? handleAddNewClick : void 0) == null ? void 0 : _a5.apply(this, $$args);
});
event("keydown", div_1, (e) => {
if (!get(pendingNewTask) && (e.key === "Enter" || e.key === " ")) {
e.preventDefault();
handleAddNewClick(e);
}
});
append($$anchor2, fragment_1);
};
if_block(node, ($$render) => {
if (get(isColTag)) $$render(consequent_2);
});
}
var node_4 = sibling(node, 2);
{
var consequent_4 = ($$anchor2) => {
var div_3 = root_44();
let classes_3;
var textarea = child(div_3);
bind_this(textarea, ($$value) => set(newTaskTextAreaEl, $$value), () => get(newTaskTextAreaEl));
var node_5 = sibling(textarea, 2);
{
var consequent_3 = ($$anchor3) => {
var div_4 = root_34();
var node_6 = child(div_4);
DateInputFields(node_6, {
get values() {
return get(newTaskDateValues);
},
onDateChange: handleNewTaskDateChange
});
reset(div_4);
append($$anchor3, div_4);
};
if_block(node_5, ($$render) => {
if (get(canEditNewTaskDates)) $$render(consequent_3);
});
}
reset(div_3);
bind_this(div_3, ($$value) => set(newTaskInputEl, $$value), () => get(newTaskInputEl));
template_effect(() => classes_3 = set_class(div_3, 1, "new-task-input svelte-1f00z8", null, classes_3, { "vertical-flow": isVerticalFlow() }));
event("keydown", textarea, handleNewTaskKeydown);
event("focusout", div_3, handleNewTaskSave);
append($$anchor2, div_3);
};
if_block(node_4, ($$render) => {
if (get(pendingNewTask)) $$render(consequent_4);
});
}
append($$anchor, fragment);
return pop($$exports);
}
// src/ui/board/BoardCell.svelte
var root12 = from_html(`<div role="presentation"><!></div>`);
var root_111 = from_html(`<div><!> <div class="tasks svelte-xi2aql"></div></div>`);
var $$css12 = {
hash: "svelte-xi2aql",
code: '.tasks-wrapper.svelte-xi2aql {display:flex;flex-direction:column;height:100%;min-height:100%;border:var(--border-width) solid transparent;border-radius:var(--radius-s);\n /* The wrapper should be invisible if collapsed in horizontal mode */}.tasks-wrapper.collapsed.svelte-xi2aql {display:none;}.tasks-wrapper.vertical-collapsed.svelte-xi2aql {display:none;}.tasks-wrapper.vertical-flow.svelte-xi2aql {width:100%;display:flex;flex-direction:column;gap:var(--size-4-2);}.tasks-wrapper.vertical-flow.svelte-xi2aql .tasks:where(.svelte-xi2aql) {order:1;flex-direction:row;flex-wrap:nowrap;align-items:flex-start;justify-content:flex-start;min-width:max-content;}.tasks-wrapper.vertical-flow.svelte-xi2aql .tasks:where(.svelte-xi2aql) .task {width:var(--column-width, 300px);flex-shrink:0;}.tasks-wrapper.vertical-flow.svelte-xi2aql .task-slot:where(.svelte-xi2aql) {flex:0 0 var(--column-width, 300px);}.tasks-wrapper.drop-active.svelte-xi2aql .tasks:where(.svelte-xi2aql) {opacity:0.4;}.tasks-wrapper.drop-hover.svelte-xi2aql {border-color:color-mix(in srgb, var(--column-color, var(--interactive-accent)) 75%, transparent);background:color-mix(in srgb, var(--column-color, var(--interactive-accent)) 10%, transparent);}.tasks-wrapper.svelte-xi2aql .tasks:where(.svelte-xi2aql) {display:flex;flex-direction:column;gap:var(--size-4-2);padding-top:var(--size-4-2);}.tasks-wrapper.svelte-xi2aql .task-slot:where(.svelte-xi2aql) {position:relative;}.tasks-wrapper.svelte-xi2aql .task-slot.drop-before:where(.svelte-xi2aql)::before, .tasks-wrapper.svelte-xi2aql .task-slot.drop-after:where(.svelte-xi2aql)::before {content:"";position:absolute;left:8px;right:8px;height:2px;background:var(--column-color, var(--interactive-accent));pointer-events:none;}.tasks-wrapper.svelte-xi2aql .task-slot.drop-before:where(.svelte-xi2aql)::after, .tasks-wrapper.svelte-xi2aql .task-slot.drop-after:where(.svelte-xi2aql)::after {content:"";position:absolute;left:4px;width:10px;height:10px;border-radius:999px;background:var(--column-color, var(--interactive-accent));pointer-events:none;}.tasks-wrapper.svelte-xi2aql .task-slot.drop-before:where(.svelte-xi2aql)::before {top:calc(-1 * var(--size-4-1) - 1px);}.tasks-wrapper.svelte-xi2aql .task-slot.drop-before:where(.svelte-xi2aql)::after {top:calc(-1 * var(--size-4-1) - 5px);}.tasks-wrapper.svelte-xi2aql .task-slot.drop-after:where(.svelte-xi2aql)::before {bottom:calc(-1 * var(--size-4-1) - 1px);}.tasks-wrapper.svelte-xi2aql .task-slot.drop-after:where(.svelte-xi2aql)::after {bottom:calc(-1 * var(--size-4-1) - 5px);}'
};
function BoardCell($$anchor, $$props) {
if (new.target) return createClassComponent({ component: BoardCell, ...$$anchor });
push($$props, false);
append_styles($$anchor, $$css12);
const $selectionModeStore = () => store_get(selectionModeStore, "$selectionModeStore", $$stores);
const $taskSelectionStore = () => store_get(taskSelectionStore, "$taskSelectionStore", $$stores);
const $isDraggingStore = () => store_get(isDraggingStore, "$isDraggingStore", $$stores);
const [$$stores, $$cleanup] = setup_stores();
const column = mutable_source();
const tasks = mutable_source();
const columnTitle = mutable_source();
const creationMetadata = mutable_source();
const fileGroupTargetFile = mutable_source();
const effectiveTargetTaskFile = mutable_source();
const effectiveTargetFileIsDefault = mutable_source();
const isSelectMode = mutable_source();
const columnTaskIds = mutable_source();
const selectedIds = mutable_source();
const taskSecondaryIds = mutable_source();
const pinnedIds = mutable_source();
const displayIds = mutable_source();
const isManualReorderDrag = mutable_source();
const draggingData = mutable_source();
const dropPlan = mutable_source();
const canDrop = mutable_source();
let app = prop($$props, "app", 12);
let cell = prop($$props, "cell", 12);
let primaryTasks = prop($$props, "primaryTasks", 28, () => []);
let secondaryAxisBucket = prop($$props, "secondaryAxisBucket", 12);
let primaryAxisLabel = prop($$props, "primaryAxisLabel", 12);
let taskActions = prop($$props, "taskActions", 12);
let columnTagTableStore = prop($$props, "columnTagTableStore", 12);
let showFilepath = prop($$props, "showFilepath", 12);
let propertyDisplay = prop($$props, "propertyDisplay", 28, () => "none" /* None */);
let propertySchemaOption = prop($$props, "propertySchemaOption", 28, () => "none" /* None */);
let consolidateTags = prop($$props, "consolidateTags", 12);
let excludedTags = prop($$props, "excludedTags", 28, () => []);
let isVerticalFlow = prop($$props, "isVerticalFlow", 12, false);
let targetTaskFile = prop($$props, "targetTaskFile", 12, null);
let targetFileIsDefault = prop($$props, "targetFileIsDefault", 12, false);
let doneColumnName = prop($$props, "doneColumnName", 12, void 0);
let accentColor = prop($$props, "accentColor", 12, void 0);
let treatNestedTasksAsSubtasks = prop($$props, "treatNestedTasksAsSubtasks", 12, false);
let isManualOrder = prop($$props, "isManualOrder", 12, false);
let manualOrderEntries = prop($$props, "manualOrderEntries", 12, void 0);
let reorderEnabled = prop($$props, "reorderEnabled", 12, false);
let isCollapsed = prop($$props, "isCollapsed", 12, false);
let isDraggedOver = mutable_source(false);
let reorderOverId = mutable_source(null);
let reorderPlaceBefore = mutable_source(false);
function computeTargetIndex(draggedId, overId, placeBefore) {
const without = get(displayIds).filter((id) => id !== draggedId);
const overPos = without.indexOf(overId);
if (overPos === -1) return without.length;
return placeBefore ? overPos : overPos + 1;
}
function handleReorderDragOver(e, overTaskId) {
if (!get(isManualReorderDrag)) return;
e.preventDefault();
e.stopPropagation();
const target = e.currentTarget;
const rect = target.getBoundingClientRect();
set(reorderPlaceBefore, e.clientY < rect.top + rect.height / 2);
set(reorderOverId, overTaskId);
if (e.dataTransfer) e.dataTransfer.dropEffect = "move";
}
function handleReorderDragLeave() {
set(reorderOverId, null);
}
async function handleReorderDrop(e, overTaskId) {
if (!get(isManualReorderDrag) || !get(draggingData)) return;
e.preventDefault();
e.stopPropagation();
const draggedId = get(draggingData).draggedTaskIds[0];
const placeBefore = get(reorderPlaceBefore);
set(reorderOverId, null);
if (!draggedId || draggedId === overTaskId) return;
const targetIndex = computeTargetIndex(draggedId, overTaskId, placeBefore);
await taskActions().reorderTask(cell().secondaryId, get(column), get(displayIds), draggedId, targetIndex);
}
function handleDragOver(e) {
e.preventDefault();
if (!get(canDrop)) {
if (e.dataTransfer) {
e.dataTransfer.dropEffect = "none";
}
return;
}
set(isDraggedOver, true);
if (e.dataTransfer) {
e.dataTransfer.dropEffect = "move";
}
}
function handleDragLeave(e) {
set(isDraggedOver, false);
}
async function handleDrop(e) {
e.preventDefault();
set(isDraggedOver, false);
const plan = get(dropPlan);
if (!plan || !get(draggingData)) {
return;
}
const droppedIds = get(draggingData).draggedTaskIds.length > 0 ? get(draggingData).draggedTaskIds : (() => {
var _a5;
const id = (_a5 = e.dataTransfer) == null ? void 0 : _a5.getData("text/plain");
return id ? [id] : [];
})();
if (droppedIds.length === 0) return;
switch (plan.kind) {
case "move-to-file": {
if (!get(fileGroupTargetFile)) return;
const droppedIdsBySourceSwimlane = groupIdsBySecondaryId(droppedIds, get(draggingData).taskSecondaryIds);
for (const [sourceFilePath, ids] of droppedIdsBySourceSwimlane) {
if (sourceFilePath === plan.targetFilePath) {
if (plan.changeColumn) await applyColumnChange(ids);
} else {
await taskActions().moveTasksToFile(ids, get(fileGroupTargetFile), get(column));
}
}
break;
}
case "set-tag":
await taskActions().updateSwimlaneTag(droppedIds, plan.tag, plan.prefix, excludedTags(), plan.includeTags);
if (plan.changeColumn) await applyColumnChange(droppedIds);
break;
case "set-property":
await taskActions().updateSwimlaneProperty(droppedIds, plan.key, plan.value);
if (plan.changeColumn) await applyColumnChange(droppedIds);
break;
case "column-only":
await applyColumnChange(droppedIds);
break;
}
clearColumnSelections(droppedIds);
}
function groupIdsBySecondaryId(taskIds, taskSecondaryIds2) {
var _a5, _b3;
const grouped = /* @__PURE__ */ new Map();
for (const id of taskIds) {
const secondaryId = (_a5 = taskSecondaryIds2[id]) != null ? _a5 : "";
const ids = (_b3 = grouped.get(secondaryId)) != null ? _b3 : [];
ids.push(id);
grouped.set(secondaryId, ids);
}
return grouped;
}
async function applyColumnChange(taskIds) {
await taskActions().moveTasksToColumn(taskIds, get(column));
}
legacy_pre_effect(() => deep_read_state(cell()), () => {
set(column, cell().primaryId);
});
legacy_pre_effect(() => deep_read_state(cell()), () => {
set(tasks, cell().tasks);
});
legacy_pre_effect(() => deep_read_state(primaryAxisLabel()), () => {
set(columnTitle, primaryAxisLabel());
});
legacy_pre_effect(
() => (deriveCellCreationMetadata, deep_read_state(secondaryAxisBucket())),
() => {
set(creationMetadata, deriveCellCreationMetadata(secondaryAxisBucket()));
}
);
legacy_pre_effect(() => (get(creationMetadata), deep_read_state(app()), import_obsidian7.TFile), () => {
set(fileGroupTargetFile, (() => {
if (!get(creationMetadata).targetFilePath) return null;
const file = app().vault.getAbstractFileByPath(get(creationMetadata).targetFilePath);
return file instanceof import_obsidian7.TFile ? file : null;
})());
});
legacy_pre_effect(
() => (get(fileGroupTargetFile), deep_read_state(targetTaskFile())),
() => {
var _a5;
set(effectiveTargetTaskFile, (_a5 = get(fileGroupTargetFile)) != null ? _a5 : targetTaskFile());
}
);
legacy_pre_effect(
() => (get(fileGroupTargetFile), deep_read_state(targetFileIsDefault())),
() => {
set(effectiveTargetFileIsDefault, get(fileGroupTargetFile) ? false : targetFileIsDefault());
}
);
legacy_pre_effect(() => (isInSelectionMode, get(column), $selectionModeStore()), () => {
set(isSelectMode, isInSelectionMode(get(column), $selectionModeStore()));
});
legacy_pre_effect(() => deep_read_state(primaryTasks()), () => {
set(columnTaskIds, primaryTasks().map((t) => t.id));
});
legacy_pre_effect(() => (get(columnTaskIds), isTaskSelected, $taskSelectionStore()), () => {
set(selectedIds, get(columnTaskIds).filter((id) => isTaskSelected(id, $taskSelectionStore())));
});
legacy_pre_effect(() => deep_read_state(primaryTasks()), () => {
set(taskSecondaryIds, Object.fromEntries(primaryTasks().map((task) => [task.id, task.path])));
});
legacy_pre_effect(
() => (deep_read_state(isManualOrder()), computePinnedIds, get(tasks), deep_read_state(manualOrderEntries())),
() => {
set(pinnedIds, isManualOrder() ? computePinnedIds(get(tasks), manualOrderEntries()) : /* @__PURE__ */ new Set());
}
);
legacy_pre_effect(() => get(tasks), () => {
set(displayIds, get(tasks).map((t) => t.id));
});
legacy_pre_effect(() => $isDraggingStore(), () => {
set(draggingData, $isDraggingStore());
});
legacy_pre_effect(
() => (deep_read_state(reorderEnabled()), get(draggingData), get(column), deep_read_state(cell())),
() => {
set(isManualReorderDrag, reorderEnabled() && !!get(draggingData) && get(draggingData).fromColumn === get(column) && get(draggingData).fromSecondaryId === cell().secondaryId && get(draggingData).draggedTaskIds.length === 1);
}
);
legacy_pre_effect(
() => (deriveDropPlan, get(draggingData), get(column), deep_read_state(cell()), deep_read_state(secondaryAxisBucket()), get(fileGroupTargetFile), getPropertyWriteAdapter, deep_read_state(propertySchemaOption())),
() => {
var _a5, _b3;
set(dropPlan, deriveDropPlan({
dragging: get(draggingData),
column: get(column),
secondaryId: cell().secondaryId,
bucketMeta: secondaryAxisBucket().meta,
fileGroupTargetFilePath: (_b3 = (_a5 = get(fileGroupTargetFile)) == null ? void 0 : _a5.path) != null ? _b3 : null,
canWriteProperties: getPropertyWriteAdapter(propertySchemaOption()) !== null
}));
}
);
legacy_pre_effect(() => get(dropPlan), () => {
set(canDrop, get(dropPlan) !== null);
});
legacy_pre_effect_reset();
var $$exports = {
get app() {
return app();
},
set app($$value) {
app($$value);
flushSync();
},
get cell() {
return cell();
},
set cell($$value) {
cell($$value);
flushSync();
},
get primaryTasks() {
return primaryTasks();
},
set primaryTasks($$value) {
primaryTasks($$value);
flushSync();
},
get secondaryAxisBucket() {
return secondaryAxisBucket();
},
set secondaryAxisBucket($$value) {
secondaryAxisBucket($$value);
flushSync();
},
get primaryAxisLabel() {
return primaryAxisLabel();
},
set primaryAxisLabel($$value) {
primaryAxisLabel($$value);
flushSync();
},
get taskActions() {
return taskActions();
},
set taskActions($$value) {
taskActions($$value);
flushSync();
},
get columnTagTableStore() {
return columnTagTableStore();
},
set columnTagTableStore($$value) {
columnTagTableStore($$value);
flushSync();
},
get showFilepath() {
return showFilepath();
},
set showFilepath($$value) {
showFilepath($$value);
flushSync();
},
get propertyDisplay() {
return propertyDisplay();
},
set propertyDisplay($$value) {
propertyDisplay($$value);
flushSync();
},
get propertySchemaOption() {
return propertySchemaOption();
},
set propertySchemaOption($$value) {
propertySchemaOption($$value);
flushSync();
},
get consolidateTags() {
return consolidateTags();
},
set consolidateTags($$value) {
consolidateTags($$value);
flushSync();
},
get excludedTags() {
return excludedTags();
},
set excludedTags($$value) {
excludedTags($$value);
flushSync();
},
get isVerticalFlow() {
return isVerticalFlow();
},
set isVerticalFlow($$value) {
isVerticalFlow($$value);
flushSync();
},
get targetTaskFile() {
return targetTaskFile();
},
set targetTaskFile($$value) {
targetTaskFile($$value);
flushSync();
},
get targetFileIsDefault() {
return targetFileIsDefault();
},
set targetFileIsDefault($$value) {
targetFileIsDefault($$value);
flushSync();
},
get doneColumnName() {
return doneColumnName();
},
set doneColumnName($$value) {
doneColumnName($$value);
flushSync();
},
get accentColor() {
return accentColor();
},
set accentColor($$value) {
accentColor($$value);
flushSync();
},
get treatNestedTasksAsSubtasks() {
return treatNestedTasksAsSubtasks();
},
set treatNestedTasksAsSubtasks($$value) {
treatNestedTasksAsSubtasks($$value);
flushSync();
},
get isManualOrder() {
return isManualOrder();
},
set isManualOrder($$value) {
isManualOrder($$value);
flushSync();
},
get manualOrderEntries() {
return manualOrderEntries();
},
set manualOrderEntries($$value) {
manualOrderEntries($$value);
flushSync();
},
get reorderEnabled() {
return reorderEnabled();
},
set reorderEnabled($$value) {
reorderEnabled($$value);
flushSync();
},
get isCollapsed() {
return isCollapsed();
},
set isCollapsed($$value) {
isCollapsed($$value);
flushSync();
},
$set: update_legacy_props,
$on: ($$event_name, $$event_cb) => add_legacy_event_listener($$props, $$event_name, $$event_cb)
};
init();
var div = root_111();
let classes;
var node = child(div);
NewTaskControls(node, {
get taskActions() {
return taskActions();
},
get column() {
return get(column);
},
get columnTagTableStore() {
return columnTagTableStore();
},
get columnTitle() {
return get(columnTitle);
},
get additionalTags() {
return get(creationMetadata), untrack(() => get(creationMetadata).additionalTags);
},
get fileGroupTargetFile() {
return get(fileGroupTargetFile);
},
get targetTaskFile() {
return get(effectiveTargetTaskFile);
},
get targetFileIsDefault() {
return get(effectiveTargetFileIsDefault);
},
get propertySchemaOption() {
return propertySchemaOption();
},
get isVerticalFlow() {
return isVerticalFlow();
}
});
var div_1 = sibling(node, 2);
each(div_1, 5, () => get(tasks), (task) => task.id, ($$anchor2, task) => {
var div_2 = root12();
let classes_1;
var node_1 = child(div_2);
{
let $0 = derived_safe_equal(() => (deep_read_state(isTaskSelected), get(task), $taskSelectionStore(), untrack(() => isTaskSelected(get(task).id, $taskSelectionStore()))));
let $1 = derived_safe_equal(() => (get(pinnedIds), get(task), untrack(() => get(pinnedIds).has(get(task).id))));
Task2(node_1, {
get app() {
return app();
},
get task() {
return get(task);
},
get taskActions() {
return taskActions();
},
get columnTagTableStore() {
return columnTagTableStore();
},
get showFilepath() {
return showFilepath();
},
get propertyDisplay() {
return propertyDisplay();
},
get propertySchemaOption() {
return propertySchemaOption();
},
get consolidateTags() {
return consolidateTags();
},
get excludedTags() {
return excludedTags();
},
get treatNestedTasksAsSubtasks() {
return treatNestedTasksAsSubtasks();
},
get displayColumn() {
return get(column);
},
get displaySecondaryId() {
return deep_read_state(cell()), untrack(() => cell().secondaryId);
},
get isSelectionMode() {
return get(isSelectMode);
},
get isSelected() {
return get($0);
},
onToggleSelection: () => toggleTaskSelection(get(task).id),
get selectedTaskIds() {
return get(selectedIds);
},
get taskSecondaryIds() {
return get(taskSecondaryIds);
},
get doneColumnName() {
return doneColumnName();
},
get accentColor() {
return accentColor();
},
get isManualOrder() {
return isManualOrder();
},
get isPinned() {
return get($1);
},
get showDragHandle() {
return reorderEnabled();
},
onUnpin: () => taskActions().unpinTask(cell().secondaryId, get(column), get(task).id)
});
}
reset(div_2);
template_effect(() => classes_1 = set_class(div_2, 1, "task-slot svelte-xi2aql", null, classes_1, {
"drop-before": get(isManualReorderDrag) && get(reorderOverId) === get(task).id && get(reorderPlaceBefore),
"drop-after": get(isManualReorderDrag) && get(reorderOverId) === get(task).id && !get(reorderPlaceBefore)
}));
event("dragover", div_2, (e) => handleReorderDragOver(e, get(task).id));
event("drop", div_2, (e) => handleReorderDrop(e, get(task).id));
event("dragleave", div_2, handleReorderDragLeave);
append($$anchor2, div_2);
});
reset(div_1);
reset(div);
template_effect(() => classes = set_class(div, 1, "tasks-wrapper svelte-xi2aql", null, classes, {
"vertical-flow": isVerticalFlow(),
collapsed: isCollapsed() && !isVerticalFlow(),
"vertical-collapsed": isCollapsed() && isVerticalFlow(),
"drop-active": !!get(draggingData) && !get(isManualReorderDrag),
"drop-hover": get(isDraggedOver)
}));
event("dragover", div, handleDragOver);
event("dragleave", div, handleDragLeave);
event("drop", div, handleDrop);
append($$anchor, div);
var $$pop = pop($$exports);
$$cleanup();
return $$pop;
}
// src/ui/board/board_matrix_vertical.svelte
var root13 = from_html(`<span class="matrix-task-count svelte-iq029y" aria-live="polite"> </span>`);
var root_112 = from_html(`<div><!></div> <div><!></div>`, 1);
var root_27 = from_html(`<div class="matrix-vertical ungrouped-grid svelte-iq029y"><div class="matrix-corner svelte-iq029y"><!></div> <div class="group-header-cell svelte-iq029y" aria-hidden="true"></div> <!></div>`);
var root_35 = from_html(`<div class="group-header-cell svelte-iq029y"><span class="group-label svelte-iq029y"> </span></div>`);
var root_45 = from_html(`<div><!></div>`);
var root_54 = from_html(`<div><!></div> <!>`, 1);
var root_63 = from_html(`<div class="matrix-vertical transposed-grid svelte-iq029y"><div class="matrix-corner svelte-iq029y"><!></div> <!> <!></div>`);
var $$css13 = {
hash: "svelte-iq029y",
code: ".matrix-vertical.svelte-iq029y {--vertical-row-header-width: clamp(220px, 24vw, 280px);position:relative;padding-bottom:var(--size-4-4);}.matrix-vertical.ungrouped-grid.svelte-iq029y, .matrix-vertical.transposed-grid.svelte-iq029y {display:grid;column-gap:0;row-gap:0;align-items:stretch;min-width:max-content;border:var(--border-width) solid var(--background-modifier-border);border-radius:var(--radius-m);background:var(--background-primary);box-shadow:var(--shadow-s);overflow:visible;}.matrix-vertical.ungrouped-grid.svelte-iq029y {grid-template-columns:var(--vertical-row-header-width) max-content;}.matrix-vertical.ungrouped-grid.svelte-iq029y .matrix-corner:where(.svelte-iq029y),\n.matrix-vertical.ungrouped-grid.svelte-iq029y .group-header-cell:where(.svelte-iq029y) {min-height:0;padding-top:var(--size-2-1);padding-bottom:var(--size-2-1);}.matrix-corner.svelte-iq029y,\n.group-header-cell.svelte-iq029y {position:sticky;top:0;z-index:5;min-height:64px;background:color-mix(in srgb, var(--background-secondary) 72%, var(--background-primary));border-right:var(--border-width) solid var(--background-modifier-border);border-bottom:var(--border-width) solid var(--background-modifier-border);box-shadow:inset 0 var(--border-width) 0 var(--background-modifier-border), inset var(--border-width) 0 0 var(--background-modifier-border);}.matrix-corner.svelte-iq029y {left:0;z-index:8;display:flex;align-items:center;min-width:0;padding:var(--size-2-2) var(--size-4-3);overflow:hidden;}.matrix-task-count.svelte-iq029y {display:block;max-width:100%;overflow:hidden;color:var(--text-muted);font-size:var(--font-ui-smaller);font-weight:500;line-height:1.2;text-overflow:ellipsis;white-space:nowrap;}.group-header-cell.svelte-iq029y {display:flex;align-items:center;min-width:var(--column-width, 300px);padding:var(--size-4-3) var(--size-4-4);overflow:clip;}.group-header-cell.svelte-iq029y .group-label:where(.svelte-iq029y) {position:sticky;left:calc(var(--vertical-row-header-width) + var(--size-4-4));display:inline-block;max-width:max-content;color:var(--text-normal);font-size:var(--font-ui-medium);font-weight:var(--font-medium);line-height:1.2;white-space:nowrap;}.row-header-wrapper.svelte-iq029y,\n.row-cell.svelte-iq029y {border-bottom:var(--border-width) solid var(--background-modifier-border);}.row-header-wrapper.svelte-iq029y {position:sticky;left:0;z-index:4;display:flex;align-items:stretch;min-height:96px;padding:var(--size-4-2) var(--size-4-3);background:color-mix(in srgb, var(--background-secondary) 72%, var(--background-primary));border-right:var(--border-width) solid var(--background-modifier-border);--column-header-x-padding-override: var(--size-4-3);--column-header-y-padding-override: var(--size-4-2);}.row-header-wrapper.collapsed.svelte-iq029y {min-height:64px;cursor:pointer;}.row-cell.svelte-iq029y {z-index:1;display:flex;align-self:stretch;min-height:96px;min-width:max-content;padding:var(--size-4-2) var(--size-4-4);background:color-mix(in srgb, var(--background-primary) 88%, var(--background-secondary));}.row-cell.collapsed.svelte-iq029y {display:none;}.cell-wrapper.svelte-iq029y {padding:var(--size-4-2) var(--size-4-4);border-bottom:var(--border-width) solid var(--background-modifier-border);}.cell-wrapper.grouped-cell.svelte-iq029y {z-index:1;display:flex;align-self:stretch;min-height:96px;min-width:var(--column-width, 300px);background:color-mix(in srgb, var(--background-primary) 88%, var(--background-secondary));border-right:var(--border-width) solid var(--background-modifier-border);}.cell-wrapper.grouped-cell.collapsed.svelte-iq029y {display:none;}"
};
function Board_matrix_vertical($$anchor, $$props) {
if (new.target) return createClassComponent({ component: Board_matrix_vertical, ...$$anchor });
push($$props, false);
append_styles($$anchor, $$css13);
const tasksByPrimary = mutable_source();
const showSwimlaneHeaders = mutable_source();
const ungroupedSecondaryBucket = mutable_source();
const ungroupedGridTemplateRows = mutable_source();
const groupedGridTemplateColumns = mutable_source();
const groupedGridTemplateRows = mutable_source();
let app = prop($$props, "app", 12);
let matrix = prop($$props, "matrix", 12);
let taskActions = prop($$props, "taskActions", 12);
let columnTagTableStore = prop($$props, "columnTagTableStore", 12);
let columnColourTableStore = prop($$props, "columnColourTableStore", 12);
let columnMatchTagTableStore = prop($$props, "columnMatchTagTableStore", 12);
let columnSubtitleTableStore = prop($$props, "columnSubtitleTableStore", 12);
let showFilepath = prop($$props, "showFilepath", 12);
let propertyDisplay = prop($$props, "propertyDisplay", 28, () => "none" /* None */);
let propertySchemaOption = prop($$props, "propertySchemaOption", 28, () => "none" /* None */);
let consolidateTags = prop($$props, "consolidateTags", 12);
let excludedTags = prop($$props, "excludedTags", 28, () => []);
let targetTaskFile = prop($$props, "targetTaskFile", 12, null);
let targetFileIsDefault = prop($$props, "targetFileIsDefault", 12, false);
let onToggleCollapse = prop($$props, "onToggleCollapse", 12);
let uncategorizedColumnName = prop($$props, "uncategorizedColumnName", 12, void 0);
let doneColumnName = prop($$props, "doneColumnName", 12, void 0);
let isManualOrder = prop($$props, "isManualOrder", 12, false);
let manualOrder = prop($$props, "manualOrder", 28, () => ({}));
let reorderEnabled = prop($$props, "reorderEnabled", 12, false);
let treatNestedTasksAsSubtasks = prop($$props, "treatNestedTasksAsSubtasks", 12, false);
let taskCountLabel = prop($$props, "taskCountLabel", 12, "");
let headerHeight = mutable_source(64);
legacy_pre_effect(() => deep_read_state(matrix()), () => {
set(tasksByPrimary, Object.fromEntries(matrix().primaryAxis.map((bucket) => [
bucket.id,
Object.values(matrix().cells[bucket.id] || {}).flatMap((cell) => cell.tasks)
])));
});
legacy_pre_effect(() => deep_read_state(matrix()), () => {
var _a5, _b3;
set(showSwimlaneHeaders, matrix().secondaryAxis.length > 1 || matrix().secondaryAxis.length > 0 && !((_b3 = (_a5 = matrix().secondaryAxis[0]) == null ? void 0 : _a5.meta) == null ? void 0 : _b3.isDefault));
});
legacy_pre_effect(() => deep_read_state(matrix()), () => {
set(ungroupedSecondaryBucket, matrix().secondaryAxis[0]);
});
legacy_pre_effect(() => deep_read_state(matrix()), () => {
set(ungroupedGridTemplateRows, [
"max-content",
...matrix().primaryAxis.map(() => "max-content")
].join(" "));
});
legacy_pre_effect(() => deep_read_state(matrix()), () => {
set(groupedGridTemplateColumns, [
"var(--vertical-row-header-width)",
...matrix().secondaryAxis.map(() => "max-content")
].join(" "));
});
legacy_pre_effect(() => deep_read_state(matrix()), () => {
set(groupedGridTemplateRows, [
"max-content",
...matrix().primaryAxis.map(() => "max-content")
].join(" "));
});
legacy_pre_effect_reset();
var $$exports = {
get app() {
return app();
},
set app($$value) {
app($$value);
flushSync();
},
get matrix() {
return matrix();
},
set matrix($$value) {
matrix($$value);
flushSync();
},
get taskActions() {
return taskActions();
},
set taskActions($$value) {
taskActions($$value);
flushSync();
},
get columnTagTableStore() {
return columnTagTableStore();
},
set columnTagTableStore($$value) {
columnTagTableStore($$value);
flushSync();
},
get columnColourTableStore() {
return columnColourTableStore();
},
set columnColourTableStore($$value) {
columnColourTableStore($$value);
flushSync();
},
get columnMatchTagTableStore() {
return columnMatchTagTableStore();
},
set columnMatchTagTableStore($$value) {
columnMatchTagTableStore($$value);
flushSync();
},
get columnSubtitleTableStore() {
return columnSubtitleTableStore();
},
set columnSubtitleTableStore($$value) {
columnSubtitleTableStore($$value);
flushSync();
},
get showFilepath() {
return showFilepath();
},
set showFilepath($$value) {
showFilepath($$value);
flushSync();
},
get propertyDisplay() {
return propertyDisplay();
},
set propertyDisplay($$value) {
propertyDisplay($$value);
flushSync();
},
get propertySchemaOption() {
return propertySchemaOption();
},
set propertySchemaOption($$value) {
propertySchemaOption($$value);
flushSync();
},
get consolidateTags() {
return consolidateTags();
},
set consolidateTags($$value) {
consolidateTags($$value);
flushSync();
},
get excludedTags() {
return excludedTags();
},
set excludedTags($$value) {
excludedTags($$value);
flushSync();
},
get targetTaskFile() {
return targetTaskFile();
},
set targetTaskFile($$value) {
targetTaskFile($$value);
flushSync();
},
get targetFileIsDefault() {
return targetFileIsDefault();
},
set targetFileIsDefault($$value) {
targetFileIsDefault($$value);
flushSync();
},
get onToggleCollapse() {
return onToggleCollapse();
},
set onToggleCollapse($$value) {
onToggleCollapse($$value);
flushSync();
},
get uncategorizedColumnName() {
return uncategorizedColumnName();
},
set uncategorizedColumnName($$value) {
uncategorizedColumnName($$value);
flushSync();
},
get doneColumnName() {
return doneColumnName();
},
set doneColumnName($$value) {
doneColumnName($$value);
flushSync();
},
get isManualOrder() {
return isManualOrder();
},
set isManualOrder($$value) {
isManualOrder($$value);
flushSync();
},
get manualOrder() {
return manualOrder();
},
set manualOrder($$value) {
manualOrder($$value);
flushSync();
},
get reorderEnabled() {
return reorderEnabled();
},
set reorderEnabled($$value) {
reorderEnabled($$value);
flushSync();
},
get treatNestedTasksAsSubtasks() {
return treatNestedTasksAsSubtasks();
},
set treatNestedTasksAsSubtasks($$value) {
treatNestedTasksAsSubtasks($$value);
flushSync();
},
get taskCountLabel() {
return taskCountLabel();
},
set taskCountLabel($$value) {
taskCountLabel($$value);
flushSync();
},
$set: update_legacy_props,
$on: ($$event_name, $$event_cb) => add_legacy_event_listener($$props, $$event_name, $$event_cb)
};
init();
var fragment = comment();
var node = first_child(fragment);
{
var consequent_1 = ($$anchor2) => {
var div = root_27();
let styles;
var div_1 = child(div);
set_style(div_1, "", {}, { "grid-column": "1", "grid-row": "1" });
var node_1 = child(div_1);
{
var consequent = ($$anchor3) => {
var span = root13();
var text2 = child(span, true);
reset(span);
template_effect(() => set_text(text2, taskCountLabel()));
append($$anchor3, span);
};
if_block(node_1, ($$render) => {
if (taskCountLabel()) $$render(consequent);
});
}
reset(div_1);
var div_2 = sibling(div_1, 2);
set_style(div_2, "", {}, { "grid-column": "2", "grid-row": "1" });
var node_2 = sibling(div_2, 2);
each(
node_2,
3,
() => (deep_read_state(matrix()), untrack(() => matrix().primaryAxis)),
(pBucket) => pBucket.id,
($$anchor3, pBucket, pIndex) => {
var fragment_1 = root_112();
var div_3 = first_child(fragment_1);
let classes;
let styles_1;
var node_3 = child(div_3);
{
let $0 = derived_safe_equal(() => (get(tasksByPrimary), get(pBucket), untrack(() => {
var _a5;
return (_a5 = get(tasksByPrimary)[get(pBucket).id]) != null ? _a5 : [];
})));
ColumnHeader(node_3, {
get column() {
return get(pBucket), untrack(() => get(pBucket).id);
},
get tasks() {
return get($0);
},
get taskActions() {
return taskActions();
},
get columnTagTableStore() {
return columnTagTableStore();
},
get columnColourTableStore() {
return columnColourTableStore();
},
get columnMatchTagTableStore() {
return columnMatchTagTableStore();
},
get columnSubtitleTableStore() {
return columnSubtitleTableStore();
},
isVerticalFlow: true,
get isCollapsed() {
return get(pBucket), untrack(() => get(pBucket).collapsed);
},
onToggleCollapse: () => onToggleCollapse()(get(pBucket).id),
get uncategorizedColumnName() {
return uncategorizedColumnName();
},
get doneColumnName() {
return doneColumnName();
}
});
}
reset(div_3);
var div_4 = sibling(div_3, 2);
let classes_1;
let styles_2;
var node_4 = child(div_4);
{
let $0 = derived_safe_equal(() => (deep_read_state(getBoardCell), deep_read_state(matrix()), get(pBucket), get(ungroupedSecondaryBucket), untrack(() => getBoardCell(matrix(), get(pBucket).id, get(ungroupedSecondaryBucket).id))));
let $1 = derived_safe_equal(() => (get(tasksByPrimary), get(pBucket), untrack(() => {
var _a5;
return (_a5 = get(tasksByPrimary)[get(pBucket).id]) != null ? _a5 : [];
})));
let $2 = derived_safe_equal(() => (get(pBucket), untrack(() => {
var _a5;
return (_a5 = get(pBucket).meta) == null ? void 0 : _a5.color;
})));
let $3 = derived_safe_equal(() => (deep_read_state(manualOrder()), get(ungroupedSecondaryBucket), get(pBucket), untrack(() => {
var _a5;
return (_a5 = manualOrder()[get(ungroupedSecondaryBucket).id]) == null ? void 0 : _a5[get(pBucket).id];
})));
BoardCell(node_4, {
get app() {
return app();
},
get cell() {
return get($0);
},
get primaryTasks() {
return get($1);
},
get secondaryAxisBucket() {
return get(ungroupedSecondaryBucket);
},
get primaryAxisLabel() {
return get(pBucket), untrack(() => get(pBucket).label);
},
get taskActions() {
return taskActions();
},
get columnTagTableStore() {
return columnTagTableStore();
},
get showFilepath() {
return showFilepath();
},
get propertyDisplay() {
return propertyDisplay();
},
get propertySchemaOption() {
return propertySchemaOption();
},
get consolidateTags() {
return consolidateTags();
},
get excludedTags() {
return excludedTags();
},
get treatNestedTasksAsSubtasks() {
return treatNestedTasksAsSubtasks();
},
isVerticalFlow: true,
get targetTaskFile() {
return targetTaskFile();
},
get targetFileIsDefault() {
return targetFileIsDefault();
},
get doneColumnName() {
return doneColumnName();
},
get isCollapsed() {
return get(pBucket), untrack(() => get(pBucket).collapsed);
},
get accentColor() {
return get($2);
},
get isManualOrder() {
return isManualOrder();
},
get manualOrderEntries() {
return get($3);
},
get reorderEnabled() {
return reorderEnabled();
}
});
}
reset(div_4);
template_effect(() => {
classes = set_class(div_3, 1, "row-header-wrapper svelte-iq029y", null, classes, { collapsed: get(pBucket).collapsed });
styles_1 = set_style(div_3, "", styles_1, {
"grid-column": "1",
"grid-row": get(pIndex) + 2,
"--column-color": (get(pBucket), untrack(() => {
var _a5;
return (_a5 = get(pBucket).meta) == null ? void 0 : _a5.color;
}))
});
classes_1 = set_class(div_4, 1, "cell-wrapper row-cell svelte-iq029y", null, classes_1, { collapsed: get(pBucket).collapsed });
styles_2 = set_style(div_4, "", styles_2, {
"grid-column": "2",
"grid-row": get(pIndex) + 2,
"--column-color": (get(pBucket), untrack(() => {
var _a5;
return (_a5 = get(pBucket).meta) == null ? void 0 : _a5.color;
}))
});
});
append($$anchor3, fragment_1);
}
);
reset(div);
template_effect(() => {
var _a5;
return styles = set_style(div, "", styles, {
"grid-template-rows": get(ungroupedGridTemplateRows),
"--header-height": `${(_a5 = get(headerHeight)) != null ? _a5 : ""}px`
});
});
bind_element_size(div_1, "clientHeight", ($$value) => set(headerHeight, $$value));
append($$anchor2, div);
};
var alternate = ($$anchor2) => {
var div_5 = root_63();
let styles_3;
var div_6 = child(div_5);
set_style(div_6, "", {}, { "grid-column": "1", "grid-row": "1" });
var node_5 = child(div_6);
{
var consequent_2 = ($$anchor3) => {
var span_1 = root13();
var text_1 = child(span_1, true);
reset(span_1);
template_effect(() => set_text(text_1, taskCountLabel()));
append($$anchor3, span_1);
};
if_block(node_5, ($$render) => {
if (taskCountLabel()) $$render(consequent_2);
});
}
reset(div_6);
var node_6 = sibling(div_6, 2);
each(
node_6,
3,
() => (deep_read_state(matrix()), untrack(() => matrix().secondaryAxis)),
(sBucket) => sBucket.id,
($$anchor3, sBucket, sIndex) => {
var div_7 = root_35();
let styles_4;
var span_2 = child(div_7);
var text_2 = child(span_2, true);
reset(span_2);
reset(div_7);
template_effect(() => {
styles_4 = set_style(div_7, "", styles_4, { "grid-column": get(sIndex) + 2, "grid-row": "1" });
set_attribute2(span_2, "title", (get(sBucket), untrack(() => get(sBucket).label)));
set_text(text_2, (get(sBucket), untrack(() => get(sBucket).label)));
});
append($$anchor3, div_7);
}
);
var node_7 = sibling(node_6, 2);
each(
node_7,
3,
() => (deep_read_state(matrix()), untrack(() => matrix().primaryAxis)),
(pBucket) => pBucket.id,
($$anchor3, pBucket, pIndex) => {
var fragment_2 = root_54();
var div_8 = first_child(fragment_2);
let classes_2;
let styles_5;
var node_8 = child(div_8);
{
let $0 = derived_safe_equal(() => (get(tasksByPrimary), get(pBucket), untrack(() => {
var _a5;
return (_a5 = get(tasksByPrimary)[get(pBucket).id]) != null ? _a5 : [];
})));
ColumnHeader(node_8, {
get column() {
return get(pBucket), untrack(() => get(pBucket).id);
},
get tasks() {
return get($0);
},
get taskActions() {
return taskActions();
},
get columnTagTableStore() {
return columnTagTableStore();
},
get columnColourTableStore() {
return columnColourTableStore();
},
get columnMatchTagTableStore() {
return columnMatchTagTableStore();
},
get columnSubtitleTableStore() {
return columnSubtitleTableStore();
},
isVerticalFlow: true,
get isCollapsed() {
return get(pBucket), untrack(() => get(pBucket).collapsed);
},
onToggleCollapse: () => onToggleCollapse()(get(pBucket).id),
get uncategorizedColumnName() {
return uncategorizedColumnName();
},
get doneColumnName() {
return doneColumnName();
}
});
}
reset(div_8);
var node_9 = sibling(div_8, 2);
each(
node_9,
3,
() => (deep_read_state(matrix()), untrack(() => matrix().secondaryAxis)),
(sBucket) => sBucket.id,
($$anchor4, sBucket, sIndex) => {
var div_9 = root_45();
let classes_3;
let styles_6;
var node_10 = child(div_9);
{
let $0 = derived_safe_equal(() => (deep_read_state(getBoardCell), deep_read_state(matrix()), get(pBucket), get(sBucket), untrack(() => getBoardCell(matrix(), get(pBucket).id, get(sBucket).id))));
let $1 = derived_safe_equal(() => (get(tasksByPrimary), get(pBucket), untrack(() => {
var _a5;
return (_a5 = get(tasksByPrimary)[get(pBucket).id]) != null ? _a5 : [];
})));
let $2 = derived_safe_equal(() => (get(pBucket), untrack(() => {
var _a5;
return (_a5 = get(pBucket).meta) == null ? void 0 : _a5.color;
})));
let $3 = derived_safe_equal(() => (deep_read_state(manualOrder()), get(sBucket), get(pBucket), untrack(() => {
var _a5;
return (_a5 = manualOrder()[get(sBucket).id]) == null ? void 0 : _a5[get(pBucket).id];
})));
BoardCell(node_10, {
get app() {
return app();
},
get cell() {
return get($0);
},
get primaryTasks() {
return get($1);
},
get secondaryAxisBucket() {
return get(sBucket);
},
get primaryAxisLabel() {
return get(pBucket), untrack(() => get(pBucket).label);
},
get taskActions() {
return taskActions();
},
get columnTagTableStore() {
return columnTagTableStore();
},
get showFilepath() {
return showFilepath();
},
get propertyDisplay() {
return propertyDisplay();
},
get propertySchemaOption() {
return propertySchemaOption();
},
get consolidateTags() {
return consolidateTags();
},
get excludedTags() {
return excludedTags();
},
get treatNestedTasksAsSubtasks() {
return treatNestedTasksAsSubtasks();
},
isVerticalFlow: true,
get targetTaskFile() {
return targetTaskFile();
},
get targetFileIsDefault() {
return targetFileIsDefault();
},
get doneColumnName() {
return doneColumnName();
},
get isCollapsed() {
return get(pBucket), untrack(() => get(pBucket).collapsed);
},
get accentColor() {
return get($2);
},
get isManualOrder() {
return isManualOrder();
},
get manualOrderEntries() {
return get($3);
},
get reorderEnabled() {
return reorderEnabled();
}
});
}
reset(div_9);
template_effect(() => {
classes_3 = set_class(div_9, 1, "cell-wrapper grouped-cell svelte-iq029y", null, classes_3, { collapsed: get(pBucket).collapsed });
styles_6 = set_style(div_9, "", styles_6, {
"grid-column": get(sIndex) + 2,
"grid-row": get(pIndex) + 2,
"--column-color": (get(pBucket), untrack(() => {
var _a5;
return (_a5 = get(pBucket).meta) == null ? void 0 : _a5.color;
}))
});
});
append($$anchor4, div_9);
}
);
template_effect(() => {
classes_2 = set_class(div_8, 1, "row-header-wrapper svelte-iq029y", null, classes_2, { collapsed: get(pBucket).collapsed });
styles_5 = set_style(div_8, "", styles_5, {
"grid-column": "1",
"grid-row": get(pIndex) + 2,
"--column-color": (get(pBucket), untrack(() => {
var _a5;
return (_a5 = get(pBucket).meta) == null ? void 0 : _a5.color;
}))
});
});
append($$anchor3, fragment_2);
}
);
reset(div_5);
template_effect(() => {
var _a5;
return styles_3 = set_style(div_5, "", styles_3, {
"grid-template-columns": get(groupedGridTemplateColumns),
"grid-template-rows": get(groupedGridTemplateRows),
"--header-height": `${(_a5 = get(headerHeight)) != null ? _a5 : ""}px`
});
});
bind_element_size(div_6, "clientHeight", ($$value) => set(headerHeight, $$value));
append($$anchor2, div_5);
};
if_block(node, ($$render) => {
if (!get(showSwimlaneHeaders) && get(ungroupedSecondaryBucket)) $$render(consequent_1);
else $$render(alternate, -1);
});
}
append($$anchor, fragment);
return pop($$exports);
}
// src/ui/board/board_matrix_horizontal.svelte
var root14 = from_html(`<span class="matrix-task-count svelte-1j479gc" aria-live="polite"> </span>`);
var root_113 = from_html(`<div><!></div>`);
var root_28 = from_html(`<span class="swimlane-label svelte-1j479gc"> </span>`);
var root_36 = from_html(`<div class="swimlane-header-cell svelte-1j479gc"><!></div> <!>`, 1);
var root_46 = from_html(`<div class="matrix-horizontal svelte-1j479gc"><div class="matrix-corner svelte-1j479gc"><!></div> <!> <!></div>`);
var $$css14 = {
hash: "svelte-1j479gc",
code: ".matrix-horizontal.svelte-1j479gc {display:grid;position:relative;column-gap:0;row-gap:0;align-items:stretch;min-width:max-content;padding-bottom:var(--size-4-4);border:var(--border-width) solid var(--background-modifier-border);border-radius:var(--radius-m);background:var(--background-primary);box-shadow:var(--shadow-s);overflow:visible;}.matrix-corner.svelte-1j479gc,\n.header-wrapper.svelte-1j479gc {background:color-mix(in srgb, var(--background-secondary) 72%, var(--background-primary));border-bottom:var(--border-width) solid var(--background-modifier-border);border-right:var(--border-width) solid var(--background-modifier-border);min-height:64px;}.matrix-corner.svelte-1j479gc {position:sticky;left:0;top:0;z-index:7;display:flex;align-items:center;justify-content:center;min-width:0;padding:var(--size-2-1);overflow:hidden;}.matrix-task-count.svelte-1j479gc {display:block;max-width:100%;overflow:hidden;color:var(--text-muted);font-size:var(--font-ui-smaller);font-weight:500;line-height:1.15;text-align:center;text-overflow:ellipsis;white-space:normal;overflow-wrap:break-word;}.header-wrapper.svelte-1j479gc {position:sticky;top:0;z-index:5;padding:var(--size-4-2) var(--size-4-3);--column-header-x-padding-override: var(--size-4-3);--column-header-y-padding-override: var(--size-4-2);display:flex;align-items:stretch;}.header-wrapper.collapsed.svelte-1j479gc {position:sticky;top:0;display:flex;flex-direction:column;align-self:start;height:100%;min-height:100%;padding:0 var(--size-2-3) var(--size-4-3);--column-header-x-padding-override: var(--size-2-3);--column-header-y-padding-override: 0px;cursor:pointer;z-index:6;}.swimlane-header-cell.svelte-1j479gc {position:sticky;left:0;z-index:3;display:flex;align-items:start;justify-content:flex-start;min-height:188px;min-width:0;padding:var(--size-4-3) var(--size-4-4);background:color-mix(in srgb, var(--background-secondary) 72%, var(--background-primary));border-right:var(--border-width) solid var(--background-modifier-border);border-bottom:var(--border-width) solid var(--background-modifier-border);}.swimlane-header-cell.svelte-1j479gc .swimlane-label:where(.svelte-1j479gc) {position:sticky;top:calc(var(--header-height) + var(--size-4-3));left:var(--size-4-4);display:block;max-width:min(28ch, 24vw);color:var(--text-normal);font-size:var(--font-ui-medium);font-weight:var(--font-medium);line-height:1.2;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;}.cell-wrapper.svelte-1j479gc {z-index:1;min-height:188px;padding:var(--size-4-2) var(--size-4-4);display:flex;flex-direction:column;align-self:stretch;background:color-mix(in srgb, var(--background-primary) 88%, var(--background-secondary));border-right:var(--border-width) solid var(--background-modifier-border);border-bottom:var(--border-width) solid var(--background-modifier-border);}.cell-wrapper.collapsed.svelte-1j479gc {display:none;}"
};
function Board_matrix_horizontal($$anchor, $$props) {
if (new.target) return createClassComponent({ component: Board_matrix_horizontal, ...$$anchor });
push($$props, false);
append_styles($$anchor, $$css14);
const tasksByPrimary = mutable_source();
const showSwimlaneLabels = mutable_source();
const gridTemplateColumns = mutable_source();
const primaryGridColumnOffset = mutable_source();
const gridTemplateRows = mutable_source();
let app = prop($$props, "app", 12);
let matrix = prop($$props, "matrix", 12);
let taskActions = prop($$props, "taskActions", 12);
let columnTagTableStore = prop($$props, "columnTagTableStore", 12);
let columnColourTableStore = prop($$props, "columnColourTableStore", 12);
let columnMatchTagTableStore = prop($$props, "columnMatchTagTableStore", 12);
let columnSubtitleTableStore = prop($$props, "columnSubtitleTableStore", 12);
let showFilepath = prop($$props, "showFilepath", 12);
let propertyDisplay = prop($$props, "propertyDisplay", 28, () => "none" /* None */);
let propertySchemaOption = prop($$props, "propertySchemaOption", 28, () => "none" /* None */);
let consolidateTags = prop($$props, "consolidateTags", 12);
let excludedTags = prop($$props, "excludedTags", 28, () => []);
let targetTaskFile = prop($$props, "targetTaskFile", 12, null);
let targetFileIsDefault = prop($$props, "targetFileIsDefault", 12, false);
let onToggleCollapse = prop($$props, "onToggleCollapse", 12);
let uncategorizedColumnName = prop($$props, "uncategorizedColumnName", 12, void 0);
let doneColumnName = prop($$props, "doneColumnName", 12, void 0);
let columnWidth = prop($$props, "columnWidth", 12, "300px");
let isManualOrder = prop($$props, "isManualOrder", 12, false);
let manualOrder = prop($$props, "manualOrder", 28, () => ({}));
let reorderEnabled = prop($$props, "reorderEnabled", 12, false);
let treatNestedTasksAsSubtasks = prop($$props, "treatNestedTasksAsSubtasks", 12, false);
let taskCountLabel = prop($$props, "taskCountLabel", 12, "");
let headerHeight = mutable_source(64);
legacy_pre_effect(() => deep_read_state(matrix()), () => {
set(tasksByPrimary, Object.fromEntries(matrix().primaryAxis.map((bucket) => [
bucket.id,
Object.values(matrix().cells[bucket.id] || {}).flatMap((cell) => cell.tasks)
])));
});
legacy_pre_effect(() => deep_read_state(matrix()), () => {
var _a5, _b3;
set(showSwimlaneLabels, matrix().secondaryAxis.length > 1 || matrix().secondaryAxis.length > 0 && !((_b3 = (_a5 = matrix().secondaryAxis[0]) == null ? void 0 : _a5.meta) == null ? void 0 : _b3.isDefault));
});
legacy_pre_effect(
() => (get(showSwimlaneLabels), deep_read_state(matrix()), deep_read_state(columnWidth())),
() => {
set(gridTemplateColumns, [
get(showSwimlaneLabels) ? "max-content" : "56px",
...matrix().primaryAxis.map((b) => b.collapsed ? "48px" : columnWidth())
].join(" "));
}
);
legacy_pre_effect(() => {
}, () => {
set(primaryGridColumnOffset, 2);
});
legacy_pre_effect(() => deep_read_state(matrix()), () => {
set(gridTemplateRows, (() => {
const rows = ["max-content"];
for (let i = 0; i < matrix().secondaryAxis.length; i++) {
rows.push(i === matrix().secondaryAxis.length - 1 ? "minmax(188px, 1fr)" : "minmax(188px, max-content)");
}
return rows.join(" ");
})());
});
legacy_pre_effect_reset();
var $$exports = {
get app() {
return app();
},
set app($$value) {
app($$value);
flushSync();
},
get matrix() {
return matrix();
},
set matrix($$value) {
matrix($$value);
flushSync();
},
get taskActions() {
return taskActions();
},
set taskActions($$value) {
taskActions($$value);
flushSync();
},
get columnTagTableStore() {
return columnTagTableStore();
},
set columnTagTableStore($$value) {
columnTagTableStore($$value);
flushSync();
},
get columnColourTableStore() {
return columnColourTableStore();
},
set columnColourTableStore($$value) {
columnColourTableStore($$value);
flushSync();
},
get columnMatchTagTableStore() {
return columnMatchTagTableStore();
},
set columnMatchTagTableStore($$value) {
columnMatchTagTableStore($$value);
flushSync();
},
get columnSubtitleTableStore() {
return columnSubtitleTableStore();
},
set columnSubtitleTableStore($$value) {
columnSubtitleTableStore($$value);
flushSync();
},
get showFilepath() {
return showFilepath();
},
set showFilepath($$value) {
showFilepath($$value);
flushSync();
},
get propertyDisplay() {
return propertyDisplay();
},
set propertyDisplay($$value) {
propertyDisplay($$value);
flushSync();
},
get propertySchemaOption() {
return propertySchemaOption();
},
set propertySchemaOption($$value) {
propertySchemaOption($$value);
flushSync();
},
get consolidateTags() {
return consolidateTags();
},
set consolidateTags($$value) {
consolidateTags($$value);
flushSync();
},
get excludedTags() {
return excludedTags();
},
set excludedTags($$value) {
excludedTags($$value);
flushSync();
},
get targetTaskFile() {
return targetTaskFile();
},
set targetTaskFile($$value) {
targetTaskFile($$value);
flushSync();
},
get targetFileIsDefault() {
return targetFileIsDefault();
},
set targetFileIsDefault($$value) {
targetFileIsDefault($$value);
flushSync();
},
get onToggleCollapse() {
return onToggleCollapse();
},
set onToggleCollapse($$value) {
onToggleCollapse($$value);
flushSync();
},
get uncategorizedColumnName() {
return uncategorizedColumnName();
},
set uncategorizedColumnName($$value) {
uncategorizedColumnName($$value);
flushSync();
},
get doneColumnName() {
return doneColumnName();
},
set doneColumnName($$value) {
doneColumnName($$value);
flushSync();
},
get columnWidth() {
return columnWidth();
},
set columnWidth($$value) {
columnWidth($$value);
flushSync();
},
get isManualOrder() {
return isManualOrder();
},
set isManualOrder($$value) {
isManualOrder($$value);
flushSync();
},
get manualOrder() {
return manualOrder();
},
set manualOrder($$value) {
manualOrder($$value);
flushSync();
},
get reorderEnabled() {
return reorderEnabled();
},
set reorderEnabled($$value) {
reorderEnabled($$value);
flushSync();
},
get treatNestedTasksAsSubtasks() {
return treatNestedTasksAsSubtasks();
},
set treatNestedTasksAsSubtasks($$value) {
treatNestedTasksAsSubtasks($$value);
flushSync();
},
get taskCountLabel() {
return taskCountLabel();
},
set taskCountLabel($$value) {
taskCountLabel($$value);
flushSync();
},
$set: update_legacy_props,
$on: ($$event_name, $$event_cb) => add_legacy_event_listener($$props, $$event_name, $$event_cb)
};
init();
var div = root_46();
let styles;
var div_1 = child(div);
set_style(div_1, "", {}, { "grid-column": "1", "grid-row": "1" });
var node = child(div_1);
{
var consequent = ($$anchor2) => {
var span = root14();
var text2 = child(span, true);
reset(span);
template_effect(() => set_text(text2, taskCountLabel()));
append($$anchor2, span);
};
if_block(node, ($$render) => {
if (taskCountLabel()) $$render(consequent);
});
}
reset(div_1);
var node_1 = sibling(div_1, 2);
each(
node_1,
3,
() => (deep_read_state(matrix()), untrack(() => matrix().primaryAxis)),
(pBucket) => pBucket.id,
($$anchor2, pBucket, index2) => {
var div_2 = root_113();
let classes;
let styles_1;
var node_2 = child(div_2);
{
let $0 = derived_safe_equal(() => (get(tasksByPrimary), get(pBucket), untrack(() => {
var _a5;
return (_a5 = get(tasksByPrimary)[get(pBucket).id]) != null ? _a5 : [];
})));
ColumnHeader(node_2, {
get column() {
return get(pBucket), untrack(() => get(pBucket).id);
},
get tasks() {
return get($0);
},
get taskActions() {
return taskActions();
},
get columnTagTableStore() {
return columnTagTableStore();
},
get columnColourTableStore() {
return columnColourTableStore();
},
get columnMatchTagTableStore() {
return columnMatchTagTableStore();
},
get columnSubtitleTableStore() {
return columnSubtitleTableStore();
},
isVerticalFlow: false,
get isCollapsed() {
return get(pBucket), untrack(() => get(pBucket).collapsed);
},
onToggleCollapse: () => onToggleCollapse()(get(pBucket).id),
get uncategorizedColumnName() {
return uncategorizedColumnName();
},
get doneColumnName() {
return doneColumnName();
}
});
}
reset(div_2);
template_effect(() => {
classes = set_class(div_2, 1, "header-wrapper svelte-1j479gc", null, classes, { collapsed: get(pBucket).collapsed });
styles_1 = set_style(div_2, "", styles_1, {
"grid-column": get(index2) + get(primaryGridColumnOffset),
"grid-row": (get(pBucket), untrack(() => get(pBucket).collapsed ? "1 / -1" : "1")),
"--column-color": (get(pBucket), untrack(() => {
var _a5;
return (_a5 = get(pBucket).meta) == null ? void 0 : _a5.color;
}))
});
});
append($$anchor2, div_2);
}
);
var node_3 = sibling(node_1, 2);
each(
node_3,
3,
() => (deep_read_state(matrix()), untrack(() => matrix().secondaryAxis)),
(sBucket) => sBucket.id,
($$anchor2, sBucket, sIndex) => {
var fragment = root_36();
var div_3 = first_child(fragment);
let styles_2;
var node_4 = child(div_3);
{
var consequent_1 = ($$anchor3) => {
var span_1 = root_28();
var text_1 = child(span_1, true);
reset(span_1);
template_effect(() => {
set_attribute2(span_1, "title", (get(sBucket), untrack(() => get(sBucket).label)));
set_text(text_1, (get(sBucket), untrack(() => get(sBucket).label)));
});
append($$anchor3, span_1);
};
if_block(node_4, ($$render) => {
if (get(showSwimlaneLabels)) $$render(consequent_1);
});
}
reset(div_3);
var node_5 = sibling(div_3, 2);
each(
node_5,
3,
() => (deep_read_state(matrix()), untrack(() => matrix().primaryAxis)),
(pBucket) => pBucket.id,
($$anchor3, pBucket, pIndex) => {
var div_4 = root_113();
let classes_1;
let styles_3;
var node_6 = child(div_4);
{
let $0 = derived_safe_equal(() => (deep_read_state(getBoardCell), deep_read_state(matrix()), get(pBucket), get(sBucket), untrack(() => getBoardCell(matrix(), get(pBucket).id, get(sBucket).id))));
let $1 = derived_safe_equal(() => (get(tasksByPrimary), get(pBucket), untrack(() => {
var _a5;
return (_a5 = get(tasksByPrimary)[get(pBucket).id]) != null ? _a5 : [];
})));
let $2 = derived_safe_equal(() => (get(pBucket), untrack(() => {
var _a5;
return (_a5 = get(pBucket).meta) == null ? void 0 : _a5.color;
})));
let $3 = derived_safe_equal(() => (deep_read_state(manualOrder()), get(sBucket), get(pBucket), untrack(() => {
var _a5;
return (_a5 = manualOrder()[get(sBucket).id]) == null ? void 0 : _a5[get(pBucket).id];
})));
BoardCell(node_6, {
get app() {
return app();
},
get cell() {
return get($0);
},
get primaryTasks() {
return get($1);
},
get secondaryAxisBucket() {
return get(sBucket);
},
get primaryAxisLabel() {
return get(pBucket), untrack(() => get(pBucket).label);
},
get taskActions() {
return taskActions();
},
get columnTagTableStore() {
return columnTagTableStore();
},
get showFilepath() {
return showFilepath();
},
get propertyDisplay() {
return propertyDisplay();
},
get propertySchemaOption() {
return propertySchemaOption();
},
get consolidateTags() {
return consolidateTags();
},
get excludedTags() {
return excludedTags();
},
get treatNestedTasksAsSubtasks() {
return treatNestedTasksAsSubtasks();
},
isVerticalFlow: false,
get targetTaskFile() {
return targetTaskFile();
},
get targetFileIsDefault() {
return targetFileIsDefault();
},
get doneColumnName() {
return doneColumnName();
},
get isCollapsed() {
return get(pBucket), untrack(() => get(pBucket).collapsed);
},
get accentColor() {
return get($2);
},
get isManualOrder() {
return isManualOrder();
},
get manualOrderEntries() {
return get($3);
},
get reorderEnabled() {
return reorderEnabled();
}
});
}
reset(div_4);
template_effect(() => {
classes_1 = set_class(div_4, 1, "cell-wrapper svelte-1j479gc", null, classes_1, { collapsed: get(pBucket).collapsed });
styles_3 = set_style(div_4, "", styles_3, {
"grid-column": get(pIndex) + get(primaryGridColumnOffset),
"grid-row": get(sIndex) + 2,
"--column-color": (get(pBucket), untrack(() => {
var _a5;
return (_a5 = get(pBucket).meta) == null ? void 0 : _a5.color;
}))
});
});
append($$anchor3, div_4);
}
);
template_effect(() => {
set_attribute2(div_3, "aria-hidden", !get(showSwimlaneLabels));
styles_2 = set_style(div_3, "", styles_2, { "grid-column": "1", "grid-row": get(sIndex) + 2 });
});
append($$anchor2, fragment);
}
);
reset(div);
template_effect(() => {
var _a5;
return styles = set_style(div, "", styles, {
"grid-template-columns": get(gridTemplateColumns),
"grid-template-rows": get(gridTemplateRows),
"--header-height": `${(_a5 = get(headerHeight)) != null ? _a5 : ""}px`,
"--sticky-left-offset": "56px"
});
});
bind_element_size(div_1, "clientHeight", ($$value) => set(headerHeight, $$value));
append($$anchor, div);
return pop($$exports);
}
// src/ui/components/select/compact_tag_select.svelte
var root15 = from_html(`<input class="svelte-1j8ru35"/>`);
var root_114 = from_html(`<!> <span role="listitem" draggable="true"><span class="tag-chip-text svelte-1j8ru35"> </span> <button type="button" class="tag-chip-remove svelte-1j8ru35">\xD7</button></span>`, 1);
var root_29 = from_html(`<!> <!>`, 1);
var root_37 = from_html(`<li><button type="button" role="option" aria-selected="false" class="svelte-1j8ru35"> </button></li>`);
var root_47 = from_html(`<ul class="option-list svelte-1j8ru35" role="listbox"></ul>`);
var root_55 = from_html(`<div class="compact-tag-select svelte-1j8ru35"><div role="combobox" aria-haspopup="listbox" tabindex="0"><!></div> <!></div>`);
var $$css15 = {
hash: "svelte-1j8ru35",
code: ".compact-tag-select.svelte-1j8ru35 {--compact-tag-select-reserve: 64px;--compact-tag-chip-bg: color-mix(\n in srgb,\n var(--interactive-accent) 10%,\n var(--background-modifier-form-field, var(--background-primary))\n );--compact-tag-chip-border: color-mix(\n in srgb,\n var(--interactive-accent) 24%,\n var(--background-modifier-border)\n );--compact-tag-chip-color: var(--text-normal);position:relative;width:100%;min-width:0;max-width:100%;font-size:var(--compact-tag-select-font-size, var(--font-ui-smaller));}.select-shell.svelte-1j8ru35 {display:flex;align-items:center;gap:4px;flex-wrap:wrap;width:100%;min-height:var(--compact-tag-select-height, 24px);min-width:0;max-width:100%;box-sizing:border-box;padding:2px 8px;border:var(--border-width) solid var(--background-modifier-border);border-radius:var(--input-radius);background:var(--background-modifier-form-field, var(--background-primary));color:var(--text-normal);}.select-shell.focused.svelte-1j8ru35 {border-color:var(--background-modifier-border-focus);}input.svelte-1j8ru35 {flex:0 1 auto;min-width:1ch;max-width:100%;border:0 !important;background:transparent !important;box-shadow:none !important;appearance:none !important;color:var(--text-normal);font-size:var(--compact-tag-select-font-size, var(--font-ui-smaller));line-height:calc(var(--compact-tag-select-height, 24px) - 6px);margin:0;padding:0;caret-color:var(--text-normal);}input.svelte-1j8ru35::placeholder {color:var(--text-faint);}input.svelte-1j8ru35:focus-visible {outline:none;}.tag-chip.svelte-1j8ru35 {display:inline-flex;align-items:center;gap:2px;min-height:20px;border:var(--border-width) solid var(--compact-tag-chip-border);border-radius:var(--pill-radius, 8px);background:var(--compact-tag-chip-bg);color:var(--compact-tag-chip-color);cursor:grab;line-height:1;font-size:calc(var(--font-ui-smaller) - 1px);padding:2px 4px 2px 8px;}.tag-chip.dragging.svelte-1j8ru35 {opacity:0.45;cursor:grabbing;}.tag-chip-text.svelte-1j8ru35 {display:inline-flex;align-items:center;line-height:1;}.tag-chip-remove.svelte-1j8ru35 {display:inline-flex;align-items:center;justify-content:center;width:16px;height:16px;padding:0;border:0;background:transparent;color:var(--compact-tag-chip-color);cursor:pointer;box-shadow:none;}.option-list.svelte-1j8ru35 {position:absolute;top:calc(100% + 2px);left:0;z-index:1000;min-width:100%;width:max-content;max-width:min(320px, 100vw - 32px);margin:0;padding:4px 0;list-style:none;border:var(--border-width) solid var(--background-modifier-border);border-radius:var(--radius-s);background:var(--background-modifier-form-field, var(--background-primary));box-shadow:var(--shadow-s);}.option-list.svelte-1j8ru35 button:where(.svelte-1j8ru35) {display:block;width:100%;border:0;border-radius:0;background:transparent;box-shadow:none;color:var(--text-normal);cursor:pointer;font-size:var(--font-ui-smaller);font-weight:var(--font-normal);padding:var(--size-2-2) var(--size-4-3);text-align:left;white-space:nowrap;}.option-list.svelte-1j8ru35 button:where(.svelte-1j8ru35):hover {background:var(--background-modifier-hover);}"
};
function Compact_tag_select($$anchor, $$props) {
if (new.target) return createClassComponent({ component: Compact_tag_select, ...$$anchor });
push($$props, false);
append_styles($$anchor, $$css15);
const normalizedItems = mutable_source();
const selectedValues = mutable_source();
const selectedLowercase = mutable_source();
const trimmedFilter = mutable_source();
const matchingItems = mutable_source();
const hasCustomOption = mutable_source();
const options = mutable_source();
const visiblePlaceholder = mutable_source();
const inputWidthCh = mutable_source();
let items = prop($$props, "items", 28, () => []);
let value = prop($$props, "value", 28, () => []);
let maxSelected = prop($$props, "maxSelected", 12, 1);
let placeholder = prop($$props, "placeholder", 12, "");
let ariaLabel = prop($$props, "ariaLabel", 12, "Tag selector");
const dispatch = createEventDispatcher();
const listboxId = `compact-tag-select-${Math.random().toString(36).slice(2)}`;
let filterText = mutable_source("");
let insertIndex = mutable_source(0);
let isOpen = mutable_source(false);
let inputEl = mutable_source();
let rootEl = mutable_source();
let dragIndex = mutable_source(null);
let dragOverIndex = null;
onMount(() => {
document.addEventListener("pointerdown", handleDocumentPointerDown);
});
onDestroy(() => {
document.removeEventListener("pointerdown", handleDocumentPointerDown);
});
function handleDocumentPointerDown(event2) {
if (get(rootEl) && !get(rootEl).contains(event2.target)) {
set(isOpen, false);
}
}
function normalizeValues(values) {
const seen = /* @__PURE__ */ new Set();
const normalized = [];
for (const rawValue of values) {
const entry = rawValue.trim();
const key2 = entry.toLowerCase();
if (!entry || seen.has(key2)) continue;
seen.add(key2);
normalized.push(entry);
}
return maxSelected() > 0 ? normalized.slice(-maxSelected()) : normalized;
}
function commit(nextValue, nextInsertIndex = get(insertIndex)) {
const normalized = normalizeValues(nextValue);
value(normalized);
set(insertIndex, Math.min(Math.max(nextInsertIndex, 0), normalized.length));
dispatch("change", normalized);
}
async function focusAt(index2) {
var _a5;
set(insertIndex, Math.min(Math.max(index2, 0), get(selectedValues).length));
set(isOpen, true);
await tick();
(_a5 = get(inputEl)) == null ? void 0 : _a5.focus();
}
function addTag(rawTag) {
const tag2 = rawTag.trim();
if (!tag2) return;
const existingIndex = get(selectedValues).findIndex((item) => item.toLowerCase() === tag2.toLowerCase());
const insertionIndex = existingIndex >= 0 && existingIndex < get(insertIndex) ? get(insertIndex) - 1 : get(insertIndex);
const withoutExisting = get(selectedValues).filter((item) => item.toLowerCase() !== tag2.toLowerCase());
const nextValue = [
...withoutExisting.slice(0, insertionIndex),
tag2,
...withoutExisting.slice(insertionIndex)
];
const nextInsertIndex = maxSelected() === 1 ? 1 : insertionIndex + 1;
set(filterText, "");
set(isOpen, true);
commit(nextValue, nextInsertIndex);
set(insertIndex, nextInsertIndex);
void tick().then(() => {
var _a5;
return (_a5 = get(inputEl)) == null ? void 0 : _a5.focus();
});
}
function removeTag(index2) {
const nextValue = get(selectedValues).filter((_, currentIndex) => currentIndex !== index2);
commit(nextValue, index2);
void focusAt(index2);
}
function handleInputFocus() {
set(isOpen, true);
}
function handleInputKeydown(event2) {
if (event2.key === "Enter" || event2.key === ",") {
event2.preventDefault();
addTag(get(trimmedFilter) || get(options)[0] || "");
} else if (event2.key === "Backspace" && get(filterText) === "" && get(insertIndex) > 0) {
event2.preventDefault();
removeTag(get(insertIndex) - 1);
} else if (event2.key === "ArrowLeft" && get(filterText) === "" && get(insertIndex) > 0) {
event2.preventDefault();
void focusAt(get(insertIndex) - 1);
} else if (event2.key === "ArrowRight" && get(filterText) === "" && get(insertIndex) < get(selectedValues).length) {
event2.preventDefault();
void focusAt(get(insertIndex) + 1);
} else if (event2.key === "Escape") {
set(isOpen, false);
}
}
function handleShellKeydown(event2) {
if (event2.target === get(inputEl)) return;
if (event2.key === "Enter" || event2.key === " ") {
event2.preventDefault();
void focusAt(get(insertIndex));
}
}
function getInsertIndexFromPoint(clientX, clientY) {
const chips = get(rootEl) ? Array.from(get(rootEl).querySelectorAll(".tag-chip")) : [];
for (let index2 = 0; index2 < chips.length; index2 += 1) {
const rect = chips[index2].getBoundingClientRect();
if (clientY < rect.top) return index2;
if (clientY <= rect.bottom) {
return clientX < rect.left + rect.width / 2 ? index2 : index2 + 1;
}
}
return get(selectedValues).length;
}
function handleShellClick(event2) {
if (event2.target === get(inputEl)) return;
void focusAt(getInsertIndexFromPoint(event2.clientX, event2.clientY));
}
function reorderTag(fromIndex, toIndex) {
if (fromIndex === toIndex || fromIndex < 0 || fromIndex >= get(selectedValues).length) return;
const nextValue = [...get(selectedValues)];
const [moved] = nextValue.splice(fromIndex, 1);
if (!moved) return;
const adjustedIndex = fromIndex < toIndex ? toIndex - 1 : toIndex;
nextValue.splice(adjustedIndex, 0, moved);
commit(nextValue, adjustedIndex + 1);
}
function handleDragStart(event2, index2) {
var _a5, _b3;
set(dragIndex, index2);
(_b3 = event2.dataTransfer) == null ? void 0 : _b3.setData("text/plain", (_a5 = get(selectedValues)[index2]) != null ? _a5 : "");
if (event2.dataTransfer) {
event2.dataTransfer.effectAllowed = "move";
}
}
function handleDragOver(event2) {
event2.preventDefault();
dragOverIndex = getInsertIndexFromPoint(event2.clientX, event2.clientY);
if (event2.dataTransfer) {
event2.dataTransfer.dropEffect = "move";
}
}
function handleDrop(event2) {
event2.preventDefault();
if (get(dragIndex) !== null) {
reorderTag(get(dragIndex), dragOverIndex != null ? dragOverIndex : getInsertIndexFromPoint(event2.clientX, event2.clientY));
}
set(dragIndex, null);
dragOverIndex = null;
}
function handleDragEnd() {
set(dragIndex, null);
dragOverIndex = null;
}
legacy_pre_effect(() => deep_read_state(items()), () => {
set(normalizedItems, [
...new Set(items().map((item) => item.trim()).filter(Boolean))
].sort((a, b) => a.localeCompare(b)));
});
legacy_pre_effect(() => deep_read_state(value()), () => {
set(selectedValues, normalizeValues(value()));
});
legacy_pre_effect(() => get(selectedValues), () => {
set(selectedLowercase, new Set(get(selectedValues).map((item) => item.toLowerCase())));
});
legacy_pre_effect(() => get(filterText), () => {
set(trimmedFilter, get(filterText).trim());
});
legacy_pre_effect(
() => (get(normalizedItems), get(selectedLowercase), get(trimmedFilter)),
() => {
set(matchingItems, get(normalizedItems).filter((item) => !get(selectedLowercase).has(item.toLowerCase())).filter((item) => item.toLowerCase().includes(get(trimmedFilter).toLowerCase())));
}
);
legacy_pre_effect(
() => (get(trimmedFilter), get(selectedLowercase), get(normalizedItems)),
() => {
set(hasCustomOption, get(trimmedFilter).length > 0 && !get(selectedLowercase).has(get(trimmedFilter).toLowerCase()) && !get(normalizedItems).some((item) => item.toLowerCase() === get(trimmedFilter).toLowerCase()));
}
);
legacy_pre_effect(
() => (get(hasCustomOption), get(trimmedFilter), get(matchingItems)),
() => {
set(options, get(hasCustomOption) ? [get(trimmedFilter), ...get(matchingItems)] : get(matchingItems));
}
);
legacy_pre_effect(() => (get(selectedValues), deep_read_state(placeholder())), () => {
set(visiblePlaceholder, get(selectedValues).length === 0 ? placeholder() : "");
});
legacy_pre_effect(
() => (get(filterText), get(visiblePlaceholder), get(selectedValues)),
() => {
set(inputWidthCh, Math.max((get(filterText) || get(visiblePlaceholder)).length + 1, get(selectedValues).length === 0 ? 8 : 1));
}
);
legacy_pre_effect(() => (get(insertIndex), get(selectedValues)), () => {
if (get(insertIndex) > get(selectedValues).length) {
set(insertIndex, get(selectedValues).length);
}
});
legacy_pre_effect_reset();
var $$exports = {
get items() {
return items();
},
set items($$value) {
items($$value);
flushSync();
},
get value() {
return value();
},
set value($$value) {
value($$value);
flushSync();
},
get maxSelected() {
return maxSelected();
},
set maxSelected($$value) {
maxSelected($$value);
flushSync();
},
get placeholder() {
return placeholder();
},
set placeholder($$value) {
placeholder($$value);
flushSync();
},
get ariaLabel() {
return ariaLabel();
},
set ariaLabel($$value) {
ariaLabel($$value);
flushSync();
},
$set: update_legacy_props,
$on: ($$event_name, $$event_cb) => add_legacy_event_listener($$props, $$event_name, $$event_cb)
};
init();
var div = root_55();
var div_1 = child(div);
let classes;
var node = child(div_1);
{
var consequent = ($$anchor2) => {
var input = root15();
remove_input_defaults(input);
let styles;
bind_this(input, ($$value) => set(inputEl, $$value), () => get(inputEl));
template_effect(() => {
set_attribute2(input, "placeholder", get(visiblePlaceholder));
set_attribute2(input, "aria-label", ariaLabel());
styles = set_style(input, "", styles, { width: `${get(inputWidthCh)}ch` });
});
bind_value(input, () => get(filterText), ($$value) => set(filterText, $$value));
event("focus", input, handleInputFocus);
event("keydown", input, handleInputKeydown);
append($$anchor2, input);
};
var alternate = ($$anchor2) => {
var fragment = root_29();
var node_1 = first_child(fragment);
each(node_1, 3, () => get(selectedValues), (tag2) => tag2.toLowerCase(), ($$anchor3, tag2, index2) => {
var fragment_1 = root_114();
var node_2 = first_child(fragment_1);
{
var consequent_1 = ($$anchor4) => {
var input_1 = root15();
remove_input_defaults(input_1);
let styles_1;
bind_this(input_1, ($$value) => set(inputEl, $$value), () => get(inputEl));
template_effect(() => {
set_attribute2(input_1, "placeholder", get(visiblePlaceholder));
set_attribute2(input_1, "aria-label", ariaLabel());
styles_1 = set_style(input_1, "", styles_1, { width: `${get(inputWidthCh)}ch` });
});
bind_value(input_1, () => get(filterText), ($$value) => set(filterText, $$value));
event("focus", input_1, handleInputFocus);
event("keydown", input_1, handleInputKeydown);
append($$anchor4, input_1);
};
if_block(node_2, ($$render) => {
if (get(insertIndex) === get(index2)) $$render(consequent_1);
});
}
var span = sibling(node_2, 2);
let classes_1;
var span_1 = child(span);
var text2 = child(span_1, true);
reset(span_1);
var button = sibling(span_1, 2);
reset(span);
template_effect(() => {
classes_1 = set_class(span, 1, "tag-chip svelte-1j8ru35", null, classes_1, { dragging: get(dragIndex) === get(index2) });
set_text(text2, get(tag2));
set_attribute2(button, "aria-label", `Remove ${get(tag2)}`);
});
event("click", button, stopPropagation(() => removeTag(get(index2))));
event("dragstart", span, (event2) => handleDragStart(event2, get(index2)));
event("dragend", span, handleDragEnd);
append($$anchor3, fragment_1);
});
var node_3 = sibling(node_1, 2);
{
var consequent_2 = ($$anchor3) => {
var input_2 = root15();
remove_input_defaults(input_2);
let styles_2;
bind_this(input_2, ($$value) => set(inputEl, $$value), () => get(inputEl));
template_effect(() => {
set_attribute2(input_2, "placeholder", get(visiblePlaceholder));
set_attribute2(input_2, "aria-label", ariaLabel());
styles_2 = set_style(input_2, "", styles_2, { width: `${get(inputWidthCh)}ch` });
});
bind_value(input_2, () => get(filterText), ($$value) => set(filterText, $$value));
event("focus", input_2, handleInputFocus);
event("keydown", input_2, handleInputKeydown);
append($$anchor3, input_2);
};
if_block(node_3, ($$render) => {
if (get(insertIndex), get(selectedValues), untrack(() => get(insertIndex) === get(selectedValues).length)) $$render(consequent_2);
});
}
append($$anchor2, fragment);
};
if_block(node, ($$render) => {
if (get(selectedValues), untrack(() => get(selectedValues).length === 0)) $$render(consequent);
else $$render(alternate, -1);
});
}
reset(div_1);
var node_4 = sibling(div_1, 2);
{
var consequent_3 = ($$anchor2) => {
var ul = root_47();
each(ul, 5, () => get(options), (option) => option.toLowerCase(), ($$anchor3, option) => {
var li = root_37();
var button_1 = child(li);
var text_1 = child(button_1, true);
reset(button_1);
reset(li);
template_effect(() => set_text(text_1, get(option)));
event("mousedown", button_1, preventDefault(function($$arg) {
bubble_event.call(this, $$props, $$arg);
}));
event("click", button_1, () => addTag(get(option)));
append($$anchor3, li);
});
reset(ul);
template_effect(() => set_attribute2(ul, "id", listboxId));
append($$anchor2, ul);
};
if_block(node_4, ($$render) => {
if (get(isOpen), get(options), untrack(() => get(isOpen) && get(options).length > 0)) $$render(consequent_3);
});
}
reset(div);
bind_this(div, ($$value) => set(rootEl, $$value), () => get(rootEl));
template_effect(() => {
classes = set_class(div_1, 1, "select-shell svelte-1j8ru35", null, classes, { focused: get(isOpen) });
set_attribute2(div_1, "aria-controls", listboxId);
set_attribute2(div_1, "aria-expanded", get(isOpen) ? "true" : "false");
});
event("click", div_1, handleShellClick);
event("keydown", div_1, handleShellKeydown);
event("dragover", div_1, handleDragOver);
event("drop", div_1, handleDrop);
append($$anchor, div);
return pop($$exports);
}
// src/ui/views/saved_views.ts
var SAVED_VIEW_PROPERTIES = [
{ key: "query", label: "Filter" },
{ key: "sort", label: "Sort" },
{ key: "group", label: "Group" },
{ key: "flowDirection", label: "Flow" },
{ key: "columnWidth", label: "Width" }
];
function hasOwn(object, key2) {
return Object.prototype.hasOwnProperty.call(object, key2);
}
function captureSavedViewProperties(settings, overrides) {
var _a5, _b3, _c2, _d, _e, _f, _g;
const properties = {};
if (hasOwn(overrides, "lastFilter") && settings.lastFilter) {
properties.query = settings.lastFilter;
}
if (hasOwn(overrides, "columnOrderMode") || hasOwn(overrides, "sortProperty") || hasOwn(overrides, "sortDirection")) {
properties.sort = {
mode: (_a5 = settings.columnOrderMode) != null ? _a5 : "file" /* FileOrder */,
property: (_b3 = settings.sortProperty) != null ? _b3 : null,
direction: (_c2 = settings.sortDirection) != null ? _c2 : "asc"
};
}
if (hasOwn(overrides, "groupSource") || hasOwn(overrides, "groupDirection")) {
properties.group = {
source: structuredClone((_d = settings.groupSource) != null ? _d : { kind: "none" }),
direction: (_e = settings.groupDirection) != null ? _e : "asc"
};
}
if (hasOwn(overrides, "flowDirection")) {
properties.flowDirection = (_f = settings.flowDirection) != null ? _f : "ltr" /* LeftToRight */;
}
if (hasOwn(overrides, "columnWidth")) {
properties.columnWidth = (_g = settings.columnWidth) != null ? _g : 300;
}
return properties;
}
function savedViewHasProperties(view) {
return SAVED_VIEW_PROPERTIES.some(({ key: key2 }) => view[key2] !== void 0);
}
function savedViewPropertyLabels(view) {
return SAVED_VIEW_PROPERTIES.filter(({ key: key2 }) => view[key2] !== void 0).map(
({ label }) => label
);
}
function savedViewIsQueryOnly(view) {
return view.query !== void 0 && SAVED_VIEW_PROPERTIES.every(
({ key: key2 }) => key2 === "query" || view[key2] === void 0
);
}
function defaultSavedViewName(properties) {
const labels = savedViewPropertyLabels(properties);
return labels.length > 0 ? labels.join(" + ") : "View";
}
function applySavedViewProperties(settings, view) {
var _a5;
const next2 = { ...settings };
if (view.sort) {
next2.columnOrderMode = view.sort.mode;
next2.sortProperty = (_a5 = view.sort.property) != null ? _a5 : null;
next2.sortDirection = view.sort.direction;
}
if (view.group) {
next2.groupSource = structuredClone(view.group.source);
next2.groupDirection = view.group.direction;
}
if (view.flowDirection !== void 0) {
next2.flowDirection = view.flowDirection;
}
if (view.columnWidth !== void 0) {
next2.columnWidth = view.columnWidth;
}
return next2;
}
function mergeLocalAndGlobalSavedViews(localViews = [], globalViews = []) {
return [
...localViews.map((view) => ({ ...view, isGlobal: false })),
...globalViews.map((view) => ({ ...view, isGlobal: true }))
];
}
// src/ui/views/view_editor_options.ts
var SORT_FILE_VALUE = "__file__";
var SORT_TASK_NAME_VALUE = "__task_name__";
var SORT_MANUAL_VALUE = "__manual__";
var PROPERTY_OPTION_PREFIX = "prop:";
function propertyOptionValue(key2) {
return `${PROPERTY_OPTION_PREFIX}${key2}`;
}
function propertyKeyFromOptionValue(value) {
return value.startsWith(PROPERTY_OPTION_PREFIX) ? value.slice(PROPERTY_OPTION_PREFIX.length) : void 0;
}
function sortSelectValueFor(mode, sortProperty) {
switch (mode) {
case "manual" /* Manual */:
return SORT_MANUAL_VALUE;
case "task-name" /* TaskName */:
return SORT_TASK_NAME_VALUE;
case "property" /* Property */:
return sortProperty ? propertyOptionValue(sortProperty) : SORT_FILE_VALUE;
default:
return SORT_FILE_VALUE;
}
}
function sortSelectionFromValue(value) {
const property = propertyKeyFromOptionValue(value);
if (property !== void 0) {
return { mode: "property" /* Property */, property };
}
if (value === SORT_TASK_NAME_VALUE) {
return { mode: "task-name" /* TaskName */ };
}
if (value === SORT_MANUAL_VALUE) {
return { mode: "manual" /* Manual */ };
}
return { mode: "file" /* FileOrder */ };
}
// src/ui/view_editor.svelte
var root16 = from_html(`<option> </option>`);
var root_115 = from_html(`<optgroup label="Properties"></optgroup>`);
var root_210 = from_html(`<button type="button" class="view-editor-icon-button svelte-1lpntxd" aria-label="Toggle sort direction"><!></button>`);
var root_38 = from_html(`<button type="button" class="view-editor-icon-button svelte-1lpntxd" aria-label="Toggle group direction"><!></button>`);
var root_48 = from_html(`<label class="view-editor-toggle-row svelte-1lpntxd"><input type="checkbox" class="svelte-1lpntxd"/> <span>Combine past dates</span></label>`);
var root_56 = from_html(`<input type="text" class="grouping-prefix-input svelte-1lpntxd" placeholder="Prefix" aria-label="Tag group prefix"/>`);
var root_64 = from_html(`<div class="view-editor-row view-editor-subrow svelte-1lpntxd"><div class="view-editor-label svelte-1lpntxd"><span>Tags</span></div> <div class="view-editor-controls view-editor-controls-stack svelte-1lpntxd"><div class="tag-group-input-row svelte-1lpntxd"><div class="tag-group-mode-toggle svelte-1lpntxd"><button type="button">Prefix</button> <button type="button">Include</button></div> <div class="tag-group-input svelte-1lpntxd"><!></div></div></div></div>`);
var root_73 = from_html(`<span class="saved-view-source svelte-1lpntxd" title="Global saved view">Global</span>`);
var root_82 = from_html(`<button type="button" class="saved-view-delete svelte-1lpntxd">\xD7</button>`);
var root_92 = from_html(`<span class="svelte-1lpntxd"> </span>`);
var root_102 = from_html(`<li class="svelte-1lpntxd"><!> <button type="button" class="saved-view-name svelte-1lpntxd"><span class="saved-view-title svelte-1lpntxd"> </span> <span class="saved-view-badges svelte-1lpntxd"></span></button></li>`);
var root_116 = from_html(`<ul class="saved-view-list svelte-1lpntxd" role="list"></ul>`);
var root_123 = from_html(`<p class="view-editor-hint svelte-1lpntxd">No saved views yet.</p>`);
var root_133 = from_html(`<div class="view-editor-controls view-editor-controls-stack svelte-1lpntxd"><!></div>`);
var root_143 = from_html(`<section class="view-editor svelte-1lpntxd" aria-label="View settings"><div class="view-editor-row svelte-1lpntxd"><div class="view-editor-label svelte-1lpntxd"><span>Sort</span></div> <div class="view-editor-controls svelte-1lpntxd"><select class="dropdown view-editor-select svelte-1lpntxd" aria-label="Sort tasks"><option>File order</option><option>Task name</option><option>Manual</option><!></select> <!></div></div> <div class="view-editor-row svelte-1lpntxd"><div class="view-editor-label svelte-1lpntxd"><span>Group</span></div> <div class="view-editor-controls view-editor-controls-stack svelte-1lpntxd"><div class="view-editor-inline-controls svelte-1lpntxd"><select class="dropdown view-editor-select svelte-1lpntxd" aria-label="Group tasks"><option>None</option><option>File</option><option>Tag</option><!></select> <!></div> <!></div></div> <!> <div class="view-editor-row svelte-1lpntxd"><div class="view-editor-label svelte-1lpntxd"><span>Flow</span></div> <div class="view-editor-controls svelte-1lpntxd"><select class="dropdown view-editor-select svelte-1lpntxd" aria-label="Flow direction"></select></div></div> <div class="view-editor-row svelte-1lpntxd"><div class="view-editor-label svelte-1lpntxd"><span>Card width</span></div> <div class="view-editor-controls svelte-1lpntxd"><div class="card-width-control svelte-1lpntxd"><input type="range" min="200" max="600" step="10" aria-label="Card width" class="svelte-1lpntxd"/> <output class="svelte-1lpntxd"> </output></div></div></div> <div class="view-editor-row svelte-1lpntxd"><div class="view-editor-label svelte-1lpntxd"><span>Save as</span></div> <div class="view-editor-controls view-editor-controls-stack svelte-1lpntxd"><div class="save-view-row svelte-1lpntxd"><input type="text" class="view-editor-text-input svelte-1lpntxd" placeholder="Name (optional)" aria-label="Saved view name" spellcheck="false"/> <button type="button" class="save-view-button svelte-1lpntxd">Save</button></div> <p class="view-editor-hint svelte-1lpntxd"><!></p></div></div> <div class="view-editor-row saved-views-section svelte-1lpntxd"><button type="button" class="saved-views-toggle svelte-1lpntxd"><!> <span>Saved views</span></button> <!></div></section>`);
var $$css16 = {
hash: "svelte-1lpntxd",
code: ".view-editor.svelte-1lpntxd {--view-editor-control-height: 34px;position:relative;z-index:40;width:100%;max-width:none;margin:0;padding:var(--size-4-3) var(--size-4-4);background:var(--background-primary);border:var(--input-border-width, 1px) solid var(--background-modifier-border);border-radius:var(--radius-m);box-shadow:var(--shadow-s);display:grid;gap:var(--size-4-2);}.view-editor-row.svelte-1lpntxd {display:grid;grid-template-columns:88px minmax(0, 1fr);gap:var(--size-4-2);align-items:start;min-height:var(--view-editor-control-height);}.view-editor-subrow.svelte-1lpntxd {padding-top:var(--size-2-3);border-top:1px solid var(--background-modifier-border);}.view-editor-label.svelte-1lpntxd {display:flex;align-items:center;min-height:var(--view-editor-control-height);color:var(--text-muted);font-size:var(--font-ui-small);font-weight:400;line-height:1.2;}.view-editor-controls.svelte-1lpntxd,\n.view-editor-inline-controls.svelte-1lpntxd {display:flex;align-items:center;gap:var(--size-2-2);min-height:var(--view-editor-control-height);min-width:0;}.view-editor-controls-stack.svelte-1lpntxd {align-items:flex-start;flex-direction:column;}.view-editor-select.svelte-1lpntxd {flex:1 1 auto;min-width:280px;max-width:360px;height:var(--view-editor-control-height);min-height:0;box-sizing:border-box;background-color:transparent;border:none;border-bottom:1px solid var(--background-modifier-border);border-radius:0;box-shadow:none;padding:0 var(--size-4-4) 0 0;font-size:var(--font-ui-small);line-height:var(--view-editor-control-height);}.view-editor-select.svelte-1lpntxd:hover {background-color:transparent;box-shadow:none;}.view-editor-select.svelte-1lpntxd:focus, .view-editor-select.svelte-1lpntxd:focus-visible {border-bottom-color:var(--interactive-accent);box-shadow:none;outline:none;}.view-editor-text-input.svelte-1lpntxd {flex:1 1 auto;min-width:0;height:var(--view-editor-control-height);min-height:0;box-sizing:border-box;background:transparent;border:none;border-bottom:1px solid var(--background-modifier-border);border-radius:0;box-shadow:none;padding:0;font-size:var(--font-ui-small);line-height:var(--view-editor-control-height);}.view-editor-text-input.svelte-1lpntxd:focus, .view-editor-text-input.svelte-1lpntxd:focus-visible {border-bottom-color:var(--interactive-accent);box-shadow:none;outline:none;}.view-editor-icon-button.svelte-1lpntxd {display:inline-flex;align-items:center;justify-content:center;border:none;border-radius:999px;background:transparent;box-shadow:none;color:var(--text-muted);cursor:pointer;width:var(--view-editor-control-height);height:var(--view-editor-control-height);box-sizing:border-box;padding:0;}.view-editor-icon-button.svelte-1lpntxd:hover {color:var(--text-normal);background:var(--background-modifier-hover);}.view-editor-icon-button.svelte-1lpntxd:disabled {cursor:default;opacity:0.5;}.view-editor-toggle-row.svelte-1lpntxd {display:inline-flex;align-items:center;gap:var(--size-2-1);padding-top:var(--size-2-1);font-size:var(--font-ui-small);line-height:1;color:var(--text-muted);cursor:pointer;}.view-editor-toggle-row.svelte-1lpntxd input[type=checkbox]:where(.svelte-1lpntxd) {margin:0;--checkbox-size: 12px;}.view-editor-toggle-row.svelte-1lpntxd:hover {color:var(--text-normal);}.tag-group-input-row.svelte-1lpntxd {--tag-group-control-height: 30px;display:grid;grid-template-columns:auto minmax(180px, 1fr);align-items:center;gap:var(--size-2-3);width:min(100%, 440px);min-width:0;}.tag-group-mode-toggle.svelte-1lpntxd {display:inline-flex;align-items:stretch;border:var(--input-border-width, 1px) solid var(--background-modifier-border);border-radius:var(--input-radius);overflow:hidden;background:var(--background-modifier-form-field, var(--background-primary));height:var(--tag-group-control-height);}.tag-group-mode-toggle.svelte-1lpntxd button:where(.svelte-1lpntxd) {display:inline-flex;align-items:center;justify-content:center;height:100%;min-height:0;margin:0;border:0;border-radius:0;box-shadow:none;background:transparent;color:var(--text-muted);font-size:var(--font-ui-smaller);line-height:1;padding:var(--size-2-1) var(--size-2-3);cursor:pointer;}.tag-group-mode-toggle.svelte-1lpntxd button:where(.svelte-1lpntxd):hover {color:var(--text-normal);background:var(--background-modifier-hover);}.tag-group-mode-toggle.svelte-1lpntxd button.active:where(.svelte-1lpntxd) {background:var(--interactive-accent);color:var(--text-on-accent);}.tag-group-mode-toggle.svelte-1lpntxd button:where(.svelte-1lpntxd):focus-visible {outline:2px solid var(--background-modifier-border-focus);outline-offset:-2px;}.tag-group-mode-toggle.svelte-1lpntxd button:where(.svelte-1lpntxd) + button:where(.svelte-1lpntxd) {border-left:var(--input-border-width, 1px) solid var(--background-modifier-border);}.tag-group-input.svelte-1lpntxd {min-width:0;--compact-tag-select-height: var(--tag-group-control-height);--compact-tag-select-font-size: var(--font-ui-small);}.grouping-prefix-input.svelte-1lpntxd {width:100%;height:var(--tag-group-control-height);font-size:var(--font-ui-small);background:transparent;border:none;border-bottom:1px solid var(--background-modifier-border);border-radius:0;box-shadow:none;}.grouping-prefix-input.svelte-1lpntxd:focus, .grouping-prefix-input.svelte-1lpntxd:focus-visible {border-bottom-color:var(--interactive-accent);box-shadow:none;outline:none;}.card-width-control.svelte-1lpntxd {display:grid;grid-template-columns:minmax(180px, 1fr) 48px;align-items:center;gap:var(--size-2-2);width:min(100%, 360px);min-height:var(--view-editor-control-height);color:var(--text-muted);font-size:var(--font-ui-small);}.card-width-control.svelte-1lpntxd input[type=range]:where(.svelte-1lpntxd) {width:100%;margin:0;}.card-width-control.svelte-1lpntxd output:where(.svelte-1lpntxd) {color:var(--text-normal);font-variant-numeric:tabular-nums;text-align:right;}.save-view-row.svelte-1lpntxd {display:flex;align-items:center;gap:var(--size-2-3);width:min(100%, 440px);min-width:0;}.save-view-button.svelte-1lpntxd {flex:0 0 auto;padding:var(--size-2-2) var(--size-4-3);background:transparent;color:var(--text-muted);border:1px solid var(--background-modifier-border);border-radius:999px;box-shadow:none;cursor:pointer;font-size:var(--font-ui-small);}.save-view-button.svelte-1lpntxd:hover:not(:disabled) {color:var(--text-normal);background:var(--background-modifier-hover);}.save-view-button.svelte-1lpntxd:disabled {opacity:0.5;cursor:default;color:var(--text-muted);}.view-editor-hint.svelte-1lpntxd {margin:0;color:var(--text-faint);font-size:var(--font-ui-smaller);line-height:1.2;}.saved-views-section.svelte-1lpntxd {padding-top:var(--size-2-3);border-top:1px solid var(--background-modifier-border);}.saved-views-toggle.svelte-1lpntxd {display:inline-flex;align-items:center;gap:var(--size-2-1);min-height:var(--view-editor-control-height);width:fit-content;margin:0;padding:0;border:none;border-radius:0;background:transparent;box-shadow:none;color:var(--text-muted);font-size:var(--font-ui-small);font-weight:500;cursor:pointer;}.saved-views-toggle.svelte-1lpntxd:hover {color:var(--text-normal);background:transparent;box-shadow:none;}.saved-view-list.svelte-1lpntxd {display:flex;flex-direction:column;gap:var(--size-2-1);width:min(100%, 520px);margin:0;padding:0;list-style:none;}.saved-view-list.svelte-1lpntxd li:where(.svelte-1lpntxd) {display:flex;align-items:center;gap:var(--size-2-1);min-height:30px;}.saved-view-source.svelte-1lpntxd,\n.saved-view-delete.svelte-1lpntxd,\n.saved-view-name.svelte-1lpntxd {display:inline-flex;align-items:center;margin:0;border:none;border-radius:var(--radius-s);background:transparent;box-shadow:none;cursor:pointer;}.saved-view-delete.svelte-1lpntxd {justify-content:center;flex:0 0 auto;padding:var(--size-2-1);color:var(--text-muted);font-size:18px;line-height:1;}.saved-view-delete.svelte-1lpntxd:hover {color:var(--color-red);background:transparent;}.saved-view-source.svelte-1lpntxd {justify-content:center;flex:0 0 auto;padding:var(--size-2-1);color:var(--text-muted);font-size:var(--font-ui-smaller);line-height:1;border:1px solid var(--background-modifier-border);border-radius:var(--radius-s);}.saved-view-name.svelte-1lpntxd {justify-content:flex-start;gap:var(--size-2-2);flex:1 1 auto;min-width:0;padding:var(--size-2-1) var(--size-2-2);color:var(--text-normal);font-size:var(--font-ui-small);text-align:left;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;}.saved-view-name.svelte-1lpntxd:hover {background:var(--background-modifier-hover);color:var(--text-normal);}.saved-view-title.svelte-1lpntxd {overflow:hidden;text-overflow:ellipsis;white-space:nowrap;}.saved-view-badges.svelte-1lpntxd {display:inline-flex;flex:0 0 auto;gap:var(--size-2-1);color:var(--text-muted);font-size:var(--font-ui-smaller);}.saved-view-badges.svelte-1lpntxd span:where(.svelte-1lpntxd) {border:1px solid var(--background-modifier-border);border-radius:var(--radius-s);padding:1px var(--size-2-1);line-height:1.2;}\n\n@media (max-width: 680px) {.view-editor.svelte-1lpntxd {max-width:100%;padding:var(--size-4-2);}.view-editor-row.svelte-1lpntxd {grid-template-columns:1fr;gap:var(--size-2-2);}.view-editor-controls.svelte-1lpntxd,\n .view-editor-inline-controls.svelte-1lpntxd {align-items:stretch;flex-direction:column;}.view-editor-select.svelte-1lpntxd,\n .view-editor-text-input.svelte-1lpntxd,\n .tag-group-input-row.svelte-1lpntxd,\n .card-width-control.svelte-1lpntxd,\n .save-view-row.svelte-1lpntxd,\n .saved-view-list.svelte-1lpntxd {width:100%;max-width:none;}.tag-group-input-row.svelte-1lpntxd,\n .card-width-control.svelte-1lpntxd {grid-template-columns:1fr;}.saved-view-list.svelte-1lpntxd li:where(.svelte-1lpntxd) {flex-wrap:wrap;}.view-editor-icon-button.svelte-1lpntxd {width:100%;}\n}"
};
function View_editor($$anchor, $$props) {
if (new.target) return createClassComponent({ component: View_editor, ...$$anchor });
push($$props, false);
append_styles($$anchor, $$css16);
const currentViewPropertyLabels = mutable_source();
let sortSelectValue = prop($$props, "sortSelectValue", 12);
let availableSortKeys = prop($$props, "availableSortKeys", 28, () => []);
let isDirectionalSort = prop($$props, "isDirectionalSort", 12, false);
let sortDirection = prop($$props, "sortDirection", 12, "asc");
let onSortChange = prop($$props, "onSortChange", 12);
let onToggleSortDirection = prop($$props, "onToggleSortDirection", 12);
let groupSelectValue = prop($$props, "groupSelectValue", 12);
let availableGroupKeys = prop($$props, "availableGroupKeys", 28, () => []);
let isDirectionalGroup = prop($$props, "isDirectionalGroup", 12, false);
let groupDirection = prop($$props, "groupDirection", 12, "asc");
let onGroupChange = prop($$props, "onGroupChange", 12);
let onToggleGroupDirection = prop($$props, "onToggleGroupDirection", 12);
let showCollapsePastDatesToggle = prop($$props, "showCollapsePastDatesToggle", 12, false);
let collapsePastDates = prop($$props, "collapsePastDates", 12, false);
let onSetCollapsePastDates = prop($$props, "onSetCollapsePastDates", 12);
let isTagPrefixGrouping = prop($$props, "isTagPrefixGrouping", 12, false);
let tagGroupInputMode = prop($$props, "tagGroupInputMode", 12, "prefix");
let availableTags = prop($$props, "availableTags", 28, () => []);
let tagGroupPrefix = prop($$props, "tagGroupPrefix", 12, "");
let tagGroupIncludeTags = prop($$props, "tagGroupIncludeTags", 28, () => []);
let onSetTagGroupInputMode = prop($$props, "onSetTagGroupInputMode", 12);
let onUpdateTagGroupPrefix = prop($$props, "onUpdateTagGroupPrefix", 12);
let onUpdateTagGroupIncludeTags = prop($$props, "onUpdateTagGroupIncludeTags", 12);
let flowDirection = prop($$props, "flowDirection", 28, () => "ltr" /* LeftToRight */);
let columnWidth = prop($$props, "columnWidth", 12, 300);
let onSetFlowDirection = prop($$props, "onSetFlowDirection", 12);
let onSetColumnWidth = prop($$props, "onSetColumnWidth", 12);
let savedViews = prop($$props, "savedViews", 28, () => []);
let savedViewListExpanded = prop($$props, "savedViewListExpanded", 12, false);
let canSaveView = prop($$props, "canSaveView", 12, false);
let currentViewProperties = prop($$props, "currentViewProperties", 28, () => ({}));
let onSaveCurrentView = prop($$props, "onSaveCurrentView", 12);
let onApplySavedView = prop($$props, "onApplySavedView", 12);
let onDeleteSavedView = prop($$props, "onDeleteSavedView", 12);
let onToggleSavedViewList = prop($$props, "onToggleSavedViewList", 12);
const flowDirectionOptions = [
{ value: "ltr" /* LeftToRight */, label: "LTR" },
{ value: "rtl" /* RightToLeft */, label: "RTL" },
{ value: "ttb" /* TopToBottom */, label: "TTB" },
{ value: "btt" /* BottomToTop */, label: "BTT" }
];
function handleFlowDirectionChange(value) {
if (isFlowDirection(value)) {
onSetFlowDirection()(value);
}
}
function handleColumnWidthChange(value) {
const parsed = Number(value);
if (Number.isFinite(parsed)) {
onSetColumnWidth()(parsed);
}
}
let saveViewName = mutable_source("");
function saveView() {
if (!canSaveView()) {
return;
}
const name = get(saveViewName).trim();
onSaveCurrentView()(name === "" ? void 0 : name);
set(saveViewName, "");
}
function onSaveViewNameKeydown(e) {
if (e.key === "Enter" && canSaveView()) {
saveView();
}
}
legacy_pre_effect(
() => (savedViewPropertyLabels, deep_read_state(currentViewProperties())),
() => {
set(currentViewPropertyLabels, savedViewPropertyLabels(currentViewProperties()));
}
);
legacy_pre_effect_reset();
var $$exports = {
get sortSelectValue() {
return sortSelectValue();
},
set sortSelectValue($$value) {
sortSelectValue($$value);
flushSync();
},
get availableSortKeys() {
return availableSortKeys();
},
set availableSortKeys($$value) {
availableSortKeys($$value);
flushSync();
},
get isDirectionalSort() {
return isDirectionalSort();
},
set isDirectionalSort($$value) {
isDirectionalSort($$value);
flushSync();
},
get sortDirection() {
return sortDirection();
},
set sortDirection($$value) {
sortDirection($$value);
flushSync();
},
get onSortChange() {
return onSortChange();
},
set onSortChange($$value) {
onSortChange($$value);
flushSync();
},
get onToggleSortDirection() {
return onToggleSortDirection();
},
set onToggleSortDirection($$value) {
onToggleSortDirection($$value);
flushSync();
},
get groupSelectValue() {
return groupSelectValue();
},
set groupSelectValue($$value) {
groupSelectValue($$value);
flushSync();
},
get availableGroupKeys() {
return availableGroupKeys();
},
set availableGroupKeys($$value) {
availableGroupKeys($$value);
flushSync();
},
get isDirectionalGroup() {
return isDirectionalGroup();
},
set isDirectionalGroup($$value) {
isDirectionalGroup($$value);
flushSync();
},
get groupDirection() {
return groupDirection();
},
set groupDirection($$value) {
groupDirection($$value);
flushSync();
},
get onGroupChange() {
return onGroupChange();
},
set onGroupChange($$value) {
onGroupChange($$value);
flushSync();
},
get onToggleGroupDirection() {
return onToggleGroupDirection();
},
set onToggleGroupDirection($$value) {
onToggleGroupDirection($$value);
flushSync();
},
get showCollapsePastDatesToggle() {
return showCollapsePastDatesToggle();
},
set showCollapsePastDatesToggle($$value) {
showCollapsePastDatesToggle($$value);
flushSync();
},
get collapsePastDates() {
return collapsePastDates();
},
set collapsePastDates($$value) {
collapsePastDates($$value);
flushSync();
},
get onSetCollapsePastDates() {
return onSetCollapsePastDates();
},
set onSetCollapsePastDates($$value) {
onSetCollapsePastDates($$value);
flushSync();
},
get isTagPrefixGrouping() {
return isTagPrefixGrouping();
},
set isTagPrefixGrouping($$value) {
isTagPrefixGrouping($$value);
flushSync();
},
get tagGroupInputMode() {
return tagGroupInputMode();
},
set tagGroupInputMode($$value) {
tagGroupInputMode($$value);
flushSync();
},
get availableTags() {
return availableTags();
},
set availableTags($$value) {
availableTags($$value);
flushSync();
},
get tagGroupPrefix() {
return tagGroupPrefix();
},
set tagGroupPrefix($$value) {
tagGroupPrefix($$value);
flushSync();
},
get tagGroupIncludeTags() {
return tagGroupIncludeTags();
},
set tagGroupIncludeTags($$value) {
tagGroupIncludeTags($$value);
flushSync();
},
get onSetTagGroupInputMode() {
return onSetTagGroupInputMode();
},
set onSetTagGroupInputMode($$value) {
onSetTagGroupInputMode($$value);
flushSync();
},
get onUpdateTagGroupPrefix() {
return onUpdateTagGroupPrefix();
},
set onUpdateTagGroupPrefix($$value) {
onUpdateTagGroupPrefix($$value);
flushSync();
},
get onUpdateTagGroupIncludeTags() {
return onUpdateTagGroupIncludeTags();
},
set onUpdateTagGroupIncludeTags($$value) {
onUpdateTagGroupIncludeTags($$value);
flushSync();
},
get flowDirection() {
return flowDirection();
},
set flowDirection($$value) {
flowDirection($$value);
flushSync();
},
get columnWidth() {
return columnWidth();
},
set columnWidth($$value) {
columnWidth($$value);
flushSync();
},
get onSetFlowDirection() {
return onSetFlowDirection();
},
set onSetFlowDirection($$value) {
onSetFlowDirection($$value);
flushSync();
},
get onSetColumnWidth() {
return onSetColumnWidth();
},
set onSetColumnWidth($$value) {
onSetColumnWidth($$value);
flushSync();
},
get savedViews() {
return savedViews();
},
set savedViews($$value) {
savedViews($$value);
flushSync();
},
get savedViewListExpanded() {
return savedViewListExpanded();
},
set savedViewListExpanded($$value) {
savedViewListExpanded($$value);
flushSync();
},
get canSaveView() {
return canSaveView();
},
set canSaveView($$value) {
canSaveView($$value);
flushSync();
},
get currentViewProperties() {
return currentViewProperties();
},
set currentViewProperties($$value) {
currentViewProperties($$value);
flushSync();
},
get onSaveCurrentView() {
return onSaveCurrentView();
},
set onSaveCurrentView($$value) {
onSaveCurrentView($$value);
flushSync();
},
get onApplySavedView() {
return onApplySavedView();
},
set onApplySavedView($$value) {
onApplySavedView($$value);
flushSync();
},
get onDeleteSavedView() {
return onDeleteSavedView();
},
set onDeleteSavedView($$value) {
onDeleteSavedView($$value);
flushSync();
},
get onToggleSavedViewList() {
return onToggleSavedViewList();
},
set onToggleSavedViewList($$value) {
onToggleSavedViewList($$value);
flushSync();
},
$set: update_legacy_props,
$on: ($$event_name, $$event_cb) => add_legacy_event_listener($$props, $$event_name, $$event_cb)
};
init();
var section = root_143();
var div = child(section);
var div_1 = sibling(child(div), 2);
var select = child(div_1);
var option_1 = child(select);
var option_1_value = {};
var option_2 = sibling(option_1);
var option_2_value = {};
var option_3 = sibling(option_2);
var option_3_value = {};
var node = sibling(option_3);
{
var consequent = ($$anchor2) => {
var optgroup = root_115();
each(optgroup, 5, availableSortKeys, (sortKey) => sortKey.key, ($$anchor3, sortKey) => {
var option_4 = root16();
var text2 = child(option_4, true);
reset(option_4);
var option_4_value = {};
template_effect(
($0) => {
var _a5;
set_text(text2, (get(sortKey), untrack(() => get(sortKey).label)));
if (option_4_value !== (option_4_value = $0)) {
option_4.value = (_a5 = option_4.__value = $0) != null ? _a5 : "";
}
},
[
() => (deep_read_state(propertyOptionValue), get(sortKey), untrack(() => propertyOptionValue(get(sortKey).key)))
]
);
append($$anchor3, option_4);
});
reset(optgroup);
append($$anchor2, optgroup);
};
if_block(node, ($$render) => {
if (deep_read_state(availableSortKeys()), untrack(() => availableSortKeys().length > 0)) $$render(consequent);
});
}
reset(select);
var select_value;
init_select(select);
var node_1 = sibling(select, 2);
{
var consequent_1 = ($$anchor2) => {
var button = root_210();
var node_2 = child(button);
{
let $0 = derived_safe_equal(() => sortDirection() === "asc" ? "arrow-up-narrow-wide" : "arrow-down-wide-narrow");
Icon(node_2, {
get name() {
return get($0);
},
size: 16
});
}
reset(button);
template_effect(() => set_attribute2(button, "title", sortDirection() === "asc" ? "Ascending" : "Descending"));
event("click", button, function(...$$args) {
var _a5;
(_a5 = onToggleSortDirection()) == null ? void 0 : _a5.apply(this, $$args);
});
append($$anchor2, button);
};
if_block(node_1, ($$render) => {
if (isDirectionalSort()) $$render(consequent_1);
});
}
reset(div_1);
reset(div);
var div_2 = sibling(div, 2);
var div_3 = sibling(child(div_2), 2);
var div_4 = child(div_3);
var select_1 = child(div_4);
var option_5 = child(select_1);
option_5.value = option_5.__value = "none";
var option_6 = sibling(option_5);
option_6.value = option_6.__value = "file";
var option_7 = sibling(option_6);
option_7.value = option_7.__value = "tag-prefix";
var node_3 = sibling(option_7);
{
var consequent_2 = ($$anchor2) => {
var optgroup_1 = root_115();
each(optgroup_1, 5, availableGroupKeys, (groupKey) => groupKey.key, ($$anchor3, groupKey) => {
var option_8 = root16();
var text_1 = child(option_8, true);
reset(option_8);
var option_8_value = {};
template_effect(
($0) => {
var _a5;
set_text(text_1, (get(groupKey), untrack(() => get(groupKey).label)));
if (option_8_value !== (option_8_value = $0)) {
option_8.value = (_a5 = option_8.__value = $0) != null ? _a5 : "";
}
},
[
() => (deep_read_state(propertyOptionValue), get(groupKey), untrack(() => propertyOptionValue(get(groupKey).key)))
]
);
append($$anchor3, option_8);
});
reset(optgroup_1);
append($$anchor2, optgroup_1);
};
if_block(node_3, ($$render) => {
if (deep_read_state(availableGroupKeys()), untrack(() => availableGroupKeys().length > 0)) $$render(consequent_2);
});
}
reset(select_1);
var select_1_value;
init_select(select_1);
var node_4 = sibling(select_1, 2);
{
var consequent_3 = ($$anchor2) => {
var button_1 = root_38();
var node_5 = child(button_1);
{
let $0 = derived_safe_equal(() => groupDirection() === "asc" ? "arrow-up-narrow-wide" : "arrow-down-wide-narrow");
Icon(node_5, {
get name() {
return get($0);
},
size: 16
});
}
reset(button_1);
template_effect(() => set_attribute2(button_1, "title", groupDirection() === "asc" ? "Group ascending" : "Group descending"));
event("click", button_1, function(...$$args) {
var _a5;
(_a5 = onToggleGroupDirection()) == null ? void 0 : _a5.apply(this, $$args);
});
append($$anchor2, button_1);
};
if_block(node_4, ($$render) => {
if (isDirectionalGroup()) $$render(consequent_3);
});
}
reset(div_4);
var node_6 = sibling(div_4, 2);
{
var consequent_4 = ($$anchor2) => {
var label_1 = root_48();
var input = child(label_1);
remove_input_defaults(input);
next(2);
reset(label_1);
template_effect(() => set_checked(input, collapsePastDates()));
event("change", input, (e) => onSetCollapsePastDates()(e.currentTarget.checked));
append($$anchor2, label_1);
};
if_block(node_6, ($$render) => {
if (showCollapsePastDatesToggle()) $$render(consequent_4);
});
}
reset(div_3);
reset(div_2);
var node_7 = sibling(div_2, 2);
{
var consequent_6 = ($$anchor2) => {
var div_5 = root_64();
var div_6 = sibling(child(div_5), 2);
var div_7 = child(div_6);
var div_8 = child(div_7);
var button_2 = child(div_8);
let classes;
var button_3 = sibling(button_2, 2);
let classes_1;
reset(div_8);
var div_9 = sibling(div_8, 2);
var node_8 = child(div_9);
{
var consequent_5 = ($$anchor3) => {
var input_1 = root_56();
remove_input_defaults(input_1);
template_effect(() => set_value(input_1, tagGroupPrefix()));
event("input", input_1, (e) => onUpdateTagGroupPrefix()(e.currentTarget.value));
append($$anchor3, input_1);
};
var alternate = ($$anchor3) => {
Compact_tag_select($$anchor3, {
get items() {
return availableTags();
},
get value() {
return tagGroupIncludeTags();
},
maxSelected: 0,
placeholder: "Choose tags",
ariaLabel: "Included tag swimlanes",
$$events: { change: (e) => onUpdateTagGroupIncludeTags()(e.detail) }
});
};
if_block(node_8, ($$render) => {
if (tagGroupInputMode() === "prefix") $$render(consequent_5);
else $$render(alternate, -1);
});
}
reset(div_9);
reset(div_7);
reset(div_6);
reset(div_5);
template_effect(() => {
set_attribute2(button_2, "aria-pressed", tagGroupInputMode() === "prefix");
classes = set_class(button_2, 1, "svelte-1lpntxd", null, classes, { active: tagGroupInputMode() === "prefix" });
set_attribute2(button_3, "aria-pressed", tagGroupInputMode() === "include");
classes_1 = set_class(button_3, 1, "svelte-1lpntxd", null, classes_1, { active: tagGroupInputMode() === "include" });
});
event("click", button_2, () => onSetTagGroupInputMode()("prefix"));
event("click", button_3, () => onSetTagGroupInputMode()("include"));
append($$anchor2, div_5);
};
if_block(node_7, ($$render) => {
if (isTagPrefixGrouping()) $$render(consequent_6);
});
}
var div_10 = sibling(node_7, 2);
var div_11 = sibling(child(div_10), 2);
var select_2 = child(div_11);
each(select_2, 5, () => flowDirectionOptions, (option) => option.value, ($$anchor2, option) => {
var option_9 = root16();
var text_2 = child(option_9, true);
reset(option_9);
var option_9_value = {};
template_effect(() => {
var _a5;
set_text(text_2, (get(option), untrack(() => get(option).label)));
if (option_9_value !== (option_9_value = (get(option), untrack(() => get(option).value)))) {
option_9.value = (_a5 = option_9.__value = (get(option), untrack(() => get(option).value))) != null ? _a5 : "";
}
});
append($$anchor2, option_9);
});
reset(select_2);
var select_2_value;
init_select(select_2);
reset(div_11);
reset(div_10);
var div_12 = sibling(div_10, 2);
var div_13 = sibling(child(div_12), 2);
var div_14 = child(div_13);
var input_2 = child(div_14);
remove_input_defaults(input_2);
var output = sibling(input_2, 2);
var text_3 = child(output);
reset(output);
reset(div_14);
reset(div_13);
reset(div_12);
var div_15 = sibling(div_12, 2);
var div_16 = sibling(child(div_15), 2);
var div_17 = child(div_16);
var input_3 = child(div_17);
remove_input_defaults(input_3);
var button_4 = sibling(input_3, 2);
reset(div_17);
var p = sibling(div_17, 2);
var node_9 = child(p);
{
var consequent_7 = ($$anchor2) => {
var text_4 = text();
template_effect(($0) => set_text(text_4, `Saves: ${$0 != null ? $0 : ""}`), [
() => (get(currentViewPropertyLabels), untrack(() => get(currentViewPropertyLabels).join(" \xB7 ")))
]);
append($$anchor2, text_4);
};
var alternate_1 = ($$anchor2) => {
var text_5 = text("Nothing set to save \u2014 change a filter, sort, group, flow, or width first.");
append($$anchor2, text_5);
};
if_block(node_9, ($$render) => {
if (canSaveView()) $$render(consequent_7);
else $$render(alternate_1, -1);
});
}
reset(p);
reset(div_16);
reset(div_15);
var div_18 = sibling(div_15, 2);
var button_5 = child(div_18);
var node_10 = child(button_5);
{
let $0 = derived_safe_equal(() => savedViewListExpanded() ? "chevron-down" : "chevron-right");
Icon(node_10, {
get name() {
return get($0);
},
size: 14
});
}
next(2);
reset(button_5);
var node_11 = sibling(button_5, 2);
{
var consequent_10 = ($$anchor2) => {
var div_19 = root_133();
var node_12 = child(div_19);
{
var consequent_9 = ($$anchor3) => {
var ul = root_116();
each(ul, 5, savedViews, (view) => `${view.isGlobal ? "global" : "local"}:${view.id}`, ($$anchor4, view) => {
var li = root_102();
var node_13 = child(li);
{
var consequent_8 = ($$anchor5) => {
var span = root_73();
append($$anchor5, span);
};
var alternate_2 = ($$anchor5) => {
var button_6 = root_82();
template_effect(() => {
var _a5;
return set_attribute2(button_6, "aria-label", `Delete saved view: ${(_a5 = (get(view), untrack(() => get(view).name))) != null ? _a5 : ""}`);
});
event("click", button_6, () => onDeleteSavedView()(get(view)));
append($$anchor5, button_6);
};
if_block(node_13, ($$render) => {
if (get(view), untrack(() => get(view).isGlobal)) $$render(consequent_8);
else $$render(alternate_2, -1);
});
}
var button_7 = sibling(node_13, 2);
var span_1 = child(button_7);
var text_6 = child(span_1, true);
reset(span_1);
var span_2 = sibling(span_1, 2);
each(
span_2,
5,
() => (deep_read_state(savedViewPropertyLabels), get(view), untrack(() => savedViewPropertyLabels(get(view)))),
index,
($$anchor5, label) => {
var span_3 = root_92();
var text_7 = child(span_3, true);
reset(span_3);
template_effect(() => set_text(text_7, get(label)));
append($$anchor5, span_3);
}
);
reset(span_2);
reset(button_7);
reset(li);
template_effect(() => set_text(text_6, (get(view), untrack(() => get(view).name))));
event("click", button_7, () => onApplySavedView()(get(view)));
append($$anchor4, li);
});
reset(ul);
append($$anchor3, ul);
};
var alternate_3 = ($$anchor3) => {
var p_1 = root_123();
append($$anchor3, p_1);
};
if_block(node_12, ($$render) => {
if (deep_read_state(savedViews()), untrack(() => savedViews().length > 0)) $$render(consequent_9);
else $$render(alternate_3, -1);
});
}
reset(div_19);
append($$anchor2, div_19);
};
if_block(node_11, ($$render) => {
if (savedViewListExpanded()) $$render(consequent_10);
});
}
reset(div_18);
reset(section);
template_effect(() => {
var _a5, _b3, _c2, _d, _e, _f, _g;
if (option_1_value !== (option_1_value = SORT_FILE_VALUE)) {
option_1.value = (_a5 = option_1.__value = SORT_FILE_VALUE) != null ? _a5 : "";
}
if (option_2_value !== (option_2_value = SORT_TASK_NAME_VALUE)) {
option_2.value = (_b3 = option_2.__value = SORT_TASK_NAME_VALUE) != null ? _b3 : "";
}
if (option_3_value !== (option_3_value = SORT_MANUAL_VALUE)) {
option_3.value = (_c2 = option_3.__value = SORT_MANUAL_VALUE) != null ? _c2 : "";
}
if (select_value !== (select_value = sortSelectValue())) {
select.value = (_d = select.__value = sortSelectValue()) != null ? _d : "", select_option(select, sortSelectValue());
}
if (select_1_value !== (select_1_value = groupSelectValue())) {
select_1.value = (_e = select_1.__value = groupSelectValue()) != null ? _e : "", select_option(select_1, groupSelectValue());
}
if (select_2_value !== (select_2_value = flowDirection())) {
select_2.value = (_f = select_2.__value = flowDirection()) != null ? _f : "", select_option(select_2, flowDirection());
}
set_value(input_2, columnWidth());
set_text(text_3, `${(_g = columnWidth()) != null ? _g : ""}px`);
button_4.disabled = !canSaveView();
set_attribute2(button_5, "aria-expanded", savedViewListExpanded());
});
event("change", select, (e) => onSortChange()(e.currentTarget.value));
event("change", select_1, (e) => onGroupChange()(e.currentTarget.value));
event("change", select_2, (e) => handleFlowDirectionChange(e.currentTarget.value));
event("input", input_2, (e) => handleColumnWidthChange(e.currentTarget.value));
bind_value(input_3, () => get(saveViewName), ($$value) => set(saveViewName, $$value));
event("keydown", input_3, onSaveViewNameKeydown);
event("click", button_4, saveView);
event("click", button_5, () => onToggleSavedViewList()(!savedViewListExpanded()));
append($$anchor, section);
return pop($$exports);
}
// src/ui/board_counts.ts
function isActiveBoardTask(task) {
return task.column !== "archived" && !task.done && task.column !== "done";
}
function getBoardTaskCount(tasks) {
return tasks.filter(isActiveBoardTask).length;
}
// src/ui/components/delete_filter_modal.svelte
var root17 = from_html(`<div class="modal-backdrop svelte-z61jvf" role="presentation"><div class="modal svelte-z61jvf" role="dialog" aria-modal="true" aria-labelledby="modal-title"><h3 id="modal-title" class="svelte-z61jvf"> </h3> <div class="filter-preview svelte-z61jvf"> </div> <div class="modal-actions svelte-z61jvf"><button class="cancel-btn svelte-z61jvf">Cancel</button> <button class="delete-btn svelte-z61jvf">Delete</button></div></div></div>`);
var $$css17 = {
hash: "svelte-z61jvf",
code: ".modal-backdrop.svelte-z61jvf {position:fixed;top:0;left:0;right:0;bottom:0;background:rgba(0, 0, 0, 0.5);display:flex;align-items:flex-start;justify-content:center;padding-top:20vh;z-index:1000;}.modal.svelte-z61jvf {background:var(--background-primary);border:1px solid var(--background-modifier-border);border-radius:var(--radius-m);padding:var(--size-4-4);min-width:300px;max-width:500px;box-shadow:var(--shadow-l);pointer-events:auto;}h3.svelte-z61jvf {margin:0 0 var(--size-4-3) 0;font-size:var(--font-ui-medium);font-weight:var(--font-semibold);}.filter-preview.svelte-z61jvf {padding:var(--size-4-2);background:var(--background-secondary);border-radius:var(--radius-s);margin-bottom:var(--size-4-4);font-family:var(--font-monospace);font-size:var(--font-ui-small);}.modal-actions.svelte-z61jvf {display:flex;gap:var(--size-4-2);justify-content:flex-end;}button.svelte-z61jvf {padding:var(--size-4-1) var(--size-4-3);border-radius:var(--radius-s);cursor:pointer;font-size:var(--font-ui-small);transition:background 100ms linear;}.cancel-btn.svelte-z61jvf {background:var(--background-secondary);border:1px solid var(--background-modifier-border);color:var(--text-normal);}.cancel-btn.svelte-z61jvf:hover {background:var(--background-secondary-alt);}.delete-btn.svelte-z61jvf {background:var(--color-red);border:none;color:white;}.delete-btn.svelte-z61jvf:hover {background:var(--color-red);opacity:0.8;}"
};
function Delete_filter_modal($$anchor, $$props) {
if (new.target) return createClassComponent({ component: Delete_filter_modal, ...$$anchor });
push($$props, false);
append_styles($$anchor, $$css17);
let title = prop($$props, "title", 12, "Delete saved filter?");
let filterText = prop($$props, "filterText", 12);
let onConfirm = prop($$props, "onConfirm", 12);
let onCancel = prop($$props, "onCancel", 12);
let modalElement = mutable_source();
let deleteButton = mutable_source();
function handleKeydown(event2) {
if (event2.key === "Escape") {
onCancel()();
}
}
onMount(() => {
var _a5;
(_a5 = get(deleteButton)) == null ? void 0 : _a5.focus();
const focusableElements = get(modalElement).querySelectorAll('button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])');
const firstElement = focusableElements[0];
const lastElement = focusableElements[focusableElements.length - 1];
const handleTabKey = (e) => {
if (e.key === "Tab") {
if (e.shiftKey && document.activeElement === firstElement) {
e.preventDefault();
lastElement == null ? void 0 : lastElement.focus();
} else if (!e.shiftKey && document.activeElement === lastElement) {
e.preventDefault();
firstElement == null ? void 0 : firstElement.focus();
}
}
};
get(modalElement).addEventListener("keydown", handleTabKey);
return () => get(modalElement).removeEventListener("keydown", handleTabKey);
});
var $$exports = {
get title() {
return title();
},
set title($$value) {
title($$value);
flushSync();
},
get filterText() {
return filterText();
},
set filterText($$value) {
filterText($$value);
flushSync();
},
get onConfirm() {
return onConfirm();
},
set onConfirm($$value) {
onConfirm($$value);
flushSync();
},
get onCancel() {
return onCancel();
},
set onCancel($$value) {
onCancel($$value);
flushSync();
},
$set: update_legacy_props,
$on: ($$event_name, $$event_cb) => add_legacy_event_listener($$props, $$event_name, $$event_cb)
};
init();
var div = root17();
event("keydown", $window, handleKeydown);
var div_1 = child(div);
var h3 = child(div_1);
var text2 = child(h3, true);
reset(h3);
var div_2 = sibling(h3, 2);
var text_1 = child(div_2, true);
reset(div_2);
var div_3 = sibling(div_2, 2);
var button = child(div_3);
var button_1 = sibling(button, 2);
bind_this(button_1, ($$value) => set(deleteButton, $$value), () => get(deleteButton));
reset(div_3);
reset(div_1);
bind_this(div_1, ($$value) => set(modalElement, $$value), () => get(modalElement));
reset(div);
template_effect(() => {
set_text(text2, title());
set_text(text_1, filterText());
});
event("click", button, function(...$$args) {
var _a5;
(_a5 = onCancel()) == null ? void 0 : _a5.apply(this, $$args);
});
event("click", button_1, function(...$$args) {
var _a5;
(_a5 = onConfirm()) == null ? void 0 : _a5.apply(this, $$args);
});
event("click", div, (e) => e.target === e.currentTarget && onCancel()());
append($$anchor, div);
return pop($$exports);
}
// src/ui/filters/filter_suggestions.ts
function applyFilterSuggestion(text2, suggestion) {
return {
text: text2.slice(0, suggestion.replaceStart) + suggestion.insert + text2.slice(suggestion.replaceEnd),
caret: suggestion.replaceStart + suggestion.insert.length
};
}
function stepSuggestionIndex(count, index2, delta) {
if (count === 0) {
return -1;
}
if (delta === 1) {
return (index2 + 1) % count;
}
return index2 <= 0 ? count - 1 : index2 - 1;
}
function tokenSpanAt(text2, caret) {
let quoted = false;
let start = -1;
for (let i = 0; i < text2.length; i++) {
const char = text2[i];
if (char === '"') {
if (start === -1) {
start = i;
}
quoted = !quoted;
} else if (!quoted && /\s/.test(char)) {
if (start !== -1) {
if (start < caret && caret <= i) {
return { start, end: i };
}
start = -1;
}
} else if (start === -1) {
start = i;
}
}
if (start !== -1 && start < caret) {
return { start, end: text2.length };
}
return { start: caret, end: caret };
}
function rankMatches(items, typed) {
const needle = typed.toLowerCase();
const prefixMatches = [];
const containsMatches = [];
for (const item of items) {
const lower = item.toLowerCase();
if (lower === needle) {
continue;
}
if (lower.startsWith(needle)) {
prefixMatches.push(item);
} else if (lower.includes(needle)) {
containsMatches.push(item);
}
}
return [...prefixMatches, ...containsMatches];
}
function stripQuotes(value) {
return value.replace(/"/g, "");
}
function listEntrySuggestions(text2, listStart, listEnd, caret, items, kind, quoteWhitespace) {
const value = text2.slice(listStart, listEnd);
const caretInValue = Math.min(Math.max(caret - listStart, 0), value.length);
const segmentStart = value.lastIndexOf(",", caretInValue - 1) + 1;
const nextComma = value.indexOf(",", caretInValue);
const segmentEnd = nextComma === -1 ? value.length : nextComma;
const typed = stripQuotes(value.slice(segmentStart, caretInValue)).trim();
const segmentIndex = value.slice(0, segmentStart).split(",").length - 1;
const used = new Set(
value.split(",").filter((_, i) => i !== segmentIndex).map((entry) => stripQuotes(entry).trim().toLowerCase()).filter((entry) => entry !== "")
);
const available = items.filter((item) => !used.has(item.toLowerCase()));
return rankMatches(available, typed).map((item) => ({
kind,
label: item,
replaceStart: listStart + segmentStart,
replaceEnd: listStart + segmentEnd,
insert: quoteWhitespace && /\s/.test(item) ? `"${item}"` : item
}));
}
function getListSuggestions(value, caret, items, kind) {
return listEntrySuggestions(value, 0, value.length, caret, items, kind, false);
}
function prefixSuggestions(typed, replaceStart, replaceEnd, context) {
const candidates = [
{ insert: "tag:", detail: "filter by tag" },
{ insert: "file:", detail: "filter by file path" },
...context.dateKeys.map((key2) => ({
insert: `${key2.key}:`,
detail: `filter by ${key2.label} date`
}))
];
const ranked = rankMatches(
candidates.map((candidate) => candidate.insert),
typed
);
return ranked.map((insert) => {
var _a5;
return {
kind: "prefix",
label: insert,
detail: (_a5 = candidates.find((candidate) => candidate.insert === insert)) == null ? void 0 : _a5.detail,
replaceStart,
replaceEnd,
insert
};
});
}
function getFilterSuggestions(text2, caret, context) {
const span = tokenSpanAt(text2, caret);
const token = text2.slice(span.start, span.end);
if (token.startsWith('"')) {
return [];
}
const colonIndex = token.indexOf(":");
const quoteIndex = token.indexOf('"');
const hasPrefix = colonIndex > 0 && (quoteIndex === -1 || colonIndex < quoteIndex);
if (!hasPrefix) {
const typed = text2.slice(span.start, caret);
return [
...prefixSuggestions(typed, span.start, span.end, context),
...rankMatches(context.savedFilterNames, typed).map((name) => ({
kind: "saved",
label: name,
detail: "saved filter",
replaceStart: span.start,
replaceEnd: span.end,
insert: name
}))
];
}
if (caret <= span.start + colonIndex) {
return prefixSuggestions(
text2.slice(span.start, caret),
span.start,
span.start + colonIndex + 1,
context
);
}
const prefix = token.slice(0, colonIndex).toLowerCase();
const valueStart = span.start + colonIndex + 1;
if (prefix === "tag") {
return listEntrySuggestions(
text2,
valueStart,
span.end,
caret,
context.tags,
"tag",
false
);
}
if (prefix === "file") {
return listEntrySuggestions(
text2,
valueStart,
span.end,
caret,
context.filePaths,
"file",
true
);
}
const dateKey = context.dateKeys.find(
(key2) => key2.key.toLowerCase() === prefix
);
if (dateKey) {
const typed = text2.slice(valueStart, caret);
return DATE_FILTER_OPERATORS.map((operator) => ({
insert: `${TEXT_BY_OPERATOR[operator.value]}${TODAY_FILTER_VALUE}`,
detail: `${operator.label} today`
})).filter(
(candidate) => candidate.insert.toLowerCase().startsWith(typed.toLowerCase()) && candidate.insert.toLowerCase() !== typed.toLowerCase()
).map((candidate) => ({
kind: "date",
label: candidate.insert,
detail: candidate.detail,
replaceStart: valueStart,
replaceEnd: span.end,
insert: candidate.insert
}));
}
return [];
}
// src/ui/filters/filter_suggestion_list.svelte
var root18 = from_html(`<span class="suggestion-detail svelte-dc5wae"> </span>`);
var root_117 = from_html(`<li role="option"><span class="suggestion-label svelte-dc5wae"> </span> <!></li>`);
var root_211 = from_html(`<ul class="filter-suggestions svelte-dc5wae" role="listbox"></ul>`);
var $$css18 = {
hash: "svelte-dc5wae",
code: ".filter-suggestions.svelte-dc5wae {position:absolute;top:100%;left:0;right:0;z-index:300;margin:var(--size-2-1) 0 0 0;padding:var(--size-2-1);list-style:none;background:var(--background-primary);border:1px solid var(--background-modifier-border);border-radius:var(--radius-m);box-shadow:var(--shadow-s);max-height:240px;overflow-y:auto;}.filter-suggestions.svelte-dc5wae li:where(.svelte-dc5wae) {display:flex;align-items:baseline;gap:var(--size-2-3);padding:var(--size-2-2) var(--size-2-3);border-radius:var(--radius-s);cursor:pointer;}.filter-suggestions.svelte-dc5wae li:where(.svelte-dc5wae):hover, .filter-suggestions.svelte-dc5wae li.selected:where(.svelte-dc5wae) {background:var(--background-modifier-hover);}.filter-suggestions.svelte-dc5wae li:where(.svelte-dc5wae) .suggestion-label:where(.svelte-dc5wae) {flex:0 1 auto;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-size:var(--font-ui-small);}.filter-suggestions.svelte-dc5wae li:where(.svelte-dc5wae) .suggestion-detail:where(.svelte-dc5wae) {flex:0 0 auto;margin-left:auto;color:var(--text-muted);font-size:var(--font-ui-smaller);}"
};
function Filter_suggestion_list($$anchor, $$props) {
if (new.target) return createClassComponent({ component: Filter_suggestion_list, ...$$anchor });
push($$props, false);
append_styles($$anchor, $$css18);
let suggestions = prop($$props, "suggestions", 12);
let selectedIndex = prop($$props, "selectedIndex", 12);
let onAccept = prop($$props, "onAccept", 12);
let listEl = mutable_source();
legacy_pre_effect(() => (get(listEl), deep_read_state(selectedIndex())), () => {
var _a5;
if (get(listEl) && selectedIndex() >= 0) {
(_a5 = get(listEl).children[selectedIndex()]) == null ? void 0 : _a5.scrollIntoView({ block: "nearest" });
}
});
legacy_pre_effect_reset();
var $$exports = {
get suggestions() {
return suggestions();
},
set suggestions($$value) {
suggestions($$value);
flushSync();
},
get selectedIndex() {
return selectedIndex();
},
set selectedIndex($$value) {
selectedIndex($$value);
flushSync();
},
get onAccept() {
return onAccept();
},
set onAccept($$value) {
onAccept($$value);
flushSync();
},
$set: update_legacy_props,
$on: ($$event_name, $$event_cb) => add_legacy_event_listener($$props, $$event_name, $$event_cb)
};
init();
var ul = root_211();
each(ul, 5, suggestions, index, ($$anchor2, suggestion, index2) => {
var li = root_117();
let classes;
var span = child(li);
var text2 = child(span, true);
reset(span);
var node = sibling(span, 2);
{
var consequent = ($$anchor3) => {
var span_1 = root18();
var text_1 = child(span_1, true);
reset(span_1);
template_effect(() => set_text(text_1, (get(suggestion), untrack(() => get(suggestion).detail))));
append($$anchor3, span_1);
};
if_block(node, ($$render) => {
if (get(suggestion), untrack(() => get(suggestion).detail)) $$render(consequent);
});
}
reset(li);
template_effect(() => {
set_attribute2(li, "aria-selected", index2 === selectedIndex());
classes = set_class(li, 1, "svelte-dc5wae", null, classes, { selected: index2 === selectedIndex() });
set_text(text2, (get(suggestion), untrack(() => get(suggestion).label)));
});
event("mousedown", li, preventDefault(function($$arg) {
bubble_event.call(this, $$props, $$arg);
}));
event("click", li, () => onAccept()(get(suggestion)));
append($$anchor2, li);
});
reset(ul);
bind_this(ul, ($$value) => set(listEl, $$value), () => get(listEl));
append($$anchor, ul);
return pop($$exports);
}
// src/ui/filters/filter_editor.svelte
var root19 = from_html(`<button type="button" class="row-remove svelte-t4llj4" aria-label="Remove tag group">\xD7</button>`);
var root_118 = from_html(`<div class="editor-row svelte-t4llj4"><div class="suggestion-anchor svelte-t4llj4"><input class="text-input svelte-t4llj4" type="text" placeholder="tag, tag (any of)" aria-label="Tag group (comma-separated, any of)" spellcheck="false"/> <!></div> <!></div>`);
var root_212 = from_html(`<p class="section-hint svelte-t4llj4">Enable a property schema in the board settings to filter by
date; date-shaped tokens currently match as text.</p>`);
var root_39 = from_html(`<p class="section-hint svelte-t4llj4">Enable a property schema in the board settings to filter by date.</p>`);
var root_49 = from_html(`<option> </option>`);
var root_57 = from_html(`<input type="date" aria-label="Comparison date" class="svelte-t4llj4"/>`);
var root_65 = from_html(`<button type="button" class="row-remove svelte-t4llj4" aria-label="Remove date condition">\xD7</button>`);
var root_74 = from_html(`<div class="date-condition-row svelte-t4llj4"><select class="dropdown svelte-t4llj4" aria-label="Date property"><option></option><!><!></select> <select class="dropdown svelte-t4llj4" aria-label="Date comparison"><option></option><!></select> <div class="date-value-toggle svelte-t4llj4"><button type="button">Today</button> <button type="button">Date</button></div> <!> <!></div>`);
var root_83 = from_html(`<!> <button type="button" class="add-row-btn svelte-t4llj4">+ Add condition</button>`, 1);
var root_93 = from_html(`<span class="global-saved-badge svelte-t4llj4" title="Global saved view">Global</span>`);
var root_103 = from_html(`<button type="button" class="row-remove svelte-t4llj4">\xD7</button>`);
var root_119 = from_html(`<li class="svelte-t4llj4"><!> <button type="button"> </button></li>`);
var root_124 = from_html(`<ul class="saved-filter-list svelte-t4llj4" role="list"></ul>`);
var root_134 = from_html(`<p class="section-hint svelte-t4llj4">No saved filters yet.</p>`);
var root_144 = from_html(`<div class="section-rows svelte-t4llj4"><!></div>`);
var root_153 = from_html(`<div class="filter-editor svelte-t4llj4"><div class="editor-section svelte-t4llj4"><span class="section-label svelte-t4llj4">Content</span> <div class="section-rows svelte-t4llj4"><input class="text-input svelte-t4llj4" type="text" aria-label="Content search" spellcheck="false"/></div></div> <div class="editor-section svelte-t4llj4"><span class="section-label svelte-t4llj4">Tags</span> <div class="section-rows svelte-t4llj4"><!> <button type="button" class="add-row-btn svelte-t4llj4">+ Add tag group</button></div></div> <div class="editor-section svelte-t4llj4"><span class="section-label svelte-t4llj4">Files</span> <div class="section-rows svelte-t4llj4"><div class="suggestion-anchor svelte-t4llj4"><input class="text-input svelte-t4llj4" type="text" placeholder="path, path (any of)" aria-label="File paths (comma-separated, any of)" spellcheck="false"/> <!></div></div></div> <div class="editor-section svelte-t4llj4"><span class="section-label svelte-t4llj4">Date</span> <div class="section-rows svelte-t4llj4"><!></div></div> <div class="editor-section svelte-t4llj4"><span class="section-label svelte-t4llj4">Save as</span> <div class="section-rows svelte-t4llj4"><div class="save-row svelte-t4llj4"><input class="text-input svelte-t4llj4" type="text" placeholder="Name (optional)" aria-label="Saved filter name" spellcheck="false"/> <button type="button" class="save-filter-btn svelte-t4llj4">Save</button></div></div></div> <div class="editor-section saved-section svelte-t4llj4"><button type="button" class="saved-toggle svelte-t4llj4"><!> Saved</button> <!></div> <div class="editor-actions svelte-t4llj4"><button type="button" class="editor-clear-btn svelte-t4llj4">Clear</button> <button type="button" class="editor-search-btn svelte-t4llj4">Search</button></div></div>`);
var $$css19 = {
hash: "svelte-t4llj4",
code: ".filter-editor.svelte-t4llj4 {position:absolute;top:100%;left:0;right:0;z-index:200;margin-top:var(--size-2-1);padding:var(--size-4-4);display:flex;flex-direction:column;gap:var(--size-4-3);background:var(--background-primary);border:1px solid var(--background-modifier-border);border-radius:var(--radius-m);box-shadow:var(--shadow-s);max-height:70vh;overflow-y:auto;}.filter-editor.svelte-t4llj4 .editor-section:where(.svelte-t4llj4) {display:grid;grid-template-columns:72px 1fr;gap:var(--size-2-3);align-items:start;}.filter-editor.svelte-t4llj4 .editor-section:where(.svelte-t4llj4) .section-label:where(.svelte-t4llj4) {font-size:var(--font-ui-small);color:var(--text-muted);padding-top:var(--size-2-2);}.filter-editor.svelte-t4llj4 .editor-section:where(.svelte-t4llj4) .section-rows:where(.svelte-t4llj4) {display:flex;flex-direction:column;gap:var(--size-2-2);min-width:0;}.filter-editor.svelte-t4llj4 .global-saved-badge:where(.svelte-t4llj4) {flex:0 0 auto;color:var(--text-muted);font-size:var(--font-ui-smaller);line-height:1;border:1px solid var(--background-modifier-border);border-radius:var(--radius-s);padding:var(--size-2-1);}.filter-editor.svelte-t4llj4 .editor-row:where(.svelte-t4llj4) {display:flex;align-items:center;gap:var(--size-2-2);}.filter-editor.svelte-t4llj4 .suggestion-anchor:where(.svelte-t4llj4) {position:relative;display:flex;flex:1 1 auto;min-width:0;}.filter-editor.svelte-t4llj4 input.text-input:where(.svelte-t4llj4) {flex:1 1 auto;width:100%;min-width:0;background:transparent;border:none;border-bottom:1px solid var(--background-modifier-border);border-radius:0;box-shadow:none;padding:var(--size-2-2) 0;}.filter-editor.svelte-t4llj4 input.text-input:where(.svelte-t4llj4):focus, .filter-editor.svelte-t4llj4 input.text-input:where(.svelte-t4llj4):focus-visible {border-bottom-color:var(--interactive-accent);box-shadow:none;outline:none;}.filter-editor.svelte-t4llj4 .row-remove:where(.svelte-t4llj4) {flex:0 0 auto;padding:var(--size-2-1);background:transparent;border:none;box-shadow:none;cursor:pointer;color:var(--text-muted);font-size:18px;line-height:1;}.filter-editor.svelte-t4llj4 .row-remove:where(.svelte-t4llj4):hover {color:var(--color-red);}.filter-editor.svelte-t4llj4 .add-row-btn:where(.svelte-t4llj4) {align-self:flex-start;padding:var(--size-2-1) 0;background:transparent;color:var(--text-muted);border:none;box-shadow:none;cursor:pointer;font-size:var(--font-ui-small);}.filter-editor.svelte-t4llj4 .add-row-btn:where(.svelte-t4llj4):hover {color:var(--text-normal);}.filter-editor.svelte-t4llj4 .section-hint:where(.svelte-t4llj4) {margin:0;padding-top:var(--size-2-2);color:var(--text-muted);font-size:var(--font-ui-small);}.filter-editor.svelte-t4llj4 .saved-section:where(.svelte-t4llj4) {padding-top:var(--size-2-3);border-top:1px solid var(--background-modifier-border);}.filter-editor.svelte-t4llj4 .saved-toggle:where(.svelte-t4llj4) {display:inline-flex;align-items:center;justify-content:flex-start;gap:var(--size-2-1);align-self:start;margin:0;padding:var(--size-2-2) 0;background:transparent;border:none;box-shadow:none;cursor:pointer;color:var(--text-muted);font-size:var(--font-ui-small);}.filter-editor.svelte-t4llj4 .saved-toggle:where(.svelte-t4llj4):hover {color:var(--text-normal);}.filter-editor.svelte-t4llj4 .saved-filter-list:where(.svelte-t4llj4) {margin:0;padding:0;list-style:none;display:flex;flex-direction:column;gap:var(--size-2-1);}.filter-editor.svelte-t4llj4 .saved-filter-list:where(.svelte-t4llj4) li:where(.svelte-t4llj4) {display:flex;align-items:center;gap:var(--size-2-1);min-width:0;}.filter-editor.svelte-t4llj4 .saved-filter-list:where(.svelte-t4llj4) .saved-filter-name:where(.svelte-t4llj4) {display:block;flex:1 1 auto;min-width:0;padding:var(--size-2-1) var(--size-2-2);background:transparent;border:none;box-shadow:none;border-radius:var(--radius-s);cursor:pointer;text-align:left;font-size:var(--font-ui-small);overflow:hidden;text-overflow:ellipsis;white-space:nowrap;}.filter-editor.svelte-t4llj4 .saved-filter-list:where(.svelte-t4llj4) .saved-filter-name:where(.svelte-t4llj4):hover {background:var(--background-modifier-hover);}.filter-editor.svelte-t4llj4 .saved-filter-list:where(.svelte-t4llj4) .saved-filter-name.active:where(.svelte-t4llj4) {background:var(--interactive-accent);color:var(--text-on-accent);}.filter-editor.svelte-t4llj4 .save-row:where(.svelte-t4llj4) {display:flex;align-items:center;gap:var(--size-2-3);}.filter-editor.svelte-t4llj4 .save-row:where(.svelte-t4llj4) .save-filter-btn:where(.svelte-t4llj4) {flex:0 0 auto;padding:var(--size-2-2) var(--size-4-3);background:transparent;color:var(--text-muted);border:1px solid var(--background-modifier-border);border-radius:999px;box-shadow:none;cursor:pointer;font-size:var(--font-ui-small);}.filter-editor.svelte-t4llj4 .save-row:where(.svelte-t4llj4) .save-filter-btn:where(.svelte-t4llj4):hover:not(:disabled) {color:var(--text-normal);background:var(--background-modifier-hover);}.filter-editor.svelte-t4llj4 .save-row:where(.svelte-t4llj4) .save-filter-btn:where(.svelte-t4llj4):disabled {opacity:0.5;cursor:default;}.filter-editor.svelte-t4llj4 .date-condition-row:where(.svelte-t4llj4) {display:flex;flex-wrap:wrap;align-items:center;gap:var(--size-4-2);font-size:var(--font-ui-small);}.filter-editor.svelte-t4llj4 .date-condition-row:where(.svelte-t4llj4) select.dropdown:where(.svelte-t4llj4) {flex:0 1 auto;min-width:0;background-color:transparent;border:none;border-bottom:1px solid var(--background-modifier-border);border-radius:0;box-shadow:none;padding-left:0;}.filter-editor.svelte-t4llj4 .date-condition-row:where(.svelte-t4llj4) select.dropdown:where(.svelte-t4llj4):hover {background-color:transparent;box-shadow:none;}.filter-editor.svelte-t4llj4 .date-condition-row:where(.svelte-t4llj4) select.dropdown:where(.svelte-t4llj4):focus, .filter-editor.svelte-t4llj4 .date-condition-row:where(.svelte-t4llj4) select.dropdown:where(.svelte-t4llj4):focus-visible {border-bottom-color:var(--interactive-accent);box-shadow:none;outline:none;}.filter-editor.svelte-t4llj4 .date-condition-row:where(.svelte-t4llj4) .date-value-toggle:where(.svelte-t4llj4) {display:inline-flex;align-items:stretch;border:var(--input-border-width, 1px) solid var(--background-modifier-border);border-radius:var(--input-radius);overflow:hidden;background:var(--background-modifier-form-field, var(--background-primary));}.filter-editor.svelte-t4llj4 .date-condition-row:where(.svelte-t4llj4) .date-value-toggle:where(.svelte-t4llj4) button:where(.svelte-t4llj4) {display:inline-flex;align-items:center;justify-content:center;margin:0;border:none;border-radius:0;box-shadow:none;background:transparent;color:var(--text-muted);font-size:var(--font-ui-smaller);line-height:1;padding:var(--size-2-2) var(--size-2-3);cursor:pointer;}.filter-editor.svelte-t4llj4 .date-condition-row:where(.svelte-t4llj4) .date-value-toggle:where(.svelte-t4llj4) button:where(.svelte-t4llj4):hover {color:var(--text-normal);background:var(--background-modifier-hover);}.filter-editor.svelte-t4llj4 .date-condition-row:where(.svelte-t4llj4) .date-value-toggle:where(.svelte-t4llj4) button.active:where(.svelte-t4llj4) {background:var(--interactive-accent);color:var(--text-on-accent);}.filter-editor.svelte-t4llj4 .date-condition-row:where(.svelte-t4llj4) .date-value-toggle:where(.svelte-t4llj4) button:where(.svelte-t4llj4):focus-visible {outline:2px solid var(--background-modifier-border-focus);outline-offset:-2px;}.filter-editor.svelte-t4llj4 .date-condition-row:where(.svelte-t4llj4) .date-value-toggle:where(.svelte-t4llj4) button:where(.svelte-t4llj4) + button:where(.svelte-t4llj4) {border-left:var(--input-border-width, 1px) solid var(--background-modifier-border);}.filter-editor.svelte-t4llj4 .date-condition-row:where(.svelte-t4llj4) input[type=date]:where(.svelte-t4llj4) {background:transparent;border:none;border-bottom:1px solid var(--background-modifier-border);border-radius:0;box-shadow:none;}.filter-editor.svelte-t4llj4 .date-condition-row:where(.svelte-t4llj4) input[type=date]:where(.svelte-t4llj4):focus, .filter-editor.svelte-t4llj4 .date-condition-row:where(.svelte-t4llj4) input[type=date]:where(.svelte-t4llj4):focus-visible {border-bottom-color:var(--interactive-accent);box-shadow:none;outline:none;}.filter-editor.svelte-t4llj4 .editor-actions:where(.svelte-t4llj4) {display:flex;justify-content:flex-end;gap:var(--size-2-3);padding-top:var(--size-2-3);border-top:1px solid var(--background-modifier-border);}.filter-editor.svelte-t4llj4 .editor-actions:where(.svelte-t4llj4) .editor-clear-btn:where(.svelte-t4llj4) {padding:var(--size-2-2) var(--size-4-3);background:transparent;color:var(--text-muted);border:none;box-shadow:none;cursor:pointer;}.filter-editor.svelte-t4llj4 .editor-actions:where(.svelte-t4llj4) .editor-clear-btn:where(.svelte-t4llj4):hover {color:var(--text-normal);}.filter-editor.svelte-t4llj4 .editor-actions:where(.svelte-t4llj4) .editor-search-btn:where(.svelte-t4llj4) {padding:var(--size-2-2) var(--size-4-5);background:var(--interactive-accent);color:var(--text-on-accent);border:none;border-radius:999px;cursor:pointer;}.filter-editor.svelte-t4llj4 .editor-actions:where(.svelte-t4llj4) .editor-search-btn:where(.svelte-t4llj4):hover {background:var(--interactive-accent-hover);}"
};
function Filter_editor($$anchor, $$props) {
if (new.target) return createClassComponent({ component: Filter_editor, ...$$anchor });
push($$props, false);
append_styles($$anchor, $$css19);
const hasDateShapedTerm = mutable_source();
const dateKeyNames = mutable_source();
const draftKey = mutable_source();
const savedEntries = mutable_source();
const activeSavedFilterId = mutable_source();
const saveDisabled = mutable_source();
let query = prop($$props, "query", 12);
let dateKeys = prop($$props, "dateKeys", 28, () => []);
let tagSuggestionItems = prop($$props, "tagSuggestionItems", 28, () => []);
let fileSuggestionItems = prop($$props, "fileSuggestionItems", 28, () => []);
let savedFilters = prop($$props, "savedFilters", 28, () => []);
let savedListExpanded = prop($$props, "savedListExpanded", 12, false);
let onChange = prop($$props, "onChange", 12);
let onSearch = prop($$props, "onSearch", 12);
let onClear = prop($$props, "onClear", 12);
let onApplySavedFilter = prop($$props, "onApplySavedFilter", 12);
let onDeleteSavedFilter = prop($$props, "onDeleteSavedFilter", 12);
let onSaveFilter = prop($$props, "onSaveFilter", 12);
let onToggleSavedList = prop($$props, "onToggleSavedList", 12);
function emptyDateRow() {
return { property: "", operator: "", value: TODAY_FILTER_VALUE };
}
let contentRow = mutable_source("");
let tagRows = mutable_source([""]);
let fileRow = mutable_source("");
let dateRows = mutable_source([emptyDateRow()]);
let lastEmittedKey;
function syncFromQuery(incoming) {
if (serializeFilterQuery(incoming) === lastEmittedKey) {
return;
}
lastEmittedKey = serializeFilterQuery(incoming);
set(contentRow, serializeContentTerms(incoming.contentTerms));
set(tagRows, incoming.tagGroups.map((group) => group.join(",")));
if (get(tagRows).length === 0) {
set(tagRows, [""]);
}
set(fileRow, incoming.filePaths.join(","));
set(dateRows, incoming.dateConditions.map((condition) => ({ ...condition })));
if (get(dateRows).length === 0) {
set(dateRows, [emptyDateRow()]);
}
}
function isCompleteDateCondition(row) {
return row.property !== "" && row.operator !== "" && (row.value === TODAY_FILTER_VALUE || parseDateOnly(row.value) !== null);
}
function stripQuotes2(value) {
return value.replace(/"/g, "");
}
function rowsToQuery() {
return {
contentTerms: parseContentTerms(get(contentRow)),
tagGroups: get(tagRows).map((row) => stripQuotes2(row).split(",").map((tag2) => tag2.trim()).filter((tag2) => tag2 !== "")).filter((group) => group.length > 0),
filePaths: stripQuotes2(get(fileRow)).split(",").map((path) => path.trim()).filter((path) => path !== ""),
dateConditions: get(dateRows).filter(isCompleteDateCondition).map((row) => ({
property: row.property,
operator: row.operator,
value: row.value
}))
};
}
function emit() {
const next2 = rowsToQuery();
lastEmittedKey = serializeFilterQuery(next2);
onChange()(next2);
}
function onRowKeydown(e) {
if (e.key === "Enter") {
onSearch()();
}
}
let activeSuggestField = mutable_source(null);
let fieldSuggestions = mutable_source([]);
let fieldSuggestionIndex = mutable_source(-1);
let tagInputEls = mutable_source([]);
let fileInputEl = mutable_source();
function fieldEl(field) {
return field.kind === "tag" ? get(tagInputEls)[field.index] : get(fileInputEl);
}
function fieldValue(field) {
var _a5;
return field.kind === "tag" ? (_a5 = get(tagRows)[field.index]) != null ? _a5 : "" : get(fileRow);
}
function refreshFieldSuggestions(field) {
var _a5, _b3;
const value = fieldValue(field);
const caret = (_b3 = (_a5 = fieldEl(field)) == null ? void 0 : _a5.selectionStart) != null ? _b3 : value.length;
set(fieldSuggestions, getListSuggestions(value, caret, field.kind === "tag" ? tagSuggestionItems() : fileSuggestionItems(), field.kind));
set(fieldSuggestionIndex, -1);
set(activeSuggestField, get(fieldSuggestions).length > 0 ? field : null);
}
function hideFieldSuggestions() {
set(activeSuggestField, null);
set(fieldSuggestions, []);
set(fieldSuggestionIndex, -1);
}
async function acceptFieldSuggestion(suggestion) {
const field = get(activeSuggestField);
if (!field) {
return;
}
const applied = applyFilterSuggestion(fieldValue(field), suggestion);
if (field.kind === "tag") {
mutate(tagRows, get(tagRows)[field.index] = applied.text);
} else {
set(fileRow, applied.text);
}
emit();
hideFieldSuggestions();
await tick();
const el = fieldEl(field);
el == null ? void 0 : el.focus();
el == null ? void 0 : el.setSelectionRange(applied.caret, applied.caret);
}
function onSuggestingKeydown(e) {
if (get(activeSuggestField) && get(fieldSuggestions).length > 0) {
if (e.key === "ArrowDown" || e.key === "ArrowUp") {
e.preventDefault();
set(fieldSuggestionIndex, stepSuggestionIndex(get(fieldSuggestions).length, get(fieldSuggestionIndex), e.key === "ArrowDown" ? 1 : -1));
return;
}
if (e.key === "Tab") {
e.preventDefault();
acceptFieldSuggestion(get(fieldSuggestions)[Math.max(get(fieldSuggestionIndex), 0)]);
return;
}
if (e.key === "Enter" && get(fieldSuggestionIndex) >= 0) {
e.preventDefault();
acceptFieldSuggestion(get(fieldSuggestions)[get(fieldSuggestionIndex)]);
return;
}
if (e.key === "Escape") {
e.stopPropagation();
hideFieldSuggestions();
return;
}
}
onRowKeydown(e);
}
function retargetFieldSuggestions(field) {
if (get(activeSuggestField)) {
refreshFieldSuggestions(field);
}
}
function updateDateRow(index2, patch) {
set(dateRows, get(dateRows).map((condition, i) => i === index2 ? { ...condition, ...patch } : condition));
emit();
}
function removeDateRow(index2) {
set(dateRows, get(dateRows).filter((_, i) => i !== index2));
if (get(dateRows).length === 0) {
set(dateRows, [emptyDateRow()]);
}
emit();
}
let saveName = mutable_source("");
function saveFilter() {
if (get(saveDisabled)) {
return;
}
const name = get(saveName).trim();
onSaveFilter()(name === "" ? void 0 : name);
set(saveName, "");
}
function onSaveNameKeydown(e) {
if (e.key === "Enter") {
if (get(saveDisabled)) {
onSearch()();
} else {
saveFilter();
}
}
}
function toggleSavedFilter(entry) {
if (entry.id === get(activeSavedFilterId)) {
onClear()();
} else {
onApplySavedFilter()(entry);
}
}
legacy_pre_effect(() => deep_read_state(query()), () => {
syncFromQuery(query());
});
legacy_pre_effect(() => deep_read_state(query()), () => {
set(hasDateShapedTerm, query().contentTerms.some((term) => /^[^\s:"]+:(<=|>=|<|>|=)/.test(term)));
});
legacy_pre_effect(() => deep_read_state(dateKeys()), () => {
set(dateKeyNames, dateKeys().map((key2) => key2.key));
});
legacy_pre_effect(() => (serializeFilterQuery, deep_read_state(query())), () => {
set(draftKey, serializeFilterQuery(query()));
});
legacy_pre_effect(
() => (deep_read_state(savedFilters()), serializeFilterQuery, parseFilterQuery, get(dateKeyNames)),
() => {
set(savedEntries, savedFilters().map((entry) => ({
entry,
key: serializeFilterQuery(parseFilterQuery(entry.query, get(dateKeyNames)))
})));
}
);
legacy_pre_effect(() => (get(draftKey), get(savedEntries)), () => {
var _a5;
set(activeSavedFilterId, get(draftKey) === "" ? void 0 : (_a5 = get(savedEntries).find(({ key: key2 }) => key2 === get(draftKey))) == null ? void 0 : _a5.entry.id);
});
legacy_pre_effect(() => (get(draftKey), get(savedEntries)), () => {
set(saveDisabled, get(draftKey) === "" || get(savedEntries).some(({ key: key2 }) => key2 === get(draftKey)));
});
legacy_pre_effect_reset();
var $$exports = {
get query() {
return query();
},
set query($$value) {
query($$value);
flushSync();
},
get dateKeys() {
return dateKeys();
},
set dateKeys($$value) {
dateKeys($$value);
flushSync();
},
get tagSuggestionItems() {
return tagSuggestionItems();
},
set tagSuggestionItems($$value) {
tagSuggestionItems($$value);
flushSync();
},
get fileSuggestionItems() {
return fileSuggestionItems();
},
set fileSuggestionItems($$value) {
fileSuggestionItems($$value);
flushSync();
},
get savedFilters() {
return savedFilters();
},
set savedFilters($$value) {
savedFilters($$value);
flushSync();
},
get savedListExpanded() {
return savedListExpanded();
},
set savedListExpanded($$value) {
savedListExpanded($$value);
flushSync();
},
get onChange() {
return onChange();
},
set onChange($$value) {
onChange($$value);
flushSync();
},
get onSearch() {
return onSearch();
},
set onSearch($$value) {
onSearch($$value);
flushSync();
},
get onClear() {
return onClear();
},
set onClear($$value) {
onClear($$value);
flushSync();
},
get onApplySavedFilter() {
return onApplySavedFilter();
},
set onApplySavedFilter($$value) {
onApplySavedFilter($$value);
flushSync();
},
get onDeleteSavedFilter() {
return onDeleteSavedFilter();
},
set onDeleteSavedFilter($$value) {
onDeleteSavedFilter($$value);
flushSync();
},
get onSaveFilter() {
return onSaveFilter();
},
set onSaveFilter($$value) {
onSaveFilter($$value);
flushSync();
},
get onToggleSavedList() {
return onToggleSavedList();
},
set onToggleSavedList($$value) {
onToggleSavedList($$value);
flushSync();
},
$set: update_legacy_props,
$on: ($$event_name, $$event_cb) => add_legacy_event_listener($$props, $$event_name, $$event_cb)
};
init();
var div = root_153();
var div_1 = child(div);
var div_2 = sibling(child(div_1), 2);
var input = child(div_2);
remove_input_defaults(input);
set_attribute2(input, "placeholder", 'words match anywhere, "quotes match the phrase"');
reset(div_2);
reset(div_1);
var div_3 = sibling(div_1, 2);
var div_4 = sibling(child(div_3), 2);
var node = child(div_4);
each(node, 1, () => get(tagRows), index, ($$anchor2, _, index2) => {
var div_5 = root_118();
var div_6 = child(div_5);
var input_1 = child(div_6);
remove_input_defaults(input_1);
bind_this(input_1, ($$value, index3) => mutate(tagInputEls, get(tagInputEls)[index3] = $$value), (index3) => {
var _a5;
return (_a5 = get(tagInputEls)) == null ? void 0 : _a5[index3];
}, () => [index2]);
var node_1 = sibling(input_1, 2);
{
var consequent = ($$anchor3) => {
Filter_suggestion_list($$anchor3, {
get suggestions() {
return get(fieldSuggestions);
},
get selectedIndex() {
return get(fieldSuggestionIndex);
},
onAccept: acceptFieldSuggestion
});
};
if_block(node_1, ($$render) => {
if (get(activeSuggestField), index2, untrack(() => {
var _a5;
return ((_a5 = get(activeSuggestField)) == null ? void 0 : _a5.kind) === "tag" && get(activeSuggestField).index === index2;
})) $$render(consequent);
});
}
reset(div_6);
var node_2 = sibling(div_6, 2);
{
var consequent_1 = ($$anchor3) => {
var button = root19();
event("click", button, () => {
set(tagRows, get(tagRows).filter((_2, i) => i !== index2));
if (get(tagRows).length === 0) {
set(tagRows, [""]);
}
emit();
});
append($$anchor3, button);
};
if_block(node_2, ($$render) => {
if (get(tagRows), untrack(() => get(tagRows).length > 1)) $$render(consequent_1);
});
}
reset(div_5);
bind_value(input_1, () => get(tagRows)[index2], ($$value) => mutate(tagRows, get(tagRows)[index2] = $$value));
event("input", input_1, () => {
var _a5;
mutate(tagRows, get(tagRows)[index2] = stripQuotes2((_a5 = get(tagRows)[index2]) != null ? _a5 : ""));
emit();
refreshFieldSuggestions({ kind: "tag", index: index2 });
});
event("keydown", input_1, onSuggestingKeydown);
event("click", input_1, () => retargetFieldSuggestions({ kind: "tag", index: index2 }));
event("blur", input_1, hideFieldSuggestions);
append($$anchor2, div_5);
});
var button_1 = sibling(node, 2);
reset(div_4);
reset(div_3);
var div_7 = sibling(div_3, 2);
var div_8 = sibling(child(div_7), 2);
var div_9 = child(div_8);
var input_2 = child(div_9);
remove_input_defaults(input_2);
bind_this(input_2, ($$value) => set(fileInputEl, $$value), () => get(fileInputEl));
var node_3 = sibling(input_2, 2);
{
var consequent_2 = ($$anchor2) => {
Filter_suggestion_list($$anchor2, {
get suggestions() {
return get(fieldSuggestions);
},
get selectedIndex() {
return get(fieldSuggestionIndex);
},
onAccept: acceptFieldSuggestion
});
};
if_block(node_3, ($$render) => {
if (get(activeSuggestField), untrack(() => {
var _a5;
return ((_a5 = get(activeSuggestField)) == null ? void 0 : _a5.kind) === "file";
})) $$render(consequent_2);
});
}
reset(div_9);
reset(div_8);
reset(div_7);
var div_10 = sibling(div_7, 2);
var div_11 = sibling(child(div_10), 2);
var node_4 = child(div_11);
{
var consequent_4 = ($$anchor2) => {
var fragment_2 = comment();
var node_5 = first_child(fragment_2);
{
var consequent_3 = ($$anchor3) => {
var p = root_212();
append($$anchor3, p);
};
var alternate = ($$anchor3) => {
var p_1 = root_39();
append($$anchor3, p_1);
};
if_block(node_5, ($$render) => {
if (get(hasDateShapedTerm)) $$render(consequent_3);
else $$render(alternate, -1);
});
}
append($$anchor2, fragment_2);
};
var alternate_1 = ($$anchor2) => {
var fragment_3 = root_83();
var node_6 = first_child(fragment_3);
each(node_6, 1, () => get(dateRows), index, ($$anchor3, condition, index2) => {
var div_12 = root_74();
var select = child(div_12);
var option = child(select);
option.value = option.__value = "";
var node_7 = sibling(option);
{
var consequent_5 = ($$anchor4) => {
var option_1 = root_49();
var text2 = child(option_1, true);
reset(option_1);
var option_1_value = {};
template_effect(() => {
var _a5;
set_text(text2, (get(condition), untrack(() => get(condition).property)));
if (option_1_value !== (option_1_value = (get(condition), untrack(() => get(condition).property)))) {
option_1.value = (_a5 = option_1.__value = (get(condition), untrack(() => get(condition).property))) != null ? _a5 : "";
}
});
append($$anchor4, option_1);
};
var d = user_derived(() => (get(condition), deep_read_state(dateKeys()), untrack(() => get(condition).property !== "" && !dateKeys().some((key2) => key2.key === get(condition).property))));
if_block(node_7, ($$render) => {
if (get(d)) $$render(consequent_5);
});
}
var node_8 = sibling(node_7);
each(node_8, 1, dateKeys, index, ($$anchor4, key2) => {
var option_2 = root_49();
var text_1 = child(option_2, true);
reset(option_2);
var option_2_value = {};
template_effect(() => {
var _a5;
set_text(text_1, (get(key2), untrack(() => get(key2).label)));
if (option_2_value !== (option_2_value = (get(key2), untrack(() => get(key2).key)))) {
option_2.value = (_a5 = option_2.__value = (get(key2), untrack(() => get(key2).key))) != null ? _a5 : "";
}
});
append($$anchor4, option_2);
});
reset(select);
var select_value;
init_select(select);
var select_1 = sibling(select, 2);
var option_3 = child(select_1);
option_3.value = option_3.__value = "";
var node_9 = sibling(option_3);
each(node_9, 1, () => DATE_FILTER_OPERATORS, index, ($$anchor4, operator) => {
var option_4 = root_49();
var text_2 = child(option_4, true);
reset(option_4);
var option_4_value = {};
template_effect(() => {
var _a5;
set_text(text_2, (get(operator), untrack(() => get(operator).label)));
if (option_4_value !== (option_4_value = (get(operator), untrack(() => get(operator).value)))) {
option_4.value = (_a5 = option_4.__value = (get(operator), untrack(() => get(operator).value))) != null ? _a5 : "";
}
});
append($$anchor4, option_4);
});
reset(select_1);
var select_1_value;
init_select(select_1);
var div_13 = sibling(select_1, 2);
var button_2 = child(div_13);
let classes;
var button_3 = sibling(button_2, 2);
let classes_1;
reset(div_13);
var node_10 = sibling(div_13, 2);
{
var consequent_6 = ($$anchor4) => {
var input_3 = root_57();
remove_input_defaults(input_3);
template_effect(() => set_value(input_3, (get(condition), untrack(() => get(condition).value))));
event("change", input_3, (e) => updateDateRow(index2, { value: e.currentTarget.value }));
append($$anchor4, input_3);
};
if_block(node_10, ($$render) => {
if (get(condition), deep_read_state(TODAY_FILTER_VALUE), untrack(() => get(condition).value !== TODAY_FILTER_VALUE)) $$render(consequent_6);
});
}
var node_11 = sibling(node_10, 2);
{
var consequent_7 = ($$anchor4) => {
var button_4 = root_65();
event("click", button_4, () => removeDateRow(index2));
append($$anchor4, button_4);
};
if_block(node_11, ($$render) => {
if (get(dateRows), untrack(() => get(dateRows).length > 1)) $$render(consequent_7);
});
}
reset(div_12);
template_effect(() => {
var _a5, _b3;
if (select_value !== (select_value = (get(condition), untrack(() => get(condition).property)))) {
select.value = (_a5 = select.__value = (get(condition), untrack(() => get(condition).property))) != null ? _a5 : "", select_option(select, (get(condition), untrack(() => get(condition).property)));
}
if (select_1_value !== (select_1_value = (get(condition), untrack(() => get(condition).operator)))) {
select_1.value = (_b3 = select_1.__value = (get(condition), untrack(() => get(condition).operator))) != null ? _b3 : "", select_option(select_1, (get(condition), untrack(() => get(condition).operator)));
}
set_attribute2(button_2, "aria-pressed", (get(condition), deep_read_state(TODAY_FILTER_VALUE), untrack(() => get(condition).value === TODAY_FILTER_VALUE)));
classes = set_class(button_2, 1, "svelte-t4llj4", null, classes, { active: get(condition).value === TODAY_FILTER_VALUE });
set_attribute2(button_3, "aria-pressed", (get(condition), deep_read_state(TODAY_FILTER_VALUE), untrack(() => get(condition).value !== TODAY_FILTER_VALUE)));
classes_1 = set_class(button_3, 1, "svelte-t4llj4", null, classes_1, { active: get(condition).value !== TODAY_FILTER_VALUE });
});
event("change", select, (e) => updateDateRow(index2, { property: e.currentTarget.value }));
event("change", select_1, (e) => updateDateRow(index2, { operator: e.currentTarget.value }));
event("click", button_2, () => updateDateRow(index2, { value: TODAY_FILTER_VALUE }));
event("click", button_3, () => {
if (get(condition).value === TODAY_FILTER_VALUE) {
updateDateRow(index2, { value: "" });
}
});
append($$anchor3, div_12);
});
var button_5 = sibling(node_6, 2);
event("click", button_5, () => set(dateRows, [...get(dateRows), emptyDateRow()]));
append($$anchor2, fragment_3);
};
if_block(node_4, ($$render) => {
if (deep_read_state(dateKeys()), untrack(() => dateKeys().length === 0)) $$render(consequent_4);
else $$render(alternate_1, -1);
});
}
reset(div_11);
reset(div_10);
var div_14 = sibling(div_10, 2);
var div_15 = sibling(child(div_14), 2);
var div_16 = child(div_15);
var input_4 = child(div_16);
remove_input_defaults(input_4);
var button_6 = sibling(input_4, 2);
reset(div_16);
reset(div_15);
reset(div_14);
var div_17 = sibling(div_14, 2);
var button_7 = child(div_17);
var node_12 = child(button_7);
{
let $0 = derived_safe_equal(() => savedListExpanded() ? "chevron-down" : "chevron-right");
Icon(node_12, {
get name() {
return get($0);
},
size: 14
});
}
next();
reset(button_7);
var node_13 = sibling(button_7, 2);
{
var consequent_10 = ($$anchor2) => {
var div_18 = root_144();
var node_14 = child(div_18);
{
var consequent_9 = ($$anchor3) => {
var ul = root_124();
each(ul, 5, savedFilters, (entry) => entry.id, ($$anchor4, entry) => {
var li = root_119();
var node_15 = child(li);
{
var consequent_8 = ($$anchor5) => {
var span = root_93();
append($$anchor5, span);
};
var alternate_2 = ($$anchor5) => {
var button_8 = root_103();
template_effect(() => {
var _a5;
return set_attribute2(button_8, "aria-label", `Delete saved filter: ${(_a5 = (get(entry), untrack(() => {
var _a6;
return (_a6 = get(entry).name) != null ? _a6 : get(entry).query;
}))) != null ? _a5 : ""}`);
});
event("click", button_8, () => onDeleteSavedFilter()(get(entry)));
append($$anchor5, button_8);
};
if_block(node_15, ($$render) => {
if (get(entry), untrack(() => get(entry).isGlobal)) $$render(consequent_8);
else $$render(alternate_2, -1);
});
}
var button_9 = sibling(node_15, 2);
let classes_2;
var text_3 = child(button_9, true);
reset(button_9);
reset(li);
template_effect(() => {
classes_2 = set_class(button_9, 1, "saved-filter-name svelte-t4llj4", null, classes_2, { active: get(entry).id === get(activeSavedFilterId) });
set_attribute2(button_9, "aria-pressed", (get(entry), get(activeSavedFilterId), untrack(() => get(entry).id === get(activeSavedFilterId))));
set_text(text_3, (get(entry), untrack(() => {
var _a5;
return (_a5 = get(entry).name) != null ? _a5 : get(entry).query;
})));
});
event("click", button_9, () => toggleSavedFilter(get(entry)));
append($$anchor4, li);
});
reset(ul);
append($$anchor3, ul);
};
var alternate_3 = ($$anchor3) => {
var p_2 = root_134();
append($$anchor3, p_2);
};
if_block(node_14, ($$render) => {
if (deep_read_state(savedFilters()), untrack(() => savedFilters().length > 0)) $$render(consequent_9);
else $$render(alternate_3, -1);
});
}
reset(div_18);
append($$anchor2, div_18);
};
if_block(node_13, ($$render) => {
if (savedListExpanded()) $$render(consequent_10);
});
}
reset(div_17);
var div_19 = sibling(div_17, 2);
var button_10 = child(div_19);
var button_11 = sibling(button_10, 2);
reset(div_19);
reset(div);
template_effect(() => {
button_6.disabled = get(saveDisabled);
set_attribute2(button_7, "aria-expanded", savedListExpanded());
});
bind_value(input, () => get(contentRow), ($$value) => set(contentRow, $$value));
event("input", input, emit);
event("keydown", input, onRowKeydown);
event("click", button_1, () => set(tagRows, [...get(tagRows), ""]));
bind_value(input_2, () => get(fileRow), ($$value) => set(fileRow, $$value));
event("input", input_2, () => {
set(fileRow, stripQuotes2(get(fileRow)));
emit();
refreshFieldSuggestions({ kind: "file" });
});
event("keydown", input_2, onSuggestingKeydown);
event("click", input_2, () => retargetFieldSuggestions({ kind: "file" }));
event("blur", input_2, hideFieldSuggestions);
bind_value(input_4, () => get(saveName), ($$value) => set(saveName, $$value));
event("keydown", input_4, onSaveNameKeydown);
event("click", button_6, saveFilter);
event("click", button_7, () => onToggleSavedList()(!savedListExpanded()));
event("click", button_10, function(...$$args) {
var _a5;
(_a5 = onClear()) == null ? void 0 : _a5.apply(this, $$args);
});
event("click", button_11, function(...$$args) {
var _a5;
(_a5 = onSearch()) == null ? void 0 : _a5.apply(this, $$args);
});
append($$anchor, div);
return pop($$exports);
}
// src/ui/filters/today_store.ts
var ROLLOVER_SLACK_MS = 1e3;
function millisUntilNextLocalMidnight(now2) {
const nextMidnight = new Date(
now2.getFullYear(),
now2.getMonth(),
now2.getDate() + 1
);
return nextMidnight.getTime() - now2.getTime() + ROLLOVER_SLACK_MS;
}
function registerDefaultWakeListeners(onWake) {
if (typeof document === "undefined" || typeof window === "undefined") {
return () => {
};
}
document.addEventListener("visibilitychange", onWake);
window.addEventListener("focus", onWake);
return () => {
document.removeEventListener("visibilitychange", onWake);
window.removeEventListener("focus", onWake);
};
}
function createTodayStore(registerWakeListeners = registerDefaultWakeListeners) {
let current = getToday();
return readable(current, (set3) => {
let timer;
const check = () => {
const next2 = getToday();
if (next2.getTime() !== current.getTime()) {
current = next2;
set3(next2);
}
};
const arm = () => {
timer = setTimeout(() => {
check();
arm();
}, millisUntilNextLocalMidnight(/* @__PURE__ */ new Date()));
};
check();
arm();
const removeWakeListeners = registerWakeListeners(check);
return () => {
if (timer !== void 0) {
clearTimeout(timer);
}
removeWakeListeners();
};
});
}
// src/ui/dashboard/dashboard_panel.svelte
var import_obsidian10 = require("obsidian");
// src/ui/boards/board_index.ts
var KANBAN_PLUGIN_KEY = "kanban_plugin";
function createBoardIndex(app, registerEvent) {
const store = writable([]);
let lastSerialized = JSON.stringify([]);
let recomputeTimer;
const recompute = () => {
const entries = sortBoardEntries(
app.vault.getMarkdownFiles().filter((file) => isBoardFile(app, file)).map((file) => {
var _a5, _b3;
return {
path: file.path,
name: file.basename,
folder: (_b3 = (_a5 = file.parent) == null ? void 0 : _a5.path) != null ? _b3 : ""
};
})
);
const serialized = JSON.stringify(entries);
if (serialized !== lastSerialized) {
lastSerialized = serialized;
store.set(entries);
}
};
const scheduleRecompute = () => {
if (recomputeTimer) {
clearTimeout(recomputeTimer);
}
recomputeTimer = setTimeout(() => {
recomputeTimer = void 0;
recompute();
}, 250);
};
registerEvent(app.metadataCache.on("changed", scheduleRecompute));
registerEvent(app.metadataCache.on("deleted", scheduleRecompute));
registerEvent(app.metadataCache.on("resolved", scheduleRecompute));
registerEvent(app.vault.on("rename", scheduleRecompute));
recompute();
return {
store: { subscribe: store.subscribe },
destroy: () => {
if (recomputeTimer) {
clearTimeout(recomputeTimer);
}
}
};
}
function rewriteBoardPath(path, oldPath, newPath) {
if (path === oldPath) {
return newPath;
}
if (path.startsWith(`${oldPath}/`)) {
return `${newPath}${path.slice(oldPath.length)}`;
}
return path;
}
function isBoardFile(app, file) {
var _a5;
const frontmatter = (_a5 = app.metadataCache.getFileCache(file)) == null ? void 0 : _a5.frontmatter;
return !!frontmatter && KANBAN_PLUGIN_KEY in frontmatter;
}
function sortBoardEntries(entries) {
return [...entries].sort(
(a, b) => a.name.localeCompare(b.name, void 0, { sensitivity: "base" }) || a.path.localeCompare(b.path)
);
}
function resolveBoardList(boards, boardList) {
var _a5, _b3;
const orderedPaths = (_a5 = boardList == null ? void 0 : boardList.boardPaths) != null ? _a5 : [];
const orderedPathSet = new Set(orderedPaths);
const unpinnedPaths = new Set((_b3 = boardList == null ? void 0 : boardList.unpinnedPaths) != null ? _b3 : []);
const boardsByPath = new Map(boards.map((board) => [board.path, board]));
const ordered = orderedPaths.filter((path) => !unpinnedPaths.has(path)).map((path) => boardsByPath.get(path)).filter((board) => board !== void 0);
const rest = sortBoardEntries(
boards.filter(
(board) => !orderedPathSet.has(board.path) && !unpinnedPaths.has(board.path)
)
);
const hidden = sortBoardEntries(
boards.filter((board) => unpinnedPaths.has(board.path))
);
return { shown: [...ordered, ...rest], hidden };
}
function rewriteBoardListPaths(boardList, oldPath, newPath) {
var _a5, _b3;
const boardPaths = (_a5 = boardList == null ? void 0 : boardList.boardPaths) != null ? _a5 : [];
const unpinnedPaths = (_b3 = boardList == null ? void 0 : boardList.unpinnedPaths) != null ? _b3 : [];
const rewrittenBoardPaths = boardPaths.map(
(path) => rewriteBoardPath(path, oldPath, newPath)
);
const rewrittenUnpinnedPaths = unpinnedPaths.map(
(path) => rewriteBoardPath(path, oldPath, newPath)
);
if (rewrittenBoardPaths.every((path, index2) => path === boardPaths[index2]) && rewrittenUnpinnedPaths.every((path, index2) => path === unpinnedPaths[index2])) {
return null;
}
return {
...rewrittenBoardPaths.length > 0 ? { boardPaths: rewrittenBoardPaths } : {},
...rewrittenUnpinnedPaths.length > 0 ? { unpinnedPaths: rewrittenUnpinnedPaths } : {}
};
}
function rewriteLastOpenedPaths(lastOpenedByPath, oldPath, newPath) {
var _a5;
if (!lastOpenedByPath) {
return null;
}
let changed = false;
const rewritten = {};
for (const [path, openedAt] of Object.entries(lastOpenedByPath)) {
const nextPath = rewriteBoardPath(path, oldPath, newPath);
changed || (changed = nextPath !== path);
rewritten[nextPath] = Math.max((_a5 = rewritten[nextPath]) != null ? _a5 : 0, openedAt);
}
return changed ? rewritten : null;
}
function movePathRelativeTo(paths, draggedPath, targetPath, position) {
if (draggedPath === targetPath) {
return paths;
}
const draggedIndex = paths.indexOf(draggedPath);
const targetIndex = paths.indexOf(targetPath);
if (draggedIndex < 0 || targetIndex < 0) {
return paths;
}
const next2 = [...paths];
next2.splice(draggedIndex, 1);
const baseTargetIndex = draggedIndex < targetIndex ? targetIndex - 1 : targetIndex;
next2.splice(position === "after" ? baseTargetIndex + 1 : baseTargetIndex, 0, draggedPath);
return next2;
}
// src/ui/boards/rename_board_modal.ts
var import_obsidian8 = require("obsidian");
// src/ui/boards/board_rename.ts
function boardRenameTarget(entry, newName) {
const trimmed = newName.trim();
if (trimmed === "") {
return { ok: false, reason: "Board name cannot be empty." };
}
if (/[\\/]/.test(trimmed)) {
return { ok: false, reason: "Board name cannot contain path separators." };
}
const folderPrefix = entry.folder === "" || entry.folder === "/" ? "" : `${entry.folder}/`;
return { ok: true, path: `${folderPrefix}${trimmed}.md` };
}
// src/ui/boards/rename_board_modal.ts
async function renameBoardFile(app, entry, newName) {
const target = boardRenameTarget(entry, newName);
if (!target.ok) {
new import_obsidian8.Notice(target.reason);
return false;
}
if (target.path === entry.path) {
return true;
}
const source2 = app.vault.getAbstractFileByPath(entry.path);
if (!(source2 instanceof import_obsidian8.TFile)) {
new import_obsidian8.Notice("Board file not found.");
return false;
}
if (app.vault.getAbstractFileByPath(target.path)) {
new import_obsidian8.Notice(`A file named "${target.path}" already exists.`);
return false;
}
try {
await app.fileManager.renameFile(source2, target.path);
return true;
} catch (error) {
console.error("Failed to rename board", error);
new import_obsidian8.Notice("Failed to rename board.");
return false;
}
}
var RenameBoardModal = class extends import_obsidian8.Modal {
constructor(app, entry) {
super(app);
this.entry = entry;
}
onOpen() {
this.contentEl.addClass("task-list-kanban-confirm-modal");
this.contentEl.createEl("h2", { text: "Rename board" });
this.contentEl.createEl("p", {
text: `Rename "${this.entry.path}" without moving it.`,
cls: "setting-item-description"
});
const input = this.contentEl.createEl("input", {
type: "text",
value: this.entry.name
});
input.style.width = "100%";
const actions = this.contentEl.createDiv({ cls: "confirm-modal-actions" });
const cancelButton = actions.createEl("button", { text: "Cancel" });
cancelButton.addEventListener("click", () => this.close());
const renameButton = actions.createEl("button", {
text: "Rename",
cls: "mod-cta"
});
const submit = async () => {
renameButton.disabled = true;
try {
if (await renameBoardFile(this.app, this.entry, input.value)) {
this.close();
}
} finally {
renameButton.disabled = false;
}
};
renameButton.addEventListener("click", () => void submit());
input.addEventListener("keydown", (event2) => {
if (event2.key === "Enter") {
event2.preventDefault();
void submit();
}
});
window.requestAnimationFrame(() => {
input.focus();
input.select();
});
}
onClose() {
this.contentEl.empty();
}
};
// src/ui/settings/confirm_modal.ts
var import_obsidian9 = require("obsidian");
var ConfirmModal = class extends import_obsidian9.Modal {
constructor(app, options) {
super(app);
this.options = options;
}
onOpen() {
this.contentEl.addClass("task-list-kanban-confirm-modal");
this.contentEl.createEl("h2", { text: this.options.title });
this.contentEl.createEl("p", { text: this.options.body });
if (this.options.note) {
this.contentEl.createEl("p", {
text: this.options.note,
cls: "setting-item-description"
});
}
const actions = this.contentEl.createDiv({ cls: "confirm-modal-actions" });
const cancelButton = actions.createEl("button", { text: "Cancel" });
cancelButton.addEventListener("click", () => this.close());
const confirmButton = actions.createEl("button", {
text: this.options.confirmText,
cls: "mod-warning"
});
confirmButton.addEventListener("click", async () => {
confirmButton.disabled = true;
try {
await this.options.onConfirm();
this.close();
} finally {
confirmButton.disabled = false;
}
});
window.requestAnimationFrame(() => cancelButton.focus());
}
onClose() {
this.contentEl.empty();
}
};
// src/ui/dashboard/dashboard_cards.ts
function buildBoardCards(entries, getStat, lastOpenedByPath = {}) {
return entries.map((entry) => {
var _a5;
return {
path: entry.path,
name: entry.name,
folder: normalizeCardFolder(entry.folder),
lastModified: (_a5 = getStat(entry.path)) == null ? void 0 : _a5.mtime,
lastOpened: lastOpenedByPath[entry.path]
};
});
}
function normalizeCardFolder(folder) {
return folder === "/" ? "" : folder;
}
var MINUTE_MS = 6e4;
var HOUR_MS = 60 * MINUTE_MS;
var DAY_MS = 24 * HOUR_MS;
function formatLastModified(mtime, now2) {
const elapsed = now2 - mtime;
if (elapsed < MINUTE_MS) {
return "just now";
}
if (elapsed < HOUR_MS) {
return pluralAgo(Math.floor(elapsed / MINUTE_MS), "minute");
}
if (elapsed < DAY_MS) {
return pluralAgo(Math.floor(elapsed / HOUR_MS), "hour");
}
if (elapsed < 7 * DAY_MS) {
return pluralAgo(Math.floor(elapsed / DAY_MS), "day");
}
return new Date(mtime).toLocaleDateString(void 0, {
year: "numeric",
month: "short",
day: "numeric"
});
}
function pluralAgo(count, unit) {
return `${count} ${unit}${count === 1 ? "" : "s"} ago`;
}
// src/ui/dashboard/dashboard_card.svelte
var root20 = from_html(`<span class="board-card-folder svelte-1q4k65g"> </span>`);
var root_120 = from_html(`<span class="board-card-counts svelte-1q4k65g"> </span>`);
var root_213 = from_html(`<span class="board-card-counts pending svelte-1q4k65g">Counting\u2026</span>`);
var root_310 = from_html(`<span class="board-card-attention-badge overdue svelte-1q4k65g"> </span>`);
var root_410 = from_html(`<span class="board-card-attention-badge due-today svelte-1q4k65g"> </span>`);
var root_58 = from_html(`<span class="board-card-attention svelte-1q4k65g"><!> <!></span>`);
var root_66 = from_html(`<span class="board-card-meta svelte-1q4k65g"> </span>`);
var root_75 = from_html(`<li class="svelte-1q4k65g"><span class="board-card-column-label svelte-1q4k65g"> </span> <span class="board-card-column-count svelte-1q4k65g"> </span></li>`);
var root_84 = from_html(`<ul class="board-card-columns svelte-1q4k65g"></ul>`);
var root_94 = from_html(`<button type="button" class="board-card-columns-toggle svelte-1q4k65g"><!> <span>Columns</span></button> <!>`, 1);
var root_104 = from_html(`<div><button type="button" class="board-card-main svelte-1q4k65g"><span class="board-card-name svelte-1q4k65g"> </span> <!> <!> <!> <!> <!></button> <!></div>`);
var $$css20 = {
hash: "svelte-1q4k65g",
code: ".board-card.svelte-1q4k65g {display:flex;flex-direction:column;align-items:flex-start;gap:var(--size-2-2);margin:0;padding:var(--size-4-3);background:var(--background-secondary);border:1px solid var(--background-modifier-border);border-radius:var(--radius-m);box-shadow:none;text-align:left;cursor:pointer;}.board-card.svelte-1q4k65g:hover {background:var(--background-modifier-hover);border-color:var(--background-modifier-border-hover);}.board-card.current.svelte-1q4k65g {border-color:color-mix(in srgb, var(--interactive-accent) 48%, transparent);box-shadow:0 0 0 2px color-mix(in srgb, var(--interactive-accent) 18%, transparent);}.board-card.is-dragging.svelte-1q4k65g {opacity:0.5;}.board-card.drop-before.svelte-1q4k65g {box-shadow:-3px 0 0 0 var(--interactive-accent);}.board-card.drop-after.svelte-1q4k65g {box-shadow:3px 0 0 0 var(--interactive-accent);}.board-card-main.svelte-1q4k65g {display:flex;flex-direction:column;align-items:flex-start;gap:var(--size-2-2);width:100%;height:auto;margin:0;padding:0;background:transparent;border:none;border-radius:0;box-shadow:none;text-align:left;cursor:pointer;}.board-card-name.svelte-1q4k65g {max-width:100%;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;color:var(--text-normal);font-weight:600;}.board-card-folder.svelte-1q4k65g {max-width:100%;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;color:var(--text-muted);font-size:var(--font-ui-small);}.board-card-counts.svelte-1q4k65g {color:var(--text-muted);font-size:var(--font-ui-small);}.board-card-counts.pending.svelte-1q4k65g {color:var(--text-faint);}.board-card-attention.svelte-1q4k65g {display:flex;flex-wrap:wrap;gap:var(--size-2-2);}.board-card-attention-badge.svelte-1q4k65g {display:inline-flex;align-items:center;min-height:18px;padding:1px var(--size-2-2);border-radius:var(--radius-s);font-size:var(--font-ui-smaller);font-weight:600;line-height:1.3;}.board-card-attention-badge.overdue.svelte-1q4k65g {color:var(--text-on-accent);background:var(--text-error);}.board-card-attention-badge.due-today.svelte-1q4k65g {color:var(--text-accent);background:color-mix(in srgb, var(--interactive-accent) 14%, transparent);}.board-card-meta.svelte-1q4k65g {color:var(--text-faint);font-size:var(--font-ui-smaller);}.board-card-columns-toggle.svelte-1q4k65g {display:inline-flex;align-items:center;gap:var(--size-2-2);margin:0;padding:0;height:auto;background:transparent;border:none;box-shadow:none;color:var(--text-muted);font-size:var(--font-ui-smaller);font-weight:600;cursor:pointer;}.board-card-columns-toggle.svelte-1q4k65g:hover {color:var(--text-normal);}.board-card-columns.svelte-1q4k65g {width:100%;margin:0;padding:0;list-style:none;}.board-card-columns.svelte-1q4k65g li:where(.svelte-1q4k65g) {display:flex;justify-content:space-between;gap:var(--size-4-2);color:var(--text-muted);font-size:var(--font-ui-small);}.board-card-column-label.svelte-1q4k65g {overflow:hidden;text-overflow:ellipsis;white-space:nowrap;}.board-card-column-count.svelte-1q4k65g {color:var(--text-normal);font-variant-numeric:tabular-nums;}"
};
function Dashboard_card($$anchor, $$props) {
if (new.target) return createClassComponent({ component: Dashboard_card, ...$$anchor });
push($$props, false);
append_styles($$anchor, $$css20);
const attention = mutable_source();
const hasAttention = mutable_source();
let card = prop($$props, "card", 12);
let current = prop($$props, "current", 12);
let now2 = prop($$props, "now", 12);
let counts = prop($$props, "counts", 12, null);
let onSelect = prop($$props, "onSelect", 12);
let onContextMenu = prop($$props, "onContextMenu", 12);
let reorderable = prop($$props, "reorderable", 12, false);
let dragging = prop($$props, "dragging", 12, false);
let dropPosition = prop($$props, "dropPosition", 12, null);
let onDragStart = prop($$props, "onDragStart", 12, void 0);
let onDragEnd = prop($$props, "onDragEnd", 12, void 0);
let onDragOver = prop($$props, "onDragOver", 12, void 0);
let onDragLeave = prop($$props, "onDragLeave", 12, void 0);
let onDrop = prop($$props, "onDrop", 12, void 0);
let columnsExpanded = mutable_source(false);
function positionFromEvent(event2) {
const rect = event2.currentTarget.getBoundingClientRect();
return event2.clientX > rect.left + rect.width / 2 ? "after" : "before";
}
function handleDragOver(event2) {
if (!onDragOver()) {
return;
}
if (onDragOver()(positionFromEvent(event2))) {
event2.preventDefault();
if (event2.dataTransfer) {
event2.dataTransfer.dropEffect = "move";
}
}
}
function handleDrop(event2) {
var _a5;
event2.preventDefault();
(_a5 = onDrop()) == null ? void 0 : _a5(positionFromEvent(event2));
}
legacy_pre_effect(() => deep_read_state(counts()), () => {
var _a5;
set(attention, (_a5 = counts()) == null ? void 0 : _a5.attention);
});
legacy_pre_effect(() => get(attention), () => {
set(hasAttention, get(attention) !== void 0 && (get(attention).overdue > 0 || get(attention).dueToday > 0));
});
legacy_pre_effect_reset();
var $$exports = {
get card() {
return card();
},
set card($$value) {
card($$value);
flushSync();
},
get current() {
return current();
},
set current($$value) {
current($$value);
flushSync();
},
get now() {
return now2();
},
set now($$value) {
now2($$value);
flushSync();
},
get counts() {
return counts();
},
set counts($$value) {
counts($$value);
flushSync();
},
get onSelect() {
return onSelect();
},
set onSelect($$value) {
onSelect($$value);
flushSync();
},
get onContextMenu() {
return onContextMenu();
},
set onContextMenu($$value) {
onContextMenu($$value);
flushSync();
},
get reorderable() {
return reorderable();
},
set reorderable($$value) {
reorderable($$value);
flushSync();
},
get dragging() {
return dragging();
},
set dragging($$value) {
dragging($$value);
flushSync();
},
get dropPosition() {
return dropPosition();
},
set dropPosition($$value) {
dropPosition($$value);
flushSync();
},
get onDragStart() {
return onDragStart();
},
set onDragStart($$value) {
onDragStart($$value);
flushSync();
},
get onDragEnd() {
return onDragEnd();
},
set onDragEnd($$value) {
onDragEnd($$value);
flushSync();
},
get onDragOver() {
return onDragOver();
},
set onDragOver($$value) {
onDragOver($$value);
flushSync();
},
get onDragLeave() {
return onDragLeave();
},
set onDragLeave($$value) {
onDragLeave($$value);
flushSync();
},
get onDrop() {
return onDrop();
},
set onDrop($$value) {
onDrop($$value);
flushSync();
},
$set: update_legacy_props,
$on: ($$event_name, $$event_cb) => add_legacy_event_listener($$props, $$event_name, $$event_cb)
};
init();
var div = root_104();
let classes;
var button = child(div);
var span = child(button);
var text2 = child(span, true);
reset(span);
var node = sibling(span, 2);
{
var consequent = ($$anchor2) => {
var span_1 = root20();
var text_1 = child(span_1, true);
reset(span_1);
template_effect(() => set_text(text_1, (deep_read_state(card()), untrack(() => card().folder))));
append($$anchor2, span_1);
};
if_block(node, ($$render) => {
if (deep_read_state(card()), untrack(() => card().folder)) $$render(consequent);
});
}
var node_1 = sibling(node, 2);
{
var consequent_1 = ($$anchor2) => {
var span_2 = root_120();
var text_2 = child(span_2);
reset(span_2);
template_effect(() => {
var _a5, _b3;
return set_text(text_2, `${(_a5 = (deep_read_state(counts()), untrack(() => counts().open))) != null ? _a5 : ""} open \xB7 ${(_b3 = (deep_read_state(counts()), untrack(() => counts().done))) != null ? _b3 : ""} done`);
});
append($$anchor2, span_2);
};
var alternate = ($$anchor2) => {
var span_3 = root_213();
append($$anchor2, span_3);
};
if_block(node_1, ($$render) => {
if (counts()) $$render(consequent_1);
else $$render(alternate, -1);
});
}
var node_2 = sibling(node_1, 2);
{
var consequent_4 = ($$anchor2) => {
var span_4 = root_58();
var node_3 = child(span_4);
{
var consequent_2 = ($$anchor3) => {
var span_5 = root_310();
var text_3 = child(span_5);
reset(span_5);
template_effect(() => {
var _a5;
return set_text(text_3, `${(_a5 = (get(attention), untrack(() => get(attention).overdue))) != null ? _a5 : ""} overdue`);
});
append($$anchor3, span_5);
};
if_block(node_3, ($$render) => {
if (get(attention), untrack(() => get(attention).overdue > 0)) $$render(consequent_2);
});
}
var node_4 = sibling(node_3, 2);
{
var consequent_3 = ($$anchor3) => {
var span_6 = root_410();
var text_4 = child(span_6);
reset(span_6);
template_effect(() => {
var _a5;
return set_text(text_4, `${(_a5 = (get(attention), untrack(() => get(attention).dueToday))) != null ? _a5 : ""} due today`);
});
append($$anchor3, span_6);
};
if_block(node_4, ($$render) => {
if (get(attention), untrack(() => get(attention).dueToday > 0)) $$render(consequent_3);
});
}
reset(span_4);
append($$anchor2, span_4);
};
if_block(node_2, ($$render) => {
if (get(hasAttention) && get(attention)) $$render(consequent_4);
});
}
var node_5 = sibling(node_2, 2);
{
var consequent_5 = ($$anchor2) => {
var span_7 = root_66();
var text_5 = child(span_7);
reset(span_7);
template_effect(($0) => set_text(text_5, `Updated ${$0 != null ? $0 : ""}`), [
() => (deep_read_state(formatLastModified), deep_read_state(card()), deep_read_state(now2()), untrack(() => formatLastModified(card().lastModified, now2())))
]);
append($$anchor2, span_7);
};
if_block(node_5, ($$render) => {
if (deep_read_state(card()), untrack(() => card().lastModified !== void 0)) $$render(consequent_5);
});
}
var node_6 = sibling(node_5, 2);
{
var consequent_6 = ($$anchor2) => {
var span_8 = root_66();
var text_6 = child(span_8);
reset(span_8);
template_effect(($0) => set_text(text_6, `Opened ${$0 != null ? $0 : ""}`), [
() => (deep_read_state(formatLastModified), deep_read_state(card()), deep_read_state(now2()), untrack(() => formatLastModified(card().lastOpened, now2())))
]);
append($$anchor2, span_8);
};
if_block(node_6, ($$render) => {
if (deep_read_state(card()), untrack(() => card().lastOpened !== void 0)) $$render(consequent_6);
});
}
reset(button);
var node_7 = sibling(button, 2);
{
var consequent_8 = ($$anchor2) => {
var fragment = root_94();
var button_1 = first_child(fragment);
var node_8 = child(button_1);
{
let $0 = derived_safe_equal(() => get(columnsExpanded) ? "chevron-down" : "chevron-right");
Icon(node_8, {
get name() {
return get($0);
},
size: 14
});
}
next(2);
reset(button_1);
var node_9 = sibling(button_1, 2);
{
var consequent_7 = ($$anchor3) => {
var ul = root_84();
each(
ul,
5,
() => (deep_read_state(counts()), untrack(() => counts().columns)),
index,
($$anchor4, columnCount) => {
var li = root_75();
var span_9 = child(li);
var text_7 = child(span_9, true);
reset(span_9);
var span_10 = sibling(span_9, 2);
var text_8 = child(span_10, true);
reset(span_10);
reset(li);
template_effect(() => {
set_text(text_7, (get(columnCount), untrack(() => get(columnCount).label)));
set_text(text_8, (get(columnCount), untrack(() => get(columnCount).count)));
});
append($$anchor4, li);
}
);
reset(ul);
append($$anchor3, ul);
};
if_block(node_9, ($$render) => {
if (get(columnsExpanded)) $$render(consequent_7);
});
}
template_effect(() => set_attribute2(button_1, "aria-expanded", get(columnsExpanded)));
event("click", button_1, stopPropagation(() => set(columnsExpanded, !get(columnsExpanded))));
append($$anchor2, fragment);
};
if_block(node_7, ($$render) => {
if (deep_read_state(counts()), untrack(() => counts() && counts().columns.length > 0)) $$render(consequent_8);
});
}
reset(div);
template_effect(() => {
classes = set_class(div, 1, "board-card svelte-1q4k65g", null, classes, {
current: current(),
"is-dragging": dragging(),
"drop-before": dropPosition() === "before",
"drop-after": dropPosition() === "after"
});
set_attribute2(div, "title", (deep_read_state(card()), untrack(() => card().path)));
set_attribute2(div, "draggable", reorderable());
set_attribute2(button, "aria-current", current() ? "true" : void 0);
set_text(text2, (deep_read_state(card()), untrack(() => card().name)));
});
event("click", div, () => onSelect()(card().path));
event("contextmenu", div, preventDefault((event2) => onContextMenu()(card(), event2)));
event("dragstart", div, (event2) => {
var _a5;
if (event2.dataTransfer) {
event2.dataTransfer.effectAllowed = "move";
event2.dataTransfer.setData("text/plain", card().path);
}
(_a5 = onDragStart()) == null ? void 0 : _a5();
});
event("dragend", div, () => {
var _a5;
return (_a5 = onDragEnd()) == null ? void 0 : _a5();
});
event("dragover", div, handleDragOver);
event("dragleave", div, () => {
var _a5;
return (_a5 = onDragLeave()) == null ? void 0 : _a5();
});
event("drop", div, handleDrop);
append($$anchor, div);
return pop($$exports);
}
// node_modules/svelte/src/easing/index.js
function cubicOut(t) {
const f = t - 1;
return f * f * f + 1;
}
// src/ui/dashboard/dashboard_panel_state.ts
var PANEL_TRANSITION_DURATION_MS = 350;
function panelTransitionDuration(reducedMotion) {
return reducedMotion ? 0 : PANEL_TRANSITION_DURATION_MS;
}
function panelSlide(_node, options) {
const translate = options.axis === "y" ? "translateY" : "translateX";
return {
duration: options.duration,
easing: cubicOut,
css: (t) => `transform: ${translate}(${(t - 1) * 100}%)`
};
}
function scrimFade(_node, options) {
return {
duration: options.duration,
easing: cubicOut,
css: (t) => `opacity: ${t}`
};
}
function shouldSwitchBoard(selectedPath, currentPath) {
return selectedPath !== currentPath;
}
// src/ui/dashboard/dashboard_panel.svelte
var root21 = from_html(`<button type="button" class="dashboard-new-board svelte-v52puw"><!> <span>New board</span></button>`);
var root_121 = from_html(`<p class="dashboard-empty svelte-v52puw">No kanban boards found in this vault. Use New board above, or create
one from a folder's context menu with "New kanban".</p>`);
var root_214 = from_html(`<div class="dashboard-grid svelte-v52puw"></div>`);
var root_311 = from_html(`<button type="button" class="other-boards-toggle svelte-v52puw"><!> <span> </span></button> <!>`, 1);
var root_411 = from_html(`<div class="dashboard-grid svelte-v52puw"></div> <!>`, 1);
var root_59 = from_html(`<div class="dashboard-overlay svelte-v52puw"><div class="dashboard-scrim svelte-v52puw" aria-hidden="true"></div> <div class="dashboard-panel svelte-v52puw" role="dialog" aria-label="Board dashboard" tabindex="-1"><div class="dashboard-header svelte-v52puw"><h2 class="dashboard-title svelte-v52puw">Kanban boards</h2> <div class="dashboard-actions svelte-v52puw"><!> <button type="button" class="dashboard-close svelte-v52puw" aria-label="Close dashboard"><!></button></div></div> <!></div></div>`);
var $$css21 = {
hash: "svelte-v52puw",
code: ".dashboard-overlay.svelte-v52puw {position:absolute;top:calc(-1 * var(--size-4-2));bottom:0;left:calc(-1 * var(--size-4-4));right:calc(-1 * var(--size-4-4));z-index:200;overflow:hidden;}.dashboard-scrim.svelte-v52puw {position:absolute;inset:0;background:rgba(0, 0, 0, 0.25);}.dashboard-panel.svelte-v52puw {position:absolute;top:0;bottom:0;left:0;width:min(75%, 960px);box-sizing:border-box;padding:var(--size-4-4);overflow-y:auto;background:var(--background-primary);border-top:1px solid var(--background-modifier-border);border-right:1px solid var(--background-modifier-border);box-shadow:var(--shadow-l, 4px 0 24px rgba(0, 0, 0, 0.2));outline:none;}.dashboard-header.svelte-v52puw {display:flex;align-items:center;justify-content:space-between;gap:var(--size-4-2);margin:0 0 var(--size-4-4) 0;}.dashboard-title.svelte-v52puw {margin:0;}.dashboard-actions.svelte-v52puw {display:inline-flex;align-items:center;gap:var(--size-4-2);flex:0 0 auto;}.dashboard-new-board.svelte-v52puw {display:inline-flex;align-items:center;gap:var(--size-4-1);height:32px;margin:0;padding:0 var(--size-4-2);border-radius:var(--radius-s);font-size:var(--font-ui-small);font-weight:var(--font-medium);cursor:pointer;}.dashboard-close.svelte-v52puw {display:inline-flex;align-items:center;justify-content:center;flex:0 0 auto;width:28px;height:28px;margin:0;padding:0;background:transparent;border:none;border-radius:var(--radius-s);box-shadow:none;color:var(--text-muted);cursor:pointer;}.dashboard-close.svelte-v52puw:hover {background:var(--background-modifier-hover);color:var(--text-normal);}.dashboard-empty.svelte-v52puw {color:var(--text-muted);}.dashboard-grid.svelte-v52puw {display:grid;grid-template-columns:repeat(auto-fill, minmax(220px, 1fr));gap:var(--size-4-3);}.other-boards-toggle.svelte-v52puw {display:inline-flex;align-items:center;gap:var(--size-2-2);margin:var(--size-4-4) 0 var(--size-4-3) 0;padding:0;background:transparent;border:none;box-shadow:none;color:var(--text-muted);font-size:var(--font-ui-small);font-weight:600;cursor:pointer;}.other-boards-toggle.svelte-v52puw:hover {color:var(--text-normal);}"
};
function Dashboard_panel($$anchor, $$props) {
if (new.target) return createClassComponent({ component: Dashboard_panel, ...$$anchor });
push($$props, false);
append_styles($$anchor, $$css21);
const $boardIndexStore = () => store_get(boardIndexStore(), "$boardIndexStore", $$stores);
const $boardListSettingsStore = () => store_get(boardListSettingsStore(), "$boardListSettingsStore", $$stores);
const $lastOpenedStore = () => store_get(lastOpenedStore(), "$lastOpenedStore", $$stores);
const $boardCountsStore = () => store_get(boardCountsStore(), "$boardCountsStore", $$stores);
const [$$stores, $$cleanup] = setup_stores();
let app = prop($$props, "app", 12);
let boardIndexStore = prop($$props, "boardIndexStore", 12);
let boardListSettingsStore = prop($$props, "boardListSettingsStore", 28, () => readable(void 0));
let currentPath = prop($$props, "currentPath", 12);
let getBoardStat = prop($$props, "getBoardStat", 12);
let onSelect = prop($$props, "onSelect", 12);
let onSetBoardHidden = prop($$props, "onSetBoardHidden", 12, void 0);
let onReorderBoards = prop($$props, "onReorderBoards", 12, void 0);
let boardCountsStore = prop($$props, "boardCountsStore", 28, () => readable(/* @__PURE__ */ new Map()));
let onRequestBoardCounts = prop($$props, "onRequestBoardCounts", 12, void 0);
let lastOpenedStore = prop($$props, "lastOpenedStore", 28, () => readable({}));
let onCreateBoard = prop($$props, "onCreateBoard", 12, void 0);
let onDeleteBoard = prop($$props, "onDeleteBoard", 12, void 0);
let slideFrom = prop($$props, "slideFrom", 12, "left");
let onClose = prop($$props, "onClose", 12);
const duration = panelTransitionDuration(window.matchMedia("(prefers-reduced-motion: reduce)").matches);
let panelEl = mutable_source();
let modifyEventRef;
let refreshTimer;
let midnightRefreshTimer;
let refreshTick = mutable_source(0);
let otherBoardsExpanded = mutable_source(false);
let now2 = mutable_source(Date.now());
let shownCards = mutable_source([]);
let hiddenCards = mutable_source([]);
function requestVisibleCounts(shown, hidden, hiddenExpanded) {
var _a5;
const paths = [
...shown.map((card) => card.path),
...hiddenExpanded ? hidden.map((card) => card.path) : []
];
if (paths.length > 0) {
(_a5 = onRequestBoardCounts()) == null ? void 0 : _a5(paths);
}
}
onMount(() => {
var _a5;
(_a5 = get(panelEl)) == null ? void 0 : _a5.focus();
modifyEventRef = app().vault.on("modify", scheduleRefresh);
scheduleMidnightRefresh();
});
onDestroy(() => {
if (modifyEventRef) {
app().vault.offref(modifyEventRef);
}
if (refreshTimer !== void 0) {
window.clearTimeout(refreshTimer);
}
if (midnightRefreshTimer !== void 0) {
window.clearTimeout(midnightRefreshTimer);
}
});
function scheduleRefresh() {
if (refreshTimer !== void 0) {
window.clearTimeout(refreshTimer);
}
refreshTimer = window.setTimeout(
() => {
refreshTimer = void 0;
set(refreshTick, get(refreshTick) + 1);
},
500
);
}
function scheduleMidnightRefresh() {
if (midnightRefreshTimer !== void 0) {
window.clearTimeout(midnightRefreshTimer);
}
const now3 = /* @__PURE__ */ new Date();
const nextMidnight = new Date(now3.getFullYear(), now3.getMonth(), now3.getDate() + 1, 0, 0, 1);
midnightRefreshTimer = window.setTimeout(
() => {
midnightRefreshTimer = void 0;
set(refreshTick, get(refreshTick) + 1);
scheduleMidnightRefresh();
},
Math.max(1e3, nextMidnight.getTime() - now3.getTime())
);
}
function handleKeydown(event2) {
if (event2.key === "Escape") {
event2.stopPropagation();
onClose()();
}
}
async function handleCreateBoard() {
var _a5;
const created = await ((_a5 = onCreateBoard()) == null ? void 0 : _a5());
if (created) {
onClose()();
}
}
function confirmDeleteBoard(card) {
new ConfirmModal(app(), {
title: "Delete board?",
body: `Delete "${card.name}" from the vault?`,
note: card.path,
confirmText: "Delete board",
onConfirm: async () => {
var _a5;
await ((_a5 = onDeleteBoard()) == null ? void 0 : _a5(card.path));
}
}).open();
}
let draggedPath = mutable_source(null);
let dropTarget = mutable_source(null);
function handleCardDragOver(path, position) {
if (!onReorderBoards() || !get(draggedPath) || get(draggedPath) === path) {
return false;
}
set(dropTarget, { path, position });
return true;
}
function handleCardDrop(path, position) {
const dragged = get(draggedPath);
set(draggedPath, null);
set(dropTarget, null);
if (!onReorderBoards() || !dragged || dragged === path) {
return;
}
const shownPaths = get(shownCards).map((card) => card.path);
const nextOrder = movePathRelativeTo(shownPaths, dragged, path, position);
if (nextOrder !== shownPaths) {
onReorderBoards()(nextOrder);
}
}
function clearDragState() {
set(draggedPath, null);
set(dropTarget, null);
}
function handleCardContextMenu(card, event2, hidden) {
const entry = { path: card.path, name: card.name, folder: card.folder };
const menu = new import_obsidian10.Menu();
menu.addItem((item) => item.setTitle("Rename board").setIcon("pencil").onClick(() => new RenameBoardModal(app(), entry).open()));
if (onSetBoardHidden()) {
menu.addItem((item) => item.setTitle(hidden ? "Show board" : "Hide board").setIcon(hidden ? "eye" : "eye-off").onClick(() => {
var _a5;
return (_a5 = onSetBoardHidden()) == null ? void 0 : _a5(card.path, !hidden);
}));
}
if (onDeleteBoard()) {
menu.addItem((item) => item.setTitle("Delete board").setIcon("trash-2").onClick(() => confirmDeleteBoard(card)));
}
menu.showAtMouseEvent(event2);
}
legacy_pre_effect(
() => (get(refreshTick), resolveBoardList, $boardIndexStore(), $boardListSettingsStore(), buildBoardCards, deep_read_state(getBoardStat()), $lastOpenedStore()),
() => {
void get(refreshTick);
set(now2, Date.now());
const resolved = resolveBoardList($boardIndexStore(), $boardListSettingsStore());
set(shownCards, buildBoardCards(resolved.shown, getBoardStat(), $lastOpenedStore()));
set(hiddenCards, buildBoardCards(resolved.hidden, getBoardStat(), $lastOpenedStore()));
}
);
legacy_pre_effect(
() => (get(shownCards), get(hiddenCards), get(otherBoardsExpanded)),
() => {
requestVisibleCounts(get(shownCards), get(hiddenCards), get(otherBoardsExpanded));
}
);
legacy_pre_effect_reset();
var $$exports = {
get app() {
return app();
},
set app($$value) {
app($$value);
flushSync();
},
get boardIndexStore() {
return boardIndexStore();
},
set boardIndexStore($$value) {
boardIndexStore($$value);
flushSync();
},
get boardListSettingsStore() {
return boardListSettingsStore();
},
set boardListSettingsStore($$value) {
boardListSettingsStore($$value);
flushSync();
},
get currentPath() {
return currentPath();
},
set currentPath($$value) {
currentPath($$value);
flushSync();
},
get getBoardStat() {
return getBoardStat();
},
set getBoardStat($$value) {
getBoardStat($$value);
flushSync();
},
get onSelect() {
return onSelect();
},
set onSelect($$value) {
onSelect($$value);
flushSync();
},
get onSetBoardHidden() {
return onSetBoardHidden();
},
set onSetBoardHidden($$value) {
onSetBoardHidden($$value);
flushSync();
},
get onReorderBoards() {
return onReorderBoards();
},
set onReorderBoards($$value) {
onReorderBoards($$value);
flushSync();
},
get boardCountsStore() {
return boardCountsStore();
},
set boardCountsStore($$value) {
boardCountsStore($$value);
flushSync();
},
get onRequestBoardCounts() {
return onRequestBoardCounts();
},
set onRequestBoardCounts($$value) {
onRequestBoardCounts($$value);
flushSync();
},
get lastOpenedStore() {
return lastOpenedStore();
},
set lastOpenedStore($$value) {
lastOpenedStore($$value);
flushSync();
},
get onCreateBoard() {
return onCreateBoard();
},
set onCreateBoard($$value) {
onCreateBoard($$value);
flushSync();
},
get onDeleteBoard() {
return onDeleteBoard();
},
set onDeleteBoard($$value) {
onDeleteBoard($$value);
flushSync();
},
get slideFrom() {
return slideFrom();
},
set slideFrom($$value) {
slideFrom($$value);
flushSync();
},
get onClose() {
return onClose();
},
set onClose($$value) {
onClose($$value);
flushSync();
},
$set: update_legacy_props,
$on: ($$event_name, $$event_cb) => add_legacy_event_listener($$props, $$event_name, $$event_cb)
};
init();
var div = root_59();
var div_1 = child(div);
var div_2 = sibling(div_1, 2);
var div_3 = child(div_2);
var div_4 = sibling(child(div_3), 2);
var node = child(div_4);
{
var consequent = ($$anchor2) => {
var button = root21();
var node_1 = child(button);
Icon(node_1, { name: "plus", size: 16 });
next(2);
reset(button);
event("click", button, handleCreateBoard);
append($$anchor2, button);
};
if_block(node, ($$render) => {
if (onCreateBoard()) $$render(consequent);
});
}
var button_1 = sibling(node, 2);
var node_2 = child(button_1);
Icon(node_2, { name: "x", size: 18 });
reset(button_1);
reset(div_4);
reset(div_3);
var node_3 = sibling(div_3, 2);
{
var consequent_1 = ($$anchor2) => {
var p = root_121();
append($$anchor2, p);
};
var alternate = ($$anchor2) => {
var fragment = root_411();
var div_5 = first_child(fragment);
each(div_5, 5, () => get(shownCards), (card) => card.path, ($$anchor3, card) => {
{
let $0 = derived_safe_equal(() => (get(card), deep_read_state(currentPath()), untrack(() => get(card).path === currentPath())));
let $1 = derived_safe_equal(() => ($boardCountsStore(), get(card), untrack(() => {
var _a5;
return (_a5 = $boardCountsStore().get(get(card).path)) != null ? _a5 : null;
})));
let $2 = derived_safe_equal(() => onReorderBoards() !== void 0);
let $3 = derived_safe_equal(() => (get(draggedPath), get(card), untrack(() => get(draggedPath) === get(card).path)));
let $4 = derived_safe_equal(() => (get(dropTarget), get(card), untrack(() => {
var _a5;
return ((_a5 = get(dropTarget)) == null ? void 0 : _a5.path) === get(card).path ? get(dropTarget).position : null;
})));
Dashboard_card($$anchor3, {
get card() {
return get(card);
},
get current() {
return get($0);
},
get now() {
return get(now2);
},
get counts() {
return get($1);
},
get onSelect() {
return onSelect();
},
onContextMenu: (menuCard, event2) => handleCardContextMenu(menuCard, event2, false),
get reorderable() {
return get($2);
},
get dragging() {
return get($3);
},
get dropPosition() {
return get($4);
},
onDragStart: () => set(draggedPath, get(card).path),
onDragEnd: clearDragState,
onDragOver: (position) => handleCardDragOver(get(card).path, position),
onDragLeave: () => {
var _a5;
if (((_a5 = get(dropTarget)) == null ? void 0 : _a5.path) === get(card).path) {
set(dropTarget, null);
}
},
onDrop: (position) => handleCardDrop(get(card).path, position)
});
}
});
reset(div_5);
var node_4 = sibling(div_5, 2);
{
var consequent_3 = ($$anchor3) => {
var fragment_2 = root_311();
var button_2 = first_child(fragment_2);
var node_5 = child(button_2);
{
let $0 = derived_safe_equal(() => get(otherBoardsExpanded) ? "chevron-down" : "chevron-right");
Icon(node_5, {
get name() {
return get($0);
},
size: 16
});
}
var span = sibling(node_5, 2);
var text2 = child(span);
reset(span);
reset(button_2);
var node_6 = sibling(button_2, 2);
{
var consequent_2 = ($$anchor4) => {
var div_6 = root_214();
each(div_6, 5, () => get(hiddenCards), (card) => card.path, ($$anchor5, card) => {
{
let $0 = derived_safe_equal(() => (get(card), deep_read_state(currentPath()), untrack(() => get(card).path === currentPath())));
let $1 = derived_safe_equal(() => ($boardCountsStore(), get(card), untrack(() => {
var _a5;
return (_a5 = $boardCountsStore().get(get(card).path)) != null ? _a5 : null;
})));
Dashboard_card($$anchor5, {
get card() {
return get(card);
},
get current() {
return get($0);
},
get now() {
return get(now2);
},
get counts() {
return get($1);
},
get onSelect() {
return onSelect();
},
onContextMenu: (menuCard, event2) => handleCardContextMenu(menuCard, event2, true)
});
}
});
reset(div_6);
append($$anchor4, div_6);
};
if_block(node_6, ($$render) => {
if (get(otherBoardsExpanded)) $$render(consequent_2);
});
}
template_effect(() => {
var _a5;
set_attribute2(button_2, "aria-expanded", get(otherBoardsExpanded));
set_text(text2, `Other boards (${(_a5 = (get(hiddenCards), untrack(() => get(hiddenCards).length))) != null ? _a5 : ""})`);
});
event("click", button_2, () => set(otherBoardsExpanded, !get(otherBoardsExpanded)));
append($$anchor3, fragment_2);
};
if_block(node_4, ($$render) => {
if (get(hiddenCards), untrack(() => get(hiddenCards).length > 0)) $$render(consequent_3);
});
}
append($$anchor2, fragment);
};
if_block(node_3, ($$render) => {
if (get(shownCards), get(hiddenCards), untrack(() => get(shownCards).length === 0 && get(hiddenCards).length === 0)) $$render(consequent_1);
else $$render(alternate, -1);
});
}
reset(div_2);
bind_this(div_2, ($$value) => set(panelEl, $$value), () => get(panelEl));
reset(div);
transition(3, div_1, () => scrimFade, () => ({ duration }));
event("click", div_1, function(...$$args) {
var _a5;
(_a5 = onClose()) == null ? void 0 : _a5.apply(this, $$args);
});
event("click", button_1, function(...$$args) {
var _a5;
(_a5 = onClose()) == null ? void 0 : _a5.apply(this, $$args);
});
transition(3, div_2, () => panelSlide, () => ({ duration, axis: slideFrom() === "top" ? "y" : "x" }));
event("keydown", div, handleKeydown);
append($$anchor, div);
var $$pop = pop($$exports);
$$cleanup();
return $$pop;
}
// src/ui/dashboard/board_rail_state.ts
var RAIL_MIN_WIDTH = 44;
var RAIL_MAX_WIDTH = 320;
var RAIL_LABEL_MIN_WIDTH = 72;
function railDisplayMode(width) {
return width >= RAIL_LABEL_MIN_WIDTH ? "label" : "chip";
}
function clampRailWidth(width) {
return Math.min(RAIL_MAX_WIDTH, Math.max(RAIL_MIN_WIDTH, Math.round(width)));
}
function railVisible(discoveredBoardCount) {
return discoveredBoardCount > 1;
}
function railChipLabel(name) {
var _a5;
const first = [...name.trim()][0];
return (_a5 = first == null ? void 0 : first.toUpperCase()) != null ? _a5 : "?";
}
function railDropPosition(clientY, rect) {
return clientY > rect.top + rect.height / 2 ? "after" : "before";
}
function railDropPositionHorizontal(clientX, rect) {
return clientX > rect.left + rect.width / 2 ? "after" : "before";
}
// src/ui/dashboard/board_rail.svelte
var root22 = from_html(`<span class="rail-dashboard-label svelte-59wfna">Kanban dashboard</span>`);
var root_125 = from_html(`<span class="rail-tab-chip svelte-59wfna"> </span>`);
var root_215 = from_html(`<span class="rail-tab-label svelte-59wfna"> </span>`);
var root_312 = from_html(`<button type="button"><!></button>`);
var root_412 = from_html(`<div class="rail-resize-handle svelte-59wfna" aria-hidden="true"></div>`);
var root_510 = from_html(`<nav aria-label="Kanban boards"><button type="button"><!> <!></button> <div class="rail-separator svelte-59wfna" aria-hidden="true"></div> <div class="rail-tabs svelte-59wfna"></div> <!></nav>`);
var $$css22 = {
hash: "svelte-59wfna",
code: ".board-rail.svelte-59wfna {position:relative;display:flex;flex-direction:column;flex:0 0 auto;box-sizing:border-box;min-height:0;padding:var(--size-4-2) var(--size-2-3) var(--size-4-4) var(--size-2-3);border-right:1px solid var(--background-modifier-border);}.rail-dashboard-toggle.svelte-59wfna {display:inline-flex;align-items:center;justify-content:flex-start;gap:var(--size-2-3);flex:0 0 auto;width:100%;height:36px;min-height:0;box-sizing:border-box;margin:0;padding:0 var(--size-2-3);border:var(--input-border-width, 1px) solid var(--background-modifier-border);border-radius:var(--radius-m);background:var(--background-primary);box-shadow:var(--shadow-s);color:var(--text-normal);cursor:pointer;}.rail-dashboard-toggle.svelte-59wfna:hover {background:var(--background-modifier-hover);}.rail-dashboard-toggle.active.svelte-59wfna {background:var(--background-primary);border-color:color-mix(in srgb, var(--interactive-accent) 24%, transparent);box-shadow:0 0 0 2px color-mix(in srgb, var(--interactive-accent) 18%, transparent);}.rail-dashboard-label.svelte-59wfna {min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-size:var(--font-ui-small);font-weight:600;}.rail-separator.svelte-59wfna {flex:0 0 auto;height:1px;margin:var(--size-4-2) 0;background:var(--background-modifier-border);}.rail-tabs.svelte-59wfna {display:flex;flex-direction:column;gap:var(--size-2-2);flex:1 1 auto;min-height:0;overflow-y:auto;}.rail-tab.svelte-59wfna {display:flex;align-items:center;justify-content:flex-start;flex:0 0 auto;width:100%;min-height:32px;box-sizing:border-box;margin:0;padding:0 var(--size-2-3);background:transparent;border:1px solid transparent;border-radius:var(--radius-m);box-shadow:none;color:var(--text-muted);font-size:var(--font-ui-small);text-align:left;cursor:pointer;}.rail-tab.svelte-59wfna:hover {background:var(--background-modifier-hover);color:var(--text-normal);}.rail-tab.current.svelte-59wfna {background:var(--background-secondary);border-color:color-mix(in srgb, var(--interactive-accent) 48%, transparent);color:var(--text-normal);cursor:default;}.rail-tab.is-dragging.svelte-59wfna {opacity:0.5;}.rail-tab.drop-before.svelte-59wfna {box-shadow:0 -3px 0 0 var(--interactive-accent);}.rail-tab.drop-after.svelte-59wfna {box-shadow:0 3px 0 0 var(--interactive-accent);}.rail-tab-chip.svelte-59wfna {font-weight:600;}.rail-tab-label.svelte-59wfna {min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;}.board-rail.top-dock.svelte-59wfna {flex-direction:row;align-items:center;width:auto;padding:var(--size-2-3) var(--size-4-4);border-right:none;border-bottom:1px solid var(--background-modifier-border);}.board-rail.top-dock.svelte-59wfna .rail-dashboard-toggle:where(.svelte-59wfna) {width:auto;}.board-rail.top-dock.svelte-59wfna .rail-separator:where(.svelte-59wfna) {width:1px;height:20px;margin:0 var(--size-4-2);}.board-rail.top-dock.svelte-59wfna .rail-tabs:where(.svelte-59wfna) {flex-direction:row;align-items:center;min-width:0;overflow-x:auto;overflow-y:hidden;}.board-rail.top-dock.svelte-59wfna .rail-tab:where(.svelte-59wfna) {width:auto;max-width:180px;}.board-rail.top-dock.svelte-59wfna .rail-tab.drop-before:where(.svelte-59wfna) {box-shadow:-3px 0 0 0 var(--interactive-accent);}.board-rail.top-dock.svelte-59wfna .rail-tab.drop-after:where(.svelte-59wfna) {box-shadow:3px 0 0 0 var(--interactive-accent);}.rail-resize-handle.svelte-59wfna {position:absolute;top:0;bottom:0;right:-4px;width:8px;z-index:10;cursor:col-resize;touch-action:none;}"
};
function Board_rail($$anchor, $$props) {
if (new.target) return createClassComponent({ component: Board_rail, ...$$anchor });
push($$props, false);
append_styles($$anchor, $$css22);
const $boardIndexStore = () => store_get(boardIndexStore(), "$boardIndexStore", $$stores);
const $boardListSettingsStore = () => store_get(boardListSettingsStore(), "$boardListSettingsStore", $$stores);
const [$$stores, $$cleanup] = setup_stores();
const tabs = mutable_source();
const displayWidth = mutable_source();
const mode = mutable_source();
let boardIndexStore = prop($$props, "boardIndexStore", 12);
let boardListSettingsStore = prop($$props, "boardListSettingsStore", 28, () => readable(void 0));
let currentPath = prop($$props, "currentPath", 12);
let dashboardOpen = prop($$props, "dashboardOpen", 12);
let onToggleDashboard = prop($$props, "onToggleDashboard", 12);
let onSelect = prop($$props, "onSelect", 12);
let onReorderBoards = prop($$props, "onReorderBoards", 12, void 0);
let dock = prop($$props, "dock", 12, "left");
let width = prop($$props, "width", 12);
let onSetWidth = prop($$props, "onSetWidth", 12, void 0);
let dashboardButtonEl = prop($$props, "dashboardButtonEl", 12, void 0);
let dragWidth = mutable_source(null);
let resizeStartX = 0;
let resizeStartWidth = 0;
function handleResizeStart(event2) {
event2.currentTarget.setPointerCapture(event2.pointerId);
resizeStartX = event2.clientX;
resizeStartWidth = get(displayWidth);
set(dragWidth, get(displayWidth));
}
function handleResizeMove(event2) {
if (get(dragWidth) === null) {
return;
}
set(dragWidth, clampRailWidth(resizeStartWidth + event2.clientX - resizeStartX));
}
function handleResizeEnd() {
var _a5;
if (get(dragWidth) === null) {
return;
}
const next2 = get(dragWidth);
set(dragWidth, null);
if (next2 !== width()) {
(_a5 = onSetWidth()) == null ? void 0 : _a5(next2);
}
}
function handleTabClick(tab) {
if (tab.path === currentPath()) {
return;
}
onSelect()(tab.path);
}
let draggedPath = mutable_source(null);
let dropTarget = mutable_source(null);
function handleTabDragStart(tab, event2) {
if (event2.dataTransfer) {
event2.dataTransfer.effectAllowed = "move";
event2.dataTransfer.setData("text/plain", tab.path);
}
set(draggedPath, tab.path);
}
function tabDropPosition(event2) {
const rect = event2.currentTarget.getBoundingClientRect();
return dock() === "top" ? railDropPositionHorizontal(event2.clientX, rect) : railDropPosition(event2.clientY, rect);
}
function handleTabDragOver(path, event2) {
if (!onReorderBoards() || !get(draggedPath) || get(draggedPath) === path) {
return;
}
set(dropTarget, { path, position: tabDropPosition(event2) });
event2.preventDefault();
if (event2.dataTransfer) {
event2.dataTransfer.dropEffect = "move";
}
}
function handleTabDrop(path, event2) {
event2.preventDefault();
const position = tabDropPosition(event2);
const dragged = get(draggedPath);
clearDragState();
if (!onReorderBoards() || !dragged || dragged === path) {
return;
}
const shownPaths = get(tabs).map((tab) => tab.path);
const nextOrder = movePathRelativeTo(shownPaths, dragged, path, position);
if (nextOrder !== shownPaths) {
onReorderBoards()(nextOrder);
}
}
function clearDragState() {
set(draggedPath, null);
set(dropTarget, null);
}
legacy_pre_effect(
() => (resolveBoardList, $boardIndexStore(), $boardListSettingsStore()),
() => {
set(tabs, resolveBoardList($boardIndexStore(), $boardListSettingsStore()).shown);
}
);
legacy_pre_effect(() => (get(dragWidth), deep_read_state(width())), () => {
var _a5;
set(displayWidth, (_a5 = get(dragWidth)) != null ? _a5 : width());
});
legacy_pre_effect(
() => (deep_read_state(dock()), railDisplayMode, get(displayWidth)),
() => {
set(mode, dock() === "top" ? "label" : railDisplayMode(get(displayWidth)));
}
);
legacy_pre_effect_reset();
var $$exports = {
get boardIndexStore() {
return boardIndexStore();
},
set boardIndexStore($$value) {
boardIndexStore($$value);
flushSync();
},
get boardListSettingsStore() {
return boardListSettingsStore();
},
set boardListSettingsStore($$value) {
boardListSettingsStore($$value);
flushSync();
},
get currentPath() {
return currentPath();
},
set currentPath($$value) {
currentPath($$value);
flushSync();
},
get dashboardOpen() {
return dashboardOpen();
},
set dashboardOpen($$value) {
dashboardOpen($$value);
flushSync();
},
get onToggleDashboard() {
return onToggleDashboard();
},
set onToggleDashboard($$value) {
onToggleDashboard($$value);
flushSync();
},
get onSelect() {
return onSelect();
},
set onSelect($$value) {
onSelect($$value);
flushSync();
},
get onReorderBoards() {
return onReorderBoards();
},
set onReorderBoards($$value) {
onReorderBoards($$value);
flushSync();
},
get dock() {
return dock();
},
set dock($$value) {
dock($$value);
flushSync();
},
get width() {
return width();
},
set width($$value) {
width($$value);
flushSync();
},
get onSetWidth() {
return onSetWidth();
},
set onSetWidth($$value) {
onSetWidth($$value);
flushSync();
},
get dashboardButtonEl() {
return dashboardButtonEl();
},
set dashboardButtonEl($$value) {
dashboardButtonEl($$value);
flushSync();
},
$set: update_legacy_props,
$on: ($$event_name, $$event_cb) => add_legacy_event_listener($$props, $$event_name, $$event_cb)
};
init();
var nav = root_510();
let classes;
var button = child(nav);
let classes_1;
var node = child(button);
Icon(node, { name: "layout-dashboard", size: 16 });
var node_1 = sibling(node, 2);
{
var consequent = ($$anchor2) => {
var span = root22();
append($$anchor2, span);
};
if_block(node_1, ($$render) => {
if (get(mode) === "label") $$render(consequent);
});
}
reset(button);
bind_this(button, ($$value) => dashboardButtonEl($$value), () => dashboardButtonEl());
var div = sibling(button, 4);
each(div, 5, () => get(tabs), (tab) => tab.path, ($$anchor2, tab) => {
var button_1 = root_312();
let classes_2;
var node_2 = child(button_1);
{
var consequent_1 = ($$anchor3) => {
var span_1 = root_125();
var text2 = child(span_1, true);
reset(span_1);
template_effect(($0) => set_text(text2, $0), [
() => (deep_read_state(railChipLabel), get(tab), untrack(() => railChipLabel(get(tab).name)))
]);
append($$anchor3, span_1);
};
var alternate = ($$anchor3) => {
var span_2 = root_215();
var text_1 = child(span_2, true);
reset(span_2);
template_effect(() => set_text(text_1, (get(tab), untrack(() => get(tab).name))));
append($$anchor3, span_2);
};
if_block(node_2, ($$render) => {
if (get(mode) === "chip") $$render(consequent_1);
else $$render(alternate, -1);
});
}
reset(button_1);
template_effect(() => {
var _a5, _b3;
classes_2 = set_class(button_1, 1, "rail-tab svelte-59wfna", null, classes_2, {
current: get(tab).path === currentPath(),
"is-dragging": get(draggedPath) === get(tab).path,
"drop-before": ((_a5 = get(dropTarget)) == null ? void 0 : _a5.path) === get(tab).path && get(dropTarget).position === "before",
"drop-after": ((_b3 = get(dropTarget)) == null ? void 0 : _b3.path) === get(tab).path && get(dropTarget).position === "after"
});
set_attribute2(button_1, "title", (get(tab), untrack(() => get(tab).path)));
set_attribute2(button_1, "aria-current", (get(tab), deep_read_state(currentPath()), untrack(() => get(tab).path === currentPath() ? "true" : void 0)));
set_attribute2(button_1, "draggable", onReorderBoards() !== void 0);
});
event("click", button_1, () => handleTabClick(get(tab)));
event("dragstart", button_1, (event2) => handleTabDragStart(get(tab), event2));
event("dragend", button_1, clearDragState);
event("dragover", button_1, (event2) => handleTabDragOver(get(tab).path, event2));
event("dragleave", button_1, () => {
var _a5;
if (((_a5 = get(dropTarget)) == null ? void 0 : _a5.path) === get(tab).path) {
set(dropTarget, null);
}
});
event("drop", button_1, (event2) => handleTabDrop(get(tab).path, event2));
append($$anchor2, button_1);
});
reset(div);
var node_3 = sibling(div, 2);
{
var consequent_2 = ($$anchor2) => {
var div_1 = root_412();
event("pointerdown", div_1, handleResizeStart);
event("pointermove", div_1, handleResizeMove);
event("pointerup", div_1, handleResizeEnd);
event("pointercancel", div_1, handleResizeEnd);
append($$anchor2, div_1);
};
if_block(node_3, ($$render) => {
if (dock() === "left") $$render(consequent_2);
});
}
reset(nav);
template_effect(() => {
classes = set_class(nav, 1, "board-rail svelte-59wfna", null, classes, { "top-dock": dock() === "top" });
set_style(nav, dock() === "left" ? `width: ${get(displayWidth)}px` : void 0);
classes_1 = set_class(button, 1, "rail-dashboard-toggle svelte-59wfna", null, classes_1, { active: dashboardOpen() });
set_attribute2(button, "aria-expanded", dashboardOpen());
set_attribute2(button, "aria-label", dashboardOpen() ? "Hide board dashboard" : "Show board dashboard");
});
event("click", button, function(...$$args) {
var _a5;
(_a5 = onToggleDashboard()) == null ? void 0 : _a5.apply(this, $$args);
});
append($$anchor, nav);
var $$pop = pop($$exports);
$$cleanup();
return $$pop;
}
// src/ui/main.svelte
var import_obsidian11 = require("obsidian");
// src/ui/commands/board_command_targets.ts
function getVisibleSelectedTaskIds(matrix, selectionMap, dashboardOpen) {
var _a5;
if (dashboardOpen) {
return [];
}
const selected = /* @__PURE__ */ new Set();
for (const [id, isSelected] of selectionMap) {
if (isSelected) {
selected.add(id);
}
}
if (selected.size === 0) {
return [];
}
const output = [];
for (const primary of matrix.primaryAxis) {
for (const secondary of matrix.secondaryAxis) {
const cell = (_a5 = matrix.cells[primary.id]) == null ? void 0 : _a5[secondary.id];
if (!cell) continue;
for (const task of cell.tasks) {
if (selected.has(task.id)) {
output.push(task.id);
}
}
}
}
return output;
}
// src/ui/main.svelte
var root23 = from_html(`<div class="view-editor-popover svelte-16qe0yp"><!></div>`);
var root_126 = from_html(`<button class="filter-bar-clear svelte-16qe0yp" aria-label="Clear filter">\xD7</button>`);
var root_216 = from_html(`<div class="main svelte-16qe0yp"><div><!> <div class="board-body svelte-16qe0yp"><div><div class="view-control svelte-16qe0yp"><button type="button"><!> <span>View</span> <span class="view-editor-chevron svelte-16qe0yp"><!></span></button> <!></div> <div class="filter-bar-container svelte-16qe0yp"><div class="filter-bar svelte-16qe0yp"><!> <input type="text" class="filter-bar-input svelte-16qe0yp" aria-label="Filter tasks (press Enter to apply)" spellcheck="false"/> <!> <button class="filter-bar-expand svelte-16qe0yp"><!></button></div> <!> <!></div> <div class="settings-control svelte-16qe0yp"><!></div></div> <!> <!> <div class="board-main svelte-16qe0yp"><div><!></div></div> <!></div></div></div>`);
var $$css23 = {
hash: "svelte-16qe0yp",
code: ".main.svelte-16qe0yp {--view-toolbar-control-height: 42px;height:100%;display:flex;flex-direction:column;font-size:var(--font-text-size);}.main.svelte-16qe0yp .board-toolbar.dashboard-open:where(.svelte-16qe0yp) .view-control:where(.svelte-16qe0yp),\n.main.svelte-16qe0yp .board-toolbar.dashboard-open:where(.svelte-16qe0yp) .filter-bar-container:where(.svelte-16qe0yp),\n.main.svelte-16qe0yp .board-toolbar.dashboard-open:where(.svelte-16qe0yp) .settings-control:where(.svelte-16qe0yp) {opacity:0.5;}.main.svelte-16qe0yp .board-toolbar:where(.svelte-16qe0yp) {position:relative;z-index:120;display:flex;align-items:center;justify-content:center;gap:var(--size-2-2);width:100%;max-width:min(1120px, 100% - var(--size-4-8));margin:0 auto var(--size-4-2) auto;line-height:1;}.main.svelte-16qe0yp .filter-bar-container:where(.svelte-16qe0yp) {position:relative;z-index:100;flex:1 1 auto;min-width:0;width:auto;max-width:none;margin:0;}.main.svelte-16qe0yp .view-control:where(.svelte-16qe0yp),\n.main.svelte-16qe0yp .settings-control:where(.svelte-16qe0yp) {position:relative;display:flex;align-items:center;justify-content:center;flex:0 0 auto;height:var(--view-toolbar-control-height);box-sizing:border-box;}.main.svelte-16qe0yp .settings-control:where(.svelte-16qe0yp) .clickable-icon {display:inline-flex;align-items:center;justify-content:center;width:var(--view-toolbar-control-height);height:var(--view-toolbar-control-height);box-sizing:border-box;margin:0;border-radius:999px;}.main.svelte-16qe0yp .view-editor-toggle:where(.svelte-16qe0yp) {display:inline-flex;align-items:center;justify-content:center;gap:var(--size-2-2);height:var(--view-toolbar-control-height);min-height:0;box-sizing:border-box;margin:0;padding:0 var(--size-4-3);border:var(--input-border-width, 1px) solid var(--background-modifier-border);border-radius:999px;background:var(--background-primary);box-shadow:var(--shadow-s);color:var(--text-normal);font-size:var(--font-ui-small);font-weight:600;line-height:1;cursor:pointer;}.main.svelte-16qe0yp .view-editor-toggle:where(.svelte-16qe0yp):hover {background:var(--background-modifier-hover);}.main.svelte-16qe0yp .view-editor-toggle.active:where(.svelte-16qe0yp) {background:var(--background-primary);border-color:color-mix(in srgb, var(--interactive-accent) 24%, transparent);box-shadow:0 0 0 2px color-mix(in srgb, var(--interactive-accent) 18%, transparent);}.main.svelte-16qe0yp .view-editor-toggle:where(.svelte-16qe0yp) .view-editor-chevron:where(.svelte-16qe0yp) {display:inline-flex;align-items:center;color:var(--text-muted);}.main.svelte-16qe0yp .view-editor-popover:where(.svelte-16qe0yp) {position:absolute;top:calc(100% + var(--view-editor-popover-gap));left:0;z-index:130;width:max-content;max-width:calc(100vw - var(--size-4-8));max-height:min(680px, 100vh - 120px);overflow:auto;}.main.svelte-16qe0yp .filter-bar:where(.svelte-16qe0yp) {display:flex;align-items:center;gap:var(--size-2-3);height:var(--view-toolbar-control-height);min-height:0;box-sizing:border-box;padding:0 var(--size-2-3) 0 var(--size-4-3);background:var(--background-primary);border:var(--input-border-width, 1px) solid var(--background-modifier-border);border-radius:999px;box-shadow:var(--shadow-s);}.main.svelte-16qe0yp .filter-bar:where(.svelte-16qe0yp):focus-within {box-shadow:0 0 0 2px var(--background-modifier-border-focus);}.main.svelte-16qe0yp .filter-bar:where(.svelte-16qe0yp) input.filter-bar-input:where(.svelte-16qe0yp) {flex:1 1 auto;min-width:0;height:100%;background:transparent;border:none;box-shadow:none;margin:0;padding:0;font-size:var(--font-ui-medium);line-height:1;}.main.svelte-16qe0yp .filter-bar:where(.svelte-16qe0yp) input.filter-bar-input:where(.svelte-16qe0yp):focus, .main.svelte-16qe0yp .filter-bar:where(.svelte-16qe0yp) input.filter-bar-input:where(.svelte-16qe0yp):focus-visible {border:none;box-shadow:none;outline:none;}.main.svelte-16qe0yp .filter-bar:where(.svelte-16qe0yp) .filter-bar-clear:where(.svelte-16qe0yp),\n.main.svelte-16qe0yp .filter-bar:where(.svelte-16qe0yp) .filter-bar-expand:where(.svelte-16qe0yp) {display:inline-flex;align-items:center;justify-content:center;flex:0 0 auto;width:30px;height:30px;margin:0;padding:0;background:transparent;border:none;box-shadow:none;cursor:pointer;color:var(--text-muted);font-size:18px;line-height:1;}.main.svelte-16qe0yp .filter-bar:where(.svelte-16qe0yp) .filter-bar-clear:where(.svelte-16qe0yp):hover,\n.main.svelte-16qe0yp .filter-bar:where(.svelte-16qe0yp) .filter-bar-expand:where(.svelte-16qe0yp):hover {color:var(--text-normal);}.main.svelte-16qe0yp .filter-bar:where(.svelte-16qe0yp) .filter-bar-expand:where(.svelte-16qe0yp) {border-radius:999px;}.main.svelte-16qe0yp .filter-bar:where(.svelte-16qe0yp) .filter-bar-expand:where(.svelte-16qe0yp):hover {background:var(--background-modifier-hover);}.main.svelte-16qe0yp .board-content:where(.svelte-16qe0yp) {--view-editor-popover-gap: 8px;display:flex;flex-direction:row;height:100%;overflow:visible;background:color-mix(in srgb, var(--background-primary) 92%, var(--background-secondary));}.main.svelte-16qe0yp .board-content.rail-top:where(.svelte-16qe0yp) {flex-direction:column;}.main.svelte-16qe0yp .board-body:where(.svelte-16qe0yp) {position:relative;display:flex;flex-direction:column;flex:1 1 0;min-width:0;min-height:0;overflow:visible;padding:var(--size-4-2) var(--size-4-4) 0 var(--size-4-4);}\n@media (max-width: 760px) {.main.svelte-16qe0yp .board-toolbar:where(.svelte-16qe0yp) {flex-wrap:wrap;justify-content:flex-start;}.main.svelte-16qe0yp .filter-bar-container:where(.svelte-16qe0yp) {flex-basis:100%;width:100%;max-width:100%;}.main.svelte-16qe0yp .settings-control:where(.svelte-16qe0yp) {margin-left:auto;}.main.svelte-16qe0yp .view-editor-popover:where(.svelte-16qe0yp) {width:calc(100vw - var(--size-4-8));}\n}.main.svelte-16qe0yp .board-main:where(.svelte-16qe0yp) {position:relative;display:flex;flex-direction:column;flex:1 1 0;min-width:0;min-height:0;}.main.svelte-16qe0yp .columns:where(.svelte-16qe0yp) {flex:1 1 0;width:100%;min-width:0;min-height:0;max-width:100%;box-sizing:border-box;overflow-x:scroll;overflow-y:auto;padding-bottom:var(--size-4-4);}.main.svelte-16qe0yp .columns.vertical-flow:where(.svelte-16qe0yp) {overflow-x:auto;overflow-y:scroll;}"
};
function Main($$anchor, $$props) {
if (new.target) return createClassComponent({ component: Main, ...$$anchor });
push($$props, false);
append_styles($$anchor, $$css23);
const $boardIndexStore = () => store_get(boardIndexStore(), "$boardIndexStore", $$stores);
const $boardRailSettingsStore = () => store_get(boardRailSettingsStore(), "$boardRailSettingsStore", $$stores);
const $taskSelectionStore = () => store_get(taskSelectionStore, "$taskSelectionStore", $$stores);
const $dashboardOpenStore = () => store_get(dashboardOpenStore(), "$dashboardOpenStore", $$stores);
const $currentPathStore = () => store_get(currentPathStore(), "$currentPathStore", $$stores);
const $collapsedColumnsStore = () => store_get(collapsedColumnsStore, "$collapsedColumnsStore", $$stores);
const $tasksStore = () => store_get(tasksStore(), "$tasksStore", $$stores);
const $settingsStore = () => store_get(settingsStore(), "$settingsStore", $$stores);
const $globalViewsStore = () => store_get(globalViewsStore(), "$globalViewsStore", $$stores);
const $todayStore = () => store_get(todayStore, "$todayStore", $$stores);
const [$$stores, $$cleanup] = setup_stores();
const railVisible2 = mutable_source();
const railWidth = mutable_source();
const railDock = mutable_source();
const railOnTop = mutable_source();
const tags = mutable_source();
const availableTags = mutable_source();
const dateFilterKeys = mutable_source();
const dateFilterKeyNames = mutable_source();
const draftQuery = mutable_source();
const appliedQuery = mutable_source();
const isFiltered = mutable_source();
const savedViews = mutable_source();
const globalSavedViews = mutable_source();
const mergedSavedViews = mutable_source();
const currentSavedViewProperties = mutable_source();
const canSaveCurrentView = mutable_source();
const taskFilePaths = mutable_source();
const suggestionContext = mutable_source();
const savedFilterEntries = mutable_source();
const filteredTasks = mutable_source();
const tasksByColumn = mutable_source();
const totalTaskCount = mutable_source();
const filteredTaskCount = mutable_source();
const boardTaskCountLabel = mutable_source();
const showFilepath = mutable_source();
const consolidateTags = mutable_source();
const uncategorizedVisibility = mutable_source();
const doneVisibility = mutable_source();
const columnWidth = mutable_source();
const flowDirection = mutable_source();
const uncategorizedColumnName = mutable_source();
const doneColumnName = mutable_source();
const propertyDisplay = mutable_source();
const treatNestedTasksAsSubtasks = mutable_source();
const targetFileIsDefault = mutable_source();
const showUncategorizedColumn = mutable_source();
const showDoneColumn = mutable_source();
const orderedColumns = mutable_source();
const isVerticalFlow = mutable_source();
const activeMatrix = mutable_source();
const activeSchema = mutable_source();
const propertySchemaOption = mutable_source();
const availableSortKeys = mutable_source();
const availableGroupKeys = mutable_source();
const orderMode = mutable_source();
const isTaskNameSort = mutable_source();
const isPropertySort = mutable_source();
const isDirectionalSort = mutable_source();
const isManualOrder = mutable_source();
const sortSelectValue = mutable_source();
const groupSelectValue = mutable_source();
const isDirectionalGroup = mutable_source();
const isTagPrefixGrouping = mutable_source();
const tagGroupPrefix = mutable_source();
const tagGroupIncludeTags = mutable_source();
const manualOrder = mutable_source();
const reorderEnabled = mutable_source();
const propertyGroupSource = mutable_source();
const showCollapsePastDatesToggle = mutable_source();
let app = prop($$props, "app", 12);
let tasksStore = prop($$props, "tasksStore", 12);
let taskActions = prop($$props, "taskActions", 12);
let openSettings = prop($$props, "openSettings", 12);
let columnTagTableStore = prop($$props, "columnTagTableStore", 12);
let columnColourTableStore = prop($$props, "columnColourTableStore", 12);
let columnMatchTagTableStore = prop($$props, "columnMatchTagTableStore", 12);
let columnSubtitleTableStore = prop($$props, "columnSubtitleTableStore", 12);
let settingsStore = prop($$props, "settingsStore", 12);
let globalViewsStore = prop($$props, "globalViewsStore", 28, () => readable([]));
let boardIndexStore = prop($$props, "boardIndexStore", 28, () => readable([]));
let boardListSettingsStore = prop($$props, "boardListSettingsStore", 28, () => readable(void 0));
let currentPathStore = prop($$props, "currentPathStore", 28, () => readable(null));
let dashboardOpenStore = prop($$props, "dashboardOpenStore", 28, () => writable(false));
let openBoard = prop($$props, "openBoard", 12, () => void 0);
let onSetBoardHidden = prop($$props, "onSetBoardHidden", 12, void 0);
let onReorderBoards = prop($$props, "onReorderBoards", 12, void 0);
let boardCountsStore = prop($$props, "boardCountsStore", 28, () => readable(/* @__PURE__ */ new Map()));
let onRequestBoardCounts = prop($$props, "onRequestBoardCounts", 12, void 0);
let lastOpenedStore = prop($$props, "lastOpenedStore", 28, () => readable({}));
let boardRailSettingsStore = prop($$props, "boardRailSettingsStore", 28, () => readable(void 0));
let onSetRailWidth = prop($$props, "onSetRailWidth", 12, void 0);
let onCreateBoard = prop($$props, "onCreateBoard", 12, void 0);
let onDeleteBoard = prop($$props, "onDeleteBoard", 12, void 0);
let requestSave = prop($$props, "requestSave", 12);
let railDashboardButtonEl = mutable_source();
let dashboardWasOpen = mutable_source(false);
async function openCurrentBoardSettings() {
dashboardOpenStore().set(false);
set(viewEditorExpanded, false);
set(filterEditorExpanded, false);
await tick();
await openSettings()();
return true;
}
function getSelectedCommandTaskIds() {
return getVisibleSelectedTaskIds(get(activeMatrix), $taskSelectionStore(), $dashboardOpenStore());
}
function hasVisibleSelectedCards() {
return getSelectedCommandTaskIds().length > 0;
}
async function runSelectedCardsAction(action2) {
const ids = getSelectedCommandTaskIds();
if (ids.length === 0) {
return false;
}
await action2(ids);
clearTaskIdSelections(ids);
return true;
}
async function markSelectedCardsDone() {
return runSelectedCardsAction((ids) => taskActions().moveTasksToColumn(ids, "done"));
}
async function archiveSelectedCards() {
return runSelectedCardsAction((ids) => taskActions().archiveTasks(ids));
}
async function cancelSelectedCards() {
return runSelectedCardsAction((ids) => taskActions().cancelTasks(ids));
}
async function duplicateSelectedCards() {
const ids = getSelectedCommandTaskIds();
const completed = [];
for (const id of ids) {
try {
await taskActions().duplicateTask(id);
completed.push(id);
} catch (error) {
console.error("Failed to duplicate selected card", error);
new import_obsidian11.Notice("Failed to duplicate one selected card.");
}
}
if (completed.length > 0) {
clearTaskIdSelections(completed);
}
return completed.length > 0;
}
async function deleteSelectedCards(ids) {
const completed = [];
for (const id of ids) {
try {
await taskActions().deleteTask(id);
completed.push(id);
} catch (error) {
console.error("Failed to delete selected card", error);
new import_obsidian11.Notice("Failed to delete one selected card.");
}
}
if (completed.length > 0) {
clearTaskIdSelections(completed);
}
return completed.length > 0;
}
async function deleteSelectedCardsCommand() {
const ids = getSelectedCommandTaskIds();
if (ids.length === 0) {
return false;
}
if (ids.length === 1) {
return deleteSelectedCards(ids);
}
new ConfirmModal(app(), {
title: "Delete selected cards?",
body: `Delete ${ids.length} selected cards from their source files.`,
note: "This removes each selected card's owned source block.",
confirmText: "Delete cards",
onConfirm: async () => {
await deleteSelectedCards(ids);
}
}).open();
return true;
}
function toggleDashboard() {
dashboardOpenStore().update((open) => !open);
}
function handleDashboardSelect(path) {
if (shouldSwitchBoard(path, $currentPathStore())) {
openBoard()(path);
}
dashboardOpenStore().set(false);
}
function getDashboardBoardStat(path) {
const file = app().vault.getAbstractFileByPath(path);
return file instanceof import_obsidian11.TFile ? { mtime: file.stat.mtime } : null;
}
const collapsedColumnsStore = createCollapsedColumnsStore(settingsStore());
const todayStore = createTodayStore();
function toggleColumnCollapse(col) {
const isCurrentlyCollapsed = $collapsedColumnsStore().has(col);
settingsStore().update((s) => {
var _a5;
const collapsed = (_a5 = s.collapsedColumns) != null ? _a5 : [];
const tag2 = col;
return {
...s,
collapsedColumns: isCurrentlyCollapsed ? collapsed.filter((c) => c !== tag2) : [...collapsed, tag2]
};
});
requestSave()();
}
let tagGroupInputMode = mutable_source("prefix");
function tagGroupInputModeForSource(source2) {
var _a5, _b3;
return (source2 == null ? void 0 : source2.kind) === "tag-prefix" && ((_b3 = (_a5 = source2.includeTags) == null ? void 0 : _a5.length) != null ? _b3 : 0) > 0 ? "include" : "prefix";
}
function updateTagGroupPrefix(prefix) {
const src = $settingsStore().groupSource;
if (!src || src.kind !== "tag-prefix") return;
store_mutate(settingsStore(), untrack($settingsStore).groupSource = { kind: "tag-prefix", prefix }, untrack($settingsStore));
requestSave()();
}
function updateTagGroupIncludeTags(includeTags) {
const src = $settingsStore().groupSource;
if (!src || src.kind !== "tag-prefix") return;
store_mutate(
settingsStore(),
untrack($settingsStore).groupSource = {
kind: "tag-prefix",
prefix: "",
includeTags: normalizeTagIncludeList(includeTags)
},
untrack($settingsStore)
);
requestSave()();
}
function setTagGroupInputMode(mode) {
var _a5, _b3;
const src = $settingsStore().groupSource;
if (!src || src.kind !== "tag-prefix" || get(tagGroupInputMode) === mode) return;
set(tagGroupInputMode, mode);
store_mutate(
settingsStore(),
untrack($settingsStore).groupSource = mode === "prefix" ? { kind: "tag-prefix", prefix: (_a5 = src.prefix) != null ? _a5 : "" } : {
kind: "tag-prefix",
prefix: "",
includeTags: (_b3 = src.includeTags) != null ? _b3 : []
},
untrack($settingsStore)
);
requestSave()();
}
function groupByColumnTag(tasks) {
var _a5;
const output = { uncategorised: [], done: [] };
for (const task of tasks) {
if (task.done || task.column === "done") {
output["done"] = output["done"].concat(task);
} else if (task.column === "archived") {
} else if (task.column) {
output[task.column] = ((_a5 = output[task.column]) != null ? _a5 : []).concat(task);
} else {
output["uncategorised"] = output["uncategorised"].concat(task);
}
}
return output;
}
let columns = mutable_source();
let filterQueryText = mutable_source("");
let appliedQueryText = mutable_source("");
let hydrated = mutable_source(false);
let lastPersistedQuery = "";
onMount(() => {
set(tagGroupInputMode, tagGroupInputModeForSource($settingsStore().groupSource));
const unsubscribe = settingsStore().subscribe((settings) => {
const incomingQuery = readBoardFilterState(settings);
if (shouldApplyIncomingBoardFilterState(get(filterQueryText), incomingQuery, lastPersistedQuery, get(hydrated))) {
set(filterQueryText, incomingQuery);
set(appliedQueryText, incomingQuery);
lastPersistedQuery = incomingQuery;
set(hydrated, true);
}
});
return unsubscribe;
});
function saveFilterState() {
if (!get(hydrated) || get(appliedQueryText) === lastPersistedQuery) {
return;
}
lastPersistedQuery = get(appliedQueryText);
settingsStore().update((settings) => writeBoardFilterState(settings, get(appliedQueryText)));
requestSave()();
}
let filterEditorExpanded = mutable_source(false);
let viewEditorExpanded = mutable_source(false);
let filterBarContainer = mutable_source();
let viewControlContainer = mutable_source();
let boardContentEl = mutable_source();
let viewEditorPopover = mutable_source();
let viewEditorPopoverStyle = mutable_source("");
const VIEW_EDITOR_POPOVER_GAP = 8;
const VIEW_EDITOR_POPOVER_MARGIN = 12;
function toggleViewEditor() {
set(viewEditorExpanded, !get(viewEditorExpanded));
}
function updateViewEditorPopoverPosition() {
if (!get(viewEditorExpanded) || !get(boardContentEl) || !get(viewControlContainer) || !get(viewEditorPopover)) {
return;
}
const boardRect = get(boardContentEl).getBoundingClientRect();
const triggerRect = get(viewControlContainer).getBoundingClientRect();
const popoverRect = get(viewEditorPopover).getBoundingClientRect();
const margin = VIEW_EDITOR_POPOVER_MARGIN;
const gap = VIEW_EDITOR_POPOVER_GAP;
const maxWidth = Math.max(240, boardRect.width - margin * 2);
const popoverWidth = Math.min(popoverRect.width || maxWidth, maxWidth);
const minLeft = boardRect.left + margin;
const maxLeft = boardRect.right - margin - popoverWidth;
const left = Math.max(minLeft, Math.min(triggerRect.left, maxLeft));
const availableBelow = boardRect.bottom - triggerRect.bottom - gap - margin;
const maxHeight = Math.max(160, availableBelow);
set(viewEditorPopoverStyle, [
`left: ${Math.round(left - triggerRect.left)}px`,
`max-width: ${Math.round(maxWidth)}px`,
`max-height: ${Math.round(maxHeight)}px`
].join("; "));
}
function applyFilter() {
const canonical = serializeFilterQuery(parseFilterQuery(get(filterQueryText), get(dateFilterKeyNames)));
set(filterQueryText, canonical);
set(appliedQueryText, canonical);
hideBarSuggestions();
}
function clearFilter() {
set(filterQueryText, "");
set(appliedQueryText, "");
hideBarSuggestions();
}
let filterInputEl = mutable_source();
let barSuggestions = mutable_source([]);
let barSuggestionIndex = mutable_source(-1);
let barSuggestionsVisible = mutable_source(false);
function refreshBarSuggestions() {
var _a5, _b3;
const caret = (_b3 = (_a5 = get(filterInputEl)) == null ? void 0 : _a5.selectionStart) != null ? _b3 : get(filterQueryText).length;
set(barSuggestions, getFilterSuggestions(get(filterQueryText), caret, get(suggestionContext)));
set(barSuggestionIndex, -1);
set(barSuggestionsVisible, get(barSuggestions).length > 0);
}
function hideBarSuggestions() {
set(barSuggestionsVisible, false);
set(barSuggestionIndex, -1);
}
async function acceptBarSuggestion(suggestion) {
var _a5, _b3, _c2, _d;
if (suggestion.kind === "saved") {
const entry = get(savedFilterEntries).find((candidate) => candidate.name === suggestion.label);
if (entry) {
applySavedFilter(entry);
await tick();
(_a5 = get(filterInputEl)) == null ? void 0 : _a5.focus();
(_b3 = get(filterInputEl)) == null ? void 0 : _b3.setSelectionRange(get(filterQueryText).length, get(filterQueryText).length);
return;
}
}
const applied = applyFilterSuggestion(get(filterQueryText), suggestion);
set(filterQueryText, applied.text);
await tick();
(_c2 = get(filterInputEl)) == null ? void 0 : _c2.focus();
(_d = get(filterInputEl)) == null ? void 0 : _d.setSelectionRange(applied.caret, applied.caret);
if (suggestion.kind === "prefix") {
refreshBarSuggestions();
} else {
hideBarSuggestions();
}
}
function handleFilterInputKeydown(e) {
if (get(barSuggestionsVisible) && get(barSuggestions).length > 0) {
if (e.key === "ArrowDown" || e.key === "ArrowUp") {
e.preventDefault();
set(barSuggestionIndex, stepSuggestionIndex(get(barSuggestions).length, get(barSuggestionIndex), e.key === "ArrowDown" ? 1 : -1));
return;
}
if (e.key === "Tab") {
e.preventDefault();
acceptBarSuggestion(get(barSuggestions)[Math.max(get(barSuggestionIndex), 0)]);
return;
}
if (e.key === "Enter" && get(barSuggestionIndex) >= 0) {
e.preventDefault();
acceptBarSuggestion(get(barSuggestions)[get(barSuggestionIndex)]);
return;
}
if (e.key === "Escape") {
e.stopPropagation();
hideBarSuggestions();
return;
}
}
if (e.key === "Enter") {
hideBarSuggestions();
applyFilter();
}
}
function handleFilterInputClick() {
if (get(barSuggestionsVisible)) {
refreshBarSuggestions();
}
}
function applyEditorQuery(next2) {
set(filterQueryText, serializeFilterQuery(next2));
}
function searchFromEditor() {
applyFilter();
set(filterEditorExpanded, false);
}
function applySavedFilter(entry) {
set(filterQueryText, entry.query);
applyFilter();
}
function saveCurrentFilter(name) {
const query = serializeFilterQuery(get(draftQuery));
if (query === "") {
return;
}
store_mutate(
settingsStore(),
untrack($settingsStore).savedViews = [
...get(savedViews),
{ id: crypto.randomUUID(), name: name != null ? name : query, query }
],
untrack($settingsStore)
);
requestSave()();
}
let savedFilterPendingDelete = mutable_source();
let savedViewPendingDelete = mutable_source();
let savedFilterListExpanded = mutable_source(false);
let savedViewListExpanded = mutable_source(false);
function confirmDeleteSavedFilter() {
const pending2 = get(savedFilterPendingDelete);
set(savedFilterPendingDelete, void 0);
if (!pending2 || pending2.isGlobal) {
return;
}
const localId = pending2.id.startsWith("local:") ? pending2.id.slice("local:".length) : pending2.id;
store_mutate(settingsStore(), untrack($settingsStore).savedViews = get(savedViews).filter((view) => view.id !== localId), untrack($settingsStore));
requestSave()();
}
function saveCurrentView(name) {
const properties = get(currentSavedViewProperties);
if (!savedViewHasProperties(properties)) {
return;
}
store_mutate(
settingsStore(),
untrack($settingsStore).savedViews = [
...get(savedViews),
{
id: crypto.randomUUID(),
name: (name == null ? void 0 : name.trim()) || defaultSavedViewName(properties),
...properties
}
],
untrack($settingsStore)
);
requestSave()();
}
function applySavedView(view) {
var _a5;
if (view.query !== void 0) {
set(filterQueryText, view.query);
set(appliedQueryText, view.query);
lastPersistedQuery = view.query;
}
settingsStore().update((settings) => {
const next2 = applySavedViewProperties(settings, view);
return view.query !== void 0 ? writeBoardFilterState(next2, view.query) : next2;
});
if (((_a5 = view.group) == null ? void 0 : _a5.source.kind) === "tag-prefix") {
set(tagGroupInputMode, tagGroupInputModeForSource(view.group.source));
}
hideBarSuggestions();
requestSave()();
}
function confirmDeleteSavedView() {
const pending2 = get(savedViewPendingDelete);
set(savedViewPendingDelete, void 0);
if (!pending2 || pending2.isGlobal) {
return;
}
store_mutate(settingsStore(), untrack($settingsStore).savedViews = get(savedViews).filter((view) => view.id !== pending2.id), untrack($settingsStore));
requestSave()();
}
function handleWindowKeydown(e) {
if (get(savedFilterPendingDelete) || get(savedViewPendingDelete)) {
return;
}
if (e.key === "Escape" && get(filterEditorExpanded)) {
set(filterEditorExpanded, false);
return;
}
if (e.key === "Escape" && get(viewEditorExpanded)) {
set(viewEditorExpanded, false);
}
}
function handleWindowMousedown(e) {
if (get(savedFilterPendingDelete) || get(savedViewPendingDelete)) {
return;
}
if (get(filterEditorExpanded) && get(filterBarContainer) && e.target instanceof Node && !get(filterBarContainer).contains(e.target)) {
set(filterEditorExpanded, false);
}
if (get(viewEditorExpanded) && get(viewControlContainer) && e.target instanceof Node && !get(viewControlContainer).contains(e.target)) {
set(viewEditorExpanded, false);
}
}
function handleWindowViewportChange() {
updateViewEditorPopoverPosition();
}
let targetTaskFile = mutable_source(null);
function onSortChange(value) {
const selection = sortSelectionFromValue(value);
store_mutate(settingsStore(), untrack($settingsStore).columnOrderMode = selection.mode, untrack($settingsStore));
if (selection.property !== void 0) {
store_mutate(settingsStore(), untrack($settingsStore).sortProperty = selection.property, untrack($settingsStore));
}
requestSave()();
}
function onGroupChange(value) {
var _a5, _b3;
const groupProperty = propertyKeyFromOptionValue(value);
if (value === "file") {
store_mutate(settingsStore(), untrack($settingsStore).groupSource = { kind: "file" }, untrack($settingsStore));
} else if (value === "tag-prefix") {
const nextGroupSource = ((_a5 = $settingsStore().groupSource) == null ? void 0 : _a5.kind) === "tag-prefix" ? {
kind: "tag-prefix",
prefix: $settingsStore().groupSource.prefix,
includeTags: $settingsStore().groupSource.includeTags
} : { kind: "tag-prefix", prefix: "" };
store_mutate(settingsStore(), untrack($settingsStore).groupSource = nextGroupSource, untrack($settingsStore));
set(tagGroupInputMode, tagGroupInputModeForSource(nextGroupSource));
} else if (groupProperty !== void 0) {
store_mutate(
settingsStore(),
untrack($settingsStore).groupSource = {
kind: "property",
key: groupProperty,
collapsePastDates: ((_b3 = $settingsStore().groupSource) == null ? void 0 : _b3.kind) === "property" ? $settingsStore().groupSource.collapsePastDates : void 0
},
untrack($settingsStore)
);
} else {
store_mutate(settingsStore(), untrack($settingsStore).groupSource = { kind: "none" }, untrack($settingsStore));
}
requestSave()();
}
let pruneTimer;
function schedulePrune() {
if (pruneTimer) {
clearTimeout(pruneTimer);
}
pruneTimer = setTimeout(
() => {
var _a5, _b3, _c2, _d, _e, _f;
pruneTimer = void 0;
const groupSource = (_a5 = $settingsStore().groupSource) != null ? _a5 : { kind: "none" };
const groupBuckets = deriveGroupBuckets($tasksStore(), groupSource, (_b3 = $settingsStore().excludedTags) != null ? _b3 : [], (_c2 = $settingsStore().statusMarkerOrder) != null ? _c2 : "", (_d = $settingsStore().doneStatusMarkers) != null ? _d : "", (_e = $settingsStore().groupDirection) != null ? _e : "asc", $todayStore());
const assignGroupId = createGroupAssigner(groupBuckets, groupSource, (_f = $settingsStore().excludedTags) != null ? _f : [], $todayStore());
taskActions().pruneManualOrder(collectPresentManualOrderKeys($tasksStore(), assignGroupId));
},
500
);
}
onDestroy(() => {
if (pruneTimer) {
clearTimeout(pruneTimer);
}
});
function toggleSortDirection() {
var _a5;
store_mutate(settingsStore(), untrack($settingsStore).sortDirection = ((_a5 = $settingsStore().sortDirection) != null ? _a5 : "asc") === "asc" ? "desc" : "asc", untrack($settingsStore));
requestSave()();
}
function toggleGroupDirection() {
var _a5;
store_mutate(settingsStore(), untrack($settingsStore).groupDirection = ((_a5 = $settingsStore().groupDirection) != null ? _a5 : "asc") === "asc" ? "desc" : "asc", untrack($settingsStore));
requestSave()();
}
function setCollapsePastDates(collapse) {
const src = $settingsStore().groupSource;
if ((src == null ? void 0 : src.kind) !== "property") return;
store_mutate(settingsStore(), untrack($settingsStore).groupSource = { ...src, collapsePastDates: collapse || void 0 }, untrack($settingsStore));
requestSave()();
}
function setFlowDirection(value) {
store_mutate(settingsStore(), untrack($settingsStore).flowDirection = value, untrack($settingsStore));
requestSave()();
}
function setColumnWidth(value) {
const clamped = Math.min(600, Math.max(200, Math.round(value / 10) * 10));
store_mutate(settingsStore(), untrack($settingsStore).columnWidth = clamped, untrack($settingsStore));
requestSave()();
}
async function handleOpenSettings() {
openSettings()();
}
legacy_pre_effect(() => (railVisible, $boardIndexStore()), () => {
set(railVisible2, railVisible($boardIndexStore().length));
});
legacy_pre_effect(() => ($boardRailSettingsStore(), RAIL_MIN_WIDTH), () => {
var _a5, _b3;
set(railWidth, (_b3 = (_a5 = $boardRailSettingsStore()) == null ? void 0 : _a5.width) != null ? _b3 : RAIL_MIN_WIDTH);
});
legacy_pre_effect(() => $boardRailSettingsStore(), () => {
var _a5, _b3;
set(railDock, (_b3 = (_a5 = $boardRailSettingsStore()) == null ? void 0 : _a5.dock) != null ? _b3 : "left");
});
legacy_pre_effect(() => (get(railVisible2), get(railDock)), () => {
set(railOnTop, get(railVisible2) && get(railDock) === "top");
});
legacy_pre_effect(
() => (get(dashboardWasOpen), $dashboardOpenStore(), get(railDashboardButtonEl)),
() => {
var _a5;
if (get(dashboardWasOpen) && !$dashboardOpenStore()) {
(_a5 = get(railDashboardButtonEl)) == null ? void 0 : _a5.focus();
} else if (!get(dashboardWasOpen) && $dashboardOpenStore()) {
set(viewEditorExpanded, false);
set(filterEditorExpanded, false);
}
set(dashboardWasOpen, $dashboardOpenStore());
}
);
legacy_pre_effect(() => $tasksStore(), () => {
set(tags, $tasksStore().reduce(
(acc, curr) => {
for (const tag2 of curr.tags) {
acc.add(tag2);
}
return acc;
},
/* @__PURE__ */ new Set()
));
});
legacy_pre_effect(() => get(tags), () => {
set(availableTags, [...get(tags)].sort((a, b) => a.localeCompare(b)));
});
legacy_pre_effect(() => (getSchemaImpl, $settingsStore(), PropertySchemaOption), () => {
var _a5;
set(activeSchema, getSchemaImpl((_a5 = $settingsStore().propertySchema) != null ? _a5 : "none" /* None */));
});
legacy_pre_effect(() => get(activeSchema), () => {
set(dateFilterKeys, get(activeSchema).knownKeys().filter((key2) => key2.type === "date"));
});
legacy_pre_effect(() => $settingsStore(), () => {
set(columns, $settingsStore().columns.map((column) => column.id));
});
legacy_pre_effect(() => (get(hydrated), get(appliedQueryText)), () => {
if (get(hydrated)) {
get(appliedQueryText);
saveFilterState();
}
});
legacy_pre_effect(() => get(dateFilterKeys), () => {
set(dateFilterKeyNames, get(dateFilterKeys).map((key2) => key2.key));
});
legacy_pre_effect(
() => (parseFilterQuery, get(filterQueryText), get(dateFilterKeyNames)),
() => {
set(draftQuery, parseFilterQuery(get(filterQueryText), get(dateFilterKeyNames)));
}
);
legacy_pre_effect(
() => (parseFilterQuery, get(appliedQueryText), get(dateFilterKeyNames)),
() => {
set(appliedQuery, parseFilterQuery(get(appliedQueryText), get(dateFilterKeyNames)));
}
);
legacy_pre_effect(() => (isEmptyFilterQuery, get(appliedQuery)), () => {
set(isFiltered, !isEmptyFilterQuery(get(appliedQuery)));
});
legacy_pre_effect(() => $settingsStore(), () => {
var _a5;
set(savedViews, (_a5 = $settingsStore().savedViews) != null ? _a5 : []);
});
legacy_pre_effect(() => $globalViewsStore(), () => {
var _a5;
set(globalSavedViews, (_a5 = $globalViewsStore()) != null ? _a5 : []);
});
legacy_pre_effect(
() => (mergeLocalAndGlobalSavedViews, get(savedViews), get(globalSavedViews)),
() => {
set(mergedSavedViews, mergeLocalAndGlobalSavedViews(get(savedViews), get(globalSavedViews)));
}
);
legacy_pre_effect(
() => (captureSavedViewProperties, $settingsStore(), deep_read_state(settingsStore())),
() => {
set(currentSavedViewProperties, captureSavedViewProperties($settingsStore(), settingsStore().getOverrides()));
}
);
legacy_pre_effect(() => (savedViewHasProperties, get(currentSavedViewProperties)), () => {
set(canSaveCurrentView, savedViewHasProperties(get(currentSavedViewProperties)));
});
legacy_pre_effect(() => $settingsStore(), () => {
var _a5;
set(isTagPrefixGrouping, ((_a5 = $settingsStore().groupSource) == null ? void 0 : _a5.kind) === "tag-prefix");
});
legacy_pre_effect(() => ($settingsStore(), ColumnOrderMode), () => {
var _a5;
set(orderMode, (_a5 = $settingsStore().columnOrderMode) != null ? _a5 : "file" /* FileOrder */);
});
legacy_pre_effect(() => (sortSelectValueFor, get(orderMode), $settingsStore()), () => {
set(sortSelectValue, sortSelectValueFor(get(orderMode), $settingsStore().sortProperty));
});
legacy_pre_effect(() => ($settingsStore(), propertyOptionValue), () => {
var _a5, _b3, _c2;
set(groupSelectValue, ((_a5 = $settingsStore().groupSource) == null ? void 0 : _a5.kind) === "property" ? propertyOptionValue($settingsStore().groupSource.key) : (_c2 = (_b3 = $settingsStore().groupSource) == null ? void 0 : _b3.kind) != null ? _c2 : "none");
});
legacy_pre_effect(
() => (get(viewEditorExpanded), get(isTagPrefixGrouping), get(savedViewListExpanded), get(sortSelectValue), get(groupSelectValue), tick),
() => {
get(viewEditorExpanded);
get(isTagPrefixGrouping);
get(savedViewListExpanded);
get(sortSelectValue);
get(groupSelectValue);
if (get(viewEditorExpanded)) {
void tick().then(updateViewEditorPopoverPosition);
}
}
);
legacy_pre_effect(() => $tasksStore(), () => {
set(taskFilePaths, [...new Set($tasksStore().map((task) => task.path))].sort((a, b) => a.localeCompare(b)));
});
legacy_pre_effect(() => (get(mergedSavedViews), savedViewIsQueryOnly), () => {
set(savedFilterEntries, get(mergedSavedViews).filter((view) => savedViewIsQueryOnly(view) && view.query !== void 0).map((view) => ({
id: `${view.isGlobal ? "global" : "local"}:${view.id}`,
name: view.name === view.query ? void 0 : view.name,
query: view.query,
isGlobal: view.isGlobal
})));
});
legacy_pre_effect(
() => (get(availableTags), get(taskFilePaths), get(dateFilterKeys), get(savedFilterEntries)),
() => {
set(suggestionContext, {
tags: get(availableTags),
filePaths: get(taskFilePaths),
dateKeys: get(dateFilterKeys),
savedFilterNames: get(savedFilterEntries).map((entry) => entry.name).filter((name) => !!name)
});
}
);
legacy_pre_effect(
() => (get(isFiltered), $tasksStore(), taskMatchesFilterQuery, get(appliedQuery), $todayStore()),
() => {
set(filteredTasks, get(isFiltered) ? $tasksStore().filter((task) => taskMatchesFilterQuery(task, get(appliedQuery), $todayStore())) : $tasksStore());
}
);
legacy_pre_effect(() => get(filteredTasks), () => {
set(tasksByColumn, groupByColumnTag(get(filteredTasks)));
});
legacy_pre_effect(() => (getBoardTaskCount, $tasksStore()), () => {
set(totalTaskCount, getBoardTaskCount($tasksStore()));
});
legacy_pre_effect(() => (getBoardTaskCount, get(filteredTasks)), () => {
set(filteredTaskCount, getBoardTaskCount(get(filteredTasks)));
});
legacy_pre_effect(
() => (get(isFiltered), get(filteredTaskCount), get(totalTaskCount)),
() => {
set(boardTaskCountLabel, get(isFiltered) ? `${get(filteredTaskCount)} of ${get(totalTaskCount)} tasks` : `Total: ${get(totalTaskCount)} tasks`);
}
);
legacy_pre_effect(
() => (get(showFilepath), get(consolidateTags), get(uncategorizedVisibility), VisibilityOption, get(doneVisibility), get(columnWidth), get(flowDirection), FlowDirection, get(uncategorizedColumnName), get(doneColumnName), get(propertyDisplay), PropertyDisplayMode, get(treatNestedTasksAsSubtasks), $settingsStore()),
() => {
(($$value) => {
set(showFilepath, fallback($$value.showFilepath, true));
set(consolidateTags, fallback($$value.consolidateTags, false));
set(uncategorizedVisibility, fallback($$value.uncategorizedVisibility, () => "auto" /* Auto */, true));
set(doneVisibility, fallback($$value.doneVisibility, () => "always" /* AlwaysShow */, true));
set(columnWidth, fallback($$value.columnWidth, 300));
set(flowDirection, fallback($$value.flowDirection, () => "ltr" /* LeftToRight */, true));
set(uncategorizedColumnName, $$value.uncategorizedColumnName);
set(doneColumnName, $$value.doneColumnName);
set(propertyDisplay, fallback($$value.propertyDisplay, () => "none" /* None */, true));
set(treatNestedTasksAsSubtasks, fallback($$value.treatNestedTasksAsSubtasks, false));
})($settingsStore());
}
);
legacy_pre_effect(() => ($settingsStore(), deep_read_state(taskActions())), () => {
void $settingsStore(), set(targetTaskFile, taskActions().getTargetFile());
});
legacy_pre_effect(() => (get(targetTaskFile), $settingsStore()), () => {
set(targetFileIsDefault, !!get(targetTaskFile) && !!$settingsStore().defaultTaskFile && get(targetTaskFile).path === $settingsStore().defaultTaskFile);
});
legacy_pre_effect(
() => (get(uncategorizedVisibility), VisibilityOption, get(tasksByColumn)),
() => {
var _a5;
set(showUncategorizedColumn, get(uncategorizedVisibility) === "always" /* AlwaysShow */ || get(uncategorizedVisibility) === "auto" /* Auto */ && ((_a5 = get(tasksByColumn)["uncategorised"]) == null ? void 0 : _a5.length) > 0);
}
);
legacy_pre_effect(
() => (get(doneVisibility), VisibilityOption, get(tasksByColumn)),
() => {
var _a5;
set(showDoneColumn, get(doneVisibility) === "always" /* AlwaysShow */ || get(doneVisibility) === "auto" /* Auto */ && ((_a5 = get(tasksByColumn)["done"]) == null ? void 0 : _a5.length) > 0);
}
);
legacy_pre_effect(
() => (get(showUncategorizedColumn), get(columns), get(showDoneColumn), get(flowDirection), FlowDirection),
() => {
set(orderedColumns, (() => {
const allColumns = [];
if (get(showUncategorizedColumn)) allColumns.push("uncategorised");
allColumns.push(...get(columns));
if (get(showDoneColumn)) allColumns.push("done");
const shouldReverse = get(flowDirection) === "rtl" /* RightToLeft */ || get(flowDirection) === "btt" /* BottomToTop */;
return shouldReverse ? allColumns.reverse() : allColumns;
})());
}
);
legacy_pre_effect(() => (get(flowDirection), FlowDirection), () => {
set(isVerticalFlow, get(flowDirection) === "ttb" /* TopToBottom */ || get(flowDirection) === "btt" /* BottomToTop */);
});
legacy_pre_effect(
() => (deriveBoardMatrix, get(filteredTasks), $settingsStore(), $collapsedColumnsStore(), $todayStore()),
() => {
set(activeMatrix, deriveBoardMatrix(
get(filteredTasks),
$settingsStore().columns,
{
...$settingsStore(),
collapsedColumns: Array.from($collapsedColumnsStore())
},
$todayStore()
));
}
);
legacy_pre_effect(() => ($settingsStore(), PropertySchemaOption), () => {
var _a5;
set(propertySchemaOption, (_a5 = $settingsStore().propertySchema) != null ? _a5 : "none" /* None */);
});
legacy_pre_effect(
() => (get(activeSchema), $settingsStore(), PropertySchemaOption, $tasksStore()),
() => {
set(availableSortKeys, (() => {
const known = get(activeSchema).knownKeys().map((k) => ({ key: k.key, label: k.label }));
if ($settingsStore().propertySchema !== "dataview" /* Dataview */) {
return known;
}
const seen = new Set(known.map((k) => k.key));
const discovered = [];
for (const task of $tasksStore()) {
for (const key2 of task.properties.keys()) {
if (!seen.has(key2)) {
seen.add(key2);
discovered.push({ key: key2, label: key2 });
}
}
}
return [...known, ...discovered];
})());
}
);
legacy_pre_effect(() => get(availableSortKeys), () => {
set(availableGroupKeys, get(availableSortKeys));
});
legacy_pre_effect(() => (get(orderMode), ColumnOrderMode), () => {
set(isTaskNameSort, get(orderMode) === "task-name" /* TaskName */);
});
legacy_pre_effect(() => (get(orderMode), ColumnOrderMode), () => {
set(isPropertySort, get(orderMode) === "property" /* Property */);
});
legacy_pre_effect(() => (get(isTaskNameSort), get(isPropertySort)), () => {
set(isDirectionalSort, get(isTaskNameSort) || get(isPropertySort));
});
legacy_pre_effect(() => (get(orderMode), ColumnOrderMode), () => {
set(isManualOrder, get(orderMode) === "manual" /* Manual */);
});
legacy_pre_effect(() => $settingsStore(), () => {
var _a5, _b3;
set(isDirectionalGroup, ((_b3 = (_a5 = $settingsStore().groupSource) == null ? void 0 : _a5.kind) != null ? _b3 : "none") !== "none");
});
legacy_pre_effect(() => $settingsStore(), () => {
var _a5, _b3;
set(tagGroupPrefix, ((_a5 = $settingsStore().groupSource) == null ? void 0 : _a5.kind) === "tag-prefix" ? (_b3 = $settingsStore().groupSource.prefix) != null ? _b3 : "" : "");
});
legacy_pre_effect(() => $settingsStore(), () => {
var _a5, _b3;
set(tagGroupIncludeTags, ((_a5 = $settingsStore().groupSource) == null ? void 0 : _a5.kind) === "tag-prefix" ? (_b3 = $settingsStore().groupSource.includeTags) != null ? _b3 : [] : []);
});
legacy_pre_effect(() => $settingsStore(), () => {
var _a5;
set(manualOrder, (_a5 = $settingsStore().manualOrder) != null ? _a5 : {});
});
legacy_pre_effect(() => get(isManualOrder), () => {
set(reorderEnabled, get(isManualOrder));
});
legacy_pre_effect(() => (get(isManualOrder), $tasksStore()), () => {
if (get(isManualOrder) && $tasksStore()) {
schedulePrune();
}
});
legacy_pre_effect(() => $settingsStore(), () => {
var _a5;
set(propertyGroupSource, ((_a5 = $settingsStore().groupSource) == null ? void 0 : _a5.kind) === "property" ? $settingsStore().groupSource : null);
});
legacy_pre_effect(() => (get(propertyGroupSource), get(dateFilterKeys)), () => {
set(showCollapsePastDatesToggle, get(propertyGroupSource) !== null && get(dateFilterKeys).some((key2) => key2.key === get(propertyGroupSource).key));
});
legacy_pre_effect_reset();
var $$exports = {
openCurrentBoardSettings,
hasVisibleSelectedCards,
markSelectedCardsDone,
archiveSelectedCards,
cancelSelectedCards,
duplicateSelectedCards,
deleteSelectedCardsCommand,
get app() {
return app();
},
set app($$value) {
app($$value);
flushSync();
},
get tasksStore() {
return tasksStore();
},
set tasksStore($$value) {
tasksStore($$value);
flushSync();
},
get taskActions() {
return taskActions();
},
set taskActions($$value) {
taskActions($$value);
flushSync();
},
get openSettings() {
return openSettings();
},
set openSettings($$value) {
openSettings($$value);
flushSync();
},
get columnTagTableStore() {
return columnTagTableStore();
},
set columnTagTableStore($$value) {
columnTagTableStore($$value);
flushSync();
},
get columnColourTableStore() {
return columnColourTableStore();
},
set columnColourTableStore($$value) {
columnColourTableStore($$value);
flushSync();
},
get columnMatchTagTableStore() {
return columnMatchTagTableStore();
},
set columnMatchTagTableStore($$value) {
columnMatchTagTableStore($$value);
flushSync();
},
get columnSubtitleTableStore() {
return columnSubtitleTableStore();
},
set columnSubtitleTableStore($$value) {
columnSubtitleTableStore($$value);
flushSync();
},
get settingsStore() {
return settingsStore();
},
set settingsStore($$value) {
settingsStore($$value);
flushSync();
},
get globalViewsStore() {
return globalViewsStore();
},
set globalViewsStore($$value) {
globalViewsStore($$value);
flushSync();
},
get boardIndexStore() {
return boardIndexStore();
},
set boardIndexStore($$value) {
boardIndexStore($$value);
flushSync();
},
get boardListSettingsStore() {
return boardListSettingsStore();
},
set boardListSettingsStore($$value) {
boardListSettingsStore($$value);
flushSync();
},
get currentPathStore() {
return currentPathStore();
},
set currentPathStore($$value) {
currentPathStore($$value);
flushSync();
},
get dashboardOpenStore() {
return dashboardOpenStore();
},
set dashboardOpenStore($$value) {
dashboardOpenStore($$value);
flushSync();
},
get openBoard() {
return openBoard();
},
set openBoard($$value) {
openBoard($$value);
flushSync();
},
get onSetBoardHidden() {
return onSetBoardHidden();
},
set onSetBoardHidden($$value) {
onSetBoardHidden($$value);
flushSync();
},
get onReorderBoards() {
return onReorderBoards();
},
set onReorderBoards($$value) {
onReorderBoards($$value);
flushSync();
},
get boardCountsStore() {
return boardCountsStore();
},
set boardCountsStore($$value) {
boardCountsStore($$value);
flushSync();
},
get onRequestBoardCounts() {
return onRequestBoardCounts();
},
set onRequestBoardCounts($$value) {
onRequestBoardCounts($$value);
flushSync();
},
get lastOpenedStore() {
return lastOpenedStore();
},
set lastOpenedStore($$value) {
lastOpenedStore($$value);
flushSync();
},
get boardRailSettingsStore() {
return boardRailSettingsStore();
},
set boardRailSettingsStore($$value) {
boardRailSettingsStore($$value);
flushSync();
},
get onSetRailWidth() {
return onSetRailWidth();
},
set onSetRailWidth($$value) {
onSetRailWidth($$value);
flushSync();
},
get onCreateBoard() {
return onCreateBoard();
},
set onCreateBoard($$value) {
onCreateBoard($$value);
flushSync();
},
get onDeleteBoard() {
return onDeleteBoard();
},
set onDeleteBoard($$value) {
onDeleteBoard($$value);
flushSync();
},
get requestSave() {
return requestSave();
},
set requestSave($$value) {
requestSave($$value);
flushSync();
},
$set: update_legacy_props,
$on: ($$event_name, $$event_cb) => add_legacy_event_listener($$props, $$event_name, $$event_cb)
};
init();
var div = root_216();
event("keydown", $window, handleWindowKeydown);
event("mousedown", $window, handleWindowMousedown);
event("resize", $window, handleWindowViewportChange);
event("scroll", $window, handleWindowViewportChange);
var div_1 = child(div);
let classes;
var node = child(div_1);
{
var consequent = ($$anchor2) => {
Board_rail($$anchor2, {
get boardIndexStore() {
return boardIndexStore();
},
get boardListSettingsStore() {
return boardListSettingsStore();
},
get currentPath() {
return $currentPathStore();
},
get dashboardOpen() {
return $dashboardOpenStore();
},
onToggleDashboard: toggleDashboard,
onSelect: handleDashboardSelect,
get onReorderBoards() {
return onReorderBoards();
},
get dock() {
return get(railDock);
},
get width() {
return get(railWidth);
},
get onSetWidth() {
return onSetRailWidth();
},
get dashboardButtonEl() {
return get(railDashboardButtonEl);
},
set dashboardButtonEl($$value) {
set(railDashboardButtonEl, $$value);
},
$$legacy: true
});
};
if_block(node, ($$render) => {
if (get(railVisible2)) $$render(consequent);
});
}
var div_2 = sibling(node, 2);
var div_3 = child(div_2);
let classes_1;
var div_4 = child(div_3);
var button = child(div_4);
let classes_2;
var node_1 = child(button);
Icon(node_1, { name: "sliders-horizontal", size: 16 });
var span = sibling(node_1, 4);
var node_2 = child(span);
{
let $0 = derived_safe_equal(() => get(viewEditorExpanded) ? "chevron-up" : "chevron-down");
Icon(node_2, {
get name() {
return get($0);
},
size: 15
});
}
reset(span);
reset(button);
var node_3 = sibling(button, 2);
{
var consequent_1 = ($$anchor2) => {
var div_5 = root23();
var node_4 = child(div_5);
{
let $0 = derived_safe_equal(() => ($settingsStore(), untrack(() => {
var _a5;
return (_a5 = $settingsStore().sortDirection) != null ? _a5 : "asc";
})));
let $1 = derived_safe_equal(() => ($settingsStore(), untrack(() => {
var _a5;
return (_a5 = $settingsStore().groupDirection) != null ? _a5 : "asc";
})));
let $2 = derived_safe_equal(() => (get(propertyGroupSource), untrack(() => {
var _a5, _b3;
return (_b3 = (_a5 = get(propertyGroupSource)) == null ? void 0 : _a5.collapsePastDates) != null ? _b3 : false;
})));
View_editor(node_4, {
get sortSelectValue() {
return get(sortSelectValue);
},
get availableSortKeys() {
return get(availableSortKeys);
},
get isDirectionalSort() {
return get(isDirectionalSort);
},
get sortDirection() {
return get($0);
},
onSortChange,
onToggleSortDirection: toggleSortDirection,
get groupSelectValue() {
return get(groupSelectValue);
},
get availableGroupKeys() {
return get(availableGroupKeys);
},
get isDirectionalGroup() {
return get(isDirectionalGroup);
},
get groupDirection() {
return get($1);
},
onGroupChange,
onToggleGroupDirection: toggleGroupDirection,
get showCollapsePastDatesToggle() {
return get(showCollapsePastDatesToggle);
},
get collapsePastDates() {
return get($2);
},
onSetCollapsePastDates: setCollapsePastDates,
get isTagPrefixGrouping() {
return get(isTagPrefixGrouping);
},
get tagGroupInputMode() {
return get(tagGroupInputMode);
},
get availableTags() {
return get(availableTags);
},
get tagGroupPrefix() {
return get(tagGroupPrefix);
},
get tagGroupIncludeTags() {
return get(tagGroupIncludeTags);
},
onSetTagGroupInputMode: setTagGroupInputMode,
onUpdateTagGroupPrefix: updateTagGroupPrefix,
onUpdateTagGroupIncludeTags: updateTagGroupIncludeTags,
get flowDirection() {
return get(flowDirection);
},
get columnWidth() {
return get(columnWidth);
},
onSetFlowDirection: setFlowDirection,
onSetColumnWidth: setColumnWidth,
get savedViews() {
return get(mergedSavedViews);
},
get savedViewListExpanded() {
return get(savedViewListExpanded);
},
get canSaveView() {
return get(canSaveCurrentView);
},
get currentViewProperties() {
return get(currentSavedViewProperties);
},
onSaveCurrentView: saveCurrentView,
onApplySavedView: applySavedView,
onDeleteSavedView: (view) => set(savedViewPendingDelete, view),
onToggleSavedViewList: (expanded) => set(savedViewListExpanded, expanded)
});
}
reset(div_5);
bind_this(div_5, ($$value) => set(viewEditorPopover, $$value), () => get(viewEditorPopover));
template_effect(() => set_style(div_5, get(viewEditorPopoverStyle)));
append($$anchor2, div_5);
};
if_block(node_3, ($$render) => {
if (get(viewEditorExpanded)) $$render(consequent_1);
});
}
reset(div_4);
bind_this(div_4, ($$value) => set(viewControlContainer, $$value), () => get(viewControlContainer));
var div_6 = sibling(div_4, 2);
var div_7 = child(div_6);
var node_5 = child(div_7);
Icon(node_5, { name: "search", size: 16, opacity: 0.7 });
var input = sibling(node_5, 2);
remove_input_defaults(input);
set_attribute2(input, "placeholder", 'Filter tasks \u2014 e.g. "big rocks" tag:home file:projects due:<$TODAY');
bind_this(input, ($$value) => set(filterInputEl, $$value), () => get(filterInputEl));
var node_6 = sibling(input, 2);
{
var consequent_2 = ($$anchor2) => {
var button_1 = root_126();
event("click", button_1, clearFilter);
append($$anchor2, button_1);
};
if_block(node_6, ($$render) => {
if (get(filterQueryText) !== "" || get(appliedQueryText) !== "") $$render(consequent_2);
});
}
var button_2 = sibling(node_6, 2);
var node_7 = child(button_2);
Icon(node_7, { name: "sliders-horizontal", size: 18 });
reset(button_2);
reset(div_7);
var node_8 = sibling(div_7, 2);
{
var consequent_3 = ($$anchor2) => {
Filter_suggestion_list($$anchor2, {
get suggestions() {
return get(barSuggestions);
},
get selectedIndex() {
return get(barSuggestionIndex);
},
onAccept: acceptBarSuggestion
});
};
if_block(node_8, ($$render) => {
if (get(barSuggestionsVisible)) $$render(consequent_3);
});
}
var node_9 = sibling(node_8, 2);
{
var consequent_4 = ($$anchor2) => {
Filter_editor($$anchor2, {
get query() {
return get(draftQuery);
},
get dateKeys() {
return get(dateFilterKeys);
},
get tagSuggestionItems() {
return get(availableTags);
},
get fileSuggestionItems() {
return get(taskFilePaths);
},
get savedFilters() {
return get(savedFilterEntries);
},
get savedListExpanded() {
return get(savedFilterListExpanded);
},
onChange: applyEditorQuery,
onSearch: searchFromEditor,
onClear: clearFilter,
onApplySavedFilter: applySavedFilter,
onDeleteSavedFilter: (entry) => set(savedFilterPendingDelete, entry),
onSaveFilter: saveCurrentFilter,
onToggleSavedList: (expanded) => set(savedFilterListExpanded, expanded)
});
};
if_block(node_9, ($$render) => {
if (get(filterEditorExpanded)) $$render(consequent_4);
});
}
reset(div_6);
bind_this(div_6, ($$value) => set(filterBarContainer, $$value), () => get(filterBarContainer));
var div_8 = sibling(div_6, 2);
var node_10 = child(div_8);
Icon_button(node_10, {
icon: "lucide-settings",
$$events: { click: handleOpenSettings }
});
reset(div_8);
reset(div_3);
var node_11 = sibling(div_3, 2);
{
var consequent_5 = ($$anchor2) => {
{
let $0 = derived_safe_equal(() => (get(savedFilterPendingDelete), untrack(() => {
var _a5;
return (_a5 = get(savedFilterPendingDelete).name) != null ? _a5 : get(savedFilterPendingDelete).query;
})));
Delete_filter_modal($$anchor2, {
get filterText() {
return get($0);
},
onConfirm: confirmDeleteSavedFilter,
onCancel: () => set(savedFilterPendingDelete, void 0)
});
}
};
if_block(node_11, ($$render) => {
if (get(savedFilterPendingDelete)) $$render(consequent_5);
});
}
var node_12 = sibling(node_11, 2);
{
var consequent_6 = ($$anchor2) => {
Delete_filter_modal($$anchor2, {
title: "Delete saved view?",
get filterText() {
return get(savedViewPendingDelete), untrack(() => get(savedViewPendingDelete).name);
},
onConfirm: confirmDeleteSavedView,
onCancel: () => set(savedViewPendingDelete, void 0)
});
};
if_block(node_12, ($$render) => {
if (get(savedViewPendingDelete)) $$render(consequent_6);
});
}
var div_9 = sibling(node_12, 2);
var div_10 = child(div_9);
let classes_3;
var node_13 = child(div_10);
{
var consequent_7 = ($$anchor2) => {
{
let $0 = derived_safe_equal(() => ($settingsStore(), untrack(() => {
var _a5;
return (_a5 = $settingsStore().excludedTags) != null ? _a5 : [];
})));
Board_matrix_horizontal($$anchor2, {
get app() {
return app();
},
get matrix() {
return get(activeMatrix);
},
get taskActions() {
return taskActions();
},
get columnTagTableStore() {
return columnTagTableStore();
},
get columnColourTableStore() {
return columnColourTableStore();
},
get columnMatchTagTableStore() {
return columnMatchTagTableStore();
},
get columnSubtitleTableStore() {
return columnSubtitleTableStore();
},
get showFilepath() {
return get(showFilepath);
},
get consolidateTags() {
return get(consolidateTags);
},
get excludedTags() {
return get($0);
},
get targetTaskFile() {
return get(targetTaskFile);
},
get targetFileIsDefault() {
return get(targetFileIsDefault);
},
onToggleCollapse: toggleColumnCollapse,
get uncategorizedColumnName() {
return get(uncategorizedColumnName);
},
get doneColumnName() {
return get(doneColumnName);
},
get columnWidth() {
var _a5;
return `${(_a5 = get(columnWidth)) != null ? _a5 : ""}px`;
},
get propertyDisplay() {
return get(propertyDisplay);
},
get propertySchemaOption() {
return get(propertySchemaOption);
},
get isManualOrder() {
return get(isManualOrder);
},
get manualOrder() {
return get(manualOrder);
},
get reorderEnabled() {
return get(reorderEnabled);
},
get treatNestedTasksAsSubtasks() {
return get(treatNestedTasksAsSubtasks);
},
get taskCountLabel() {
return get(boardTaskCountLabel);
}
});
}
};
var alternate = ($$anchor2) => {
{
let $0 = derived_safe_equal(() => ($settingsStore(), untrack(() => {
var _a5;
return (_a5 = $settingsStore().excludedTags) != null ? _a5 : [];
})));
Board_matrix_vertical($$anchor2, {
get app() {
return app();
},
get matrix() {
return get(activeMatrix);
},
get taskActions() {
return taskActions();
},
get columnTagTableStore() {
return columnTagTableStore();
},
get columnColourTableStore() {
return columnColourTableStore();
},
get columnMatchTagTableStore() {
return columnMatchTagTableStore();
},
get columnSubtitleTableStore() {
return columnSubtitleTableStore();
},
get showFilepath() {
return get(showFilepath);
},
get consolidateTags() {
return get(consolidateTags);
},
get excludedTags() {
return get($0);
},
get targetTaskFile() {
return get(targetTaskFile);
},
get targetFileIsDefault() {
return get(targetFileIsDefault);
},
onToggleCollapse: toggleColumnCollapse,
get uncategorizedColumnName() {
return get(uncategorizedColumnName);
},
get doneColumnName() {
return get(doneColumnName);
},
get propertyDisplay() {
return get(propertyDisplay);
},
get propertySchemaOption() {
return get(propertySchemaOption);
},
get isManualOrder() {
return get(isManualOrder);
},
get manualOrder() {
return get(manualOrder);
},
get reorderEnabled() {
return get(reorderEnabled);
},
get treatNestedTasksAsSubtasks() {
return get(treatNestedTasksAsSubtasks);
},
get taskCountLabel() {
return get(boardTaskCountLabel);
}
});
}
};
if_block(node_13, ($$render) => {
if (!get(isVerticalFlow)) $$render(consequent_7);
else $$render(alternate, -1);
});
}
reset(div_10);
reset(div_9);
var node_14 = sibling(div_9, 2);
{
var consequent_8 = ($$anchor2) => {
{
let $0 = derived_safe_equal(() => get(railOnTop) ? "top" : "left");
Dashboard_panel($$anchor2, {
get app() {
return app();
},
get boardIndexStore() {
return boardIndexStore();
},
get boardListSettingsStore() {
return boardListSettingsStore();
},
get currentPath() {
return $currentPathStore();
},
getBoardStat: getDashboardBoardStat,
onSelect: handleDashboardSelect,
get onSetBoardHidden() {
return onSetBoardHidden();
},
get onReorderBoards() {
return onReorderBoards();
},
get boardCountsStore() {
return boardCountsStore();
},
get onRequestBoardCounts() {
return onRequestBoardCounts();
},
get lastOpenedStore() {
return lastOpenedStore();
},
get onCreateBoard() {
return onCreateBoard();
},
get onDeleteBoard() {
return onDeleteBoard();
},
get slideFrom() {
return get($0);
},
onClose: () => dashboardOpenStore().set(false)
});
}
};
if_block(node_14, ($$render) => {
if ($dashboardOpenStore()) $$render(consequent_8);
});
}
reset(div_2);
bind_this(div_2, ($$value) => set(boardContentEl, $$value), () => get(boardContentEl));
reset(div_1);
reset(div);
template_effect(() => {
var _a5;
classes = set_class(div_1, 1, "board-content svelte-16qe0yp", null, classes, { "rail-top": get(railOnTop) });
classes_1 = set_class(div_3, 1, "board-toolbar svelte-16qe0yp", null, classes_1, { "dashboard-open": $dashboardOpenStore() });
div_4.inert = $dashboardOpenStore();
classes_2 = set_class(button, 1, "view-editor-toggle svelte-16qe0yp", null, classes_2, { active: get(viewEditorExpanded) });
set_attribute2(button, "aria-expanded", get(viewEditorExpanded));
set_attribute2(button, "aria-label", get(viewEditorExpanded) ? "Hide view settings" : "Show view settings");
div_6.inert = $dashboardOpenStore();
set_attribute2(button_2, "aria-label", get(filterEditorExpanded) ? "Hide search options" : "Show search options");
set_attribute2(button_2, "aria-expanded", get(filterEditorExpanded));
div_8.inert = $dashboardOpenStore();
classes_3 = set_class(div_10, 1, "columns svelte-16qe0yp", null, classes_3, { "vertical-flow": get(isVerticalFlow) });
set_style(div_10, `--column-width: ${(_a5 = get(columnWidth)) != null ? _a5 : ""}px;`);
});
event("click", button, toggleViewEditor);
bind_value(input, () => get(filterQueryText), ($$value) => set(filterQueryText, $$value));
event("input", input, refreshBarSuggestions);
event("keydown", input, handleFilterInputKeydown);
event("click", input, handleFilterInputClick);
event("blur", input, hideBarSuggestions);
event("click", button_2, () => set(filterEditorExpanded, !get(filterEditorExpanded)));
append($$anchor, div);
bind_prop($$props, "openCurrentBoardSettings", openCurrentBoardSettings);
bind_prop($$props, "hasVisibleSelectedCards", hasVisibleSelectedCards);
bind_prop($$props, "markSelectedCardsDone", markSelectedCardsDone);
bind_prop($$props, "archiveSelectedCards", archiveSelectedCards);
bind_prop($$props, "cancelSelectedCards", cancelSelectedCards);
bind_prop($$props, "duplicateSelectedCards", duplicateSelectedCards);
bind_prop($$props, "deleteSelectedCardsCommand", deleteSelectedCardsCommand);
var $$pop = pop($$exports);
$$cleanup();
return $$pop;
}
// src/ui/settings/settings.ts
var import_obsidian13 = require("obsidian");
// src/ui/tasks/scope.ts
function normalizePath(path) {
return path.replace(/^\//, "").replace(/\/$/, "");
}
function pathMatchesFilter(filePath, filterPath) {
const normalized = normalizePath(filterPath);
if (normalized === "") {
return true;
}
return filePath === normalized || filePath.startsWith(`${normalized}/`);
}
function shouldIncludeFilePath(filePath, filenameFilter, excludeFilter, boardFolderPath) {
if (filenameFilter !== null) {
const included = filenameFilter.some(
(folder) => pathMatchesFilter(filePath, folder)
);
if (!included) {
return false;
}
}
if (excludeFilter && excludeFilter.length > 0) {
const normalizedBoard = boardFolderPath !== null && boardFolderPath !== void 0 ? normalizePath(boardFolderPath) : null;
const isExcluded = excludeFilter.some((excludePath) => {
if (!pathMatchesFilter(filePath, excludePath)) {
return false;
}
if (normalizedBoard !== null) {
const normalizedExclude = normalizePath(excludePath);
const excludeCoversBoard = normalizedExclude === "" || // root exclude covers everything
normalizedBoard === normalizedExclude || normalizedBoard.startsWith(`${normalizedExclude}/`);
if (excludeCoversBoard) {
const fileInBoardFolder = normalizedBoard === "" || // if board is at root, every file is inside the board folder
filePath === normalizedBoard || filePath.startsWith(`${normalizedBoard}/`);
if (fileInBoardFolder) {
return false;
}
}
}
return true;
});
if (isExcluded) {
return false;
}
}
return true;
}
function resolveScopeFilter(scope, scopeFolders, boardFolderPath) {
switch (scope) {
case "folder" /* Folder */:
return boardFolderPath !== null ? [boardFolderPath] : null;
case "selectedFolders" /* SelectedFolders */: {
const selected = scopeFolders != null ? scopeFolders : [];
return boardFolderPath !== null ? [boardFolderPath, ...selected.filter((folder) => folder !== boardFolderPath)] : selected;
}
default:
return null;
}
}
// src/ui/settings/column_reorder.ts
function moveColumnRelativeTo(columns, draggedColumnId, targetColumnId, position) {
if (draggedColumnId === targetColumnId) {
return columns;
}
const draggedIndex = columns.findIndex((column) => column.id === draggedColumnId);
const targetIndex = columns.findIndex((column) => column.id === targetColumnId);
if (draggedIndex < 0 || targetIndex < 0) {
return columns;
}
const nextColumns = [...columns];
const [draggedColumn] = nextColumns.splice(draggedIndex, 1);
if (!draggedColumn) {
return columns;
}
const baseTargetIndex = draggedIndex < targetIndex ? targetIndex - 1 : targetIndex;
const adjustedTargetIndex = position === "after" ? baseTargetIndex + 1 : baseTargetIndex;
nextColumns.splice(adjustedTargetIndex, 0, draggedColumn);
return nextColumns;
}
// src/ui/settings/column_validation.ts
function getColumnValidationError(columns, options = {}) {
var _a5, _b3, _c2, _d;
const errors = [];
const seenSignatures = /* @__PURE__ */ new Map();
const doneStatusMarkers = Array.from((_a5 = options.doneStatusMarkers) != null ? _a5 : "");
const ignoredStatusMarkers = Array.from((_b3 = options.ignoredStatusMarkers) != null ? _b3 : "");
const originalColumnsById = new Map(((_c2 = options.originalColumns) != null ? _c2 : []).map((column) => [column.id, column]));
for (const column of columns) {
const label = column.label.trim();
if (label.length === 0) {
errors.push("Column labels cannot be empty.");
continue;
}
const derivedTag = kebab(label);
if (RESERVED_COLUMN_KEYS.has(derivedTag)) {
errors.push(`Column name "${label}" conflicts with a built-in column.`);
}
if (usesTagMatching(column) && column.matchTags.length === 0) {
errors.push(`Column "${label}" must define at least one explicit tag.`);
continue;
}
if (usesTagMatching(column)) {
for (const tag2 of column.matchTags) {
if (!isValidTag(tag2)) {
errors.push(`Column "${label}" has an invalid tag "${tag2}".`);
break;
}
}
}
if (usesStatusMatching(column)) {
const marker = column.matchStatus;
if (marker == null || marker.length === 0) {
errors.push(`Column "${label}" must define a status marker.`);
continue;
}
if (Array.from(marker).length !== 1) {
errors.push(`Column "${label}" status marker must be a single character.`);
continue;
}
if (marker !== " " && /\s/.test(marker)) {
errors.push(`Column "${label}" status marker cannot be whitespace.`);
continue;
}
if (doneStatusMarkers.includes(marker)) {
errors.push(`Column "${label}" uses done status marker "${getStatusColumnLabel(marker)}".`);
continue;
}
if (ignoredStatusMarkers.includes(marker)) {
errors.push(`Column "${label}" uses ignored status marker "${getStatusColumnLabel(marker)}".`);
continue;
}
}
if (usesPriorityMatching(column)) {
const priority = (_d = column.matchPriority) == null ? void 0 : _d.trim();
if (!priority) {
errors.push(`Column "${label}" must define a priority.`);
continue;
}
const originalColumn = originalColumnsById.get(column.id);
const priorityRuleUnchanged = !!originalColumn && usesPriorityMatching(originalColumn) && columnRuleSignature(originalColumn) === columnRuleSignature(column);
const columnPrioritySchema = getColumnPrioritySchema(column);
const schemaMatches = options.propertySchema === columnPrioritySchema;
if (!schemaMatches) {
if (priorityRuleUnchanged) {
continue;
}
if (options.propertySchema === "none" /* None */) {
errors.push(`Column "${label}" uses priority matching, but task properties are disabled.`);
continue;
}
errors.push(`Column "${label}" priority matching requires the ${columnPrioritySchema === "dataview" /* Dataview */ ? "Dataview" : "Tasks Plugin"} property schema.`);
continue;
}
if (columnPrioritySchema === "tasks" /* TasksPlugin */ && !TASKS_PRIORITY_OPTIONS.some((option) => option.value === priority)) {
errors.push(`Column "${label}" has an unknown priority "${priority}".`);
continue;
}
}
const signature = columnRuleSignature(column);
const existingLabel = seenSignatures.get(signature);
if (existingLabel) {
const criterion = usesStatusMatching(column) ? "status marker" : usesPriorityMatching(column) ? `priority "${getPriorityColumnLabel(normalizePriorityMatchValue(column.matchPriority, getColumnPrioritySchema(column)))}"` : "tag";
errors.push(`Columns "${existingLabel}" and "${label}" match the same ${criterion}.`);
} else {
seenSignatures.set(signature, label);
}
if (usesTagMatching(column) && column.matchTags.length === 1) {
const nameEquivalent = `name:${kebab(column.matchTags[0])}`;
const nameCollision = seenSignatures.get(nameEquivalent);
if (nameCollision) {
errors.push(`Columns "${nameCollision}" and "${label}" match the same tag.`);
}
}
if (column.matchMode === "name") {
const tagsEquivalent = `tags:${derivedTag}`;
const tagsCollision = seenSignatures.get(tagsEquivalent);
if (tagsCollision) {
errors.push(`Columns "${tagsCollision}" and "${label}" match the same tag.`);
}
}
}
return errors.length > 0 ? errors[0] : null;
}
// src/ui/settings/suggest.ts
var import_obsidian12 = require("obsidian");
var FolderSuggest = class extends import_obsidian12.AbstractInputSuggest {
constructor(app, inputEl, onSelectCallback) {
super(app, inputEl);
this.inputEl = inputEl;
this.onSelectCallback = onSelectCallback;
}
getSuggestions(query) {
const folders = this.app.vault.getAllLoadedFiles().filter(
(f) => f instanceof import_obsidian12.TFolder
);
const lowerQuery = query.toLowerCase();
return folders.filter(
(folder) => folder.path.toLowerCase().includes(lowerQuery) && folder.path !== "/"
);
}
renderSuggestion(folder, el) {
el.setText(folder.path);
}
selectSuggestion(folder, evt) {
this.setValue(folder.path);
this.inputEl.dispatchEvent(new Event("input"));
if (this.onSelectCallback) {
this.onSelectCallback();
}
this.close();
}
};
var PathSuggest = class extends import_obsidian12.AbstractInputSuggest {
constructor(app, inputEl, onSelectCallback) {
super(app, inputEl);
this.inputEl = inputEl;
this.onSelectCallback = onSelectCallback;
}
getSuggestions(query) {
const files = this.app.vault.getAllLoadedFiles();
const lowerQuery = query.toLowerCase();
return files.filter(
(file) => file.path.toLowerCase().includes(lowerQuery) && file.path !== "/"
);
}
renderSuggestion(file, el) {
el.setText(file.path);
}
selectSuggestion(file, evt) {
this.setValue(file.path);
this.inputEl.dispatchEvent(new Event("input"));
if (this.onSelectCallback) {
this.onSelectCallback();
}
this.close();
}
};
var FileSuggest = class extends import_obsidian12.AbstractInputSuggest {
constructor(app, inputEl, onSelectCallback) {
super(app, inputEl);
this.inputEl = inputEl;
this.onSelectCallback = onSelectCallback;
}
getSuggestions(query) {
const files = this.app.vault.getFiles();
const lowerQuery = query.toLowerCase();
return files.filter(
(file) => file.path.toLowerCase().includes(lowerQuery)
);
}
renderSuggestion(file, el) {
el.setText(file.path);
}
selectSuggestion(file, evt) {
this.setValue(file.path);
this.inputEl.dispatchEvent(new Event("input"));
if (this.onSelectCallback) {
this.onSelectCallback();
}
this.close();
}
};
var TagSuggest = class extends import_obsidian12.AbstractInputSuggest {
constructor(app, inputEl, onSelectCallback) {
super(app, inputEl);
this.inputEl = inputEl;
this.onSelectCallback = onSelectCallback;
}
getSuggestions(query) {
const tags = Object.keys(this.app.metadataCache.getTags());
const lowerQuery = query.toLowerCase();
return tags.map((t) => t.replace(/^#/, "")).filter((tag2) => tag2.toLowerCase().includes(lowerQuery));
}
renderSuggestion(tag2, el) {
el.setText(tag2);
}
selectSuggestion(tag2, evt) {
this.setValue(tag2);
this.inputEl.dispatchEvent(new Event("input"));
if (this.onSelectCallback) {
this.onSelectCallback();
}
this.close();
}
};
// src/ui/settings/settings.ts
var VisibilityOptionSchema = z.nativeEnum(VisibilityOption);
var ScopeOptionSchema = z.nativeEnum(ScopeOption);
function normalizePathInput(raw) {
return raw.trim().replace(/^\//, "").replace(/\/$/, "");
}
function normalizeTagInput(raw) {
return raw.trim().replace(/^#/, "");
}
var HEX_COLOR_PATTERN = /^#[0-9a-fA-F]{6}$/;
function validHexColor(color) {
const trimmed = color == null ? void 0 : color.trim();
return trimmed && HEX_COLOR_PATTERN.test(trimmed) ? trimmed : null;
}
var SettingsModal = class extends import_obsidian13.Modal {
constructor(app, settings, onSubmit, boardFolderPath, options = {}) {
var _a5, _b3;
super(app);
this.settings = settings;
this.onSubmit = onSubmit;
this.boardFolderPath = boardFolderPath;
this.options = options;
this.validationError = null;
this.saveBtn = null;
this.columnsEditorEl = null;
this.headerDirtyPill = null;
this.headerValidationPill = null;
this.availableColumnTags = [];
this.mountedColumnControls = [];
this.updateExistingTaskTagsByColumnId = /* @__PURE__ */ new Map();
this.activeColumnPopover = null;
this.draggedColumnId = null;
this.dragPreviewTarget = null;
this.focusTagEditorColumnId = null;
this.embeddedSubmitTimer = null;
this.defaultTaskFileInputEl = null;
this.defaultTaskFileErrorEl = null;
this.pinnedKeys = /* @__PURE__ */ new Set();
this.clearedKeys = /* @__PURE__ */ new Set();
this.overrideChipUpdaters = [];
this.originalSettings = structuredClone(settings);
this.originalSettingsSnapshot = JSON.stringify(settings);
this.initialOverriddenKeys = new Set((_b3 = (_a5 = options.overrideContext) == null ? void 0 : _a5.overriddenKeys) != null ? _b3 : []);
}
isGlobalDefaultsMode() {
return this.options.mode === "globalDefaults";
}
isEmbedded() {
return this.options.layout === "embedded";
}
mountInline(containerEl) {
this.contentEl = containerEl;
this.onOpen();
return () => this.onClose();
}
isDirty() {
return JSON.stringify(this.settings) !== this.originalSettingsSnapshot || this.pinnedKeys.size > 0 || this.clearedKeys.size > 0;
}
overrideTrackingEnabled() {
return !this.isGlobalDefaultsMode() && !!this.options.overrideContext;
}
baseSettingsRecord() {
var _a5, _b3;
return (_b3 = (_a5 = this.options.overrideContext) == null ? void 0 : _a5.baseSettings) != null ? _b3 : defaultSettings;
}
/**
* Whether a field would be persisted as an override if the modal were
* saved now: it was an override at open time (and not reset since), it
* was pinned this session, or its value was edited away from the
* original resolved value.
*/
isEffectivelyOverridden(key2) {
const settingsRecord = this.settings;
if (this.clearedKeys.has(key2)) {
return JSON.stringify(settingsRecord[key2]) !== JSON.stringify(this.baseSettingsRecord()[key2]);
}
if (this.initialOverriddenKeys.has(key2) || this.pinnedKeys.has(key2)) {
return true;
}
const originalRecord = this.originalSettings;
return JSON.stringify(settingsRecord[key2]) !== JSON.stringify(originalRecord[key2]);
}
/** Sheds the fields' overrides: restores base values and marks them cleared. */
resetOverrideKeys(keys) {
const settingsRecord = this.settings;
const baseRecord = this.baseSettingsRecord();
let valuesChanged = false;
for (const key2 of keys) {
if (!this.isEffectivelyOverridden(key2)) {
continue;
}
if (this.pinnedKeys.delete(key2) && !this.initialOverriddenKeys.has(key2)) {
continue;
}
if (JSON.stringify(settingsRecord[key2]) !== JSON.stringify(baseRecord[key2])) {
settingsRecord[key2] = structuredClone(baseRecord[key2]);
valuesChanged = true;
}
this.clearedKeys.add(key2);
}
if (valuesChanged) {
this.rerender();
}
this.touchSettings();
}
/**
* Pins fields at their current values. On a field that was reset earlier
* this session, this instead undoes the reset (restores the original
* override value).
*/
pinOverrideKeys(keys) {
const settingsRecord = this.settings;
const originalRecord = this.originalSettings;
let valuesChanged = false;
for (const key2 of keys) {
if (this.clearedKeys.delete(key2)) {
if (this.initialOverriddenKeys.has(key2) && JSON.stringify(settingsRecord[key2]) !== JSON.stringify(originalRecord[key2])) {
settingsRecord[key2] = structuredClone(originalRecord[key2]);
valuesChanged = true;
}
} else {
this.pinnedKeys.add(key2);
}
}
if (valuesChanged) {
this.rerender();
}
this.touchSettings();
}
/** The pin/reset decisions to hand to onSubmit, reconciled with edits. */
overrideLifecycleOptions() {
if (!this.overrideTrackingEnabled()) {
return { pinnedSettingKeys: [], clearedSettingKeys: [] };
}
const settingsRecord = this.settings;
const baseRecord = this.baseSettingsRecord();
const clearedSettingKeys = [...this.clearedKeys].filter(
(key2) => JSON.stringify(settingsRecord[key2]) === JSON.stringify(baseRecord[key2])
);
const clearedSet = new Set(clearedSettingKeys);
const pinnedSettingKeys = [...this.pinnedKeys].filter((key2) => !clearedSet.has(key2));
return { pinnedSettingKeys, clearedSettingKeys };
}
/**
* The inherited/overridden chip shown beside a setting. One chip can
* cover several fields (e.g. a bookend column's name and visibility);
* clicking toggles between resetting to the inherited values and
* pinning the current ones.
*/
createOverrideChip(containerEl, keys) {
if (!this.overrideTrackingEnabled()) {
return;
}
const chip = containerEl.createEl("button", { cls: "settings-override-chip" });
chip.type = "button";
const update2 = () => {
var _a5;
if (!chip.isConnected) {
return false;
}
const overridden = keys.some((key2) => this.isEffectivelyOverridden(key2));
chip.setText(overridden ? "Reset to defaults" : "Inherited");
chip.toggleClass("is-overridden", overridden);
chip.setAttribute(
"aria-label",
overridden ? "This board overrides the default. Click to reset to the inherited value." : "Following the default. Click to pin the current value to this board."
);
chip.title = (_a5 = chip.getAttribute("aria-label")) != null ? _a5 : "";
return true;
};
update2();
this.overrideChipUpdaters.push(update2);
chip.addEventListener("click", () => {
const overridden = keys.some((key2) => this.isEffectivelyOverridden(key2));
if (overridden) {
this.resetOverrideKeys(keys);
} else {
this.pinOverrideKeys(keys);
}
});
}
/** Rebuilds the whole modal body (used when a reset changes field values). */
rerender() {
var _a5, _b3;
const scrollTop = (_b3 = (_a5 = this.scrollWrapper) == null ? void 0 : _a5.scrollTop) != null ? _b3 : 0;
for (const destroy of this.mountedColumnControls) {
destroy();
}
this.mountedColumnControls = [];
this.overrideChipUpdaters = [];
this.contentEl.empty();
this.onOpen();
this.scrollWrapper.scrollTop = scrollTop;
}
validateColumns() {
var _a5, _b3, _c2, _d;
this.validationError = getColumnValidationError((_a5 = this.settings.columns) != null ? _a5 : [], {
doneStatusMarkers: (_b3 = this.settings.doneStatusMarkers) != null ? _b3 : DEFAULT_DONE_STATUS_MARKERS,
ignoredStatusMarkers: (_c2 = this.settings.ignoredStatusMarkers) != null ? _c2 : DEFAULT_IGNORED_STATUS_MARKERS,
propertySchema: (_d = this.settings.propertySchema) != null ? _d : "none" /* None */,
originalColumns: this.originalSettings.columns
});
this.updateValidationBanner();
}
touchSettings() {
this.validateColumns();
this.updateDirtyBanner();
}
scheduleEmbeddedSubmit() {
if (!this.isEmbedded() || this.validationError) {
return;
}
if (this.embeddedSubmitTimer) {
clearTimeout(this.embeddedSubmitTimer);
}
this.embeddedSubmitTimer = setTimeout(() => {
this.embeddedSubmitTimer = null;
void this.onSubmit(this.settings, {
updateExistingTaskTagsByColumnId: Object.fromEntries(this.updateExistingTaskTagsByColumnId),
...this.overrideLifecycleOptions()
});
}, 150);
}
getOriginalColumn(columnId) {
return this.originalSettings.columns.find((column) => column.id === columnId);
}
shouldShowRetagOption(column) {
if (this.isGlobalDefaultsMode()) return false;
const originalColumn = this.getOriginalColumn(column.id);
if (!originalColumn) return false;
return columnRuleSignature(originalColumn) !== columnRuleSignature(column);
}
shouldUpdateExistingTaskTags(columnId) {
var _a5;
return (_a5 = this.updateExistingTaskTagsByColumnId.get(columnId)) != null ? _a5 : true;
}
getActivePrioritySchema() {
return this.settings.propertySchema === "tasks" /* TasksPlugin */ || this.settings.propertySchema === "dataview" /* Dataview */ ? this.settings.propertySchema : void 0;
}
canSelectPriorityMode(column) {
return !!this.getActivePrioritySchema() || usesPriorityMatching(column);
}
canEditPriorityValue(column) {
return usesPriorityMatching(column) && getColumnPrioritySchema(column) === this.getActivePrioritySchema();
}
confirmRemoveColumn(column) {
new ConfirmModal(this.app, {
title: "Remove column?",
body: `Remove "${column.label || "Untitled column"}" from this board's settings?`,
note: "This change is not saved until you save the settings modal.",
confirmText: "Remove",
onConfirm: () => {
var _a5;
this.settings.columns = this.settings.columns.filter((candidate) => candidate.id !== column.id);
this.updateExistingTaskTagsByColumnId.delete(column.id);
if (((_a5 = this.activeColumnPopover) == null ? void 0 : _a5.columnId) === column.id) {
this.activeColumnPopover = null;
}
this.renderColumnsEditor();
this.touchSettings();
}
}).open();
}
addColumn() {
const usedIds = new Set(this.settings.columns.map((column) => column.id));
this.settings.columns = [
...this.settings.columns,
{
id: createColumnId("New Column", usedIds),
label: "New Column",
matchMode: "name",
matchTags: []
}
];
this.renderColumnsEditor();
this.touchSettings();
}
reorderColumns(draggedColumnId, targetColumnId, position) {
const reordered = moveColumnRelativeTo(this.settings.columns, draggedColumnId, targetColumnId, position);
if (reordered === this.settings.columns) {
return;
}
this.settings.columns = reordered;
this.renderColumnsEditor();
this.touchSettings();
}
setDragPreview(columnId, position) {
this.dragPreviewTarget = { columnId, position };
}
clearDragPreview() {
this.dragPreviewTarget = null;
}
clearDragState(container) {
this.draggedColumnId = null;
this.clearDragPreview();
if (!container) return;
container.querySelectorAll(".column-editor-row").forEach((candidate) => {
candidate.removeClass("is-drop-target");
candidate.removeClass("is-drop-before");
candidate.removeClass("is-drop-after");
candidate.removeClass("is-dragging");
});
}
async refreshAvailableColumnTags() {
var _a5;
const files = this.app.vault.getMarkdownFiles().filter(
(file) => {
var _a6;
return shouldIncludeFilePath(
file.path,
this.getScopeFilter(),
(_a6 = this.settings.excludePaths) != null ? _a6 : [],
this.boardFolderPath
);
}
);
const tags = /* @__PURE__ */ new Set();
const ignoredStatusMarkers = (_a5 = this.settings.ignoredStatusMarkers) != null ? _a5 : DEFAULT_IGNORED_STATUS_MARKERS;
for (const file of files) {
const contents = await this.app.vault.cachedRead(file);
for (const row of contents.split("\n")) {
if (!row || !isTrackedTaskString(row, ignoredStatusMarkers)) continue;
for (const tag2 of getTagsFromContent(row)) {
if (tag2 === "archived") continue;
tags.add(tag2);
}
}
}
const nextTags = [...tags].sort((a, b) => a.localeCompare(b));
if (JSON.stringify(nextTags) === JSON.stringify(this.availableColumnTags)) {
return;
}
this.availableColumnTags = nextTags;
if (this.columnsEditorEl) {
this.renderColumnsEditor();
}
}
renderColumnsEditor() {
var _a5, _b3, _c2, _d;
if (!this.columnsEditorEl) {
return;
}
for (const destroy of this.mountedColumnControls) {
destroy();
}
this.mountedColumnControls = [];
this.columnsEditorEl.empty();
const section = this.columnsEditorEl.createDiv({ cls: "column-editor-section" });
const sectionIntro = section.createDiv({ cls: "column-editor-intro" });
const introText = sectionIntro.createDiv({ cls: "column-editor-intro-text" });
introText.createEl("p", {
text: "Rename, reorder, and map board columns. Use the color and match controls to edit each column's rules.",
cls: "setting-item-description"
});
const rows = section.createDiv({ cls: "column-editor-list" });
this.renderBookendRow(rows, {
title: "Uncategorized",
label: (_a5 = this.settings.uncategorizedColumnName) != null ? _a5 : "",
placeholder: "Uncategorized",
overrideKeys: ["uncategorizedColumnName", "uncategorizedVisibility"],
visibility: (_b3 = this.settings.uncategorizedVisibility) != null ? _b3 : "auto" /* Auto */,
onLabelChange: (value) => {
this.settings.uncategorizedColumnName = value;
this.touchSettings();
},
onVisibilityChange: (value) => {
const validatedValue = VisibilityOptionSchema.safeParse(value);
this.settings.uncategorizedVisibility = validatedValue.success ? validatedValue.data : defaultSettings.uncategorizedVisibility;
this.touchSettings();
}
});
for (const column of this.settings.columns) {
this.renderCustomColumnRow(rows, column);
}
this.renderBookendRow(rows, {
title: "Done",
label: (_c2 = this.settings.doneColumnName) != null ? _c2 : "",
placeholder: "Done",
overrideKeys: ["doneColumnName", "doneVisibility"],
visibility: (_d = this.settings.doneVisibility) != null ? _d : "always" /* AlwaysShow */,
onLabelChange: (value) => {
this.settings.doneColumnName = value;
this.touchSettings();
},
onVisibilityChange: (value) => {
const validatedValue = VisibilityOptionSchema.safeParse(value);
this.settings.doneVisibility = validatedValue.success ? validatedValue.data : defaultSettings.doneVisibility;
this.touchSettings();
}
});
const controls = section.createDiv({ cls: "column-editor-controls" });
const addButton = controls.createEl("button", { text: "Add column" });
addButton.addEventListener("click", () => this.addColumn());
if (this.focusTagEditorColumnId) {
const targetColumnId = this.focusTagEditorColumnId;
this.focusTagEditorColumnId = null;
window.requestAnimationFrame(() => {
const targetInput = section.querySelector(
`[data-column-id="${targetColumnId}"] .column-editor-field-tag input`
);
targetInput == null ? void 0 : targetInput.focus();
targetInput == null ? void 0 : targetInput.click();
});
}
}
renderBookendRow(container, options) {
const row = container.createDiv({ cls: "column-editor-row is-bookend" });
row.createDiv({ cls: "column-editor-handle-spacer" });
const content = row.createDiv({ cls: "column-editor-row-content" });
const fields = content.createDiv({ cls: "column-editor-summary" });
const labelField = fields.createDiv({ cls: "column-editor-field column-editor-field-label" });
const labelInput = labelField.createEl("input", {
type: "text",
value: options.label,
placeholder: options.placeholder
});
labelInput.addClass("setting-input");
labelInput.setAttribute("aria-label", `${options.title} column label`);
labelInput.addEventListener("input", () => {
options.onLabelChange(labelInput.value);
});
const visibilityField = fields.createDiv({ cls: "column-editor-field column-editor-field-visibility" });
const visibilitySelect = visibilityField.createEl("select");
visibilitySelect.addClass("dropdown");
visibilitySelect.setAttribute("aria-label", `${options.title} visibility`);
visibilitySelect.createEl("option", {
value: "always" /* AlwaysShow */,
text: "Always show"
});
visibilitySelect.createEl("option", {
value: "auto" /* Auto */,
text: "Hide when empty"
});
visibilitySelect.createEl("option", {
value: "never" /* NeverShow */,
text: "Never show"
});
visibilitySelect.value = options.visibility;
visibilitySelect.addEventListener("change", () => {
options.onVisibilityChange(visibilitySelect.value);
});
this.createOverrideChip(fields, options.overrideKeys);
}
getColumnMatchSummary(column) {
var _a5;
if (usesStatusMatching(column)) {
return column.matchStatus ? `Status: ${getStatusColumnLabel(column.matchStatus)}` : "Needs status";
}
if (usesPriorityMatching(column)) {
return column.matchPriority ? `Priority: ${getPriorityColumnLabel(column.matchPriority)}` : "Needs priority";
}
if (!usesTagMatching(column)) {
return "Matches name";
}
const tags = (_a5 = column.matchTags) != null ? _a5 : [];
if (tags.length === 0) {
return "Needs tags";
}
if (tags.length === 1) {
return `#${tags[0]}`;
}
return `${tags.length} required tags`;
}
/**
* A text setting that only commits valid values: invalid input gets an
* error border and tooltip while the last valid value stays in effect.
*/
addValidatedTextSetting(container, options) {
new import_obsidian13.Setting(container).setName(options.name).setDesc(options.desc).addText((text2) => {
text2.setValue(options.value);
text2.onChange((value) => {
const errors = options.validate(value);
if (errors.length > 0) {
text2.inputEl.style.borderColor = "var(--text-error)";
text2.inputEl.title = `Invalid: ${errors.join(", ")}`;
} else {
text2.inputEl.style.borderColor = "";
text2.inputEl.title = options.validTitle;
options.onValid(value);
this.touchSettings();
}
});
}).then((setting) => {
if (options.overrideKey) {
this.createOverrideChip(setting.nameEl, [options.overrideKey]);
}
});
}
/**
* A string-list editor: an input row (suggester + Enter/Add commit)
* above removable rows. Empty, duplicate, and rejected values are
* silently ignored.
*/
createStringListEditor(container, options) {
const addRowEl = container.createDiv({ cls: "settings-list-add-row" });
const inputEl = addRowEl.createEl("input", {
type: "text",
placeholder: options.placeholder
});
inputEl.addClass("setting-input");
const listEl = container.createDiv();
const refresh = () => {
var _a5;
listEl.empty();
if (options.pinnedRow) {
const row = listEl.createDiv({ cls: "settings-list-row" });
row.createSpan({ cls: "settings-list-label", text: options.pinnedRow.label });
row.createSpan({ cls: "settings-list-note", text: options.pinnedRow.badge });
}
for (const item of ((_a5 = options.renderItems) != null ? _a5 : options.getItems)()) {
const row = listEl.createDiv({ cls: "settings-list-row" });
row.createSpan({
cls: options.monospaceLabels ? "settings-list-label-mono" : "settings-list-label",
text: item
});
if (options.warnWhenMissingFromVault && !this.app.vault.getAbstractFileByPath(item)) {
row.createSpan({ cls: "settings-list-note is-warning", text: " (not found)" });
}
const removeButton = row.createEl("button", {
text: options.removeStyle === "icon" ? "\u2715" : "Remove",
cls: options.removeStyle === "icon" ? "settings-list-remove-icon" : "settings-list-remove-text"
});
removeButton.addEventListener("click", () => {
var _a6;
options.setItems(options.getItems().filter((candidate) => candidate !== item));
refresh();
(_a6 = options.onChanged) == null ? void 0 : _a6.call(options);
});
}
};
const add = () => {
var _a5, _b3;
const value = options.normalize(inputEl.value);
if (!value || ((_a5 = options.reject) == null ? void 0 : _a5.call(options, value))) return;
const items = options.getItems();
if (items.includes(value)) return;
options.setItems([...items, value]);
inputEl.value = "";
refresh();
(_b3 = options.onChanged) == null ? void 0 : _b3.call(options);
};
options.createSuggest(inputEl, add);
const addButton = addRowEl.createEl("button", { text: "Add" });
addButton.addEventListener("click", add);
inputEl.addEventListener("keydown", (event2) => {
if (event2.key === "Enter") {
event2.preventDefault();
add();
}
});
refresh();
return { addRowEl, refresh };
}
getStatusMarkerOptions() {
var _a5, _b3;
const values = /* @__PURE__ */ new Set([" "]);
for (const marker of Array.from((_a5 = this.settings.statusMarkerOrder) != null ? _a5 : "")) {
values.add(marker);
}
for (const marker of Array.from((_b3 = this.settings.cancelledStatusMarkers) != null ? _b3 : DEFAULT_CANCELLED_STATUS_MARKERS)) {
values.add(marker);
}
return [...values].map((value) => ({
value,
label: value === " " ? "Unchecked" : value
}));
}
mountColumnPopoverDismiss(popover, trigger) {
const ownerDocument = popover.ownerDocument;
const closePopover = () => {
this.activeColumnPopover = null;
this.renderColumnsEditor();
};
const handleDocumentClick = (event2) => {
const target = event2.target;
if (!(target instanceof Node)) return;
if (popover.contains(target) || trigger.contains(target)) return;
closePopover();
};
const handleKeyDown = (event2) => {
if (event2.key !== "Escape") return;
event2.preventDefault();
closePopover();
};
const timeoutId = window.setTimeout(() => {
ownerDocument.addEventListener("click", handleDocumentClick);
ownerDocument.addEventListener("keydown", handleKeyDown);
});
this.mountedColumnControls.push(() => {
window.clearTimeout(timeoutId);
ownerDocument.removeEventListener("click", handleDocumentClick);
ownerDocument.removeEventListener("keydown", handleKeyDown);
});
}
wireColumnDragAndDrop(container, row, dragHandle, column) {
dragHandle.draggable = true;
dragHandle.addEventListener("dragstart", (event2) => {
this.draggedColumnId = column.id;
this.clearDragPreview();
row.addClass("is-dragging");
if (event2.dataTransfer) {
event2.dataTransfer.effectAllowed = "move";
event2.dataTransfer.setData("text/plain", column.id);
}
});
dragHandle.addEventListener("dragend", () => {
this.clearDragState(container);
});
row.addEventListener("dragover", (event2) => {
if (!this.draggedColumnId || this.draggedColumnId === column.id) {
return;
}
event2.preventDefault();
const rowRect = row.getBoundingClientRect();
const position = event2.clientY > rowRect.top + rowRect.height / 2 ? "after" : "before";
this.setDragPreview(column.id, position);
row.addClass("is-drop-target");
row.classList.toggle("is-drop-before", position === "before");
row.classList.toggle("is-drop-after", position === "after");
if (event2.dataTransfer) {
event2.dataTransfer.dropEffect = "move";
}
});
row.addEventListener("dragleave", () => {
var _a5;
if (((_a5 = this.dragPreviewTarget) == null ? void 0 : _a5.columnId) === column.id) {
this.clearDragPreview();
}
row.removeClass("is-drop-target");
row.removeClass("is-drop-before");
row.removeClass("is-drop-after");
});
row.addEventListener("drop", (event2) => {
var _a5, _b3, _c2, _d;
event2.preventDefault();
const position = ((_a5 = this.dragPreviewTarget) == null ? void 0 : _a5.columnId) === column.id ? this.dragPreviewTarget.position : "before";
const draggedColumnId = (_d = (_c2 = this.draggedColumnId) != null ? _c2 : (_b3 = event2.dataTransfer) == null ? void 0 : _b3.getData("text/plain")) != null ? _d : "";
this.clearDragState(container);
this.reorderColumns(draggedColumnId, column.id, position);
});
}
renderCustomColumnRow(container, column) {
var _a5;
const activePopover = ((_a5 = this.activeColumnPopover) == null ? void 0 : _a5.columnId) === column.id ? this.activeColumnPopover.kind : null;
const row = container.createDiv({
cls: "column-editor-row"
});
row.dataset.columnId = column.id;
const dragHandle = row.createEl("button", {
text: "\u22EE\u22EE",
cls: "column-editor-handle clickable-icon"
});
dragHandle.setAttribute("aria-label", `Reorder ${column.label} column`);
this.wireColumnDragAndDrop(container, row, dragHandle, column);
const content = row.createDiv({ cls: "column-editor-row-content" });
const summary = content.createDiv({ cls: "column-editor-summary" });
const labelField = summary.createDiv({ cls: "column-editor-field column-editor-field-label" });
const labelInput = labelField.createEl("input", { type: "text", value: column.label });
labelInput.addClass("setting-input");
labelInput.setAttribute("aria-label", "Column label");
const openPopover = (kind) => {
this.activeColumnPopover = activePopover === kind ? null : { columnId: column.id, kind };
this.renderColumnsEditor();
};
const colorAnchor = summary.createDiv({ cls: "column-editor-popover-anchor column-editor-color-anchor" });
const colorSummary = colorAnchor.createEl("button", {
cls: "column-editor-color-swatch column-editor-summary-swatch"
});
colorSummary.type = "button";
colorSummary.setAttribute("aria-haspopup", "dialog");
colorSummary.setAttribute("aria-expanded", activePopover === "color" ? "true" : "false");
colorSummary.setAttribute("aria-label", `Edit color for ${column.label || "column"}`);
colorSummary.addEventListener("click", () => openPopover("color"));
const matchAnchor = summary.createDiv({ cls: "column-editor-popover-anchor column-editor-match-anchor" });
const matchSummary = matchAnchor.createEl("button", {
cls: "column-editor-pill column-editor-summary-button"
});
matchSummary.type = "button";
matchSummary.setText(this.getColumnMatchSummary(column));
matchSummary.setAttribute("aria-haspopup", "dialog");
matchSummary.setAttribute("aria-expanded", activePopover === "match" ? "true" : "false");
matchSummary.setAttribute("aria-label", `Edit match settings for ${column.label || "column"}`);
matchSummary.addEventListener("click", () => openPopover("match"));
const updateSummarySwatch = () => {
const hexColor = validHexColor(column.color);
colorSummary.toggleClass("has-color", !!hexColor);
colorSummary.style.setProperty("--column-editor-swatch-color", hexColor != null ? hexColor : "transparent");
colorSummary.title = hexColor != null ? hexColor : "No color";
};
if (activePopover === "color") {
this.renderColumnColorPopover(column, colorAnchor, colorSummary, updateSummarySwatch);
}
updateSummarySwatch();
const updateRenameOption = activePopover === "match" ? this.renderColumnMatchPopover(column, matchAnchor, matchSummary) : () => void 0;
labelInput.addEventListener("input", () => {
column.label = labelInput.value;
updateRenameOption();
this.touchSettings();
});
const removeRail = row.createDiv({ cls: "column-editor-remove-rail" });
const removeButton = removeRail.createEl("button", { cls: "clickable-icon" });
removeButton.type = "button";
(0, import_obsidian13.setIcon)(removeButton, "x");
removeButton.setAttribute("aria-label", `Remove ${column.label} column`);
removeButton.addEventListener("click", () => {
this.confirmRemoveColumn(column);
});
}
renderColumnColorPopover(column, anchor, summaryButton, refreshSummarySwatch) {
var _a5, _b3;
const popover = anchor.createDiv({
cls: "column-editor-popover column-editor-color-popover",
attr: { role: "dialog", "aria-label": `${column.label || "Column"} color settings` }
});
popover.addEventListener("click", (event2) => event2.stopPropagation());
const colorField = popover.createDiv({ cls: "column-editor-popover-field column-editor-field-color" });
colorField.createDiv({ cls: "column-editor-inline-label", text: "Color" });
const swatchButton = colorField.createEl("button", {
cls: "column-editor-color-swatch"
});
swatchButton.type = "button";
swatchButton.setAttribute("aria-label", `Pick color for ${column.label}`);
const pickerInput = colorField.createEl("input", {
type: "color",
value: (_a5 = validHexColor(column.color)) != null ? _a5 : "#000000"
});
pickerInput.addClass("column-editor-color-picker");
const textInput = colorField.createEl("input", {
type: "text",
value: (_b3 = column.color) != null ? _b3 : "",
placeholder: "#RRGGBB"
});
textInput.addClass("setting-input");
textInput.setAttribute("aria-label", `${column.label} color`);
const refreshControls = () => {
var _a6;
const hexColor = validHexColor(column.color);
swatchButton.toggleClass("has-color", !!hexColor);
swatchButton.style.setProperty("--column-editor-swatch-color", hexColor != null ? hexColor : "transparent");
pickerInput.value = hexColor != null ? hexColor : "#000000";
textInput.value = (_a6 = column.color) != null ? _a6 : "";
refreshSummarySwatch();
};
textInput.addEventListener("input", () => {
column.color = textInput.value.trim() || void 0;
refreshControls();
this.touchSettings();
});
swatchButton.addEventListener("click", () => {
pickerInput.click();
});
pickerInput.addEventListener("input", () => {
column.color = pickerInput.value;
refreshControls();
this.touchSettings();
});
refreshControls();
this.mountColumnPopoverDismiss(popover, summaryButton);
}
/**
* Renders the match-rule popover and returns the refresher for its
* "Update existing tasks" row, which the label input also triggers.
*/
renderColumnMatchPopover(column, anchor, summaryButton) {
var _a5, _b3;
let updateRenameOption = () => void 0;
const matchPopover = anchor.createDiv({
cls: "column-editor-popover column-editor-match-popover",
attr: { role: "dialog", "aria-label": `${column.label || "Column"} match settings` }
});
matchPopover.addEventListener("click", (event2) => event2.stopPropagation());
const matchModeField = matchPopover.createDiv({ cls: "column-editor-popover-field column-editor-field-match" });
matchModeField.createDiv({ cls: "column-editor-inline-label", text: "Match by" });
const matchModeSelect = matchModeField.createEl("select");
matchModeSelect.addClass("dropdown");
matchModeSelect.createEl("option", {
value: "name",
text: "Name"
});
matchModeSelect.createEl("option", {
value: "tags",
text: "Tags"
});
matchModeSelect.createEl("option", {
value: "status",
text: "Status marker"
});
if (this.canSelectPriorityMode(column)) {
matchModeSelect.createEl("option", {
value: "priority",
text: "Priority"
});
}
matchModeSelect.value = column.matchMode;
matchModeSelect.addEventListener("change", () => {
var _a6, _b4;
const activePrioritySchema = this.getActivePrioritySchema();
column.matchMode = matchModeSelect.value === "tags" || matchModeSelect.value === "status" || matchModeSelect.value === "priority" && activePrioritySchema ? matchModeSelect.value : "name";
if (column.matchMode === "name") {
column.matchTags = [];
column.matchStatus = void 0;
column.matchPriority = void 0;
column.matchPropertySchema = void 0;
} else if (column.matchMode === "status") {
column.matchTags = [];
column.matchStatus = (_a6 = column.matchStatus) != null ? _a6 : " ";
column.matchPriority = void 0;
column.matchPropertySchema = void 0;
} else if (column.matchMode === "priority") {
column.matchTags = [];
column.matchStatus = void 0;
column.matchPriority = (_b4 = column.matchPriority) != null ? _b4 : "medium";
column.matchPropertySchema = activePrioritySchema;
} else {
column.matchStatus = void 0;
column.matchPriority = void 0;
column.matchPropertySchema = void 0;
this.focusTagEditorColumnId = column.id;
}
this.activeColumnPopover = { columnId: column.id, kind: "match" };
this.renderColumnsEditor();
this.touchSettings();
});
if (usesTagMatching(column)) {
const tagsField = matchPopover.createDiv({ cls: "column-editor-popover-field column-editor-field-tag" });
tagsField.createDiv({ cls: "column-editor-inline-label", text: "Tags" });
const tagPicker = tagsField.createDiv({ cls: "column-editor-tag-select-host" });
const tagSelect = new Compact_tag_select({
target: tagPicker,
props: {
items: this.availableColumnTags,
value: [...column.matchTags],
maxSelected: 0,
placeholder: "",
ariaLabel: `${column.label} match tags`
}
});
const onChange = tagSelect.$on("change", (event2) => {
column.matchTags = event2.detail;
updateRenameOption();
this.touchSettings();
});
this.mountedColumnControls.push(() => {
onChange();
tagSelect.$destroy();
});
}
if (usesStatusMatching(column)) {
const statusField = matchPopover.createDiv({ cls: "column-editor-popover-field column-editor-field-status" });
statusField.createDiv({ cls: "column-editor-inline-label", text: "Status" });
const statusSelect = statusField.createEl("select");
statusSelect.addClass("dropdown");
statusSelect.setAttribute("aria-label", `${column.label} known status marker`);
const markerOptions = this.getStatusMarkerOptions();
for (const option of markerOptions) {
statusSelect.createEl("option", {
value: option.value,
text: option.label
});
}
statusSelect.createEl("option", {
value: "custom",
text: "Custom"
});
const customStatusInput = statusField.createEl("input", {
type: "text",
value: column.matchStatus && column.matchStatus !== " " ? column.matchStatus : "",
placeholder: "e.g., /"
});
customStatusInput.addClass("setting-input");
customStatusInput.setAttribute("aria-label", `${column.label} custom status marker`);
customStatusInput.title = "Enter one status marker, such as / or !";
const setStatusControlValues = () => {
var _a6;
const status = (_a6 = column.matchStatus) != null ? _a6 : " ";
statusSelect.value = markerOptions.some((option) => option.value === status) ? status : "custom";
customStatusInput.value = status === " " ? "" : status;
customStatusInput.toggleClass("is-visible", statusSelect.value === "custom");
};
setStatusControlValues();
statusSelect.addEventListener("change", () => {
if (statusSelect.value !== "custom") {
column.matchStatus = statusSelect.value;
setStatusControlValues();
} else if (!column.matchStatus || column.matchStatus === " ") {
column.matchStatus = "";
customStatusInput.value = "";
customStatusInput.focus();
}
customStatusInput.toggleClass("is-visible", statusSelect.value === "custom");
updateRenameOption();
this.touchSettings();
});
customStatusInput.addEventListener("input", () => {
column.matchStatus = customStatusInput.value;
statusSelect.value = markerOptions.some((option) => option.value === column.matchStatus) ? column.matchStatus : "custom";
customStatusInput.toggleClass("is-visible", statusSelect.value === "custom");
updateRenameOption();
this.touchSettings();
});
}
if (usesPriorityMatching(column)) {
const priorityField = matchPopover.createDiv({ cls: "column-editor-popover-field column-editor-field-priority" });
priorityField.createDiv({ cls: "column-editor-inline-label", text: "Priority" });
if (this.canEditPriorityValue(column)) {
if (getColumnPrioritySchema(column) === "dataview" /* Dataview */) {
const priorityInput = priorityField.createEl("input", {
type: "text",
value: (_a5 = column.matchPriority) != null ? _a5 : "",
placeholder: "high"
});
priorityInput.addClass("column-editor-inline-input");
priorityInput.setAttribute("aria-label", `${column.label} priority`);
priorityInput.addEventListener("input", () => {
column.matchPriority = priorityInput.value;
column.matchPropertySchema = "dataview" /* Dataview */;
updateRenameOption();
this.touchSettings();
});
} else {
const prioritySelect = priorityField.createEl("select");
prioritySelect.addClass("dropdown");
prioritySelect.setAttribute("aria-label", `${column.label} priority`);
for (const option of TASKS_PRIORITY_OPTIONS) {
prioritySelect.createEl("option", {
value: option.value,
text: `${option.label} ${option.emoji}`
});
}
prioritySelect.value = (_b3 = column.matchPriority) != null ? _b3 : "medium";
prioritySelect.addEventListener("change", () => {
column.matchPriority = prioritySelect.value;
column.matchPropertySchema = "tasks" /* TasksPlugin */;
updateRenameOption();
this.touchSettings();
});
}
} else {
const schemaLabel = getColumnPrioritySchema(column) === "dataview" /* Dataview */ ? "Dataview" : "Tasks Plugin";
priorityField.createDiv({
cls: "setting-item-description",
text: `${schemaLabel}: ${getPriorityColumnLabel(column.matchPriority)}. Switch Property schema to ${schemaLabel} to edit this value.`
});
}
}
const renameOption = matchPopover.createDiv({ cls: "column-editor-rename-option" });
const renameCheckbox = renameOption.createEl("input", { type: "checkbox" });
const renameCheckboxId = `column-editor-update-${column.id}`;
renameCheckbox.id = renameCheckboxId;
const renameLabel = renameOption.createEl("label", {
text: "Update existing tasks"
});
renameLabel.htmlFor = renameCheckboxId;
updateRenameOption = () => {
const show = this.shouldShowRetagOption(column);
renameOption.style.display = show ? "flex" : "none";
renameCheckbox.checked = this.shouldUpdateExistingTaskTags(column.id);
renameCheckbox.setAttribute("aria-label", `Update existing tasks for ${column.label || "column"}`);
};
updateRenameOption();
renameCheckbox.addEventListener("change", () => {
this.updateExistingTaskTagsByColumnId.set(column.id, renameCheckbox.checked);
this.touchSettings();
});
this.mountColumnPopoverDismiss(matchPopover, summaryButton);
return updateRenameOption;
}
updateValidationBanner() {
var _a5, _b3;
if (this.headerValidationPill) {
this.headerValidationPill.setText((_a5 = this.validationError) != null ? _a5 : "");
this.headerValidationPill.toggleClass("is-visible", !!this.validationError);
this.headerValidationPill.title = (_b3 = this.validationError) != null ? _b3 : "";
}
if (this.saveBtn) this.saveBtn.disabled = !!this.validationError;
}
updateDirtyBanner() {
if (this.headerDirtyPill) {
const isDirty2 = this.isDirty();
this.headerDirtyPill.setText(isDirty2 ? "Unsaved changes" : "");
this.headerDirtyPill.toggleClass("is-visible", isDirty2);
}
this.overrideChipUpdaters = this.overrideChipUpdaters.filter((update2) => update2());
this.scheduleEmbeddedSubmit();
}
onOpen() {
var _a5;
if (this.isEmbedded()) {
this.contentEl.addClass("task-list-kanban-settings-inline");
} else {
this.modalEl.addClass("task-list-kanban-settings-modal-container");
this.contentEl.addClass("task-list-kanban-settings-modal");
}
this.scrollWrapper = this.contentEl.createDiv({ cls: "settings-scroll-wrapper" });
const header = this.scrollWrapper.createDiv({ cls: "settings-header" });
header.createEl(this.isEmbedded() ? "h2" : "h1", { text: (_a5 = this.options.title) != null ? _a5 : "Settings" });
const headerStatus = header.createDiv({ cls: "settings-header-status" });
this.headerValidationPill = headerStatus.createDiv({ cls: "settings-status-pill settings-status-pill-validation" });
this.headerDirtyPill = headerStatus.createDiv({ cls: "settings-status-pill settings-status-pill-dirty" });
const settingsBody = this.scrollWrapper.createDiv({
cls: this.isEmbedded() ? "settings-body settings-body-inline" : "settings-body"
});
const settingsNav = this.isEmbedded() ? null : settingsBody.createDiv({ cls: "settings-nav" });
const settingsContent = settingsBody.createDiv({ cls: "settings-content" });
const createSection = (id, title, description, resetKeys) => {
const section = settingsContent.createDiv({
cls: "settings-section",
attr: { id: `settings-${id}` }
});
if (settingsNav) {
const navButton = settingsNav.createEl("button", { text: title });
navButton.type = "button";
navButton.addEventListener("click", () => {
section.scrollIntoView({ behavior: "smooth", block: "start" });
});
}
const sectionHeader = section.createDiv({ cls: "settings-section-header" });
const headerRow = sectionHeader.createDiv({ cls: "settings-section-header-row" });
headerRow.createEl("h2", { text: title });
if (resetKeys && this.overrideTrackingEnabled()) {
const resetButton = headerRow.createEl("button", {
text: "Reset to defaults",
cls: "settings-override-chip settings-section-reset"
});
resetButton.type = "button";
resetButton.title = "Reset this section's settings to the inherited defaults. Board-only settings are not changed.";
resetButton.addEventListener("click", () => this.resetOverrideKeys(resetKeys));
const update2 = () => {
if (!resetButton.isConnected) {
return false;
}
resetButton.disabled = !resetKeys.some(
(key2) => this.isEffectivelyOverridden(key2)
);
return true;
};
update2();
this.overrideChipUpdaters.push(update2);
}
sectionHeader.createEl("p", { text: description, cls: "setting-item-description" });
return section.createDiv({ cls: "settings-section-body" });
};
const columnsSection = createSection(
"columns",
"Columns",
"Board columns, column labels, matching rules, and color accents.",
[
"columns",
"uncategorizedColumnName",
"uncategorizedVisibility",
"doneColumnName",
"doneVisibility"
]
);
const taskPropertiesSection = createSection(
"task-properties",
"Task properties",
"Property parsing, card property display, and task creation defaults.",
["propertySchema", "propertyDisplay", "treatNestedTasksAsSubtasks"]
);
const scopeSection = createSection(
"scope",
"Scope",
"Choose where the board looks for tasks, then subtract paths it should ignore.",
["scope", "excludePaths"]
);
const displaySection = createSection(
"display",
"Display",
"Card metadata, filepath, and tag display behavior.",
["excludedTags", "excludedTaskTags", "showFilepath", "consolidateTags"]
);
const statusMarkersSection = createSection(
"status-markers",
"Status markers",
"Task status markers and status-specific board behavior.",
[
"statusMarkerOrder",
"doneStatusMarkers",
"cancelledStatusMarkers",
"ignoredStatusMarkers"
]
);
this.columnsEditorEl = columnsSection;
this.renderColumnsEditor();
this.validateColumns();
void this.refreshAvailableColumnTags();
this.renderTaskPropertiesSection(taskPropertiesSection);
this.renderScopeSection(scopeSection);
this.renderDisplaySection(displaySection);
this.renderStatusMarkersSection(statusMarkersSection);
if (!this.isEmbedded()) {
this.renderButtonBar();
}
if (this.validationError && this.saveBtn) {
this.saveBtn.disabled = true;
}
}
setDefaultTaskFileError(message) {
if (!this.defaultTaskFileInputEl) return;
if (message) {
this.defaultTaskFileInputEl.style.outline = "2px solid var(--text-error)";
this.defaultTaskFileInputEl.style.outlineOffset = "-1px";
this.defaultTaskFileInputEl.title = message;
if (this.defaultTaskFileErrorEl) {
this.defaultTaskFileErrorEl.setText(message);
this.defaultTaskFileErrorEl.style.visibility = "visible";
}
} else {
this.defaultTaskFileInputEl.style.outline = "";
this.defaultTaskFileInputEl.style.outlineOffset = "";
this.defaultTaskFileInputEl.title = "";
if (this.defaultTaskFileErrorEl) {
this.defaultTaskFileErrorEl.setText("");
this.defaultTaskFileErrorEl.style.visibility = "hidden";
}
}
}
/** Re-checked from the scope controls too: scope decides file validity. */
validateDefaultTaskFile() {
var _a5, _b3, _c2;
if (this.isGlobalDefaultsMode()) {
this.setDefaultTaskFileError("");
return;
}
const value = (_a5 = this.settings.defaultTaskFile) != null ? _a5 : "";
if (!value) {
this.setDefaultTaskFileError("");
return;
}
const abstractFile = this.app.vault.getAbstractFileByPath(value);
if (!(abstractFile instanceof import_obsidian13.TFile)) {
this.setDefaultTaskFileError("File not found");
return;
}
const scopeFilter = this.getScopeFilter();
if (!shouldIncludeFilePath(value, scopeFilter, (_b3 = this.settings.excludePaths) != null ? _b3 : [], this.boardFolderPath)) {
const excludePaths = (_c2 = this.settings.excludePaths) != null ? _c2 : [];
const isExcludedByPath = excludePaths.length > 0 && shouldIncludeFilePath(value, scopeFilter) && !shouldIncludeFilePath(value, scopeFilter, excludePaths, this.boardFolderPath);
this.setDefaultTaskFileError(
isExcludedByPath ? "File is excluded from the board's scope" : "File is outside the board's folder scope"
);
return;
}
this.setDefaultTaskFileError("");
}
renderTaskPropertiesSection(container) {
new import_obsidian13.Setting(container).setName("Property schema").setDesc("Which format to use for extracting task properties.").addDropdown((dropdown) => {
var _a5;
dropdown.addOption("none" /* None */, "None").addOption("tasks" /* TasksPlugin */, "Tasks Plugin").addOption("dataview" /* Dataview */, "Dataview").setValue((_a5 = this.settings.propertySchema) != null ? _a5 : "none" /* None */).onChange((value) => {
this.settings.propertySchema = value;
this.updateDirtyBanner();
});
}).then((setting) => this.createOverrideChip(setting.nameEl, ["propertySchema"]));
new import_obsidian13.Setting(container).setName("Show properties").setDesc(
'How parsed property values are displayed below task text. "Pretty" shows formatted values; "Debug (JSON)" shows the raw parsed data.'
).addDropdown((dropdown) => {
var _a5;
dropdown.addOption("none" /* None */, "None").addOption("pretty" /* Pretty */, "Pretty").addOption("debug" /* Debug */, "Debug (JSON)").setValue((_a5 = this.settings.propertyDisplay) != null ? _a5 : "none" /* None */).onChange((value) => {
this.settings.propertyDisplay = value;
this.updateDirtyBanner();
});
}).then((setting) => this.createOverrideChip(setting.nameEl, ["propertyDisplay"]));
new import_obsidian13.Setting(container).setName("Treat nested tasks as subtasks").setDesc("Display nested task rows inside their root task card instead of as separate cards.").addToggle((toggle) => {
var _a5;
toggle.setValue((_a5 = this.settings.treatNestedTasksAsSubtasks) != null ? _a5 : false).onChange((value) => {
this.settings.treatNestedTasksAsSubtasks = value;
this.updateDirtyBanner();
});
}).then(
(setting) => this.createOverrideChip(setting.nameEl, ["treatNestedTasksAsSubtasks"])
);
if (!this.isGlobalDefaultsMode()) {
const defaultTaskFileSetting = new import_obsidian13.Setting(container).setName("Default task file").setDesc(
"New tasks from 'Add new' will be created in this file by default. Use the vault-relative path (e.g., 'folder/tasks.md'). Leave empty to always show the full file picker."
).addText((text2) => {
var _a5;
this.defaultTaskFileInputEl = text2.inputEl;
text2.setPlaceholder("e.g., notes/tasks.md");
text2.setValue((_a5 = this.settings.defaultTaskFile) != null ? _a5 : "");
text2.onChange((value) => {
this.settings.defaultTaskFile = value;
this.validateDefaultTaskFile();
this.updateDirtyBanner();
});
new FileSuggest(this.app, text2.inputEl);
});
defaultTaskFileSetting.controlEl.style.flexDirection = "column";
defaultTaskFileSetting.controlEl.style.alignItems = "flex-end";
const errorEl = createEl("div", {
cls: "setting-error-message"
});
errorEl.style.color = "var(--text-error)";
errorEl.style.fontSize = "var(--font-smallest)";
errorEl.style.fontStyle = "italic";
errorEl.style.marginTop = "4px";
errorEl.style.minHeight = "1.2em";
errorEl.style.visibility = "hidden";
defaultTaskFileSetting.controlEl.appendChild(errorEl);
this.defaultTaskFileErrorEl = errorEl;
this.validateDefaultTaskFile();
}
}
renderScopeSection(scopeSection) {
const scopeContainer = scopeSection.createDiv();
let folderListContainer = null;
const updateFolderListVisibility = () => {
if (!folderListContainer) return;
folderListContainer.style.display = this.settings.scope === "selectedFolders" /* SelectedFolders */ ? "block" : "none";
};
new import_obsidian13.Setting(scopeContainer).setName("Included folders").setDesc("Folders the board searches for tasks. The board's own folder is always included.").addDropdown((dropdown) => {
dropdown.addOption("folder" /* Folder */, "Same as board folder");
dropdown.addOption("everywhere" /* Everywhere */, "Every folder");
dropdown.addOption(
"selectedFolders" /* SelectedFolders */,
this.isGlobalDefaultsMode() ? "Selected folders (configured per board)" : "Selected folders"
);
dropdown.setValue(this.settings.scope);
dropdown.onChange((value) => {
const validatedValue = ScopeOptionSchema.safeParse(value);
this.settings.scope = validatedValue.success ? validatedValue.data : defaultSettings.scope;
updateFolderListVisibility();
this.validateDefaultTaskFile();
this.updateDirtyBanner();
});
}).then((setting) => this.createOverrideChip(setting.nameEl, ["scope"]));
if (this.isGlobalDefaultsMode()) {
scopeContainer.createEl("p", {
text: "Selected folder paths stay board-local. The global default only chooses the scope mode.",
cls: "setting-item-description"
});
} else {
folderListContainer = scopeContainer.createDiv({
cls: "settings-list-indent settings-list-block"
});
this.createStringListEditor(folderListContainer, {
placeholder: "e.g., projects/active",
normalize: normalizePathInput,
// The board's own folder is already included implicitly.
reject: (value) => value === this.boardFolderPath,
getItems: () => {
var _a5;
return (_a5 = this.settings.scopeFolders) != null ? _a5 : [];
},
setItems: (items) => {
this.settings.scopeFolders = items;
},
renderItems: () => {
var _a5;
return ((_a5 = this.settings.scopeFolders) != null ? _a5 : []).filter(
(folder) => folder !== this.boardFolderPath
);
},
createSuggest: (inputEl, commit) => {
new FolderSuggest(this.app, inputEl, commit);
},
onChanged: () => {
this.validateDefaultTaskFile();
this.updateDirtyBanner();
},
removeStyle: "icon",
warnWhenMissingFromVault: true,
pinnedRow: this.boardFolderPath ? { label: this.boardFolderPath, badge: " (this board)" } : void 0
});
updateFolderListVisibility();
}
const excludeContainer = scopeSection.createDiv({ cls: "settings-subsection" });
new import_obsidian13.Setting(excludeContainer).setName("Excluded paths").setDesc(
"Folders and files the board skips after included folders are chosen."
).then((setting) => this.createOverrideChip(setting.nameEl, ["excludePaths"]));
const excludeInputContainer = excludeContainer.createDiv({ cls: "settings-list-indent" });
this.createStringListEditor(excludeInputContainer, {
placeholder: "e.g., templates or notes/scratch.md",
normalize: normalizePathInput,
// The board's own folder can't be excluded directly.
reject: (value) => value === this.boardFolderPath,
getItems: () => {
var _a5;
return (_a5 = this.settings.excludePaths) != null ? _a5 : [];
},
setItems: (items) => {
this.settings.excludePaths = items;
},
createSuggest: (inputEl, commit) => {
new PathSuggest(this.app, inputEl, commit);
},
onChanged: () => {
this.validateDefaultTaskFile();
this.updateDirtyBanner();
},
removeStyle: "icon",
warnWhenMissingFromVault: true
});
}
renderDisplaySection(displaySection) {
const excludedTagsContainer = displaySection.createDiv({ cls: "settings-subsection" });
new import_obsidian13.Setting(excludedTagsContainer).setName("Hidden Tags").setDesc(
"Tags to hide from display on task cards. The tasks themselves will still appear on the board."
).then((setting) => this.createOverrideChip(setting.nameEl, ["excludedTags"]));
const excludedTagsInputContainer = excludedTagsContainer.createDiv({
cls: "settings-list-indent"
});
const hiddenTagsEditor = this.createStringListEditor(excludedTagsInputContainer, {
placeholder: "e.g., status",
normalize: normalizeTagInput,
getItems: () => {
var _a5;
return (_a5 = this.settings.excludedTags) != null ? _a5 : [];
},
setItems: (items) => {
this.settings.excludedTags = items;
},
createSuggest: (inputEl, commit) => {
new TagSuggest(this.app, inputEl, commit);
},
onChanged: () => this.updateDirtyBanner(),
removeStyle: "text",
monospaceLabels: true
});
const excludeColumnTagsBtn = hiddenTagsEditor.addRowEl.createEl("button", {
text: "Exclude column tags"
});
excludeColumnTagsBtn.title = "Automatically add all configured column placement tags to the exclusion list";
excludeColumnTagsBtn.addEventListener("click", () => {
var _a5, _b3;
const currentExcluded = new Set((_a5 = this.settings.excludedTags) != null ? _a5 : []);
for (const col of (_b3 = this.settings.columns) != null ? _b3 : []) {
const tags = getColumnWriteTags(col);
for (const tag2 of tags) {
currentExcluded.add(tag2);
}
}
this.settings.excludedTags = Array.from(currentExcluded);
hiddenTagsEditor.refresh();
this.updateDirtyBanner();
});
const excludedTaskTagsContainer = displaySection.createDiv({ cls: "settings-subsection" });
new import_obsidian13.Setting(excludedTaskTagsContainer).setName("Excluded task tags").setDesc(
"Tasks containing these tags will be completely excluded from the board."
).then((setting) => this.createOverrideChip(setting.nameEl, ["excludedTaskTags"]));
const excludedTaskTagsInputContainer = excludedTaskTagsContainer.createDiv({
cls: "settings-list-indent"
});
this.createStringListEditor(excludedTaskTagsInputContainer, {
placeholder: "e.g., archived",
normalize: normalizeTagInput,
getItems: () => {
var _a5;
return (_a5 = this.settings.excludedTaskTags) != null ? _a5 : [];
},
setItems: (items) => {
this.settings.excludedTaskTags = items;
},
createSuggest: (inputEl, commit) => {
new TagSuggest(this.app, inputEl, commit);
},
onChanged: () => this.updateDirtyBanner(),
removeStyle: "text",
monospaceLabels: true
});
new import_obsidian13.Setting(displaySection).setName("Show filepath").setDesc("Show the filepath on each task in Kanban?").addToggle((toggle) => {
var _a5;
toggle.setValue((_a5 = this.settings.showFilepath) != null ? _a5 : true);
toggle.onChange((value) => {
this.settings.showFilepath = value;
this.updateDirtyBanner();
});
}).then((setting) => this.createOverrideChip(setting.nameEl, ["showFilepath"]));
new import_obsidian13.Setting(displaySection).setName("Consolidate tags").setDesc(
"Consolidate the tags on each task in Kanban into the footer?"
).addToggle((toggle) => {
var _a5;
toggle.setValue((_a5 = this.settings.consolidateTags) != null ? _a5 : false);
toggle.onChange((value) => {
this.settings.consolidateTags = value;
this.updateDirtyBanner();
});
}).then((setting) => this.createOverrideChip(setting.nameEl, ["consolidateTags"]));
}
renderStatusMarkersSection(statusMarkersSection) {
var _a5, _b3, _c2, _d;
this.addValidatedTextSetting(statusMarkersSection, {
name: "Status marker order",
overrideKey: "statusMarkerOrder",
desc: "Ascending order for status grouping and status sorting. Unchecked tasks come first unless this order includes a literal space. Unspecified markers appear afterward alphabetically, followed by done markers.",
value: (_a5 = this.settings.statusMarkerOrder) != null ? _a5 : "",
validTitle: "Valid status marker order",
validate: validateStatusMarkerOrder,
onValid: (value) => {
this.settings.statusMarkerOrder = value;
}
});
this.addValidatedTextSetting(statusMarkersSection, {
name: "Done status markers",
overrideKey: "doneStatusMarkers",
desc: "Characters that mark a task as done (e.g., 'xX' for [x] and [X]). Each character should be a single Unicode character without spaces.",
value: (_b3 = this.settings.doneStatusMarkers) != null ? _b3 : DEFAULT_DONE_STATUS_MARKERS,
validTitle: "Valid done status markers",
validate: validateDoneStatusMarkers,
onValid: (value) => {
this.settings.doneStatusMarkers = value;
}
});
this.addValidatedTextSetting(statusMarkersSection, {
name: "Cancelled status markers",
overrideKey: "cancelledStatusMarkers",
desc: "Characters that mark a task as cancelled (e.g., '-' for [-]). Each character should be a single Unicode character without spaces.",
value: (_c2 = this.settings.cancelledStatusMarkers) != null ? _c2 : DEFAULT_CANCELLED_STATUS_MARKERS,
validTitle: "Valid cancelled status markers",
validate: validateCancelledStatusMarkers,
onValid: (value) => {
this.settings.cancelledStatusMarkers = value;
}
});
this.addValidatedTextSetting(statusMarkersSection, {
name: "Ignored status markers",
overrideKey: "ignoredStatusMarkers",
desc: "Characters that mark tasks to be completely ignored by the kanban (e.g., '-' for [-] cancelled tasks). Leave empty to process all task-like strings. Each character should be a single Unicode character without spaces.",
value: (_d = this.settings.ignoredStatusMarkers) != null ? _d : DEFAULT_IGNORED_STATUS_MARKERS,
validTitle: "Valid ignored status markers",
validate: validateIgnoredStatusMarkers,
onValid: (value) => {
this.settings.ignoredStatusMarkers = value;
}
});
}
renderButtonBar() {
const buttonBar = this.contentEl.createDiv({ cls: "settings-button-bar" });
const cancelBtn = buttonBar.createEl("button", { text: "Cancel" });
cancelBtn.addEventListener("click", () => {
this.close();
});
this.saveBtn = buttonBar.createEl("button", { text: "Save", cls: "mod-cta" });
this.saveBtn.addEventListener("click", async () => {
if (this.saveBtn) {
this.saveBtn.disabled = true;
}
try {
await this.onSubmit(this.settings, {
updateExistingTaskTagsByColumnId: Object.fromEntries(this.updateExistingTaskTagsByColumnId),
...this.overrideLifecycleOptions()
});
this.close();
} finally {
if (this.saveBtn) {
this.saveBtn.disabled = false;
}
}
});
}
onClose() {
if (this.embeddedSubmitTimer) {
clearTimeout(this.embeddedSubmitTimer);
this.embeddedSubmitTimer = null;
}
for (const destroy of this.mountedColumnControls) {
destroy();
}
this.mountedColumnControls = [];
this.contentEl.empty();
}
getScopeFilter() {
return resolveScopeFilter(this.settings.scope, this.settings.scopeFolders, this.boardFolderPath);
}
};
// src/ui/tasks/store.ts
var import_obsidian16 = require("obsidian");
// src/ui/tasks/tasks.ts
function getMarkerSettings(settings) {
var _a5, _b3, _c2, _d, _e, _f, _g;
return {
consolidateTags: (_a5 = settings.consolidateTags) != null ? _a5 : false,
doneStatusMarkers: (_b3 = settings.doneStatusMarkers) != null ? _b3 : DEFAULT_DONE_STATUS_MARKERS,
cancelledStatusMarkers: (_c2 = settings.cancelledStatusMarkers) != null ? _c2 : DEFAULT_CANCELLED_STATUS_MARKERS,
ignoredStatusMarkers: (_d = settings.ignoredStatusMarkers) != null ? _d : DEFAULT_IGNORED_STATUS_MARKERS,
excludedTaskTags: new Set(
((_e = settings.excludedTaskTags) != null ? _e : []).map((t) => t.trim().toLowerCase())
),
propertySchema: getSchemaImpl((_f = settings.propertySchema) != null ? _f : "none" /* None */),
treatNestedTasksAsSubtasks: (_g = settings.treatNestedTasksAsSubtasks) != null ? _g : false
};
}
async function updateMapsFromFile({
fileHandle,
taskIdsByFileHandle,
tasksByTaskId,
metadataByTaskId,
vault,
columnDefinitionsStore,
columnPlacementTagTableStore,
consolidateTags,
doneStatusMarkers,
cancelledStatusMarkers,
ignoredStatusMarkers,
excludedTaskTags,
propertySchema,
treatNestedTasksAsSubtasks
}) {
var _a5;
try {
const previousTaskIds = (_a5 = taskIdsByFileHandle.get(fileHandle)) != null ? _a5 : /* @__PURE__ */ new Set();
const newTaskIds = /* @__PURE__ */ new Set();
const contents = await vault.read(fileHandle);
const rows = contents.split("\n");
const columnDefinitions = get2(columnDefinitionsStore);
const columnPlacementTagTable = get2(columnPlacementTagTableStore);
const parseContext = {
columnDefinitions,
columnPlacementTagTable,
consolidateTags,
doneStatusMarkers,
cancelledStatusMarkers,
ignoredStatusMarkers,
propertySchema
};
if (treatNestedTasksAsSubtasks) {
const { nodesByRowIndex, parentByRowIndex } = buildSourceTree({
rows,
fileHandle,
parseContext,
excludedTaskTags
});
for (const node of nodesByRowIndex.values()) {
if (node.kind !== "task" || node.taskVisibility !== "visible" || hasVisibleTaskAncestor(node, parentByRowIndex)) {
continue;
}
const task = new Task(
node.rawLine,
fileHandle,
node.rowIndex,
parseContext,
node.sourceChildren
);
cacheParsedTask({
task,
rowIndex: node.rowIndex,
fileHandle,
tasksByTaskId,
metadataByTaskId,
newTaskIds
});
previousTaskIds.delete(task.id);
}
for (const prevId of previousTaskIds) {
tasksByTaskId.delete(prevId);
metadataByTaskId.delete(prevId);
}
taskIdsByFileHandle.set(fileHandle, newTaskIds);
return;
}
for (let i = 0; i < rows.length; i++) {
const row = rows[i];
if (!row) {
continue;
}
if (isTrackedTaskString(row, ignoredStatusMarkers)) {
const task = new Task(
row,
fileHandle,
i,
parseContext
);
const hasExcludedTag = Array.from(task.tags).some(
(tag2) => excludedTaskTags.has(tag2.trim().toLowerCase())
);
if (!hasExcludedTag) {
cacheParsedTask({
task,
rowIndex: i,
fileHandle,
tasksByTaskId,
metadataByTaskId,
newTaskIds
});
previousTaskIds.delete(task.id);
}
}
}
for (const prevId of previousTaskIds) {
tasksByTaskId.delete(prevId);
metadataByTaskId.delete(prevId);
}
taskIdsByFileHandle.set(fileHandle, newTaskIds);
} catch (error) {
console.error(`Failed to update task cache for ${fileHandle.path}`, error);
}
}
function cacheParsedTask({
task,
rowIndex,
fileHandle,
tasksByTaskId,
metadataByTaskId,
newTaskIds
}) {
newTaskIds.add(task.id);
tasksByTaskId.set(task.id, task);
metadataByTaskId.set(task.id, { rowIndex, fileHandle });
}
function buildSourceTree({
rows,
fileHandle,
parseContext,
excludedTaskTags
}) {
var _a5;
const nodesByRowIndex = /* @__PURE__ */ new Map();
const parentByRowIndex = /* @__PURE__ */ new Map();
const stack2 = [];
for (let rowIndex = 0; rowIndex < rows.length; rowIndex++) {
const rawLine = (_a5 = rows[rowIndex]) != null ? _a5 : "";
if (rawLine === "") {
stack2.length = 0;
continue;
}
const node = createSourceNode({
rawLine,
rowIndex,
fileHandle,
parseContext,
excludedTaskTags
});
nodesByRowIndex.set(rowIndex, node);
while (stack2.length > 0 && !isSourceDescendant(node.indentation, stack2[stack2.length - 1].indentation)) {
stack2.pop();
}
const parent = stack2[stack2.length - 1];
if (parent) {
parent.sourceChildren.push(node);
parentByRowIndex.set(rowIndex, parent);
}
stack2.push(node);
}
return { nodesByRowIndex, parentByRowIndex };
}
function createSourceNode({
rawLine,
rowIndex,
fileHandle,
parseContext,
excludedTaskTags
}) {
const parsedTaskLine = parseSourceTaskLine(rawLine);
if (!parsedTaskLine) {
return createRawNode(rawLine, rowIndex);
}
if (!isTrackedTaskString(rawLine, parseContext.ignoredStatusMarkers)) {
return {
kind: "task",
taskVisibility: "ignored",
rowIndex,
rawLine,
indentation: parsedTaskLine.indentation,
status: parsedTaskLine.status || " ",
content: parsedTaskLine.content,
sourceChildren: []
};
}
const task = new Task(
rawLine,
fileHandle,
rowIndex,
parseContext
);
const hasExcludedTag = Array.from(task.tags).some(
(tag2) => excludedTaskTags.has(tag2.trim().toLowerCase())
);
return {
kind: "task",
taskVisibility: hasExcludedTag ? "ignored" : "visible",
rowIndex,
rawLine,
indentation: parsedTaskLine.indentation,
status: parsedTaskLine.status || " ",
content: parsedTaskLine.content,
sourceChildren: []
};
}
function createRawNode(rawLine, rowIndex) {
var _a5, _b3;
return {
kind: "raw",
rowIndex,
rawLine,
indentation: (_b3 = (_a5 = rawLine.match(/^\s*/)) == null ? void 0 : _a5[0]) != null ? _b3 : "",
sourceChildren: []
};
}
function isSourceDescendant(indentation, ancestorIndentation) {
return indentation.length > ancestorIndentation.length && indentation.startsWith(ancestorIndentation);
}
function hasVisibleTaskAncestor(node, parentByRowIndex) {
let parent = parentByRowIndex.get(node.rowIndex);
while (parent) {
if (parent.kind === "task" && parent.taskVisibility === "visible") {
return true;
}
parent = parentByRowIndex.get(parent.rowIndex);
}
return false;
}
// src/ui/tasks/actions.ts
var import_obsidian15 = require("obsidian");
// src/ui/tasks/duplicate.ts
var blockLinkRegexp3 = /\s\^[a-zA-Z0-9-]+$/;
var checkboxRegexp = /^(\s*[-*+]\s)\[([^\[\]]*)\]/;
function createDuplicateLine(rawLine) {
return rawLine.replace(blockLinkRegexp3, "").replace(checkboxRegexp, "$1[ ]");
}
// src/ui/components/file_picker_menu.ts
var import_obsidian14 = require("obsidian");
function showFilePickerMenu({
files,
position,
defaultFileEntry,
onFileSelected
}) {
const folder = {};
for (const file of files) {
const segments = file.path.split("/");
let currFolder = folder;
for (const [i, segment] of segments.entries()) {
if (i === segments.length - 1) {
currFolder[segment] = file;
} else {
const nextFolder = currFolder[segment] || {};
if (nextFolder instanceof import_obsidian14.TFile) {
continue;
}
currFolder[segment] = nextFolder;
currFolder = nextFolder;
}
}
}
function createMenu(folder2, parentMenu) {
const menu = new import_obsidian14.Menu();
menu.addItem((i) => {
i.setTitle(parentMenu ? `\u2190 back` : "Choose a file").setDisabled(!parentMenu).onClick(() => {
parentMenu == null ? void 0 : parentMenu.showAtPosition(position);
});
});
if (!parentMenu && defaultFileEntry) {
if ("file" in defaultFileEntry) {
const df = defaultFileEntry.file;
menu.addItem((i) => {
i.setTitle(`\u2605 ${df.path}`).onClick(() => {
onFileSelected(df);
});
});
} else {
menu.addItem((i) => {
i.setTitle(defaultFileEntry.error).setDisabled(true);
});
}
menu.addSeparator();
}
for (const [label, folderItem] of Object.entries(folder2)) {
menu.addItem((i) => {
i.setTitle(
folderItem instanceof import_obsidian14.TFile ? label : label + " \u2192"
).onClick(() => {
if (folderItem instanceof import_obsidian14.TFile) {
onFileSelected(folderItem);
} else {
createMenu(folderItem, menu);
}
});
});
}
menu.showAtPosition(position);
}
createMenu(folder, void 0);
}
// src/ui/tasks/source_line_editor.ts
async function readFileRows(vault, fileHandle) {
return (await vault.read(fileHandle)).split("\n");
}
async function writeFileRows(vault, fileHandle, rows, prepareFileContentsForWrite) {
const nextContents = rows.join("\n");
await vault.modify(
fileHandle,
prepareFileContentsForWrite ? prepareFileContentsForWrite(fileHandle, nextContents) : nextContents
);
}
async function transformSourceRows(vault, fileHandle, edits, prepareFileContentsForWrite) {
const rows = await readFileRows(vault, fileHandle);
let changed = false;
for (const { rowIndex, transform } of edits) {
const row = rows[rowIndex];
if (row == null) {
continue;
}
const nextRow = transform(row);
if (nextRow !== row) {
rows[rowIndex] = nextRow;
changed = true;
}
}
if (changed) {
await writeFileRows(vault, fileHandle, rows, prepareFileContentsForWrite);
}
return changed;
}
async function updateRow(vault, fileHandle, row, newText, prepareFileContentsForWrite) {
const rows = await readFileRows(vault, fileHandle);
const rowIndex = row != null ? row : rows.length;
if (rows.length < rowIndex) {
return false;
}
if (newText === "") {
rows.splice(rowIndex, 1);
} else {
rows[rowIndex] = newText;
}
await writeFileRows(vault, fileHandle, rows, prepareFileContentsForWrite);
return true;
}
async function deleteRowBlocks(vault, fileHandle, blocks, prepareFileContentsForWrite) {
const rows = await readFileRows(vault, fileHandle);
for (const block2 of [...blocks].sort((a, b) => b.rowIndex - a.rowIndex)) {
if (block2.rowIndex < rows.length && block2.lineCount > 0) {
rows.splice(block2.rowIndex, block2.lineCount);
}
}
await writeFileRows(vault, fileHandle, rows, prepareFileContentsForWrite);
}
// src/ui/tasks/task_creation.ts
function createTaskLine(content, placementTags, additionalTags = [], status = " ") {
const seenTags = /* @__PURE__ */ new Set();
const appendedTags = [];
for (const tag2 of [...placementTags, ...additionalTags]) {
const normalizedTag = tag2.trim().replace(/^#/, "");
if (!normalizedTag) continue;
const key2 = normalizedTag.toLowerCase();
if (seenTags.has(key2)) continue;
seenTags.add(key2);
appendedTags.push(normalizedTag);
}
return `- [${status}] ${content}${appendedTags.map((tag2) => ` #${tag2}`).join("")}`;
}
// src/ui/tasks/task_line_builder.ts
function buildNewTaskLine({
content,
column,
columnDefinitions,
getPlacementTagsForColumn,
propertySchemaOption,
additionalTags = [],
dateProperties = {}
}) {
var _a5, _b3;
const columnDefinition = column === "uncategorised" || column === "done" ? void 0 : columnDefinitions.find((definition) => definition.id === column);
const adapter = getPropertyWriteAdapter(propertySchemaOption);
const priorityAdapter = getPropertyWriteAdapter(
(_a5 = getColumnPrioritySchema(columnDefinition)) != null ? _a5 : propertySchemaOption
);
let taskLine = createTaskLine(
content,
column === "uncategorised" || column === "done" ? [] : getPlacementTagsForColumn(column),
additionalTags,
column === "done" ? "x" : (_b3 = getColumnStatus(columnDefinition)) != null ? _b3 : " "
);
const priority = getColumnPriority(columnDefinition);
if (priority && priorityAdapter) {
taskLine = priorityAdapter.upsertPriority(taskLine, priority);
}
if (adapter) {
for (const key2 of ["due", "scheduled", "start"]) {
const date = dateProperties[key2];
if (date) {
taskLine = adapter.upsertDate(taskLine, key2, date);
}
}
}
return taskLine;
}
// src/ui/tasks/actions.ts
function createTaskActions({
tasksByTaskId,
metadataByTaskId,
vault,
workspace,
getFilenameFilter,
getExcludeFilter,
getBoardFolderPath,
getPlacementTagsForColumn,
getColumnDefinitions,
getDefaultTaskFile,
getLastUsedTaskFile,
setLastUsedTaskFile,
getPropertySchemaOption,
getStatusMarkerOrder,
getCurrentDate,
getManualOrder,
setManualOrder,
prepareFileContentsForWrite
}) {
function resolveFileIfValid(filePath) {
if (!filePath) return null;
const abstractFile = vault.getAbstractFileByPath(filePath);
if (!(abstractFile instanceof import_obsidian15.TFile)) return null;
if (!shouldIncludeFilePath(filePath, getFilenameFilter(), getExcludeFilter(), getBoardFolderPath())) return null;
return abstractFile;
}
function getTargetFile() {
var _a5;
return (_a5 = resolveFileIfValid(getDefaultTaskFile())) != null ? _a5 : resolveFileIfValid(getLastUsedTaskFile());
}
function collectTaskEntriesByFile(ids) {
var _a5;
const byFile = /* @__PURE__ */ new Map();
for (const id of ids) {
const entry = getTaskWithMetadata(id);
if (!entry) continue;
const list = (_a5 = byFile.get(entry.metadata.fileHandle)) != null ? _a5 : [];
list.push(entry);
byFile.set(entry.metadata.fileHandle, list);
}
return byFile;
}
function notifyMissingTasks(requestedCount, foundCount) {
if (foundCount >= requestedCount) return;
const missing = requestedCount - foundCount;
new import_obsidian15.Notice(
missing === 1 ? "A task could not be updated because it is out of sync with its file." : `${missing} tasks could not be updated because they are out of sync with their files.`
);
}
async function rewriteTaskRows(ids, updater, transformSerialized) {
const entriesByFile = collectTaskEntriesByFile(ids);
notifyMissingTasks(
ids.length,
Array.from(entriesByFile.values()).reduce((sum, entries) => sum + entries.length, 0)
);
for (const [fileHandle, entries] of entriesByFile) {
const edits = entries.map(({ task, metadata }) => {
updater(task);
const serialized = task.serialise();
const newRow = transformSerialized ? transformSerialized(serialized) : serialized;
return { rowIndex: metadata.rowIndex, transform: () => newRow };
});
await transformSourceRows(vault, fileHandle, edits, prepareFileContentsForWrite);
}
}
async function editTaskSourceRows(ids, transform) {
var _a5;
const byFile = /* @__PURE__ */ new Map();
let foundCount = 0;
for (const id of ids) {
const metadata = metadataByTaskId.get(id);
if (!metadata) continue;
foundCount += 1;
const list = (_a5 = byFile.get(metadata.fileHandle)) != null ? _a5 : [];
list.push(metadata);
byFile.set(metadata.fileHandle, list);
}
notifyMissingTasks(ids.length, foundCount);
for (const [fileHandle, fileMetadata] of byFile) {
await transformSourceRows(
vault,
fileHandle,
fileMetadata.map(({ rowIndex }) => ({ rowIndex, transform })),
prepareFileContentsForWrite
);
}
}
function getTaskWithMetadata(id) {
const metadata = metadataByTaskId.get(id);
const task = tasksByTaskId.get(id);
return task && metadata ? { task, metadata } : null;
}
async function assignBlockLinks(tasks) {
var _a5;
const resolved = /* @__PURE__ */ new Map();
const needsAssignment = [];
for (const task of tasks) {
if (task.blockLink) {
resolved.set(task.id, task.blockLink);
continue;
}
const metadata = metadataByTaskId.get(task.id);
if (metadata) {
needsAssignment.push({ task, metadata });
}
}
if (needsAssignment.length === 0) {
return resolved;
}
const byFile = /* @__PURE__ */ new Map();
for (const entry of needsAssignment) {
const list = (_a5 = byFile.get(entry.metadata.fileHandle)) != null ? _a5 : [];
list.push(entry);
byFile.set(entry.metadata.fileHandle, list);
}
for (const [fileHandle, entries] of byFile) {
const rows = await readFileRows(vault, fileHandle);
const existing = /* @__PURE__ */ new Set();
for (const row of rows) {
const match = row.match(/\s\^([a-zA-Z0-9-]+)\s*$/);
if (match == null ? void 0 : match[1]) existing.add(match[1]);
}
let changed = false;
for (const { task, metadata } of entries) {
const row = rows[metadata.rowIndex];
if (row == null) continue;
const ensured = ensureRowBlockLink(row, existing);
rows[metadata.rowIndex] = ensured.row;
changed = changed || ensured.changed;
resolved.set(task.id, ensured.blockLink);
}
if (changed) {
await writeFileRows(vault, fileHandle, rows, prepareFileContentsForWrite);
}
}
return resolved;
}
return {
async changeColumn(id, column) {
await rewriteTaskRows([id], (task) => task.column = column);
},
async moveTasksToColumn(ids, column) {
if (column === "done") {
let shouldAddCompletionDate = false;
await rewriteTaskRows(
ids,
(task) => {
shouldAddCompletionDate = !task.done;
task.done = true;
},
(row) => shouldAddCompletionDate ? addCompletionDateIfEnabled(row) : row
);
} else {
await rewriteTaskRows(ids, (task) => task.column = column);
}
},
async reorderTask(groupId, columnTag, displayOrderIds, draggedId, targetIndex) {
var _a5;
const displayOrder = displayOrderIds.map((id) => tasksByTaskId.get(id)).filter((task) => !!task);
const plan = computeDropPlan(displayOrder, draggedId, targetIndex);
if (plan.prefixTasks.length === 0) {
return;
}
const resolved = await assignBlockLinks(plan.tasksNeedingBlockLink);
const entries = buildOrderEntries(plan.prefixTasks, (task) => {
var _a6;
const link2 = (_a6 = task.blockLink) != null ? _a6 : resolved.get(task.id);
if (!link2) {
return task.id;
}
return link2;
});
const current = getManualOrder();
setManualOrder({
...current,
[groupId]: {
...(_a5 = current[groupId]) != null ? _a5 : {},
[columnTag]: entries
}
});
},
async unpinTask(groupId, columnTag, taskId) {
const task = tasksByTaskId.get(taskId);
if (!task) return;
const key2 = taskKey(task);
if (!key2) return;
const current = getManualOrder();
const groupEntries = current[groupId];
const entries = groupEntries == null ? void 0 : groupEntries[columnTag];
const next2 = removeEntry(entries, key2);
if (next2 === entries) return;
const nextStore = { ...current };
const nextGroup = { ...groupEntries != null ? groupEntries : {} };
if (next2.length === 0) {
delete nextGroup[columnTag];
} else {
nextGroup[columnTag] = next2;
}
if (Object.keys(nextGroup).length === 0) {
delete nextStore[groupId];
} else {
nextStore[groupId] = nextGroup;
}
setManualOrder(nextStore);
},
pruneManualOrder(presentKeysByGroupAndColumn) {
var _a5, _b3;
const current = getManualOrder();
let changed = false;
const next2 = { ...current };
for (const [groupId, entriesByColumn] of Object.entries(current)) {
const presentByColumn = (_a5 = presentKeysByGroupAndColumn[groupId]) != null ? _a5 : {};
const nextGroup = { ...entriesByColumn };
for (const [columnTag, entries] of Object.entries(entriesByColumn)) {
const present = (_b3 = presentByColumn[columnTag]) != null ? _b3 : /* @__PURE__ */ new Set();
const pruned = entries.filter((entry) => present.has(entry));
if (pruned.length !== entries.length) {
changed = true;
if (pruned.length === 0) {
delete nextGroup[columnTag];
} else {
nextGroup[columnTag] = pruned;
}
}
}
if (Object.keys(nextGroup).length === 0) {
changed = true;
delete next2[groupId];
} else {
next2[groupId] = nextGroup;
}
}
if (changed) {
setManualOrder(next2);
}
},
async markDone(id) {
let shouldAddCompletionDate = false;
await rewriteTaskRows(
[id],
(task) => {
shouldAddCompletionDate = !task.done;
task.done = true;
},
(row) => shouldAddCompletionDate ? addCompletionDateIfEnabled(row) : row
);
},
async toggleDone(id) {
let shouldAddCompletionDate = false;
await rewriteTaskRows(
[id],
(task) => {
shouldAddCompletionDate = task.cycleStatus(getStatusMarkerOrder());
},
(row) => shouldAddCompletionDate ? addCompletionDateIfEnabled(row) : row
);
},
async updateContent(id, content) {
await rewriteTaskRows([id], (task) => task.content = content);
},
async updateSourceBlockRow(id, rowIndex, content) {
const entry = getTaskWithMetadata(id);
if (!entry) {
return;
}
const nextRow = entry.task.updateSourceBlockRowContent(rowIndex, content);
if (nextRow == null) {
return;
}
await updateRow(vault, entry.metadata.fileHandle, rowIndex, nextRow, prepareFileContentsForWrite);
},
async toggleSourceTaskStatus(id, rowIndex) {
const entry = getTaskWithMetadata(id);
if (!entry) {
return;
}
const nextRow = entry.task.cycleSourceTaskRowStatus(rowIndex, getStatusMarkerOrder());
if (nextRow == null) {
return;
}
await updateRow(vault, entry.metadata.fileHandle, rowIndex, nextRow, prepareFileContentsForWrite);
},
async addSourceBlockRow(id, rowIndex, location, kind) {
const entry = getTaskWithMetadata(id);
if (!entry) {
return;
}
const { fileHandle } = entry.metadata;
const rows = await readFileRows(vault, fileHandle);
const row = rows[rowIndex];
if (row == null) {
return;
}
const block2 = getNodeBlock(rows, rowIndex);
let targetIndex = block2.start;
let indentation = block2.indentation;
if (location === "child") {
targetIndex = block2.end;
indentation = block2.indentation + detectIndentationStep(rows);
} else {
targetIndex = block2.end;
}
let bullet = "-";
const bulletMatch = row.match(/^(\s*)([-*+])/);
if (bulletMatch == null ? void 0 : bulletMatch[2]) {
bullet = bulletMatch[2];
}
const text2 = kind === "task" ? "New subtask" : "New note";
const newLine = kind === "task" ? `${indentation}${bullet} [ ] ${text2}` : `${indentation}${bullet} ${text2}`;
rows.splice(targetIndex, 0, newLine);
await writeFileRows(vault, fileHandle, rows, prepareFileContentsForWrite);
},
async deleteSourceBlockRow(id, rowIndex) {
const entry = getTaskWithMetadata(id);
if (!entry) {
return;
}
const { fileHandle } = entry.metadata;
const rows = await readFileRows(vault, fileHandle);
const block2 = getNodeBlock(rows, rowIndex);
rows.splice(block2.start, block2.end - block2.start);
await writeFileRows(vault, fileHandle, rows, prepareFileContentsForWrite);
},
async moveSourceBlockRow(id, draggedRowIndex, targetRowIndex, position, targetDepth) {
var _a5, _b3;
const entry = getTaskWithMetadata(id);
if (!entry) {
return;
}
const { fileHandle } = entry.metadata;
const rows = await readFileRows(vault, fileHandle);
const draggedBlock = getNodeBlock(rows, draggedRowIndex);
const parentCardRow = rows[entry.task.rowIndex];
if (parentCardRow == null) {
return;
}
const parentCardIndentation = (_b3 = (_a5 = parentCardRow.match(/^\s*/)) == null ? void 0 : _a5[0]) != null ? _b3 : "";
const stepChar = detectIndentationStep(rows);
const safeTargetDepth = Math.max(1, targetDepth);
const newRootIndentation = parentCardIndentation + stepChar.repeat(safeTargetDepth);
const blockRows = rows.slice(draggedBlock.start, draggedBlock.end).map((row) => {
var _a6, _b4;
if (row == null) return "";
const rowIndentation = (_b4 = (_a6 = row.match(/^\s*/)) == null ? void 0 : _a6[0]) != null ? _b4 : "";
const relativeIndentation = rowIndentation.slice(draggedBlock.indentation.length);
const nextIndentation = newRootIndentation + relativeIndentation;
return nextIndentation + row.slice(rowIndentation.length);
});
const targetBlock = getNodeBlock(rows, targetRowIndex);
let insertIndex = position === "before" ? targetBlock.start : targetBlock.end;
rows.splice(draggedBlock.start, blockRows.length);
if (draggedBlock.start < insertIndex) {
insertIndex -= blockRows.length;
}
rows.splice(insertIndex, 0, ...blockRows);
await writeFileRows(vault, fileHandle, rows, prepareFileContentsForWrite);
},
async applyDateEdits(id, edits) {
if (edits.length === 0) return;
await editTaskSourceRows([id], (row) => {
const adapter = getPropertyWriteAdapter(getPropertySchemaOption());
if (!adapter) return row;
return edits.reduce(
(line, { key: key2, value }) => value ? adapter.upsertDate(line, key2, value) : adapter.removeDate(line, key2),
row
);
});
},
async archiveTasks(ids) {
await rewriteTaskRows(ids, (task) => task.archive());
},
async cancelTasks(ids) {
await rewriteTaskRows(ids, (task) => task.cancel());
},
async restoreTasks(ids) {
await rewriteTaskRows(ids, (task) => task.restore());
},
async deleteTask(id) {
const entry = getTaskWithMetadata(id);
if (!entry) {
notifyMissingTasks(1, 0);
return;
}
await deleteRowBlocks(vault, entry.metadata.fileHandle, [
{
rowIndex: entry.metadata.rowIndex,
lineCount: entry.task.sourceBlockLineCount
}
], prepareFileContentsForWrite);
},
async updateSwimlaneTag(ids, newTag, prefix, excludedTags, includeTags) {
await rewriteTaskRows(ids, (task) => {
const oldTag = getTaskTagGroupValue(
task,
{ kind: "tag-prefix", prefix, includeTags },
excludedTags
);
task.replaceTag(oldTag, newTag);
});
},
async updateSwimlaneProperty(ids, key2, value) {
const adapter = getPropertyWriteAdapter(getPropertySchemaOption());
if (!adapter) return;
const transform = createSwimlanePropertyTransform(adapter, key2, value);
if (!transform) return;
await editTaskSourceRows(ids, transform);
},
async duplicateTask(id) {
const entry = getTaskWithMetadata(id);
if (!entry) {
notifyMissingTasks(1, 0);
return;
}
const { fileHandle, rowIndex } = entry.metadata;
const rows = await readFileRows(vault, fileHandle);
if (rowIndex >= rows.length) return;
const sourceBlockRows = rows.slice(rowIndex, rowIndex + entry.task.sourceBlockLineCount);
const originalLine = sourceBlockRows[0];
if (!originalLine) return;
const duplicatedRows = [
createDuplicateLine(originalLine),
...sourceBlockRows.slice(1)
];
rows.splice(rowIndex + sourceBlockRows.length, 0, ...duplicatedRows);
await writeFileRows(vault, fileHandle, rows, prepareFileContentsForWrite);
},
async moveTasksToFile(ids, destinationFile, destinationColumn) {
var _a5;
const moves = ids.map((id) => {
const task = tasksByTaskId.get(id);
const metadata = metadataByTaskId.get(id);
return task && metadata ? { task, metadata } : null;
}).filter((move2) => !!move2).filter((move2) => move2.metadata.fileHandle.path !== destinationFile.path);
if (moves.length === 0) {
return;
}
const destinationRows = await readFileRows(vault, destinationFile);
for (const { task } of moves) {
const serializedParent = taskIsInColumn(task, destinationColumn) ? task.serialise() : task.serialiseForColumn(destinationColumn);
destinationRows.push(...task.sourceBlockRows(serializedParent));
}
await writeFileRows(vault, destinationFile, destinationRows, prepareFileContentsForWrite);
const movesBySourceFile = /* @__PURE__ */ new Map();
for (const { task, metadata } of moves) {
const sourceMoves = (_a5 = movesBySourceFile.get(metadata.fileHandle)) != null ? _a5 : [];
sourceMoves.push({
rowIndex: metadata.rowIndex,
lineCount: task.sourceBlockLineCount
});
movesBySourceFile.set(metadata.fileHandle, sourceMoves);
}
for (const [sourceFile, sourceMoves] of movesBySourceFile) {
await deleteRowBlocks(vault, sourceFile, sourceMoves, prepareFileContentsForWrite);
}
},
async viewFile(id, event2) {
const metadata = metadataByTaskId.get(id);
if (!metadata) {
new import_obsidian15.Notice("Could not open the task's file; the board may be out of sync.");
return;
}
const { fileHandle, rowIndex } = metadata;
const leaf = workspace.getLeaf(import_obsidian15.Keymap.isModEvent(event2));
await leaf.openFile(fileHandle);
const editorView = workspace.getActiveViewOfType(import_obsidian15.MarkdownView);
editorView == null ? void 0 : editorView.editor.setCursor(rowIndex);
},
getTargetFile,
pickFileForNewTask(column, e, onFileSelected, forceShowPicker = false) {
if (!forceShowPicker) {
const targetFile = getTargetFile();
if (targetFile) {
onFileSelected(targetFile);
return;
}
}
const onFileSelectedWithPersist = (file) => {
setLastUsedTaskFile(file.path);
onFileSelected(file);
};
const files = vault.getMarkdownFiles().filter(
(file) => shouldIncludeFilePath(file.path, getFilenameFilter(), getExcludeFilter(), getBoardFolderPath())
).sort((a, b) => a.path.localeCompare(b.path));
const target = e.target;
if (!target) {
return;
}
const boundingRect = target.getBoundingClientRect();
const y = boundingRect.top + boundingRect.height / 2;
const x = boundingRect.left + boundingRect.width / 2;
const defaultTaskFilePath = getDefaultTaskFile();
let defaultFileEntry = null;
if (defaultTaskFilePath) {
const abstractFile = vault.getAbstractFileByPath(defaultTaskFilePath);
if (!(abstractFile instanceof import_obsidian15.TFile)) {
defaultFileEntry = {
error: `\u2605 ${defaultTaskFilePath} (not found)`
};
} else if (!shouldIncludeFilePath(
defaultTaskFilePath,
getFilenameFilter(),
getExcludeFilter(),
getBoardFolderPath()
)) {
defaultFileEntry = {
error: `\u2605 ${defaultTaskFilePath} (outside scope)`
};
} else {
defaultFileEntry = { file: abstractFile };
}
}
showFilePickerMenu({
files,
position: { x, y },
defaultFileEntry,
onFileSelected: onFileSelectedWithPersist
});
},
async createTask(file, content, column, additionalTags = [], dateProperties = {}) {
const taskLine = buildNewTaskLine({
content,
column,
columnDefinitions: getColumnDefinitions(),
getPlacementTagsForColumn,
propertySchemaOption: getPropertySchemaOption(),
additionalTags,
dateProperties
});
await updateRow(
vault,
file,
void 0,
taskLine,
prepareFileContentsForWrite
);
}
};
function addCompletionDateIfEnabled(rawLine) {
var _a5;
const adapter = getPropertyWriteAdapter(getPropertySchemaOption());
if (!adapter) {
return rawLine;
}
return adapter.addCompletionDateIfMissing(rawLine, formatLocalDate((_a5 = getCurrentDate == null ? void 0 : getCurrentDate()) != null ? _a5 : /* @__PURE__ */ new Date()));
}
}
function taskIsInColumn(task, column) {
if (column === "done") {
return task.done || task.column === "done";
}
if (column === "uncategorised") {
return !task.done && !task.column;
}
return task.column === column;
}
function detectIndentationStep(rows) {
for (const row of rows) {
if (!row) continue;
const match = row.match(/^(\s+)/);
if (match == null ? void 0 : match[1]) {
return match[1].includes(" ") ? " " : " ";
}
}
return " ";
}
function getNodeBlock(rows, rowIndex) {
var _a5, _b3, _c2, _d;
const rootRow = rows[rowIndex];
if (rootRow == null) return { start: rowIndex, end: rowIndex, indentation: "" };
const indentation = (_b3 = (_a5 = rootRow.match(/^\s*/)) == null ? void 0 : _a5[0]) != null ? _b3 : "";
let end = rowIndex + 1;
while (end < rows.length) {
const row = rows[end];
if (row == null || row === "") {
break;
}
const rowIndentation = (_d = (_c2 = row.match(/^\s*/)) == null ? void 0 : _c2[0]) != null ? _d : "";
if (!rowIndentation.startsWith(indentation) || rowIndentation.length <= indentation.length) {
break;
}
end++;
}
return { start: rowIndex, end, indentation };
}
// src/ui/tasks/store.ts
function createTasksStore(vault, workspace, registerEvent, columnDefinitionsStore, columnPlacementTagTableStore, getFilenameFilter, getExcludeFilter, getBoardFolderPath, settingsStore, requestSave, prepareFileContentsForWrite) {
const tasksStore = writable([]);
let timer;
const tasksByTaskId = /* @__PURE__ */ new Map();
const metadataByTaskId = /* @__PURE__ */ new Map();
const taskIdsByFileHandle = /* @__PURE__ */ new Map();
function publishTasks() {
tasksStore.set(
[...tasksByTaskId.values()].sort((a, b) => {
if (a.path !== b.path) {
return a.path.localeCompare(b.path);
}
return a.rowIndex - b.rowIndex;
})
);
}
function debounceSetTasks() {
if (timer) {
return;
}
timer = window.setTimeout(() => {
timer = void 0;
publishTasks();
}, 50);
}
function publishTasksImmediately() {
if (timer) {
window.clearTimeout(timer);
timer = void 0;
}
publishTasks();
}
function shouldHandle(file) {
return shouldIncludeFilePath(file.path, getFilenameFilter(), getExcludeFilter(), getBoardFolderPath());
}
function processFile(fileHandle) {
updateMapsFromFile({
fileHandle,
tasksByTaskId,
metadataByTaskId,
taskIdsByFileHandle,
vault,
columnDefinitionsStore,
columnPlacementTagTableStore,
...getMarkerSettings(get2(settingsStore))
}).then(() => {
debounceSetTasks();
});
}
function initialise() {
tasksByTaskId.clear();
metadataByTaskId.clear();
taskIdsByFileHandle.clear();
publishTasksImmediately();
for (const fileHandle of vault.getMarkdownFiles()) {
if (!shouldHandle(fileHandle)) {
continue;
}
processFile(fileHandle);
}
}
registerEvent(
vault.on("modify", (fileHandle) => {
if (fileHandle instanceof import_obsidian16.TFile && shouldHandle(fileHandle)) {
processFile(fileHandle);
}
})
);
registerEvent(
vault.on("create", (fileHandle) => {
if (fileHandle instanceof import_obsidian16.TFile && shouldHandle(fileHandle)) {
processFile(fileHandle);
}
})
);
registerEvent(
vault.on("delete", (fileHandle) => {
if (fileHandle instanceof import_obsidian16.TFile) {
const tasksToDelete = taskIdsByFileHandle.get(fileHandle);
if (!tasksToDelete) return;
for (const taskId of tasksToDelete) {
tasksByTaskId.delete(taskId);
metadataByTaskId.delete(taskId);
}
taskIdsByFileHandle.delete(fileHandle);
debounceSetTasks();
}
})
);
registerEvent(
vault.on("rename", (fileHandle) => {
if (fileHandle instanceof import_obsidian16.TFile) {
initialise();
}
})
);
const taskActions = createTaskActions({
tasksByTaskId,
metadataByTaskId,
vault,
workspace,
getFilenameFilter,
getExcludeFilter,
getBoardFolderPath,
getPlacementTagsForColumn: (column) => {
var _a5;
return (_a5 = get2(columnPlacementTagTableStore)[column]) != null ? _a5 : [column];
},
getColumnDefinitions: () => get2(columnDefinitionsStore),
getDefaultTaskFile: () => get2(settingsStore).defaultTaskFile || null,
getLastUsedTaskFile: () => get2(settingsStore).lastUsedTaskFile || null,
setLastUsedTaskFile: (path) => {
settingsStore.update((s) => ({ ...s, lastUsedTaskFile: path }));
requestSave();
},
getPropertySchemaOption: () => {
var _a5;
return (_a5 = get2(settingsStore).propertySchema) != null ? _a5 : "none" /* None */;
},
getStatusMarkerOrder: () => {
var _a5;
return (_a5 = get2(settingsStore).statusMarkerOrder) != null ? _a5 : "";
},
getManualOrder: () => {
var _a5;
return (_a5 = get2(settingsStore).manualOrder) != null ? _a5 : {};
},
setManualOrder: (next2) => {
settingsStore.update((s) => ({ ...s, manualOrder: next2 }));
requestSave();
},
prepareFileContentsForWrite
});
return { tasksStore, taskActions, initialise };
}
// node_modules/js-yaml/dist/js-yaml.mjs
function getDefaultExportFromCjs(x) {
return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, "default") ? x["default"] : x;
}
var jsYaml = {};
var loader = {};
var common = {};
var hasRequiredCommon;
function requireCommon() {
if (hasRequiredCommon) return common;
hasRequiredCommon = 1;
function isNothing(subject) {
return typeof subject === "undefined" || subject === null;
}
function isObject(subject) {
return typeof subject === "object" && subject !== null;
}
function toArray(sequence) {
if (Array.isArray(sequence)) return sequence;
else if (isNothing(sequence)) return [];
return [sequence];
}
function extend(target, source2) {
if (source2) {
const sourceKeys = Object.keys(source2);
for (let index2 = 0, length = sourceKeys.length; index2 < length; index2 += 1) {
const key2 = sourceKeys[index2];
target[key2] = source2[key2];
}
}
return target;
}
function repeat(string, count) {
let result = "";
for (let cycle = 0; cycle < count; cycle += 1) {
result += string;
}
return result;
}
function isNegativeZero(number) {
return number === 0 && Number.NEGATIVE_INFINITY === 1 / number;
}
common.isNothing = isNothing;
common.isObject = isObject;
common.toArray = toArray;
common.repeat = repeat;
common.isNegativeZero = isNegativeZero;
common.extend = extend;
return common;
}
var exception;
var hasRequiredException;
function requireException() {
if (hasRequiredException) return exception;
hasRequiredException = 1;
function formatError(exception2, compact) {
let where = "";
const message = exception2.reason || "(unknown reason)";
if (!exception2.mark) return message;
if (exception2.mark.name) {
where += 'in "' + exception2.mark.name + '" ';
}
where += "(" + (exception2.mark.line + 1) + ":" + (exception2.mark.column + 1) + ")";
if (!compact && exception2.mark.snippet) {
where += "\n\n" + exception2.mark.snippet;
}
return message + " " + where;
}
function YAMLException2(reason, mark) {
Error.call(this);
this.name = "YAMLException";
this.reason = reason;
this.mark = mark;
this.message = formatError(this, false);
if (Error.captureStackTrace) {
Error.captureStackTrace(this, this.constructor);
} else {
this.stack = new Error().stack || "";
}
}
YAMLException2.prototype = Object.create(Error.prototype);
YAMLException2.prototype.constructor = YAMLException2;
YAMLException2.prototype.toString = function toString(compact) {
return this.name + ": " + formatError(this, compact);
};
exception = YAMLException2;
return exception;
}
var snippet2;
var hasRequiredSnippet;
function requireSnippet() {
if (hasRequiredSnippet) return snippet2;
hasRequiredSnippet = 1;
const common2 = requireCommon();
function getLine(buffer, lineStart, lineEnd, position, maxLineLength) {
let head2 = "";
let tail = "";
const maxHalfLength = Math.floor(maxLineLength / 2) - 1;
if (position - lineStart > maxHalfLength) {
head2 = " ... ";
lineStart = position - maxHalfLength + head2.length;
}
if (lineEnd - position > maxHalfLength) {
tail = " ...";
lineEnd = position + maxHalfLength - tail.length;
}
return {
str: head2 + buffer.slice(lineStart, lineEnd).replace(/\t/g, "\u2192") + tail,
pos: position - lineStart + head2.length
// relative position
};
}
function padStart(string, max) {
return common2.repeat(" ", max - string.length) + string;
}
function makeSnippet(mark, options) {
options = Object.create(options || null);
if (!mark.buffer) return null;
if (!options.maxLength) options.maxLength = 79;
if (typeof options.indent !== "number") options.indent = 1;
if (typeof options.linesBefore !== "number") options.linesBefore = 3;
if (typeof options.linesAfter !== "number") options.linesAfter = 2;
const re = /\r?\n|\r|\0/g;
const lineStarts = [0];
const lineEnds = [];
let match;
let foundLineNo = -1;
while (match = re.exec(mark.buffer)) {
lineEnds.push(match.index);
lineStarts.push(match.index + match[0].length);
if (mark.position <= match.index && foundLineNo < 0) {
foundLineNo = lineStarts.length - 2;
}
}
if (foundLineNo < 0) foundLineNo = lineStarts.length - 1;
let result = "";
const lineNoLength = Math.min(mark.line + options.linesAfter, lineEnds.length).toString().length;
const maxLineLength = options.maxLength - (options.indent + lineNoLength + 3);
for (let i = 1; i <= options.linesBefore; i++) {
if (foundLineNo - i < 0) break;
const line2 = getLine(
mark.buffer,
lineStarts[foundLineNo - i],
lineEnds[foundLineNo - i],
mark.position - (lineStarts[foundLineNo] - lineStarts[foundLineNo - i]),
maxLineLength
);
result = common2.repeat(" ", options.indent) + padStart((mark.line - i + 1).toString(), lineNoLength) + " | " + line2.str + "\n" + result;
}
const line = getLine(mark.buffer, lineStarts[foundLineNo], lineEnds[foundLineNo], mark.position, maxLineLength);
result += common2.repeat(" ", options.indent) + padStart((mark.line + 1).toString(), lineNoLength) + " | " + line.str + "\n";
result += common2.repeat("-", options.indent + lineNoLength + 3 + line.pos) + "^\n";
for (let i = 1; i <= options.linesAfter; i++) {
if (foundLineNo + i >= lineEnds.length) break;
const line2 = getLine(
mark.buffer,
lineStarts[foundLineNo + i],
lineEnds[foundLineNo + i],
mark.position - (lineStarts[foundLineNo] - lineStarts[foundLineNo + i]),
maxLineLength
);
result += common2.repeat(" ", options.indent) + padStart((mark.line + i + 1).toString(), lineNoLength) + " | " + line2.str + "\n";
}
return result.replace(/\n$/, "");
}
snippet2 = makeSnippet;
return snippet2;
}
var type;
var hasRequiredType;
function requireType() {
if (hasRequiredType) return type;
hasRequiredType = 1;
const YAMLException2 = requireException();
const TYPE_CONSTRUCTOR_OPTIONS = [
"kind",
"multi",
"resolve",
"construct",
"instanceOf",
"predicate",
"represent",
"representName",
"defaultStyle",
"styleAliases"
];
const YAML_NODE_KINDS = [
"scalar",
"sequence",
"mapping"
];
function compileStyleAliases(map2) {
const result = {};
if (map2 !== null) {
Object.keys(map2).forEach(function(style) {
map2[style].forEach(function(alias) {
result[String(alias)] = style;
});
});
}
return result;
}
function Type2(tag2, options) {
options = options || {};
Object.keys(options).forEach(function(name) {
if (TYPE_CONSTRUCTOR_OPTIONS.indexOf(name) === -1) {
throw new YAMLException2('Unknown option "' + name + '" is met in definition of "' + tag2 + '" YAML type.');
}
});
this.options = options;
this.tag = tag2;
this.kind = options["kind"] || null;
this.resolve = options["resolve"] || function() {
return true;
};
this.construct = options["construct"] || function(data) {
return data;
};
this.instanceOf = options["instanceOf"] || null;
this.predicate = options["predicate"] || null;
this.represent = options["represent"] || null;
this.representName = options["representName"] || null;
this.defaultStyle = options["defaultStyle"] || null;
this.multi = options["multi"] || false;
this.styleAliases = compileStyleAliases(options["styleAliases"] || null);
if (YAML_NODE_KINDS.indexOf(this.kind) === -1) {
throw new YAMLException2('Unknown kind "' + this.kind + '" is specified for "' + tag2 + '" YAML type.');
}
}
type = Type2;
return type;
}
var schema;
var hasRequiredSchema;
function requireSchema() {
if (hasRequiredSchema) return schema;
hasRequiredSchema = 1;
const YAMLException2 = requireException();
const Type2 = requireType();
function compileList(schema2, name) {
const result = [];
schema2[name].forEach(function(currentType) {
let newIndex = result.length;
result.forEach(function(previousType, previousIndex) {
if (previousType.tag === currentType.tag && previousType.kind === currentType.kind && previousType.multi === currentType.multi) {
newIndex = previousIndex;
}
});
result[newIndex] = currentType;
});
return result;
}
function compileMap() {
const result = {
scalar: {},
sequence: {},
mapping: {},
fallback: {},
multi: {
scalar: [],
sequence: [],
mapping: [],
fallback: []
}
};
function collectType(type2) {
if (type2.multi) {
result.multi[type2.kind].push(type2);
result.multi["fallback"].push(type2);
} else {
result[type2.kind][type2.tag] = result["fallback"][type2.tag] = type2;
}
}
for (let index2 = 0, length = arguments.length; index2 < length; index2 += 1) {
arguments[index2].forEach(collectType);
}
return result;
}
function Schema2(definition) {
return this.extend(definition);
}
Schema2.prototype.extend = function extend(definition) {
let implicit = [];
let explicit = [];
if (definition instanceof Type2) {
explicit.push(definition);
} else if (Array.isArray(definition)) {
explicit = explicit.concat(definition);
} else if (definition && (Array.isArray(definition.implicit) || Array.isArray(definition.explicit))) {
if (definition.implicit) implicit = implicit.concat(definition.implicit);
if (definition.explicit) explicit = explicit.concat(definition.explicit);
} else {
throw new YAMLException2("Schema.extend argument should be a Type, [ Type ], or a schema definition ({ implicit: [...], explicit: [...] })");
}
implicit.forEach(function(type2) {
if (!(type2 instanceof Type2)) {
throw new YAMLException2("Specified list of YAML types (or a single Type object) contains a non-Type object.");
}
if (type2.loadKind && type2.loadKind !== "scalar") {
throw new YAMLException2("There is a non-scalar type in the implicit list of a schema. Implicit resolving of such types is not supported.");
}
if (type2.multi) {
throw new YAMLException2("There is a multi type in the implicit list of a schema. Multi tags can only be listed as explicit.");
}
});
explicit.forEach(function(type2) {
if (!(type2 instanceof Type2)) {
throw new YAMLException2("Specified list of YAML types (or a single Type object) contains a non-Type object.");
}
});
const result = Object.create(Schema2.prototype);
result.implicit = (this.implicit || []).concat(implicit);
result.explicit = (this.explicit || []).concat(explicit);
result.compiledImplicit = compileList(result, "implicit");
result.compiledExplicit = compileList(result, "explicit");
result.compiledTypeMap = compileMap(result.compiledImplicit, result.compiledExplicit);
return result;
};
schema = Schema2;
return schema;
}
var str;
var hasRequiredStr;
function requireStr() {
if (hasRequiredStr) return str;
hasRequiredStr = 1;
const Type2 = requireType();
str = new Type2("tag:yaml.org,2002:str", {
kind: "scalar",
construct: function(data) {
return data !== null ? data : "";
}
});
return str;
}
var seq;
var hasRequiredSeq;
function requireSeq() {
if (hasRequiredSeq) return seq;
hasRequiredSeq = 1;
const Type2 = requireType();
seq = new Type2("tag:yaml.org,2002:seq", {
kind: "sequence",
construct: function(data) {
return data !== null ? data : [];
}
});
return seq;
}
var map;
var hasRequiredMap;
function requireMap() {
if (hasRequiredMap) return map;
hasRequiredMap = 1;
const Type2 = requireType();
map = new Type2("tag:yaml.org,2002:map", {
kind: "mapping",
construct: function(data) {
return data !== null ? data : {};
}
});
return map;
}
var failsafe;
var hasRequiredFailsafe;
function requireFailsafe() {
if (hasRequiredFailsafe) return failsafe;
hasRequiredFailsafe = 1;
const Schema2 = requireSchema();
failsafe = new Schema2({
explicit: [
requireStr(),
requireSeq(),
requireMap()
]
});
return failsafe;
}
var _null;
var hasRequired_null;
function require_null() {
if (hasRequired_null) return _null;
hasRequired_null = 1;
const Type2 = requireType();
function resolveYamlNull(data) {
if (data === null) return true;
const max = data.length;
return max === 1 && data === "~" || max === 4 && (data === "null" || data === "Null" || data === "NULL");
}
function constructYamlNull() {
return null;
}
function isNull(object) {
return object === null;
}
_null = new Type2("tag:yaml.org,2002:null", {
kind: "scalar",
resolve: resolveYamlNull,
construct: constructYamlNull,
predicate: isNull,
represent: {
canonical: function() {
return "~";
},
lowercase: function() {
return "null";
},
uppercase: function() {
return "NULL";
},
camelcase: function() {
return "Null";
},
empty: function() {
return "";
}
},
defaultStyle: "lowercase"
});
return _null;
}
var bool;
var hasRequiredBool;
function requireBool() {
if (hasRequiredBool) return bool;
hasRequiredBool = 1;
const Type2 = requireType();
function resolveYamlBoolean(data) {
if (data === null) return false;
const max = data.length;
return max === 4 && (data === "true" || data === "True" || data === "TRUE") || max === 5 && (data === "false" || data === "False" || data === "FALSE");
}
function constructYamlBoolean(data) {
return data === "true" || data === "True" || data === "TRUE";
}
function isBoolean(object) {
return Object.prototype.toString.call(object) === "[object Boolean]";
}
bool = new Type2("tag:yaml.org,2002:bool", {
kind: "scalar",
resolve: resolveYamlBoolean,
construct: constructYamlBoolean,
predicate: isBoolean,
represent: {
lowercase: function(object) {
return object ? "true" : "false";
},
uppercase: function(object) {
return object ? "TRUE" : "FALSE";
},
camelcase: function(object) {
return object ? "True" : "False";
}
},
defaultStyle: "lowercase"
});
return bool;
}
var int;
var hasRequiredInt;
function requireInt() {
if (hasRequiredInt) return int;
hasRequiredInt = 1;
const common2 = requireCommon();
const Type2 = requireType();
function isHexCode(c) {
return c >= 48 && c <= 57 || c >= 65 && c <= 70 || c >= 97 && c <= 102;
}
function isOctCode(c) {
return c >= 48 && c <= 55;
}
function isDecCode(c) {
return c >= 48 && c <= 57;
}
function resolveYamlInteger(data) {
if (data === null) return false;
const max = data.length;
let index2 = 0;
let hasDigits = false;
if (!max) return false;
let ch = data[index2];
if (ch === "-" || ch === "+") {
ch = data[++index2];
}
if (ch === "0") {
if (index2 + 1 === max) return true;
ch = data[++index2];
if (ch === "b") {
index2++;
for (; index2 < max; index2++) {
ch = data[index2];
if (ch !== "0" && ch !== "1") return false;
hasDigits = true;
}
return hasDigits && isFinite(parseYamlInteger(data));
}
if (ch === "x") {
index2++;
for (; index2 < max; index2++) {
if (!isHexCode(data.charCodeAt(index2))) return false;
hasDigits = true;
}
return hasDigits && isFinite(parseYamlInteger(data));
}
if (ch === "o") {
index2++;
for (; index2 < max; index2++) {
if (!isOctCode(data.charCodeAt(index2))) return false;
hasDigits = true;
}
return hasDigits && isFinite(parseYamlInteger(data));
}
}
for (; index2 < max; index2++) {
if (!isDecCode(data.charCodeAt(index2))) {
return false;
}
hasDigits = true;
}
if (!hasDigits) return false;
return isFinite(parseYamlInteger(data));
}
function parseYamlInteger(data) {
let value = data;
let sign = 1;
let ch = value[0];
if (ch === "-" || ch === "+") {
if (ch === "-") sign = -1;
value = value.slice(1);
ch = value[0];
}
if (value === "0") return 0;
if (ch === "0") {
if (value[1] === "b") return sign * parseInt(value.slice(2), 2);
if (value[1] === "x") return sign * parseInt(value.slice(2), 16);
if (value[1] === "o") return sign * parseInt(value.slice(2), 8);
}
return sign * parseInt(value, 10);
}
function constructYamlInteger(data) {
return parseYamlInteger(data);
}
function isInteger(object) {
return Object.prototype.toString.call(object) === "[object Number]" && (object % 1 === 0 && !common2.isNegativeZero(object));
}
int = new Type2("tag:yaml.org,2002:int", {
kind: "scalar",
resolve: resolveYamlInteger,
construct: constructYamlInteger,
predicate: isInteger,
represent: {
binary: function(obj) {
return obj >= 0 ? "0b" + obj.toString(2) : "-0b" + obj.toString(2).slice(1);
},
octal: function(obj) {
return obj >= 0 ? "0o" + obj.toString(8) : "-0o" + obj.toString(8).slice(1);
},
decimal: function(obj) {
return obj.toString(10);
},
hexadecimal: function(obj) {
return obj >= 0 ? "0x" + obj.toString(16).toUpperCase() : "-0x" + obj.toString(16).toUpperCase().slice(1);
}
},
defaultStyle: "decimal",
styleAliases: {
binary: [2, "bin"],
octal: [8, "oct"],
decimal: [10, "dec"],
hexadecimal: [16, "hex"]
}
});
return int;
}
var float;
var hasRequiredFloat;
function requireFloat() {
if (hasRequiredFloat) return float;
hasRequiredFloat = 1;
const common2 = requireCommon();
const Type2 = requireType();
const YAML_FLOAT_PATTERN = new RegExp(
// 2.5e4, 2.5 and integers
"^(?:[-+]?(?:[0-9]+)(?:\\.[0-9]*)?(?:[eE][-+]?[0-9]+)?|\\.[0-9]+(?:[eE][-+]?[0-9]+)?|[-+]?\\.(?:inf|Inf|INF)|\\.(?:nan|NaN|NAN))$"
);
const YAML_FLOAT_SPECIAL_PATTERN = new RegExp(
"^(?:[-+]?\\.(?:inf|Inf|INF)|\\.(?:nan|NaN|NAN))$"
);
function resolveYamlFloat(data) {
if (data === null) return false;
if (!YAML_FLOAT_PATTERN.test(data)) {
return false;
}
if (isFinite(parseFloat(data, 10))) {
return true;
}
return YAML_FLOAT_SPECIAL_PATTERN.test(data);
}
function constructYamlFloat(data) {
let value = data.toLowerCase();
const sign = value[0] === "-" ? -1 : 1;
if ("+-".indexOf(value[0]) >= 0) {
value = value.slice(1);
}
if (value === ".inf") {
return sign === 1 ? Number.POSITIVE_INFINITY : Number.NEGATIVE_INFINITY;
} else if (value === ".nan") {
return NaN;
}
return sign * parseFloat(value, 10);
}
const SCIENTIFIC_WITHOUT_DOT = /^[-+]?[0-9]+e/;
function representYamlFloat(object, style) {
if (isNaN(object)) {
switch (style) {
case "lowercase":
return ".nan";
case "uppercase":
return ".NAN";
case "camelcase":
return ".NaN";
}
} else if (Number.POSITIVE_INFINITY === object) {
switch (style) {
case "lowercase":
return ".inf";
case "uppercase":
return ".INF";
case "camelcase":
return ".Inf";
}
} else if (Number.NEGATIVE_INFINITY === object) {
switch (style) {
case "lowercase":
return "-.inf";
case "uppercase":
return "-.INF";
case "camelcase":
return "-.Inf";
}
} else if (common2.isNegativeZero(object)) {
return "-0.0";
}
const res = object.toString(10);
return SCIENTIFIC_WITHOUT_DOT.test(res) ? res.replace("e", ".e") : res;
}
function isFloat(object) {
return Object.prototype.toString.call(object) === "[object Number]" && (object % 1 !== 0 || common2.isNegativeZero(object));
}
float = new Type2("tag:yaml.org,2002:float", {
kind: "scalar",
resolve: resolveYamlFloat,
construct: constructYamlFloat,
predicate: isFloat,
represent: representYamlFloat,
defaultStyle: "lowercase"
});
return float;
}
var json;
var hasRequiredJson;
function requireJson() {
if (hasRequiredJson) return json;
hasRequiredJson = 1;
json = requireFailsafe().extend({
implicit: [
require_null(),
requireBool(),
requireInt(),
requireFloat()
]
});
return json;
}
var core;
var hasRequiredCore;
function requireCore() {
if (hasRequiredCore) return core;
hasRequiredCore = 1;
core = requireJson();
return core;
}
var timestamp;
var hasRequiredTimestamp;
function requireTimestamp() {
if (hasRequiredTimestamp) return timestamp;
hasRequiredTimestamp = 1;
const Type2 = requireType();
const YAML_DATE_REGEXP = new RegExp(
"^([0-9][0-9][0-9][0-9])-([0-9][0-9])-([0-9][0-9])$"
);
const YAML_TIMESTAMP_REGEXP = new RegExp(
"^([0-9][0-9][0-9][0-9])-([0-9][0-9]?)-([0-9][0-9]?)(?:[Tt]|[ \\t]+)([0-9][0-9]?):([0-9][0-9]):([0-9][0-9])(?:\\.([0-9]*))?(?:[ \\t]*(Z|([-+])([0-9][0-9]?)(?::([0-9][0-9]))?))?$"
);
function resolveYamlTimestamp(data) {
if (data === null) return false;
if (YAML_DATE_REGEXP.exec(data) !== null) return true;
if (YAML_TIMESTAMP_REGEXP.exec(data) !== null) return true;
return false;
}
function constructYamlTimestamp(data) {
let fraction = 0;
let delta = null;
let match = YAML_DATE_REGEXP.exec(data);
if (match === null) match = YAML_TIMESTAMP_REGEXP.exec(data);
if (match === null) throw new Error("Date resolve error");
const year = +match[1];
const month = +match[2] - 1;
const day = +match[3];
if (!match[4]) {
return new Date(Date.UTC(year, month, day));
}
const hour = +match[4];
const minute = +match[5];
const second = +match[6];
if (match[7]) {
fraction = match[7].slice(0, 3);
while (fraction.length < 3) {
fraction += "0";
}
fraction = +fraction;
}
if (match[9]) {
const tzHour = +match[10];
const tzMinute = +(match[11] || 0);
delta = (tzHour * 60 + tzMinute) * 6e4;
if (match[9] === "-") delta = -delta;
}
const date = new Date(Date.UTC(year, month, day, hour, minute, second, fraction));
if (delta) date.setTime(date.getTime() - delta);
return date;
}
function representYamlTimestamp(object) {
return object.toISOString();
}
timestamp = new Type2("tag:yaml.org,2002:timestamp", {
kind: "scalar",
resolve: resolveYamlTimestamp,
construct: constructYamlTimestamp,
instanceOf: Date,
represent: representYamlTimestamp
});
return timestamp;
}
var merge;
var hasRequiredMerge;
function requireMerge() {
if (hasRequiredMerge) return merge;
hasRequiredMerge = 1;
const Type2 = requireType();
function resolveYamlMerge(data) {
return data === "<<" || data === null;
}
merge = new Type2("tag:yaml.org,2002:merge", {
kind: "scalar",
resolve: resolveYamlMerge
});
return merge;
}
var binary;
var hasRequiredBinary;
function requireBinary() {
if (hasRequiredBinary) return binary;
hasRequiredBinary = 1;
const Type2 = requireType();
const BASE64_MAP = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=\n\r";
function resolveYamlBinary(data) {
if (data === null) return false;
let bitlen = 0;
const max = data.length;
const map2 = BASE64_MAP;
for (let idx = 0; idx < max; idx++) {
const code = map2.indexOf(data.charAt(idx));
if (code > 64) continue;
if (code < 0) return false;
bitlen += 6;
}
return bitlen % 8 === 0;
}
function constructYamlBinary(data) {
const input = data.replace(/[\r\n=]/g, "");
const max = input.length;
const map2 = BASE64_MAP;
let bits = 0;
const result = [];
for (let idx = 0; idx < max; idx++) {
if (idx % 4 === 0 && idx) {
result.push(bits >> 16 & 255);
result.push(bits >> 8 & 255);
result.push(bits & 255);
}
bits = bits << 6 | map2.indexOf(input.charAt(idx));
}
const tailbits = max % 4 * 6;
if (tailbits === 0) {
result.push(bits >> 16 & 255);
result.push(bits >> 8 & 255);
result.push(bits & 255);
} else if (tailbits === 18) {
result.push(bits >> 10 & 255);
result.push(bits >> 2 & 255);
} else if (tailbits === 12) {
result.push(bits >> 4 & 255);
}
return new Uint8Array(result);
}
function representYamlBinary(object) {
let result = "";
let bits = 0;
const max = object.length;
const map2 = BASE64_MAP;
for (let idx = 0; idx < max; idx++) {
if (idx % 3 === 0 && idx) {
result += map2[bits >> 18 & 63];
result += map2[bits >> 12 & 63];
result += map2[bits >> 6 & 63];
result += map2[bits & 63];
}
bits = (bits << 8) + object[idx];
}
const tail = max % 3;
if (tail === 0) {
result += map2[bits >> 18 & 63];
result += map2[bits >> 12 & 63];
result += map2[bits >> 6 & 63];
result += map2[bits & 63];
} else if (tail === 2) {
result += map2[bits >> 10 & 63];
result += map2[bits >> 4 & 63];
result += map2[bits << 2 & 63];
result += map2[64];
} else if (tail === 1) {
result += map2[bits >> 2 & 63];
result += map2[bits << 4 & 63];
result += map2[64];
result += map2[64];
}
return result;
}
function isBinary(obj) {
return Object.prototype.toString.call(obj) === "[object Uint8Array]";
}
binary = new Type2("tag:yaml.org,2002:binary", {
kind: "scalar",
resolve: resolveYamlBinary,
construct: constructYamlBinary,
predicate: isBinary,
represent: representYamlBinary
});
return binary;
}
var omap;
var hasRequiredOmap;
function requireOmap() {
if (hasRequiredOmap) return omap;
hasRequiredOmap = 1;
const Type2 = requireType();
const _hasOwnProperty = Object.prototype.hasOwnProperty;
const _toString = Object.prototype.toString;
function resolveYamlOmap(data) {
if (data === null) return true;
const objectKeys = [];
const object = data;
for (let index2 = 0, length = object.length; index2 < length; index2 += 1) {
const pair = object[index2];
let pairHasKey = false;
if (_toString.call(pair) !== "[object Object]") return false;
let pairKey;
for (pairKey in pair) {
if (_hasOwnProperty.call(pair, pairKey)) {
if (!pairHasKey) pairHasKey = true;
else return false;
}
}
if (!pairHasKey) return false;
if (objectKeys.indexOf(pairKey) === -1) objectKeys.push(pairKey);
else return false;
}
return true;
}
function constructYamlOmap(data) {
return data !== null ? data : [];
}
omap = new Type2("tag:yaml.org,2002:omap", {
kind: "sequence",
resolve: resolveYamlOmap,
construct: constructYamlOmap
});
return omap;
}
var pairs;
var hasRequiredPairs;
function requirePairs() {
if (hasRequiredPairs) return pairs;
hasRequiredPairs = 1;
const Type2 = requireType();
const _toString = Object.prototype.toString;
function resolveYamlPairs(data) {
if (data === null) return true;
const object = data;
const result = new Array(object.length);
for (let index2 = 0, length = object.length; index2 < length; index2 += 1) {
const pair = object[index2];
if (_toString.call(pair) !== "[object Object]") return false;
const keys = Object.keys(pair);
if (keys.length !== 1) return false;
result[index2] = [keys[0], pair[keys[0]]];
}
return true;
}
function constructYamlPairs(data) {
if (data === null) return [];
const object = data;
const result = new Array(object.length);
for (let index2 = 0, length = object.length; index2 < length; index2 += 1) {
const pair = object[index2];
const keys = Object.keys(pair);
result[index2] = [keys[0], pair[keys[0]]];
}
return result;
}
pairs = new Type2("tag:yaml.org,2002:pairs", {
kind: "sequence",
resolve: resolveYamlPairs,
construct: constructYamlPairs
});
return pairs;
}
var set2;
var hasRequiredSet;
function requireSet() {
if (hasRequiredSet) return set2;
hasRequiredSet = 1;
const Type2 = requireType();
const _hasOwnProperty = Object.prototype.hasOwnProperty;
function resolveYamlSet(data) {
if (data === null) return true;
const object = data;
for (const key2 in object) {
if (_hasOwnProperty.call(object, key2)) {
if (object[key2] !== null) return false;
}
}
return true;
}
function constructYamlSet(data) {
return data !== null ? data : {};
}
set2 = new Type2("tag:yaml.org,2002:set", {
kind: "mapping",
resolve: resolveYamlSet,
construct: constructYamlSet
});
return set2;
}
var _default;
var hasRequired_default;
function require_default() {
if (hasRequired_default) return _default;
hasRequired_default = 1;
_default = requireCore().extend({
implicit: [
requireTimestamp(),
requireMerge()
],
explicit: [
requireBinary(),
requireOmap(),
requirePairs(),
requireSet()
]
});
return _default;
}
var hasRequiredLoader;
function requireLoader() {
if (hasRequiredLoader) return loader;
hasRequiredLoader = 1;
const common2 = requireCommon();
const YAMLException2 = requireException();
const makeSnippet = requireSnippet();
const DEFAULT_SCHEMA2 = require_default();
const _hasOwnProperty = Object.prototype.hasOwnProperty;
const CONTEXT_FLOW_IN = 1;
const CONTEXT_FLOW_OUT = 2;
const CONTEXT_BLOCK_IN = 3;
const CONTEXT_BLOCK_OUT = 4;
const CHOMPING_CLIP = 1;
const CHOMPING_STRIP = 2;
const CHOMPING_KEEP = 3;
const PATTERN_NON_PRINTABLE = /[\x00-\x08\x0B\x0C\x0E-\x1F\x7F-\x84\x86-\x9F\uFFFE\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/;
const PATTERN_NON_ASCII_LINE_BREAKS = /[\x85\u2028\u2029]/;
const PATTERN_FLOW_INDICATORS = /[,\[\]{}]/;
const PATTERN_TAG_HANDLE = /^(?:!|!!|![0-9A-Za-z-]+!)$/;
const PATTERN_TAG_URI = /^(?:!|[^,\[\]{}])(?:%[0-9a-f]{2}|[0-9a-z\-#;/?:@&=+$,_.!~*'()\[\]])*$/i;
function _class(obj) {
return Object.prototype.toString.call(obj);
}
function isEol(c) {
return c === 10 || c === 13;
}
function isWhiteSpace(c) {
return c === 9 || c === 32;
}
function isWsOrEol(c) {
return c === 9 || c === 32 || c === 10 || c === 13;
}
function isFlowIndicator(c) {
return c === 44 || c === 91 || c === 93 || c === 123 || c === 125;
}
function fromHexCode(c) {
if (c >= 48 && c <= 57) {
return c - 48;
}
const lc = c | 32;
if (lc >= 97 && lc <= 102) {
return lc - 97 + 10;
}
return -1;
}
function escapedHexLen(c) {
if (c === 120) {
return 2;
}
if (c === 117) {
return 4;
}
if (c === 85) {
return 8;
}
return 0;
}
function fromDecimalCode(c) {
if (c >= 48 && c <= 57) {
return c - 48;
}
return -1;
}
function simpleEscapeSequence(c) {
switch (c) {
case 48:
return "\0";
case 97:
return "\x07";
case 98:
return "\b";
case 116:
return " ";
case 9:
return " ";
case 110:
return "\n";
case 118:
return "\v";
case 102:
return "\f";
case 114:
return "\r";
case 101:
return "\x1B";
case 32:
return " ";
case 34:
return '"';
case 47:
return "/";
case 92:
return "\\";
case 78:
return "\x85";
case 95:
return "\xA0";
case 76:
return "\u2028";
case 80:
return "\u2029";
default:
return "";
}
}
function charFromCodepoint(c) {
if (c <= 65535) {
return String.fromCharCode(c);
}
return String.fromCharCode(
(c - 65536 >> 10) + 55296,
(c - 65536 & 1023) + 56320
);
}
function setProperty(object, key2, value) {
if (key2 === "__proto__") {
Object.defineProperty(object, key2, {
configurable: true,
enumerable: true,
writable: true,
value
});
} else {
object[key2] = value;
}
}
const simpleEscapeCheck = new Array(256);
const simpleEscapeMap = new Array(256);
for (let i = 0; i < 256; i++) {
simpleEscapeCheck[i] = simpleEscapeSequence(i) ? 1 : 0;
simpleEscapeMap[i] = simpleEscapeSequence(i);
}
function State(input, options) {
this.input = input;
this.filename = options["filename"] || null;
this.schema = options["schema"] || DEFAULT_SCHEMA2;
this.onWarning = options["onWarning"] || null;
this.legacy = options["legacy"] || false;
this.json = options["json"] || false;
this.listener = options["listener"] || null;
this.maxDepth = typeof options["maxDepth"] === "number" ? options["maxDepth"] : 100;
this.maxTotalMergeKeys = typeof options["maxTotalMergeKeys"] === "number" ? options["maxTotalMergeKeys"] : 1e4;
this.implicitTypes = this.schema.compiledImplicit;
this.typeMap = this.schema.compiledTypeMap;
this.length = input.length;
this.position = 0;
this.line = 0;
this.lineStart = 0;
this.lineIndent = 0;
this.depth = 0;
this.totalMergeKeys = 0;
this.firstTabInLine = -1;
this.documents = [];
this.anchorMapTransactions = [];
}
function generateError(state2, message) {
const mark = {
name: state2.filename,
buffer: state2.input.slice(0, -1),
// omit trailing \0
position: state2.position,
line: state2.line,
column: state2.position - state2.lineStart
};
mark.snippet = makeSnippet(mark);
return new YAMLException2(message, mark);
}
function throwError(state2, message) {
throw generateError(state2, message);
}
function throwWarning(state2, message) {
if (state2.onWarning) {
state2.onWarning.call(null, generateError(state2, message));
}
}
function storeAnchor(state2, name, value) {
const transactions = state2.anchorMapTransactions;
if (transactions.length !== 0) {
const transaction = transactions[transactions.length - 1];
if (!_hasOwnProperty.call(transaction, name)) {
transaction[name] = {
existed: _hasOwnProperty.call(state2.anchorMap, name),
value: state2.anchorMap[name]
};
}
}
state2.anchorMap[name] = value;
}
function beginAnchorTransaction(state2) {
state2.anchorMapTransactions.push(/* @__PURE__ */ Object.create(null));
}
function commitAnchorTransaction(state2) {
const transaction = state2.anchorMapTransactions.pop();
const transactions = state2.anchorMapTransactions;
if (transactions.length === 0) return;
const parent = transactions[transactions.length - 1];
const names = Object.keys(transaction);
for (let index2 = 0, length = names.length; index2 < length; index2 += 1) {
const name = names[index2];
if (!_hasOwnProperty.call(parent, name)) {
parent[name] = transaction[name];
}
}
}
function rollbackAnchorTransaction(state2) {
const transaction = state2.anchorMapTransactions.pop();
const names = Object.keys(transaction);
for (let index2 = names.length - 1; index2 >= 0; index2 -= 1) {
const entry = transaction[names[index2]];
if (entry.existed) {
state2.anchorMap[names[index2]] = entry.value;
} else {
delete state2.anchorMap[names[index2]];
}
}
}
function snapshotState(state2) {
return {
position: state2.position,
line: state2.line,
lineStart: state2.lineStart,
lineIndent: state2.lineIndent,
firstTabInLine: state2.firstTabInLine,
tag: state2.tag,
anchor: state2.anchor,
kind: state2.kind,
result: state2.result
};
}
function restoreState(state2, snapshot2) {
state2.position = snapshot2.position;
state2.line = snapshot2.line;
state2.lineStart = snapshot2.lineStart;
state2.lineIndent = snapshot2.lineIndent;
state2.firstTabInLine = snapshot2.firstTabInLine;
state2.tag = snapshot2.tag;
state2.anchor = snapshot2.anchor;
state2.kind = snapshot2.kind;
state2.result = snapshot2.result;
}
const directiveHandlers = {
YAML: function handleYamlDirective(state2, name, args) {
if (state2.version !== null) {
throwError(state2, "duplication of %YAML directive");
}
if (args.length !== 1) {
throwError(state2, "YAML directive accepts exactly one argument");
}
const match = /^([0-9]+)\.([0-9]+)$/.exec(args[0]);
if (match === null) {
throwError(state2, "ill-formed argument of the YAML directive");
}
const major = parseInt(match[1], 10);
const minor = parseInt(match[2], 10);
if (major !== 1) {
throwError(state2, "unacceptable YAML version of the document");
}
state2.version = args[0];
state2.checkLineBreaks = minor < 2;
if (minor !== 1 && minor !== 2) {
throwWarning(state2, "unsupported YAML version of the document");
}
},
TAG: function handleTagDirective(state2, name, args) {
let prefix;
if (args.length !== 2) {
throwError(state2, "TAG directive accepts exactly two arguments");
}
const handle = args[0];
prefix = args[1];
if (!PATTERN_TAG_HANDLE.test(handle)) {
throwError(state2, "ill-formed tag handle (first argument) of the TAG directive");
}
if (_hasOwnProperty.call(state2.tagMap, handle)) {
throwError(state2, 'there is a previously declared suffix for "' + handle + '" tag handle');
}
if (!PATTERN_TAG_URI.test(prefix)) {
throwError(state2, "ill-formed tag prefix (second argument) of the TAG directive");
}
try {
prefix = decodeURIComponent(prefix);
} catch (err) {
throwError(state2, "tag prefix is malformed: " + prefix);
}
state2.tagMap[handle] = prefix;
}
};
function captureSegment(state2, start, end, checkJson) {
if (start < end) {
const _result = state2.input.slice(start, end);
if (checkJson) {
for (let _position = 0, _length = _result.length; _position < _length; _position += 1) {
const _character = _result.charCodeAt(_position);
if (!(_character === 9 || _character >= 32 && _character <= 1114111)) {
throwError(state2, "expected valid JSON character");
}
}
} else if (PATTERN_NON_PRINTABLE.test(_result)) {
throwError(state2, "the stream contains non-printable characters");
}
state2.result += _result;
}
}
function mergeMappings(state2, destination, source2, overridableKeys) {
if (!common2.isObject(source2)) {
throwError(state2, "cannot merge mappings; the provided source object is unacceptable");
}
const sourceKeys = Object.keys(source2);
for (let index2 = 0, quantity = sourceKeys.length; index2 < quantity; index2 += 1) {
const key2 = sourceKeys[index2];
if (state2.maxTotalMergeKeys !== -1 && ++state2.totalMergeKeys > state2.maxTotalMergeKeys) {
throwError(state2, "merge keys exceeded maxTotalMergeKeys (" + state2.maxTotalMergeKeys + ")");
}
if (!_hasOwnProperty.call(destination, key2)) {
setProperty(destination, key2, source2[key2]);
overridableKeys[key2] = true;
}
}
}
function storeMappingPair(state2, _result, overridableKeys, keyTag, keyNode, valueNode, startLine, startLineStart, startPos) {
if (Array.isArray(keyNode)) {
keyNode = Array.prototype.slice.call(keyNode);
for (let index2 = 0, quantity = keyNode.length; index2 < quantity; index2 += 1) {
if (Array.isArray(keyNode[index2])) {
throwError(state2, "nested arrays are not supported inside keys");
}
if (typeof keyNode === "object" && _class(keyNode[index2]) === "[object Object]") {
keyNode[index2] = "[object Object]";
}
}
}
if (typeof keyNode === "object" && _class(keyNode) === "[object Object]") {
keyNode = "[object Object]";
}
keyNode = String(keyNode);
if (_result === null) {
_result = {};
}
if (keyTag === "tag:yaml.org,2002:merge") {
if (Array.isArray(valueNode)) {
for (let index2 = 0, quantity = valueNode.length; index2 < quantity; index2 += 1) {
mergeMappings(state2, _result, valueNode[index2], overridableKeys);
}
} else {
mergeMappings(state2, _result, valueNode, overridableKeys);
}
} else {
if (!state2.json && !_hasOwnProperty.call(overridableKeys, keyNode) && _hasOwnProperty.call(_result, keyNode)) {
state2.line = startLine || state2.line;
state2.lineStart = startLineStart || state2.lineStart;
state2.position = startPos || state2.position;
throwError(state2, "duplicated mapping key");
}
setProperty(_result, keyNode, valueNode);
delete overridableKeys[keyNode];
}
return _result;
}
function readLineBreak(state2) {
const ch = state2.input.charCodeAt(state2.position);
if (ch === 10) {
state2.position++;
} else if (ch === 13) {
state2.position++;
if (state2.input.charCodeAt(state2.position) === 10) {
state2.position++;
}
} else {
throwError(state2, "a line break is expected");
}
state2.line += 1;
state2.lineStart = state2.position;
state2.firstTabInLine = -1;
}
function skipSeparationSpace(state2, allowComments, checkIndent) {
let lineBreaks = 0;
let ch = state2.input.charCodeAt(state2.position);
while (ch !== 0) {
while (isWhiteSpace(ch)) {
if (ch === 9 && state2.firstTabInLine === -1) {
state2.firstTabInLine = state2.position;
}
ch = state2.input.charCodeAt(++state2.position);
}
if (allowComments && ch === 35) {
do {
ch = state2.input.charCodeAt(++state2.position);
} while (ch !== 10 && ch !== 13 && ch !== 0);
}
if (isEol(ch)) {
readLineBreak(state2);
ch = state2.input.charCodeAt(state2.position);
lineBreaks++;
state2.lineIndent = 0;
while (ch === 32) {
state2.lineIndent++;
ch = state2.input.charCodeAt(++state2.position);
}
} else {
break;
}
}
if (checkIndent !== -1 && lineBreaks !== 0 && state2.lineIndent < checkIndent) {
throwWarning(state2, "deficient indentation");
}
return lineBreaks;
}
function testDocumentSeparator(state2) {
let _position = state2.position;
let ch = state2.input.charCodeAt(_position);
if ((ch === 45 || ch === 46) && ch === state2.input.charCodeAt(_position + 1) && ch === state2.input.charCodeAt(_position + 2)) {
_position += 3;
ch = state2.input.charCodeAt(_position);
if (ch === 0 || isWsOrEol(ch)) {
return true;
}
}
return false;
}
function writeFoldedLines(state2, count) {
if (count === 1) {
state2.result += " ";
} else if (count > 1) {
state2.result += common2.repeat("\n", count - 1);
}
}
function readPlainScalar(state2, nodeIndent, withinFlowCollection) {
let captureStart;
let captureEnd;
let hasPendingContent;
let _line;
let _lineStart;
let _lineIndent;
const _kind = state2.kind;
const _result = state2.result;
let ch = state2.input.charCodeAt(state2.position);
if (isWsOrEol(ch) || isFlowIndicator(ch) || ch === 35 || ch === 38 || ch === 42 || ch === 33 || ch === 124 || ch === 62 || ch === 39 || ch === 34 || ch === 37 || ch === 64 || ch === 96) {
return false;
}
if (ch === 63 || ch === 45) {
const following = state2.input.charCodeAt(state2.position + 1);
if (isWsOrEol(following) || withinFlowCollection && isFlowIndicator(following)) {
return false;
}
}
state2.kind = "scalar";
state2.result = "";
captureStart = captureEnd = state2.position;
hasPendingContent = false;
while (ch !== 0) {
if (ch === 58) {
const following = state2.input.charCodeAt(state2.position + 1);
if (isWsOrEol(following) || withinFlowCollection && isFlowIndicator(following)) {
break;
}
} else if (ch === 35) {
const preceding = state2.input.charCodeAt(state2.position - 1);
if (isWsOrEol(preceding)) {
break;
}
} else if (state2.position === state2.lineStart && testDocumentSeparator(state2) || withinFlowCollection && isFlowIndicator(ch)) {
break;
} else if (isEol(ch)) {
_line = state2.line;
_lineStart = state2.lineStart;
_lineIndent = state2.lineIndent;
skipSeparationSpace(state2, false, -1);
if (state2.lineIndent >= nodeIndent) {
hasPendingContent = true;
ch = state2.input.charCodeAt(state2.position);
continue;
} else {
state2.position = captureEnd;
state2.line = _line;
state2.lineStart = _lineStart;
state2.lineIndent = _lineIndent;
break;
}
}
if (hasPendingContent) {
captureSegment(state2, captureStart, captureEnd, false);
writeFoldedLines(state2, state2.line - _line);
captureStart = captureEnd = state2.position;
hasPendingContent = false;
}
if (!isWhiteSpace(ch)) {
captureEnd = state2.position + 1;
}
ch = state2.input.charCodeAt(++state2.position);
}
captureSegment(state2, captureStart, captureEnd, false);
if (state2.result) {
return true;
}
state2.kind = _kind;
state2.result = _result;
return false;
}
function readSingleQuotedScalar(state2, nodeIndent) {
let captureStart;
let captureEnd;
let ch = state2.input.charCodeAt(state2.position);
if (ch !== 39) {
return false;
}
state2.kind = "scalar";
state2.result = "";
state2.position++;
captureStart = captureEnd = state2.position;
while ((ch = state2.input.charCodeAt(state2.position)) !== 0) {
if (ch === 39) {
captureSegment(state2, captureStart, state2.position, true);
ch = state2.input.charCodeAt(++state2.position);
if (ch === 39) {
captureStart = state2.position;
state2.position++;
captureEnd = state2.position;
} else {
return true;
}
} else if (isEol(ch)) {
captureSegment(state2, captureStart, captureEnd, true);
writeFoldedLines(state2, skipSeparationSpace(state2, false, nodeIndent));
captureStart = captureEnd = state2.position;
} else if (state2.position === state2.lineStart && testDocumentSeparator(state2)) {
throwError(state2, "unexpected end of the document within a single quoted scalar");
} else {
state2.position++;
if (!isWhiteSpace(ch)) {
captureEnd = state2.position;
}
}
}
throwError(state2, "unexpected end of the stream within a single quoted scalar");
}
function readDoubleQuotedScalar(state2, nodeIndent) {
let captureStart;
let captureEnd;
let tmp;
let ch = state2.input.charCodeAt(state2.position);
if (ch !== 34) {
return false;
}
state2.kind = "scalar";
state2.result = "";
state2.position++;
captureStart = captureEnd = state2.position;
while ((ch = state2.input.charCodeAt(state2.position)) !== 0) {
if (ch === 34) {
captureSegment(state2, captureStart, state2.position, true);
state2.position++;
return true;
} else if (ch === 92) {
captureSegment(state2, captureStart, state2.position, true);
ch = state2.input.charCodeAt(++state2.position);
if (isEol(ch)) {
skipSeparationSpace(state2, false, nodeIndent);
} else if (ch < 256 && simpleEscapeCheck[ch]) {
state2.result += simpleEscapeMap[ch];
state2.position++;
} else if ((tmp = escapedHexLen(ch)) > 0) {
let hexLength = tmp;
let hexResult = 0;
for (; hexLength > 0; hexLength--) {
ch = state2.input.charCodeAt(++state2.position);
if ((tmp = fromHexCode(ch)) >= 0) {
hexResult = (hexResult << 4) + tmp;
} else {
throwError(state2, "expected hexadecimal character");
}
}
state2.result += charFromCodepoint(hexResult);
state2.position++;
} else {
throwError(state2, "unknown escape sequence");
}
captureStart = captureEnd = state2.position;
} else if (isEol(ch)) {
captureSegment(state2, captureStart, captureEnd, true);
writeFoldedLines(state2, skipSeparationSpace(state2, false, nodeIndent));
captureStart = captureEnd = state2.position;
} else if (state2.position === state2.lineStart && testDocumentSeparator(state2)) {
throwError(state2, "unexpected end of the document within a double quoted scalar");
} else {
state2.position++;
if (!isWhiteSpace(ch)) {
captureEnd = state2.position;
}
}
}
throwError(state2, "unexpected end of the stream within a double quoted scalar");
}
function readFlowCollection(state2, nodeIndent) {
let readNext = true;
let _line;
let _lineStart;
let _pos;
const _tag = state2.tag;
let _result;
const _anchor2 = state2.anchor;
let terminator;
let isPair;
let isExplicitPair;
let isMapping;
const overridableKeys = /* @__PURE__ */ Object.create(null);
let keyNode;
let keyTag;
let valueNode;
let ch = state2.input.charCodeAt(state2.position);
if (ch === 91) {
terminator = 93;
isMapping = false;
_result = [];
} else if (ch === 123) {
terminator = 125;
isMapping = true;
_result = {};
} else {
return false;
}
if (state2.anchor !== null) {
storeAnchor(state2, state2.anchor, _result);
}
ch = state2.input.charCodeAt(++state2.position);
while (ch !== 0) {
skipSeparationSpace(state2, true, nodeIndent);
ch = state2.input.charCodeAt(state2.position);
if (ch === terminator) {
state2.position++;
state2.tag = _tag;
state2.anchor = _anchor2;
state2.kind = isMapping ? "mapping" : "sequence";
state2.result = _result;
return true;
} else if (!readNext) {
throwError(state2, "missed comma between flow collection entries");
} else if (ch === 44) {
throwError(state2, "expected the node content, but found ','");
}
keyTag = keyNode = valueNode = null;
isPair = isExplicitPair = false;
if (ch === 63) {
const following = state2.input.charCodeAt(state2.position + 1);
if (isWsOrEol(following)) {
isPair = isExplicitPair = true;
state2.position++;
skipSeparationSpace(state2, true, nodeIndent);
}
}
_line = state2.line;
_lineStart = state2.lineStart;
_pos = state2.position;
composeNode(state2, nodeIndent, CONTEXT_FLOW_IN, false, true);
keyTag = state2.tag;
keyNode = state2.result;
skipSeparationSpace(state2, true, nodeIndent);
ch = state2.input.charCodeAt(state2.position);
if ((isExplicitPair || state2.line === _line) && ch === 58) {
isPair = true;
ch = state2.input.charCodeAt(++state2.position);
skipSeparationSpace(state2, true, nodeIndent);
composeNode(state2, nodeIndent, CONTEXT_FLOW_IN, false, true);
valueNode = state2.result;
}
if (isMapping) {
storeMappingPair(state2, _result, overridableKeys, keyTag, keyNode, valueNode, _line, _lineStart, _pos);
} else if (isPair) {
_result.push(storeMappingPair(state2, null, overridableKeys, keyTag, keyNode, valueNode, _line, _lineStart, _pos));
} else {
_result.push(keyNode);
}
skipSeparationSpace(state2, true, nodeIndent);
ch = state2.input.charCodeAt(state2.position);
if (ch === 44) {
readNext = true;
ch = state2.input.charCodeAt(++state2.position);
} else {
readNext = false;
}
}
throwError(state2, "unexpected end of the stream within a flow collection");
}
function readBlockScalar(state2, nodeIndent) {
let folding;
let chomping = CHOMPING_CLIP;
let didReadContent = false;
let detectedIndent = false;
let textIndent = nodeIndent;
let emptyLines = 0;
let atMoreIndented = false;
let tmp;
let ch = state2.input.charCodeAt(state2.position);
if (ch === 124) {
folding = false;
} else if (ch === 62) {
folding = true;
} else {
return false;
}
state2.kind = "scalar";
state2.result = "";
while (ch !== 0) {
ch = state2.input.charCodeAt(++state2.position);
if (ch === 43 || ch === 45) {
if (CHOMPING_CLIP === chomping) {
chomping = ch === 43 ? CHOMPING_KEEP : CHOMPING_STRIP;
} else {
throwError(state2, "repeat of a chomping mode identifier");
}
} else if ((tmp = fromDecimalCode(ch)) >= 0) {
if (tmp === 0) {
throwError(state2, "bad explicit indentation width of a block scalar; it cannot be less than one");
} else if (!detectedIndent) {
textIndent = nodeIndent + tmp - 1;
detectedIndent = true;
} else {
throwError(state2, "repeat of an indentation width identifier");
}
} else {
break;
}
}
if (isWhiteSpace(ch)) {
do {
ch = state2.input.charCodeAt(++state2.position);
} while (isWhiteSpace(ch));
if (ch === 35) {
do {
ch = state2.input.charCodeAt(++state2.position);
} while (!isEol(ch) && ch !== 0);
}
}
while (ch !== 0) {
readLineBreak(state2);
state2.lineIndent = 0;
ch = state2.input.charCodeAt(state2.position);
while ((!detectedIndent || state2.lineIndent < textIndent) && ch === 32) {
state2.lineIndent++;
ch = state2.input.charCodeAt(++state2.position);
}
if (!detectedIndent && state2.lineIndent > textIndent) {
textIndent = state2.lineIndent;
}
if (isEol(ch)) {
emptyLines++;
continue;
}
if (!detectedIndent && textIndent === 0) {
throwError(state2, "missing indentation for block scalar");
}
if (state2.lineIndent < textIndent) {
if (chomping === CHOMPING_KEEP) {
state2.result += common2.repeat("\n", didReadContent ? 1 + emptyLines : emptyLines);
} else if (chomping === CHOMPING_CLIP) {
if (didReadContent) {
state2.result += "\n";
}
}
break;
}
if (folding) {
if (isWhiteSpace(ch)) {
atMoreIndented = true;
state2.result += common2.repeat("\n", didReadContent ? 1 + emptyLines : emptyLines);
} else if (atMoreIndented) {
atMoreIndented = false;
state2.result += common2.repeat("\n", emptyLines + 1);
} else if (emptyLines === 0) {
if (didReadContent) {
state2.result += " ";
}
} else {
state2.result += common2.repeat("\n", emptyLines);
}
} else {
state2.result += common2.repeat("\n", didReadContent ? 1 + emptyLines : emptyLines);
}
didReadContent = true;
detectedIndent = true;
emptyLines = 0;
const captureStart = state2.position;
while (!isEol(ch) && ch !== 0) {
ch = state2.input.charCodeAt(++state2.position);
}
captureSegment(state2, captureStart, state2.position, false);
}
return true;
}
function readBlockSequence(state2, nodeIndent) {
const _tag = state2.tag;
const _anchor2 = state2.anchor;
const _result = [];
let detected = false;
if (state2.firstTabInLine !== -1) return false;
if (state2.anchor !== null) {
storeAnchor(state2, state2.anchor, _result);
}
let ch = state2.input.charCodeAt(state2.position);
while (ch !== 0) {
if (state2.firstTabInLine !== -1) {
state2.position = state2.firstTabInLine;
throwError(state2, "tab characters must not be used in indentation");
}
if (ch !== 45) {
break;
}
const following = state2.input.charCodeAt(state2.position + 1);
if (!isWsOrEol(following)) {
break;
}
detected = true;
state2.position++;
if (skipSeparationSpace(state2, true, -1)) {
if (state2.lineIndent <= nodeIndent) {
_result.push(null);
ch = state2.input.charCodeAt(state2.position);
continue;
}
}
const _line = state2.line;
composeNode(state2, nodeIndent, CONTEXT_BLOCK_IN, false, true);
_result.push(state2.result);
skipSeparationSpace(state2, true, -1);
ch = state2.input.charCodeAt(state2.position);
if ((state2.line === _line || state2.lineIndent > nodeIndent) && ch !== 0) {
throwError(state2, "bad indentation of a sequence entry");
} else if (state2.lineIndent < nodeIndent) {
break;
}
}
if (detected) {
state2.tag = _tag;
state2.anchor = _anchor2;
state2.kind = "sequence";
state2.result = _result;
return true;
}
return false;
}
function readBlockMapping(state2, nodeIndent, flowIndent) {
let allowCompact;
let _keyLine;
let _keyLineStart;
let _keyPos;
const _tag = state2.tag;
const _anchor2 = state2.anchor;
const _result = {};
const overridableKeys = /* @__PURE__ */ Object.create(null);
let keyTag = null;
let keyNode = null;
let valueNode = null;
let atExplicitKey = false;
let detected = false;
if (state2.firstTabInLine !== -1) return false;
if (state2.anchor !== null) {
storeAnchor(state2, state2.anchor, _result);
}
let ch = state2.input.charCodeAt(state2.position);
while (ch !== 0) {
if (!atExplicitKey && state2.firstTabInLine !== -1) {
state2.position = state2.firstTabInLine;
throwError(state2, "tab characters must not be used in indentation");
}
const following = state2.input.charCodeAt(state2.position + 1);
const _line = state2.line;
if ((ch === 63 || ch === 58) && isWsOrEol(following)) {
if (ch === 63) {
if (atExplicitKey) {
storeMappingPair(state2, _result, overridableKeys, keyTag, keyNode, null, _keyLine, _keyLineStart, _keyPos);
keyTag = keyNode = valueNode = null;
}
detected = true;
atExplicitKey = true;
allowCompact = true;
} else if (atExplicitKey) {
atExplicitKey = false;
allowCompact = true;
} else {
throwError(state2, "incomplete explicit mapping pair; a key node is missed; or followed by a non-tabulated empty line");
}
state2.position += 1;
ch = following;
} else {
_keyLine = state2.line;
_keyLineStart = state2.lineStart;
_keyPos = state2.position;
if (!composeNode(state2, flowIndent, CONTEXT_FLOW_OUT, false, true)) {
break;
}
if (state2.line === _line) {
ch = state2.input.charCodeAt(state2.position);
while (isWhiteSpace(ch)) {
ch = state2.input.charCodeAt(++state2.position);
}
if (ch === 58) {
ch = state2.input.charCodeAt(++state2.position);
if (!isWsOrEol(ch)) {
throwError(state2, "a whitespace character is expected after the key-value separator within a block mapping");
}
if (atExplicitKey) {
storeMappingPair(state2, _result, overridableKeys, keyTag, keyNode, null, _keyLine, _keyLineStart, _keyPos);
keyTag = keyNode = valueNode = null;
}
detected = true;
atExplicitKey = false;
allowCompact = false;
keyTag = state2.tag;
keyNode = state2.result;
} else if (detected) {
throwError(state2, "can not read an implicit mapping pair; a colon is missed");
} else {
state2.tag = _tag;
state2.anchor = _anchor2;
return true;
}
} else if (detected) {
throwError(state2, "can not read a block mapping entry; a multiline key may not be an implicit key");
} else {
state2.tag = _tag;
state2.anchor = _anchor2;
return true;
}
}
if (state2.line === _line || state2.lineIndent > nodeIndent) {
if (atExplicitKey) {
_keyLine = state2.line;
_keyLineStart = state2.lineStart;
_keyPos = state2.position;
}
if (composeNode(state2, nodeIndent, CONTEXT_BLOCK_OUT, true, allowCompact)) {
if (atExplicitKey) {
keyNode = state2.result;
} else {
valueNode = state2.result;
}
}
if (!atExplicitKey) {
storeMappingPair(state2, _result, overridableKeys, keyTag, keyNode, valueNode, _keyLine, _keyLineStart, _keyPos);
keyTag = keyNode = valueNode = null;
}
skipSeparationSpace(state2, true, -1);
ch = state2.input.charCodeAt(state2.position);
}
if ((state2.line === _line || state2.lineIndent > nodeIndent) && ch !== 0) {
throwError(state2, "bad indentation of a mapping entry");
} else if (state2.lineIndent < nodeIndent) {
break;
}
}
if (atExplicitKey) {
storeMappingPair(state2, _result, overridableKeys, keyTag, keyNode, null, _keyLine, _keyLineStart, _keyPos);
}
if (detected) {
state2.tag = _tag;
state2.anchor = _anchor2;
state2.kind = "mapping";
state2.result = _result;
}
return detected;
}
function readTagProperty(state2) {
let isVerbatim = false;
let isNamed = false;
let tagHandle;
let tagName;
let ch = state2.input.charCodeAt(state2.position);
if (ch !== 33) return false;
if (state2.tag !== null) {
throwError(state2, "duplication of a tag property");
}
ch = state2.input.charCodeAt(++state2.position);
if (ch === 60) {
isVerbatim = true;
ch = state2.input.charCodeAt(++state2.position);
} else if (ch === 33) {
isNamed = true;
tagHandle = "!!";
ch = state2.input.charCodeAt(++state2.position);
} else {
tagHandle = "!";
}
let _position = state2.position;
if (isVerbatim) {
do {
ch = state2.input.charCodeAt(++state2.position);
} while (ch !== 0 && ch !== 62);
if (state2.position < state2.length) {
tagName = state2.input.slice(_position, state2.position);
ch = state2.input.charCodeAt(++state2.position);
} else {
throwError(state2, "unexpected end of the stream within a verbatim tag");
}
} else {
while (ch !== 0 && !isWsOrEol(ch)) {
if (ch === 33) {
if (!isNamed) {
tagHandle = state2.input.slice(_position - 1, state2.position + 1);
if (!PATTERN_TAG_HANDLE.test(tagHandle)) {
throwError(state2, "named tag handle cannot contain such characters");
}
isNamed = true;
_position = state2.position + 1;
} else {
throwError(state2, "tag suffix cannot contain exclamation marks");
}
}
ch = state2.input.charCodeAt(++state2.position);
}
tagName = state2.input.slice(_position, state2.position);
if (PATTERN_FLOW_INDICATORS.test(tagName)) {
throwError(state2, "tag suffix cannot contain flow indicator characters");
}
}
if (tagName && !PATTERN_TAG_URI.test(tagName)) {
throwError(state2, "tag name cannot contain such characters: " + tagName);
}
try {
tagName = decodeURIComponent(tagName);
} catch (err) {
throwError(state2, "tag name is malformed: " + tagName);
}
if (isVerbatim) {
state2.tag = tagName;
} else if (_hasOwnProperty.call(state2.tagMap, tagHandle)) {
state2.tag = state2.tagMap[tagHandle] + tagName;
} else if (tagHandle === "!") {
state2.tag = "!" + tagName;
} else if (tagHandle === "!!") {
state2.tag = "tag:yaml.org,2002:" + tagName;
} else {
throwError(state2, 'undeclared tag handle "' + tagHandle + '"');
}
return true;
}
function readAnchorProperty(state2) {
let ch = state2.input.charCodeAt(state2.position);
if (ch !== 38) return false;
if (state2.anchor !== null) {
throwError(state2, "duplication of an anchor property");
}
ch = state2.input.charCodeAt(++state2.position);
const _position = state2.position;
while (ch !== 0 && !isWsOrEol(ch) && !isFlowIndicator(ch)) {
ch = state2.input.charCodeAt(++state2.position);
}
if (state2.position === _position) {
throwError(state2, "name of an anchor node must contain at least one character");
}
state2.anchor = state2.input.slice(_position, state2.position);
return true;
}
function readAlias(state2) {
let ch = state2.input.charCodeAt(state2.position);
if (ch !== 42) return false;
ch = state2.input.charCodeAt(++state2.position);
const _position = state2.position;
while (ch !== 0 && !isWsOrEol(ch) && !isFlowIndicator(ch)) {
ch = state2.input.charCodeAt(++state2.position);
}
if (state2.position === _position) {
throwError(state2, "name of an alias node must contain at least one character");
}
const alias = state2.input.slice(_position, state2.position);
if (!_hasOwnProperty.call(state2.anchorMap, alias)) {
throwError(state2, 'unidentified alias "' + alias + '"');
}
state2.result = state2.anchorMap[alias];
skipSeparationSpace(state2, true, -1);
return true;
}
function tryReadBlockMappingFromProperty(state2, propertyStart, nodeIndent, flowIndent) {
const fallbackState = snapshotState(state2);
beginAnchorTransaction(state2);
restoreState(state2, propertyStart);
state2.tag = null;
state2.anchor = null;
state2.kind = null;
state2.result = null;
if (readBlockMapping(state2, nodeIndent, flowIndent) && state2.kind === "mapping") {
commitAnchorTransaction(state2);
return true;
}
rollbackAnchorTransaction(state2);
restoreState(state2, fallbackState);
return false;
}
function composeNode(state2, parentIndent, nodeContext, allowToSeek, allowCompact) {
let allowBlockScalars;
let allowBlockCollections;
let indentStatus = 1;
let atNewLine = false;
let hasContent = false;
let propertyStart = null;
let type2;
let flowIndent;
let blockIndent;
if (state2.depth >= state2.maxDepth) {
throwError(state2, "nesting exceeded maxDepth (" + state2.maxDepth + ")");
}
state2.depth += 1;
if (state2.listener !== null) {
state2.listener("open", state2);
}
state2.tag = null;
state2.anchor = null;
state2.kind = null;
state2.result = null;
const allowBlockStyles = allowBlockScalars = allowBlockCollections = CONTEXT_BLOCK_OUT === nodeContext || CONTEXT_BLOCK_IN === nodeContext;
if (allowToSeek) {
if (skipSeparationSpace(state2, true, -1)) {
atNewLine = true;
if (state2.lineIndent > parentIndent) {
indentStatus = 1;
} else if (state2.lineIndent === parentIndent) {
indentStatus = 0;
} else if (state2.lineIndent < parentIndent) {
indentStatus = -1;
}
}
}
if (indentStatus === 1) {
while (true) {
const ch = state2.input.charCodeAt(state2.position);
const propertyState = snapshotState(state2);
if (atNewLine && (ch === 33 && state2.tag !== null || ch === 38 && state2.anchor !== null)) {
break;
}
if (!readTagProperty(state2) && !readAnchorProperty(state2)) {
break;
}
if (propertyStart === null) {
propertyStart = propertyState;
}
if (skipSeparationSpace(state2, true, -1)) {
atNewLine = true;
allowBlockCollections = allowBlockStyles;
if (state2.lineIndent > parentIndent) {
indentStatus = 1;
} else if (state2.lineIndent === parentIndent) {
indentStatus = 0;
} else if (state2.lineIndent < parentIndent) {
indentStatus = -1;
}
} else {
allowBlockCollections = false;
}
}
}
if (allowBlockCollections) {
allowBlockCollections = atNewLine || allowCompact;
}
if (indentStatus === 1 || CONTEXT_BLOCK_OUT === nodeContext) {
if (CONTEXT_FLOW_IN === nodeContext || CONTEXT_FLOW_OUT === nodeContext) {
flowIndent = parentIndent;
} else {
flowIndent = parentIndent + 1;
}
blockIndent = state2.position - state2.lineStart;
if (indentStatus === 1) {
if (allowBlockCollections && (readBlockSequence(state2, blockIndent) || readBlockMapping(state2, blockIndent, flowIndent)) || readFlowCollection(state2, flowIndent)) {
hasContent = true;
} else {
const ch = state2.input.charCodeAt(state2.position);
if (propertyStart !== null && allowBlockStyles && !allowBlockCollections && ch !== 124 && ch !== 62 && tryReadBlockMappingFromProperty(
state2,
propertyStart,
propertyStart.position - propertyStart.lineStart,
flowIndent
)) {
hasContent = true;
} else if (allowBlockScalars && readBlockScalar(state2, flowIndent) || readSingleQuotedScalar(state2, flowIndent) || readDoubleQuotedScalar(state2, flowIndent)) {
hasContent = true;
} else if (readAlias(state2)) {
hasContent = true;
if (state2.tag !== null || state2.anchor !== null) {
throwError(state2, "alias node should not have any properties");
}
} else if (readPlainScalar(state2, flowIndent, CONTEXT_FLOW_IN === nodeContext)) {
hasContent = true;
if (state2.tag === null) {
state2.tag = "?";
}
}
if (state2.anchor !== null) {
storeAnchor(state2, state2.anchor, state2.result);
}
}
} else if (indentStatus === 0) {
hasContent = allowBlockCollections && readBlockSequence(state2, blockIndent);
}
}
if (state2.tag === null) {
if (state2.anchor !== null) {
storeAnchor(state2, state2.anchor, state2.result);
}
} else if (state2.tag === "?") {
if (state2.result !== null && state2.kind !== "scalar") {
throwError(state2, 'unacceptable node kind for !<?> tag; it should be "scalar", not "' + state2.kind + '"');
}
for (let typeIndex = 0, typeQuantity = state2.implicitTypes.length; typeIndex < typeQuantity; typeIndex += 1) {
type2 = state2.implicitTypes[typeIndex];
if (type2.resolve(state2.result)) {
state2.result = type2.construct(state2.result);
state2.tag = type2.tag;
if (state2.anchor !== null) {
storeAnchor(state2, state2.anchor, state2.result);
}
break;
}
}
} else if (state2.tag !== "!") {
if (_hasOwnProperty.call(state2.typeMap[state2.kind || "fallback"], state2.tag)) {
type2 = state2.typeMap[state2.kind || "fallback"][state2.tag];
} else {
type2 = null;
const typeList = state2.typeMap.multi[state2.kind || "fallback"];
for (let typeIndex = 0, typeQuantity = typeList.length; typeIndex < typeQuantity; typeIndex += 1) {
if (state2.tag.slice(0, typeList[typeIndex].tag.length) === typeList[typeIndex].tag) {
type2 = typeList[typeIndex];
break;
}
}
}
if (!type2) {
throwError(state2, "unknown tag !<" + state2.tag + ">");
}
if (state2.result !== null && type2.kind !== state2.kind) {
throwError(state2, "unacceptable node kind for !<" + state2.tag + '> tag; it should be "' + type2.kind + '", not "' + state2.kind + '"');
}
if (!type2.resolve(state2.result, state2.tag)) {
throwError(state2, "cannot resolve a node with !<" + state2.tag + "> explicit tag");
} else {
state2.result = type2.construct(state2.result, state2.tag);
if (state2.anchor !== null) {
storeAnchor(state2, state2.anchor, state2.result);
}
}
}
if (state2.listener !== null) {
state2.listener("close", state2);
}
state2.depth -= 1;
return state2.tag !== null || state2.anchor !== null || hasContent;
}
function readDocument(state2) {
const documentStart = state2.position;
let hasDirectives = false;
let ch;
state2.version = null;
state2.checkLineBreaks = state2.legacy;
state2.tagMap = /* @__PURE__ */ Object.create(null);
state2.anchorMap = /* @__PURE__ */ Object.create(null);
while ((ch = state2.input.charCodeAt(state2.position)) !== 0) {
skipSeparationSpace(state2, true, -1);
ch = state2.input.charCodeAt(state2.position);
if (state2.lineIndent > 0 || ch !== 37) {
break;
}
hasDirectives = true;
ch = state2.input.charCodeAt(++state2.position);
let _position = state2.position;
while (ch !== 0 && !isWsOrEol(ch)) {
ch = state2.input.charCodeAt(++state2.position);
}
const directiveName = state2.input.slice(_position, state2.position);
const directiveArgs = [];
if (directiveName.length < 1) {
throwError(state2, "directive name must not be less than one character in length");
}
while (ch !== 0) {
while (isWhiteSpace(ch)) {
ch = state2.input.charCodeAt(++state2.position);
}
if (ch === 35) {
do {
ch = state2.input.charCodeAt(++state2.position);
} while (ch !== 0 && !isEol(ch));
break;
}
if (isEol(ch)) break;
_position = state2.position;
while (ch !== 0 && !isWsOrEol(ch)) {
ch = state2.input.charCodeAt(++state2.position);
}
directiveArgs.push(state2.input.slice(_position, state2.position));
}
if (ch !== 0) readLineBreak(state2);
if (_hasOwnProperty.call(directiveHandlers, directiveName)) {
directiveHandlers[directiveName](state2, directiveName, directiveArgs);
} else {
throwWarning(state2, 'unknown document directive "' + directiveName + '"');
}
}
skipSeparationSpace(state2, true, -1);
if (state2.lineIndent === 0 && state2.input.charCodeAt(state2.position) === 45 && state2.input.charCodeAt(state2.position + 1) === 45 && state2.input.charCodeAt(state2.position + 2) === 45) {
state2.position += 3;
skipSeparationSpace(state2, true, -1);
} else if (hasDirectives) {
throwError(state2, "directives end mark is expected");
}
composeNode(state2, state2.lineIndent - 1, CONTEXT_BLOCK_OUT, false, true);
skipSeparationSpace(state2, true, -1);
if (state2.checkLineBreaks && PATTERN_NON_ASCII_LINE_BREAKS.test(state2.input.slice(documentStart, state2.position))) {
throwWarning(state2, "non-ASCII line breaks are interpreted as content");
}
state2.documents.push(state2.result);
if (state2.position === state2.lineStart && testDocumentSeparator(state2)) {
if (state2.input.charCodeAt(state2.position) === 46) {
state2.position += 3;
skipSeparationSpace(state2, true, -1);
}
return;
}
if (state2.position < state2.length - 1) {
throwError(state2, "end of the stream or a document separator is expected");
}
}
function loadDocuments(input, options) {
input = String(input);
options = options || {};
if (input.length !== 0) {
if (input.charCodeAt(input.length - 1) !== 10 && input.charCodeAt(input.length - 1) !== 13) {
input += "\n";
}
if (input.charCodeAt(0) === 65279) {
input = input.slice(1);
}
}
const state2 = new State(input, options);
const nullpos = input.indexOf("\0");
if (nullpos !== -1) {
state2.position = nullpos;
throwError(state2, "null byte is not allowed in input");
}
state2.input += "\0";
while (state2.input.charCodeAt(state2.position) === 32) {
state2.lineIndent += 1;
state2.position += 1;
}
while (state2.position < state2.length - 1) {
readDocument(state2);
}
return state2.documents;
}
function loadAll2(input, iterator, options) {
if (iterator !== null && typeof iterator === "object" && typeof options === "undefined") {
options = iterator;
iterator = null;
}
const documents = loadDocuments(input, options);
if (typeof iterator !== "function") {
return documents;
}
for (let index2 = 0, length = documents.length; index2 < length; index2 += 1) {
iterator(documents[index2]);
}
}
function load2(input, options) {
const documents = loadDocuments(input, options);
if (documents.length === 0) {
return void 0;
} else if (documents.length === 1) {
return documents[0];
}
throw new YAMLException2("expected a single document in the stream, but found more");
}
loader.loadAll = loadAll2;
loader.load = load2;
return loader;
}
var dumper = {};
var hasRequiredDumper;
function requireDumper() {
if (hasRequiredDumper) return dumper;
hasRequiredDumper = 1;
const common2 = requireCommon();
const YAMLException2 = requireException();
const DEFAULT_SCHEMA2 = require_default();
const _toString = Object.prototype.toString;
const _hasOwnProperty = Object.prototype.hasOwnProperty;
const CHAR_BOM = 65279;
const CHAR_TAB = 9;
const CHAR_LINE_FEED = 10;
const CHAR_CARRIAGE_RETURN = 13;
const CHAR_SPACE = 32;
const CHAR_EXCLAMATION = 33;
const CHAR_DOUBLE_QUOTE = 34;
const CHAR_SHARP = 35;
const CHAR_PERCENT = 37;
const CHAR_AMPERSAND = 38;
const CHAR_SINGLE_QUOTE = 39;
const CHAR_ASTERISK = 42;
const CHAR_COMMA = 44;
const CHAR_MINUS = 45;
const CHAR_COLON = 58;
const CHAR_EQUALS = 61;
const CHAR_GREATER_THAN = 62;
const CHAR_QUESTION = 63;
const CHAR_COMMERCIAL_AT = 64;
const CHAR_LEFT_SQUARE_BRACKET = 91;
const CHAR_RIGHT_SQUARE_BRACKET = 93;
const CHAR_GRAVE_ACCENT = 96;
const CHAR_LEFT_CURLY_BRACKET = 123;
const CHAR_VERTICAL_LINE = 124;
const CHAR_RIGHT_CURLY_BRACKET = 125;
const ESCAPE_SEQUENCES = {};
ESCAPE_SEQUENCES[0] = "\\0";
ESCAPE_SEQUENCES[7] = "\\a";
ESCAPE_SEQUENCES[8] = "\\b";
ESCAPE_SEQUENCES[9] = "\\t";
ESCAPE_SEQUENCES[10] = "\\n";
ESCAPE_SEQUENCES[11] = "\\v";
ESCAPE_SEQUENCES[12] = "\\f";
ESCAPE_SEQUENCES[13] = "\\r";
ESCAPE_SEQUENCES[27] = "\\e";
ESCAPE_SEQUENCES[34] = '\\"';
ESCAPE_SEQUENCES[92] = "\\\\";
ESCAPE_SEQUENCES[133] = "\\N";
ESCAPE_SEQUENCES[160] = "\\_";
ESCAPE_SEQUENCES[8232] = "\\L";
ESCAPE_SEQUENCES[8233] = "\\P";
const DEPRECATED_BOOLEANS_SYNTAX = [
"y",
"Y",
"yes",
"Yes",
"YES",
"on",
"On",
"ON",
"n",
"N",
"no",
"No",
"NO",
"off",
"Off",
"OFF"
];
const DEPRECATED_BASE60_SYNTAX = /^[-+]?[0-9_]+(?::[0-9_]+)+(?:\.[0-9_]*)?$/;
function compileStyleMap(schema2, map2) {
if (map2 === null) return {};
const result = {};
const keys = Object.keys(map2);
for (let index2 = 0, length = keys.length; index2 < length; index2 += 1) {
let tag2 = keys[index2];
let style = String(map2[tag2]);
if (tag2.slice(0, 2) === "!!") {
tag2 = "tag:yaml.org,2002:" + tag2.slice(2);
}
const type2 = schema2.compiledTypeMap["fallback"][tag2];
if (type2 && _hasOwnProperty.call(type2.styleAliases, style)) {
style = type2.styleAliases[style];
}
result[tag2] = style;
}
return result;
}
function encodeHex(character) {
let handle;
let length;
const string = character.toString(16).toUpperCase();
if (character <= 255) {
handle = "x";
length = 2;
} else if (character <= 65535) {
handle = "u";
length = 4;
} else if (character <= 4294967295) {
handle = "U";
length = 8;
} else {
throw new YAMLException2("code point within a string may not be greater than 0xFFFFFFFF");
}
return "\\" + handle + common2.repeat("0", length - string.length) + string;
}
const QUOTING_TYPE_SINGLE = 1;
const QUOTING_TYPE_DOUBLE = 2;
function State(options) {
this.schema = options["schema"] || DEFAULT_SCHEMA2;
this.indent = Math.max(1, options["indent"] || 2);
this.noArrayIndent = options["noArrayIndent"] || false;
this.skipInvalid = options["skipInvalid"] || false;
this.flowLevel = common2.isNothing(options["flowLevel"]) ? -1 : options["flowLevel"];
this.styleMap = compileStyleMap(this.schema, options["styles"] || null);
this.sortKeys = options["sortKeys"] || false;
this.lineWidth = options["lineWidth"] || 80;
this.noRefs = options["noRefs"] || false;
this.noCompatMode = options["noCompatMode"] || false;
this.condenseFlow = options["condenseFlow"] || false;
this.quotingType = options["quotingType"] === '"' ? QUOTING_TYPE_DOUBLE : QUOTING_TYPE_SINGLE;
this.forceQuotes = options["forceQuotes"] || false;
this.replacer = typeof options["replacer"] === "function" ? options["replacer"] : null;
this.implicitTypes = this.schema.compiledImplicit;
this.explicitTypes = this.schema.compiledExplicit;
this.tag = null;
this.result = "";
this.duplicates = [];
this.usedDuplicates = null;
}
function indentString(string, spaces) {
const ind = common2.repeat(" ", spaces);
let position = 0;
let result = "";
const length = string.length;
while (position < length) {
let line;
const next2 = string.indexOf("\n", position);
if (next2 === -1) {
line = string.slice(position);
position = length;
} else {
line = string.slice(position, next2 + 1);
position = next2 + 1;
}
if (line.length && line !== "\n") result += ind;
result += line;
}
return result;
}
function generateNextLine(state2, level) {
return "\n" + common2.repeat(" ", state2.indent * level);
}
function testImplicitResolving(state2, str2) {
for (let index2 = 0, length = state2.implicitTypes.length; index2 < length; index2 += 1) {
const type2 = state2.implicitTypes[index2];
if (type2.resolve(str2)) {
return true;
}
}
return false;
}
function isWhitespace(c) {
return c === CHAR_SPACE || c === CHAR_TAB;
}
function isPrintable(c) {
return c >= 32 && c <= 126 || c >= 161 && c <= 55295 && c !== 8232 && c !== 8233 || c >= 57344 && c <= 65533 && c !== CHAR_BOM || c >= 65536 && c <= 1114111;
}
function isNsCharOrWhitespace(c) {
return isPrintable(c) && c !== CHAR_BOM && // - b-char
c !== CHAR_CARRIAGE_RETURN && c !== CHAR_LINE_FEED;
}
function isPlainSafe(c, prev, inblock) {
const cIsNsCharOrWhitespace = isNsCharOrWhitespace(c);
const cIsNsChar = cIsNsCharOrWhitespace && !isWhitespace(c);
return (
// ns-plain-safe
(inblock ? cIsNsCharOrWhitespace : cIsNsCharOrWhitespace && // - c-flow-indicator
c !== CHAR_COMMA && c !== CHAR_LEFT_SQUARE_BRACKET && c !== CHAR_RIGHT_SQUARE_BRACKET && c !== CHAR_LEFT_CURLY_BRACKET && c !== CHAR_RIGHT_CURLY_BRACKET) && // ns-plain-char
c !== CHAR_SHARP && // false on '#'
!(prev === CHAR_COLON && !cIsNsChar) || // false on ': '
isNsCharOrWhitespace(prev) && !isWhitespace(prev) && c === CHAR_SHARP || // change to true on '[^ ]#'
prev === CHAR_COLON && cIsNsChar
);
}
function isPlainSafeFirst(c) {
return isPrintable(c) && c !== CHAR_BOM && !isWhitespace(c) && // - s-white
// - (c-indicator ::=
// “-” | “?” | “:” | “,” | “[” | “]” | “{” | “}”
c !== CHAR_MINUS && c !== CHAR_QUESTION && c !== CHAR_COLON && c !== CHAR_COMMA && c !== CHAR_LEFT_SQUARE_BRACKET && c !== CHAR_RIGHT_SQUARE_BRACKET && c !== CHAR_LEFT_CURLY_BRACKET && c !== CHAR_RIGHT_CURLY_BRACKET && // | “#” | “&” | “*” | “!” | “|” | “=” | “>” | “'” | “"”
c !== CHAR_SHARP && c !== CHAR_AMPERSAND && c !== CHAR_ASTERISK && c !== CHAR_EXCLAMATION && c !== CHAR_VERTICAL_LINE && c !== CHAR_EQUALS && c !== CHAR_GREATER_THAN && c !== CHAR_SINGLE_QUOTE && c !== CHAR_DOUBLE_QUOTE && // | “%” | “@” | “`”)
c !== CHAR_PERCENT && c !== CHAR_COMMERCIAL_AT && c !== CHAR_GRAVE_ACCENT;
}
function isPlainSafeLast(c) {
return !isWhitespace(c) && c !== CHAR_COLON;
}
function codePointAt(string, pos) {
const first = string.charCodeAt(pos);
let second;
if (first >= 55296 && first <= 56319 && pos + 1 < string.length) {
second = string.charCodeAt(pos + 1);
if (second >= 56320 && second <= 57343) {
return (first - 55296) * 1024 + second - 56320 + 65536;
}
}
return first;
}
function needIndentIndicator(string) {
const leadingSpaceRe = /^\n* /;
return leadingSpaceRe.test(string);
}
const STYLE_PLAIN = 1;
const STYLE_SINGLE = 2;
const STYLE_LITERAL = 3;
const STYLE_FOLDED = 4;
const STYLE_DOUBLE = 5;
function chooseScalarStyle(string, singleLineOnly, indentPerLevel, lineWidth, testAmbiguousType, quotingType, forceQuotes, inblock) {
let i;
let char = 0;
let prevChar = null;
let hasLineBreak = false;
let hasFoldableLine = false;
const shouldTrackWidth = lineWidth !== -1;
let previousLineBreak = -1;
let plain = isPlainSafeFirst(codePointAt(string, 0)) && isPlainSafeLast(codePointAt(string, string.length - 1));
if (singleLineOnly || forceQuotes) {
for (i = 0; i < string.length; char >= 65536 ? i += 2 : i++) {
char = codePointAt(string, i);
if (!isPrintable(char)) {
return STYLE_DOUBLE;
}
plain = plain && isPlainSafe(char, prevChar, inblock);
prevChar = char;
}
} else {
for (i = 0; i < string.length; char >= 65536 ? i += 2 : i++) {
char = codePointAt(string, i);
if (char === CHAR_LINE_FEED) {
hasLineBreak = true;
if (shouldTrackWidth) {
hasFoldableLine = hasFoldableLine || // Foldable line = too long, and not more-indented.
i - previousLineBreak - 1 > lineWidth && string[previousLineBreak + 1] !== " ";
previousLineBreak = i;
}
} else if (!isPrintable(char)) {
return STYLE_DOUBLE;
}
plain = plain && isPlainSafe(char, prevChar, inblock);
prevChar = char;
}
hasFoldableLine = hasFoldableLine || shouldTrackWidth && (i - previousLineBreak - 1 > lineWidth && string[previousLineBreak + 1] !== " ");
}
if (!hasLineBreak && !hasFoldableLine) {
if (plain && !forceQuotes && !testAmbiguousType(string)) {
return STYLE_PLAIN;
}
return quotingType === QUOTING_TYPE_DOUBLE ? STYLE_DOUBLE : STYLE_SINGLE;
}
if (indentPerLevel > 9 && needIndentIndicator(string)) {
return STYLE_DOUBLE;
}
if (!forceQuotes) {
return hasFoldableLine ? STYLE_FOLDED : STYLE_LITERAL;
}
return quotingType === QUOTING_TYPE_DOUBLE ? STYLE_DOUBLE : STYLE_SINGLE;
}
function writeScalar(state2, string, level, iskey, inblock) {
state2.dump = (function() {
if (string.length === 0) {
return state2.quotingType === QUOTING_TYPE_DOUBLE ? '""' : "''";
}
if (!state2.noCompatMode) {
if (DEPRECATED_BOOLEANS_SYNTAX.indexOf(string) !== -1 || DEPRECATED_BASE60_SYNTAX.test(string)) {
return state2.quotingType === QUOTING_TYPE_DOUBLE ? '"' + string + '"' : "'" + string + "'";
}
}
const indent = state2.indent * Math.max(1, level);
const lineWidth = state2.lineWidth === -1 ? -1 : Math.max(Math.min(state2.lineWidth, 40), state2.lineWidth - indent);
const singleLineOnly = iskey || // No block styles in flow mode.
state2.flowLevel > -1 && level >= state2.flowLevel;
function testAmbiguity(string2) {
return testImplicitResolving(state2, string2);
}
switch (chooseScalarStyle(
string,
singleLineOnly,
state2.indent,
lineWidth,
testAmbiguity,
state2.quotingType,
state2.forceQuotes && !iskey,
inblock
)) {
case STYLE_PLAIN:
return string;
case STYLE_SINGLE:
return "'" + string.replace(/'/g, "''") + "'";
case STYLE_LITERAL:
return "|" + blockHeader(string, state2.indent) + dropEndingNewline(indentString(string, indent));
case STYLE_FOLDED:
return ">" + blockHeader(string, state2.indent) + dropEndingNewline(indentString(foldString(string, lineWidth), indent));
case STYLE_DOUBLE:
return '"' + escapeString(string) + '"';
default:
throw new YAMLException2("impossible error: invalid scalar style");
}
})();
}
function blockHeader(string, indentPerLevel) {
const indentIndicator = needIndentIndicator(string) ? String(indentPerLevel) : "";
const clip = string[string.length - 1] === "\n";
const keep = clip && (string[string.length - 2] === "\n" || string === "\n");
const chomp = keep ? "+" : clip ? "" : "-";
return indentIndicator + chomp + "\n";
}
function dropEndingNewline(string) {
return string[string.length - 1] === "\n" ? string.slice(0, -1) : string;
}
function foldString(string, width) {
const lineRe = /(\n+)([^\n]*)/g;
let result = (function() {
let nextLF = string.indexOf("\n");
nextLF = nextLF !== -1 ? nextLF : string.length;
lineRe.lastIndex = nextLF;
return foldLine(string.slice(0, nextLF), width);
})();
let prevMoreIndented = string[0] === "\n" || string[0] === " ";
let moreIndented;
let match;
while (match = lineRe.exec(string)) {
const prefix = match[1];
const line = match[2];
moreIndented = line[0] === " ";
result += prefix + (!prevMoreIndented && !moreIndented && line !== "" ? "\n" : "") + foldLine(line, width);
prevMoreIndented = moreIndented;
}
return result;
}
function foldLine(line, width) {
if (line === "" || line[0] === " ") return line;
const breakRe = / [^ ]/g;
let match;
let start = 0;
let end;
let curr = 0;
let next2 = 0;
let result = "";
while (match = breakRe.exec(line)) {
next2 = match.index;
if (next2 - start > width) {
end = curr > start ? curr : next2;
result += "\n" + line.slice(start, end);
start = end + 1;
}
curr = next2;
}
result += "\n";
if (line.length - start > width && curr > start) {
result += line.slice(start, curr) + "\n" + line.slice(curr + 1);
} else {
result += line.slice(start);
}
return result.slice(1);
}
function escapeString(string) {
let result = "";
let char = 0;
for (let i = 0; i < string.length; char >= 65536 ? i += 2 : i++) {
char = codePointAt(string, i);
const escapeSeq = ESCAPE_SEQUENCES[char];
if (!escapeSeq && isPrintable(char)) {
result += string[i];
if (char >= 65536) result += string[i + 1];
} else {
result += escapeSeq || encodeHex(char);
}
}
return result;
}
function writeFlowSequence(state2, level, object) {
let _result = "";
const _tag = state2.tag;
for (let index2 = 0, length = object.length; index2 < length; index2 += 1) {
let value = object[index2];
if (state2.replacer) {
value = state2.replacer.call(object, String(index2), value);
}
if (writeNode(state2, level, value, false, false) || typeof value === "undefined" && writeNode(state2, level, null, false, false)) {
if (_result !== "") _result += "," + (!state2.condenseFlow ? " " : "");
_result += state2.dump;
}
}
state2.tag = _tag;
state2.dump = "[" + _result + "]";
}
function writeBlockSequence(state2, level, object, compact) {
let _result = "";
const _tag = state2.tag;
for (let index2 = 0, length = object.length; index2 < length; index2 += 1) {
let value = object[index2];
if (state2.replacer) {
value = state2.replacer.call(object, String(index2), value);
}
if (writeNode(state2, level + 1, value, true, true, false, true) || typeof value === "undefined" && writeNode(state2, level + 1, null, true, true, false, true)) {
if (!compact || _result !== "") {
_result += generateNextLine(state2, level);
}
if (state2.dump && CHAR_LINE_FEED === state2.dump.charCodeAt(0)) {
_result += "-";
} else {
_result += "- ";
}
_result += state2.dump;
}
}
state2.tag = _tag;
state2.dump = _result || "[]";
}
function writeFlowMapping(state2, level, object) {
let _result = "";
const _tag = state2.tag;
const objectKeyList = Object.keys(object);
for (let index2 = 0, length = objectKeyList.length; index2 < length; index2 += 1) {
let pairBuffer = "";
if (_result !== "") pairBuffer += ", ";
if (state2.condenseFlow) pairBuffer += '"';
const objectKey = objectKeyList[index2];
let objectValue = object[objectKey];
if (state2.replacer) {
objectValue = state2.replacer.call(object, objectKey, objectValue);
}
if (!writeNode(state2, level, objectKey, false, false)) {
continue;
}
if (state2.dump.length > 1024) pairBuffer += "? ";
pairBuffer += state2.dump + (state2.condenseFlow ? '"' : "") + ":" + (state2.condenseFlow ? "" : " ");
if (!writeNode(state2, level, objectValue, false, false)) {
continue;
}
pairBuffer += state2.dump;
_result += pairBuffer;
}
state2.tag = _tag;
state2.dump = "{" + _result + "}";
}
function writeBlockMapping(state2, level, object, compact) {
let _result = "";
const _tag = state2.tag;
const objectKeyList = Object.keys(object);
if (state2.sortKeys === true) {
objectKeyList.sort();
} else if (typeof state2.sortKeys === "function") {
objectKeyList.sort(state2.sortKeys);
} else if (state2.sortKeys) {
throw new YAMLException2("sortKeys must be a boolean or a function");
}
for (let index2 = 0, length = objectKeyList.length; index2 < length; index2 += 1) {
let pairBuffer = "";
if (!compact || _result !== "") {
pairBuffer += generateNextLine(state2, level);
}
const objectKey = objectKeyList[index2];
let objectValue = object[objectKey];
if (state2.replacer) {
objectValue = state2.replacer.call(object, objectKey, objectValue);
}
if (!writeNode(state2, level + 1, objectKey, true, true, true)) {
continue;
}
const explicitPair = state2.tag !== null && state2.tag !== "?" || state2.dump && state2.dump.length > 1024;
if (explicitPair) {
if (state2.dump && CHAR_LINE_FEED === state2.dump.charCodeAt(0)) {
pairBuffer += "?";
} else {
pairBuffer += "? ";
}
}
pairBuffer += state2.dump;
if (explicitPair) {
pairBuffer += generateNextLine(state2, level);
}
if (!writeNode(state2, level + 1, objectValue, true, explicitPair)) {
continue;
}
if (state2.dump && CHAR_LINE_FEED === state2.dump.charCodeAt(0)) {
pairBuffer += ":";
} else {
pairBuffer += ": ";
}
pairBuffer += state2.dump;
_result += pairBuffer;
}
state2.tag = _tag;
state2.dump = _result || "{}";
}
function detectType(state2, object, explicit) {
const typeList = explicit ? state2.explicitTypes : state2.implicitTypes;
for (let index2 = 0, length = typeList.length; index2 < length; index2 += 1) {
const type2 = typeList[index2];
if ((type2.instanceOf || type2.predicate) && (!type2.instanceOf || typeof object === "object" && object instanceof type2.instanceOf) && (!type2.predicate || type2.predicate(object))) {
if (explicit) {
if (type2.multi && type2.representName) {
state2.tag = type2.representName(object);
} else {
state2.tag = type2.tag;
}
} else {
state2.tag = "?";
}
if (type2.represent) {
const style = state2.styleMap[type2.tag] || type2.defaultStyle;
let _result;
if (_toString.call(type2.represent) === "[object Function]") {
_result = type2.represent(object, style);
} else if (_hasOwnProperty.call(type2.represent, style)) {
_result = type2.represent[style](object, style);
} else {
throw new YAMLException2("!<" + type2.tag + '> tag resolver accepts not "' + style + '" style');
}
state2.dump = _result;
}
return true;
}
}
return false;
}
function writeNode(state2, level, object, block2, compact, iskey, isblockseq) {
state2.tag = null;
state2.dump = object;
if (!detectType(state2, object, false)) {
detectType(state2, object, true);
}
const type2 = _toString.call(state2.dump);
const inblock = block2;
if (block2) {
block2 = state2.flowLevel < 0 || state2.flowLevel > level;
}
const objectOrArray = type2 === "[object Object]" || type2 === "[object Array]";
let duplicateIndex;
let duplicate;
if (objectOrArray) {
duplicateIndex = state2.duplicates.indexOf(object);
duplicate = duplicateIndex !== -1;
}
if (state2.tag !== null && state2.tag !== "?" || duplicate || state2.indent !== 2 && level > 0) {
compact = false;
}
if (duplicate && state2.usedDuplicates[duplicateIndex]) {
state2.dump = "*ref_" + duplicateIndex;
} else {
if (objectOrArray && duplicate && !state2.usedDuplicates[duplicateIndex]) {
state2.usedDuplicates[duplicateIndex] = true;
}
if (type2 === "[object Object]") {
if (block2 && Object.keys(state2.dump).length !== 0) {
writeBlockMapping(state2, level, state2.dump, compact);
if (duplicate) {
state2.dump = "&ref_" + duplicateIndex + state2.dump;
}
} else {
writeFlowMapping(state2, level, state2.dump);
if (duplicate) {
state2.dump = "&ref_" + duplicateIndex + " " + state2.dump;
}
}
} else if (type2 === "[object Array]") {
if (block2 && state2.dump.length !== 0) {
if (state2.noArrayIndent && !isblockseq && level > 0) {
writeBlockSequence(state2, level - 1, state2.dump, compact);
} else {
writeBlockSequence(state2, level, state2.dump, compact);
}
if (duplicate) {
state2.dump = "&ref_" + duplicateIndex + state2.dump;
}
} else {
writeFlowSequence(state2, level, state2.dump);
if (duplicate) {
state2.dump = "&ref_" + duplicateIndex + " " + state2.dump;
}
}
} else if (type2 === "[object String]") {
if (state2.tag !== "?") {
writeScalar(state2, state2.dump, level, iskey, inblock);
}
} else if (type2 === "[object Undefined]") {
return false;
} else {
if (state2.skipInvalid) return false;
throw new YAMLException2("unacceptable kind of an object to dump " + type2);
}
if (state2.tag !== null && state2.tag !== "?") {
let tagStr = encodeURI(
state2.tag[0] === "!" ? state2.tag.slice(1) : state2.tag
).replace(/!/g, "%21");
if (state2.tag[0] === "!") {
tagStr = "!" + tagStr;
} else if (tagStr.slice(0, 18) === "tag:yaml.org,2002:") {
tagStr = "!!" + tagStr.slice(18);
} else {
tagStr = "!<" + tagStr + ">";
}
state2.dump = tagStr + " " + state2.dump;
}
}
return true;
}
function getDuplicateReferences(object, state2) {
const objects = [];
const duplicatesIndexes = [];
inspectNode(object, objects, duplicatesIndexes);
const length = duplicatesIndexes.length;
for (let index2 = 0; index2 < length; index2 += 1) {
state2.duplicates.push(objects[duplicatesIndexes[index2]]);
}
state2.usedDuplicates = new Array(length);
}
function inspectNode(object, objects, duplicatesIndexes) {
if (object !== null && typeof object === "object") {
const index2 = objects.indexOf(object);
if (index2 !== -1) {
if (duplicatesIndexes.indexOf(index2) === -1) {
duplicatesIndexes.push(index2);
}
} else {
objects.push(object);
if (Array.isArray(object)) {
for (let i = 0, length = object.length; i < length; i += 1) {
inspectNode(object[i], objects, duplicatesIndexes);
}
} else {
const objectKeyList = Object.keys(object);
for (let i = 0, length = objectKeyList.length; i < length; i += 1) {
inspectNode(object[objectKeyList[i]], objects, duplicatesIndexes);
}
}
}
}
}
function dump2(input, options) {
options = options || {};
const state2 = new State(options);
if (!state2.noRefs) getDuplicateReferences(input, state2);
let value = input;
if (state2.replacer) {
value = state2.replacer.call({ "": value }, "", value);
}
if (writeNode(state2, 0, value, true, true)) return state2.dump + "\n";
return "";
}
dumper.dump = dump2;
return dumper;
}
var hasRequiredJsYaml;
function requireJsYaml() {
if (hasRequiredJsYaml) return jsYaml;
hasRequiredJsYaml = 1;
const loader2 = requireLoader();
const dumper2 = requireDumper();
function renamed(from, to) {
return function() {
throw new Error("Function yaml." + from + " is removed in js-yaml 4. Use yaml." + to + " instead, which is now safe by default.");
};
}
jsYaml.Type = requireType();
jsYaml.Schema = requireSchema();
jsYaml.FAILSAFE_SCHEMA = requireFailsafe();
jsYaml.JSON_SCHEMA = requireJson();
jsYaml.CORE_SCHEMA = requireCore();
jsYaml.DEFAULT_SCHEMA = require_default();
jsYaml.load = loader2.load;
jsYaml.loadAll = loader2.loadAll;
jsYaml.dump = dumper2.dump;
jsYaml.YAMLException = requireException();
jsYaml.types = {
binary: requireBinary(),
float: requireFloat(),
map: requireMap(),
null: require_null(),
pairs: requirePairs(),
set: requireSet(),
timestamp: requireTimestamp(),
bool: requireBool(),
int: requireInt(),
merge: requireMerge(),
omap: requireOmap(),
seq: requireSeq(),
str: requireStr()
};
jsYaml.safeLoad = renamed("safeLoad", "load");
jsYaml.safeLoadAll = renamed("safeLoadAll", "loadAll");
jsYaml.safeDump = renamed("safeDump", "dump");
return jsYaml;
}
var jsYamlExports = requireJsYaml();
var yaml = /* @__PURE__ */ getDefaultExportFromCjs(jsYamlExports);
var {
Type,
Schema,
FAILSAFE_SCHEMA,
JSON_SCHEMA,
CORE_SCHEMA,
DEFAULT_SCHEMA,
load,
loadAll,
dump,
YAMLException,
types,
safeLoad,
safeLoadAll,
safeDump
} = yaml;
// src/ui/kanban_frontmatter.ts
var KANBAN_PLUGIN_KEY2 = "kanban_plugin";
var FRONTMATTER_DELIMITER = "---";
function parseKanbanSettingsOverridesFromViewData(data) {
const parsed = parseFrontmatter(data);
return parseSettingsOverrides(toSettingsPayload(parsed.data[KANBAN_PLUGIN_KEY2]));
}
function writeKanbanSettingsToViewData(data, settings) {
const parsed = parseFrontmatter(data);
return stringifyFrontmatter(parsed.content, {
...parsed.data,
[KANBAN_PLUGIN_KEY2]: toSettingsString(settings)
});
}
function parseFrontmatter(data) {
if (!data.startsWith(FRONTMATTER_DELIMITER)) {
return { data: {}, content: data };
}
if (data.charAt(FRONTMATTER_DELIMITER.length) === "-") {
return { data: {}, content: data };
}
const startOfFrontmatter = data.indexOf("\n") + 1;
if (startOfFrontmatter === 0) {
return { data: {}, content: "" };
}
const endDelimiterStart = data.indexOf(`
${FRONTMATTER_DELIMITER}`, startOfFrontmatter);
const frontmatterEnd = endDelimiterStart === -1 ? data.length : endDelimiterStart;
const rawFrontmatter = data.slice(startOfFrontmatter, frontmatterEnd);
const parsed = rawFrontmatter.trim() === "" ? {} : load(rawFrontmatter);
const frontmatter = isRecord(parsed) ? parsed : {};
if (endDelimiterStart === -1) {
return { data: frontmatter, content: "" };
}
let content = data.slice(endDelimiterStart + FRONTMATTER_DELIMITER.length + 1);
if (content.startsWith("\r")) {
content = content.slice(1);
}
if (content.startsWith("\n")) {
content = content.slice(1);
}
return { data: frontmatter, content };
}
function stringifyFrontmatter(content, frontmatter) {
const rawFrontmatter = dump(frontmatter).trim();
const prefix = rawFrontmatter === "{}" ? "" : `${FRONTMATTER_DELIMITER}
${rawFrontmatter}
${FRONTMATTER_DELIMITER}
`;
return `${prefix}${ensureTrailingNewline(content)}`;
}
function ensureTrailingNewline(value) {
return value.endsWith("\n") ? value : `${value}
`;
}
function toSettingsPayload(value) {
if (typeof value === "string") {
return value;
}
if (value == null) {
return "";
}
return JSON.stringify(value);
}
function isRecord(value) {
return typeof value === "object" && value !== null && !Array.isArray(value);
}
// src/ui/settings/column_rename_migration.ts
function getChangedColumnMatchRules(oldSettings, newSettings) {
const oldColumnsById = new Map(oldSettings.columns.map((column) => [column.id, column]));
return newSettings.columns.flatMap((newColumn) => {
const oldColumn = oldColumnsById.get(newColumn.id);
if (!oldColumn) return [];
if (columnRuleSignature(oldColumn) === columnRuleSignature(newColumn)) return [];
return [{ id: newColumn.id, oldColumn, newColumn }];
});
}
async function applyChangedColumnTagUpdates({
vault,
oldSettings,
newSettings,
boardFolderPath,
updateChoices
}) {
const changedColumns = getChangedColumnMatchRules(oldSettings, newSettings).filter(
({ id }) => updateChoices[id] !== false
);
if (changedColumns.length === 0) {
return;
}
const newColumnData = createColumnData(newSettings.columns);
const oldSettingsScope = resolveScopeSettings(oldSettings, boardFolderPath);
const changedColumnsById = new Map(changedColumns.map((column) => [column.id, column]));
const files = vault.getMarkdownFiles().filter(
(file) => shouldIncludeFilePath(
file.path,
oldSettingsScope.filenameFilter,
oldSettingsScope.excludeFilter,
boardFolderPath
)
);
for (const file of files) {
await updateFileForChangedColumns(
vault,
file,
changedColumnsById,
oldSettings.columns,
newSettings.columns,
newColumnData.columnPlacementTagTable,
oldSettings
);
}
}
async function updateFileForChangedColumns(vault, file, changedColumnsById, oldColumnDefinitions, newColumnDefinitions, newPlacementTagTable, settings) {
var _a5, _b3, _c2, _d, _e, _f, _g;
const contents = await vault.read(file);
const rows = contents.split("\n");
const oldPropertySchemaOption = (_a5 = settings.propertySchema) != null ? _a5 : "none" /* None */;
const oldPropertySchema = getSchemaImpl(oldPropertySchemaOption);
let changed = false;
for (let i = 0; i < rows.length; i += 1) {
const row = rows[i];
if (!row || !isTrackedTaskString(row, (_b3 = settings.ignoredStatusMarkers) != null ? _b3 : DEFAULT_IGNORED_STATUS_MARKERS)) {
continue;
}
const status = ((_c2 = row.match(/^\s*[-*+]\s\[([^\[\]]*)\]\s/)) == null ? void 0 : _c2[1]) || " ";
const oldProperties = oldPropertySchema.parseProperties(row);
const matchedColumn = resolveMatchedColumnDefinition(oldColumnDefinitions, {
tags: getTagsFromContent(row),
status,
priority: getPriorityMatchValue(oldPropertySchemaOption, oldProperties),
prioritySchema: getPriorityColumnContextSchema2(oldPropertySchemaOption),
priorities: getPriorityMatchValues(row)
});
const targetColumnId = matchedColumn == null ? void 0 : matchedColumn.id;
const changedColumn = targetColumnId ? changedColumnsById.get(targetColumnId) : void 0;
if (!targetColumnId || targetColumnId === "archived" || !changedColumn) {
continue;
}
const task = new Task(
row,
file,
i,
{
columnDefinitions: oldColumnDefinitions,
columnWriteDefinitions: newColumnDefinitions,
columnPlacementTagTable: newPlacementTagTable,
consolidateTags: (_d = settings.consolidateTags) != null ? _d : false,
doneStatusMarkers: (_e = settings.doneStatusMarkers) != null ? _e : DEFAULT_DONE_STATUS_MARKERS,
cancelledStatusMarkers: (_f = settings.cancelledStatusMarkers) != null ? _f : DEFAULT_CANCELLED_STATUS_MARKERS,
ignoredStatusMarkers: (_g = settings.ignoredStatusMarkers) != null ? _g : DEFAULT_IGNORED_STATUS_MARKERS,
propertySchema: getSchemaImpl(getMigrationSchema(changedColumn, oldPropertySchemaOption))
}
);
if (!task.done) {
task.column = targetColumnId;
}
const nextRow = task.serialise();
if (nextRow !== row) {
rows[i] = nextRow;
changed = true;
}
}
if (changed) {
await vault.modify(file, rows.join("\n"));
}
}
function getMigrationSchema(changedColumn, fallbackSchema) {
var _a5, _b3;
if (usesPriorityMatching(changedColumn.newColumn)) {
return (_a5 = getColumnPrioritySchema(changedColumn.newColumn)) != null ? _a5 : fallbackSchema;
}
if (usesPriorityMatching(changedColumn.oldColumn)) {
return (_b3 = getColumnPrioritySchema(changedColumn.oldColumn)) != null ? _b3 : fallbackSchema;
}
return fallbackSchema;
}
function getPriorityColumnContextSchema2(propertySchemaOption) {
return propertySchemaOption === "tasks" /* TasksPlugin */ || propertySchemaOption === "dataview" /* Dataview */ ? propertySchemaOption : void 0;
}
function getPriorityMatchValue(propertySchemaOption, properties) {
const priority = properties.get("priority");
if (propertySchemaOption === "tasks" /* TasksPlugin */ && typeof (priority == null ? void 0 : priority.value) === "number") {
return getTasksPriorityValueFromWeight(priority.value);
}
if (propertySchemaOption === "dataview" /* Dataview */ && typeof (priority == null ? void 0 : priority.value) === "string") {
return priority.value.trim();
}
return void 0;
}
function getPriorityMatchValues(rawLine) {
return {
["tasks" /* TasksPlugin */]: getPriorityMatchValue(
"tasks" /* TasksPlugin */,
getSchemaImpl("tasks" /* TasksPlugin */).parseProperties(rawLine)
),
["dataview" /* Dataview */]: getPriorityMatchValue(
"dataview" /* Dataview */,
getSchemaImpl("dataview" /* Dataview */).parseProperties(rawLine)
)
};
}
function resolveScopeSettings(settings, boardFolderPath) {
var _a5, _b3;
let filenameFilter = null;
switch (settings.scope) {
case "everywhere":
filenameFilter = null;
break;
case "folder":
filenameFilter = boardFolderPath ? [boardFolderPath] : null;
break;
case "selectedFolders": {
const selected = (_a5 = settings.scopeFolders) != null ? _a5 : [];
filenameFilter = boardFolderPath ? [boardFolderPath, ...selected.filter((folder) => folder !== boardFolderPath)] : selected;
break;
}
}
const excludePaths = (_b3 = settings.excludePaths) != null ? _b3 : [];
return {
filenameFilter,
excludeFilter: excludePaths.length > 0 ? excludePaths : null
};
}
// src/ui/text_view.ts
var KANBAN_VIEW_NAME = "kanban-view";
var KanbanView = class extends import_obsidian17.TextFileView {
constructor(leaf, inheritedSettingsStore, globalViewsStore, boardIndexStore, boardListSettingsStore, onSetBoardHidden, onReorderBoards, boardCountsStore, onRequestBoardCounts, lastOpenedStore, onBoardOpened, boardRailSettingsStore, onSetRailWidth, onCreateBoardFromDashboard, onDeleteBoardFromDashboard) {
super(leaf);
this.globalViewsStore = globalViewsStore;
this.boardIndexStore = boardIndexStore;
this.boardListSettingsStore = boardListSettingsStore;
this.onSetBoardHidden = onSetBoardHidden;
this.onReorderBoards = onReorderBoards;
this.boardCountsStore = boardCountsStore;
this.onRequestBoardCounts = onRequestBoardCounts;
this.lastOpenedStore = lastOpenedStore;
this.onBoardOpened = onBoardOpened;
this.boardRailSettingsStore = boardRailSettingsStore;
this.onSetRailWidth = onSetRailWidth;
this.onCreateBoardFromDashboard = onCreateBoardFromDashboard;
this.onDeleteBoardFromDashboard = onDeleteBoardFromDashboard;
this.filenameFilter = null;
this.excludeFilter = null;
this.boardFolderPath = null;
this.currentPathStore = writable(null);
// Transient by design (SPEC 0033): the dashboard never reopens itself
// after a reload or board switch.
this.dashboardOpenStore = writable(false);
this.pendingSelfTaskFileWrites = [];
this.icon = "kanban-square";
this.settingsStore = createSettingsStore(inheritedSettingsStore);
this.destroySettingsStore = this.settingsStore.subscribe((settings) => {
var _a5, _b3, _c2, _d;
this.boardFolderPath = (_c2 = (_b3 = (_a5 = this.file) == null ? void 0 : _a5.parent) == null ? void 0 : _b3.path) != null ? _c2 : null;
this.filenameFilter = resolveScopeFilter(
settings.scope,
settings.scopeFolders,
this.boardFolderPath
);
const excludePaths = (_d = settings.excludePaths) != null ? _d : [];
this.excludeFilter = excludePaths.length > 0 ? excludePaths : null;
});
const {
columnDefinitions,
columnTagTable,
columnColourTable,
columnPlacementTagTable,
columnMatchTagTable,
columnSubtitleTable
} = createColumnStores(
this.settingsStore
);
this.columnDefinitionsStore = columnDefinitions;
this.columnTagTableStore = columnTagTable;
this.columnColourTableStore = columnColourTable;
this.columnPlacementTagTableStore = columnPlacementTagTable;
this.columnMatchTagTableStore = columnMatchTagTable;
this.columnSubtitleTableStore = columnSubtitleTable;
const { tasksStore, taskActions, initialise } = createTasksStore(
this.app.vault,
this.app.workspace,
this.registerEvent.bind(this),
this.columnDefinitionsStore,
this.columnPlacementTagTableStore,
() => this.filenameFilter,
() => this.excludeFilter,
() => this.boardFolderPath,
this.settingsStore,
() => this.requestSave(),
(fileHandle, nextContent) => this.prepareTaskWriteContent(fileHandle, nextContent)
);
this.tasksStore = tasksStore;
this.taskActions = taskActions;
this.initialiseTasksStore = initialise;
}
async onLocalSettingsChange(newSettings, options) {
var _a5, _b3, _c2;
const previousSettings = structuredClone(get2(this.settingsStore));
try {
await applyChangedColumnTagUpdates({
vault: this.app.vault,
oldSettings: previousSettings,
newSettings,
boardFolderPath: (_c2 = (_b3 = (_a5 = this.file) == null ? void 0 : _a5.parent) == null ? void 0 : _b3.path) != null ? _c2 : null,
updateChoices: options.updateExistingTaskTagsByColumnId
});
} catch (error) {
console.error("Failed to update changed column task tags", error);
new import_obsidian17.Notice("Failed to update existing task tags for changed columns.");
return;
}
this.settingsStore.set(newSettings);
if (options.pinnedSettingKeys.length > 0) {
this.settingsStore.pinOverrides(options.pinnedSettingKeys);
}
if (options.clearedSettingKeys.length > 0) {
this.settingsStore.clearOverrides(options.clearedSettingKeys);
}
this.initialiseTasksStore();
this.requestSave();
}
openSettingsModal() {
var _a5, _b3, _c2;
const settingsModal = new SettingsModal(
this.app,
structuredClone(get2(this.settingsStore)),
(newSettings, options) => this.onLocalSettingsChange(newSettings, options),
(_c2 = (_b3 = (_a5 = this.file) == null ? void 0 : _a5.parent) == null ? void 0 : _b3.path) != null ? _c2 : null,
{
overrideContext: {
overriddenKeys: Object.keys(
this.settingsStore.getOverrides()
),
baseSettings: this.settingsStore.getBaseSettings()
}
}
);
settingsModal.open();
return new Promise((resolve) => {
settingsModal.onClose = () => {
resolve();
settingsModal.onClose = () => void 0;
};
});
}
// In-leaf board switching (SPEC 0032). Setting the view state straight
// to the kanban type skips the markdown-view detour `openFile` would
// take; the unload of the current file flushes any pending save first.
async openBoard(path) {
var _a5;
if (path === ((_a5 = this.file) == null ? void 0 : _a5.path)) {
return;
}
await this.leaf.setViewState({
type: KANBAN_VIEW_NAME,
state: { file: path },
active: true
});
}
// The "Show board dashboard" command's entry point; the button in the
// board chrome flips the same store.
toggleDashboard() {
this.dashboardOpenStore.update((open) => !open);
}
openCurrentBoardSettings() {
var _a5;
void ((_a5 = this.component) == null ? void 0 : _a5.openCurrentBoardSettings());
}
hasVisibleSelectedCards() {
var _a5, _b3;
return (_b3 = (_a5 = this.component) == null ? void 0 : _a5.hasVisibleSelectedCards()) != null ? _b3 : false;
}
markSelectedCardsDone() {
var _a5;
void ((_a5 = this.component) == null ? void 0 : _a5.markSelectedCardsDone());
}
archiveSelectedCards() {
var _a5;
void ((_a5 = this.component) == null ? void 0 : _a5.archiveSelectedCards());
}
cancelSelectedCards() {
var _a5;
void ((_a5 = this.component) == null ? void 0 : _a5.cancelSelectedCards());
}
duplicateSelectedCards() {
var _a5;
void ((_a5 = this.component) == null ? void 0 : _a5.duplicateSelectedCards());
}
deleteSelectedCards() {
var _a5;
void ((_a5 = this.component) == null ? void 0 : _a5.deleteSelectedCardsCommand());
}
getViewType() {
return KANBAN_VIEW_NAME;
}
getViewData() {
return writeKanbanSettingsToViewData(this.data, this.settingsStore.getOverrides());
}
getResolvedSettingsSnapshot() {
return structuredClone(get2(this.settingsStore));
}
getSettingsOverridesSnapshot() {
return structuredClone(this.settingsStore.getOverrides());
}
// The escape hatch for legacy fully-materialized boards (SPEC 0030
// Part A): sheds every override that matches what the board would
// inherit anyway, so those fields start following the defaults again.
pruneSettingsMatchingDefaults() {
const prunedKeys = this.settingsStore.pruneOverridesMatchingDefaults();
if (prunedKeys.length === 0) {
new import_obsidian17.Notice("No board settings match the defaults.");
return;
}
this.requestSave();
new import_obsidian17.Notice(
`Pruned ${prunedKeys.length} board setting${prunedKeys.length === 1 ? "" : "s"} matching the defaults.`
);
}
// Fires once per file this view loads (initial open and in-leaf board
// switches alike) — unlike setViewData, never on external edits — so it
// is the "board opened" moment for the dashboard's last-opened stamps
// (SPEC 0033 Phase 3c).
async onLoadFile(file) {
var _a5;
await super.onLoadFile(file);
(_a5 = this.onBoardOpened) == null ? void 0 : _a5.call(this, file.path);
}
// Renaming the open board keeps this view; only the path store needs to
// follow so the active tab highlight does too.
async onRename(file) {
await super.onRename(file);
this.currentPathStore.set(file.path);
}
setViewData(data, clear) {
var _a5, _b3;
this.data = data;
this.currentPathStore.set((_b3 = (_a5 = this.file) == null ? void 0 : _a5.path) != null ? _b3 : null);
const selfWriteIndex = this.pendingSelfTaskFileWrites.indexOf(data);
if (selfWriteIndex !== -1) {
this.pendingSelfTaskFileWrites.splice(selfWriteIndex, 1);
return;
}
this.settingsStore.load(parseKanbanSettingsOverridesFromViewData(data));
this.initialiseTasksStore();
}
prepareTaskWriteContent(fileHandle, nextContent) {
var _a5;
if (fileHandle.path !== ((_a5 = this.file) == null ? void 0 : _a5.path)) {
return nextContent;
}
const preparedContent = writeKanbanSettingsToViewData(nextContent, this.settingsStore.getOverrides());
this.pendingSelfTaskFileWrites.push(preparedContent);
return preparedContent;
}
clear() {
}
async onOpen() {
this.contentEl.addClass("task-list-kanban-view");
this.component = new Main({
target: this.contentEl,
props: {
app: this.app,
tasksStore: this.tasksStore,
taskActions: this.taskActions,
columnTagTableStore: this.columnTagTableStore,
columnColourTableStore: this.columnColourTableStore,
columnMatchTagTableStore: this.columnMatchTagTableStore,
columnSubtitleTableStore: this.columnSubtitleTableStore,
openSettings: () => this.openSettingsModal(),
settingsStore: this.settingsStore,
globalViewsStore: this.globalViewsStore,
boardIndexStore: this.boardIndexStore,
boardListSettingsStore: this.boardListSettingsStore,
currentPathStore: this.currentPathStore,
dashboardOpenStore: this.dashboardOpenStore,
openBoard: (path) => void this.openBoard(path),
onSetBoardHidden: this.onSetBoardHidden,
onReorderBoards: this.onReorderBoards,
boardCountsStore: this.boardCountsStore,
onRequestBoardCounts: this.onRequestBoardCounts,
lastOpenedStore: this.lastOpenedStore,
boardRailSettingsStore: this.boardRailSettingsStore,
onSetRailWidth: this.onSetRailWidth,
onCreateBoard: () => {
var _a5, _b3;
return (_b3 = (_a5 = this.onCreateBoardFromDashboard) == null ? void 0 : _a5.call(this, this)) != null ? _b3 : false;
},
onDeleteBoard: (path) => {
var _a5, _b3;
return (_b3 = (_a5 = this.onDeleteBoardFromDashboard) == null ? void 0 : _a5.call(this, path)) != null ? _b3 : false;
},
requestSave: () => this.requestSave()
}
});
}
async onClose() {
var _a5;
this.contentEl.removeClass("task-list-kanban-view");
(_a5 = this.component) == null ? void 0 : _a5.$destroy();
this.destroySettingsStore();
this.settingsStore.destroy();
}
};
// src/ui/settings/global_settings.ts
var GLOBAL_SETTINGS_VERSION = 1;
var BOARD_DEFAULT_SETTING_KEYS = [
"columns",
"uncategorizedColumnName",
"doneColumnName",
"uncategorizedVisibility",
"doneVisibility",
"doneStatusMarkers",
"cancelledStatusMarkers",
"ignoredStatusMarkers",
"statusMarkerOrder",
"propertySchema",
"treatNestedTasksAsSubtasks",
"scope",
"excludePaths",
"excludedTags",
"excludedTaskTags",
"showFilepath",
"consolidateTags",
"propertyDisplay"
];
var defaultGlobalSettings = {
version: GLOBAL_SETTINGS_VERSION,
boardDefaults: {}
};
function createGlobalSettingsStore(initial = defaultGlobalSettings) {
let current = cloneGlobalSettings(initial);
const inner = writable(current);
return {
subscribe: inner.subscribe,
set: (next2) => {
current = cloneGlobalSettings(next2);
inner.set(current);
},
update: (updater) => {
const next2 = updater(cloneGlobalSettings(current));
current = cloneGlobalSettings(next2);
inner.set(current);
},
get: () => cloneGlobalSettings(current)
};
}
function createInheritedSettingsStore(globalSettingsStore) {
return derived(globalSettingsStore, inheritedSettingsFromGlobalSettings);
}
function parseGlobalSettings(data) {
var _a5;
if (!isRecord2(data)) {
return cloneGlobalSettings(defaultGlobalSettings);
}
const rawBoardDefaults = isRecord2(data.boardDefaults) ? data.boardDefaults : {};
const rawDefaultView = isRecord2(data.defaultView) ? data.defaultView : void 0;
const rawGlobalViews = Array.isArray(data.globalViews) ? data.globalViews : void 0;
const rawBoardList = isRecord2(data.boardList) ? data.boardList : void 0;
const rawLastOpened = isRecord2(data.lastOpenedByPath) ? data.lastOpenedByPath : void 0;
const rawBoardRail = isRecord2(data.boardRail) ? data.boardRail : void 0;
const parsedBoardDefaults = pickBoardDefaultSettings(
parseSettingsOverrides(JSON.stringify(rawBoardDefaults))
);
const parsedDefaultView = pickGlobalDefaultViewProperties(
parseSavedViewProperties(rawDefaultView)
);
if (parsedDefaultView.flowDirection === "ltr" /* LeftToRight */) {
delete parsedDefaultView.flowDirection;
}
if (parsedDefaultView.columnWidth === defaultSettings.columnWidth) {
delete parsedDefaultView.columnWidth;
}
const parsedGlobalViews = rawGlobalViews ? ((_a5 = parseSettingsOverrides(JSON.stringify({ savedViews: rawGlobalViews })).savedViews) != null ? _a5 : []).filter(savedViewHasProperties) : void 0;
const settings = {
version: GLOBAL_SETTINGS_VERSION,
boardDefaults: parsedBoardDefaults
};
if (savedViewHasProperties(parsedDefaultView)) {
settings.defaultView = parsedDefaultView;
}
if (parsedGlobalViews && parsedGlobalViews.length > 0) {
settings.globalViews = parsedGlobalViews;
}
const parsedBoardList = parseBoardListSettings(rawBoardList);
if (parsedBoardList) {
settings.boardList = parsedBoardList;
}
const parsedLastOpened = parseLastOpenedByPath(rawLastOpened);
if (parsedLastOpened) {
settings.lastOpenedByPath = parsedLastOpened;
}
const parsedBoardRail = parseBoardRailSettings(rawBoardRail);
if (parsedBoardRail) {
settings.boardRail = parsedBoardRail;
}
return settings;
}
function parseBoardRailSettings(raw) {
if (!raw) {
return void 0;
}
const parsed = {};
if (typeof raw.width === "number" && Number.isFinite(raw.width)) {
const width = clampRailWidth(raw.width);
if (width !== RAIL_MIN_WIDTH) {
parsed.width = width;
}
}
if (raw.dock === "top") {
parsed.dock = "top";
}
return Object.keys(parsed).length > 0 ? parsed : void 0;
}
function parseLastOpenedByPath(raw) {
if (!raw) {
return void 0;
}
const parsed = {};
for (const [path, value] of Object.entries(raw)) {
const trimmed = path.trim();
if (trimmed === "" || typeof value !== "number" || !Number.isFinite(value) || value <= 0) {
continue;
}
parsed[trimmed] = value;
}
return Object.keys(parsed).length > 0 ? parsed : void 0;
}
function parseBoardListSettings(raw) {
if (!raw) {
return void 0;
}
const boardPaths = normalizeBoardPaths(
Array.isArray(raw.boardPaths) ? raw.boardPaths : []
);
const unpinnedPaths = normalizeBoardPaths(
Array.isArray(raw.unpinnedPaths) ? raw.unpinnedPaths : []
);
if (boardPaths.length === 0 && unpinnedPaths.length === 0) {
return void 0;
}
return {
...boardPaths.length > 0 ? { boardPaths } : {},
...unpinnedPaths.length > 0 ? { unpinnedPaths } : {}
};
}
function normalizeBoardPaths(paths) {
const seen = /* @__PURE__ */ new Set();
const normalized = [];
for (const path of paths) {
if (typeof path !== "string") {
continue;
}
const trimmed = path.trim();
if (trimmed === "" || seen.has(trimmed)) {
continue;
}
seen.add(trimmed);
normalized.push(trimmed);
}
return normalized;
}
function serializeGlobalSettings(settings) {
return cloneGlobalSettings(parseGlobalSettings(settings));
}
function removeBoardPathFromGlobalSettings(settings, path) {
var _a5, _b3, _c2, _d, _e;
const boardPaths = ((_b3 = (_a5 = settings.boardList) == null ? void 0 : _a5.boardPaths) != null ? _b3 : []).filter(
(candidate) => candidate !== path
);
const unpinnedPaths = ((_d = (_c2 = settings.boardList) == null ? void 0 : _c2.unpinnedPaths) != null ? _d : []).filter(
(candidate) => candidate !== path
);
const lastOpenedByPath = { ...(_e = settings.lastOpenedByPath) != null ? _e : {} };
delete lastOpenedByPath[path];
return cloneGlobalSettings({
...settings,
...boardPaths.length > 0 || unpinnedPaths.length > 0 ? {
boardList: {
...boardPaths.length > 0 ? { boardPaths } : {},
...unpinnedPaths.length > 0 ? { unpinnedPaths } : {}
}
} : { boardList: void 0 },
...Object.keys(lastOpenedByPath).length > 0 ? { lastOpenedByPath } : { lastOpenedByPath: void 0 }
});
}
function inheritedSettingsFromGlobalSettings(settings) {
var _a5;
return {
...pickBoardDefaultSettings(settings.boardDefaults),
...pickGlobalDefaultViewProperties((_a5 = settings.defaultView) != null ? _a5 : {})
};
}
function pickGlobalDefaultViewProperties(view) {
const picked = {};
if (view.flowDirection !== void 0) {
picked.flowDirection = view.flowDirection;
}
if (view.columnWidth !== void 0) {
picked.columnWidth = view.columnWidth;
}
return picked;
}
function pickBoardDefaultSettings(settings) {
const picked = {};
const copy = (key2) => {
const value = settings[key2];
if (value !== void 0) {
picked[key2] = cloneJson(value);
}
};
for (const key2 of BOARD_DEFAULT_SETTING_KEYS) {
copy(key2);
}
return picked;
}
function cloneGlobalSettings(settings) {
var _a5, _b3, _c2, _d, _e;
return {
version: GLOBAL_SETTINGS_VERSION,
boardDefaults: pickBoardDefaultSettings((_a5 = settings.boardDefaults) != null ? _a5 : {}),
...settings.defaultView && savedViewHasProperties(settings.defaultView) ? { defaultView: cloneJson(settings.defaultView) } : {},
...settings.globalViews && settings.globalViews.length > 0 ? { globalViews: cloneJson(settings.globalViews) } : {},
...settings.boardList && (((_c2 = (_b3 = settings.boardList.boardPaths) == null ? void 0 : _b3.length) != null ? _c2 : 0) > 0 || ((_e = (_d = settings.boardList.unpinnedPaths) == null ? void 0 : _d.length) != null ? _e : 0) > 0) ? { boardList: cloneJson(settings.boardList) } : {},
...settings.lastOpenedByPath && Object.keys(settings.lastOpenedByPath).length > 0 ? { lastOpenedByPath: cloneJson(settings.lastOpenedByPath) } : {},
...settings.boardRail && (settings.boardRail.width !== void 0 || settings.boardRail.dock !== void 0) ? { boardRail: cloneJson(settings.boardRail) } : {}
};
}
function cloneJson(value) {
return JSON.parse(JSON.stringify(value));
}
function isRecord2(value) {
return typeof value === "object" && value !== null && !Array.isArray(value);
}
// src/ui/settings/global_settings_tab.ts
var import_obsidian18 = require("obsidian");
var GlobalSettingsTab = class extends import_obsidian18.PluginSettingTab {
constructor(app, plugin, globalSettingsStore, onChange) {
super(app, plugin);
this.globalSettingsStore = globalSettingsStore;
this.onChange = onChange;
this.destroyBoardDefaultsEditor = null;
}
display() {
var _a5;
(_a5 = this.destroyBoardDefaultsEditor) == null ? void 0 : _a5.call(this);
this.destroyBoardDefaultsEditor = null;
const { containerEl } = this;
containerEl.empty();
containerEl.addClass("task-list-kanban-global-settings");
containerEl.createEl("h2", { text: "Task List Kanban" });
new import_obsidian18.Setting(containerEl).setName("Board rail position").setDesc(
"Where the board rail docks in vaults with more than one board. The rail lists every shown board for one-click switching."
).addDropdown((dropdown) => {
var _a6, _b3;
dropdown.addOption("left", "Left side").addOption("top", "Top").setValue((_b3 = (_a6 = this.globalSettingsStore.get().boardRail) == null ? void 0 : _a6.dock) != null ? _b3 : "left").onChange((value) => {
void this.mutate((settings) => ({
...settings,
boardRail: {
...settings.boardRail,
// "left" is the default; only "top" is stored.
dock: value === "top" ? "top" : void 0
}
}));
});
});
new import_obsidian18.Setting(containerEl).setName("Board defaults").setHeading();
containerEl.createEl("p", {
text: "Defaults here apply to boards that have not saved a local override for the same setting.",
cls: "setting-item-description"
});
new import_obsidian18.Setting(containerEl).setName("Reset board defaults").setDesc("Clear plugin-level board defaults and fall back to the built-in defaults.").addButton((button) => {
button.setButtonText("Reset all").onClick(() => {
new ConfirmModal(this.app, {
title: "Reset global board defaults?",
body: "Boards that inherit these plugin-level defaults will fall back to the built-in defaults. Board-local overrides will not be changed.",
confirmText: "Reset defaults",
onConfirm: async () => {
await this.mutate((settings) => ({
...settings,
boardDefaults: {}
}));
this.display();
}
}).open();
});
});
this.renderBoardDefaultsEditor(containerEl);
this.renderDefaultView(containerEl);
this.renderGlobalSavedViews(containerEl);
}
hide() {
var _a5;
(_a5 = this.destroyBoardDefaultsEditor) == null ? void 0 : _a5.call(this);
this.destroyBoardDefaultsEditor = null;
this.containerEl.empty();
}
renderBoardDefaultsEditor(containerEl) {
const editorHost = containerEl.createDiv({ cls: "global-board-defaults-editor" });
const originalGlobalSettings = this.globalSettingsStore.get();
let currentDefaults = originalGlobalSettings.boardDefaults;
let currentResolvedSettings = resolveSettings(currentDefaults);
const editor = new SettingsModal(
this.app,
structuredClone(currentResolvedSettings),
async (newSettings) => {
const nextDefaults = mergeChangedBoardDefaults(
currentDefaults,
currentResolvedSettings,
newSettings
);
currentDefaults = nextDefaults;
currentResolvedSettings = resolveSettings(nextDefaults);
await this.mutate((settings) => ({
...settings,
boardDefaults: nextDefaults
}));
},
null,
{
title: "Default board settings",
mode: "globalDefaults",
layout: "embedded"
}
);
this.destroyBoardDefaultsEditor = editor.mountInline(editorHost);
}
renderDefaultView(containerEl) {
var _a5, _b3, _c2;
new import_obsidian18.Setting(containerEl).setName("Default view").setHeading();
containerEl.createEl("p", {
text: "Layout defaults apply only where a board has not saved its own layout setting.",
cls: "setting-item-description"
});
const defaultView = (_a5 = this.globalSettingsStore.get().defaultView) != null ? _a5 : {};
new import_obsidian18.Setting(containerEl).setName("Default flow").addDropdown((dropdown) => {
var _a6;
dropdown.addOption("ltr" /* LeftToRight */, "Left to right").addOption("rtl" /* RightToLeft */, "Right to left").addOption("ttb" /* TopToBottom */, "Top to bottom").addOption("btt" /* BottomToTop */, "Bottom to top").setValue((_a6 = defaultView.flowDirection) != null ? _a6 : "ltr" /* LeftToRight */).onChange((value) => {
void this.updateDefaultView((view) => {
if (isFlowDirection(value) && value !== "ltr" /* LeftToRight */) {
view.flowDirection = value;
} else {
delete view.flowDirection;
}
});
});
});
const builtinColumnWidth = (_b3 = defaultSettings.columnWidth) != null ? _b3 : 300;
const columnWidth = (_c2 = defaultView.columnWidth) != null ? _c2 : builtinColumnWidth;
let columnWidthLabel = null;
new import_obsidian18.Setting(containerEl).setName("Default card width").setDesc("Card width for boards that have not saved their own width.").addSlider((slider) => {
slider.setLimits(200, 600, 10).setValue(columnWidth).setDynamicTooltip().onChange((value) => {
columnWidthLabel == null ? void 0 : columnWidthLabel.setText(`${value}px`);
void this.updateDefaultView((view) => {
if (value === builtinColumnWidth) {
delete view.columnWidth;
} else {
view.columnWidth = value;
}
});
});
}).then((setting) => {
columnWidthLabel = setting.controlEl.createSpan({
text: `${columnWidth}px`,
cls: "setting-item-description"
});
});
}
async updateDefaultView(updater) {
await this.mutate((settings) => {
var _a5;
const view = { ...(_a5 = settings.defaultView) != null ? _a5 : {} };
updater(view);
return {
...settings,
defaultView: Object.keys(view).length > 0 ? view : void 0
};
});
}
renderGlobalSavedViews(containerEl) {
var _a5, _b3;
new import_obsidian18.Setting(containerEl).setName("Global saved views").setHeading();
containerEl.createEl("p", {
text: "Global saved views are available from every board. Edit or delete them here.",
cls: "setting-item-description"
});
let draftName = "";
let draftQuery = "";
let draftSortMode = "";
let draftSortDirection = "asc";
let draftGroupKind = "";
let draftGroupDirection = "asc";
let draftTagPrefix = "";
let draftFlowDirection = "";
let draftColumnWidthEnabled = false;
let draftColumnWidth = (_a5 = defaultSettings.columnWidth) != null ? _a5 : 300;
new import_obsidian18.Setting(containerEl).setName("Name").addText((text2) => {
text2.setPlaceholder("Overdue only").onChange((value) => {
draftName = value;
});
});
new import_obsidian18.Setting(containerEl).setName("Filter query").setDesc("Optional search query to apply with this view.").addText((text2) => {
text2.setPlaceholder("due:<$TODAY").onChange((value) => {
draftQuery = value;
});
});
new import_obsidian18.Setting(containerEl).setName("Sort").addDropdown((dropdown) => {
dropdown.addOption("", "Leave unchanged").addOption("file" /* FileOrder */, "File order").addOption("task-name" /* TaskName */, "Task name").addOption("manual" /* Manual */, "Manual").onChange((value) => {
draftSortMode = value;
});
}).addDropdown((dropdown) => {
dropdown.addOption("asc", "Ascending").addOption("desc", "Descending").onChange((value) => {
draftSortDirection = value;
});
});
new import_obsidian18.Setting(containerEl).setName("Group").addDropdown((dropdown) => {
dropdown.addOption("", "Leave unchanged").addOption("none", "None").addOption("file", "File").addOption("tag-prefix", "Tag prefix").onChange((value) => {
draftGroupKind = value;
});
}).addText((text2) => {
text2.setPlaceholder("Tag prefix").onChange((value) => {
draftTagPrefix = value;
});
}).addDropdown((dropdown) => {
dropdown.addOption("asc", "Ascending").addOption("desc", "Descending").onChange((value) => {
draftGroupDirection = value;
});
});
new import_obsidian18.Setting(containerEl).setName("Flow").addDropdown((dropdown) => {
dropdown.addOption("", "Leave unchanged").addOption("ltr" /* LeftToRight */, "Left to right").addOption("rtl" /* RightToLeft */, "Right to left").addOption("ttb" /* TopToBottom */, "Top to bottom").addOption("btt" /* BottomToTop */, "Bottom to top").onChange((value) => {
draftFlowDirection = value;
});
});
let columnWidthLabel = null;
new import_obsidian18.Setting(containerEl).setName("Card width").addToggle((toggle) => {
toggle.onChange((value) => {
draftColumnWidthEnabled = value;
});
}).addSlider((slider) => {
slider.setLimits(200, 600, 10).setValue(draftColumnWidth).setDynamicTooltip().onChange((value) => {
draftColumnWidth = value;
columnWidthLabel == null ? void 0 : columnWidthLabel.setText(`${value}px`);
});
}).then((setting) => {
columnWidthLabel = setting.controlEl.createSpan({
text: `${draftColumnWidth}px`,
cls: "setting-item-description"
});
});
new import_obsidian18.Setting(containerEl).setName("Save global view").addButton((button) => {
button.setButtonText("Save").setCta().onClick(async () => {
const properties = buildSavedViewProperties({
query: draftQuery,
sortMode: draftSortMode,
sortDirection: draftSortDirection,
groupKind: draftGroupKind,
groupDirection: draftGroupDirection,
tagPrefix: draftTagPrefix,
flowDirection: draftFlowDirection,
columnWidth: draftColumnWidthEnabled ? draftColumnWidth : void 0
});
if (!savedViewHasProperties(properties)) {
new import_obsidian18.Notice("Choose at least one saved-view property.");
return;
}
const name = draftName.trim() || defaultSavedViewName(properties);
await this.mutate((settings) => {
var _a6;
return {
...settings,
globalViews: [
...(_a6 = settings.globalViews) != null ? _a6 : [],
{
id: crypto.randomUUID(),
name,
...properties
}
]
};
});
this.display();
});
});
const globalViews = (_b3 = this.globalSettingsStore.get().globalViews) != null ? _b3 : [];
if (globalViews.length === 0) {
containerEl.createEl("p", {
text: "No global saved views yet.",
cls: "setting-item-description"
});
return;
}
for (const view of globalViews) {
new import_obsidian18.Setting(containerEl).setName(view.name).setDesc(savedViewPropertyLabels(view).join(" \xB7 ") || "No properties").addButton((button) => {
button.setButtonText("Delete").setWarning().onClick(() => {
new ConfirmModal(this.app, {
title: "Delete global saved view?",
body: `Delete "${view.name}" for every board. Board-local saved views will not be changed.`,
confirmText: "Delete",
onConfirm: async () => {
await this.mutate((settings) => {
var _a6;
return {
...settings,
globalViews: ((_a6 = settings.globalViews) != null ? _a6 : []).filter(
(candidate) => candidate.id !== view.id
)
};
});
this.display();
}
}).open();
});
});
}
}
async mutate(updater) {
this.globalSettingsStore.update(updater);
await this.onChange();
}
};
function buildSavedViewProperties(input) {
const properties = {};
const query = input.query.trim();
if (query !== "") {
properties.query = query;
}
if (input.sortMode !== "") {
properties.sort = {
mode: input.sortMode,
property: null,
direction: input.sortDirection
};
}
const groupSource = groupSourceFromDraft(input.groupKind, input.tagPrefix);
if (groupSource) {
properties.group = {
source: groupSource,
direction: input.groupDirection
};
}
if (isFlowDirection(input.flowDirection)) {
properties.flowDirection = input.flowDirection;
}
if (input.columnWidth !== void 0) {
properties.columnWidth = input.columnWidth;
}
return properties;
}
function groupSourceFromDraft(kind, tagPrefix) {
if (kind === "none") {
return { kind: "none" };
}
if (kind === "file") {
return { kind: "file" };
}
if (kind === "tag-prefix") {
return { kind: "tag-prefix", prefix: tagPrefix.trim() };
}
return void 0;
}
function mergeChangedBoardDefaults(originalDefaults, originalResolvedSettings, newSettings) {
const nextDefaults = {};
const originalDefaultsRecord = originalDefaults;
const originalResolvedRecord = originalResolvedSettings;
const newRecord = pickBoardDefaultSettings(newSettings);
const nextRecord = nextDefaults;
for (const key2 of BOARD_DEFAULT_SETTING_KEYS) {
const wasExplicit = Object.prototype.hasOwnProperty.call(originalDefaultsRecord, key2);
const changed = JSON.stringify(newRecord[key2]) !== JSON.stringify(originalResolvedRecord[key2]);
if (wasExplicit || changed) {
nextRecord[key2] = JSON.parse(JSON.stringify(newRecord[key2]));
}
}
return nextDefaults;
}
// src/ui/dashboard/board_stats.ts
var COUNT_SETTING_KEYS = [
"columns",
"scope",
"scopeFolders",
"excludePaths",
"consolidateTags",
"doneStatusMarkers",
"cancelledStatusMarkers",
"ignoredStatusMarkers",
"excludedTaskTags",
"propertySchema",
"treatNestedTasksAsSubtasks",
"uncategorizedColumnName",
"doneColumnName"
];
function createBoardStatsService(host, options = {}) {
var _a5;
const countsStore = writable(/* @__PURE__ */ new Map());
const cacheByPath = /* @__PURE__ */ new Map();
const queue = [];
const queued = /* @__PURE__ */ new Set();
let pumping = false;
let destroyed = false;
const now2 = (_a5 = options.now) != null ? _a5 : (() => /* @__PURE__ */ new Date());
function publish(path, counts) {
countsStore.update((current) => {
const existing = current.get(path);
if (counts === void 0) {
if (existing === void 0) {
return current;
}
const next2 = new Map(current);
next2.delete(path);
return next2;
}
if (existing && countsEqual(existing, counts)) {
return current;
}
return new Map(current).set(path, counts);
});
}
async function computeBoard(path) {
var _a6, _b3, _c2;
const files = host.getMarkdownFiles();
const boardFile = files.find((file) => file.path === path);
if (!boardFile) {
cacheByPath.delete(path);
publish(path, void 0);
return;
}
const settings = resolveSettings(
parseSettingsOverrides(host.getBoardSettingsPayload(boardFile)),
inheritedSettingsFromGlobalSettings(host.getGlobalSettings())
);
const boardFolder = (_b3 = (_a6 = boardFile.parent) == null ? void 0 : _a6.path) != null ? _b3 : null;
const scopeFilter = resolveScopeFilter(
settings.scope,
settings.scopeFolders,
boardFolder
);
const excludePaths = (_c2 = settings.excludePaths) != null ? _c2 : [];
const excludeFilter = excludePaths.length > 0 ? excludePaths : null;
const inScope = files.filter(
(file) => shouldIncludeFilePath(file.path, scopeFilter, excludeFilter, boardFolder)
);
const producesAttention = hasDateDueProperty(settings);
const today = getLocalCalendarDay(now2());
const key2 = buildCacheKey(settings, inScope, producesAttention ? getLocalDayKey(today) : void 0);
const cached = cacheByPath.get(path);
if (cached && cached.key === key2) {
publish(path, cached.counts);
return;
}
const counts = await countTasks(settings, inScope, producesAttention ? today : void 0);
cacheByPath.set(path, { key: key2, counts });
publish(path, counts);
}
async function countTasks(settings, inScope, today) {
var _a6;
const { columnPlacementTagTable } = createColumnData(settings.columns);
const columnDefinitionsStore = readable(settings.columns);
const columnPlacementTagTableStore = readable(columnPlacementTagTable);
const markerSettings = getMarkerSettings(settings);
const tasksByTaskId = /* @__PURE__ */ new Map();
const metadataByTaskId = /* @__PURE__ */ new Map();
const taskIdsByFileHandle = /* @__PURE__ */ new Map();
for (const fileHandle of inScope) {
await updateMapsFromFile({
fileHandle,
tasksByTaskId,
metadataByTaskId,
taskIdsByFileHandle,
vault: { read: (file) => host.cachedRead(file) },
columnDefinitionsStore,
columnPlacementTagTableStore,
...markerSettings
});
}
const tasks = [...tasksByTaskId.values()];
const attention = today ? { overdue: 0, dueToday: 0 } : void 0;
const countsByColumnId = new Map(
settings.columns.filter((column) => !RESERVED_COLUMN_KEYS.has(column.id)).map((column) => [column.id, 0])
);
let uncategorized = 0;
let done = 0;
for (const task of tasks) {
if (task.done || task.column === "done") {
done += 1;
} else if (task.column === "archived") {
} else if (task.column !== void 0 && countsByColumnId.has(task.column)) {
countsByColumnId.set(task.column, ((_a6 = countsByColumnId.get(task.column)) != null ? _a6 : 0) + 1);
countAttention(task, today, attention);
} else {
uncategorized += 1;
countAttention(task, today, attention);
}
}
const columns = [
// Non-zero only, like the board's auto uncategorized visibility;
// real columns list at zero so the breakdown mirrors the layout.
...uncategorized > 0 ? [
{
label: settings.uncategorizedColumnName || "Uncategorized",
count: uncategorized
}
] : [],
...settings.columns.filter((column) => !RESERVED_COLUMN_KEYS.has(column.id)).map((column) => {
var _a7;
return {
label: column.label,
count: (_a7 = countsByColumnId.get(column.id)) != null ? _a7 : 0
};
}),
{ label: settings.doneColumnName || "Done", count: done }
];
return {
// The board-corner rule: not done, not archived, not in done.
open: getBoardTaskCount(tasks),
done,
...attention ? { attention } : {},
columns
};
}
async function pump() {
pumping = true;
try {
while (queue.length > 0 && !destroyed) {
const path = queue.shift();
queued.delete(path);
try {
await computeBoard(path);
} catch (error) {
console.error(`Failed to compute board stats for ${path}`, error);
}
}
} finally {
pumping = false;
}
}
return {
countsStore: { subscribe: countsStore.subscribe },
requestCounts(paths) {
if (destroyed) {
return;
}
for (const path of paths) {
if (queued.has(path)) {
continue;
}
queued.add(path);
queue.push(path);
}
if (!pumping && queue.length > 0) {
void pump();
}
},
destroy() {
destroyed = true;
queue.length = 0;
queued.clear();
}
};
}
function countsEqual(a, b) {
return a.open === b.open && a.done === b.done && attentionEqual(a.attention, b.attention) && a.columns.length === b.columns.length && a.columns.every(
(column, index2) => {
var _a5, _b3;
return column.label === ((_a5 = b.columns[index2]) == null ? void 0 : _a5.label) && column.count === ((_b3 = b.columns[index2]) == null ? void 0 : _b3.count);
}
);
}
function attentionEqual(a, b) {
return a === b || a !== void 0 && b !== void 0 && a.overdue === b.overdue && a.dueToday === b.dueToday;
}
function countAttention(task, today, attention) {
var _a5;
if (!today || !attention) {
return;
}
const due = (_a5 = task.properties.get("due")) == null ? void 0 : _a5.value;
if (!(due instanceof Date)) {
return;
}
const dueDay = toCalendarDay(due).getTime();
const todayTime = today.getTime();
if (dueDay < todayTime) {
attention.overdue += 1;
} else if (dueDay === todayTime) {
attention.dueToday += 1;
}
}
function hasDateDueProperty(settings) {
const schema2 = getMarkerSettings(settings).propertySchema;
return schema2.knownKeys().some((key2) => key2.key === "due" && key2.type === "date");
}
function getLocalCalendarDay(date) {
return new Date(Date.UTC(date.getFullYear(), date.getMonth(), date.getDate()));
}
function getLocalDayKey(day) {
return day.toISOString().slice(0, 10);
}
function buildCacheKey(settings, inScope, dayKey) {
const relevantSettings = {};
for (const key2 of COUNT_SETTING_KEYS) {
relevantSettings[key2] = settings[key2];
}
const files = inScope.map((file) => [file.path, file.stat.mtime]).sort((a, b) => a[0].localeCompare(b[0]));
return JSON.stringify({ settings: relevantSettings, files, dayKey });
}
// src/ui/boards/board_creation.ts
var import_obsidian19 = require("obsidian");
var INITIAL_KANBAN_BOARD_CONTENT = `---
kanban_plugin: {}
---
`;
var DEFAULT_BOARD_BASENAME = "Kanban";
var MAX_FILENAME_ATTEMPTS = 100;
function parentFolderPathForFilePath(path) {
if (!path) {
return "";
}
const slashIndex = path.lastIndexOf("/");
return slashIndex === -1 ? "" : path.slice(0, slashIndex);
}
function boardFilePathForAttempt(folderPath, timestamp2, attempt) {
const suffix = attempt === 0 ? "" : `-${attempt}`;
const fileName = `${DEFAULT_BOARD_BASENAME}-${timestamp2}${suffix}.md`;
return folderPath ? `${folderPath}/${fileName}` : fileName;
}
function getDefaultFolderForCurrentBoard(currentBoardPath) {
return parentFolderPathForFilePath(currentBoardPath);
}
function getDefaultFolderForActiveFile(activeFilePath) {
return parentFolderPathForFilePath(activeFilePath);
}
async function createKanbanBoardInFolder(vault, folderPath, now2 = Date.now) {
const normalizedFolderPath = folderPath === "/" ? "" : folderPath;
const folder = normalizedFolderPath ? vault.getAbstractFileByPath(normalizedFolderPath) : vault.getRoot();
if (!(folder instanceof import_obsidian19.TFolder)) {
throw new Error(`Folder not found: ${folderPath || "vault root"}`);
}
const timestamp2 = now2();
for (let attempt = 0; attempt < MAX_FILENAME_ATTEMPTS; attempt += 1) {
const path = boardFilePathForAttempt(normalizedFolderPath, timestamp2, attempt);
if (vault.getAbstractFileByPath(path)) {
continue;
}
try {
return await vault.create(path, INITIAL_KANBAN_BOARD_CONTENT);
} catch (error) {
if (vault.getAbstractFileByPath(path)) {
continue;
}
throw error;
}
}
throw new Error("Could not find an available kanban board filename.");
}
var BoardFolderPickerModal = class extends import_obsidian19.FuzzySuggestModal {
constructor(app, defaultFolderPath, onChooseFolder) {
super(app);
this.defaultFolderPath = defaultFolderPath;
this.onChooseFolder = onChooseFolder;
this.setPlaceholder("Choose destination folder for the new board");
this.emptyStateText = "No matching folders";
this.limit = 50;
}
onOpen() {
super.onOpen();
this.inputEl.value = this.defaultFolderPath;
this.inputEl.select();
this.inputEl.dispatchEvent(new Event("input"));
}
getItems() {
const folders = this.app.vault.getAllLoadedFiles().filter((file) => file instanceof import_obsidian19.TFolder);
if (!folders.some((folder) => folder.path === this.app.vault.getRoot().path)) {
folders.push(this.app.vault.getRoot());
}
return folders.sort((a, b) => this.getItemText(a).localeCompare(this.getItemText(b)));
}
getItemText(folder) {
return folder.path || "Vault root";
}
onChooseItem(folder) {
this.onChooseFolder(folder);
}
};
async function createBoardWithNotice(vault, folderPath) {
try {
return await createKanbanBoardInFolder(vault, folderPath);
} catch (error) {
console.error("Failed to create kanban board", error);
new import_obsidian19.Notice("Failed to create kanban board.");
return null;
}
}
// src/ui/boards/board_deletion.ts
var import_obsidian20 = require("obsidian");
async function trashBoardFile(app, path) {
const file = app.vault.getAbstractFileByPath(path);
if (!(file instanceof import_obsidian20.TFile)) {
return { ok: false, reason: "missing" };
}
try {
await app.vault.trash(file, true);
return { ok: true };
} catch (error) {
return { ok: false, reason: "failed", error };
}
}
// src/ui/tasks/create_card_modal.ts
var import_obsidian21 = require("obsidian");
async function openCreateCardModal(app, boards, globalSettings, preferredBoardPath) {
const boardOptions = await loadBoardOptions(app, boards, globalSettings);
if (boardOptions.length === 0) {
new import_obsidian21.Notice("No kanban boards found.");
return;
}
new CreateCardModal(app, boardOptions, preferredBoardPath).open();
}
async function loadBoardOptions(app, boards, globalSettings) {
var _a5, _b3, _c2, _d;
const options = [];
for (const entry of boards) {
const file = app.vault.getAbstractFileByPath(entry.path);
if (!(file instanceof import_obsidian21.TFile)) {
continue;
}
const boardContents = await app.vault.cachedRead(file);
const overrides = parseKanbanSettingsOverridesFromViewData(boardContents);
const settings = resolveSettings(
inheritedSettingsFromGlobalSettings(globalSettings),
overrides
);
const boardFolderPath = (_b3 = (_a5 = file.parent) == null ? void 0 : _a5.path) != null ? _b3 : null;
const filenameFilter = resolveScopeFilter(
settings.scope,
settings.scopeFolders,
boardFolderPath
);
const excludeFilter = ((_c2 = settings.excludePaths) != null ? _c2 : []).length > 0 ? (_d = settings.excludePaths) != null ? _d : [] : null;
const fileOptions = app.vault.getMarkdownFiles().filter(
(candidate) => shouldIncludeFilePath(
candidate.path,
filenameFilter,
excludeFilter,
boardFolderPath
)
).sort((a, b) => a.path.localeCompare(b.path));
options.push({ entry, file, settings, overrides, boardContents, fileOptions });
}
return options;
}
var CreateCardModal = class extends import_obsidian21.Modal {
constructor(app, boardOptions, preferredBoardPath) {
var _a5, _b3;
super(app);
this.boardOptions = boardOptions;
this.selectedBoardIndex = 0;
this.selectedFilePath = "";
this.draftContent = "";
this.textAreaEl = null;
this.submitButtonEl = null;
const preferredIndex = preferredBoardPath ? this.boardOptions.findIndex((option) => option.entry.path === preferredBoardPath) : -1;
this.selectedBoardIndex = preferredIndex >= 0 ? preferredIndex : 0;
const initialBoard = this.boardOptions[this.selectedBoardIndex];
this.selectedColumn = defaultColumnFor(initialBoard.settings);
this.selectedFilePath = (_b3 = (_a5 = defaultFileFor(initialBoard)) == null ? void 0 : _a5.path) != null ? _b3 : "";
}
onOpen() {
this.modalEl.addClass("task-list-kanban-create-card-modal-container");
this.contentEl.addClass("task-list-kanban-create-card-modal");
this.render();
window.requestAnimationFrame(() => {
var _a5;
return (_a5 = this.textAreaEl) == null ? void 0 : _a5.focus();
});
}
onClose() {
this.contentEl.empty();
}
render() {
this.contentEl.empty();
this.contentEl.createEl("h2", { text: "Add card" });
const contentSetting = new import_obsidian21.Setting(this.contentEl).setName("Card text").setClass("create-card-setting").setClass("create-card-content-setting");
this.textAreaEl = contentSetting.controlEl.createEl("textarea", {
cls: "create-card-text",
attr: { rows: "4" }
});
this.textAreaEl.value = this.draftContent;
this.textAreaEl.addEventListener("input", () => {
var _a5, _b3;
this.draftContent = (_b3 = (_a5 = this.textAreaEl) == null ? void 0 : _a5.value) != null ? _b3 : "";
this.updateSubmitState();
});
this.textAreaEl.addEventListener("keydown", (event2) => {
if (event2.key === "Enter" && (event2.metaKey || event2.ctrlKey)) {
event2.preventDefault();
void this.submit();
}
});
this.createSelectField({
label: "Board",
options: this.boardOptions.map((option, index2) => ({
value: String(index2),
label: option.entry.name
})),
value: String(this.selectedBoardIndex),
onChange: (value) => {
var _a5, _b3;
this.selectedBoardIndex = Number(value);
const board = this.currentBoard();
this.selectedColumn = defaultColumnFor(board.settings);
this.selectedFilePath = (_b3 = (_a5 = defaultFileFor(board)) == null ? void 0 : _a5.path) != null ? _b3 : "";
this.render();
}
});
this.createSelectField({
label: "Column",
options: columnOptionsFor(this.currentBoard().settings).map((option) => ({
value: option.id,
label: option.label
})),
value: this.selectedColumn,
onChange: (value) => {
this.selectedColumn = value;
}
});
this.createSelectField({
label: "File",
options: this.currentBoard().fileOptions.map((file) => ({
value: file.path,
label: file.path
})),
value: this.selectedFilePath,
onChange: (value) => {
this.selectedFilePath = value;
}
});
const actions = this.contentEl.createDiv({ cls: "confirm-modal-actions" });
const cancelButton = actions.createEl("button", { text: "Cancel" });
cancelButton.addEventListener("click", () => this.close());
this.submitButtonEl = actions.createEl("button", {
text: "Add card",
cls: "mod-cta"
});
this.submitButtonEl.addEventListener("click", () => void this.submit());
this.updateSubmitState();
}
createSelectField({
label,
options,
value,
onChange
}) {
const setting = new import_obsidian21.Setting(this.contentEl).setName(label).setClass("create-card-setting");
const select = setting.controlEl.createEl("select", {
cls: "create-card-select"
});
for (const option of options) {
select.createEl("option", {
text: option.label,
value: option.value
});
}
select.value = value;
select.addEventListener("change", () => onChange(select.value));
return select;
}
currentBoard() {
var _a5;
return (_a5 = this.boardOptions[this.selectedBoardIndex]) != null ? _a5 : this.boardOptions[0];
}
updateSubmitState() {
var _a5, _b3;
if (!this.submitButtonEl) {
return;
}
this.submitButtonEl.disabled = ((_b3 = (_a5 = this.textAreaEl) == null ? void 0 : _a5.value.trim()) != null ? _b3 : "") === "" || !this.selectedFilePath || this.currentBoard().fileOptions.length === 0;
}
async submit() {
var _a5, _b3, _c2;
const content = (_b3 = (_a5 = this.textAreaEl) == null ? void 0 : _a5.value.trim()) != null ? _b3 : "";
if (!content) {
return;
}
const board = this.currentBoard();
const targetFile = board.fileOptions.find(
(file) => file.path === this.selectedFilePath
);
if (!targetFile) {
new import_obsidian21.Notice("Choose a file for the new card.");
return;
}
const { columnPlacementTagTable } = createColumnData(board.settings.columns);
const taskLine = buildNewTaskLine({
content,
column: this.selectedColumn,
columnDefinitions: board.settings.columns,
getPlacementTagsForColumn: (column) => {
var _a6;
return (_a6 = columnPlacementTagTable[column]) != null ? _a6 : [column];
},
propertySchemaOption: (_c2 = board.settings.propertySchema) != null ? _c2 : "none" /* None */
});
const nextOverrides = {
...board.overrides,
lastUsedTaskFile: targetFile.path
};
if (this.submitButtonEl) {
this.submitButtonEl.disabled = true;
}
try {
await updateRow(
this.app.vault,
targetFile,
void 0,
taskLine,
(file, nextContents) => file.path === board.file.path ? writeKanbanSettingsToViewData(nextContents, nextOverrides) : nextContents
);
if (targetFile.path !== board.file.path) {
await this.app.vault.modify(
board.file,
writeKanbanSettingsToViewData(board.boardContents, nextOverrides)
);
}
new import_obsidian21.Notice("Card added.");
this.close();
} catch (error) {
console.error("Failed to add card from command", error);
new import_obsidian21.Notice("Failed to add card.");
if (this.submitButtonEl) {
this.submitButtonEl.disabled = false;
}
}
}
};
function columnOptionsFor(settings) {
return [
{ id: "uncategorised", label: settings.uncategorizedColumnName || "Uncategorized" },
...settings.columns.map((column) => ({ id: column.id, label: column.label })),
{ id: "done", label: settings.doneColumnName || "Done" }
];
}
function defaultColumnFor(settings) {
var _a5, _b3;
return (_b3 = (_a5 = settings.columns[0]) == null ? void 0 : _a5.id) != null ? _b3 : "uncategorised";
}
function defaultFileFor(board) {
var _a5;
const preferredPaths = [
board.settings.defaultTaskFile,
board.settings.lastUsedTaskFile
].filter((path) => !!path);
for (const path of preferredPaths) {
const file = board.fileOptions.find((candidate) => candidate.path === path);
if (file) {
return file;
}
}
return (_a5 = board.fileOptions[0]) != null ? _a5 : null;
}
// src/entry.ts
var Base = class extends import_obsidian22.Plugin {
constructor() {
super(...arguments);
this.globalSettingsStore = createGlobalSettingsStore();
this.inheritedSettingsStore = createInheritedSettingsStore(this.globalSettingsStore);
this.globalViewsStore = derived(
this.globalSettingsStore,
(settings) => {
var _a5;
return (_a5 = settings.globalViews) != null ? _a5 : [];
}
);
this.boardListSettingsStore = derived(
this.globalSettingsStore,
(settings) => settings.boardList
);
this.lastOpenedStore = derived(
this.globalSettingsStore,
(settings) => {
var _a5;
return (_a5 = settings.lastOpenedByPath) != null ? _a5 : {};
}
);
this.boardRailSettingsStore = derived(
this.globalSettingsStore,
(settings) => settings.boardRail
);
}
async onload() {
this.globalSettingsStore.set(parseGlobalSettings(await this.loadData()));
const boardIndex = createBoardIndex(this.app, this.registerEvent.bind(this));
this.boardIndex = boardIndex;
const boardStats = createBoardStatsService({
getMarkdownFiles: () => this.app.vault.getMarkdownFiles(),
cachedRead: (file) => this.app.vault.cachedRead(file),
getBoardSettingsPayload: (file) => {
var _a5, _b3;
return toSettingsPayload(
(_b3 = (_a5 = this.app.metadataCache.getFileCache(file)) == null ? void 0 : _a5.frontmatter) == null ? void 0 : _b3["kanban_plugin"]
);
},
getGlobalSettings: () => this.globalSettingsStore.get()
});
this.boardStats = boardStats;
this.registerView(
KANBAN_VIEW_NAME,
(leaf) => new KanbanView(
leaf,
this.inheritedSettingsStore,
this.globalViewsStore,
boardIndex.store,
this.boardListSettingsStore,
(path, hidden) => void this.setBoardHidden(path, hidden),
(orderedPaths) => void this.reorderBoards(orderedPaths),
boardStats.countsStore,
(paths) => boardStats.requestCounts(paths),
this.lastOpenedStore,
(path) => void this.recordBoardOpened(path),
this.boardRailSettingsStore,
(width) => void this.setBoardRailWidth(width),
(view) => this.createBoardFromDashboard(view),
(path) => this.deleteBoardFromDashboard(path)
)
);
this.addSettingTab(
new GlobalSettingsTab(
this.app,
this,
this.globalSettingsStore,
() => this.saveGlobalSettings()
)
);
this.registerHoverLinkSource("kanban-view", {
display: "Kanban",
defaultMod: false
});
this.addCommand({
id: "create-new-kanban-board",
name: "Create new kanban board",
callback: () => {
void this.createBoardFromGlobalSurface();
}
});
this.addRibbonIcon("square-kanban", "New Kanban board", () => {
void this.createBoardFromGlobalSurface();
});
this.addCommand({
id: "add-card",
name: "Add card",
callback: () => {
void openCreateCardModal(
this.app,
this.boardIndex ? get2(this.boardIndex.store) : [],
this.globalSettingsStore.get(),
this.getFirstVisibleKanbanBoardPath()
);
}
});
this.addCommand({
id: "show-board-dashboard",
name: "Show board dashboard",
checkCallback: (checking) => {
const view = this.app.workspace.getActiveViewOfType(KanbanView);
if (!view) {
return false;
}
if (!checking) {
view.toggleDashboard();
}
return true;
}
});
this.addCommand({
id: "use-current-board-settings-as-global-defaults",
name: "Use current board settings as global defaults",
checkCallback: (checking) => {
const view = this.app.workspace.getActiveViewOfType(KanbanView);
if (!view) {
return false;
}
if (!checking) {
void this.useCurrentBoardSettingsAsGlobalDefaults(view);
}
return true;
}
});
this.addCommand({
id: "prune-board-settings-matching-defaults",
name: "Prune board settings that match the defaults",
checkCallback: (checking) => {
const view = this.app.workspace.getActiveViewOfType(KanbanView);
if (!view) {
return false;
}
if (!checking) {
view.pruneSettingsMatchingDefaults();
}
return true;
}
});
this.addCommand({
id: "open-current-board-settings",
name: "Open current board settings",
checkCallback: (checking) => {
const view = this.app.workspace.getActiveViewOfType(KanbanView);
if (!view) {
return false;
}
if (!checking) {
view.openCurrentBoardSettings();
}
return true;
}
});
this.addSelectedCardsCommand(
"mark-selected-cards-done",
"Mark selected cards as done",
(view) => view.markSelectedCardsDone()
);
this.addSelectedCardsCommand(
"archive-selected-cards",
"Archive selected cards",
(view) => view.archiveSelectedCards()
);
this.addSelectedCardsCommand(
"cancel-selected-cards",
"Cancel selected cards",
(view) => view.cancelSelectedCards()
);
this.addSelectedCardsCommand(
"duplicate-selected-cards",
"Duplicate selected cards",
(view) => view.duplicateSelectedCards()
);
this.addSelectedCardsCommand(
"delete-selected-cards",
"Delete selected cards",
(view) => view.deleteSelectedCards()
);
this.switchToKanbanAfterLoad();
this.registerEvent(
this.app.workspace.on("active-leaf-change", () => {
this.switchToKanbanAfterLoad();
})
);
this.registerEvent(
this.app.vault.on("rename", (file, oldPath) => {
void this.rewriteBoardListSettingsPaths(oldPath, file.path);
})
);
this.registerEvent(
this.app.workspace.on("file-menu", (menu, file) => {
if (!(file instanceof import_obsidian22.TFolder)) {
return;
}
menu.addItem((item) => {
item.setTitle("New kanban").setIcon("square-kanban").onClick(async () => {
const newFile = await createBoardWithNotice(
this.app.vault,
file.path
);
if (newFile) {
await this.openCreatedBoard(newFile);
}
});
});
})
);
}
onunload() {
var _a5, _b3;
(_a5 = this.boardIndex) == null ? void 0 : _a5.destroy();
(_b3 = this.boardStats) == null ? void 0 : _b3.destroy();
}
getFirstVisibleKanbanBoardPath() {
for (const leaf of this.app.workspace.getLeavesOfType(KANBAN_VIEW_NAME)) {
const view = leaf.view;
if (view instanceof KanbanView && view.file) {
return view.file.path;
}
}
return void 0;
}
addSelectedCardsCommand(id, name, run3) {
this.addCommand({
id,
name,
checkCallback: (checking) => {
const view = this.app.workspace.getActiveViewOfType(KanbanView);
if (!view || !view.hasVisibleSelectedCards()) {
return false;
}
if (!checking) {
run3(view);
}
return true;
}
});
}
async saveGlobalSettings() {
await this.saveData(serializeGlobalSettings(this.globalSettingsStore.get()));
}
async rewriteBoardListSettingsPaths(oldPath, newPath) {
const current = this.globalSettingsStore.get();
const rewrittenBoardList = rewriteBoardListPaths(
current.boardList,
oldPath,
newPath
);
const rewrittenLastOpened = rewriteLastOpenedPaths(
current.lastOpenedByPath,
oldPath,
newPath
);
if (!rewrittenBoardList && !rewrittenLastOpened) {
return;
}
this.globalSettingsStore.update((settings) => ({
...settings,
...rewrittenBoardList ? { boardList: rewrittenBoardList } : {},
...rewrittenLastOpened ? { lastOpenedByPath: rewrittenLastOpened } : {}
}));
await this.saveGlobalSettings();
}
// Stamped whenever a kanban view loads a board (SPEC 0033 Phase 3c) —
// neither the filesystem nor Obsidian tracks access times, so the plugin
// records its own. Entries for since-deleted files are shed on the same
// write, keeping data.json from accreting ghosts.
async recordBoardOpened(path) {
this.globalSettingsStore.update((settings) => {
var _a5;
const lastOpenedByPath = {};
for (const [boardPath, openedAt] of Object.entries(
(_a5 = settings.lastOpenedByPath) != null ? _a5 : {}
)) {
if (this.app.vault.getAbstractFileByPath(boardPath)) {
lastOpenedByPath[boardPath] = openedAt;
}
}
lastOpenedByPath[path] = Date.now();
return { ...settings, lastOpenedByPath };
});
await this.saveGlobalSettings();
}
// Board rail resize (SPEC 0034): persisted on drag release, plugin-wide
// like the rest of data.json. serializeGlobalSettings clamps the width
// and sheds the key when everything is back at the defaults. Merged so
// the width write never clobbers the dock setting.
async setBoardRailWidth(width) {
this.globalSettingsStore.update((settings) => ({
...settings,
boardRail: { ...settings.boardRail, width }
}));
await this.saveGlobalSettings();
}
// Dashboard card drag reorder: the shown order, with the dragged card
// moved, becomes the explicit board order. Unpinned state is left
// untouched, and stale paths fall out (the shown list only contains
// discovered boards).
async reorderBoards(orderedPaths) {
this.globalSettingsStore.update((settings) => ({
...settings,
boardList: {
...settings.boardList,
boardPaths: orderedPaths
}
}));
await this.saveGlobalSettings();
}
// The dashboard card menu's "Hide board" / "Show board": hidden boards
// move under the panel's "Other boards" zippy. Explicit order is left
// untouched, so hiding and re-showing an ordered board restores its slot.
async setBoardHidden(path, hidden) {
this.globalSettingsStore.update((settings) => {
var _a5, _b3;
const unpinnedPaths = ((_b3 = (_a5 = settings.boardList) == null ? void 0 : _a5.unpinnedPaths) != null ? _b3 : []).filter(
(candidate) => candidate !== path
);
if (hidden) {
unpinnedPaths.push(path);
}
return {
...settings,
boardList: {
...settings.boardList,
...unpinnedPaths.length > 0 ? { unpinnedPaths } : { unpinnedPaths: void 0 }
}
};
});
await this.saveGlobalSettings();
}
async useCurrentBoardSettingsAsGlobalDefaults(view) {
this.globalSettingsStore.update((settings) => ({
...settings,
boardDefaults: pickBoardDefaultSettings(view.getResolvedSettingsSnapshot())
}));
await this.saveGlobalSettings();
new import_obsidian22.Notice("Task List Kanban global board defaults updated.");
}
async createBoardFromDashboard(view) {
var _a5, _b3;
const defaultFolderPath = getDefaultFolderForCurrentBoard((_b3 = (_a5 = view.file) == null ? void 0 : _a5.path) != null ? _b3 : null);
const newFile = await this.pickAndCreateBoard(defaultFolderPath);
if (!newFile) {
return false;
}
await view.openBoard(newFile.path);
return true;
}
async createBoardFromGlobalSurface() {
var _a5, _b3;
const defaultFolderPath = getDefaultFolderForActiveFile(
(_b3 = (_a5 = this.app.workspace.getActiveFile()) == null ? void 0 : _a5.path) != null ? _b3 : null
);
const newFile = await this.pickAndCreateBoard(defaultFolderPath);
if (newFile) {
await this.openCreatedBoard(newFile);
}
}
pickAndCreateBoard(defaultFolderPath) {
return new Promise((resolve) => {
let resolved = false;
let creationStarted = false;
const resolveOnce = (file) => {
if (!resolved) {
resolved = true;
resolve(file);
}
};
const modal = new BoardFolderPickerModal(
this.app,
defaultFolderPath,
(folder) => {
creationStarted = true;
void (async () => {
try {
const newFile = await createKanbanBoardInFolder(
this.app.vault,
folder.path
);
resolveOnce(newFile);
} catch (error) {
console.error("Failed to create kanban board", error);
new import_obsidian22.Notice("Failed to create kanban board.");
resolveOnce(null);
}
})();
}
);
const originalOnClose = modal.onClose.bind(modal);
modal.onClose = () => {
originalOnClose();
if (!creationStarted) {
resolveOnce(null);
}
};
modal.open();
});
}
async openCreatedBoard(file) {
const kanbanView = this.app.workspace.getActiveViewOfType(KanbanView);
if (kanbanView) {
await kanbanView.openBoard(file.path);
return;
}
const markdownView = this.app.workspace.getActiveViewOfType(import_obsidian22.MarkdownView);
if (markdownView) {
await markdownView.leaf.openFile(file);
return;
}
await this.app.workspace.getLeaf(false).openFile(file);
}
async deleteBoardFromDashboard(path) {
var _a5, _b3;
const file = this.app.vault.getAbstractFileByPath(path);
if (!(file instanceof import_obsidian22.TFile)) {
new import_obsidian22.Notice("Board file not found.");
return false;
}
const activeKanbanView = this.app.workspace.getActiveViewOfType(KanbanView);
const fallbackBoardPath = this.boardIndex ? (_a5 = get2(this.boardIndex.store).find((board) => board.path !== path)) == null ? void 0 : _a5.path : void 0;
const result = await trashBoardFile(this.app, path);
if (!result.ok) {
if (result.reason === "failed") {
console.error("Failed to delete board", result.error);
}
new import_obsidian22.Notice("Failed to delete board.");
return false;
}
this.globalSettingsStore.set(
removeBoardPathFromGlobalSettings(this.globalSettingsStore.get(), path)
);
await this.saveGlobalSettings();
if (((_b3 = activeKanbanView == null ? void 0 : activeKanbanView.file) == null ? void 0 : _b3.path) === path && fallbackBoardPath) {
await activeKanbanView.openBoard(fallbackBoardPath);
}
return true;
}
switchToKanbanAfterLoad() {
this.app.workspace.onLayoutReady(() => {
let leaf;
for (leaf of this.app.workspace.getLeavesOfType("markdown")) {
if (leaf.view instanceof import_obsidian22.MarkdownView && this.isKanbanFile(leaf.view.file)) {
this.setKanbanView(leaf);
}
}
});
}
isKanbanFile(file) {
if (!file) {
return false;
}
const fileCache = this.app.metadataCache.getFileCache(file);
return !!(fileCache == null ? void 0 : fileCache.frontmatter) && !!fileCache.frontmatter["kanban_plugin"];
}
async setKanbanView(leaf) {
await leaf.setViewState({
type: KANBAN_VIEW_NAME,
state: leaf.view.getState()
});
}
};
/* nosourcemap */