Files
2026-05-31 14:33:58 -04:00

3389 lines
132 KiB
JavaScript

/*
THIS IS A GENERATED/BUNDLED FILE BY ESBUILD
if you want to view the source, please visit the github repository of this plugin
*/
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 __markAsModule = (target) => __defProp(target, "__esModule", { value: true });
var __export = (target, all) => {
__markAsModule(target);
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __reExport = (target, module2, desc) => {
if (module2 && typeof module2 === "object" || typeof module2 === "function") {
for (let key of __getOwnPropNames(module2))
if (!__hasOwnProp.call(target, key) && key !== "default")
__defProp(target, key, { get: () => module2[key], enumerable: !(desc = __getOwnPropDesc(module2, key)) || desc.enumerable });
}
return target;
};
var __toModule = (module2) => {
return __reExport(__markAsModule(__defProp(module2 != null ? __create(__getProtoOf(module2)) : {}, "default", module2 && module2.__esModule && "default" in module2 ? { get: () => module2.default, enumerable: true } : { value: module2, enumerable: true })), module2);
};
var __async = (__this, __arguments, generator) => {
return new Promise((resolve, reject) => {
var fulfilled = (value) => {
try {
step(generator.next(value));
} catch (e) {
reject(e);
}
};
var rejected = (value) => {
try {
step(generator.throw(value));
} catch (e) {
reject(e);
}
};
var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
step((generator = generator.apply(__this, __arguments)).next());
});
};
// src/main.ts
__export(exports, {
default: () => NoteAutoCreator
});
var import_obsidian8 = __toModule(require("obsidian"));
// src/settings/NoteAutoCreatorSettings.ts
var FolderSuggestionMode;
(function(FolderSuggestionMode2) {
FolderSuggestionMode2["Always"] = "always";
FolderSuggestionMode2["OnTrigger"] = "on-trigger";
})(FolderSuggestionMode || (FolderSuggestionMode = {}));
var DEFAULT_SETTINGS = {
triggerSymbol: "@",
suggestLinksToNonExistingNotes: true,
relativeTopFolders: [],
includeFoldersInSuggestions: false,
folderSuggestionSettings: { folderSuggestionMode: FolderSuggestionMode.Always, folderSuggestionTrigger: "/" },
enableRelativePaths: true,
templateTriggerSymbol: "$",
defaultTemplaterTemplate: "",
quickAddTriggerSymbol: "\u20AC",
defaultQuickAddTemplate: "",
enabledFolders: [],
triggerHeaderAsAliasSymbol: "!"
};
// src/settings/SettingTab.ts
var import_obsidian3 = __toModule(require("obsidian"));
// src/core/paths/ObsidianPath.ts
var ObsidianPath = class {
constructor(vaultPath, title) {
this.VaultPath = vaultPath;
this.Title = title;
}
toString() {
return this.VaultPath;
}
};
// src/core/paths/ObsidianFolderPath.ts
var ObsidianFolderPath = class extends ObsidianPath {
get IsRoot() {
return this.VaultPath === "" || this.VaultPath === "/";
}
constructor(path) {
const fullPath = path.trim();
const folderName = ObsidianFolderPath.getFolderName(fullPath);
super(fullPath, folderName);
}
static getFolderName(fullPath) {
let folderNameStartsAt = fullPath.lastIndexOf("/");
let folderNameEndsAt = fullPath.length;
if (folderNameStartsAt === -1) {
return fullPath;
}
if (folderNameStartsAt === fullPath.length - 1) {
folderNameStartsAt = fullPath.slice(0, folderNameStartsAt).lastIndexOf("/");
folderNameEndsAt = fullPath.length - 1;
}
return fullPath.slice(folderNameStartsAt + 1, folderNameEndsAt);
}
getParentOrThis() {
if (this.IsRoot) {
return this;
}
const lastDivider = this.VaultPath.lastIndexOf("/");
const parentPath = this.VaultPath.substring(0, lastDivider);
return new ObsidianFolderPath(parentPath);
}
isAncestorOf(path) {
if (this.IsRoot) {
return true;
}
return path.VaultPath.toLowerCase().startsWith(this.VaultPath.toLowerCase());
}
isDescendantOf(path) {
return path.isAncestorOf(this);
}
};
// src/settings/FolderSuggester.ts
var import_obsidian2 = __toModule(require("obsidian"));
// src/settings/suggest.ts
var import_obsidian = __toModule(require("obsidian"));
// node_modules/@popperjs/core/lib/enums.js
var top = "top";
var bottom = "bottom";
var right = "right";
var left = "left";
var auto = "auto";
var basePlacements = [top, bottom, right, left];
var start = "start";
var end = "end";
var clippingParents = "clippingParents";
var viewport = "viewport";
var popper = "popper";
var reference = "reference";
var variationPlacements = /* @__PURE__ */ basePlacements.reduce(function(acc, placement) {
return acc.concat([placement + "-" + start, placement + "-" + end]);
}, []);
var placements = /* @__PURE__ */ [].concat(basePlacements, [auto]).reduce(function(acc, placement) {
return acc.concat([placement, placement + "-" + start, placement + "-" + end]);
}, []);
var beforeRead = "beforeRead";
var read = "read";
var afterRead = "afterRead";
var beforeMain = "beforeMain";
var main = "main";
var afterMain = "afterMain";
var beforeWrite = "beforeWrite";
var write = "write";
var afterWrite = "afterWrite";
var modifierPhases = [beforeRead, read, afterRead, beforeMain, main, afterMain, beforeWrite, write, afterWrite];
// node_modules/@popperjs/core/lib/dom-utils/getNodeName.js
function getNodeName(element) {
return element ? (element.nodeName || "").toLowerCase() : null;
}
// node_modules/@popperjs/core/lib/dom-utils/getWindow.js
function getWindow(node) {
if (node == null) {
return window;
}
if (node.toString() !== "[object Window]") {
var ownerDocument = node.ownerDocument;
return ownerDocument ? ownerDocument.defaultView || window : window;
}
return node;
}
// node_modules/@popperjs/core/lib/dom-utils/instanceOf.js
function isElement(node) {
var OwnElement = getWindow(node).Element;
return node instanceof OwnElement || node instanceof Element;
}
function isHTMLElement(node) {
var OwnElement = getWindow(node).HTMLElement;
return node instanceof OwnElement || node instanceof HTMLElement;
}
function isShadowRoot(node) {
if (typeof ShadowRoot === "undefined") {
return false;
}
var OwnElement = getWindow(node).ShadowRoot;
return node instanceof OwnElement || node instanceof ShadowRoot;
}
// node_modules/@popperjs/core/lib/modifiers/applyStyles.js
function applyStyles(_ref) {
var state = _ref.state;
Object.keys(state.elements).forEach(function(name) {
var style = state.styles[name] || {};
var attributes = state.attributes[name] || {};
var element = state.elements[name];
if (!isHTMLElement(element) || !getNodeName(element)) {
return;
}
Object.assign(element.style, style);
Object.keys(attributes).forEach(function(name2) {
var value = attributes[name2];
if (value === false) {
element.removeAttribute(name2);
} else {
element.setAttribute(name2, value === true ? "" : value);
}
});
});
}
function effect(_ref2) {
var state = _ref2.state;
var initialStyles = {
popper: {
position: state.options.strategy,
left: "0",
top: "0",
margin: "0"
},
arrow: {
position: "absolute"
},
reference: {}
};
Object.assign(state.elements.popper.style, initialStyles.popper);
state.styles = initialStyles;
if (state.elements.arrow) {
Object.assign(state.elements.arrow.style, initialStyles.arrow);
}
return function() {
Object.keys(state.elements).forEach(function(name) {
var element = state.elements[name];
var attributes = state.attributes[name] || {};
var styleProperties = Object.keys(state.styles.hasOwnProperty(name) ? state.styles[name] : initialStyles[name]);
var style = styleProperties.reduce(function(style2, property) {
style2[property] = "";
return style2;
}, {});
if (!isHTMLElement(element) || !getNodeName(element)) {
return;
}
Object.assign(element.style, style);
Object.keys(attributes).forEach(function(attribute) {
element.removeAttribute(attribute);
});
});
};
}
var applyStyles_default = {
name: "applyStyles",
enabled: true,
phase: "write",
fn: applyStyles,
effect,
requires: ["computeStyles"]
};
// node_modules/@popperjs/core/lib/utils/getBasePlacement.js
function getBasePlacement(placement) {
return placement.split("-")[0];
}
// node_modules/@popperjs/core/lib/utils/math.js
var max = Math.max;
var min = Math.min;
var round = Math.round;
// node_modules/@popperjs/core/lib/utils/userAgent.js
function getUAString() {
var uaData = navigator.userAgentData;
if (uaData != null && uaData.brands) {
return uaData.brands.map(function(item) {
return item.brand + "/" + item.version;
}).join(" ");
}
return navigator.userAgent;
}
// node_modules/@popperjs/core/lib/dom-utils/isLayoutViewport.js
function isLayoutViewport() {
return !/^((?!chrome|android).)*safari/i.test(getUAString());
}
// node_modules/@popperjs/core/lib/dom-utils/getBoundingClientRect.js
function getBoundingClientRect(element, includeScale, isFixedStrategy) {
if (includeScale === void 0) {
includeScale = false;
}
if (isFixedStrategy === void 0) {
isFixedStrategy = false;
}
var clientRect = element.getBoundingClientRect();
var scaleX = 1;
var scaleY = 1;
if (includeScale && isHTMLElement(element)) {
scaleX = element.offsetWidth > 0 ? round(clientRect.width) / element.offsetWidth || 1 : 1;
scaleY = element.offsetHeight > 0 ? round(clientRect.height) / element.offsetHeight || 1 : 1;
}
var _ref = isElement(element) ? getWindow(element) : window, visualViewport = _ref.visualViewport;
var addVisualOffsets = !isLayoutViewport() && isFixedStrategy;
var x = (clientRect.left + (addVisualOffsets && visualViewport ? visualViewport.offsetLeft : 0)) / scaleX;
var y = (clientRect.top + (addVisualOffsets && visualViewport ? visualViewport.offsetTop : 0)) / scaleY;
var width = clientRect.width / scaleX;
var height = clientRect.height / scaleY;
return {
width,
height,
top: y,
right: x + width,
bottom: y + height,
left: x,
x,
y
};
}
// node_modules/@popperjs/core/lib/dom-utils/getLayoutRect.js
function getLayoutRect(element) {
var clientRect = getBoundingClientRect(element);
var width = element.offsetWidth;
var height = element.offsetHeight;
if (Math.abs(clientRect.width - width) <= 1) {
width = clientRect.width;
}
if (Math.abs(clientRect.height - height) <= 1) {
height = clientRect.height;
}
return {
x: element.offsetLeft,
y: element.offsetTop,
width,
height
};
}
// node_modules/@popperjs/core/lib/dom-utils/contains.js
function contains(parent, child) {
var rootNode = child.getRootNode && child.getRootNode();
if (parent.contains(child)) {
return true;
} else if (rootNode && isShadowRoot(rootNode)) {
var next = child;
do {
if (next && parent.isSameNode(next)) {
return true;
}
next = next.parentNode || next.host;
} while (next);
}
return false;
}
// node_modules/@popperjs/core/lib/dom-utils/getComputedStyle.js
function getComputedStyle(element) {
return getWindow(element).getComputedStyle(element);
}
// node_modules/@popperjs/core/lib/dom-utils/isTableElement.js
function isTableElement(element) {
return ["table", "td", "th"].indexOf(getNodeName(element)) >= 0;
}
// node_modules/@popperjs/core/lib/dom-utils/getDocumentElement.js
function getDocumentElement(element) {
return ((isElement(element) ? element.ownerDocument : element.document) || window.document).documentElement;
}
// node_modules/@popperjs/core/lib/dom-utils/getParentNode.js
function getParentNode(element) {
if (getNodeName(element) === "html") {
return element;
}
return element.assignedSlot || element.parentNode || (isShadowRoot(element) ? element.host : null) || getDocumentElement(element);
}
// node_modules/@popperjs/core/lib/dom-utils/getOffsetParent.js
function getTrueOffsetParent(element) {
if (!isHTMLElement(element) || getComputedStyle(element).position === "fixed") {
return null;
}
return element.offsetParent;
}
function getContainingBlock(element) {
var isFirefox = /firefox/i.test(getUAString());
var isIE = /Trident/i.test(getUAString());
if (isIE && isHTMLElement(element)) {
var elementCss = getComputedStyle(element);
if (elementCss.position === "fixed") {
return null;
}
}
var currentNode = getParentNode(element);
if (isShadowRoot(currentNode)) {
currentNode = currentNode.host;
}
while (isHTMLElement(currentNode) && ["html", "body"].indexOf(getNodeName(currentNode)) < 0) {
var css = getComputedStyle(currentNode);
if (css.transform !== "none" || css.perspective !== "none" || css.contain === "paint" || ["transform", "perspective"].indexOf(css.willChange) !== -1 || isFirefox && css.willChange === "filter" || isFirefox && css.filter && css.filter !== "none") {
return currentNode;
} else {
currentNode = currentNode.parentNode;
}
}
return null;
}
function getOffsetParent(element) {
var window2 = getWindow(element);
var offsetParent = getTrueOffsetParent(element);
while (offsetParent && isTableElement(offsetParent) && getComputedStyle(offsetParent).position === "static") {
offsetParent = getTrueOffsetParent(offsetParent);
}
if (offsetParent && (getNodeName(offsetParent) === "html" || getNodeName(offsetParent) === "body" && getComputedStyle(offsetParent).position === "static")) {
return window2;
}
return offsetParent || getContainingBlock(element) || window2;
}
// node_modules/@popperjs/core/lib/utils/getMainAxisFromPlacement.js
function getMainAxisFromPlacement(placement) {
return ["top", "bottom"].indexOf(placement) >= 0 ? "x" : "y";
}
// node_modules/@popperjs/core/lib/utils/within.js
function within(min2, value, max2) {
return max(min2, min(value, max2));
}
function withinMaxClamp(min2, value, max2) {
var v = within(min2, value, max2);
return v > max2 ? max2 : v;
}
// node_modules/@popperjs/core/lib/utils/getFreshSideObject.js
function getFreshSideObject() {
return {
top: 0,
right: 0,
bottom: 0,
left: 0
};
}
// node_modules/@popperjs/core/lib/utils/mergePaddingObject.js
function mergePaddingObject(paddingObject) {
return Object.assign({}, getFreshSideObject(), paddingObject);
}
// node_modules/@popperjs/core/lib/utils/expandToHashMap.js
function expandToHashMap(value, keys) {
return keys.reduce(function(hashMap, key) {
hashMap[key] = value;
return hashMap;
}, {});
}
// node_modules/@popperjs/core/lib/modifiers/arrow.js
var toPaddingObject = function toPaddingObject2(padding, state) {
padding = typeof padding === "function" ? padding(Object.assign({}, state.rects, {
placement: state.placement
})) : padding;
return mergePaddingObject(typeof padding !== "number" ? padding : expandToHashMap(padding, basePlacements));
};
function arrow(_ref) {
var _state$modifiersData$;
var state = _ref.state, name = _ref.name, options = _ref.options;
var arrowElement = state.elements.arrow;
var popperOffsets2 = state.modifiersData.popperOffsets;
var basePlacement = getBasePlacement(state.placement);
var axis = getMainAxisFromPlacement(basePlacement);
var isVertical = [left, right].indexOf(basePlacement) >= 0;
var len = isVertical ? "height" : "width";
if (!arrowElement || !popperOffsets2) {
return;
}
var paddingObject = toPaddingObject(options.padding, state);
var arrowRect = getLayoutRect(arrowElement);
var minProp = axis === "y" ? top : left;
var maxProp = axis === "y" ? bottom : right;
var endDiff = state.rects.reference[len] + state.rects.reference[axis] - popperOffsets2[axis] - state.rects.popper[len];
var startDiff = popperOffsets2[axis] - state.rects.reference[axis];
var arrowOffsetParent = getOffsetParent(arrowElement);
var clientSize = arrowOffsetParent ? axis === "y" ? arrowOffsetParent.clientHeight || 0 : arrowOffsetParent.clientWidth || 0 : 0;
var centerToReference = endDiff / 2 - startDiff / 2;
var min2 = paddingObject[minProp];
var max2 = clientSize - arrowRect[len] - paddingObject[maxProp];
var center = clientSize / 2 - arrowRect[len] / 2 + centerToReference;
var offset2 = within(min2, center, max2);
var axisProp = axis;
state.modifiersData[name] = (_state$modifiersData$ = {}, _state$modifiersData$[axisProp] = offset2, _state$modifiersData$.centerOffset = offset2 - center, _state$modifiersData$);
}
function effect2(_ref2) {
var state = _ref2.state, options = _ref2.options;
var _options$element = options.element, arrowElement = _options$element === void 0 ? "[data-popper-arrow]" : _options$element;
if (arrowElement == null) {
return;
}
if (typeof arrowElement === "string") {
arrowElement = state.elements.popper.querySelector(arrowElement);
if (!arrowElement) {
return;
}
}
if (true) {
if (!isHTMLElement(arrowElement)) {
console.error(['Popper: "arrow" element must be an HTMLElement (not an SVGElement).', "To use an SVG arrow, wrap it in an HTMLElement that will be used as", "the arrow."].join(" "));
}
}
if (!contains(state.elements.popper, arrowElement)) {
if (true) {
console.error(['Popper: "arrow" modifier\'s `element` must be a child of the popper', "element."].join(" "));
}
return;
}
state.elements.arrow = arrowElement;
}
var arrow_default = {
name: "arrow",
enabled: true,
phase: "main",
fn: arrow,
effect: effect2,
requires: ["popperOffsets"],
requiresIfExists: ["preventOverflow"]
};
// node_modules/@popperjs/core/lib/utils/getVariation.js
function getVariation(placement) {
return placement.split("-")[1];
}
// node_modules/@popperjs/core/lib/modifiers/computeStyles.js
var unsetSides = {
top: "auto",
right: "auto",
bottom: "auto",
left: "auto"
};
function roundOffsetsByDPR(_ref) {
var x = _ref.x, y = _ref.y;
var win = window;
var dpr = win.devicePixelRatio || 1;
return {
x: round(x * dpr) / dpr || 0,
y: round(y * dpr) / dpr || 0
};
}
function mapToStyles(_ref2) {
var _Object$assign2;
var popper2 = _ref2.popper, popperRect = _ref2.popperRect, placement = _ref2.placement, variation = _ref2.variation, offsets = _ref2.offsets, position = _ref2.position, gpuAcceleration = _ref2.gpuAcceleration, adaptive = _ref2.adaptive, roundOffsets = _ref2.roundOffsets, isFixed = _ref2.isFixed;
var _offsets$x = offsets.x, x = _offsets$x === void 0 ? 0 : _offsets$x, _offsets$y = offsets.y, y = _offsets$y === void 0 ? 0 : _offsets$y;
var _ref3 = typeof roundOffsets === "function" ? roundOffsets({
x,
y
}) : {
x,
y
};
x = _ref3.x;
y = _ref3.y;
var hasX = offsets.hasOwnProperty("x");
var hasY = offsets.hasOwnProperty("y");
var sideX = left;
var sideY = top;
var win = window;
if (adaptive) {
var offsetParent = getOffsetParent(popper2);
var heightProp = "clientHeight";
var widthProp = "clientWidth";
if (offsetParent === getWindow(popper2)) {
offsetParent = getDocumentElement(popper2);
if (getComputedStyle(offsetParent).position !== "static" && position === "absolute") {
heightProp = "scrollHeight";
widthProp = "scrollWidth";
}
}
offsetParent = offsetParent;
if (placement === top || (placement === left || placement === right) && variation === end) {
sideY = bottom;
var offsetY = isFixed && offsetParent === win && win.visualViewport ? win.visualViewport.height : offsetParent[heightProp];
y -= offsetY - popperRect.height;
y *= gpuAcceleration ? 1 : -1;
}
if (placement === left || (placement === top || placement === bottom) && variation === end) {
sideX = right;
var offsetX = isFixed && offsetParent === win && win.visualViewport ? win.visualViewport.width : offsetParent[widthProp];
x -= offsetX - popperRect.width;
x *= gpuAcceleration ? 1 : -1;
}
}
var commonStyles = Object.assign({
position
}, adaptive && unsetSides);
var _ref4 = roundOffsets === true ? roundOffsetsByDPR({
x,
y
}) : {
x,
y
};
x = _ref4.x;
y = _ref4.y;
if (gpuAcceleration) {
var _Object$assign;
return Object.assign({}, commonStyles, (_Object$assign = {}, _Object$assign[sideY] = hasY ? "0" : "", _Object$assign[sideX] = hasX ? "0" : "", _Object$assign.transform = (win.devicePixelRatio || 1) <= 1 ? "translate(" + x + "px, " + y + "px)" : "translate3d(" + x + "px, " + y + "px, 0)", _Object$assign));
}
return Object.assign({}, commonStyles, (_Object$assign2 = {}, _Object$assign2[sideY] = hasY ? y + "px" : "", _Object$assign2[sideX] = hasX ? x + "px" : "", _Object$assign2.transform = "", _Object$assign2));
}
function computeStyles(_ref5) {
var state = _ref5.state, options = _ref5.options;
var _options$gpuAccelerat = options.gpuAcceleration, gpuAcceleration = _options$gpuAccelerat === void 0 ? true : _options$gpuAccelerat, _options$adaptive = options.adaptive, adaptive = _options$adaptive === void 0 ? true : _options$adaptive, _options$roundOffsets = options.roundOffsets, roundOffsets = _options$roundOffsets === void 0 ? true : _options$roundOffsets;
if (true) {
var transitionProperty = getComputedStyle(state.elements.popper).transitionProperty || "";
if (adaptive && ["transform", "top", "right", "bottom", "left"].some(function(property) {
return transitionProperty.indexOf(property) >= 0;
})) {
console.warn(["Popper: Detected CSS transitions on at least one of the following", 'CSS properties: "transform", "top", "right", "bottom", "left".', "\n\n", 'Disable the "computeStyles" modifier\'s `adaptive` option to allow', "for smooth transitions, or remove these properties from the CSS", "transition declaration on the popper element if only transitioning", "opacity or background-color for example.", "\n\n", "We recommend using the popper element as a wrapper around an inner", "element that can have any CSS property transitioned for animations."].join(" "));
}
}
var commonStyles = {
placement: getBasePlacement(state.placement),
variation: getVariation(state.placement),
popper: state.elements.popper,
popperRect: state.rects.popper,
gpuAcceleration,
isFixed: state.options.strategy === "fixed"
};
if (state.modifiersData.popperOffsets != null) {
state.styles.popper = Object.assign({}, state.styles.popper, mapToStyles(Object.assign({}, commonStyles, {
offsets: state.modifiersData.popperOffsets,
position: state.options.strategy,
adaptive,
roundOffsets
})));
}
if (state.modifiersData.arrow != null) {
state.styles.arrow = Object.assign({}, state.styles.arrow, mapToStyles(Object.assign({}, commonStyles, {
offsets: state.modifiersData.arrow,
position: "absolute",
adaptive: false,
roundOffsets
})));
}
state.attributes.popper = Object.assign({}, state.attributes.popper, {
"data-popper-placement": state.placement
});
}
var computeStyles_default = {
name: "computeStyles",
enabled: true,
phase: "beforeWrite",
fn: computeStyles,
data: {}
};
// node_modules/@popperjs/core/lib/modifiers/eventListeners.js
var passive = {
passive: true
};
function effect3(_ref) {
var state = _ref.state, instance = _ref.instance, options = _ref.options;
var _options$scroll = options.scroll, scroll = _options$scroll === void 0 ? true : _options$scroll, _options$resize = options.resize, resize = _options$resize === void 0 ? true : _options$resize;
var window2 = getWindow(state.elements.popper);
var scrollParents = [].concat(state.scrollParents.reference, state.scrollParents.popper);
if (scroll) {
scrollParents.forEach(function(scrollParent) {
scrollParent.addEventListener("scroll", instance.update, passive);
});
}
if (resize) {
window2.addEventListener("resize", instance.update, passive);
}
return function() {
if (scroll) {
scrollParents.forEach(function(scrollParent) {
scrollParent.removeEventListener("scroll", instance.update, passive);
});
}
if (resize) {
window2.removeEventListener("resize", instance.update, passive);
}
};
}
var eventListeners_default = {
name: "eventListeners",
enabled: true,
phase: "write",
fn: function fn() {
},
effect: effect3,
data: {}
};
// node_modules/@popperjs/core/lib/utils/getOppositePlacement.js
var hash = {
left: "right",
right: "left",
bottom: "top",
top: "bottom"
};
function getOppositePlacement(placement) {
return placement.replace(/left|right|bottom|top/g, function(matched) {
return hash[matched];
});
}
// node_modules/@popperjs/core/lib/utils/getOppositeVariationPlacement.js
var hash2 = {
start: "end",
end: "start"
};
function getOppositeVariationPlacement(placement) {
return placement.replace(/start|end/g, function(matched) {
return hash2[matched];
});
}
// node_modules/@popperjs/core/lib/dom-utils/getWindowScroll.js
function getWindowScroll(node) {
var win = getWindow(node);
var scrollLeft = win.pageXOffset;
var scrollTop = win.pageYOffset;
return {
scrollLeft,
scrollTop
};
}
// node_modules/@popperjs/core/lib/dom-utils/getWindowScrollBarX.js
function getWindowScrollBarX(element) {
return getBoundingClientRect(getDocumentElement(element)).left + getWindowScroll(element).scrollLeft;
}
// node_modules/@popperjs/core/lib/dom-utils/getViewportRect.js
function getViewportRect(element, strategy) {
var win = getWindow(element);
var html = getDocumentElement(element);
var visualViewport = win.visualViewport;
var width = html.clientWidth;
var height = html.clientHeight;
var x = 0;
var y = 0;
if (visualViewport) {
width = visualViewport.width;
height = visualViewport.height;
var layoutViewport = isLayoutViewport();
if (layoutViewport || !layoutViewport && strategy === "fixed") {
x = visualViewport.offsetLeft;
y = visualViewport.offsetTop;
}
}
return {
width,
height,
x: x + getWindowScrollBarX(element),
y
};
}
// node_modules/@popperjs/core/lib/dom-utils/getDocumentRect.js
function getDocumentRect(element) {
var _element$ownerDocumen;
var html = getDocumentElement(element);
var winScroll = getWindowScroll(element);
var body = (_element$ownerDocumen = element.ownerDocument) == null ? void 0 : _element$ownerDocumen.body;
var width = max(html.scrollWidth, html.clientWidth, body ? body.scrollWidth : 0, body ? body.clientWidth : 0);
var height = max(html.scrollHeight, html.clientHeight, body ? body.scrollHeight : 0, body ? body.clientHeight : 0);
var x = -winScroll.scrollLeft + getWindowScrollBarX(element);
var y = -winScroll.scrollTop;
if (getComputedStyle(body || html).direction === "rtl") {
x += max(html.clientWidth, body ? body.clientWidth : 0) - width;
}
return {
width,
height,
x,
y
};
}
// node_modules/@popperjs/core/lib/dom-utils/isScrollParent.js
function isScrollParent(element) {
var _getComputedStyle = getComputedStyle(element), overflow = _getComputedStyle.overflow, overflowX = _getComputedStyle.overflowX, overflowY = _getComputedStyle.overflowY;
return /auto|scroll|overlay|hidden/.test(overflow + overflowY + overflowX);
}
// node_modules/@popperjs/core/lib/dom-utils/getScrollParent.js
function getScrollParent(node) {
if (["html", "body", "#document"].indexOf(getNodeName(node)) >= 0) {
return node.ownerDocument.body;
}
if (isHTMLElement(node) && isScrollParent(node)) {
return node;
}
return getScrollParent(getParentNode(node));
}
// node_modules/@popperjs/core/lib/dom-utils/listScrollParents.js
function listScrollParents(element, list) {
var _element$ownerDocumen;
if (list === void 0) {
list = [];
}
var scrollParent = getScrollParent(element);
var isBody = scrollParent === ((_element$ownerDocumen = element.ownerDocument) == null ? void 0 : _element$ownerDocumen.body);
var win = getWindow(scrollParent);
var target = isBody ? [win].concat(win.visualViewport || [], isScrollParent(scrollParent) ? scrollParent : []) : scrollParent;
var updatedList = list.concat(target);
return isBody ? updatedList : updatedList.concat(listScrollParents(getParentNode(target)));
}
// node_modules/@popperjs/core/lib/utils/rectToClientRect.js
function rectToClientRect(rect) {
return Object.assign({}, rect, {
left: rect.x,
top: rect.y,
right: rect.x + rect.width,
bottom: rect.y + rect.height
});
}
// node_modules/@popperjs/core/lib/dom-utils/getClippingRect.js
function getInnerBoundingClientRect(element, strategy) {
var rect = getBoundingClientRect(element, false, strategy === "fixed");
rect.top = rect.top + element.clientTop;
rect.left = rect.left + element.clientLeft;
rect.bottom = rect.top + element.clientHeight;
rect.right = rect.left + element.clientWidth;
rect.width = element.clientWidth;
rect.height = element.clientHeight;
rect.x = rect.left;
rect.y = rect.top;
return rect;
}
function getClientRectFromMixedType(element, clippingParent, strategy) {
return clippingParent === viewport ? rectToClientRect(getViewportRect(element, strategy)) : isElement(clippingParent) ? getInnerBoundingClientRect(clippingParent, strategy) : rectToClientRect(getDocumentRect(getDocumentElement(element)));
}
function getClippingParents(element) {
var clippingParents2 = listScrollParents(getParentNode(element));
var canEscapeClipping = ["absolute", "fixed"].indexOf(getComputedStyle(element).position) >= 0;
var clipperElement = canEscapeClipping && isHTMLElement(element) ? getOffsetParent(element) : element;
if (!isElement(clipperElement)) {
return [];
}
return clippingParents2.filter(function(clippingParent) {
return isElement(clippingParent) && contains(clippingParent, clipperElement) && getNodeName(clippingParent) !== "body";
});
}
function getClippingRect(element, boundary, rootBoundary, strategy) {
var mainClippingParents = boundary === "clippingParents" ? getClippingParents(element) : [].concat(boundary);
var clippingParents2 = [].concat(mainClippingParents, [rootBoundary]);
var firstClippingParent = clippingParents2[0];
var clippingRect = clippingParents2.reduce(function(accRect, clippingParent) {
var rect = getClientRectFromMixedType(element, clippingParent, strategy);
accRect.top = max(rect.top, accRect.top);
accRect.right = min(rect.right, accRect.right);
accRect.bottom = min(rect.bottom, accRect.bottom);
accRect.left = max(rect.left, accRect.left);
return accRect;
}, getClientRectFromMixedType(element, firstClippingParent, strategy));
clippingRect.width = clippingRect.right - clippingRect.left;
clippingRect.height = clippingRect.bottom - clippingRect.top;
clippingRect.x = clippingRect.left;
clippingRect.y = clippingRect.top;
return clippingRect;
}
// node_modules/@popperjs/core/lib/utils/computeOffsets.js
function computeOffsets(_ref) {
var reference2 = _ref.reference, element = _ref.element, placement = _ref.placement;
var basePlacement = placement ? getBasePlacement(placement) : null;
var variation = placement ? getVariation(placement) : null;
var commonX = reference2.x + reference2.width / 2 - element.width / 2;
var commonY = reference2.y + reference2.height / 2 - element.height / 2;
var offsets;
switch (basePlacement) {
case top:
offsets = {
x: commonX,
y: reference2.y - element.height
};
break;
case bottom:
offsets = {
x: commonX,
y: reference2.y + reference2.height
};
break;
case right:
offsets = {
x: reference2.x + reference2.width,
y: commonY
};
break;
case left:
offsets = {
x: reference2.x - element.width,
y: commonY
};
break;
default:
offsets = {
x: reference2.x,
y: reference2.y
};
}
var mainAxis = basePlacement ? getMainAxisFromPlacement(basePlacement) : null;
if (mainAxis != null) {
var len = mainAxis === "y" ? "height" : "width";
switch (variation) {
case start:
offsets[mainAxis] = offsets[mainAxis] - (reference2[len] / 2 - element[len] / 2);
break;
case end:
offsets[mainAxis] = offsets[mainAxis] + (reference2[len] / 2 - element[len] / 2);
break;
default:
}
}
return offsets;
}
// node_modules/@popperjs/core/lib/utils/detectOverflow.js
function detectOverflow(state, options) {
if (options === void 0) {
options = {};
}
var _options = options, _options$placement = _options.placement, placement = _options$placement === void 0 ? state.placement : _options$placement, _options$strategy = _options.strategy, strategy = _options$strategy === void 0 ? state.strategy : _options$strategy, _options$boundary = _options.boundary, boundary = _options$boundary === void 0 ? clippingParents : _options$boundary, _options$rootBoundary = _options.rootBoundary, rootBoundary = _options$rootBoundary === void 0 ? viewport : _options$rootBoundary, _options$elementConte = _options.elementContext, elementContext = _options$elementConte === void 0 ? popper : _options$elementConte, _options$altBoundary = _options.altBoundary, altBoundary = _options$altBoundary === void 0 ? false : _options$altBoundary, _options$padding = _options.padding, padding = _options$padding === void 0 ? 0 : _options$padding;
var paddingObject = mergePaddingObject(typeof padding !== "number" ? padding : expandToHashMap(padding, basePlacements));
var altContext = elementContext === popper ? reference : popper;
var popperRect = state.rects.popper;
var element = state.elements[altBoundary ? altContext : elementContext];
var clippingClientRect = getClippingRect(isElement(element) ? element : element.contextElement || getDocumentElement(state.elements.popper), boundary, rootBoundary, strategy);
var referenceClientRect = getBoundingClientRect(state.elements.reference);
var popperOffsets2 = computeOffsets({
reference: referenceClientRect,
element: popperRect,
strategy: "absolute",
placement
});
var popperClientRect = rectToClientRect(Object.assign({}, popperRect, popperOffsets2));
var elementClientRect = elementContext === popper ? popperClientRect : referenceClientRect;
var overflowOffsets = {
top: clippingClientRect.top - elementClientRect.top + paddingObject.top,
bottom: elementClientRect.bottom - clippingClientRect.bottom + paddingObject.bottom,
left: clippingClientRect.left - elementClientRect.left + paddingObject.left,
right: elementClientRect.right - clippingClientRect.right + paddingObject.right
};
var offsetData = state.modifiersData.offset;
if (elementContext === popper && offsetData) {
var offset2 = offsetData[placement];
Object.keys(overflowOffsets).forEach(function(key) {
var multiply = [right, bottom].indexOf(key) >= 0 ? 1 : -1;
var axis = [top, bottom].indexOf(key) >= 0 ? "y" : "x";
overflowOffsets[key] += offset2[axis] * multiply;
});
}
return overflowOffsets;
}
// node_modules/@popperjs/core/lib/utils/computeAutoPlacement.js
function computeAutoPlacement(state, options) {
if (options === void 0) {
options = {};
}
var _options = options, placement = _options.placement, boundary = _options.boundary, rootBoundary = _options.rootBoundary, padding = _options.padding, flipVariations = _options.flipVariations, _options$allowedAutoP = _options.allowedAutoPlacements, allowedAutoPlacements = _options$allowedAutoP === void 0 ? placements : _options$allowedAutoP;
var variation = getVariation(placement);
var placements2 = variation ? flipVariations ? variationPlacements : variationPlacements.filter(function(placement2) {
return getVariation(placement2) === variation;
}) : basePlacements;
var allowedPlacements = placements2.filter(function(placement2) {
return allowedAutoPlacements.indexOf(placement2) >= 0;
});
if (allowedPlacements.length === 0) {
allowedPlacements = placements2;
if (true) {
console.error(["Popper: The `allowedAutoPlacements` option did not allow any", "placements. Ensure the `placement` option matches the variation", "of the allowed placements.", 'For example, "auto" cannot be used to allow "bottom-start".', 'Use "auto-start" instead.'].join(" "));
}
}
var overflows = allowedPlacements.reduce(function(acc, placement2) {
acc[placement2] = detectOverflow(state, {
placement: placement2,
boundary,
rootBoundary,
padding
})[getBasePlacement(placement2)];
return acc;
}, {});
return Object.keys(overflows).sort(function(a, b) {
return overflows[a] - overflows[b];
});
}
// node_modules/@popperjs/core/lib/modifiers/flip.js
function getExpandedFallbackPlacements(placement) {
if (getBasePlacement(placement) === auto) {
return [];
}
var oppositePlacement = getOppositePlacement(placement);
return [getOppositeVariationPlacement(placement), oppositePlacement, getOppositeVariationPlacement(oppositePlacement)];
}
function flip(_ref) {
var state = _ref.state, options = _ref.options, name = _ref.name;
if (state.modifiersData[name]._skip) {
return;
}
var _options$mainAxis = options.mainAxis, checkMainAxis = _options$mainAxis === void 0 ? true : _options$mainAxis, _options$altAxis = options.altAxis, checkAltAxis = _options$altAxis === void 0 ? true : _options$altAxis, specifiedFallbackPlacements = options.fallbackPlacements, padding = options.padding, boundary = options.boundary, rootBoundary = options.rootBoundary, altBoundary = options.altBoundary, _options$flipVariatio = options.flipVariations, flipVariations = _options$flipVariatio === void 0 ? true : _options$flipVariatio, allowedAutoPlacements = options.allowedAutoPlacements;
var preferredPlacement = state.options.placement;
var basePlacement = getBasePlacement(preferredPlacement);
var isBasePlacement = basePlacement === preferredPlacement;
var fallbackPlacements = specifiedFallbackPlacements || (isBasePlacement || !flipVariations ? [getOppositePlacement(preferredPlacement)] : getExpandedFallbackPlacements(preferredPlacement));
var placements2 = [preferredPlacement].concat(fallbackPlacements).reduce(function(acc, placement2) {
return acc.concat(getBasePlacement(placement2) === auto ? computeAutoPlacement(state, {
placement: placement2,
boundary,
rootBoundary,
padding,
flipVariations,
allowedAutoPlacements
}) : placement2);
}, []);
var referenceRect = state.rects.reference;
var popperRect = state.rects.popper;
var checksMap = new Map();
var makeFallbackChecks = true;
var firstFittingPlacement = placements2[0];
for (var i = 0; i < placements2.length; i++) {
var placement = placements2[i];
var _basePlacement = getBasePlacement(placement);
var isStartVariation = getVariation(placement) === start;
var isVertical = [top, bottom].indexOf(_basePlacement) >= 0;
var len = isVertical ? "width" : "height";
var overflow = detectOverflow(state, {
placement,
boundary,
rootBoundary,
altBoundary,
padding
});
var mainVariationSide = isVertical ? isStartVariation ? right : left : isStartVariation ? bottom : top;
if (referenceRect[len] > popperRect[len]) {
mainVariationSide = getOppositePlacement(mainVariationSide);
}
var altVariationSide = getOppositePlacement(mainVariationSide);
var checks = [];
if (checkMainAxis) {
checks.push(overflow[_basePlacement] <= 0);
}
if (checkAltAxis) {
checks.push(overflow[mainVariationSide] <= 0, overflow[altVariationSide] <= 0);
}
if (checks.every(function(check) {
return check;
})) {
firstFittingPlacement = placement;
makeFallbackChecks = false;
break;
}
checksMap.set(placement, checks);
}
if (makeFallbackChecks) {
var numberOfChecks = flipVariations ? 3 : 1;
var _loop = function _loop2(_i2) {
var fittingPlacement = placements2.find(function(placement2) {
var checks2 = checksMap.get(placement2);
if (checks2) {
return checks2.slice(0, _i2).every(function(check) {
return check;
});
}
});
if (fittingPlacement) {
firstFittingPlacement = fittingPlacement;
return "break";
}
};
for (var _i = numberOfChecks; _i > 0; _i--) {
var _ret = _loop(_i);
if (_ret === "break")
break;
}
}
if (state.placement !== firstFittingPlacement) {
state.modifiersData[name]._skip = true;
state.placement = firstFittingPlacement;
state.reset = true;
}
}
var flip_default = {
name: "flip",
enabled: true,
phase: "main",
fn: flip,
requiresIfExists: ["offset"],
data: {
_skip: false
}
};
// node_modules/@popperjs/core/lib/modifiers/hide.js
function getSideOffsets(overflow, rect, preventedOffsets) {
if (preventedOffsets === void 0) {
preventedOffsets = {
x: 0,
y: 0
};
}
return {
top: overflow.top - rect.height - preventedOffsets.y,
right: overflow.right - rect.width + preventedOffsets.x,
bottom: overflow.bottom - rect.height + preventedOffsets.y,
left: overflow.left - rect.width - preventedOffsets.x
};
}
function isAnySideFullyClipped(overflow) {
return [top, right, bottom, left].some(function(side) {
return overflow[side] >= 0;
});
}
function hide(_ref) {
var state = _ref.state, name = _ref.name;
var referenceRect = state.rects.reference;
var popperRect = state.rects.popper;
var preventedOffsets = state.modifiersData.preventOverflow;
var referenceOverflow = detectOverflow(state, {
elementContext: "reference"
});
var popperAltOverflow = detectOverflow(state, {
altBoundary: true
});
var referenceClippingOffsets = getSideOffsets(referenceOverflow, referenceRect);
var popperEscapeOffsets = getSideOffsets(popperAltOverflow, popperRect, preventedOffsets);
var isReferenceHidden = isAnySideFullyClipped(referenceClippingOffsets);
var hasPopperEscaped = isAnySideFullyClipped(popperEscapeOffsets);
state.modifiersData[name] = {
referenceClippingOffsets,
popperEscapeOffsets,
isReferenceHidden,
hasPopperEscaped
};
state.attributes.popper = Object.assign({}, state.attributes.popper, {
"data-popper-reference-hidden": isReferenceHidden,
"data-popper-escaped": hasPopperEscaped
});
}
var hide_default = {
name: "hide",
enabled: true,
phase: "main",
requiresIfExists: ["preventOverflow"],
fn: hide
};
// node_modules/@popperjs/core/lib/modifiers/offset.js
function distanceAndSkiddingToXY(placement, rects, offset2) {
var basePlacement = getBasePlacement(placement);
var invertDistance = [left, top].indexOf(basePlacement) >= 0 ? -1 : 1;
var _ref = typeof offset2 === "function" ? offset2(Object.assign({}, rects, {
placement
})) : offset2, skidding = _ref[0], distance = _ref[1];
skidding = skidding || 0;
distance = (distance || 0) * invertDistance;
return [left, right].indexOf(basePlacement) >= 0 ? {
x: distance,
y: skidding
} : {
x: skidding,
y: distance
};
}
function offset(_ref2) {
var state = _ref2.state, options = _ref2.options, name = _ref2.name;
var _options$offset = options.offset, offset2 = _options$offset === void 0 ? [0, 0] : _options$offset;
var data = placements.reduce(function(acc, placement) {
acc[placement] = distanceAndSkiddingToXY(placement, state.rects, offset2);
return acc;
}, {});
var _data$state$placement = data[state.placement], x = _data$state$placement.x, y = _data$state$placement.y;
if (state.modifiersData.popperOffsets != null) {
state.modifiersData.popperOffsets.x += x;
state.modifiersData.popperOffsets.y += y;
}
state.modifiersData[name] = data;
}
var offset_default = {
name: "offset",
enabled: true,
phase: "main",
requires: ["popperOffsets"],
fn: offset
};
// node_modules/@popperjs/core/lib/modifiers/popperOffsets.js
function popperOffsets(_ref) {
var state = _ref.state, name = _ref.name;
state.modifiersData[name] = computeOffsets({
reference: state.rects.reference,
element: state.rects.popper,
strategy: "absolute",
placement: state.placement
});
}
var popperOffsets_default = {
name: "popperOffsets",
enabled: true,
phase: "read",
fn: popperOffsets,
data: {}
};
// node_modules/@popperjs/core/lib/utils/getAltAxis.js
function getAltAxis(axis) {
return axis === "x" ? "y" : "x";
}
// node_modules/@popperjs/core/lib/modifiers/preventOverflow.js
function preventOverflow(_ref) {
var state = _ref.state, options = _ref.options, name = _ref.name;
var _options$mainAxis = options.mainAxis, checkMainAxis = _options$mainAxis === void 0 ? true : _options$mainAxis, _options$altAxis = options.altAxis, checkAltAxis = _options$altAxis === void 0 ? false : _options$altAxis, boundary = options.boundary, rootBoundary = options.rootBoundary, altBoundary = options.altBoundary, padding = options.padding, _options$tether = options.tether, tether = _options$tether === void 0 ? true : _options$tether, _options$tetherOffset = options.tetherOffset, tetherOffset = _options$tetherOffset === void 0 ? 0 : _options$tetherOffset;
var overflow = detectOverflow(state, {
boundary,
rootBoundary,
padding,
altBoundary
});
var basePlacement = getBasePlacement(state.placement);
var variation = getVariation(state.placement);
var isBasePlacement = !variation;
var mainAxis = getMainAxisFromPlacement(basePlacement);
var altAxis = getAltAxis(mainAxis);
var popperOffsets2 = state.modifiersData.popperOffsets;
var referenceRect = state.rects.reference;
var popperRect = state.rects.popper;
var tetherOffsetValue = typeof tetherOffset === "function" ? tetherOffset(Object.assign({}, state.rects, {
placement: state.placement
})) : tetherOffset;
var normalizedTetherOffsetValue = typeof tetherOffsetValue === "number" ? {
mainAxis: tetherOffsetValue,
altAxis: tetherOffsetValue
} : Object.assign({
mainAxis: 0,
altAxis: 0
}, tetherOffsetValue);
var offsetModifierState = state.modifiersData.offset ? state.modifiersData.offset[state.placement] : null;
var data = {
x: 0,
y: 0
};
if (!popperOffsets2) {
return;
}
if (checkMainAxis) {
var _offsetModifierState$;
var mainSide = mainAxis === "y" ? top : left;
var altSide = mainAxis === "y" ? bottom : right;
var len = mainAxis === "y" ? "height" : "width";
var offset2 = popperOffsets2[mainAxis];
var min2 = offset2 + overflow[mainSide];
var max2 = offset2 - overflow[altSide];
var additive = tether ? -popperRect[len] / 2 : 0;
var minLen = variation === start ? referenceRect[len] : popperRect[len];
var maxLen = variation === start ? -popperRect[len] : -referenceRect[len];
var arrowElement = state.elements.arrow;
var arrowRect = tether && arrowElement ? getLayoutRect(arrowElement) : {
width: 0,
height: 0
};
var arrowPaddingObject = state.modifiersData["arrow#persistent"] ? state.modifiersData["arrow#persistent"].padding : getFreshSideObject();
var arrowPaddingMin = arrowPaddingObject[mainSide];
var arrowPaddingMax = arrowPaddingObject[altSide];
var arrowLen = within(0, referenceRect[len], arrowRect[len]);
var minOffset = isBasePlacement ? referenceRect[len] / 2 - additive - arrowLen - arrowPaddingMin - normalizedTetherOffsetValue.mainAxis : minLen - arrowLen - arrowPaddingMin - normalizedTetherOffsetValue.mainAxis;
var maxOffset = isBasePlacement ? -referenceRect[len] / 2 + additive + arrowLen + arrowPaddingMax + normalizedTetherOffsetValue.mainAxis : maxLen + arrowLen + arrowPaddingMax + normalizedTetherOffsetValue.mainAxis;
var arrowOffsetParent = state.elements.arrow && getOffsetParent(state.elements.arrow);
var clientOffset = arrowOffsetParent ? mainAxis === "y" ? arrowOffsetParent.clientTop || 0 : arrowOffsetParent.clientLeft || 0 : 0;
var offsetModifierValue = (_offsetModifierState$ = offsetModifierState == null ? void 0 : offsetModifierState[mainAxis]) != null ? _offsetModifierState$ : 0;
var tetherMin = offset2 + minOffset - offsetModifierValue - clientOffset;
var tetherMax = offset2 + maxOffset - offsetModifierValue;
var preventedOffset = within(tether ? min(min2, tetherMin) : min2, offset2, tether ? max(max2, tetherMax) : max2);
popperOffsets2[mainAxis] = preventedOffset;
data[mainAxis] = preventedOffset - offset2;
}
if (checkAltAxis) {
var _offsetModifierState$2;
var _mainSide = mainAxis === "x" ? top : left;
var _altSide = mainAxis === "x" ? bottom : right;
var _offset = popperOffsets2[altAxis];
var _len = altAxis === "y" ? "height" : "width";
var _min = _offset + overflow[_mainSide];
var _max = _offset - overflow[_altSide];
var isOriginSide = [top, left].indexOf(basePlacement) !== -1;
var _offsetModifierValue = (_offsetModifierState$2 = offsetModifierState == null ? void 0 : offsetModifierState[altAxis]) != null ? _offsetModifierState$2 : 0;
var _tetherMin = isOriginSide ? _min : _offset - referenceRect[_len] - popperRect[_len] - _offsetModifierValue + normalizedTetherOffsetValue.altAxis;
var _tetherMax = isOriginSide ? _offset + referenceRect[_len] + popperRect[_len] - _offsetModifierValue - normalizedTetherOffsetValue.altAxis : _max;
var _preventedOffset = tether && isOriginSide ? withinMaxClamp(_tetherMin, _offset, _tetherMax) : within(tether ? _tetherMin : _min, _offset, tether ? _tetherMax : _max);
popperOffsets2[altAxis] = _preventedOffset;
data[altAxis] = _preventedOffset - _offset;
}
state.modifiersData[name] = data;
}
var preventOverflow_default = {
name: "preventOverflow",
enabled: true,
phase: "main",
fn: preventOverflow,
requiresIfExists: ["offset"]
};
// node_modules/@popperjs/core/lib/dom-utils/getHTMLElementScroll.js
function getHTMLElementScroll(element) {
return {
scrollLeft: element.scrollLeft,
scrollTop: element.scrollTop
};
}
// node_modules/@popperjs/core/lib/dom-utils/getNodeScroll.js
function getNodeScroll(node) {
if (node === getWindow(node) || !isHTMLElement(node)) {
return getWindowScroll(node);
} else {
return getHTMLElementScroll(node);
}
}
// node_modules/@popperjs/core/lib/dom-utils/getCompositeRect.js
function isElementScaled(element) {
var rect = element.getBoundingClientRect();
var scaleX = round(rect.width) / element.offsetWidth || 1;
var scaleY = round(rect.height) / element.offsetHeight || 1;
return scaleX !== 1 || scaleY !== 1;
}
function getCompositeRect(elementOrVirtualElement, offsetParent, isFixed) {
if (isFixed === void 0) {
isFixed = false;
}
var isOffsetParentAnElement = isHTMLElement(offsetParent);
var offsetParentIsScaled = isHTMLElement(offsetParent) && isElementScaled(offsetParent);
var documentElement = getDocumentElement(offsetParent);
var rect = getBoundingClientRect(elementOrVirtualElement, offsetParentIsScaled, isFixed);
var scroll = {
scrollLeft: 0,
scrollTop: 0
};
var offsets = {
x: 0,
y: 0
};
if (isOffsetParentAnElement || !isOffsetParentAnElement && !isFixed) {
if (getNodeName(offsetParent) !== "body" || isScrollParent(documentElement)) {
scroll = getNodeScroll(offsetParent);
}
if (isHTMLElement(offsetParent)) {
offsets = getBoundingClientRect(offsetParent, true);
offsets.x += offsetParent.clientLeft;
offsets.y += offsetParent.clientTop;
} else if (documentElement) {
offsets.x = getWindowScrollBarX(documentElement);
}
}
return {
x: rect.left + scroll.scrollLeft - offsets.x,
y: rect.top + scroll.scrollTop - offsets.y,
width: rect.width,
height: rect.height
};
}
// node_modules/@popperjs/core/lib/utils/orderModifiers.js
function order(modifiers) {
var map = new Map();
var visited = new Set();
var result = [];
modifiers.forEach(function(modifier) {
map.set(modifier.name, modifier);
});
function sort(modifier) {
visited.add(modifier.name);
var requires = [].concat(modifier.requires || [], modifier.requiresIfExists || []);
requires.forEach(function(dep) {
if (!visited.has(dep)) {
var depModifier = map.get(dep);
if (depModifier) {
sort(depModifier);
}
}
});
result.push(modifier);
}
modifiers.forEach(function(modifier) {
if (!visited.has(modifier.name)) {
sort(modifier);
}
});
return result;
}
function orderModifiers(modifiers) {
var orderedModifiers = order(modifiers);
return modifierPhases.reduce(function(acc, phase) {
return acc.concat(orderedModifiers.filter(function(modifier) {
return modifier.phase === phase;
}));
}, []);
}
// node_modules/@popperjs/core/lib/utils/debounce.js
function debounce(fn2) {
var pending;
return function() {
if (!pending) {
pending = new Promise(function(resolve) {
Promise.resolve().then(function() {
pending = void 0;
resolve(fn2());
});
});
}
return pending;
};
}
// node_modules/@popperjs/core/lib/utils/format.js
function format(str) {
for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
args[_key - 1] = arguments[_key];
}
return [].concat(args).reduce(function(p, c) {
return p.replace(/%s/, c);
}, str);
}
// node_modules/@popperjs/core/lib/utils/validateModifiers.js
var INVALID_MODIFIER_ERROR = 'Popper: modifier "%s" provided an invalid %s property, expected %s but got %s';
var MISSING_DEPENDENCY_ERROR = 'Popper: modifier "%s" requires "%s", but "%s" modifier is not available';
var VALID_PROPERTIES = ["name", "enabled", "phase", "fn", "effect", "requires", "options"];
function validateModifiers(modifiers) {
modifiers.forEach(function(modifier) {
[].concat(Object.keys(modifier), VALID_PROPERTIES).filter(function(value, index, self) {
return self.indexOf(value) === index;
}).forEach(function(key) {
switch (key) {
case "name":
if (typeof modifier.name !== "string") {
console.error(format(INVALID_MODIFIER_ERROR, String(modifier.name), '"name"', '"string"', '"' + String(modifier.name) + '"'));
}
break;
case "enabled":
if (typeof modifier.enabled !== "boolean") {
console.error(format(INVALID_MODIFIER_ERROR, modifier.name, '"enabled"', '"boolean"', '"' + String(modifier.enabled) + '"'));
}
break;
case "phase":
if (modifierPhases.indexOf(modifier.phase) < 0) {
console.error(format(INVALID_MODIFIER_ERROR, modifier.name, '"phase"', "either " + modifierPhases.join(", "), '"' + String(modifier.phase) + '"'));
}
break;
case "fn":
if (typeof modifier.fn !== "function") {
console.error(format(INVALID_MODIFIER_ERROR, modifier.name, '"fn"', '"function"', '"' + String(modifier.fn) + '"'));
}
break;
case "effect":
if (modifier.effect != null && typeof modifier.effect !== "function") {
console.error(format(INVALID_MODIFIER_ERROR, modifier.name, '"effect"', '"function"', '"' + String(modifier.fn) + '"'));
}
break;
case "requires":
if (modifier.requires != null && !Array.isArray(modifier.requires)) {
console.error(format(INVALID_MODIFIER_ERROR, modifier.name, '"requires"', '"array"', '"' + String(modifier.requires) + '"'));
}
break;
case "requiresIfExists":
if (!Array.isArray(modifier.requiresIfExists)) {
console.error(format(INVALID_MODIFIER_ERROR, modifier.name, '"requiresIfExists"', '"array"', '"' + String(modifier.requiresIfExists) + '"'));
}
break;
case "options":
case "data":
break;
default:
console.error('PopperJS: an invalid property has been provided to the "' + modifier.name + '" modifier, valid properties are ' + VALID_PROPERTIES.map(function(s) {
return '"' + s + '"';
}).join(", ") + '; but "' + key + '" was provided.');
}
modifier.requires && modifier.requires.forEach(function(requirement) {
if (modifiers.find(function(mod) {
return mod.name === requirement;
}) == null) {
console.error(format(MISSING_DEPENDENCY_ERROR, String(modifier.name), requirement, requirement));
}
});
});
});
}
// node_modules/@popperjs/core/lib/utils/uniqueBy.js
function uniqueBy(arr, fn2) {
var identifiers = new Set();
return arr.filter(function(item) {
var identifier = fn2(item);
if (!identifiers.has(identifier)) {
identifiers.add(identifier);
return true;
}
});
}
// node_modules/@popperjs/core/lib/utils/mergeByName.js
function mergeByName(modifiers) {
var merged = modifiers.reduce(function(merged2, current) {
var existing = merged2[current.name];
merged2[current.name] = existing ? Object.assign({}, existing, current, {
options: Object.assign({}, existing.options, current.options),
data: Object.assign({}, existing.data, current.data)
}) : current;
return merged2;
}, {});
return Object.keys(merged).map(function(key) {
return merged[key];
});
}
// node_modules/@popperjs/core/lib/createPopper.js
var INVALID_ELEMENT_ERROR = "Popper: Invalid reference or popper argument provided. They must be either a DOM element or virtual element.";
var INFINITE_LOOP_ERROR = "Popper: An infinite loop in the modifiers cycle has been detected! The cycle has been interrupted to prevent a browser crash.";
var DEFAULT_OPTIONS = {
placement: "bottom",
modifiers: [],
strategy: "absolute"
};
function areValidElements() {
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
return !args.some(function(element) {
return !(element && typeof element.getBoundingClientRect === "function");
});
}
function popperGenerator(generatorOptions) {
if (generatorOptions === void 0) {
generatorOptions = {};
}
var _generatorOptions = generatorOptions, _generatorOptions$def = _generatorOptions.defaultModifiers, defaultModifiers2 = _generatorOptions$def === void 0 ? [] : _generatorOptions$def, _generatorOptions$def2 = _generatorOptions.defaultOptions, defaultOptions = _generatorOptions$def2 === void 0 ? DEFAULT_OPTIONS : _generatorOptions$def2;
return function createPopper2(reference2, popper2, options) {
if (options === void 0) {
options = defaultOptions;
}
var state = {
placement: "bottom",
orderedModifiers: [],
options: Object.assign({}, DEFAULT_OPTIONS, defaultOptions),
modifiersData: {},
elements: {
reference: reference2,
popper: popper2
},
attributes: {},
styles: {}
};
var effectCleanupFns = [];
var isDestroyed = false;
var instance = {
state,
setOptions: function setOptions(setOptionsAction) {
var options2 = typeof setOptionsAction === "function" ? setOptionsAction(state.options) : setOptionsAction;
cleanupModifierEffects();
state.options = Object.assign({}, defaultOptions, state.options, options2);
state.scrollParents = {
reference: isElement(reference2) ? listScrollParents(reference2) : reference2.contextElement ? listScrollParents(reference2.contextElement) : [],
popper: listScrollParents(popper2)
};
var orderedModifiers = orderModifiers(mergeByName([].concat(defaultModifiers2, state.options.modifiers)));
state.orderedModifiers = orderedModifiers.filter(function(m) {
return m.enabled;
});
if (true) {
var modifiers = uniqueBy([].concat(orderedModifiers, state.options.modifiers), function(_ref) {
var name = _ref.name;
return name;
});
validateModifiers(modifiers);
if (getBasePlacement(state.options.placement) === auto) {
var flipModifier = state.orderedModifiers.find(function(_ref2) {
var name = _ref2.name;
return name === "flip";
});
if (!flipModifier) {
console.error(['Popper: "auto" placements require the "flip" modifier be', "present and enabled to work."].join(" "));
}
}
var _getComputedStyle = getComputedStyle(popper2), marginTop = _getComputedStyle.marginTop, marginRight = _getComputedStyle.marginRight, marginBottom = _getComputedStyle.marginBottom, marginLeft = _getComputedStyle.marginLeft;
if ([marginTop, marginRight, marginBottom, marginLeft].some(function(margin) {
return parseFloat(margin);
})) {
console.warn(['Popper: CSS "margin" styles cannot be used to apply padding', "between the popper and its reference element or boundary.", "To replicate margin, use the `offset` modifier, as well as", "the `padding` option in the `preventOverflow` and `flip`", "modifiers."].join(" "));
}
}
runModifierEffects();
return instance.update();
},
forceUpdate: function forceUpdate() {
if (isDestroyed) {
return;
}
var _state$elements = state.elements, reference3 = _state$elements.reference, popper3 = _state$elements.popper;
if (!areValidElements(reference3, popper3)) {
if (true) {
console.error(INVALID_ELEMENT_ERROR);
}
return;
}
state.rects = {
reference: getCompositeRect(reference3, getOffsetParent(popper3), state.options.strategy === "fixed"),
popper: getLayoutRect(popper3)
};
state.reset = false;
state.placement = state.options.placement;
state.orderedModifiers.forEach(function(modifier) {
return state.modifiersData[modifier.name] = Object.assign({}, modifier.data);
});
var __debug_loops__ = 0;
for (var index = 0; index < state.orderedModifiers.length; index++) {
if (true) {
__debug_loops__ += 1;
if (__debug_loops__ > 100) {
console.error(INFINITE_LOOP_ERROR);
break;
}
}
if (state.reset === true) {
state.reset = false;
index = -1;
continue;
}
var _state$orderedModifie = state.orderedModifiers[index], fn2 = _state$orderedModifie.fn, _state$orderedModifie2 = _state$orderedModifie.options, _options = _state$orderedModifie2 === void 0 ? {} : _state$orderedModifie2, name = _state$orderedModifie.name;
if (typeof fn2 === "function") {
state = fn2({
state,
options: _options,
name,
instance
}) || state;
}
}
},
update: debounce(function() {
return new Promise(function(resolve) {
instance.forceUpdate();
resolve(state);
});
}),
destroy: function destroy() {
cleanupModifierEffects();
isDestroyed = true;
}
};
if (!areValidElements(reference2, popper2)) {
if (true) {
console.error(INVALID_ELEMENT_ERROR);
}
return instance;
}
instance.setOptions(options).then(function(state2) {
if (!isDestroyed && options.onFirstUpdate) {
options.onFirstUpdate(state2);
}
});
function runModifierEffects() {
state.orderedModifiers.forEach(function(_ref3) {
var name = _ref3.name, _ref3$options = _ref3.options, options2 = _ref3$options === void 0 ? {} : _ref3$options, effect4 = _ref3.effect;
if (typeof effect4 === "function") {
var cleanupFn = effect4({
state,
name,
instance,
options: options2
});
var noopFn = function noopFn2() {
};
effectCleanupFns.push(cleanupFn || noopFn);
}
});
}
function cleanupModifierEffects() {
effectCleanupFns.forEach(function(fn2) {
return fn2();
});
effectCleanupFns = [];
}
return instance;
};
}
// node_modules/@popperjs/core/lib/popper.js
var defaultModifiers = [eventListeners_default, popperOffsets_default, computeStyles_default, applyStyles_default, offset_default, flip_default, preventOverflow_default, arrow_default, hide_default];
var createPopper = /* @__PURE__ */ popperGenerator({
defaultModifiers
});
// src/settings/suggest.ts
var wrapAround = (value, size) => {
return (value % size + size) % size;
};
var Suggest = class {
constructor(owner, containerEl, scope) {
this.owner = owner;
this.containerEl = containerEl;
containerEl.on("click", ".suggestion-item", this.onSuggestionClick.bind(this));
containerEl.on("mousemove", ".suggestion-item", this.onSuggestionMouseover.bind(this));
scope.register([], "ArrowUp", (event) => {
if (!event.isComposing) {
this.setSelectedItem(this.selectedItem - 1, true);
return false;
}
});
scope.register([], "ArrowDown", (event) => {
if (!event.isComposing) {
this.setSelectedItem(this.selectedItem + 1, true);
return false;
}
});
scope.register([], "Enter", (event) => {
if (!event.isComposing) {
this.useSelectedItem(event);
return false;
}
});
}
onSuggestionClick(event, el) {
event.preventDefault();
const item = this.suggestions.indexOf(el);
this.setSelectedItem(item, false);
this.useSelectedItem(event);
}
onSuggestionMouseover(_event, el) {
const item = this.suggestions.indexOf(el);
this.setSelectedItem(item, false);
}
setSuggestions(values) {
this.containerEl.empty();
const suggestionEls = [];
values.forEach((value) => {
const suggestionEl = this.containerEl.createDiv("suggestion-item");
this.owner.renderSuggestion(value, suggestionEl);
suggestionEls.push(suggestionEl);
});
this.values = values;
this.suggestions = suggestionEls;
this.setSelectedItem(0, false);
}
useSelectedItem(event) {
const currentValue = this.values[this.selectedItem];
if (currentValue) {
this.owner.selectSuggestion(currentValue, event);
}
}
setSelectedItem(selectedIndex, scrollIntoView) {
const normalizedIndex = wrapAround(selectedIndex, this.suggestions.length);
const prevSelectedSuggestion = this.suggestions[this.selectedItem];
const selectedSuggestion = this.suggestions[normalizedIndex];
prevSelectedSuggestion == null ? void 0 : prevSelectedSuggestion.removeClass("is-selected");
selectedSuggestion == null ? void 0 : selectedSuggestion.addClass("is-selected");
this.selectedItem = normalizedIndex;
if (scrollIntoView) {
selectedSuggestion.scrollIntoView(false);
}
}
};
var TextInputSuggest = class {
constructor(app2, inputEl) {
this.app = app2;
this.inputEl = inputEl;
this.scope = new import_obsidian.Scope();
this.suggestEl = createDiv("suggestion-container");
const suggestion = this.suggestEl.createDiv("suggestion");
this.suggest = new Suggest(this, suggestion, this.scope);
this.scope.register([], "Escape", this.close.bind(this));
this.inputEl.addEventListener("input", this.onInputChanged.bind(this));
this.inputEl.addEventListener("focus", this.onInputChanged.bind(this));
this.inputEl.addEventListener("blur", this.close.bind(this));
this.suggestEl.on("mousedown", ".suggestion-container", (event) => {
event.preventDefault();
});
}
onInputChanged() {
const inputStr = this.inputEl.value;
const suggestions = this.getSuggestions(inputStr);
if (!suggestions) {
this.close();
return;
}
if (suggestions.length > 0) {
this.suggest.setSuggestions(suggestions);
this.open(this.app.dom.appContainerEl, this.inputEl);
} else {
this.close();
}
}
open(container, inputEl) {
this.app.keymap.pushScope(this.scope);
container.appendChild(this.suggestEl);
this.popper = createPopper(inputEl, this.suggestEl, {
placement: "bottom-start"
});
}
close() {
this.app.keymap.popScope(this.scope);
this.suggest.setSuggestions([]);
if (this.popper)
this.popper.destroy();
this.suggestEl.detach();
}
};
// src/settings/FolderSuggester.ts
var FolderSuggest = class extends TextInputSuggest {
getSuggestions(inputStr) {
const abstractFiles = this.app.vault.getAllLoadedFiles();
const folders = [];
const lowerCaseInputStr = inputStr.toLowerCase();
abstractFiles.forEach((folder) => {
if (folder instanceof import_obsidian2.TFolder) {
const lowerCaseFolderPath = folder.path.toLowerCase();
const queryCouldBeForThisFolder = () => lowerCaseFolderPath.contains(lowerCaseInputStr);
const queryIsAlsoForThisFolder = () => lowerCaseInputStr.endsWith("/") && `${lowerCaseFolderPath}/` === lowerCaseInputStr;
if (queryCouldBeForThisFolder() || queryIsAlsoForThisFolder()) {
folders.push(folder);
}
}
});
return folders.sort((f1, f2) => f1.path.localeCompare(f2.path));
}
renderSuggestion(folder, el) {
const folderPath = folder.path;
const pathToShow = this.addFinalFolderDelimiterToFolderNameIfNecessary(folderPath);
el.setText(pathToShow);
}
addFinalFolderDelimiterToFolderNameIfNecessary(folderPath) {
return folderPath.endsWith("/") ? folderPath : `${folderPath}/`;
}
selectSuggestion(folder) {
const folderPath = folder.path;
const pathToUse = this.addFinalFolderDelimiterToFolderNameIfNecessary(folderPath);
this.inputEl.value = pathToUse;
this.inputEl.trigger("input");
this.close();
}
};
// src/settings/FileSuggester.ts
var FileSuggester = class extends TextInputSuggest {
constructor(app2, inputEl, rootFolderPath, fileSystem) {
super(app2, inputEl);
this.fileSystem = fileSystem;
this.rootFolderPath = rootFolderPath != null ? rootFolderPath : "/";
}
getSuggestions(inputStr) {
const files = this.fileSystem.getAllFileDescendantsOf(this.rootFolderPath);
const lowerCaseInputStr = inputStr.toLowerCase();
const suggestedFiles = [];
for (const file of files) {
const lowerCasePath = file.path.toLowerCase();
const queryCouldBeForThisFile = () => lowerCasePath.contains(lowerCaseInputStr);
if (queryCouldBeForThisFile()) {
suggestedFiles.push(file);
}
}
return suggestedFiles.sort((f1, f2) => f1.path.localeCompare(f2.path));
}
renderSuggestion(file, el) {
el.setText(file.path);
}
selectSuggestion(file) {
this.inputEl.value = file.path;
this.inputEl.trigger("input");
this.close();
}
};
// src/settings/SettingTab.ts
var SettingTab = class extends import_obsidian3.PluginSettingTab {
constructor(app2, plugin, configStore, fileSystem) {
super(app2, plugin);
this.problematicSymbols = ["\\", "`", "*", "_", "{", "}", "[", "]", "<", ">", "(", ")", "#", "+", "-", ".", "!", "|"];
this.plugin = plugin;
this.configStore = configStore;
this.fileSystem = fileSystem;
}
display() {
const { containerEl } = this;
containerEl.empty();
this.addSuggestionTriggerSetting(containerEl);
this.addSuggestNonExistingNotesSetting(containerEl);
this.addRelativePathsSetting(containerEl);
this.addFolderSearchTriggerSetting(containerEl);
this.addHeaderAsAliasTriggerSetting(containerEl);
if (this.configStore.templaterIsEnabled) {
this.addTemplaterTriggerSetting(containerEl);
this.addDefaultTemplaterTemplateSetting(containerEl);
}
if (this.configStore.quickAddIsEnabled) {
this.addQuickAddTriggerSetting(containerEl);
this.addDefaultQuickAddTemplateSetting(containerEl);
}
this.addRelativeTopFolderSetting(containerEl);
this.addEnabledFoldersSetting(containerEl);
}
addSuggestionTriggerSetting(containerEl) {
const trigger = new import_obsidian3.Setting(containerEl).setName("Trigger for link insertion").setDesc("The text string that will trigger link selection.").setTooltip('The string can contain multiple symbols such as @@ Avoid using characters / strings you often use while writing or that might be used by Obsidian or by other plugins to trigger actions. Some examples of strings to avoid: "[", "|", "#"');
trigger.addText((component) => component.setValue(this.plugin.settings.triggerSymbol).onChange((value) => __async(this, null, function* () {
this.removeValidationWarning(component, trigger);
this.warnIfTriggerIsProblematic(value, trigger, component);
this.plugin.settings.triggerSymbol = value;
yield this.plugin.saveSettings();
})));
}
addHeaderAsAliasTriggerSetting(containerEl) {
const trigger = new import_obsidian3.Setting(containerEl).setName("Trigger for using header as alias").setDesc("The text string that will trigger using a header as alias for the inserted link.").setTooltip("The string can contain only a single symbol such as ! ");
trigger.addText((component) => component.setValue(this.plugin.settings.triggerHeaderAsAliasSymbol).onChange((value) => __async(this, null, function* () {
this.plugin.settings.triggerHeaderAsAliasSymbol = value;
yield this.plugin.saveSettings();
})));
}
moveFolderPath(pathCollection, fromIndex, toIndex) {
if (toIndex < 0 || toIndex > pathCollection.length - 1) {
return;
}
const thisPath = pathCollection[fromIndex];
const otherPath = pathCollection[toIndex];
pathCollection[toIndex] = thisPath;
pathCollection[fromIndex] = otherPath;
}
addRelativeTopFolderSetting(containerEl) {
const folderSelectionSettingConfig = {
headerText: "Relative top folders",
descriptionContent: {
intro: [
"Add folder names or paths to folders here if you want to filter suggestions when inserting new links. ",
"The filtering is activated when inserting a link in a note that has any of the specified folders in its folder tree. ",
"Only suggestions for notes that also have the same folder in their folder tree are shown."
],
example: [
'If you are inserting a link in "folder1/folder2/note.md" and you have configured "folder1" as a relative top folder, then you will only get suggestions for other notes descending from folder 1.'
],
outro: [
"The folder names are checked in prioritized order. ",
'If both "folder1/folder2" and "folder1" are defined as relative top folders, ',
'then "folder1/folder2" is used as the relative top folder if the path to the note is "folder1/folder2/note". ',
'If the path to the note is "folder1/my note", then "folder1" is used as the top folder.'
]
},
enablePrioritization: true,
descriptionForAddNewButton: "Add new relative top folder",
pathCollection: this.plugin.settings.relativeTopFolders
};
this.addSettingForSelectingFolders(containerEl, folderSelectionSettingConfig);
}
addEnabledFoldersSetting(containerEl) {
const folderSelectionSettingConfig = {
headerText: "Enabled folders",
descriptionContent: {
intro: [
"Add paths to folders here if you only want the plugin to be enabled in specific folders. ",
"The plugin will only be active in notes that are descendants of the folders given here. ",
"If you leave this empty, the plugin will be active in all folders."
],
example: [
'If you use the link insertion trigger symbol in "folder1/folder2/note.md" and you have configured "folder1" as an enabled folder then suggestions for links will be shown. ',
"However, if you have not configured folder1 as an enabled folder then the trigger symbol is handled as normal text and no suggestions are shown."
],
outro: [
"If you only want to see suggestions for notes in enabled folders, then you should also add the folders you want to be enabled as relative top folders."
]
},
enablePrioritization: false,
descriptionForAddNewButton: "Add new enabled folder",
pathCollection: this.plugin.settings.enabledFolders
};
this.addSettingForSelectingFolders(containerEl, folderSelectionSettingConfig);
}
addSettingForSelectingFolders(containerEl, folderSettingConfig) {
containerEl.createEl("h2", { text: folderSettingConfig.headerText });
const description = document.createDocumentFragment();
description.append(...folderSettingConfig.descriptionContent.intro, description.createEl("br"), description.createEl("br"), description.createEl("strong", { text: "Example " }), description.createEl("br"), ...folderSettingConfig.descriptionContent.example, description.createEl("br"), description.createEl("br"), ...folderSettingConfig.descriptionContent.outro);
new import_obsidian3.Setting(containerEl).setDesc(description);
new import_obsidian3.Setting(containerEl).setName("Add New").setDesc(folderSettingConfig.descriptionForAddNewButton).addButton((button) => {
button.setButtonText("+").setCta().onClick(() => __async(this, null, function* () {
folderSettingConfig.pathCollection.push(new ObsidianFolderPath(""));
yield this.plugin.saveSettings();
this.display();
}));
});
folderSettingConfig.pathCollection.forEach((folderPath, index) => {
let searchComponent;
const setting = new import_obsidian3.Setting(containerEl).addSearch((cb) => {
searchComponent = cb;
cb.setPlaceholder("Folder name or path").setValue(folderPath.VaultPath).onChange((newValue) => __async(this, null, function* () {
folderSettingConfig.pathCollection[index] = new ObsidianFolderPath(newValue);
yield this.plugin.saveSettings();
}));
}).addExtraButton((cb) => cb.setIcon("search").setTooltip("Search for specific folder").onClick(() => {
new FolderSuggest(this.app, searchComponent.inputEl);
searchComponent.inputEl.select();
})).addExtraButton((cb) => cb.setIcon("cross").setTooltip("Delete").onClick(() => __async(this, null, function* () {
folderSettingConfig.pathCollection.splice(index, 1);
yield this.plugin.saveSettings();
this.display();
})));
if (folderSettingConfig.enablePrioritization) {
setting.addExtraButton((cb) => cb.setIcon("down-chevron-glyph").setTooltip("Decrease priority").onClick(() => __async(this, null, function* () {
this.moveFolderPath(folderSettingConfig.pathCollection, index, index + 1);
yield this.plugin.saveSettings();
this.display();
}))).addExtraButton((cb) => cb.setIcon("up-chevron-glyph").setTooltip("Increase priority").onClick(() => __async(this, null, function* () {
this.moveFolderPath(folderSettingConfig.pathCollection, index, index - 1);
yield this.plugin.saveSettings();
this.display();
})));
}
});
}
addSuggestNonExistingNotesSetting(containerEl) {
new import_obsidian3.Setting(containerEl).setName("Suggest existing links to notes that do not exist").setDesc("Set this to false if you do not want to get suggestions for existing links to notes that do not exist.").addToggle((component) => component.setValue(this.plugin.settings.suggestLinksToNonExistingNotes).onChange((value) => __async(this, null, function* () {
this.plugin.settings.suggestLinksToNonExistingNotes = value;
yield this.plugin.saveSettings();
})));
}
addRelativePathsSetting(containerEl) {
new import_obsidian3.Setting(containerEl).setName("Enable relative paths").setDesc("Set this to true if you want an easy way to link to notes in the same folder as the active note or in the parent folder. Use './' to link to a note in the same folder as the active note. Use '../' to link to a note in the parent folder of the active note's folder.").addToggle((component) => component.setValue(this.plugin.settings.enableRelativePaths).onChange((value) => __async(this, null, function* () {
this.plugin.settings.enableRelativePaths = value;
yield this.plugin.saveSettings();
})));
}
addTemplaterTriggerSetting(containerEl) {
new import_obsidian3.Setting(containerEl).setName("Trigger for executing Templater templates").setDesc("The text string that will trigger execution of a Templater template. Leave empty if you don't need the ability to trigger Templater templates").addText((component) => component.setValue(this.plugin.settings.templateTriggerSymbol).onChange((value) => __async(this, null, function* () {
this.plugin.settings.templateTriggerSymbol = value;
yield this.plugin.saveSettings();
})));
}
addDefaultTemplaterTemplateSetting(containerEl) {
let searchComponent;
new import_obsidian3.Setting(containerEl).setName("Default Templater template").setDesc("This template will be the first in the list of templates to select from when triggering Templater template execution").addSearch((cb) => {
searchComponent = cb;
new FileSuggester(this.app, searchComponent.inputEl, this.configStore.getTemplaterTemplatesPath(), this.fileSystem);
cb.setPlaceholder("Default Templater template").setValue(this.plugin.settings.defaultTemplaterTemplate).onChange((newValue) => __async(this, null, function* () {
this.plugin.settings.defaultTemplaterTemplate = newValue;
yield this.plugin.saveSettings();
}));
});
}
addDefaultQuickAddTemplateSetting(containerEl) {
let searchComponent;
new import_obsidian3.Setting(containerEl).setName("Default QuickAdd template").setDesc("This template will be the first in the list of templates to select from when triggering QuickAdd template execution").addSearch((cb) => {
searchComponent = cb;
new FileSuggester(this.app, searchComponent.inputEl, this.configStore.getQuickAddTemplatesPath(), this.fileSystem);
cb.setPlaceholder("Default QuickAdd template").setValue(this.plugin.settings.defaultQuickAddTemplate).onChange((newValue) => __async(this, null, function* () {
this.plugin.settings.defaultQuickAddTemplate = newValue;
yield this.plugin.saveSettings();
}));
});
}
addQuickAddTriggerSetting(containerEl) {
new import_obsidian3.Setting(containerEl).setName("Trigger for executing QuickAdd templates").setDesc("The text string that will trigger execution of a QuickAdd template. Leave empty if you don't need the ability to trigger QuickAdd templates").addText((component) => component.setValue(this.plugin.settings.quickAddTriggerSymbol).onChange((value) => __async(this, null, function* () {
this.plugin.settings.quickAddTriggerSymbol = value;
yield this.plugin.saveSettings();
})));
}
addFolderSearchTriggerSetting(containerEl) {
var _a;
const description = document.createDocumentFragment();
description.append("Set this to true if you want to include folders in the suggestions shown.", description.createEl("br"), "You cannot create a link to a folder, but it makes it easier to create a new note or link to an existing note that is deep in your folder structure.", description.createEl("br"), "Extra options are available to control when the folder suggestions are shown.");
new import_obsidian3.Setting(containerEl).setName("Include folders in suggestions").setDesc(description).addToggle((toggle) => toggle.setValue(this.plugin.settings.includeFoldersInSuggestions).onChange((value) => __async(this, null, function* () {
this.plugin.settings.includeFoldersInSuggestions = value;
yield this.plugin.saveSettings();
this.display();
})));
if (this.plugin.settings.includeFoldersInSuggestions) {
const folderSuggestionSettings = (_a = this.plugin.settings.folderSuggestionSettings) != null ? _a : { folderSuggestionMode: FolderSuggestionMode.Always, folderSuggestionTrigger: "/" };
new import_obsidian3.Setting(containerEl).setName("When should folder suggestions be shown").addDropdown((dropdown) => {
dropdown.addOption("always", "Always").addOption("on-trigger", "Only on trigger").setValue(folderSuggestionSettings.folderSuggestionMode).onChange((value) => __async(this, null, function* () {
folderSuggestionSettings.folderSuggestionMode = value;
this.plugin.settings.folderSuggestionSettings = folderSuggestionSettings;
yield this.plugin.saveSettings();
this.display();
}));
});
if (folderSuggestionSettings.folderSuggestionMode === FolderSuggestionMode.OnTrigger) {
new import_obsidian3.Setting(containerEl).setName("Trigger for showing only folders").setDesc(`The text string that will trigger folder suggestions to be shown. Note that it will only trigger if this is the first symbol you write after writing '${this.plugin.settings.triggerSymbol}'`).addText((component) => component.setValue(folderSuggestionSettings.folderSuggestionTrigger).onChange((value) => __async(this, null, function* () {
folderSuggestionSettings.folderSuggestionTrigger = value;
this.plugin.settings.folderSuggestionSettings = folderSuggestionSettings;
yield this.plugin.saveSettings();
})));
}
}
}
warnIfTriggerIsProblematic(value, trigger, component) {
const triggerStartsWithProblematicCharacter = this.problematicSymbols.some((problem) => value.startsWith(problem));
const triggerIsEmptyOrOnlyWhitespace = value.trim().length === 0;
const triggerIsProblematic = triggerStartsWithProblematicCharacter || triggerIsEmptyOrOnlyWhitespace;
if (triggerIsProblematic) {
trigger.controlEl.addClass("setting-warning");
component.inputEl.setCustomValidity(`Using '${value}' as the trigger for inserting links might not work as intended`);
component.inputEl.reportValidity();
}
}
removeValidationWarning(component, trigger) {
component.inputEl.setCustomValidity("");
component.inputEl.reportValidity();
trigger.controlEl.removeClass("setting-warning");
}
};
// src/interop/LinkSuggestorInterop.ts
var import_obsidian6 = __toModule(require("obsidian"));
// src/interop/ObsidianInterop.ts
var import_obsidian4 = __toModule(require("obsidian"));
var ObsidianInterop = class {
constructor(app2, configStore, fileSystem) {
this.app = app2;
this.configStore = configStore;
this.fileSystem = fileSystem;
}
getFileContentOf(filePath) {
return __async(this, null, function* () {
return this.fileSystem.getFileContentOf(filePath);
});
}
generateMarkdownLink(file, sourcePath, subpath, alias) {
return this.fileSystem.generateMarkdownLink(file, sourcePath, subpath, alias);
}
getUnresolvedLinks() {
return this.app.metadataCache.unresolvedLinks;
}
folderExists(folderPath) {
return this.fileSystem.folderExists(folderPath);
}
noteExists(notePath) {
return this.fileSystem.noteExists(notePath);
}
getAllFileDescendantsOf(folderPath) {
return this.fileSystem.getAllFileDescendantsOf(folderPath);
}
getOrCreateFileAndFoldersInPath(creationCommand, currentFile) {
return __async(this, null, function* () {
return this.fileSystem.getOrCreateFileAndFoldersInPath(creationCommand, currentFile);
});
}
getFile(filePath, currentFile) {
return this.fileSystem.getFile(filePath, currentFile);
}
createFolderIfNeeded(creationCommand) {
return __async(this, null, function* () {
try {
yield this.app.vault.createFolder(creationCommand.PathToNewFolder.VaultPath);
} catch (e) {
console.debug("NAC: Failed folder creation. Folder probably already exist.");
}
});
}
tryCreateFile(creationCommand) {
return __async(this, null, function* () {
console.debug(`NAC: Note does not exist. Will be created. Path: ${creationCommand.PathToNewFile}`);
try {
return yield this.app.vault.create(creationCommand.PathToNewFile, creationCommand.NoteContent);
} catch (e) {
console.debug("NAC: Failed file creation. File probably already exist.");
}
return void 0;
});
}
runTemplaterOn(file) {
return __async(this, null, function* () {
const templater = this.app.plugins.plugins["templater-obsidian"];
if (templater) {
yield templater.templater.overwrite_file_commands(file);
}
});
}
runQuickAddFormattingOn(content) {
return __async(this, null, function* () {
const quickAdd = this.app.plugins.plugins.quickadd;
if (quickAdd) {
return yield quickAdd.api.format(content);
}
});
}
getLinkSuggestions() {
return app.metadataCache.getLinkSuggestions();
}
getPathsToAllLoadedFolders() {
return this.fileSystem.getPathsToAllLoadedFolders();
}
getHeadersIn(filePath) {
var _a;
const file = app.metadataCache.getFirstLinkpathDest(filePath, app.workspace.getActiveFile().path);
if (!(file instanceof import_obsidian4.TFile))
return [];
const headingCache = (_a = this.app.metadataCache.getFileCache(file).headings) != null ? _a : [];
return headingCache;
}
getCoreTemplatesPath() {
return this.configStore.getCoreTemplatesPath();
}
getTemplaterTemplatesPath() {
return this.configStore.getTemplaterTemplatesPath();
}
getValueFor(configKey) {
return this.configStore.getValueFor(configKey);
}
get templaterIsEnabled() {
return this.configStore.templaterIsEnabled;
}
getQuickAddTemplatesPath() {
return this.configStore.getQuickAddTemplatesPath();
}
get quickAddIsEnabled() {
return this.configStore.quickAddIsEnabled;
}
};
// src/core/paths/ObsidianFilePath.ts
var _ObsidianFilePath = class extends ObsidianPath {
get IsRoot() {
return this.VaultPath === "" || this.VaultPath === "/";
}
constructor(path) {
const fullPath = path.trim();
const { vaultPath, folderPath, title, extension, fileNameWithPossibleExtension } = _ObsidianFilePath.extractPathParts(fullPath);
super(vaultPath, title);
this.FolderPath = new ObsidianFolderPath(folderPath);
this.Extension = extension;
this.FileNameWithPossibleExtension = fileNameWithPossibleExtension;
this.NoteIsInRoot = folderPath === "/" || folderPath === "";
this.VaultPathWithoutExtension = this.NoteIsInRoot ? title : `${folderPath}/${title}`;
}
static extractPathParts(fullPath) {
let [vaultPath] = fullPath.split(/[|#]/);
const fileNameStartsAt = vaultPath.lastIndexOf("/");
const [folderPath, fileNameWithPossibleExtension] = fileNameStartsAt === -1 ? ["", vaultPath] : [vaultPath.slice(0, fileNameStartsAt), vaultPath.slice(fileNameStartsAt + 1)];
const extensionStartsAt = fileNameWithPossibleExtension.lastIndexOf(".");
const extension = extensionStartsAt !== -1 ? fileNameWithPossibleExtension.slice(extensionStartsAt + 1) : "";
const includeExtensionInTitle = !this.supportedFileTypes.has(extension);
const title = extensionStartsAt === -1 || includeExtensionInTitle ? fileNameWithPossibleExtension : fileNameWithPossibleExtension.slice(0, extensionStartsAt);
const extensionToUse = includeExtensionInTitle ? "" : extension;
return { vaultPath, folderPath, title, extension: extensionToUse, fileNameWithPossibleExtension };
}
};
var ObsidianFilePath = _ObsidianFilePath;
ObsidianFilePath.supportedFileTypes = new Set([
"md",
"base",
"canvas",
"avif",
"bmp",
"gif",
"jpeg",
"jpg",
"png",
"svg",
"webp",
"flac",
"m4a",
"mp3",
"ogg",
"wav",
"webm",
"3gp",
"mkv",
"mov",
"mp4",
"ogv",
"webm",
"pdf"
]);
// src/core/suggestions/FileSuggestion.ts
var FileSuggestion = class {
get VaultPath() {
return this.Path.VaultPath;
}
get VaultPathWithoutExtension() {
return this.Path.VaultPathWithoutExtension;
}
get Title() {
return this.Path.Title;
}
get FolderPath() {
return this.Path.FolderPath;
}
get NoteIsInRoot() {
return this.Path.NoteIsInRoot;
}
constructor(trigger) {
this.Path = new ObsidianFilePath(trigger);
const fullPath = trigger.trim();
this.Trigger = fullPath;
}
};
// src/core/suggestions/SuggestionRenderer.ts
var SuggestionRenderer = class {
static RenderSuggestion(el, params) {
var _a, _b;
el.addClass("mod-complex");
const content = el.createDiv({
cls: "suggestion-content"
});
content.createDiv({
cls: "suggestion-title",
text: params.content
});
content.createDiv({
cls: "suggestion-note",
text: params.note
});
if (params.fileTag) {
el.createDiv({
cls: "nav-file-tag",
text: params.fileTag
});
}
if (params.flair) {
const aux = el.createDiv({
cls: "suggestion-aux"
});
const flair = aux.createSpan({
cls: "suggestion-flair",
text: params.flair.text
});
flair.ariaLabel = (_a = params.flair.label) != null ? _a : flair.ariaLabel;
flair.innerHTML = (_b = params.flair.innerHTML) != null ? _b : flair.innerHTML;
}
}
};
// src/core/suggestions/NoteSuggestion.ts
var NoteSuggestion = class extends FileSuggestion {
get HasAlias() {
return this.Alias && this.Alias.length > 0;
}
constructor(trigger) {
super(trigger);
const fullPath = trigger.trim();
const { alias } = this.extractSuggestionParts(fullPath);
this.Alias = alias;
}
extractSuggestionParts(trigger) {
if (trigger.indexOf("|") === -1) {
return { alias: void 0 };
}
let alias = trigger.split("|").pop();
alias = (alias == null ? void 0 : alias.length) === 0 ? void 0 : alias == null ? void 0 : alias.trim();
return { alias };
}
get textToInsertOnLineUpdate() {
return this.VaultPathWithoutExtension;
}
};
var ExistingNoteSuggestion = class extends NoteSuggestion {
get ForExistingNote() {
return true;
}
render(el) {
SuggestionRenderer.RenderSuggestion(el, {
content: this.Title,
note: this.FolderPath + "/",
fileTag: this.Path.Extension
});
}
};
var NewNoteSuggestion = class extends NoteSuggestion {
get ForExistingNote() {
return false;
}
render(el) {
SuggestionRenderer.RenderSuggestion(el, {
content: `\u{1F195} ${this.Title}`,
note: this.FolderPath + "/"
});
}
};
var _AliasNoteSuggestion = class extends NoteSuggestion {
get ForExistingNote() {
return true;
}
constructor(path, alias) {
super(path);
this.Alias = alias;
}
render(el) {
SuggestionRenderer.RenderSuggestion(el, {
content: this.Alias,
note: this.FolderPath + "/" + this.Title,
flair: {
innerHTML: _AliasNoteSuggestion.ALIAS_ICON,
label: "Alias"
}
});
}
};
var AliasNoteSuggestion = _AliasNoteSuggestion;
AliasNoteSuggestion.ALIAS_ICON = '<svg viewBox="0 0 100 100" class="forward-arrow" width="13" height="13"><path fill="currentColor" stroke="currentColor" d="m9.9,89.09226c-0.03094,0 -0.05414,0 -0.08508,0c-1.06734,-0.04641 -1.91039,-0.92812 -1.89492,-1.99547c0.00774,-0.48726 1.14469,-48.13101 47.52,-49.44586l0,-13.89094c0,-0.7657 0.44086,-1.4618 1.12922,-1.78664c0.68062,-0.33258 1.5082,-0.23203 2.09601,0.2475l31.68,25.74c0.46406,0.37899 0.73476,0.9436 0.73476,1.53914c0,0.59555 -0.2707,1.16016 -0.72703,1.53914l-31.68,25.74c-0.59555,0.47953 -1.41539,0.57234 -2.10375,0.2475c-0.68836,-0.32485 -1.12922,-1.02094 -1.12922,-1.78664l0,-13.84453c-41.26289,0.75024 -43.49039,24.81961 -43.56773,25.85601c-0.06961,1.04414 -0.93586,1.84078 -1.97226,1.84078z"></path></svg>';
// src/core/LinkCreationPreparer.ts
var LinkCreationPreparer = class {
constructor(fileSystem, configStore) {
this.fileSystem = fileSystem;
this.configStore = configStore;
}
prepareNoteCreationForEmptyNote(suggestion, currentFile) {
return __async(this, null, function* () {
return this.prepareNoteCreation(suggestion, currentFile, () => "");
});
}
prepareNoteCreationForTemplateNote(suggestion, currentFile) {
return __async(this, null, function* () {
const templateContent = yield this.fileSystem.getFileContentOf(suggestion.VaultPath);
return this.prepareNoteCreation(suggestion.noteSuggestion, currentFile, () => templateContent);
});
}
prepareNoteCreation(suggestion, currentFile, getNoteContent) {
const noteExists = this.fileSystem.noteExists(suggestion.VaultPath);
if (noteExists) {
return this.createLinkToExistingNote(suggestion);
}
if (suggestion.NoteIsInRoot && suggestion.Title !== "" && !suggestion.Trigger.startsWith("/")) {
return this.createLinkToNoteInDefaultLocation(suggestion, currentFile, getNoteContent);
}
return this.createLinkToNoteInSubfolder(suggestion, noteExists, getNoteContent);
}
createLinkToNoteInSubfolder(suggestion, noteExists, getNoteContent) {
const fileCreationNeeded = suggestion.Title !== "" && !noteExists;
const folderCreationNeeded = !suggestion.FolderPath.IsRoot && !this.fileSystem.folderExists(suggestion.FolderPath);
const folderCreationCmd = folderCreationNeeded ? { PathToNewFolder: suggestion.FolderPath } : void 0;
const noteCreationCmd = fileCreationNeeded ? { NoteContent: getNoteContent(), PathToNewFile: this.getFileName(suggestion) } : void 0;
return {
FolderCreationCommand: folderCreationCmd,
NoteCreationCommand: noteCreationCmd,
NoteAlias: suggestion.Alias,
FullPath: suggestion.VaultPath
};
}
createLinkToNoteInDefaultLocation(suggestion, currentFile, getNoteContent) {
const noteCreationCmd = {
NoteContent: getNoteContent(),
PathToNewFile: this.getPathToFileInDefaultFolder(suggestion, currentFile)
};
return {
FolderCreationCommand: void 0,
NoteCreationCommand: noteCreationCmd,
NoteAlias: suggestion.Alias,
FullPath: noteCreationCmd.PathToNewFile
};
}
createLinkToExistingNote(suggestion) {
return {
FolderCreationCommand: void 0,
NoteCreationCommand: void 0,
NoteAlias: suggestion.Alias,
FullPath: suggestion.VaultPath
};
}
getFileName(suggestion) {
return suggestion.VaultPath.endsWith(".md") ? suggestion.VaultPath : `${suggestion.VaultPath}.md`;
}
getPathToFileInDefaultFolder(suggestion, currentFile) {
const defaultNoteLocation = this.configStore.getValueFor("newFileLocation");
console.debug(`NAC: default note location is ${defaultNoteLocation}`);
const pathInRoot = `${suggestion.Title}.md`;
switch (defaultNoteLocation) {
case "current": {
const suggestionForCurrentFile = new ExistingNoteSuggestion(currentFile.path);
return suggestionForCurrentFile.NoteIsInRoot ? pathInRoot : `${suggestionForCurrentFile.FolderPath.VaultPath}/${suggestion.Title}.md`;
}
case "folder": {
const defaultFolder = this.configStore.getValueFor("newFileFolderPath");
return defaultFolder && defaultFolder.length > 0 && this.fileSystem.folderExists(new ObsidianFolderPath(defaultFolder)) ? `${defaultFolder}/${suggestion.Title}.md` : pathInRoot;
}
case "root":
default:
return pathInRoot;
}
}
};
// src/core/suggestionExtraction.ts
function extractSuggestionTrigger(lineText, cursorPosition, triggerSymbol) {
const safeTriggerSymbol = triggerSymbol.replace(/[-/\\^$*+?.()|[\]{}]/g, "\\$&");
const regex = new RegExp(`(?:^| )${safeTriggerSymbol}(?!.*]])(.*)`, "d");
const triggerSymbolIndex = lineText.indexOf(triggerSymbol);
if (lineText.length === 0 || cursorPosition.ch === 0 || triggerSymbolIndex == -1) {
return null;
}
const textToSearch = lineText.slice(0, cursorPosition.ch);
const match = regex.exec(textToSearch);
if (!match) {
return null;
}
const myMatch = match;
const query = match[1];
const groupIndices = myMatch.indices;
const queryStartIndex = Number(groupIndices[1][0]);
const queryEndIndex = Number(groupIndices[1][1]);
return {
start: { line: cursorPosition.line, ch: queryStartIndex },
end: { line: cursorPosition.line, ch: queryEndIndex },
query
};
}
// src/core/LinkSuggestor.ts
var import_obsidian5 = __toModule(require("obsidian"));
// src/core/suggestions/TemplateSuggestion.ts
var TemplateSuggestion = class extends FileSuggestion {
constructor(templatePath, noteSuggestion, rootTemplateFolder, templateConfig) {
super(templatePath);
this.rootTemplateFolder = rootTemplateFolder != null ? rootTemplateFolder : "";
this.templateIsInTemplateFolder = this.VaultPath.toLowerCase().includes(this.rootTemplateFolder.toLowerCase());
this.pathFromTemplateRoot = this.templateIsInTemplateFolder ? this.VaultPathWithoutExtension.slice(this.rootTemplateFolder.length) : this.VaultPathWithoutExtension;
this.noteSuggestion = noteSuggestion;
this.triggerSymbol = templateConfig.triggerSymbol;
this.templateEngine = templateConfig.templateEngine;
}
render(el) {
SuggestionRenderer.RenderSuggestion(el, {
content: this.pathFromTemplateRoot,
note: `Apply ${this.templateEngine} template to "${this.noteSuggestion.VaultPath}"`
});
}
get textToInsertOnLineUpdate() {
return `${this.noteSuggestion.textToInsertOnLineUpdate}${this.triggerSymbol}${this.pathFromTemplateRoot}`;
}
};
// src/core/queries/QueryResult.ts
var QueryResult = class {
constructor(isAtLeastPartialMatch, isCompleteMatch) {
this.isCompleteMatch = isCompleteMatch;
this.isAtLeastPartialMatch = isAtLeastPartialMatch;
this.isNoMatch = !(isCompleteMatch || isAtLeastPartialMatch);
}
static forCompleteMatch() {
return new QueryResult(true, true);
}
static forPartialMatch() {
return new QueryResult(true, false);
}
static forNoMatch() {
return new QueryResult(false, false);
}
};
// src/core/queries/Query.ts
function allTrue(matchers) {
return (suggestion) => matchers.every((m) => m(suggestion));
}
function anyTrue(matchers) {
return (suggestion) => matchers.some((m) => m(suggestion));
}
var Query = class {
constructor(query, fullMatchFoundChecker, partialMatchFoundChecker) {
this.fullMatchFoundChecker = fullMatchFoundChecker;
this.partialMatchFoundChecker = partialMatchFoundChecker;
this.query = query;
}
couldBeQueryFor(suggestion) {
if (this.fullMatchFoundChecker(suggestion)) {
return QueryResult.forCompleteMatch();
}
if (this.partialMatchFoundChecker(suggestion)) {
return QueryResult.forPartialMatch();
}
return QueryResult.forNoMatch();
}
get IsEmpty() {
return this.query === "";
}
static topFolderCheck(queryPath, context, settings) {
if (settings.relativeTopFolders.length > 0) {
const filePath = new ObsidianFilePath(context.file.path);
const topFolderToUse = settings.relativeTopFolders.find((folder) => {
return folder.isAncestorOf(filePath) || filePath.FolderPath.VaultPath.toLowerCase().includes(folder.VaultPath);
});
if (topFolderToUse) {
const endOfFolderPath = filePath.FolderPath.VaultPath.lastIndexOf(topFolderToUse.VaultPath);
const folderPathToUse = filePath.FolderPath.VaultPath.slice(0, endOfFolderPath + topFolderToUse.VaultPath.length);
const path = new ObsidianFolderPath(folderPathToUse);
return (suggestion) => path.isAncestorOf(suggestion.Path);
}
}
return (suggestion) => true;
}
};
// src/core/queries/FileQuery.ts
function getMatcherForExactMatch(lowerCaseQueryPath) {
return (suggestion) => suggestion.Path.VaultPathWithoutExtension.toLowerCase() === lowerCaseQueryPath.VaultPathWithoutExtension;
}
function getMatcherForPartialMatch(lowerCaseQueryPath) {
return (suggestion) => {
const path = suggestion.Path;
const queryIsAncestor = path.FolderPath.VaultPath.toLowerCase().includes(lowerCaseQueryPath.FolderPath.VaultPath);
const queryCouldBeForSuggestedNote = path.VaultPath.toLowerCase().replace(lowerCaseQueryPath.FolderPath.VaultPath, "").includes(lowerCaseQueryPath.Title);
return queryIsAncestor && queryCouldBeForSuggestedNote;
};
}
var FileQuery = class extends Query {
constructor(query, fullMatchFoundCheckers, partialMatchFoundCheckers) {
super(query, fullMatchFoundCheckers, partialMatchFoundCheckers);
}
static aliasCheck(queryPath) {
return (suggestion) => {
if (suggestion instanceof AliasNoteSuggestion) {
return suggestion.Alias.toLowerCase().includes(queryPath.Title);
}
return false;
};
}
static forNoteSuggestions(context, settings) {
const query = context.query;
const lowerCaseQueryPath = new ObsidianFilePath(query.toLowerCase());
const fullMatchFoundChecker = getMatcherForExactMatch(lowerCaseQueryPath);
const partialMatchFoundChecker = allTrue([
Query.topFolderCheck(lowerCaseQueryPath, context, settings),
anyTrue([
getMatcherForPartialMatch(lowerCaseQueryPath),
this.aliasCheck(lowerCaseQueryPath)
])
]);
return new FileQuery(query, fullMatchFoundChecker, partialMatchFoundChecker);
}
static forTemplateSuggestions(query) {
const lowerCaseQueryPath = new ObsidianFilePath(query.toLowerCase());
const fullMatchFoundChecker = getMatcherForExactMatch(lowerCaseQueryPath);
const partialMatchFoundChecker = getMatcherForPartialMatch(lowerCaseQueryPath);
return new FileQuery(query, fullMatchFoundChecker, partialMatchFoundChecker);
}
};
// src/core/suggestions/ISuggestion.ts
var Suggestion = class {
static compare(a, b) {
return a.Title.localeCompare(b.Title);
}
};
// src/core/suggestionCollection/TemplateSuggestionCollector.ts
var TemplateSuggestionCollector = class {
constructor(fileSystem, configStore, settings, templateConfig) {
this.fileSystem = fileSystem;
this.configStore = configStore;
this.settings = settings;
this.templateConfig = templateConfig;
}
getSuggestions(templateQuery, noteSuggestion) {
const query = FileQuery.forTemplateSuggestions(templateQuery);
const templateFolderPath = this.templateConfig.getTemplateFolderPath();
const validSuggestions = [];
const defaultTemplate = this.templateConfig.getDefaultTemplate();
const showDefaultFolderFirst = templateQuery === "" && defaultTemplate !== "";
const pathToFilterOut = showDefaultFolderFirst ? defaultTemplate : "";
for (const suggestion of this.getAllPossibleSuggestions(templateFolderPath, noteSuggestion, pathToFilterOut)) {
const queryResult = query.couldBeQueryFor(suggestion);
if (queryResult.isAtLeastPartialMatch) {
validSuggestions.push(suggestion);
}
}
validSuggestions.sort(Suggestion.compare);
if (showDefaultFolderFirst) {
const defaultTemplateSuggestion = new TemplateSuggestion(defaultTemplate, noteSuggestion, templateFolderPath, this.templateConfig);
return [defaultTemplateSuggestion, ...validSuggestions];
}
return validSuggestions;
}
getAllPossibleSuggestions(templateFolderPath, noteSuggestion, pathToFilterOut) {
return templateFolderPath ? this.fileSystem.getAllFileDescendantsOf(templateFolderPath).filter((f) => f.path.toLowerCase() !== pathToFilterOut).map((f) => new TemplateSuggestion(f.path, noteSuggestion, templateFolderPath, this.templateConfig)) : [];
}
};
// src/core/suggestions/HeaderSuggestion.ts
var HeaderSuggestion = class {
constructor(header, level, alias, noteSuggestion) {
this.header = header;
this.level = level;
this.noteSuggestion = noteSuggestion;
this.alias = alias;
}
get Path() {
return this.noteSuggestion.Path;
}
get ParentNote() {
return this.noteSuggestion;
}
get Alias() {
return this.alias;
}
get Title() {
return this.header;
}
get AsSubPath() {
return `#${this.Title}`;
}
render(el) {
SuggestionRenderer.RenderSuggestion(el, {
content: this.Title,
note: "",
flair: {
text: `H${this.level}`
}
});
}
get textToInsertOnLineUpdate() {
return `${this.noteSuggestion.Trigger}#${this.Title}`;
}
};
// src/core/suggestionCollection/HeaderSuggestionCollector.ts
var HeaderSuggestionCollector = class {
constructor(metadataCollection, settings) {
this.metadataCollection = metadataCollection;
this.headerAsAliasTrigger = settings.triggerHeaderAsAliasSymbol;
}
getSuggestions(headerQuery, noteSuggestion) {
const [query, alias] = headerQuery.split("|");
const lowerCaseQuery = query.toLowerCase();
const headersInNote = this.metadataCollection.getHeadersIn(noteSuggestion.Path.VaultPath);
let aliasToUse = noteSuggestion.Alias ? noteSuggestion.Alias : alias;
let validHeaders = headersInNote.filter((h) => h.heading.toLowerCase().includes(lowerCaseQuery));
let headerCanBeUsedAsAlias = false;
if (validHeaders.length === 0 && query.endsWith(this.headerAsAliasTrigger)) {
const queryWithoutBang = lowerCaseQuery.slice(0, query.length - 1);
validHeaders = headersInNote.filter((h) => h.heading.toLowerCase().includes(queryWithoutBang));
headerCanBeUsedAsAlias = true;
}
if (headerCanBeUsedAsAlias && validHeaders.length === 1 && !alias) {
aliasToUse = validHeaders[0].heading;
}
return validHeaders.map((h) => new HeaderSuggestion(h.heading, h.level, aliasToUse, noteSuggestion));
}
};
// src/core/suggestions/NotFoundSuggestion.ts
var NotFoundSuggestion = class {
constructor(trigger, messageToShow) {
this.trigger = trigger;
this.message = messageToShow;
}
get Title() {
return this.message;
}
render(el) {
SuggestionRenderer.RenderSuggestion(el, {
content: this.Title,
note: ""
});
}
get textToInsertOnLineUpdate() {
return this.trigger;
}
get Path() {
return void 0;
}
};
// src/core/suggestionCollection/NoteSource.ts
var NoteSource = class {
constructor(metadata, settings) {
this.metadata = metadata;
this.settings = settings;
}
createSuggestionFromQuery(query, existingSuggestionForQuery) {
const queryAsSuggestion = new NewNoteSuggestion(query.query);
if (existingSuggestionForQuery) {
const suggestionToAdd = queryAsSuggestion.HasAlias ? new ExistingNoteSuggestion(`${existingSuggestionForQuery.VaultPath}|${queryAsSuggestion.Alias}`) : existingSuggestionForQuery;
return suggestionToAdd;
} else {
return queryAsSuggestion;
}
}
getAllPossibleSuggestions(query) {
const observedPaths = new Set();
const suggestions = [];
const addIfPathHasNotBeSeen = (path, exist, alias) => {
const pathHasBeenSeen = observedPaths.has(path);
if (alias || !pathHasBeenSeen) {
suggestions.push(this.createSuggestion(path, alias, exist, query));
observedPaths.add(path);
}
return !pathHasBeenSeen;
};
const linkSuggestions = this.metadata.getLinkSuggestions();
for (const linkSuggestion of linkSuggestions) {
addIfPathHasNotBeSeen(linkSuggestion.path, linkSuggestion.file !== null, linkSuggestion.alias);
}
if (this.settings.suggestLinksToNonExistingNotes) {
return suggestions;
} else {
return suggestions.filter((suggestion) => suggestion.ForExistingNote);
}
}
createSuggestion(path, alias, pathIsToExistingNote, trigger) {
if (pathIsToExistingNote) {
if (alias && alias.toLowerCase().includes(trigger)) {
return new AliasNoteSuggestion(path, alias);
} else {
return new ExistingNoteSuggestion(path);
}
} else {
return new NewNoteSuggestion(path);
}
}
};
// src/core/suggestions/FolderSuggestion.ts
var FolderSuggestion = class {
constructor(folderPath) {
this.folderPath = folderPath;
}
get Title() {
return this.folderPath.Title;
}
render(el) {
SuggestionRenderer.RenderSuggestion(el, {
content: `\u{1F4C1} ${this.folderPath.Title}`,
note: this.folderPath.VaultPath
});
}
get textToInsertOnLineUpdate() {
return this.folderPath.VaultPath;
}
get Path() {
return this.folderPath;
}
static FromPath(path) {
return new FolderSuggestion(path);
}
};
// src/core/suggestionCollection/FolderSource.ts
var FolderSource = class {
constructor(fileSystem) {
this.fileSystem = fileSystem;
}
createSuggestionFromQuery(query, existingSuggestionForQuery) {
return existingSuggestionForQuery ? existingSuggestionForQuery : new FolderSuggestion(new ObsidianFolderPath(query.query));
}
getAllPossibleSuggestions(query) {
return this.fileSystem.getPathsToAllLoadedFolders().map(FolderSuggestion.FromPath);
}
};
// src/core/suggestionCollection/NoteAndFolderSource.ts
var NoteAndFolderSource = class {
constructor(interop, settings) {
this.noteSource = new NoteSource(interop, settings);
this.folderSource = new FolderSource(interop);
this.sources = [
this.noteSource,
this.folderSource
];
}
createSuggestionFromQuery(query, existingSuggestionForQuery) {
if (existingSuggestionForQuery && existingSuggestionForQuery instanceof FolderSuggestion) {
return this.folderSource.createSuggestionFromQuery(query, existingSuggestionForQuery);
}
return this.noteSource.createSuggestionFromQuery(query, existingSuggestionForQuery);
}
getAllPossibleSuggestions(query) {
return this.sources.flatMap((s) => s.getAllPossibleSuggestions(query));
}
};
// src/core/suggestionCollection/BaseSuggestionCollector.ts
var BaseSuggestionCollector = class {
constructor(suggestionSource) {
this.suggestionSource = suggestionSource;
}
getSuggestions(query) {
let existingSuggestionForQuery;
const validSuggestions = [];
const allPossibleSuggestions = this.suggestionSource.getAllPossibleSuggestions(query.query);
for (const suggestion of allPossibleSuggestions) {
const queryResult = query.couldBeQueryFor(suggestion);
if (queryResult.isCompleteMatch) {
existingSuggestionForQuery = suggestion;
continue;
}
if (queryResult.isAtLeastPartialMatch) {
validSuggestions.push(suggestion);
}
}
validSuggestions.sort(Suggestion.compare);
if (query.IsEmpty) {
return validSuggestions;
}
validSuggestions.unshift(this.suggestionSource.createSuggestionFromQuery(query, existingSuggestionForQuery));
return validSuggestions;
}
};
var NoteSuggestionCollector = class extends BaseSuggestionCollector {
constructor(metadata, settings) {
super(new NoteSource(metadata, settings));
}
};
var FolderSuggestionCollector = class extends BaseSuggestionCollector {
constructor(fileSystem) {
super(new FolderSource(fileSystem));
}
};
var NoteAndFolderSuggestionCollector = class extends BaseSuggestionCollector {
constructor(interop, settings) {
super(new NoteAndFolderSource(interop, settings));
}
};
// src/core/queries/FolderQuery.ts
var FolderQuery = class extends Query {
constructor(context, settings) {
const query = context.query;
const lowerCaseQueryPath = new ObsidianFolderPath(query.toLowerCase());
const fullMatchFoundChecker = (suggestion) => suggestion.Path.VaultPath.toLowerCase() === lowerCaseQueryPath.VaultPath;
const partialMatchFoundChecker = allTrue([
Query.topFolderCheck(lowerCaseQueryPath, context, settings),
anyTrue([
(suggestion) => suggestion.Path.VaultPath.toLowerCase().includes(lowerCaseQueryPath.VaultPath)
])
]);
super(query, fullMatchFoundChecker, partialMatchFoundChecker);
}
};
// src/core/queries/NoteAndFolderQuery.ts
var _NoteAndFolderQuery = class extends Query {
constructor(context, settings) {
const noteQuery = FileQuery.forNoteSuggestions(context, settings);
const folderQuery = new FolderQuery(context, settings);
const fullMatchFoundCheckers = [
allTrue([_NoteAndFolderQuery.isNoteSuggestion, noteQuery.fullMatchFoundChecker]),
allTrue([_NoteAndFolderQuery.isFolderSuggestion, folderQuery.fullMatchFoundChecker])
];
const partialMatchFoundCheckers = [
allTrue([_NoteAndFolderQuery.isNoteSuggestion, noteQuery.partialMatchFoundChecker]),
allTrue([_NoteAndFolderQuery.isFolderSuggestion, folderQuery.partialMatchFoundChecker])
];
super(context.query, anyTrue(fullMatchFoundCheckers), anyTrue(partialMatchFoundCheckers));
}
};
var NoteAndFolderQuery = _NoteAndFolderQuery;
NoteAndFolderQuery.isNoteSuggestion = (suggestion) => suggestion instanceof NoteSuggestion;
NoteAndFolderQuery.isFolderSuggestion = (suggestion) => suggestion instanceof FolderSuggestion;
// src/core/templateApplication/TemplateEngine.ts
var TemplateEngine;
(function(TemplateEngine2) {
TemplateEngine2[TemplateEngine2["Templater"] = 0] = "Templater";
TemplateEngine2[TemplateEngine2["QuickAdd"] = 1] = "QuickAdd";
})(TemplateEngine || (TemplateEngine = {}));
// src/core/templateApplication/TemplaterTemplateConfig.ts
var TemplaterTemplateConfig = class {
constructor(configStore, settings) {
this.templateEngine = TemplateEngine.Templater;
this.settings = settings;
this.configStore = configStore;
}
get triggerSymbol() {
return this.settings.templateTriggerSymbol;
}
getDefaultTemplate() {
return this.settings.defaultTemplaterTemplate;
}
getTemplateFolderPath() {
return this.configStore.getTemplaterTemplatesPath();
}
};
// src/core/templateApplication/QuickAddTemplateConfig.ts
var QuickAddTemplateConfig = class {
constructor(configStore, settings) {
this.templateEngine = TemplateEngine.QuickAdd;
this.settings = settings;
this.configStore = configStore;
}
get triggerSymbol() {
return this.settings.quickAddTriggerSymbol;
}
getDefaultTemplate() {
return this.settings.defaultQuickAddTemplate;
}
getTemplateFolderPath() {
return this.configStore.getQuickAddTemplatesPath();
}
};
// src/core/suggestionCollection/SuggestionCollector.ts
var SuggestionCollector = class {
constructor(interOp, settings) {
this.settings = settings;
this.noteSuggestionCollector = new NoteSuggestionCollector(interOp, settings);
const templaterConfig = new TemplaterTemplateConfig(interOp, settings);
const quickaddConfig = new QuickAddTemplateConfig(interOp, settings);
this.templaterTemplateSuggestionCollector = new TemplateSuggestionCollector(interOp, interOp, settings, templaterConfig);
this.quickaddTemplateSuggestionCollector = new TemplateSuggestionCollector(interOp, interOp, settings, quickaddConfig);
this.headerSuggestionCollector = new HeaderSuggestionCollector(interOp, settings);
this.folderSuggestionCollector = new FolderSuggestionCollector(interOp);
this.combinedSuggestionCollector = new NoteAndFolderSuggestionCollector(interOp, settings);
this.fileSystem = interOp;
this.configStore = interOp;
}
getNoteSuggestionFor(query) {
const tempSuggestion = new ExistingNoteSuggestion(query);
return this.fileSystem.noteExists(tempSuggestion.VaultPath) ? tempSuggestion : new NewNoteSuggestion(query);
}
getSuggestions(context) {
if (this.settings.enableRelativePaths && context.query.startsWith(".")) {
this.replaceRelativePathInQueryWithFullPath(context);
}
let suggestions = [];
if (this.configStore.templaterIsEnabled && this.settings.templateTriggerSymbol !== "" && context.query.includes(this.settings.templateTriggerSymbol)) {
suggestions = this.getTemplaterTemplateSuggestions(context.query);
} else if (this.configStore.quickAddIsEnabled && this.settings.quickAddTriggerSymbol !== "" && context.query.includes(this.settings.quickAddTriggerSymbol)) {
suggestions = this.getQuickAddTemplateSuggestions(context.query);
} else if (context.query.includes("#")) {
suggestions = this.getHeaderSuggestions(context.query);
} else if (this.settings.includeFoldersInSuggestions) {
suggestions = this.getFoldersOrCombinedSuggestions(context.query, context);
} else {
suggestions = this.getNoteSuggestions(context);
}
return suggestions.length > 0 ? suggestions : [new NotFoundSuggestion(context.query, "No match found")];
}
replaceRelativePathInQueryWithFullPath(context) {
if (context.query.startsWith("..")) {
const path = new ObsidianFilePath(context.file.path);
context.query = context.query.replace("..", path.FolderPath.getParentOrThis().VaultPath);
} else if (context.query.startsWith(".")) {
const path = new ObsidianFilePath(context.file.path);
context.query = context.query.replace(".", path.FolderPath.VaultPath);
}
}
getNoteSuggestions(context) {
return this.noteSuggestionCollector.getSuggestions(FileQuery.forNoteSuggestions(context, this.settings));
}
getFoldersOrCombinedSuggestions(query, context) {
const onlyCollectFoldersOnTrigger = this.settings.folderSuggestionSettings.folderSuggestionMode === FolderSuggestionMode.OnTrigger;
if (onlyCollectFoldersOnTrigger) {
return this.getOnlyFolderOrNoteSuggestions(query, context);
} else {
return this.getFolderAndNoteSuggestions(context);
}
}
getFolderAndNoteSuggestions(context) {
return this.combinedSuggestionCollector.getSuggestions(new NoteAndFolderQuery(context, this.settings));
}
getOnlyFolderOrNoteSuggestions(query, context) {
const trigger = this.settings.folderSuggestionSettings.folderSuggestionTrigger;
if (this.queryStartsWithTrigger(query, trigger)) {
context.query = context.query.substring(trigger.length);
return this.getFolderSuggestions(context);
} else {
return this.getNoteSuggestions(context);
}
}
getFolderSuggestions(context) {
return this.folderSuggestionCollector.getSuggestions(new FolderQuery(context, this.settings));
}
queryStartsWithTrigger(query, trigger) {
return query.toLowerCase().startsWith(trigger.toLowerCase());
}
getHeaderSuggestions(query) {
const [noteQuery, headerQuery] = query.split("#");
const noteSuggestion = this.getNoteSuggestionFor(noteQuery);
if (noteSuggestion instanceof ExistingNoteSuggestion) {
return this.headerSuggestionCollector.getSuggestions(headerQuery, noteSuggestion);
} else {
return [new NotFoundSuggestion(query, "No headers to link to in non-existing notes")];
}
}
getTemplaterTemplateSuggestions(query) {
const [noteQuery, templateQuery] = query.split(this.settings.templateTriggerSymbol);
const noteSuggestion = this.getNoteSuggestionFor(noteQuery);
return this.templaterTemplateSuggestionCollector.getSuggestions(templateQuery, noteSuggestion);
}
getQuickAddTemplateSuggestions(query) {
const [noteQuery, templateQuery] = query.split(this.settings.quickAddTriggerSymbol);
const noteSuggestion = this.getNoteSuggestionFor(noteQuery);
return this.quickaddTemplateSuggestionCollector.getSuggestions(templateQuery, noteSuggestion);
}
};
// src/core/LinkSuggestor.ts
var LinkSuggestor = class {
constructor(interop, settings) {
this.obsidianInterop = interop;
this.suggestionsCollector = new SuggestionCollector(this.obsidianInterop, settings);
this.noteCreationPreparer = new LinkCreationPreparer(this.obsidianInterop, this.obsidianInterop);
this.settings = settings;
}
get instructions() {
return [
{ command: "Type |", purpose: "to change display text" },
{ command: "Type #", purpose: "to link heading" },
{ command: `Type ${this.settings.templateTriggerSymbol}`, purpose: "to trigger template selection" }
];
}
getSuggestions(context) {
return this.suggestionsCollector.getSuggestions(context);
}
onTrigger(cursor, editor, file) {
const pathToFile = new ObsidianFilePath(file.path);
if (this.settings.enabledFolders.length > 0) {
const enablePlugin = this.settings.enabledFolders.find((enabledFolder) => enabledFolder.isAncestorOf(pathToFile)) != void 0;
if (!enablePlugin) {
return null;
}
}
const line = editor.getLine(cursor.line);
this.currentTrigger = extractSuggestionTrigger(line, cursor, this.settings.triggerSymbol);
return this.currentTrigger;
}
renderSuggestion(value, el) {
value.render(el);
}
selectSuggestion(value, evt, context) {
const currentFile = context.file;
this.selectSuggestionAsync(value, currentFile, context);
}
selectSuggestionAsync(suggestion, currentFile, context) {
return __async(this, null, function* () {
if (suggestion.Title === "") {
return;
}
if (suggestion instanceof NoteSuggestion) {
yield this.selectNoteSuggestion(suggestion, currentFile, context);
} else if (suggestion instanceof TemplateSuggestion) {
yield this.selectTemplateSuggestion(suggestion, currentFile, context);
} else if (suggestion instanceof HeaderSuggestion) {
yield this.selectHeaderSuggestion(suggestion, currentFile, context);
} else if (suggestion instanceof FolderSuggestion) {
this.updateSuggestionLine(suggestion, context);
}
});
}
selectHeaderSuggestion(suggestion, currentFile, context) {
return __async(this, null, function* () {
const linkedFile = yield this.obsidianInterop.getFile(suggestion.ParentNote.Path, currentFile);
if (linkedFile === null) {
return;
}
const linkToInsert = this.obsidianInterop.generateMarkdownLink(linkedFile, currentFile.path, suggestion.AsSubPath, suggestion.Alias);
this.replaceSuggestionWithLink(linkToInsert, context);
});
}
selectTemplateSuggestion(templateSuggestion, currentFile, context) {
return __async(this, null, function* () {
if (!this.obsidianInterop.noteExists(templateSuggestion.VaultPath)) {
new import_obsidian5.Notice(`Cannot execute a non-existing template "${templateSuggestion.VaultPath}". Note was not created`);
return;
}
const creationCommand = yield this.noteCreationPreparer.prepareNoteCreationForTemplateNote(templateSuggestion, currentFile);
if (templateSuggestion.templateEngine === TemplateEngine.QuickAdd) {
creationCommand.NoteCreationCommand.NoteContent = yield this.obsidianInterop.runQuickAddFormattingOn(creationCommand.NoteCreationCommand.NoteContent);
}
const linkedFile = yield this.obsidianInterop.getOrCreateFileAndFoldersInPath(creationCommand, currentFile);
if (templateSuggestion.templateEngine === TemplateEngine.Templater && creationCommand.NoteCreationCommand && linkedFile) {
yield this.obsidianInterop.runTemplaterOn(linkedFile);
}
const linkToInsert = this.obsidianInterop.generateMarkdownLink(linkedFile, currentFile.path, void 0, creationCommand.NoteAlias);
this.replaceSuggestionWithLink(linkToInsert, context);
});
}
selectNoteSuggestion(suggestion, currentFile, context) {
return __async(this, null, function* () {
const creationCommand = yield this.noteCreationPreparer.prepareNoteCreationForEmptyNote(suggestion, currentFile);
const linkedFile = yield this.obsidianInterop.getOrCreateFileAndFoldersInPath(creationCommand, currentFile);
const linkToInsert = this.obsidianInterop.generateMarkdownLink(linkedFile, currentFile.path, void 0, creationCommand.NoteAlias);
this.replaceSuggestionWithLink(linkToInsert, context);
});
}
replaceSuggestionWithLink(valueToInsert, context) {
const editor = context.editor;
const startPosition = {
line: this.currentTrigger.start.line,
ch: this.currentTrigger.start.ch - this.settings.triggerSymbol.length
};
editor.replaceRange(valueToInsert, startPosition, this.currentTrigger.end);
}
updateSuggestionLine(newSuggestion, context) {
const editor = context.editor;
const textToInsert = newSuggestion.textToInsertOnLineUpdate;
const finalCursorPosition = {
line: this.currentTrigger.start.line,
ch: this.currentTrigger.start.ch + textToInsert.length
};
editor.replaceRange(textToInsert, this.currentTrigger.start, this.currentTrigger.end);
editor.setCursor(finalCursorPosition);
}
};
// src/interop/LinkSuggestorInterop.ts
var LinkSuggestorInterop = class extends import_obsidian6.EditorSuggest {
constructor(app2, settings, configStore, fileSystem) {
super(app2);
this.wrapped = new LinkSuggestor(new ObsidianInterop(app2, configStore, fileSystem), settings);
this.setInstructions(this.wrapped.instructions);
this.scope.register([], "Tab", (event) => {
const suggestionCollection = this.suggestions;
const idOfHighlightedSuggestion = suggestionCollection.selectedItem;
const highlightedSuggestion = suggestionCollection.values[idOfHighlightedSuggestion];
this.wrapped.updateSuggestionLine(highlightedSuggestion, this.context);
});
}
getSuggestions(context) {
return this.wrapped.getSuggestions(context);
}
onTrigger(cursor, editor, file) {
return this.wrapped.onTrigger(cursor, editor, file);
}
renderSuggestion(value, el) {
this.wrapped.renderSuggestion(value, el);
}
selectSuggestion(value, evt) {
if (value instanceof TemplateSuggestion && value.noteSuggestion instanceof ExistingNoteSuggestion) {
new import_obsidian6.Notice("Executing templates on existing notes is not supported");
return;
}
this.wrapped.selectSuggestion(value, evt, this.context);
}
};
// src/interop/ConfigStore.ts
var ConfigStore = class {
constructor(app2) {
this.app = app2;
}
getCoreTemplatesPath() {
const internalTemplatePlugin = this.app.internalPlugins.plugins.templates;
if (internalTemplatePlugin) {
const templateFolderPath = internalTemplatePlugin.instance.options.folder;
if (templateFolderPath)
return templateFolderPath;
}
}
getTemplaterTemplatesPath() {
const templater = this.app.plugins.plugins["templater-obsidian"];
if (templater) {
const templateFolderPath = templater.settings["templates_folder"];
if (templateFolderPath)
return templateFolderPath;
}
}
getQuickAddTemplatesPath() {
const quickAdd = this.app.plugins.plugins.quickadd;
if (quickAdd) {
const templateFolderPath = quickAdd.settings["templateFolderPath"];
if (templateFolderPath)
return templateFolderPath;
}
}
getValueFor(configKey) {
return this.app.vault.getConfig(configKey);
}
get templaterIsEnabled() {
return this.app.plugins.plugins["templater-obsidian"];
}
get quickAddIsEnabled() {
return this.app.plugins.plugins.quickadd;
}
};
// src/interop/ObsidianFileSystem.ts
var import_obsidian7 = __toModule(require("obsidian"));
var ObsidianFileSystem = class {
constructor(app2) {
this.app = app2;
}
folderExists(folderPath) {
const foundItem = this.app.vault.getAbstractFileByPath(folderPath.VaultPath);
return foundItem && foundItem instanceof import_obsidian7.TFolder;
}
generateMarkdownLink(file, sourcePath, subpath, alias) {
return this.app.fileManager.generateMarkdownLink(file, sourcePath, subpath, alias);
}
getAllFileDescendantsOf(folderPath) {
const abstractFile = this.app.vault.getAbstractFileByPath(folderPath);
if (!(abstractFile instanceof import_obsidian7.TFolder)) {
console.debug(`NAC: "${folderPath}" is not a valid path to a folder`);
return [];
}
const files = [];
import_obsidian7.Vault.recurseChildren(abstractFile, (file) => {
if (file instanceof import_obsidian7.TFile) {
files.push(file);
}
});
return files;
}
getFile(filePath, currentFile) {
return this.app.metadataCache.getFirstLinkpathDest(filePath.VaultPath, currentFile.path);
}
getFileContentOf(filePath) {
return __async(this, null, function* () {
const file = this.app.vault.getAbstractFileByPath(filePath);
if (!(file instanceof import_obsidian7.TFile))
return;
return yield this.app.vault.cachedRead(file);
});
}
getOrCreateFileAndFoldersInPath(creationCommand, currentFile) {
return __async(this, null, function* () {
if (creationCommand.FolderCreationCommand) {
yield this.createFolderIfNeeded(creationCommand.FolderCreationCommand);
}
if (creationCommand.NoteCreationCommand) {
return yield this.tryCreateFile(creationCommand.NoteCreationCommand);
} else {
return this.app.metadataCache.getFirstLinkpathDest(creationCommand.FullPath, currentFile.path);
}
});
}
createFolderIfNeeded(creationCommand) {
return __async(this, null, function* () {
try {
yield this.app.vault.createFolder(creationCommand.PathToNewFolder.VaultPath);
} catch (e) {
console.debug("NAC: Failed folder creation. Folder probably already exist.");
}
});
}
tryCreateFile(creationCommand) {
return __async(this, null, function* () {
console.debug(`NAC: Note does not exist. Will be created. Path: ${creationCommand.PathToNewFile}`);
try {
return yield this.app.vault.create(creationCommand.PathToNewFile, creationCommand.NoteContent);
} catch (e) {
console.debug("NAC: Failed file creation. File probably already exist.");
}
return void 0;
});
}
getPathsToAllLoadedFolders() {
return app.vault.getAllLoadedFiles().filter((f) => f instanceof import_obsidian7.TFolder).map((f) => new ObsidianFolderPath(f.path));
}
noteExists(notePath) {
const foundItem = app.metadataCache.getFirstLinkpathDest(notePath, app.workspace.getActiveFile().path);
return foundItem && foundItem instanceof import_obsidian7.TFile;
}
};
// src/main.ts
var NoteAutoCreator = class extends import_obsidian8.Plugin {
onload() {
return __async(this, null, function* () {
yield this.loadSettings();
const configStore = new ConfigStore(this.app);
const fileSystem = new ObsidianFileSystem(this.app);
this.addSettingTab(new SettingTab(this.app, this, configStore, fileSystem));
const linkSuggestor = new LinkSuggestorInterop(this.app, this.settings, configStore, fileSystem);
this.registerEditorSuggest(linkSuggestor);
});
}
onunload() {
}
loadSettings() {
return __async(this, null, function* () {
this.settings = Object.assign({}, DEFAULT_SETTINGS, yield this.loadData());
this.settings.relativeTopFolders = this.settings.relativeTopFolders.map((f) => new ObsidianFolderPath(f.VaultPath));
});
}
saveSettings() {
return __async(this, null, function* () {
yield this.saveData(this.settings);
});
}
};
/* nosourcemap */