generated from DNDs/dnd-template
Jesse James Isler
933af5c620
Affected files: .obsidian/workspace Daily/28.06.22.md templates/New Problem Template.md vault auto-backup: 28.06.2022 - 08:56:34 Affected files: .obsidian/workspace Firmen/Steinemann Technology/Dokumentation RTM.md files/chpm002/BELEGE.md vault auto-backup: 28.06.2022 - 09:43:47 Affected files: .obsidian/community-plugins.json .obsidian/plugins/obsidian-admonition/data.json .obsidian/plugins/obsidian-admonition/main.js .obsidian/plugins/obsidian-admonition/manifest.json .obsidian/plugins/obsidian-admonition/styles.css .obsidian/plugins/obsidian-git/data.json .obsidian/plugins/obsidian-jump-to-date-plugin/main.js .obsidian/plugins/obsidian-jump-to-date-plugin/manifest.json .obsidian/plugins/obsidian-jump-to-date-plugin/styles.css .obsidian/plugins/obsidian-pandoc/data.json .obsidian/workspace Daily/28.06.22.md Firmen/Bilfinger/Tickets/Jesse James Isler/Dawn of the first day.md Firmen/Steinemann Technology/Tickets/Maik Förster/Neuer Laptop installieren.md Highsystems Asset MGMT.md attachment/Steinemann Technology/HighsystemsCM/Pasted image 20220628091615.png attachment/Steinemann Technology/HighsystemsCM/Pasted image 20220628091652.png attachment/Steinemann Technology/HighsystemsCM/Pasted image 20220628091712.png attachment/Steinemann Technology/HighsystemsCM/Pasted image 20220628091802.png attachment/Steinemann Technology/HighsystemsCM/Pasted image 20220628091830.png attachment/Steinemann Technology/HighsystemsCM/Pasted image 20220628091934.png attachment/Steinemann Technology/HighsystemsCM/Pasted image 20220628092034.png attachment/Steinemann Technology/HighsystemsCM/Pasted image 20220628092122.png attachment/Steinemann Technology/HighsystemsCM/Pasted image 20220628092141.png attachment/Steinemann Technology/HighsystemsCM/Pasted image 20220628092242.png attachment/Steinemann Technology/HighsystemsCM/neue Klasse erstellen.png vault auto-backup: 28.06.2022 - 09:44:00 Affected files: .obsidian/workspace Daily/28.06.22.md vault auto-backup: 28.06.2022 - 09:44:02 Affected files: Daily/28.06.22.md vault auto-backup: 28.06.2022 - 09:44:05 Affected files: Daily/28.06.22.md vault auto-backup: 28.06.2022 - 09:44:08 Affected files: Daily/28.06.22.md vault auto-backup: 28.06.2022 - 09:44:13 Affected files: Daily/28.06.22.md vault auto-backup: 28.06.2022 - 09:44:27 Affected files: .obsidian/workspace Firmen/Steinemann Technology/Dokumentation RTM.md vault auto-backup: 28.06.2022 - 09:44:30 Affected files: Firmen/Steinemann Technology/Dokumentation RTM.md vault auto-backup: 28.06.2022 - 09:44:33 Affected files: Firmen/Steinemann Technology/Dokumentation RTM.md vault auto-backup: 28.06.2022 - 09:44:36 Affected files: Firmen/Steinemann Technology/Dokumentation RTM.md vault auto-backup: 28.06.2022 - 09:44:39 Affected files: Firmen/Steinemann Technology/Dokumentation RTM.md vault auto-backup: 28.06.2022 - 09:44:45 Affected files: Firmen/Steinemann Technology/Dokumentation RTM.md vault auto-backup: 28.06.2022 - 09:48:31 Affected files: .obsidian/appearance.json Firmen/Steinemann Technology/Dokumentation RTM.md vault auto-backup: 28.06.2022 - 09:48:41 Affected files: .obsidian/workspace Firmen/Steinemann Technology/Dokumentation RTM.md vault auto-backup: 28.06.2022 - 09:49:12 Affected files: .obsidian/workspace Firmen/Steinemann Technology/Dokumentation RTM.md vault auto-backup: 28.06.2022 - 09:49:43 Affected files: .obsidian/workspace Firmen/Steinemann Technology/Dokumentation RTM.md vault auto-backup: 28.06.2022 - 09:49:46 Affected files: Firmen/Steinemann Technology/Dokumentation RTM.md vault auto-backup: 28.06.2022 - 09:49:51 Affected files: Firmen/Steinemann Technology/Dokumentation RTM.md vault auto-backup: 28.06.2022 - 09:49:53 Affected files: Firmen/Steinemann Technology/Dokumentation RTM.md vault auto-backup: 28.06.2022 - 09:49:56 Affected files: Firmen/Steinemann Technology/Dokumentation RTM.md vault auto-backup: 28.06.2022 - 09:50:19 Affected files: Firmen/Steinemann Technology/Dokumentation RTM.md vault auto-backup: 28.06.2022 - 09:51:29 Affected files: .obsidian/app.json Firmen/Steinemann Technology/Dokumentation RTM.md vault auto-backup: 28.06.2022 - 09:51:31 Affected files: Firmen/Steinemann Technology/Dokumentation RTM.md vault auto-backup: 28.06.2022 - 09:51:34 Affected files: Firmen/Steinemann Technology/Dokumentation RTM.md vault auto-backup: 28.06.2022 - 09:51:36 Affected files: Firmen/Steinemann Technology/Dokumentation RTM.md vault auto-backup: 28.06.2022 - 09:51:45 Affected files: Firmen/Steinemann Technology/Dokumentation RTM.md vault auto-backup: 28.06.2022 - 09:51:47 Affected files: Firmen/Steinemann Technology/Dokumentation RTM.md vault auto-backup: 28.06.2022 - 09:52:05 Affected files: .obsidian/workspace Highsystems Asset MGMT.md vault auto-backup: 28.06.2022 - 09:52:06 Affected files: Highsystems Asset MGMT.md vault auto-backup: 28.06.2022 - 09:54:16 Affected files: .obsidian/graph.json .obsidian/workspace Highsystems Asset MGMT.md attachment/Steinemann Technology/HighsystemsCM/Pasted image 20220628091652.png vault auto-backup: 28.06.2022 - 09:54:25 Affected files: Highsystems Asset MGMT.md vault auto-backup: 28.06.2022 - 09:54:30 Affected files: Highsystems Asset MGMT.md vault auto-backup: 28.06.2022 - 09:54:32 Affected files: Highsystems Asset MGMT.md vault auto-backup: 28.06.2022 - 09:54:38 Affected files: Highsystems Asset MGMT.md vault auto-backup: 28.06.2022 - 09:54:40 Affected files: Highsystems Asset MGMT.md vault auto-backup: 28.06.2022 - 09:54:50 Affected files: Highsystems Asset MGMT.md attachment/Steinemann Technology/HighsystemsCM/klassendefinition.png vault auto-backup: 28.06.2022 - 09:55:04 Affected files: Highsystems Asset MGMT.md attachment/Steinemann Technology/HighsystemsCM/neueFeldDefinition.png vault auto-backup: 28.06.2022 - 09:55:11 Affected files: Highsystems Asset MGMT.md vault auto-backup: 28.06.2022 - 09:55:17 Affected files: Highsystems Asset MGMT.md attachment/Steinemann Technology/HighsystemsCM/neueKlasseErstellen.png vault auto-backup: 28.06.2022 - 09:55:31 Affected files: .obsidian/workspace Highsystems Asset MGMT.md attachment/Steinemann Technology/HighsystemsCM/variablenInFelder.png vault auto-backup: 28.06.2022 - 09:56:06 Affected files: Highsystems Asset MGMT.md attachment/Steinemann Technology/HighsystemsCM/feldVerschiebung.png
3124 lines
130 KiB
JavaScript
3124 lines
130 KiB
JavaScript
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 __commonJS = (cb, mod) => function __require() {
|
|
return mod || (0, cb[Object.keys(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
|
|
};
|
|
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());
|
|
});
|
|
};
|
|
|
|
// node_modules/obsidian-daily-notes-interface/dist/main.js
|
|
var require_main = __commonJS({
|
|
"node_modules/obsidian-daily-notes-interface/dist/main.js"(exports) {
|
|
"use strict";
|
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
var obsidian = require("obsidian");
|
|
var DEFAULT_DAILY_NOTE_FORMAT = "YYYY-MM-DD";
|
|
var DEFAULT_WEEKLY_NOTE_FORMAT = "gggg-[W]ww";
|
|
var DEFAULT_MONTHLY_NOTE_FORMAT = "YYYY-MM";
|
|
var DEFAULT_QUARTERLY_NOTE_FORMAT = "YYYY-[Q]Q";
|
|
var DEFAULT_YEARLY_NOTE_FORMAT = "YYYY";
|
|
function shouldUsePeriodicNotesSettings(periodicity) {
|
|
var _a, _b;
|
|
const periodicNotes = window.app.plugins.getPlugin("periodic-notes");
|
|
return periodicNotes && ((_b = (_a = periodicNotes.settings) == null ? void 0 : _a[periodicity]) == null ? void 0 : _b.enabled);
|
|
}
|
|
function getDailyNoteSettings2() {
|
|
var _a, _b, _c, _d;
|
|
try {
|
|
const { internalPlugins, plugins } = window.app;
|
|
if (shouldUsePeriodicNotesSettings("daily")) {
|
|
const { format: format2, folder: folder2, template: template2 } = ((_b = (_a = plugins.getPlugin("periodic-notes")) == null ? void 0 : _a.settings) == null ? void 0 : _b.daily) || {};
|
|
return {
|
|
format: format2 || DEFAULT_DAILY_NOTE_FORMAT,
|
|
folder: (folder2 == null ? void 0 : folder2.trim()) || "",
|
|
template: (template2 == null ? void 0 : template2.trim()) || ""
|
|
};
|
|
}
|
|
const { folder, format, template } = ((_d = (_c = internalPlugins.getPluginById("daily-notes")) == null ? void 0 : _c.instance) == null ? void 0 : _d.options) || {};
|
|
return {
|
|
format: format || DEFAULT_DAILY_NOTE_FORMAT,
|
|
folder: (folder == null ? void 0 : folder.trim()) || "",
|
|
template: (template == null ? void 0 : template.trim()) || ""
|
|
};
|
|
} catch (err) {
|
|
console.info("No custom daily note settings found!", err);
|
|
}
|
|
}
|
|
function getWeeklyNoteSettings() {
|
|
var _a, _b, _c, _d, _e, _f, _g;
|
|
try {
|
|
const pluginManager = window.app.plugins;
|
|
const calendarSettings = (_a = pluginManager.getPlugin("calendar")) == null ? void 0 : _a.options;
|
|
const periodicNotesSettings = (_c = (_b = pluginManager.getPlugin("periodic-notes")) == null ? void 0 : _b.settings) == null ? void 0 : _c.weekly;
|
|
if (shouldUsePeriodicNotesSettings("weekly")) {
|
|
return {
|
|
format: periodicNotesSettings.format || DEFAULT_WEEKLY_NOTE_FORMAT,
|
|
folder: ((_d = periodicNotesSettings.folder) == null ? void 0 : _d.trim()) || "",
|
|
template: ((_e = periodicNotesSettings.template) == null ? void 0 : _e.trim()) || ""
|
|
};
|
|
}
|
|
const settings = calendarSettings || {};
|
|
return {
|
|
format: settings.weeklyNoteFormat || DEFAULT_WEEKLY_NOTE_FORMAT,
|
|
folder: ((_f = settings.weeklyNoteFolder) == null ? void 0 : _f.trim()) || "",
|
|
template: ((_g = settings.weeklyNoteTemplate) == null ? void 0 : _g.trim()) || ""
|
|
};
|
|
} catch (err) {
|
|
console.info("No custom weekly note settings found!", err);
|
|
}
|
|
}
|
|
function getMonthlyNoteSettings() {
|
|
var _a, _b, _c, _d;
|
|
const pluginManager = window.app.plugins;
|
|
try {
|
|
const settings = shouldUsePeriodicNotesSettings("monthly") && ((_b = (_a = pluginManager.getPlugin("periodic-notes")) == null ? void 0 : _a.settings) == null ? void 0 : _b.monthly) || {};
|
|
return {
|
|
format: settings.format || DEFAULT_MONTHLY_NOTE_FORMAT,
|
|
folder: ((_c = settings.folder) == null ? void 0 : _c.trim()) || "",
|
|
template: ((_d = settings.template) == null ? void 0 : _d.trim()) || ""
|
|
};
|
|
} catch (err) {
|
|
console.info("No custom monthly note settings found!", err);
|
|
}
|
|
}
|
|
function getQuarterlyNoteSettings() {
|
|
var _a, _b, _c, _d;
|
|
const pluginManager = window.app.plugins;
|
|
try {
|
|
const settings = shouldUsePeriodicNotesSettings("quarterly") && ((_b = (_a = pluginManager.getPlugin("periodic-notes")) == null ? void 0 : _a.settings) == null ? void 0 : _b.quarterly) || {};
|
|
return {
|
|
format: settings.format || DEFAULT_QUARTERLY_NOTE_FORMAT,
|
|
folder: ((_c = settings.folder) == null ? void 0 : _c.trim()) || "",
|
|
template: ((_d = settings.template) == null ? void 0 : _d.trim()) || ""
|
|
};
|
|
} catch (err) {
|
|
console.info("No custom quarterly note settings found!", err);
|
|
}
|
|
}
|
|
function getYearlyNoteSettings() {
|
|
var _a, _b, _c, _d;
|
|
const pluginManager = window.app.plugins;
|
|
try {
|
|
const settings = shouldUsePeriodicNotesSettings("yearly") && ((_b = (_a = pluginManager.getPlugin("periodic-notes")) == null ? void 0 : _a.settings) == null ? void 0 : _b.yearly) || {};
|
|
return {
|
|
format: settings.format || DEFAULT_YEARLY_NOTE_FORMAT,
|
|
folder: ((_c = settings.folder) == null ? void 0 : _c.trim()) || "",
|
|
template: ((_d = settings.template) == null ? void 0 : _d.trim()) || ""
|
|
};
|
|
} catch (err) {
|
|
console.info("No custom yearly note settings found!", err);
|
|
}
|
|
}
|
|
function join(...partSegments) {
|
|
let parts = [];
|
|
for (let i = 0, l = partSegments.length; i < l; i++) {
|
|
parts = parts.concat(partSegments[i].split("/"));
|
|
}
|
|
const newParts = [];
|
|
for (let i = 0, l = parts.length; i < l; i++) {
|
|
const part = parts[i];
|
|
if (!part || part === ".")
|
|
continue;
|
|
else
|
|
newParts.push(part);
|
|
}
|
|
if (parts[0] === "")
|
|
newParts.unshift("");
|
|
return newParts.join("/");
|
|
}
|
|
function basename(fullPath) {
|
|
let base = fullPath.substring(fullPath.lastIndexOf("/") + 1);
|
|
if (base.lastIndexOf(".") != -1)
|
|
base = base.substring(0, base.lastIndexOf("."));
|
|
return base;
|
|
}
|
|
function ensureFolderExists(path) {
|
|
return __async(this, null, function* () {
|
|
const dirs = path.replace(/\\/g, "/").split("/");
|
|
dirs.pop();
|
|
if (dirs.length) {
|
|
const dir = join(...dirs);
|
|
if (!window.app.vault.getAbstractFileByPath(dir)) {
|
|
yield window.app.vault.createFolder(dir);
|
|
}
|
|
}
|
|
});
|
|
}
|
|
function getNotePath(directory, filename) {
|
|
return __async(this, null, function* () {
|
|
if (!filename.endsWith(".md")) {
|
|
filename += ".md";
|
|
}
|
|
const path = obsidian.normalizePath(join(directory, filename));
|
|
yield ensureFolderExists(path);
|
|
return path;
|
|
});
|
|
}
|
|
function getTemplateInfo(template) {
|
|
return __async(this, null, function* () {
|
|
const { metadataCache, vault } = window.app;
|
|
const templatePath = obsidian.normalizePath(template);
|
|
if (templatePath === "/") {
|
|
return Promise.resolve(["", null]);
|
|
}
|
|
try {
|
|
const templateFile = metadataCache.getFirstLinkpathDest(templatePath, "");
|
|
const contents = yield vault.cachedRead(templateFile);
|
|
const IFoldInfo = window.app.foldManager.load(templateFile);
|
|
return [contents, IFoldInfo];
|
|
} catch (err) {
|
|
console.error(`Failed to read the daily note template '${templatePath}'`, err);
|
|
new obsidian.Notice("Failed to read the daily note template");
|
|
return ["", null];
|
|
}
|
|
});
|
|
}
|
|
function getDateUID(date, granularity = "day") {
|
|
const ts = date.clone().startOf(granularity).format();
|
|
return `${granularity}-${ts}`;
|
|
}
|
|
function removeEscapedCharacters(format) {
|
|
return format.replace(/\[[^\]]*\]/g, "");
|
|
}
|
|
function isFormatAmbiguous(format, granularity) {
|
|
if (granularity === "week") {
|
|
const cleanFormat = removeEscapedCharacters(format);
|
|
return /w{1,2}/i.test(cleanFormat) && (/M{1,4}/.test(cleanFormat) || /D{1,4}/.test(cleanFormat));
|
|
}
|
|
return false;
|
|
}
|
|
function getDateFromFile(file, granularity) {
|
|
return getDateFromFilename(file.basename, granularity);
|
|
}
|
|
function getDateFromPath(path, granularity) {
|
|
return getDateFromFilename(basename(path), granularity);
|
|
}
|
|
function getDateFromFilename(filename, granularity) {
|
|
const getSettings = {
|
|
day: getDailyNoteSettings2,
|
|
week: getWeeklyNoteSettings,
|
|
month: getMonthlyNoteSettings,
|
|
quarter: getQuarterlyNoteSettings,
|
|
year: getYearlyNoteSettings
|
|
};
|
|
const format = getSettings[granularity]().format.split("/").pop();
|
|
const noteDate = window.moment(filename, format, true);
|
|
if (!noteDate.isValid()) {
|
|
return null;
|
|
}
|
|
if (isFormatAmbiguous(format, granularity)) {
|
|
if (granularity === "week") {
|
|
const cleanFormat = removeEscapedCharacters(format);
|
|
if (/w{1,2}/i.test(cleanFormat)) {
|
|
return window.moment(filename, format.replace(/M{1,4}/g, "").replace(/D{1,4}/g, ""), false);
|
|
}
|
|
}
|
|
}
|
|
return noteDate;
|
|
}
|
|
var DailyNotesFolderMissingError = class extends Error {
|
|
};
|
|
function createDailyNote2(date) {
|
|
return __async(this, null, function* () {
|
|
const app2 = window.app;
|
|
const { vault } = app2;
|
|
const moment4 = window.moment;
|
|
const { template, format, folder } = getDailyNoteSettings2();
|
|
const [templateContents, IFoldInfo] = yield getTemplateInfo(template);
|
|
const filename = date.format(format);
|
|
const normalizedPath = yield getNotePath(folder, filename);
|
|
try {
|
|
const createdFile = yield vault.create(normalizedPath, templateContents.replace(/{{\s*date\s*}}/gi, filename).replace(/{{\s*time\s*}}/gi, moment4().format("HH:mm")).replace(/{{\s*title\s*}}/gi, filename).replace(/{{\s*(date|time)\s*(([+-]\d+)([yqmwdhs]))?\s*(:.+?)?}}/gi, (_, _timeOrDate, calc, timeDelta, unit, momentFormat) => {
|
|
const now = moment4();
|
|
const currentDate = date.clone().set({
|
|
hour: now.get("hour"),
|
|
minute: now.get("minute"),
|
|
second: now.get("second")
|
|
});
|
|
if (calc) {
|
|
currentDate.add(parseInt(timeDelta, 10), unit);
|
|
}
|
|
if (momentFormat) {
|
|
return currentDate.format(momentFormat.substring(1).trim());
|
|
}
|
|
return currentDate.format(format);
|
|
}).replace(/{{\s*yesterday\s*}}/gi, date.clone().subtract(1, "day").format(format)).replace(/{{\s*tomorrow\s*}}/gi, date.clone().add(1, "d").format(format)));
|
|
app2.foldManager.save(createdFile, IFoldInfo);
|
|
return createdFile;
|
|
} catch (err) {
|
|
console.error(`Failed to create file: '${normalizedPath}'`, err);
|
|
new obsidian.Notice("Unable to create new file.");
|
|
}
|
|
});
|
|
}
|
|
function getDailyNote2(date, dailyNotes) {
|
|
var _a;
|
|
return (_a = dailyNotes[getDateUID(date, "day")]) != null ? _a : null;
|
|
}
|
|
function getAllDailyNotes2() {
|
|
const { vault } = window.app;
|
|
const { folder } = getDailyNoteSettings2();
|
|
const dailyNotesFolder = vault.getAbstractFileByPath(obsidian.normalizePath(folder));
|
|
if (!dailyNotesFolder) {
|
|
throw new DailyNotesFolderMissingError("Failed to find daily notes folder");
|
|
}
|
|
const dailyNotes = {};
|
|
obsidian.Vault.recurseChildren(dailyNotesFolder, (note) => {
|
|
if (note instanceof obsidian.TFile) {
|
|
const date = getDateFromFile(note, "day");
|
|
if (date) {
|
|
const dateString = getDateUID(date, "day");
|
|
dailyNotes[dateString] = note;
|
|
}
|
|
}
|
|
});
|
|
return dailyNotes;
|
|
}
|
|
var WeeklyNotesFolderMissingError = class extends Error {
|
|
};
|
|
function getDaysOfWeek() {
|
|
const { moment: moment4 } = window;
|
|
let weekStart = moment4.localeData()._week.dow;
|
|
const daysOfWeek = [
|
|
"sunday",
|
|
"monday",
|
|
"tuesday",
|
|
"wednesday",
|
|
"thursday",
|
|
"friday",
|
|
"saturday"
|
|
];
|
|
while (weekStart) {
|
|
daysOfWeek.push(daysOfWeek.shift());
|
|
weekStart--;
|
|
}
|
|
return daysOfWeek;
|
|
}
|
|
function getDayOfWeekNumericalValue(dayOfWeekName) {
|
|
return getDaysOfWeek().indexOf(dayOfWeekName.toLowerCase());
|
|
}
|
|
function createWeeklyNote(date) {
|
|
return __async(this, null, function* () {
|
|
const { vault } = window.app;
|
|
const { template, format, folder } = getWeeklyNoteSettings();
|
|
const [templateContents, IFoldInfo] = yield getTemplateInfo(template);
|
|
const filename = date.format(format);
|
|
const normalizedPath = yield getNotePath(folder, filename);
|
|
try {
|
|
const createdFile = yield vault.create(normalizedPath, templateContents.replace(/{{\s*(date|time)\s*(([+-]\d+)([yqmwdhs]))?\s*(:.+?)?}}/gi, (_, _timeOrDate, calc, timeDelta, unit, momentFormat) => {
|
|
const now = window.moment();
|
|
const currentDate = date.clone().set({
|
|
hour: now.get("hour"),
|
|
minute: now.get("minute"),
|
|
second: now.get("second")
|
|
});
|
|
if (calc) {
|
|
currentDate.add(parseInt(timeDelta, 10), unit);
|
|
}
|
|
if (momentFormat) {
|
|
return currentDate.format(momentFormat.substring(1).trim());
|
|
}
|
|
return currentDate.format(format);
|
|
}).replace(/{{\s*title\s*}}/gi, filename).replace(/{{\s*time\s*}}/gi, window.moment().format("HH:mm")).replace(/{{\s*(sunday|monday|tuesday|wednesday|thursday|friday|saturday)\s*:(.*?)}}/gi, (_, dayOfWeek, momentFormat) => {
|
|
const day = getDayOfWeekNumericalValue(dayOfWeek);
|
|
return date.weekday(day).format(momentFormat.trim());
|
|
}));
|
|
window.app.foldManager.save(createdFile, IFoldInfo);
|
|
return createdFile;
|
|
} catch (err) {
|
|
console.error(`Failed to create file: '${normalizedPath}'`, err);
|
|
new obsidian.Notice("Unable to create new file.");
|
|
}
|
|
});
|
|
}
|
|
function getWeeklyNote(date, weeklyNotes) {
|
|
var _a;
|
|
return (_a = weeklyNotes[getDateUID(date, "week")]) != null ? _a : null;
|
|
}
|
|
function getAllWeeklyNotes() {
|
|
const weeklyNotes = {};
|
|
if (!appHasWeeklyNotesPluginLoaded()) {
|
|
return weeklyNotes;
|
|
}
|
|
const { vault } = window.app;
|
|
const { folder } = getWeeklyNoteSettings();
|
|
const weeklyNotesFolder = vault.getAbstractFileByPath(obsidian.normalizePath(folder));
|
|
if (!weeklyNotesFolder) {
|
|
throw new WeeklyNotesFolderMissingError("Failed to find weekly notes folder");
|
|
}
|
|
obsidian.Vault.recurseChildren(weeklyNotesFolder, (note) => {
|
|
if (note instanceof obsidian.TFile) {
|
|
const date = getDateFromFile(note, "week");
|
|
if (date) {
|
|
const dateString = getDateUID(date, "week");
|
|
weeklyNotes[dateString] = note;
|
|
}
|
|
}
|
|
});
|
|
return weeklyNotes;
|
|
}
|
|
var MonthlyNotesFolderMissingError = class extends Error {
|
|
};
|
|
function createMonthlyNote(date) {
|
|
return __async(this, null, function* () {
|
|
const { vault } = window.app;
|
|
const { template, format, folder } = getMonthlyNoteSettings();
|
|
const [templateContents, IFoldInfo] = yield getTemplateInfo(template);
|
|
const filename = date.format(format);
|
|
const normalizedPath = yield getNotePath(folder, filename);
|
|
try {
|
|
const createdFile = yield vault.create(normalizedPath, templateContents.replace(/{{\s*(date|time)\s*(([+-]\d+)([yqmwdhs]))?\s*(:.+?)?}}/gi, (_, _timeOrDate, calc, timeDelta, unit, momentFormat) => {
|
|
const now = window.moment();
|
|
const currentDate = date.clone().set({
|
|
hour: now.get("hour"),
|
|
minute: now.get("minute"),
|
|
second: now.get("second")
|
|
});
|
|
if (calc) {
|
|
currentDate.add(parseInt(timeDelta, 10), unit);
|
|
}
|
|
if (momentFormat) {
|
|
return currentDate.format(momentFormat.substring(1).trim());
|
|
}
|
|
return currentDate.format(format);
|
|
}).replace(/{{\s*date\s*}}/gi, filename).replace(/{{\s*time\s*}}/gi, window.moment().format("HH:mm")).replace(/{{\s*title\s*}}/gi, filename));
|
|
window.app.foldManager.save(createdFile, IFoldInfo);
|
|
return createdFile;
|
|
} catch (err) {
|
|
console.error(`Failed to create file: '${normalizedPath}'`, err);
|
|
new obsidian.Notice("Unable to create new file.");
|
|
}
|
|
});
|
|
}
|
|
function getMonthlyNote(date, monthlyNotes) {
|
|
var _a;
|
|
return (_a = monthlyNotes[getDateUID(date, "month")]) != null ? _a : null;
|
|
}
|
|
function getAllMonthlyNotes() {
|
|
const monthlyNotes = {};
|
|
if (!appHasMonthlyNotesPluginLoaded()) {
|
|
return monthlyNotes;
|
|
}
|
|
const { vault } = window.app;
|
|
const { folder } = getMonthlyNoteSettings();
|
|
const monthlyNotesFolder = vault.getAbstractFileByPath(obsidian.normalizePath(folder));
|
|
if (!monthlyNotesFolder) {
|
|
throw new MonthlyNotesFolderMissingError("Failed to find monthly notes folder");
|
|
}
|
|
obsidian.Vault.recurseChildren(monthlyNotesFolder, (note) => {
|
|
if (note instanceof obsidian.TFile) {
|
|
const date = getDateFromFile(note, "month");
|
|
if (date) {
|
|
const dateString = getDateUID(date, "month");
|
|
monthlyNotes[dateString] = note;
|
|
}
|
|
}
|
|
});
|
|
return monthlyNotes;
|
|
}
|
|
var QuarterlyNotesFolderMissingError = class extends Error {
|
|
};
|
|
function createQuarterlyNote(date) {
|
|
return __async(this, null, function* () {
|
|
const { vault } = window.app;
|
|
const { template, format, folder } = getQuarterlyNoteSettings();
|
|
const [templateContents, IFoldInfo] = yield getTemplateInfo(template);
|
|
const filename = date.format(format);
|
|
const normalizedPath = yield getNotePath(folder, filename);
|
|
try {
|
|
const createdFile = yield vault.create(normalizedPath, templateContents.replace(/{{\s*(date|time)\s*(([+-]\d+)([yqmwdhs]))?\s*(:.+?)?}}/gi, (_, _timeOrDate, calc, timeDelta, unit, momentFormat) => {
|
|
const now = window.moment();
|
|
const currentDate = date.clone().set({
|
|
hour: now.get("hour"),
|
|
minute: now.get("minute"),
|
|
second: now.get("second")
|
|
});
|
|
if (calc) {
|
|
currentDate.add(parseInt(timeDelta, 10), unit);
|
|
}
|
|
if (momentFormat) {
|
|
return currentDate.format(momentFormat.substring(1).trim());
|
|
}
|
|
return currentDate.format(format);
|
|
}).replace(/{{\s*date\s*}}/gi, filename).replace(/{{\s*time\s*}}/gi, window.moment().format("HH:mm")).replace(/{{\s*title\s*}}/gi, filename));
|
|
window.app.foldManager.save(createdFile, IFoldInfo);
|
|
return createdFile;
|
|
} catch (err) {
|
|
console.error(`Failed to create file: '${normalizedPath}'`, err);
|
|
new obsidian.Notice("Unable to create new file.");
|
|
}
|
|
});
|
|
}
|
|
function getQuarterlyNote(date, quarterly) {
|
|
var _a;
|
|
return (_a = quarterly[getDateUID(date, "quarter")]) != null ? _a : null;
|
|
}
|
|
function getAllQuarterlyNotes() {
|
|
const quarterly = {};
|
|
if (!appHasQuarterlyNotesPluginLoaded()) {
|
|
return quarterly;
|
|
}
|
|
const { vault } = window.app;
|
|
const { folder } = getQuarterlyNoteSettings();
|
|
const quarterlyFolder = vault.getAbstractFileByPath(obsidian.normalizePath(folder));
|
|
if (!quarterlyFolder) {
|
|
throw new QuarterlyNotesFolderMissingError("Failed to find quarterly notes folder");
|
|
}
|
|
obsidian.Vault.recurseChildren(quarterlyFolder, (note) => {
|
|
if (note instanceof obsidian.TFile) {
|
|
const date = getDateFromFile(note, "quarter");
|
|
if (date) {
|
|
const dateString = getDateUID(date, "quarter");
|
|
quarterly[dateString] = note;
|
|
}
|
|
}
|
|
});
|
|
return quarterly;
|
|
}
|
|
var YearlyNotesFolderMissingError = class extends Error {
|
|
};
|
|
function createYearlyNote(date) {
|
|
return __async(this, null, function* () {
|
|
const { vault } = window.app;
|
|
const { template, format, folder } = getYearlyNoteSettings();
|
|
const [templateContents, IFoldInfo] = yield getTemplateInfo(template);
|
|
const filename = date.format(format);
|
|
const normalizedPath = yield getNotePath(folder, filename);
|
|
try {
|
|
const createdFile = yield vault.create(normalizedPath, templateContents.replace(/{{\s*(date|time)\s*(([+-]\d+)([yqmwdhs]))?\s*(:.+?)?}}/gi, (_, _timeOrDate, calc, timeDelta, unit, momentFormat) => {
|
|
const now = window.moment();
|
|
const currentDate = date.clone().set({
|
|
hour: now.get("hour"),
|
|
minute: now.get("minute"),
|
|
second: now.get("second")
|
|
});
|
|
if (calc) {
|
|
currentDate.add(parseInt(timeDelta, 10), unit);
|
|
}
|
|
if (momentFormat) {
|
|
return currentDate.format(momentFormat.substring(1).trim());
|
|
}
|
|
return currentDate.format(format);
|
|
}).replace(/{{\s*date\s*}}/gi, filename).replace(/{{\s*time\s*}}/gi, window.moment().format("HH:mm")).replace(/{{\s*title\s*}}/gi, filename));
|
|
window.app.foldManager.save(createdFile, IFoldInfo);
|
|
return createdFile;
|
|
} catch (err) {
|
|
console.error(`Failed to create file: '${normalizedPath}'`, err);
|
|
new obsidian.Notice("Unable to create new file.");
|
|
}
|
|
});
|
|
}
|
|
function getYearlyNote(date, yearlyNotes) {
|
|
var _a;
|
|
return (_a = yearlyNotes[getDateUID(date, "year")]) != null ? _a : null;
|
|
}
|
|
function getAllYearlyNotes() {
|
|
const yearlyNotes = {};
|
|
if (!appHasYearlyNotesPluginLoaded()) {
|
|
return yearlyNotes;
|
|
}
|
|
const { vault } = window.app;
|
|
const { folder } = getYearlyNoteSettings();
|
|
const yearlyNotesFolder = vault.getAbstractFileByPath(obsidian.normalizePath(folder));
|
|
if (!yearlyNotesFolder) {
|
|
throw new YearlyNotesFolderMissingError("Failed to find yearly notes folder");
|
|
}
|
|
obsidian.Vault.recurseChildren(yearlyNotesFolder, (note) => {
|
|
if (note instanceof obsidian.TFile) {
|
|
const date = getDateFromFile(note, "year");
|
|
if (date) {
|
|
const dateString = getDateUID(date, "year");
|
|
yearlyNotes[dateString] = note;
|
|
}
|
|
}
|
|
});
|
|
return yearlyNotes;
|
|
}
|
|
function appHasDailyNotesPluginLoaded() {
|
|
var _a, _b;
|
|
const { app: app2 } = window;
|
|
const dailyNotesPlugin = app2.internalPlugins.plugins["daily-notes"];
|
|
if (dailyNotesPlugin && dailyNotesPlugin.enabled) {
|
|
return true;
|
|
}
|
|
const periodicNotes = app2.plugins.getPlugin("periodic-notes");
|
|
return periodicNotes && ((_b = (_a = periodicNotes.settings) == null ? void 0 : _a.daily) == null ? void 0 : _b.enabled);
|
|
}
|
|
function appHasWeeklyNotesPluginLoaded() {
|
|
var _a, _b;
|
|
const { app: app2 } = window;
|
|
if (app2.plugins.getPlugin("calendar")) {
|
|
return true;
|
|
}
|
|
const periodicNotes = app2.plugins.getPlugin("periodic-notes");
|
|
return periodicNotes && ((_b = (_a = periodicNotes.settings) == null ? void 0 : _a.weekly) == null ? void 0 : _b.enabled);
|
|
}
|
|
function appHasMonthlyNotesPluginLoaded() {
|
|
var _a, _b;
|
|
const { app: app2 } = window;
|
|
const periodicNotes = app2.plugins.getPlugin("periodic-notes");
|
|
return periodicNotes && ((_b = (_a = periodicNotes.settings) == null ? void 0 : _a.monthly) == null ? void 0 : _b.enabled);
|
|
}
|
|
function appHasQuarterlyNotesPluginLoaded() {
|
|
var _a, _b;
|
|
const { app: app2 } = window;
|
|
const periodicNotes = app2.plugins.getPlugin("periodic-notes");
|
|
return periodicNotes && ((_b = (_a = periodicNotes.settings) == null ? void 0 : _a.quarterly) == null ? void 0 : _b.enabled);
|
|
}
|
|
function appHasYearlyNotesPluginLoaded() {
|
|
var _a, _b;
|
|
const { app: app2 } = window;
|
|
const periodicNotes = app2.plugins.getPlugin("periodic-notes");
|
|
return periodicNotes && ((_b = (_a = periodicNotes.settings) == null ? void 0 : _a.yearly) == null ? void 0 : _b.enabled);
|
|
}
|
|
function getPeriodicNoteSettings(granularity) {
|
|
const getSettings = {
|
|
day: getDailyNoteSettings2,
|
|
week: getWeeklyNoteSettings,
|
|
month: getMonthlyNoteSettings,
|
|
quarter: getQuarterlyNoteSettings,
|
|
year: getYearlyNoteSettings
|
|
}[granularity];
|
|
return getSettings();
|
|
}
|
|
function createPeriodicNote(granularity, date) {
|
|
const createFn = {
|
|
day: createDailyNote2,
|
|
month: createMonthlyNote,
|
|
week: createWeeklyNote
|
|
};
|
|
return createFn[granularity](date);
|
|
}
|
|
exports.DEFAULT_DAILY_NOTE_FORMAT = DEFAULT_DAILY_NOTE_FORMAT;
|
|
exports.DEFAULT_MONTHLY_NOTE_FORMAT = DEFAULT_MONTHLY_NOTE_FORMAT;
|
|
exports.DEFAULT_QUARTERLY_NOTE_FORMAT = DEFAULT_QUARTERLY_NOTE_FORMAT;
|
|
exports.DEFAULT_WEEKLY_NOTE_FORMAT = DEFAULT_WEEKLY_NOTE_FORMAT;
|
|
exports.DEFAULT_YEARLY_NOTE_FORMAT = DEFAULT_YEARLY_NOTE_FORMAT;
|
|
exports.appHasDailyNotesPluginLoaded = appHasDailyNotesPluginLoaded;
|
|
exports.appHasMonthlyNotesPluginLoaded = appHasMonthlyNotesPluginLoaded;
|
|
exports.appHasQuarterlyNotesPluginLoaded = appHasQuarterlyNotesPluginLoaded;
|
|
exports.appHasWeeklyNotesPluginLoaded = appHasWeeklyNotesPluginLoaded;
|
|
exports.appHasYearlyNotesPluginLoaded = appHasYearlyNotesPluginLoaded;
|
|
exports.createDailyNote = createDailyNote2;
|
|
exports.createMonthlyNote = createMonthlyNote;
|
|
exports.createPeriodicNote = createPeriodicNote;
|
|
exports.createQuarterlyNote = createQuarterlyNote;
|
|
exports.createWeeklyNote = createWeeklyNote;
|
|
exports.createYearlyNote = createYearlyNote;
|
|
exports.getAllDailyNotes = getAllDailyNotes2;
|
|
exports.getAllMonthlyNotes = getAllMonthlyNotes;
|
|
exports.getAllQuarterlyNotes = getAllQuarterlyNotes;
|
|
exports.getAllWeeklyNotes = getAllWeeklyNotes;
|
|
exports.getAllYearlyNotes = getAllYearlyNotes;
|
|
exports.getDailyNote = getDailyNote2;
|
|
exports.getDailyNoteSettings = getDailyNoteSettings2;
|
|
exports.getDateFromFile = getDateFromFile;
|
|
exports.getDateFromPath = getDateFromPath;
|
|
exports.getDateUID = getDateUID;
|
|
exports.getMonthlyNote = getMonthlyNote;
|
|
exports.getMonthlyNoteSettings = getMonthlyNoteSettings;
|
|
exports.getPeriodicNoteSettings = getPeriodicNoteSettings;
|
|
exports.getQuarterlyNote = getQuarterlyNote;
|
|
exports.getQuarterlyNoteSettings = getQuarterlyNoteSettings;
|
|
exports.getTemplateInfo = getTemplateInfo;
|
|
exports.getWeeklyNote = getWeeklyNote;
|
|
exports.getWeeklyNoteSettings = getWeeklyNoteSettings;
|
|
exports.getYearlyNote = getYearlyNote;
|
|
exports.getYearlyNoteSettings = getYearlyNoteSettings;
|
|
}
|
|
});
|
|
|
|
// src/main.ts
|
|
__export(exports, {
|
|
default: () => ThePlugin
|
|
});
|
|
var import_obsidian6 = __toModule(require("obsidian"));
|
|
var import_obsidian_daily_notes_interface2 = __toModule(require_main());
|
|
|
|
// src/icons.ts
|
|
var import_obsidian = __toModule(require("obsidian"));
|
|
function addIcons() {
|
|
(0, import_obsidian.addIcon)("JumpToDate", `<path fill="currentColor" stroke="currentColor" d="M 36.445312 55.1875 C 36.445312 53.933594 35.429688 52.917969 34.175781 52.917969 L 26.25 52.917969 C 25 52.917969 23.984375 53.933594 23.984375 55.1875 L 23.984375 63.109375 C 23.984375 64.363281 25 65.378906 26.25 65.378906 L 34.175781 65.378906 C 35.429688 65.378906 36.445312 64.363281 36.445312 63.109375 Z M 36.445312 55.1875 "/>
|
|
<path fill="currentColor" stroke="currentColor" d="M 56.246094 55.1875 C 56.246094 53.933594 55.230469 52.917969 53.976562 52.917969 L 46.054688 52.917969 C 44.800781 52.917969 43.785156 53.933594 43.785156 55.1875 L 43.785156 63.109375 C 43.785156 64.363281 44.800781 65.378906 46.054688 65.378906 L 53.976562 65.378906 C 55.230469 65.378906 56.246094 64.363281 56.246094 63.109375 Z M 56.246094 55.1875 "/>
|
|
<path fill="currentColor" stroke="currentColor" d="M 76.046875 55.1875 C 76.046875 53.933594 75.03125 52.917969 73.78125 52.917969 L 65.855469 52.917969 C 64.601562 52.917969 63.585938 53.933594 63.585938 55.1875 L 63.585938 63.109375 C 63.585938 64.363281 64.601562 65.378906 65.855469 65.378906 L 73.78125 65.378906 C 75.03125 65.378906 76.046875 64.363281 76.046875 63.109375 Z M 76.046875 55.1875 "/>
|
|
<path fill="currentColor" stroke="currentColor" d="M 36.445312 74.988281 C 36.445312 73.734375 35.429688 72.71875 34.175781 72.71875 L 26.25 72.71875 C 25 72.71875 23.984375 73.734375 23.984375 74.988281 L 23.984375 82.910156 C 23.984375 84.164062 25 85.179688 26.25 85.179688 L 34.175781 85.179688 C 35.429688 85.179688 36.445312 84.164062 36.445312 82.910156 Z M 36.445312 74.988281 "/>
|
|
<path fill="currentColor" stroke="currentColor" d="M 56.246094 74.988281 C 56.246094 73.734375 55.230469 72.71875 53.976562 72.71875 L 46.054688 72.71875 C 44.800781 72.71875 43.785156 73.734375 43.785156 74.988281 L 43.785156 82.910156 C 43.785156 84.164062 44.800781 85.179688 46.054688 85.179688 L 53.976562 85.179688 C 55.230469 85.179688 56.246094 84.164062 56.246094 82.910156 Z M 56.246094 74.988281 "/>
|
|
<path fill="currentColor" stroke="currentColor" d="M 76.046875 74.988281 C 76.046875 73.734375 75.03125 72.71875 73.78125 72.71875 L 65.855469 72.71875 C 64.601562 72.71875 63.585938 73.734375 63.585938 74.988281 L 63.585938 82.910156 C 63.585938 84.164062 64.601562 85.179688 65.855469 85.179688 L 73.78125 85.179688 C 75.03125 85.179688 76.046875 84.164062 76.046875 82.910156 Z M 76.046875 74.988281 "/>
|
|
<path fill="currentColor" stroke="currentColor" d="M 90.214844 11.136719 L 90.214844 23.238281 C 90.214844 28.707031 85.777344 33.113281 80.3125 33.113281 L 74.0625 33.113281 C 68.59375 33.113281 64.097656 28.707031 64.097656 23.238281 L 64.097656 11.09375 L 35.933594 11.09375 L 35.933594 23.238281 C 35.933594 28.707031 31.4375 33.113281 25.96875 33.113281 L 19.71875 33.113281 C 14.253906 33.113281 9.816406 28.707031 9.816406 23.238281 L 9.816406 11.136719 C 5.035156 11.28125 1.109375 15.238281 1.109375 20.097656 L 1.109375 91.011719 C 1.109375 95.964844 5.121094 100.03125 10.074219 100.03125 L 89.957031 100.03125 C 94.902344 100.03125 98.921875 95.957031 98.921875 91.011719 L 98.921875 20.097656 C 98.921875 15.238281 94.996094 11.28125 90.214844 11.136719 Z M 87.3125 86.597656 C 87.3125 88.734375 85.578125 90.472656 83.4375 90.472656 L 16.421875 90.472656 C 14.28125 90.472656 12.546875 88.734375 12.546875 86.597656 L 12.546875 49.964844 C 12.546875 47.824219 14.28125 46.089844 16.421875 46.089844 L 83.4375 46.089844 C 85.578125 46.089844 87.3125 47.824219 87.3125 49.964844 Z M 87.3125 86.597656 "/>
|
|
<path fill="currentColor" stroke="currentColor" d="M 19.699219 26.628906 L 25.878906 26.628906 C 27.753906 26.628906 29.277344 25.109375 29.277344 23.234375 L 29.277344 3.394531 C 29.277344 1.519531 27.753906 0 25.878906 0 L 19.699219 0 C 17.820312 0 16.300781 1.519531 16.300781 3.394531 L 16.300781 23.234375 C 16.300781 25.109375 17.820312 26.628906 19.699219 26.628906 Z M 19.699219 26.628906 "/>
|
|
<path fill="currentColor" stroke="currentColor" d="M 73.984375 26.628906 L 80.164062 26.628906 C 82.039062 26.628906 83.558594 25.109375 83.558594 23.234375 L 83.558594 3.394531 C 83.558594 1.519531 82.039062 0 80.164062 0 L 73.984375 0 C 72.105469 0 70.585938 1.519531 70.585938 3.394531 L 70.585938 23.234375 C 70.585938 25.109375 72.105469 26.628906 73.984375 26.628906 Z M 73.984375 26.628906 "/>`);
|
|
}
|
|
|
|
// src/ui/settings.ts
|
|
var import_obsidian2 = __toModule(require("obsidian"));
|
|
var DEFAULT_SETTINGS = {
|
|
enableRibbon: true,
|
|
shouldConfirmBeforeCreate: false,
|
|
firstDayOfWeekIsSunday: true
|
|
};
|
|
var SettingsTab = class extends import_obsidian2.PluginSettingTab {
|
|
constructor(app2, plugin) {
|
|
super(app2, plugin);
|
|
this.plugin = plugin;
|
|
}
|
|
display() {
|
|
const { containerEl } = this;
|
|
containerEl.empty();
|
|
containerEl.createEl("h2", { text: "Obsidian42 - Jump-to-Date Setting" });
|
|
new import_obsidian2.Setting(containerEl).setName("Enable Calendar Popup").setDesc("Toggle on and off the Jump-to-Date button in the ribbon and command palette. If this is disabled, the Natural Language Date feature is still available in the command palette").addToggle((cb) => {
|
|
cb.setValue(this.plugin.settings.enableRibbon);
|
|
cb.onChange((value) => __async(this, null, function* () {
|
|
this.plugin.settings.enableRibbon = value;
|
|
if (this.plugin.settings.enableRibbon === false)
|
|
this.plugin.ribbonIcon.remove();
|
|
else
|
|
this.plugin.showRibbonButton();
|
|
yield this.plugin.saveSettings();
|
|
}));
|
|
});
|
|
new import_obsidian2.Setting(containerEl).setName("Confirm before creating new note").setDesc("Show a confirmation modal before creating a new note.").addToggle((cb) => {
|
|
cb.setValue(this.plugin.settings.shouldConfirmBeforeCreate);
|
|
cb.onChange((value) => __async(this, null, function* () {
|
|
this.plugin.settings.shouldConfirmBeforeCreate = value;
|
|
yield this.plugin.saveSettings();
|
|
}));
|
|
});
|
|
new import_obsidian2.Setting(containerEl).setName("First day of the week on calendar is Sunday").setDesc("If toggled on the calendar will show the week starting with Sunday. If toggled off, it will show Monday as the starting day.").addToggle((cb) => {
|
|
cb.setValue(this.plugin.settings.firstDayOfWeekIsSunday);
|
|
cb.onChange((value) => __async(this, null, function* () {
|
|
this.plugin.settings.firstDayOfWeekIsSunday = value;
|
|
}));
|
|
});
|
|
}
|
|
};
|
|
|
|
// node_modules/flatpickr/dist/esm/types/options.js
|
|
var HOOKS = [
|
|
"onChange",
|
|
"onClose",
|
|
"onDayCreate",
|
|
"onDestroy",
|
|
"onKeyDown",
|
|
"onMonthChange",
|
|
"onOpen",
|
|
"onParseConfig",
|
|
"onReady",
|
|
"onValueUpdate",
|
|
"onYearChange",
|
|
"onPreCalendarPosition"
|
|
];
|
|
var defaults = {
|
|
_disable: [],
|
|
allowInput: false,
|
|
allowInvalidPreload: false,
|
|
altFormat: "F j, Y",
|
|
altInput: false,
|
|
altInputClass: "form-control input",
|
|
animate: typeof window === "object" && window.navigator.userAgent.indexOf("MSIE") === -1,
|
|
ariaDateFormat: "F j, Y",
|
|
autoFillDefaultTime: true,
|
|
clickOpens: true,
|
|
closeOnSelect: true,
|
|
conjunction: ", ",
|
|
dateFormat: "Y-m-d",
|
|
defaultHour: 12,
|
|
defaultMinute: 0,
|
|
defaultSeconds: 0,
|
|
disable: [],
|
|
disableMobile: false,
|
|
enableSeconds: false,
|
|
enableTime: false,
|
|
errorHandler: (err) => typeof console !== "undefined" && console.warn(err),
|
|
getWeek: (givenDate) => {
|
|
const date = new Date(givenDate.getTime());
|
|
date.setHours(0, 0, 0, 0);
|
|
date.setDate(date.getDate() + 3 - (date.getDay() + 6) % 7);
|
|
var week1 = new Date(date.getFullYear(), 0, 4);
|
|
return 1 + Math.round(((date.getTime() - week1.getTime()) / 864e5 - 3 + (week1.getDay() + 6) % 7) / 7);
|
|
},
|
|
hourIncrement: 1,
|
|
ignoredFocusElements: [],
|
|
inline: false,
|
|
locale: "default",
|
|
minuteIncrement: 5,
|
|
mode: "single",
|
|
monthSelectorType: "dropdown",
|
|
nextArrow: "<svg version='1.1' xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink' viewBox='0 0 17 17'><g></g><path d='M13.207 8.472l-7.854 7.854-0.707-0.707 7.146-7.146-7.146-7.148 0.707-0.707 7.854 7.854z' /></svg>",
|
|
noCalendar: false,
|
|
now: new Date(),
|
|
onChange: [],
|
|
onClose: [],
|
|
onDayCreate: [],
|
|
onDestroy: [],
|
|
onKeyDown: [],
|
|
onMonthChange: [],
|
|
onOpen: [],
|
|
onParseConfig: [],
|
|
onReady: [],
|
|
onValueUpdate: [],
|
|
onYearChange: [],
|
|
onPreCalendarPosition: [],
|
|
plugins: [],
|
|
position: "auto",
|
|
positionElement: void 0,
|
|
prevArrow: "<svg version='1.1' xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink' viewBox='0 0 17 17'><g></g><path d='M5.207 8.471l7.146 7.147-0.707 0.707-7.853-7.854 7.854-7.853 0.707 0.707-7.147 7.146z' /></svg>",
|
|
shorthandCurrentMonth: false,
|
|
showMonths: 1,
|
|
static: false,
|
|
time_24hr: false,
|
|
weekNumbers: false,
|
|
wrap: false
|
|
};
|
|
|
|
// node_modules/flatpickr/dist/esm/l10n/default.js
|
|
var english = {
|
|
weekdays: {
|
|
shorthand: ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"],
|
|
longhand: [
|
|
"Sunday",
|
|
"Monday",
|
|
"Tuesday",
|
|
"Wednesday",
|
|
"Thursday",
|
|
"Friday",
|
|
"Saturday"
|
|
]
|
|
},
|
|
months: {
|
|
shorthand: [
|
|
"Jan",
|
|
"Feb",
|
|
"Mar",
|
|
"Apr",
|
|
"May",
|
|
"Jun",
|
|
"Jul",
|
|
"Aug",
|
|
"Sep",
|
|
"Oct",
|
|
"Nov",
|
|
"Dec"
|
|
],
|
|
longhand: [
|
|
"January",
|
|
"February",
|
|
"March",
|
|
"April",
|
|
"May",
|
|
"June",
|
|
"July",
|
|
"August",
|
|
"September",
|
|
"October",
|
|
"November",
|
|
"December"
|
|
]
|
|
},
|
|
daysInMonth: [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31],
|
|
firstDayOfWeek: 0,
|
|
ordinal: (nth) => {
|
|
const s = nth % 100;
|
|
if (s > 3 && s < 21)
|
|
return "th";
|
|
switch (s % 10) {
|
|
case 1:
|
|
return "st";
|
|
case 2:
|
|
return "nd";
|
|
case 3:
|
|
return "rd";
|
|
default:
|
|
return "th";
|
|
}
|
|
},
|
|
rangeSeparator: " to ",
|
|
weekAbbreviation: "Wk",
|
|
scrollTitle: "Scroll to increment",
|
|
toggleTitle: "Click to toggle",
|
|
amPM: ["AM", "PM"],
|
|
yearAriaLabel: "Year",
|
|
monthAriaLabel: "Month",
|
|
hourAriaLabel: "Hour",
|
|
minuteAriaLabel: "Minute",
|
|
time_24hr: false
|
|
};
|
|
var default_default = english;
|
|
|
|
// node_modules/flatpickr/dist/esm/utils/index.js
|
|
var pad = (number, length = 2) => `000${number}`.slice(length * -1);
|
|
var int = (bool) => bool === true ? 1 : 0;
|
|
function debounce(fn, wait) {
|
|
let t;
|
|
return function() {
|
|
clearTimeout(t);
|
|
t = setTimeout(() => fn.apply(this, arguments), wait);
|
|
};
|
|
}
|
|
var arrayify = (obj) => obj instanceof Array ? obj : [obj];
|
|
|
|
// node_modules/flatpickr/dist/esm/utils/dom.js
|
|
function toggleClass(elem, className, bool) {
|
|
if (bool === true)
|
|
return elem.classList.add(className);
|
|
elem.classList.remove(className);
|
|
}
|
|
function createElement(tag, className, content) {
|
|
const e = window.document.createElement(tag);
|
|
className = className || "";
|
|
content = content || "";
|
|
e.className = className;
|
|
if (content !== void 0)
|
|
e.textContent = content;
|
|
return e;
|
|
}
|
|
function clearNode(node) {
|
|
while (node.firstChild)
|
|
node.removeChild(node.firstChild);
|
|
}
|
|
function findParent(node, condition) {
|
|
if (condition(node))
|
|
return node;
|
|
else if (node.parentNode)
|
|
return findParent(node.parentNode, condition);
|
|
return void 0;
|
|
}
|
|
function createNumberInput(inputClassName, opts) {
|
|
const wrapper = createElement("div", "numInputWrapper"), numInput = createElement("input", "numInput " + inputClassName), arrowUp = createElement("span", "arrowUp"), arrowDown = createElement("span", "arrowDown");
|
|
if (navigator.userAgent.indexOf("MSIE 9.0") === -1) {
|
|
numInput.type = "number";
|
|
} else {
|
|
numInput.type = "text";
|
|
numInput.pattern = "\\d*";
|
|
}
|
|
if (opts !== void 0)
|
|
for (const key in opts)
|
|
numInput.setAttribute(key, opts[key]);
|
|
wrapper.appendChild(numInput);
|
|
wrapper.appendChild(arrowUp);
|
|
wrapper.appendChild(arrowDown);
|
|
return wrapper;
|
|
}
|
|
function getEventTarget(event) {
|
|
try {
|
|
if (typeof event.composedPath === "function") {
|
|
const path = event.composedPath();
|
|
return path[0];
|
|
}
|
|
return event.target;
|
|
} catch (error) {
|
|
return event.target;
|
|
}
|
|
}
|
|
|
|
// node_modules/flatpickr/dist/esm/utils/formatting.js
|
|
var doNothing = () => void 0;
|
|
var monthToStr = (monthNumber, shorthand, locale) => locale.months[shorthand ? "shorthand" : "longhand"][monthNumber];
|
|
var revFormat = {
|
|
D: doNothing,
|
|
F: function(dateObj, monthName, locale) {
|
|
dateObj.setMonth(locale.months.longhand.indexOf(monthName));
|
|
},
|
|
G: (dateObj, hour) => {
|
|
dateObj.setHours(parseFloat(hour));
|
|
},
|
|
H: (dateObj, hour) => {
|
|
dateObj.setHours(parseFloat(hour));
|
|
},
|
|
J: (dateObj, day) => {
|
|
dateObj.setDate(parseFloat(day));
|
|
},
|
|
K: (dateObj, amPM, locale) => {
|
|
dateObj.setHours(dateObj.getHours() % 12 + 12 * int(new RegExp(locale.amPM[1], "i").test(amPM)));
|
|
},
|
|
M: function(dateObj, shortMonth, locale) {
|
|
dateObj.setMonth(locale.months.shorthand.indexOf(shortMonth));
|
|
},
|
|
S: (dateObj, seconds) => {
|
|
dateObj.setSeconds(parseFloat(seconds));
|
|
},
|
|
U: (_, unixSeconds) => new Date(parseFloat(unixSeconds) * 1e3),
|
|
W: function(dateObj, weekNum, locale) {
|
|
const weekNumber = parseInt(weekNum);
|
|
const date = new Date(dateObj.getFullYear(), 0, 2 + (weekNumber - 1) * 7, 0, 0, 0, 0);
|
|
date.setDate(date.getDate() - date.getDay() + locale.firstDayOfWeek);
|
|
return date;
|
|
},
|
|
Y: (dateObj, year) => {
|
|
dateObj.setFullYear(parseFloat(year));
|
|
},
|
|
Z: (_, ISODate) => new Date(ISODate),
|
|
d: (dateObj, day) => {
|
|
dateObj.setDate(parseFloat(day));
|
|
},
|
|
h: (dateObj, hour) => {
|
|
dateObj.setHours(parseFloat(hour));
|
|
},
|
|
i: (dateObj, minutes) => {
|
|
dateObj.setMinutes(parseFloat(minutes));
|
|
},
|
|
j: (dateObj, day) => {
|
|
dateObj.setDate(parseFloat(day));
|
|
},
|
|
l: doNothing,
|
|
m: (dateObj, month) => {
|
|
dateObj.setMonth(parseFloat(month) - 1);
|
|
},
|
|
n: (dateObj, month) => {
|
|
dateObj.setMonth(parseFloat(month) - 1);
|
|
},
|
|
s: (dateObj, seconds) => {
|
|
dateObj.setSeconds(parseFloat(seconds));
|
|
},
|
|
u: (_, unixMillSeconds) => new Date(parseFloat(unixMillSeconds)),
|
|
w: doNothing,
|
|
y: (dateObj, year) => {
|
|
dateObj.setFullYear(2e3 + parseFloat(year));
|
|
}
|
|
};
|
|
var tokenRegex = {
|
|
D: "(\\w+)",
|
|
F: "(\\w+)",
|
|
G: "(\\d\\d|\\d)",
|
|
H: "(\\d\\d|\\d)",
|
|
J: "(\\d\\d|\\d)\\w+",
|
|
K: "",
|
|
M: "(\\w+)",
|
|
S: "(\\d\\d|\\d)",
|
|
U: "(.+)",
|
|
W: "(\\d\\d|\\d)",
|
|
Y: "(\\d{4})",
|
|
Z: "(.+)",
|
|
d: "(\\d\\d|\\d)",
|
|
h: "(\\d\\d|\\d)",
|
|
i: "(\\d\\d|\\d)",
|
|
j: "(\\d\\d|\\d)",
|
|
l: "(\\w+)",
|
|
m: "(\\d\\d|\\d)",
|
|
n: "(\\d\\d|\\d)",
|
|
s: "(\\d\\d|\\d)",
|
|
u: "(.+)",
|
|
w: "(\\d\\d|\\d)",
|
|
y: "(\\d{2})"
|
|
};
|
|
var formats = {
|
|
Z: (date) => date.toISOString(),
|
|
D: function(date, locale, options) {
|
|
return locale.weekdays.shorthand[formats.w(date, locale, options)];
|
|
},
|
|
F: function(date, locale, options) {
|
|
return monthToStr(formats.n(date, locale, options) - 1, false, locale);
|
|
},
|
|
G: function(date, locale, options) {
|
|
return pad(formats.h(date, locale, options));
|
|
},
|
|
H: (date) => pad(date.getHours()),
|
|
J: function(date, locale) {
|
|
return locale.ordinal !== void 0 ? date.getDate() + locale.ordinal(date.getDate()) : date.getDate();
|
|
},
|
|
K: (date, locale) => locale.amPM[int(date.getHours() > 11)],
|
|
M: function(date, locale) {
|
|
return monthToStr(date.getMonth(), true, locale);
|
|
},
|
|
S: (date) => pad(date.getSeconds()),
|
|
U: (date) => date.getTime() / 1e3,
|
|
W: function(date, _, options) {
|
|
return options.getWeek(date);
|
|
},
|
|
Y: (date) => pad(date.getFullYear(), 4),
|
|
d: (date) => pad(date.getDate()),
|
|
h: (date) => date.getHours() % 12 ? date.getHours() % 12 : 12,
|
|
i: (date) => pad(date.getMinutes()),
|
|
j: (date) => date.getDate(),
|
|
l: function(date, locale) {
|
|
return locale.weekdays.longhand[date.getDay()];
|
|
},
|
|
m: (date) => pad(date.getMonth() + 1),
|
|
n: (date) => date.getMonth() + 1,
|
|
s: (date) => date.getSeconds(),
|
|
u: (date) => date.getTime(),
|
|
w: (date) => date.getDay(),
|
|
y: (date) => String(date.getFullYear()).substring(2)
|
|
};
|
|
|
|
// node_modules/flatpickr/dist/esm/utils/dates.js
|
|
var createDateFormatter = ({ config = defaults, l10n = english, isMobile = false }) => (dateObj, frmt, overrideLocale) => {
|
|
const locale = overrideLocale || l10n;
|
|
if (config.formatDate !== void 0 && !isMobile) {
|
|
return config.formatDate(dateObj, frmt, locale);
|
|
}
|
|
return frmt.split("").map((c, i, arr) => formats[c] && arr[i - 1] !== "\\" ? formats[c](dateObj, locale, config) : c !== "\\" ? c : "").join("");
|
|
};
|
|
var createDateParser = ({ config = defaults, l10n = english }) => (date, givenFormat, timeless, customLocale) => {
|
|
if (date !== 0 && !date)
|
|
return void 0;
|
|
const locale = customLocale || l10n;
|
|
let parsedDate;
|
|
const dateOrig = date;
|
|
if (date instanceof Date)
|
|
parsedDate = new Date(date.getTime());
|
|
else if (typeof date !== "string" && date.toFixed !== void 0)
|
|
parsedDate = new Date(date);
|
|
else if (typeof date === "string") {
|
|
const format = givenFormat || (config || defaults).dateFormat;
|
|
const datestr = String(date).trim();
|
|
if (datestr === "today") {
|
|
parsedDate = new Date();
|
|
timeless = true;
|
|
} else if (/Z$/.test(datestr) || /GMT$/.test(datestr))
|
|
parsedDate = new Date(date);
|
|
else if (config && config.parseDate)
|
|
parsedDate = config.parseDate(date, format);
|
|
else {
|
|
parsedDate = !config || !config.noCalendar ? new Date(new Date().getFullYear(), 0, 1, 0, 0, 0, 0) : new Date(new Date().setHours(0, 0, 0, 0));
|
|
let matched, ops = [];
|
|
for (let i = 0, matchIndex = 0, regexStr = ""; i < format.length; i++) {
|
|
const token = format[i];
|
|
const isBackSlash = token === "\\";
|
|
const escaped = format[i - 1] === "\\" || isBackSlash;
|
|
if (tokenRegex[token] && !escaped) {
|
|
regexStr += tokenRegex[token];
|
|
const match = new RegExp(regexStr).exec(date);
|
|
if (match && (matched = true)) {
|
|
ops[token !== "Y" ? "push" : "unshift"]({
|
|
fn: revFormat[token],
|
|
val: match[++matchIndex]
|
|
});
|
|
}
|
|
} else if (!isBackSlash)
|
|
regexStr += ".";
|
|
ops.forEach(({ fn, val }) => parsedDate = fn(parsedDate, val, locale) || parsedDate);
|
|
}
|
|
parsedDate = matched ? parsedDate : void 0;
|
|
}
|
|
}
|
|
if (!(parsedDate instanceof Date && !isNaN(parsedDate.getTime()))) {
|
|
config.errorHandler(new Error(`Invalid date provided: ${dateOrig}`));
|
|
return void 0;
|
|
}
|
|
if (timeless === true)
|
|
parsedDate.setHours(0, 0, 0, 0);
|
|
return parsedDate;
|
|
};
|
|
function compareDates(date1, date2, timeless = true) {
|
|
if (timeless !== false) {
|
|
return new Date(date1.getTime()).setHours(0, 0, 0, 0) - new Date(date2.getTime()).setHours(0, 0, 0, 0);
|
|
}
|
|
return date1.getTime() - date2.getTime();
|
|
}
|
|
var isBetween = (ts, ts1, ts2) => {
|
|
return ts > Math.min(ts1, ts2) && ts < Math.max(ts1, ts2);
|
|
};
|
|
var duration = {
|
|
DAY: 864e5
|
|
};
|
|
function getDefaultHours(config) {
|
|
let hours = config.defaultHour;
|
|
let minutes = config.defaultMinute;
|
|
let seconds = config.defaultSeconds;
|
|
if (config.minDate !== void 0) {
|
|
const minHour = config.minDate.getHours();
|
|
const minMinutes = config.minDate.getMinutes();
|
|
const minSeconds = config.minDate.getSeconds();
|
|
if (hours < minHour) {
|
|
hours = minHour;
|
|
}
|
|
if (hours === minHour && minutes < minMinutes) {
|
|
minutes = minMinutes;
|
|
}
|
|
if (hours === minHour && minutes === minMinutes && seconds < minSeconds)
|
|
seconds = config.minDate.getSeconds();
|
|
}
|
|
if (config.maxDate !== void 0) {
|
|
const maxHr = config.maxDate.getHours();
|
|
const maxMinutes = config.maxDate.getMinutes();
|
|
hours = Math.min(hours, maxHr);
|
|
if (hours === maxHr)
|
|
minutes = Math.min(maxMinutes, minutes);
|
|
if (hours === maxHr && minutes === maxMinutes)
|
|
seconds = config.maxDate.getSeconds();
|
|
}
|
|
return { hours, minutes, seconds };
|
|
}
|
|
|
|
// node_modules/flatpickr/dist/esm/utils/polyfills.js
|
|
"use strict";
|
|
if (typeof Object.assign !== "function") {
|
|
Object.assign = function(target, ...args) {
|
|
if (!target) {
|
|
throw TypeError("Cannot convert undefined or null to object");
|
|
}
|
|
for (const source of args) {
|
|
if (source) {
|
|
Object.keys(source).forEach((key) => target[key] = source[key]);
|
|
}
|
|
}
|
|
return target;
|
|
};
|
|
}
|
|
|
|
// node_modules/flatpickr/dist/esm/index.js
|
|
var DEBOUNCED_CHANGE_MS = 300;
|
|
function FlatpickrInstance(element, instanceConfig) {
|
|
const self = {
|
|
config: Object.assign(Object.assign({}, defaults), flatpickr.defaultConfig),
|
|
l10n: default_default
|
|
};
|
|
self.parseDate = createDateParser({ config: self.config, l10n: self.l10n });
|
|
self._handlers = [];
|
|
self.pluginElements = [];
|
|
self.loadedPlugins = [];
|
|
self._bind = bind;
|
|
self._setHoursFromDate = setHoursFromDate;
|
|
self._positionCalendar = positionCalendar;
|
|
self.changeMonth = changeMonth;
|
|
self.changeYear = changeYear;
|
|
self.clear = clear;
|
|
self.close = close;
|
|
self._createElement = createElement;
|
|
self.destroy = destroy;
|
|
self.isEnabled = isEnabled;
|
|
self.jumpToDate = jumpToDate;
|
|
self.open = open;
|
|
self.redraw = redraw;
|
|
self.set = set;
|
|
self.setDate = setDate;
|
|
self.toggle = toggle;
|
|
function setupHelperFunctions() {
|
|
self.utils = {
|
|
getDaysInMonth(month = self.currentMonth, yr = self.currentYear) {
|
|
if (month === 1 && (yr % 4 === 0 && yr % 100 !== 0 || yr % 400 === 0))
|
|
return 29;
|
|
return self.l10n.daysInMonth[month];
|
|
}
|
|
};
|
|
}
|
|
function init() {
|
|
self.element = self.input = element;
|
|
self.isOpen = false;
|
|
parseConfig();
|
|
setupLocale();
|
|
setupInputs();
|
|
setupDates();
|
|
setupHelperFunctions();
|
|
if (!self.isMobile)
|
|
build();
|
|
bindEvents();
|
|
if (self.selectedDates.length || self.config.noCalendar) {
|
|
if (self.config.enableTime) {
|
|
setHoursFromDate(self.config.noCalendar ? self.latestSelectedDateObj : void 0);
|
|
}
|
|
updateValue(false);
|
|
}
|
|
setCalendarWidth();
|
|
const isSafari = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
|
|
if (!self.isMobile && isSafari) {
|
|
positionCalendar();
|
|
}
|
|
triggerEvent("onReady");
|
|
}
|
|
function bindToInstance(fn) {
|
|
return fn.bind(self);
|
|
}
|
|
function setCalendarWidth() {
|
|
const config = self.config;
|
|
if (config.weekNumbers === false && config.showMonths === 1) {
|
|
return;
|
|
} else if (config.noCalendar !== true) {
|
|
window.requestAnimationFrame(function() {
|
|
if (self.calendarContainer !== void 0) {
|
|
self.calendarContainer.style.visibility = "hidden";
|
|
self.calendarContainer.style.display = "block";
|
|
}
|
|
if (self.daysContainer !== void 0) {
|
|
const daysWidth = (self.days.offsetWidth + 1) * config.showMonths;
|
|
self.daysContainer.style.width = daysWidth + "px";
|
|
self.calendarContainer.style.width = daysWidth + (self.weekWrapper !== void 0 ? self.weekWrapper.offsetWidth : 0) + "px";
|
|
self.calendarContainer.style.removeProperty("visibility");
|
|
self.calendarContainer.style.removeProperty("display");
|
|
}
|
|
});
|
|
}
|
|
}
|
|
function updateTime(e) {
|
|
if (self.selectedDates.length === 0) {
|
|
const defaultDate = self.config.minDate === void 0 || compareDates(new Date(), self.config.minDate) >= 0 ? new Date() : new Date(self.config.minDate.getTime());
|
|
const defaults2 = getDefaultHours(self.config);
|
|
defaultDate.setHours(defaults2.hours, defaults2.minutes, defaults2.seconds, defaultDate.getMilliseconds());
|
|
self.selectedDates = [defaultDate];
|
|
self.latestSelectedDateObj = defaultDate;
|
|
}
|
|
if (e !== void 0 && e.type !== "blur") {
|
|
timeWrapper(e);
|
|
}
|
|
const prevValue = self._input.value;
|
|
setHoursFromInputs();
|
|
updateValue();
|
|
if (self._input.value !== prevValue) {
|
|
self._debouncedChange();
|
|
}
|
|
}
|
|
function ampm2military(hour, amPM) {
|
|
return hour % 12 + 12 * int(amPM === self.l10n.amPM[1]);
|
|
}
|
|
function military2ampm(hour) {
|
|
switch (hour % 24) {
|
|
case 0:
|
|
case 12:
|
|
return 12;
|
|
default:
|
|
return hour % 12;
|
|
}
|
|
}
|
|
function setHoursFromInputs() {
|
|
if (self.hourElement === void 0 || self.minuteElement === void 0)
|
|
return;
|
|
let hours = (parseInt(self.hourElement.value.slice(-2), 10) || 0) % 24, minutes = (parseInt(self.minuteElement.value, 10) || 0) % 60, seconds = self.secondElement !== void 0 ? (parseInt(self.secondElement.value, 10) || 0) % 60 : 0;
|
|
if (self.amPM !== void 0) {
|
|
hours = ampm2military(hours, self.amPM.textContent);
|
|
}
|
|
const limitMinHours = self.config.minTime !== void 0 || self.config.minDate && self.minDateHasTime && self.latestSelectedDateObj && compareDates(self.latestSelectedDateObj, self.config.minDate, true) === 0;
|
|
const limitMaxHours = self.config.maxTime !== void 0 || self.config.maxDate && self.maxDateHasTime && self.latestSelectedDateObj && compareDates(self.latestSelectedDateObj, self.config.maxDate, true) === 0;
|
|
if (limitMaxHours) {
|
|
const maxTime = self.config.maxTime !== void 0 ? self.config.maxTime : self.config.maxDate;
|
|
hours = Math.min(hours, maxTime.getHours());
|
|
if (hours === maxTime.getHours())
|
|
minutes = Math.min(minutes, maxTime.getMinutes());
|
|
if (minutes === maxTime.getMinutes())
|
|
seconds = Math.min(seconds, maxTime.getSeconds());
|
|
}
|
|
if (limitMinHours) {
|
|
const minTime = self.config.minTime !== void 0 ? self.config.minTime : self.config.minDate;
|
|
hours = Math.max(hours, minTime.getHours());
|
|
if (hours === minTime.getHours() && minutes < minTime.getMinutes())
|
|
minutes = minTime.getMinutes();
|
|
if (minutes === minTime.getMinutes())
|
|
seconds = Math.max(seconds, minTime.getSeconds());
|
|
}
|
|
setHours(hours, minutes, seconds);
|
|
}
|
|
function setHoursFromDate(dateObj) {
|
|
const date = dateObj || self.latestSelectedDateObj;
|
|
if (date) {
|
|
setHours(date.getHours(), date.getMinutes(), date.getSeconds());
|
|
}
|
|
}
|
|
function setHours(hours, minutes, seconds) {
|
|
if (self.latestSelectedDateObj !== void 0) {
|
|
self.latestSelectedDateObj.setHours(hours % 24, minutes, seconds || 0, 0);
|
|
}
|
|
if (!self.hourElement || !self.minuteElement || self.isMobile)
|
|
return;
|
|
self.hourElement.value = pad(!self.config.time_24hr ? (12 + hours) % 12 + 12 * int(hours % 12 === 0) : hours);
|
|
self.minuteElement.value = pad(minutes);
|
|
if (self.amPM !== void 0)
|
|
self.amPM.textContent = self.l10n.amPM[int(hours >= 12)];
|
|
if (self.secondElement !== void 0)
|
|
self.secondElement.value = pad(seconds);
|
|
}
|
|
function onYearInput(event) {
|
|
const eventTarget = getEventTarget(event);
|
|
const year = parseInt(eventTarget.value) + (event.delta || 0);
|
|
if (year / 1e3 > 1 || event.key === "Enter" && !/[^\d]/.test(year.toString())) {
|
|
changeYear(year);
|
|
}
|
|
}
|
|
function bind(element2, event, handler, options) {
|
|
if (event instanceof Array)
|
|
return event.forEach((ev) => bind(element2, ev, handler, options));
|
|
if (element2 instanceof Array)
|
|
return element2.forEach((el) => bind(el, event, handler, options));
|
|
element2.addEventListener(event, handler, options);
|
|
self._handlers.push({
|
|
remove: () => element2.removeEventListener(event, handler)
|
|
});
|
|
}
|
|
function triggerChange() {
|
|
triggerEvent("onChange");
|
|
}
|
|
function bindEvents() {
|
|
if (self.config.wrap) {
|
|
["open", "close", "toggle", "clear"].forEach((evt) => {
|
|
Array.prototype.forEach.call(self.element.querySelectorAll(`[data-${evt}]`), (el) => bind(el, "click", self[evt]));
|
|
});
|
|
}
|
|
if (self.isMobile) {
|
|
setupMobile();
|
|
return;
|
|
}
|
|
const debouncedResize = debounce(onResize, 50);
|
|
self._debouncedChange = debounce(triggerChange, DEBOUNCED_CHANGE_MS);
|
|
if (self.daysContainer && !/iPhone|iPad|iPod/i.test(navigator.userAgent))
|
|
bind(self.daysContainer, "mouseover", (e) => {
|
|
if (self.config.mode === "range")
|
|
onMouseOver(getEventTarget(e));
|
|
});
|
|
bind(window.document.body, "keydown", onKeyDown);
|
|
if (!self.config.inline && !self.config.static)
|
|
bind(window, "resize", debouncedResize);
|
|
if (window.ontouchstart !== void 0)
|
|
bind(window.document, "touchstart", documentClick);
|
|
else
|
|
bind(window.document, "mousedown", documentClick);
|
|
bind(window.document, "focus", documentClick, { capture: true });
|
|
if (self.config.clickOpens === true) {
|
|
bind(self._input, "focus", self.open);
|
|
bind(self._input, "click", self.open);
|
|
}
|
|
if (self.daysContainer !== void 0) {
|
|
bind(self.monthNav, "click", onMonthNavClick);
|
|
bind(self.monthNav, ["keyup", "increment"], onYearInput);
|
|
bind(self.daysContainer, "click", selectDate);
|
|
}
|
|
if (self.timeContainer !== void 0 && self.minuteElement !== void 0 && self.hourElement !== void 0) {
|
|
const selText = (e) => getEventTarget(e).select();
|
|
bind(self.timeContainer, ["increment"], updateTime);
|
|
bind(self.timeContainer, "blur", updateTime, { capture: true });
|
|
bind(self.timeContainer, "click", timeIncrement);
|
|
bind([self.hourElement, self.minuteElement], ["focus", "click"], selText);
|
|
if (self.secondElement !== void 0)
|
|
bind(self.secondElement, "focus", () => self.secondElement && self.secondElement.select());
|
|
if (self.amPM !== void 0) {
|
|
bind(self.amPM, "click", (e) => {
|
|
updateTime(e);
|
|
triggerChange();
|
|
});
|
|
}
|
|
}
|
|
if (self.config.allowInput) {
|
|
bind(self._input, "blur", onBlur);
|
|
}
|
|
}
|
|
function jumpToDate(jumpDate, triggerChange2) {
|
|
const jumpTo = jumpDate !== void 0 ? self.parseDate(jumpDate) : self.latestSelectedDateObj || (self.config.minDate && self.config.minDate > self.now ? self.config.minDate : self.config.maxDate && self.config.maxDate < self.now ? self.config.maxDate : self.now);
|
|
const oldYear = self.currentYear;
|
|
const oldMonth = self.currentMonth;
|
|
try {
|
|
if (jumpTo !== void 0) {
|
|
self.currentYear = jumpTo.getFullYear();
|
|
self.currentMonth = jumpTo.getMonth();
|
|
}
|
|
} catch (e) {
|
|
e.message = "Invalid date supplied: " + jumpTo;
|
|
self.config.errorHandler(e);
|
|
}
|
|
if (triggerChange2 && self.currentYear !== oldYear) {
|
|
triggerEvent("onYearChange");
|
|
buildMonthSwitch();
|
|
}
|
|
if (triggerChange2 && (self.currentYear !== oldYear || self.currentMonth !== oldMonth)) {
|
|
triggerEvent("onMonthChange");
|
|
}
|
|
self.redraw();
|
|
}
|
|
function timeIncrement(e) {
|
|
const eventTarget = getEventTarget(e);
|
|
if (~eventTarget.className.indexOf("arrow"))
|
|
incrementNumInput(e, eventTarget.classList.contains("arrowUp") ? 1 : -1);
|
|
}
|
|
function incrementNumInput(e, delta, inputElem) {
|
|
const target = e && getEventTarget(e);
|
|
const input = inputElem || target && target.parentNode && target.parentNode.firstChild;
|
|
const event = createEvent("increment");
|
|
event.delta = delta;
|
|
input && input.dispatchEvent(event);
|
|
}
|
|
function build() {
|
|
const fragment = window.document.createDocumentFragment();
|
|
self.calendarContainer = createElement("div", "flatpickr-calendar");
|
|
self.calendarContainer.tabIndex = -1;
|
|
if (!self.config.noCalendar) {
|
|
fragment.appendChild(buildMonthNav());
|
|
self.innerContainer = createElement("div", "flatpickr-innerContainer");
|
|
if (self.config.weekNumbers) {
|
|
const { weekWrapper, weekNumbers } = buildWeeks();
|
|
self.innerContainer.appendChild(weekWrapper);
|
|
self.weekNumbers = weekNumbers;
|
|
self.weekWrapper = weekWrapper;
|
|
}
|
|
self.rContainer = createElement("div", "flatpickr-rContainer");
|
|
self.rContainer.appendChild(buildWeekdays());
|
|
if (!self.daysContainer) {
|
|
self.daysContainer = createElement("div", "flatpickr-days");
|
|
self.daysContainer.tabIndex = -1;
|
|
}
|
|
buildDays();
|
|
self.rContainer.appendChild(self.daysContainer);
|
|
self.innerContainer.appendChild(self.rContainer);
|
|
fragment.appendChild(self.innerContainer);
|
|
}
|
|
if (self.config.enableTime) {
|
|
fragment.appendChild(buildTime());
|
|
}
|
|
toggleClass(self.calendarContainer, "rangeMode", self.config.mode === "range");
|
|
toggleClass(self.calendarContainer, "animate", self.config.animate === true);
|
|
toggleClass(self.calendarContainer, "multiMonth", self.config.showMonths > 1);
|
|
self.calendarContainer.appendChild(fragment);
|
|
const customAppend = self.config.appendTo !== void 0 && self.config.appendTo.nodeType !== void 0;
|
|
if (self.config.inline || self.config.static) {
|
|
self.calendarContainer.classList.add(self.config.inline ? "inline" : "static");
|
|
if (self.config.inline) {
|
|
if (!customAppend && self.element.parentNode)
|
|
self.element.parentNode.insertBefore(self.calendarContainer, self._input.nextSibling);
|
|
else if (self.config.appendTo !== void 0)
|
|
self.config.appendTo.appendChild(self.calendarContainer);
|
|
}
|
|
if (self.config.static) {
|
|
const wrapper = createElement("div", "flatpickr-wrapper");
|
|
if (self.element.parentNode)
|
|
self.element.parentNode.insertBefore(wrapper, self.element);
|
|
wrapper.appendChild(self.element);
|
|
if (self.altInput)
|
|
wrapper.appendChild(self.altInput);
|
|
wrapper.appendChild(self.calendarContainer);
|
|
}
|
|
}
|
|
if (!self.config.static && !self.config.inline)
|
|
(self.config.appendTo !== void 0 ? self.config.appendTo : window.document.body).appendChild(self.calendarContainer);
|
|
}
|
|
function createDay(className, date, dayNumber, i) {
|
|
const dateIsEnabled = isEnabled(date, true), dayElement = createElement("span", "flatpickr-day " + className, date.getDate().toString());
|
|
dayElement.dateObj = date;
|
|
dayElement.$i = i;
|
|
dayElement.setAttribute("aria-label", self.formatDate(date, self.config.ariaDateFormat));
|
|
if (className.indexOf("hidden") === -1 && compareDates(date, self.now) === 0) {
|
|
self.todayDateElem = dayElement;
|
|
dayElement.classList.add("today");
|
|
dayElement.setAttribute("aria-current", "date");
|
|
}
|
|
if (dateIsEnabled) {
|
|
dayElement.tabIndex = -1;
|
|
if (isDateSelected(date)) {
|
|
dayElement.classList.add("selected");
|
|
self.selectedDateElem = dayElement;
|
|
if (self.config.mode === "range") {
|
|
toggleClass(dayElement, "startRange", self.selectedDates[0] && compareDates(date, self.selectedDates[0], true) === 0);
|
|
toggleClass(dayElement, "endRange", self.selectedDates[1] && compareDates(date, self.selectedDates[1], true) === 0);
|
|
if (className === "nextMonthDay")
|
|
dayElement.classList.add("inRange");
|
|
}
|
|
}
|
|
} else {
|
|
dayElement.classList.add("flatpickr-disabled");
|
|
}
|
|
if (self.config.mode === "range") {
|
|
if (isDateInRange(date) && !isDateSelected(date))
|
|
dayElement.classList.add("inRange");
|
|
}
|
|
if (self.weekNumbers && self.config.showMonths === 1 && className !== "prevMonthDay" && dayNumber % 7 === 1) {
|
|
self.weekNumbers.insertAdjacentHTML("beforeend", "<span class='flatpickr-day'>" + self.config.getWeek(date) + "</span>");
|
|
}
|
|
triggerEvent("onDayCreate", dayElement);
|
|
return dayElement;
|
|
}
|
|
function focusOnDayElem(targetNode) {
|
|
targetNode.focus();
|
|
if (self.config.mode === "range")
|
|
onMouseOver(targetNode);
|
|
}
|
|
function getFirstAvailableDay(delta) {
|
|
const startMonth = delta > 0 ? 0 : self.config.showMonths - 1;
|
|
const endMonth = delta > 0 ? self.config.showMonths : -1;
|
|
for (let m = startMonth; m != endMonth; m += delta) {
|
|
const month = self.daysContainer.children[m];
|
|
const startIndex = delta > 0 ? 0 : month.children.length - 1;
|
|
const endIndex = delta > 0 ? month.children.length : -1;
|
|
for (let i = startIndex; i != endIndex; i += delta) {
|
|
const c = month.children[i];
|
|
if (c.className.indexOf("hidden") === -1 && isEnabled(c.dateObj))
|
|
return c;
|
|
}
|
|
}
|
|
return void 0;
|
|
}
|
|
function getNextAvailableDay(current, delta) {
|
|
const givenMonth = current.className.indexOf("Month") === -1 ? current.dateObj.getMonth() : self.currentMonth;
|
|
const endMonth = delta > 0 ? self.config.showMonths : -1;
|
|
const loopDelta = delta > 0 ? 1 : -1;
|
|
for (let m = givenMonth - self.currentMonth; m != endMonth; m += loopDelta) {
|
|
const month = self.daysContainer.children[m];
|
|
const startIndex = givenMonth - self.currentMonth === m ? current.$i + delta : delta < 0 ? month.children.length - 1 : 0;
|
|
const numMonthDays = month.children.length;
|
|
for (let i = startIndex; i >= 0 && i < numMonthDays && i != (delta > 0 ? numMonthDays : -1); i += loopDelta) {
|
|
const c = month.children[i];
|
|
if (c.className.indexOf("hidden") === -1 && isEnabled(c.dateObj) && Math.abs(current.$i - i) >= Math.abs(delta))
|
|
return focusOnDayElem(c);
|
|
}
|
|
}
|
|
self.changeMonth(loopDelta);
|
|
focusOnDay(getFirstAvailableDay(loopDelta), 0);
|
|
return void 0;
|
|
}
|
|
function focusOnDay(current, offset) {
|
|
const dayFocused = isInView(document.activeElement || document.body);
|
|
const startElem = current !== void 0 ? current : dayFocused ? document.activeElement : self.selectedDateElem !== void 0 && isInView(self.selectedDateElem) ? self.selectedDateElem : self.todayDateElem !== void 0 && isInView(self.todayDateElem) ? self.todayDateElem : getFirstAvailableDay(offset > 0 ? 1 : -1);
|
|
if (startElem === void 0) {
|
|
self._input.focus();
|
|
} else if (!dayFocused) {
|
|
focusOnDayElem(startElem);
|
|
} else {
|
|
getNextAvailableDay(startElem, offset);
|
|
}
|
|
}
|
|
function buildMonthDays(year, month) {
|
|
const firstOfMonth = (new Date(year, month, 1).getDay() - self.l10n.firstDayOfWeek + 7) % 7;
|
|
const prevMonthDays = self.utils.getDaysInMonth((month - 1 + 12) % 12, year);
|
|
const daysInMonth = self.utils.getDaysInMonth(month, year), days = window.document.createDocumentFragment(), isMultiMonth = self.config.showMonths > 1, prevMonthDayClass = isMultiMonth ? "prevMonthDay hidden" : "prevMonthDay", nextMonthDayClass = isMultiMonth ? "nextMonthDay hidden" : "nextMonthDay";
|
|
let dayNumber = prevMonthDays + 1 - firstOfMonth, dayIndex = 0;
|
|
for (; dayNumber <= prevMonthDays; dayNumber++, dayIndex++) {
|
|
days.appendChild(createDay(prevMonthDayClass, new Date(year, month - 1, dayNumber), dayNumber, dayIndex));
|
|
}
|
|
for (dayNumber = 1; dayNumber <= daysInMonth; dayNumber++, dayIndex++) {
|
|
days.appendChild(createDay("", new Date(year, month, dayNumber), dayNumber, dayIndex));
|
|
}
|
|
for (let dayNum = daysInMonth + 1; dayNum <= 42 - firstOfMonth && (self.config.showMonths === 1 || dayIndex % 7 !== 0); dayNum++, dayIndex++) {
|
|
days.appendChild(createDay(nextMonthDayClass, new Date(year, month + 1, dayNum % daysInMonth), dayNum, dayIndex));
|
|
}
|
|
const dayContainer = createElement("div", "dayContainer");
|
|
dayContainer.appendChild(days);
|
|
return dayContainer;
|
|
}
|
|
function buildDays() {
|
|
if (self.daysContainer === void 0) {
|
|
return;
|
|
}
|
|
clearNode(self.daysContainer);
|
|
if (self.weekNumbers)
|
|
clearNode(self.weekNumbers);
|
|
const frag = document.createDocumentFragment();
|
|
for (let i = 0; i < self.config.showMonths; i++) {
|
|
const d = new Date(self.currentYear, self.currentMonth, 1);
|
|
d.setMonth(self.currentMonth + i);
|
|
frag.appendChild(buildMonthDays(d.getFullYear(), d.getMonth()));
|
|
}
|
|
self.daysContainer.appendChild(frag);
|
|
self.days = self.daysContainer.firstChild;
|
|
if (self.config.mode === "range" && self.selectedDates.length === 1) {
|
|
onMouseOver();
|
|
}
|
|
}
|
|
function buildMonthSwitch() {
|
|
if (self.config.showMonths > 1 || self.config.monthSelectorType !== "dropdown")
|
|
return;
|
|
const shouldBuildMonth = function(month) {
|
|
if (self.config.minDate !== void 0 && self.currentYear === self.config.minDate.getFullYear() && month < self.config.minDate.getMonth()) {
|
|
return false;
|
|
}
|
|
return !(self.config.maxDate !== void 0 && self.currentYear === self.config.maxDate.getFullYear() && month > self.config.maxDate.getMonth());
|
|
};
|
|
self.monthsDropdownContainer.tabIndex = -1;
|
|
self.monthsDropdownContainer.innerHTML = "";
|
|
for (let i = 0; i < 12; i++) {
|
|
if (!shouldBuildMonth(i))
|
|
continue;
|
|
const month = createElement("option", "flatpickr-monthDropdown-month");
|
|
month.value = new Date(self.currentYear, i).getMonth().toString();
|
|
month.textContent = monthToStr(i, self.config.shorthandCurrentMonth, self.l10n);
|
|
month.tabIndex = -1;
|
|
if (self.currentMonth === i) {
|
|
month.selected = true;
|
|
}
|
|
self.monthsDropdownContainer.appendChild(month);
|
|
}
|
|
}
|
|
function buildMonth() {
|
|
const container = createElement("div", "flatpickr-month");
|
|
const monthNavFragment = window.document.createDocumentFragment();
|
|
let monthElement;
|
|
if (self.config.showMonths > 1 || self.config.monthSelectorType === "static") {
|
|
monthElement = createElement("span", "cur-month");
|
|
} else {
|
|
self.monthsDropdownContainer = createElement("select", "flatpickr-monthDropdown-months");
|
|
self.monthsDropdownContainer.setAttribute("aria-label", self.l10n.monthAriaLabel);
|
|
bind(self.monthsDropdownContainer, "change", (e) => {
|
|
const target = getEventTarget(e);
|
|
const selectedMonth = parseInt(target.value, 10);
|
|
self.changeMonth(selectedMonth - self.currentMonth);
|
|
triggerEvent("onMonthChange");
|
|
});
|
|
buildMonthSwitch();
|
|
monthElement = self.monthsDropdownContainer;
|
|
}
|
|
const yearInput = createNumberInput("cur-year", { tabindex: "-1" });
|
|
const yearElement = yearInput.getElementsByTagName("input")[0];
|
|
yearElement.setAttribute("aria-label", self.l10n.yearAriaLabel);
|
|
if (self.config.minDate) {
|
|
yearElement.setAttribute("min", self.config.minDate.getFullYear().toString());
|
|
}
|
|
if (self.config.maxDate) {
|
|
yearElement.setAttribute("max", self.config.maxDate.getFullYear().toString());
|
|
yearElement.disabled = !!self.config.minDate && self.config.minDate.getFullYear() === self.config.maxDate.getFullYear();
|
|
}
|
|
const currentMonth = createElement("div", "flatpickr-current-month");
|
|
currentMonth.appendChild(monthElement);
|
|
currentMonth.appendChild(yearInput);
|
|
monthNavFragment.appendChild(currentMonth);
|
|
container.appendChild(monthNavFragment);
|
|
return {
|
|
container,
|
|
yearElement,
|
|
monthElement
|
|
};
|
|
}
|
|
function buildMonths() {
|
|
clearNode(self.monthNav);
|
|
self.monthNav.appendChild(self.prevMonthNav);
|
|
if (self.config.showMonths) {
|
|
self.yearElements = [];
|
|
self.monthElements = [];
|
|
}
|
|
for (let m = self.config.showMonths; m--; ) {
|
|
const month = buildMonth();
|
|
self.yearElements.push(month.yearElement);
|
|
self.monthElements.push(month.monthElement);
|
|
self.monthNav.appendChild(month.container);
|
|
}
|
|
self.monthNav.appendChild(self.nextMonthNav);
|
|
}
|
|
function buildMonthNav() {
|
|
self.monthNav = createElement("div", "flatpickr-months");
|
|
self.yearElements = [];
|
|
self.monthElements = [];
|
|
self.prevMonthNav = createElement("span", "flatpickr-prev-month");
|
|
self.prevMonthNav.innerHTML = self.config.prevArrow;
|
|
self.nextMonthNav = createElement("span", "flatpickr-next-month");
|
|
self.nextMonthNav.innerHTML = self.config.nextArrow;
|
|
buildMonths();
|
|
Object.defineProperty(self, "_hidePrevMonthArrow", {
|
|
get: () => self.__hidePrevMonthArrow,
|
|
set(bool) {
|
|
if (self.__hidePrevMonthArrow !== bool) {
|
|
toggleClass(self.prevMonthNav, "flatpickr-disabled", bool);
|
|
self.__hidePrevMonthArrow = bool;
|
|
}
|
|
}
|
|
});
|
|
Object.defineProperty(self, "_hideNextMonthArrow", {
|
|
get: () => self.__hideNextMonthArrow,
|
|
set(bool) {
|
|
if (self.__hideNextMonthArrow !== bool) {
|
|
toggleClass(self.nextMonthNav, "flatpickr-disabled", bool);
|
|
self.__hideNextMonthArrow = bool;
|
|
}
|
|
}
|
|
});
|
|
self.currentYearElement = self.yearElements[0];
|
|
updateNavigationCurrentMonth();
|
|
return self.monthNav;
|
|
}
|
|
function buildTime() {
|
|
self.calendarContainer.classList.add("hasTime");
|
|
if (self.config.noCalendar)
|
|
self.calendarContainer.classList.add("noCalendar");
|
|
const defaults2 = getDefaultHours(self.config);
|
|
self.timeContainer = createElement("div", "flatpickr-time");
|
|
self.timeContainer.tabIndex = -1;
|
|
const separator = createElement("span", "flatpickr-time-separator", ":");
|
|
const hourInput = createNumberInput("flatpickr-hour", {
|
|
"aria-label": self.l10n.hourAriaLabel
|
|
});
|
|
self.hourElement = hourInput.getElementsByTagName("input")[0];
|
|
const minuteInput = createNumberInput("flatpickr-minute", {
|
|
"aria-label": self.l10n.minuteAriaLabel
|
|
});
|
|
self.minuteElement = minuteInput.getElementsByTagName("input")[0];
|
|
self.hourElement.tabIndex = self.minuteElement.tabIndex = -1;
|
|
self.hourElement.value = pad(self.latestSelectedDateObj ? self.latestSelectedDateObj.getHours() : self.config.time_24hr ? defaults2.hours : military2ampm(defaults2.hours));
|
|
self.minuteElement.value = pad(self.latestSelectedDateObj ? self.latestSelectedDateObj.getMinutes() : defaults2.minutes);
|
|
self.hourElement.setAttribute("step", self.config.hourIncrement.toString());
|
|
self.minuteElement.setAttribute("step", self.config.minuteIncrement.toString());
|
|
self.hourElement.setAttribute("min", self.config.time_24hr ? "0" : "1");
|
|
self.hourElement.setAttribute("max", self.config.time_24hr ? "23" : "12");
|
|
self.hourElement.setAttribute("maxlength", "2");
|
|
self.minuteElement.setAttribute("min", "0");
|
|
self.minuteElement.setAttribute("max", "59");
|
|
self.minuteElement.setAttribute("maxlength", "2");
|
|
self.timeContainer.appendChild(hourInput);
|
|
self.timeContainer.appendChild(separator);
|
|
self.timeContainer.appendChild(minuteInput);
|
|
if (self.config.time_24hr)
|
|
self.timeContainer.classList.add("time24hr");
|
|
if (self.config.enableSeconds) {
|
|
self.timeContainer.classList.add("hasSeconds");
|
|
const secondInput = createNumberInput("flatpickr-second");
|
|
self.secondElement = secondInput.getElementsByTagName("input")[0];
|
|
self.secondElement.value = pad(self.latestSelectedDateObj ? self.latestSelectedDateObj.getSeconds() : defaults2.seconds);
|
|
self.secondElement.setAttribute("step", self.minuteElement.getAttribute("step"));
|
|
self.secondElement.setAttribute("min", "0");
|
|
self.secondElement.setAttribute("max", "59");
|
|
self.secondElement.setAttribute("maxlength", "2");
|
|
self.timeContainer.appendChild(createElement("span", "flatpickr-time-separator", ":"));
|
|
self.timeContainer.appendChild(secondInput);
|
|
}
|
|
if (!self.config.time_24hr) {
|
|
self.amPM = createElement("span", "flatpickr-am-pm", self.l10n.amPM[int((self.latestSelectedDateObj ? self.hourElement.value : self.config.defaultHour) > 11)]);
|
|
self.amPM.title = self.l10n.toggleTitle;
|
|
self.amPM.tabIndex = -1;
|
|
self.timeContainer.appendChild(self.amPM);
|
|
}
|
|
return self.timeContainer;
|
|
}
|
|
function buildWeekdays() {
|
|
if (!self.weekdayContainer)
|
|
self.weekdayContainer = createElement("div", "flatpickr-weekdays");
|
|
else
|
|
clearNode(self.weekdayContainer);
|
|
for (let i = self.config.showMonths; i--; ) {
|
|
const container = createElement("div", "flatpickr-weekdaycontainer");
|
|
self.weekdayContainer.appendChild(container);
|
|
}
|
|
updateWeekdays();
|
|
return self.weekdayContainer;
|
|
}
|
|
function updateWeekdays() {
|
|
if (!self.weekdayContainer) {
|
|
return;
|
|
}
|
|
const firstDayOfWeek = self.l10n.firstDayOfWeek;
|
|
let weekdays = [...self.l10n.weekdays.shorthand];
|
|
if (firstDayOfWeek > 0 && firstDayOfWeek < weekdays.length) {
|
|
weekdays = [
|
|
...weekdays.splice(firstDayOfWeek, weekdays.length),
|
|
...weekdays.splice(0, firstDayOfWeek)
|
|
];
|
|
}
|
|
for (let i = self.config.showMonths; i--; ) {
|
|
self.weekdayContainer.children[i].innerHTML = `
|
|
<span class='flatpickr-weekday'>
|
|
${weekdays.join("</span><span class='flatpickr-weekday'>")}
|
|
</span>
|
|
`;
|
|
}
|
|
}
|
|
function buildWeeks() {
|
|
self.calendarContainer.classList.add("hasWeeks");
|
|
const weekWrapper = createElement("div", "flatpickr-weekwrapper");
|
|
weekWrapper.appendChild(createElement("span", "flatpickr-weekday", self.l10n.weekAbbreviation));
|
|
const weekNumbers = createElement("div", "flatpickr-weeks");
|
|
weekWrapper.appendChild(weekNumbers);
|
|
return {
|
|
weekWrapper,
|
|
weekNumbers
|
|
};
|
|
}
|
|
function changeMonth(value, isOffset = true) {
|
|
const delta = isOffset ? value : value - self.currentMonth;
|
|
if (delta < 0 && self._hidePrevMonthArrow === true || delta > 0 && self._hideNextMonthArrow === true)
|
|
return;
|
|
self.currentMonth += delta;
|
|
if (self.currentMonth < 0 || self.currentMonth > 11) {
|
|
self.currentYear += self.currentMonth > 11 ? 1 : -1;
|
|
self.currentMonth = (self.currentMonth + 12) % 12;
|
|
triggerEvent("onYearChange");
|
|
buildMonthSwitch();
|
|
}
|
|
buildDays();
|
|
triggerEvent("onMonthChange");
|
|
updateNavigationCurrentMonth();
|
|
}
|
|
function clear(triggerChangeEvent = true, toInitial = true) {
|
|
self.input.value = "";
|
|
if (self.altInput !== void 0)
|
|
self.altInput.value = "";
|
|
if (self.mobileInput !== void 0)
|
|
self.mobileInput.value = "";
|
|
self.selectedDates = [];
|
|
self.latestSelectedDateObj = void 0;
|
|
if (toInitial === true) {
|
|
self.currentYear = self._initialDate.getFullYear();
|
|
self.currentMonth = self._initialDate.getMonth();
|
|
}
|
|
if (self.config.enableTime === true) {
|
|
const { hours, minutes, seconds } = getDefaultHours(self.config);
|
|
setHours(hours, minutes, seconds);
|
|
}
|
|
self.redraw();
|
|
if (triggerChangeEvent)
|
|
triggerEvent("onChange");
|
|
}
|
|
function close() {
|
|
self.isOpen = false;
|
|
if (!self.isMobile) {
|
|
if (self.calendarContainer !== void 0) {
|
|
self.calendarContainer.classList.remove("open");
|
|
}
|
|
if (self._input !== void 0) {
|
|
self._input.classList.remove("active");
|
|
}
|
|
}
|
|
triggerEvent("onClose");
|
|
}
|
|
function destroy() {
|
|
if (self.config !== void 0)
|
|
triggerEvent("onDestroy");
|
|
for (let i = self._handlers.length; i--; ) {
|
|
self._handlers[i].remove();
|
|
}
|
|
self._handlers = [];
|
|
if (self.mobileInput) {
|
|
if (self.mobileInput.parentNode)
|
|
self.mobileInput.parentNode.removeChild(self.mobileInput);
|
|
self.mobileInput = void 0;
|
|
} else if (self.calendarContainer && self.calendarContainer.parentNode) {
|
|
if (self.config.static && self.calendarContainer.parentNode) {
|
|
const wrapper = self.calendarContainer.parentNode;
|
|
wrapper.lastChild && wrapper.removeChild(wrapper.lastChild);
|
|
if (wrapper.parentNode) {
|
|
while (wrapper.firstChild)
|
|
wrapper.parentNode.insertBefore(wrapper.firstChild, wrapper);
|
|
wrapper.parentNode.removeChild(wrapper);
|
|
}
|
|
} else
|
|
self.calendarContainer.parentNode.removeChild(self.calendarContainer);
|
|
}
|
|
if (self.altInput) {
|
|
self.input.type = "text";
|
|
if (self.altInput.parentNode)
|
|
self.altInput.parentNode.removeChild(self.altInput);
|
|
delete self.altInput;
|
|
}
|
|
if (self.input) {
|
|
self.input.type = self.input._type;
|
|
self.input.classList.remove("flatpickr-input");
|
|
self.input.removeAttribute("readonly");
|
|
}
|
|
[
|
|
"_showTimeInput",
|
|
"latestSelectedDateObj",
|
|
"_hideNextMonthArrow",
|
|
"_hidePrevMonthArrow",
|
|
"__hideNextMonthArrow",
|
|
"__hidePrevMonthArrow",
|
|
"isMobile",
|
|
"isOpen",
|
|
"selectedDateElem",
|
|
"minDateHasTime",
|
|
"maxDateHasTime",
|
|
"days",
|
|
"daysContainer",
|
|
"_input",
|
|
"_positionElement",
|
|
"innerContainer",
|
|
"rContainer",
|
|
"monthNav",
|
|
"todayDateElem",
|
|
"calendarContainer",
|
|
"weekdayContainer",
|
|
"prevMonthNav",
|
|
"nextMonthNav",
|
|
"monthsDropdownContainer",
|
|
"currentMonthElement",
|
|
"currentYearElement",
|
|
"navigationCurrentMonth",
|
|
"selectedDateElem",
|
|
"config"
|
|
].forEach((k) => {
|
|
try {
|
|
delete self[k];
|
|
} catch (_) {
|
|
}
|
|
});
|
|
}
|
|
function isCalendarElem(elem) {
|
|
if (self.config.appendTo && self.config.appendTo.contains(elem))
|
|
return true;
|
|
return self.calendarContainer.contains(elem);
|
|
}
|
|
function documentClick(e) {
|
|
if (self.isOpen && !self.config.inline) {
|
|
const eventTarget = getEventTarget(e);
|
|
const isCalendarElement = isCalendarElem(eventTarget);
|
|
const isInput = eventTarget === self.input || eventTarget === self.altInput || self.element.contains(eventTarget) || e.path && e.path.indexOf && (~e.path.indexOf(self.input) || ~e.path.indexOf(self.altInput));
|
|
const lostFocus = e.type === "blur" ? isInput && e.relatedTarget && !isCalendarElem(e.relatedTarget) : !isInput && !isCalendarElement && !isCalendarElem(e.relatedTarget);
|
|
const isIgnored = !self.config.ignoredFocusElements.some((elem) => elem.contains(eventTarget));
|
|
if (lostFocus && isIgnored) {
|
|
if (self.timeContainer !== void 0 && self.minuteElement !== void 0 && self.hourElement !== void 0 && self.input.value !== "" && self.input.value !== void 0) {
|
|
updateTime();
|
|
}
|
|
self.close();
|
|
if (self.config && self.config.mode === "range" && self.selectedDates.length === 1) {
|
|
self.clear(false);
|
|
self.redraw();
|
|
}
|
|
}
|
|
}
|
|
}
|
|
function changeYear(newYear) {
|
|
if (!newYear || self.config.minDate && newYear < self.config.minDate.getFullYear() || self.config.maxDate && newYear > self.config.maxDate.getFullYear())
|
|
return;
|
|
const newYearNum = newYear, isNewYear = self.currentYear !== newYearNum;
|
|
self.currentYear = newYearNum || self.currentYear;
|
|
if (self.config.maxDate && self.currentYear === self.config.maxDate.getFullYear()) {
|
|
self.currentMonth = Math.min(self.config.maxDate.getMonth(), self.currentMonth);
|
|
} else if (self.config.minDate && self.currentYear === self.config.minDate.getFullYear()) {
|
|
self.currentMonth = Math.max(self.config.minDate.getMonth(), self.currentMonth);
|
|
}
|
|
if (isNewYear) {
|
|
self.redraw();
|
|
triggerEvent("onYearChange");
|
|
buildMonthSwitch();
|
|
}
|
|
}
|
|
function isEnabled(date, timeless = true) {
|
|
var _a;
|
|
const dateToCheck = self.parseDate(date, void 0, timeless);
|
|
if (self.config.minDate && dateToCheck && compareDates(dateToCheck, self.config.minDate, timeless !== void 0 ? timeless : !self.minDateHasTime) < 0 || self.config.maxDate && dateToCheck && compareDates(dateToCheck, self.config.maxDate, timeless !== void 0 ? timeless : !self.maxDateHasTime) > 0)
|
|
return false;
|
|
if (!self.config.enable && self.config.disable.length === 0)
|
|
return true;
|
|
if (dateToCheck === void 0)
|
|
return false;
|
|
const bool = !!self.config.enable, array = (_a = self.config.enable) !== null && _a !== void 0 ? _a : self.config.disable;
|
|
for (let i = 0, d; i < array.length; i++) {
|
|
d = array[i];
|
|
if (typeof d === "function" && d(dateToCheck))
|
|
return bool;
|
|
else if (d instanceof Date && dateToCheck !== void 0 && d.getTime() === dateToCheck.getTime())
|
|
return bool;
|
|
else if (typeof d === "string") {
|
|
const parsed = self.parseDate(d, void 0, true);
|
|
return parsed && parsed.getTime() === dateToCheck.getTime() ? bool : !bool;
|
|
} else if (typeof d === "object" && dateToCheck !== void 0 && d.from && d.to && dateToCheck.getTime() >= d.from.getTime() && dateToCheck.getTime() <= d.to.getTime())
|
|
return bool;
|
|
}
|
|
return !bool;
|
|
}
|
|
function isInView(elem) {
|
|
if (self.daysContainer !== void 0)
|
|
return elem.className.indexOf("hidden") === -1 && elem.className.indexOf("flatpickr-disabled") === -1 && self.daysContainer.contains(elem);
|
|
return false;
|
|
}
|
|
function onBlur(e) {
|
|
const isInput = e.target === self._input;
|
|
if (isInput && (self.selectedDates.length > 0 || self._input.value.length > 0) && !(e.relatedTarget && isCalendarElem(e.relatedTarget))) {
|
|
self.setDate(self._input.value, true, e.target === self.altInput ? self.config.altFormat : self.config.dateFormat);
|
|
}
|
|
}
|
|
function onKeyDown(e) {
|
|
const eventTarget = getEventTarget(e);
|
|
const isInput = self.config.wrap ? element.contains(eventTarget) : eventTarget === self._input;
|
|
const allowInput = self.config.allowInput;
|
|
const allowKeydown = self.isOpen && (!allowInput || !isInput);
|
|
const allowInlineKeydown = self.config.inline && isInput && !allowInput;
|
|
if (e.keyCode === 13 && isInput) {
|
|
if (allowInput) {
|
|
self.setDate(self._input.value, true, eventTarget === self.altInput ? self.config.altFormat : self.config.dateFormat);
|
|
return eventTarget.blur();
|
|
} else {
|
|
self.open();
|
|
}
|
|
} else if (isCalendarElem(eventTarget) || allowKeydown || allowInlineKeydown) {
|
|
const isTimeObj = !!self.timeContainer && self.timeContainer.contains(eventTarget);
|
|
switch (e.keyCode) {
|
|
case 13:
|
|
if (isTimeObj) {
|
|
e.preventDefault();
|
|
updateTime();
|
|
focusAndClose();
|
|
} else
|
|
selectDate(e);
|
|
break;
|
|
case 27:
|
|
e.preventDefault();
|
|
focusAndClose();
|
|
break;
|
|
case 8:
|
|
case 46:
|
|
if (isInput && !self.config.allowInput) {
|
|
e.preventDefault();
|
|
self.clear();
|
|
}
|
|
break;
|
|
case 37:
|
|
case 39:
|
|
if (!isTimeObj && !isInput) {
|
|
e.preventDefault();
|
|
if (self.daysContainer !== void 0 && (allowInput === false || document.activeElement && isInView(document.activeElement))) {
|
|
const delta2 = e.keyCode === 39 ? 1 : -1;
|
|
if (!e.ctrlKey)
|
|
focusOnDay(void 0, delta2);
|
|
else {
|
|
e.stopPropagation();
|
|
changeMonth(delta2);
|
|
focusOnDay(getFirstAvailableDay(1), 0);
|
|
}
|
|
}
|
|
} else if (self.hourElement)
|
|
self.hourElement.focus();
|
|
break;
|
|
case 38:
|
|
case 40:
|
|
e.preventDefault();
|
|
const delta = e.keyCode === 40 ? 1 : -1;
|
|
if (self.daysContainer && eventTarget.$i !== void 0 || eventTarget === self.input || eventTarget === self.altInput) {
|
|
if (e.ctrlKey) {
|
|
e.stopPropagation();
|
|
changeYear(self.currentYear - delta);
|
|
focusOnDay(getFirstAvailableDay(1), 0);
|
|
} else if (!isTimeObj)
|
|
focusOnDay(void 0, delta * 7);
|
|
} else if (eventTarget === self.currentYearElement) {
|
|
changeYear(self.currentYear - delta);
|
|
} else if (self.config.enableTime) {
|
|
if (!isTimeObj && self.hourElement)
|
|
self.hourElement.focus();
|
|
updateTime(e);
|
|
self._debouncedChange();
|
|
}
|
|
break;
|
|
case 9:
|
|
if (isTimeObj) {
|
|
const elems = [
|
|
self.hourElement,
|
|
self.minuteElement,
|
|
self.secondElement,
|
|
self.amPM
|
|
].concat(self.pluginElements).filter((x) => x);
|
|
const i = elems.indexOf(eventTarget);
|
|
if (i !== -1) {
|
|
const target = elems[i + (e.shiftKey ? -1 : 1)];
|
|
e.preventDefault();
|
|
(target || self._input).focus();
|
|
}
|
|
} else if (!self.config.noCalendar && self.daysContainer && self.daysContainer.contains(eventTarget) && e.shiftKey) {
|
|
e.preventDefault();
|
|
self._input.focus();
|
|
}
|
|
break;
|
|
default:
|
|
break;
|
|
}
|
|
}
|
|
if (self.amPM !== void 0 && eventTarget === self.amPM) {
|
|
switch (e.key) {
|
|
case self.l10n.amPM[0].charAt(0):
|
|
case self.l10n.amPM[0].charAt(0).toLowerCase():
|
|
self.amPM.textContent = self.l10n.amPM[0];
|
|
setHoursFromInputs();
|
|
updateValue();
|
|
break;
|
|
case self.l10n.amPM[1].charAt(0):
|
|
case self.l10n.amPM[1].charAt(0).toLowerCase():
|
|
self.amPM.textContent = self.l10n.amPM[1];
|
|
setHoursFromInputs();
|
|
updateValue();
|
|
break;
|
|
}
|
|
}
|
|
if (isInput || isCalendarElem(eventTarget)) {
|
|
triggerEvent("onKeyDown", e);
|
|
}
|
|
}
|
|
function onMouseOver(elem) {
|
|
if (self.selectedDates.length !== 1 || elem && (!elem.classList.contains("flatpickr-day") || elem.classList.contains("flatpickr-disabled")))
|
|
return;
|
|
const hoverDate = elem ? elem.dateObj.getTime() : self.days.firstElementChild.dateObj.getTime(), initialDate = self.parseDate(self.selectedDates[0], void 0, true).getTime(), rangeStartDate = Math.min(hoverDate, self.selectedDates[0].getTime()), rangeEndDate = Math.max(hoverDate, self.selectedDates[0].getTime());
|
|
let containsDisabled = false;
|
|
let minRange = 0, maxRange = 0;
|
|
for (let t = rangeStartDate; t < rangeEndDate; t += duration.DAY) {
|
|
if (!isEnabled(new Date(t), true)) {
|
|
containsDisabled = containsDisabled || t > rangeStartDate && t < rangeEndDate;
|
|
if (t < initialDate && (!minRange || t > minRange))
|
|
minRange = t;
|
|
else if (t > initialDate && (!maxRange || t < maxRange))
|
|
maxRange = t;
|
|
}
|
|
}
|
|
for (let m = 0; m < self.config.showMonths; m++) {
|
|
const month = self.daysContainer.children[m];
|
|
for (let i = 0, l = month.children.length; i < l; i++) {
|
|
const dayElem = month.children[i], date = dayElem.dateObj;
|
|
const timestamp = date.getTime();
|
|
const outOfRange = minRange > 0 && timestamp < minRange || maxRange > 0 && timestamp > maxRange;
|
|
if (outOfRange) {
|
|
dayElem.classList.add("notAllowed");
|
|
["inRange", "startRange", "endRange"].forEach((c) => {
|
|
dayElem.classList.remove(c);
|
|
});
|
|
continue;
|
|
} else if (containsDisabled && !outOfRange)
|
|
continue;
|
|
["startRange", "inRange", "endRange", "notAllowed"].forEach((c) => {
|
|
dayElem.classList.remove(c);
|
|
});
|
|
if (elem !== void 0) {
|
|
elem.classList.add(hoverDate <= self.selectedDates[0].getTime() ? "startRange" : "endRange");
|
|
if (initialDate < hoverDate && timestamp === initialDate)
|
|
dayElem.classList.add("startRange");
|
|
else if (initialDate > hoverDate && timestamp === initialDate)
|
|
dayElem.classList.add("endRange");
|
|
if (timestamp >= minRange && (maxRange === 0 || timestamp <= maxRange) && isBetween(timestamp, initialDate, hoverDate))
|
|
dayElem.classList.add("inRange");
|
|
}
|
|
}
|
|
}
|
|
}
|
|
function onResize() {
|
|
if (self.isOpen && !self.config.static && !self.config.inline)
|
|
positionCalendar();
|
|
}
|
|
function open(e, positionElement = self._positionElement) {
|
|
if (self.isMobile === true) {
|
|
if (e) {
|
|
e.preventDefault();
|
|
const eventTarget = getEventTarget(e);
|
|
if (eventTarget) {
|
|
eventTarget.blur();
|
|
}
|
|
}
|
|
if (self.mobileInput !== void 0) {
|
|
self.mobileInput.focus();
|
|
self.mobileInput.click();
|
|
}
|
|
triggerEvent("onOpen");
|
|
return;
|
|
} else if (self._input.disabled || self.config.inline) {
|
|
return;
|
|
}
|
|
const wasOpen = self.isOpen;
|
|
self.isOpen = true;
|
|
if (!wasOpen) {
|
|
self.calendarContainer.classList.add("open");
|
|
self._input.classList.add("active");
|
|
triggerEvent("onOpen");
|
|
positionCalendar(positionElement);
|
|
}
|
|
if (self.config.enableTime === true && self.config.noCalendar === true) {
|
|
if (self.config.allowInput === false && (e === void 0 || !self.timeContainer.contains(e.relatedTarget))) {
|
|
setTimeout(() => self.hourElement.select(), 50);
|
|
}
|
|
}
|
|
}
|
|
function minMaxDateSetter(type) {
|
|
return (date) => {
|
|
const dateObj = self.config[`_${type}Date`] = self.parseDate(date, self.config.dateFormat);
|
|
const inverseDateObj = self.config[`_${type === "min" ? "max" : "min"}Date`];
|
|
if (dateObj !== void 0) {
|
|
self[type === "min" ? "minDateHasTime" : "maxDateHasTime"] = dateObj.getHours() > 0 || dateObj.getMinutes() > 0 || dateObj.getSeconds() > 0;
|
|
}
|
|
if (self.selectedDates) {
|
|
self.selectedDates = self.selectedDates.filter((d) => isEnabled(d));
|
|
if (!self.selectedDates.length && type === "min")
|
|
setHoursFromDate(dateObj);
|
|
updateValue();
|
|
}
|
|
if (self.daysContainer) {
|
|
redraw();
|
|
if (dateObj !== void 0)
|
|
self.currentYearElement[type] = dateObj.getFullYear().toString();
|
|
else
|
|
self.currentYearElement.removeAttribute(type);
|
|
self.currentYearElement.disabled = !!inverseDateObj && dateObj !== void 0 && inverseDateObj.getFullYear() === dateObj.getFullYear();
|
|
}
|
|
};
|
|
}
|
|
function parseConfig() {
|
|
const boolOpts = [
|
|
"wrap",
|
|
"weekNumbers",
|
|
"allowInput",
|
|
"allowInvalidPreload",
|
|
"clickOpens",
|
|
"time_24hr",
|
|
"enableTime",
|
|
"noCalendar",
|
|
"altInput",
|
|
"shorthandCurrentMonth",
|
|
"inline",
|
|
"static",
|
|
"enableSeconds",
|
|
"disableMobile"
|
|
];
|
|
const userConfig = Object.assign(Object.assign({}, JSON.parse(JSON.stringify(element.dataset || {}))), instanceConfig);
|
|
const formats2 = {};
|
|
self.config.parseDate = userConfig.parseDate;
|
|
self.config.formatDate = userConfig.formatDate;
|
|
Object.defineProperty(self.config, "enable", {
|
|
get: () => self.config._enable,
|
|
set: (dates) => {
|
|
self.config._enable = parseDateRules(dates);
|
|
}
|
|
});
|
|
Object.defineProperty(self.config, "disable", {
|
|
get: () => self.config._disable,
|
|
set: (dates) => {
|
|
self.config._disable = parseDateRules(dates);
|
|
}
|
|
});
|
|
const timeMode = userConfig.mode === "time";
|
|
if (!userConfig.dateFormat && (userConfig.enableTime || timeMode)) {
|
|
const defaultDateFormat = flatpickr.defaultConfig.dateFormat || defaults.dateFormat;
|
|
formats2.dateFormat = userConfig.noCalendar || timeMode ? "H:i" + (userConfig.enableSeconds ? ":S" : "") : defaultDateFormat + " H:i" + (userConfig.enableSeconds ? ":S" : "");
|
|
}
|
|
if (userConfig.altInput && (userConfig.enableTime || timeMode) && !userConfig.altFormat) {
|
|
const defaultAltFormat = flatpickr.defaultConfig.altFormat || defaults.altFormat;
|
|
formats2.altFormat = userConfig.noCalendar || timeMode ? "h:i" + (userConfig.enableSeconds ? ":S K" : " K") : defaultAltFormat + ` h:i${userConfig.enableSeconds ? ":S" : ""} K`;
|
|
}
|
|
Object.defineProperty(self.config, "minDate", {
|
|
get: () => self.config._minDate,
|
|
set: minMaxDateSetter("min")
|
|
});
|
|
Object.defineProperty(self.config, "maxDate", {
|
|
get: () => self.config._maxDate,
|
|
set: minMaxDateSetter("max")
|
|
});
|
|
const minMaxTimeSetter = (type) => (val) => {
|
|
self.config[type === "min" ? "_minTime" : "_maxTime"] = self.parseDate(val, "H:i:S");
|
|
};
|
|
Object.defineProperty(self.config, "minTime", {
|
|
get: () => self.config._minTime,
|
|
set: minMaxTimeSetter("min")
|
|
});
|
|
Object.defineProperty(self.config, "maxTime", {
|
|
get: () => self.config._maxTime,
|
|
set: minMaxTimeSetter("max")
|
|
});
|
|
if (userConfig.mode === "time") {
|
|
self.config.noCalendar = true;
|
|
self.config.enableTime = true;
|
|
}
|
|
Object.assign(self.config, formats2, userConfig);
|
|
for (let i = 0; i < boolOpts.length; i++)
|
|
self.config[boolOpts[i]] = self.config[boolOpts[i]] === true || self.config[boolOpts[i]] === "true";
|
|
HOOKS.filter((hook) => self.config[hook] !== void 0).forEach((hook) => {
|
|
self.config[hook] = arrayify(self.config[hook] || []).map(bindToInstance);
|
|
});
|
|
self.isMobile = !self.config.disableMobile && !self.config.inline && self.config.mode === "single" && !self.config.disable.length && !self.config.enable && !self.config.weekNumbers && /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);
|
|
for (let i = 0; i < self.config.plugins.length; i++) {
|
|
const pluginConf = self.config.plugins[i](self) || {};
|
|
for (const key in pluginConf) {
|
|
if (HOOKS.indexOf(key) > -1) {
|
|
self.config[key] = arrayify(pluginConf[key]).map(bindToInstance).concat(self.config[key]);
|
|
} else if (typeof userConfig[key] === "undefined")
|
|
self.config[key] = pluginConf[key];
|
|
}
|
|
}
|
|
if (!userConfig.altInputClass) {
|
|
self.config.altInputClass = getInputElem().className + " " + self.config.altInputClass;
|
|
}
|
|
triggerEvent("onParseConfig");
|
|
}
|
|
function getInputElem() {
|
|
return self.config.wrap ? element.querySelector("[data-input]") : element;
|
|
}
|
|
function setupLocale() {
|
|
if (typeof self.config.locale !== "object" && typeof flatpickr.l10ns[self.config.locale] === "undefined")
|
|
self.config.errorHandler(new Error(`flatpickr: invalid locale ${self.config.locale}`));
|
|
self.l10n = Object.assign(Object.assign({}, flatpickr.l10ns.default), typeof self.config.locale === "object" ? self.config.locale : self.config.locale !== "default" ? flatpickr.l10ns[self.config.locale] : void 0);
|
|
tokenRegex.K = `(${self.l10n.amPM[0]}|${self.l10n.amPM[1]}|${self.l10n.amPM[0].toLowerCase()}|${self.l10n.amPM[1].toLowerCase()})`;
|
|
const userConfig = Object.assign(Object.assign({}, instanceConfig), JSON.parse(JSON.stringify(element.dataset || {})));
|
|
if (userConfig.time_24hr === void 0 && flatpickr.defaultConfig.time_24hr === void 0) {
|
|
self.config.time_24hr = self.l10n.time_24hr;
|
|
}
|
|
self.formatDate = createDateFormatter(self);
|
|
self.parseDate = createDateParser({ config: self.config, l10n: self.l10n });
|
|
}
|
|
function positionCalendar(customPositionElement) {
|
|
if (typeof self.config.position === "function") {
|
|
return void self.config.position(self, customPositionElement);
|
|
}
|
|
if (self.calendarContainer === void 0)
|
|
return;
|
|
triggerEvent("onPreCalendarPosition");
|
|
const positionElement = customPositionElement || self._positionElement;
|
|
const calendarHeight = Array.prototype.reduce.call(self.calendarContainer.children, (acc, child) => acc + child.offsetHeight, 0), calendarWidth = self.calendarContainer.offsetWidth, configPos = self.config.position.split(" "), configPosVertical = configPos[0], configPosHorizontal = configPos.length > 1 ? configPos[1] : null, inputBounds = positionElement.getBoundingClientRect(), distanceFromBottom = window.innerHeight - inputBounds.bottom, showOnTop = configPosVertical === "above" || configPosVertical !== "below" && distanceFromBottom < calendarHeight && inputBounds.top > calendarHeight;
|
|
const top = window.pageYOffset + inputBounds.top + (!showOnTop ? positionElement.offsetHeight + 2 : -calendarHeight - 2);
|
|
toggleClass(self.calendarContainer, "arrowTop", !showOnTop);
|
|
toggleClass(self.calendarContainer, "arrowBottom", showOnTop);
|
|
if (self.config.inline)
|
|
return;
|
|
let left = window.pageXOffset + inputBounds.left;
|
|
let isCenter = false;
|
|
let isRight = false;
|
|
if (configPosHorizontal === "center") {
|
|
left -= (calendarWidth - inputBounds.width) / 2;
|
|
isCenter = true;
|
|
} else if (configPosHorizontal === "right") {
|
|
left -= calendarWidth - inputBounds.width;
|
|
isRight = true;
|
|
}
|
|
toggleClass(self.calendarContainer, "arrowLeft", !isCenter && !isRight);
|
|
toggleClass(self.calendarContainer, "arrowCenter", isCenter);
|
|
toggleClass(self.calendarContainer, "arrowRight", isRight);
|
|
const right = window.document.body.offsetWidth - (window.pageXOffset + inputBounds.right);
|
|
const rightMost = left + calendarWidth > window.document.body.offsetWidth;
|
|
const centerMost = right + calendarWidth > window.document.body.offsetWidth;
|
|
toggleClass(self.calendarContainer, "rightMost", rightMost);
|
|
if (self.config.static)
|
|
return;
|
|
self.calendarContainer.style.top = `${top}px`;
|
|
if (!rightMost) {
|
|
self.calendarContainer.style.left = `${left}px`;
|
|
self.calendarContainer.style.right = "auto";
|
|
} else if (!centerMost) {
|
|
self.calendarContainer.style.left = "auto";
|
|
self.calendarContainer.style.right = `${right}px`;
|
|
} else {
|
|
const doc = getDocumentStyleSheet();
|
|
if (doc === void 0)
|
|
return;
|
|
const bodyWidth = window.document.body.offsetWidth;
|
|
const centerLeft = Math.max(0, bodyWidth / 2 - calendarWidth / 2);
|
|
const centerBefore = ".flatpickr-calendar.centerMost:before";
|
|
const centerAfter = ".flatpickr-calendar.centerMost:after";
|
|
const centerIndex = doc.cssRules.length;
|
|
const centerStyle = `{left:${inputBounds.left}px;right:auto;}`;
|
|
toggleClass(self.calendarContainer, "rightMost", false);
|
|
toggleClass(self.calendarContainer, "centerMost", true);
|
|
doc.insertRule(`${centerBefore},${centerAfter}${centerStyle}`, centerIndex);
|
|
self.calendarContainer.style.left = `${centerLeft}px`;
|
|
self.calendarContainer.style.right = "auto";
|
|
}
|
|
}
|
|
function getDocumentStyleSheet() {
|
|
let editableSheet = null;
|
|
for (let i = 0; i < document.styleSheets.length; i++) {
|
|
const sheet = document.styleSheets[i];
|
|
try {
|
|
sheet.cssRules;
|
|
} catch (err) {
|
|
continue;
|
|
}
|
|
editableSheet = sheet;
|
|
break;
|
|
}
|
|
return editableSheet != null ? editableSheet : createStyleSheet();
|
|
}
|
|
function createStyleSheet() {
|
|
const style = document.createElement("style");
|
|
document.head.appendChild(style);
|
|
return style.sheet;
|
|
}
|
|
function redraw() {
|
|
if (self.config.noCalendar || self.isMobile)
|
|
return;
|
|
buildMonthSwitch();
|
|
updateNavigationCurrentMonth();
|
|
buildDays();
|
|
}
|
|
function focusAndClose() {
|
|
self._input.focus();
|
|
if (window.navigator.userAgent.indexOf("MSIE") !== -1 || navigator.msMaxTouchPoints !== void 0) {
|
|
setTimeout(self.close, 0);
|
|
} else {
|
|
self.close();
|
|
}
|
|
}
|
|
function selectDate(e) {
|
|
e.preventDefault();
|
|
e.stopPropagation();
|
|
const isSelectable = (day) => day.classList && day.classList.contains("flatpickr-day") && !day.classList.contains("flatpickr-disabled") && !day.classList.contains("notAllowed");
|
|
const t = findParent(getEventTarget(e), isSelectable);
|
|
if (t === void 0)
|
|
return;
|
|
const target = t;
|
|
const selectedDate = self.latestSelectedDateObj = new Date(target.dateObj.getTime());
|
|
const shouldChangeMonth = (selectedDate.getMonth() < self.currentMonth || selectedDate.getMonth() > self.currentMonth + self.config.showMonths - 1) && self.config.mode !== "range";
|
|
self.selectedDateElem = target;
|
|
if (self.config.mode === "single")
|
|
self.selectedDates = [selectedDate];
|
|
else if (self.config.mode === "multiple") {
|
|
const selectedIndex = isDateSelected(selectedDate);
|
|
if (selectedIndex)
|
|
self.selectedDates.splice(parseInt(selectedIndex), 1);
|
|
else
|
|
self.selectedDates.push(selectedDate);
|
|
} else if (self.config.mode === "range") {
|
|
if (self.selectedDates.length === 2) {
|
|
self.clear(false, false);
|
|
}
|
|
self.latestSelectedDateObj = selectedDate;
|
|
self.selectedDates.push(selectedDate);
|
|
if (compareDates(selectedDate, self.selectedDates[0], true) !== 0)
|
|
self.selectedDates.sort((a, b) => a.getTime() - b.getTime());
|
|
}
|
|
setHoursFromInputs();
|
|
if (shouldChangeMonth) {
|
|
const isNewYear = self.currentYear !== selectedDate.getFullYear();
|
|
self.currentYear = selectedDate.getFullYear();
|
|
self.currentMonth = selectedDate.getMonth();
|
|
if (isNewYear) {
|
|
triggerEvent("onYearChange");
|
|
buildMonthSwitch();
|
|
}
|
|
triggerEvent("onMonthChange");
|
|
}
|
|
updateNavigationCurrentMonth();
|
|
buildDays();
|
|
updateValue();
|
|
if (!shouldChangeMonth && self.config.mode !== "range" && self.config.showMonths === 1)
|
|
focusOnDayElem(target);
|
|
else if (self.selectedDateElem !== void 0 && self.hourElement === void 0) {
|
|
self.selectedDateElem && self.selectedDateElem.focus();
|
|
}
|
|
if (self.hourElement !== void 0)
|
|
self.hourElement !== void 0 && self.hourElement.focus();
|
|
if (self.config.closeOnSelect) {
|
|
const single = self.config.mode === "single" && !self.config.enableTime;
|
|
const range = self.config.mode === "range" && self.selectedDates.length === 2 && !self.config.enableTime;
|
|
if (single || range) {
|
|
focusAndClose();
|
|
}
|
|
}
|
|
triggerChange();
|
|
}
|
|
const CALLBACKS = {
|
|
locale: [setupLocale, updateWeekdays],
|
|
showMonths: [buildMonths, setCalendarWidth, buildWeekdays],
|
|
minDate: [jumpToDate],
|
|
maxDate: [jumpToDate],
|
|
clickOpens: [
|
|
() => {
|
|
if (self.config.clickOpens === true) {
|
|
bind(self._input, "focus", self.open);
|
|
bind(self._input, "click", self.open);
|
|
} else {
|
|
self._input.removeEventListener("focus", self.open);
|
|
self._input.removeEventListener("click", self.open);
|
|
}
|
|
}
|
|
]
|
|
};
|
|
function set(option, value) {
|
|
if (option !== null && typeof option === "object") {
|
|
Object.assign(self.config, option);
|
|
for (const key in option) {
|
|
if (CALLBACKS[key] !== void 0)
|
|
CALLBACKS[key].forEach((x) => x());
|
|
}
|
|
} else {
|
|
self.config[option] = value;
|
|
if (CALLBACKS[option] !== void 0)
|
|
CALLBACKS[option].forEach((x) => x());
|
|
else if (HOOKS.indexOf(option) > -1)
|
|
self.config[option] = arrayify(value);
|
|
}
|
|
self.redraw();
|
|
updateValue(true);
|
|
}
|
|
function setSelectedDate(inputDate, format) {
|
|
let dates = [];
|
|
if (inputDate instanceof Array)
|
|
dates = inputDate.map((d) => self.parseDate(d, format));
|
|
else if (inputDate instanceof Date || typeof inputDate === "number")
|
|
dates = [self.parseDate(inputDate, format)];
|
|
else if (typeof inputDate === "string") {
|
|
switch (self.config.mode) {
|
|
case "single":
|
|
case "time":
|
|
dates = [self.parseDate(inputDate, format)];
|
|
break;
|
|
case "multiple":
|
|
dates = inputDate.split(self.config.conjunction).map((date) => self.parseDate(date, format));
|
|
break;
|
|
case "range":
|
|
dates = inputDate.split(self.l10n.rangeSeparator).map((date) => self.parseDate(date, format));
|
|
break;
|
|
default:
|
|
break;
|
|
}
|
|
} else
|
|
self.config.errorHandler(new Error(`Invalid date supplied: ${JSON.stringify(inputDate)}`));
|
|
self.selectedDates = self.config.allowInvalidPreload ? dates : dates.filter((d) => d instanceof Date && isEnabled(d, false));
|
|
if (self.config.mode === "range")
|
|
self.selectedDates.sort((a, b) => a.getTime() - b.getTime());
|
|
}
|
|
function setDate(date, triggerChange2 = false, format = self.config.dateFormat) {
|
|
if (date !== 0 && !date || date instanceof Array && date.length === 0)
|
|
return self.clear(triggerChange2);
|
|
setSelectedDate(date, format);
|
|
self.latestSelectedDateObj = self.selectedDates[self.selectedDates.length - 1];
|
|
self.redraw();
|
|
jumpToDate(void 0, triggerChange2);
|
|
setHoursFromDate();
|
|
if (self.selectedDates.length === 0) {
|
|
self.clear(false);
|
|
}
|
|
updateValue(triggerChange2);
|
|
if (triggerChange2)
|
|
triggerEvent("onChange");
|
|
}
|
|
function parseDateRules(arr) {
|
|
return arr.slice().map((rule) => {
|
|
if (typeof rule === "string" || typeof rule === "number" || rule instanceof Date) {
|
|
return self.parseDate(rule, void 0, true);
|
|
} else if (rule && typeof rule === "object" && rule.from && rule.to)
|
|
return {
|
|
from: self.parseDate(rule.from, void 0),
|
|
to: self.parseDate(rule.to, void 0)
|
|
};
|
|
return rule;
|
|
}).filter((x) => x);
|
|
}
|
|
function setupDates() {
|
|
self.selectedDates = [];
|
|
self.now = self.parseDate(self.config.now) || new Date();
|
|
const preloadedDate = self.config.defaultDate || ((self.input.nodeName === "INPUT" || self.input.nodeName === "TEXTAREA") && self.input.placeholder && self.input.value === self.input.placeholder ? null : self.input.value);
|
|
if (preloadedDate)
|
|
setSelectedDate(preloadedDate, self.config.dateFormat);
|
|
self._initialDate = self.selectedDates.length > 0 ? self.selectedDates[0] : self.config.minDate && self.config.minDate.getTime() > self.now.getTime() ? self.config.minDate : self.config.maxDate && self.config.maxDate.getTime() < self.now.getTime() ? self.config.maxDate : self.now;
|
|
self.currentYear = self._initialDate.getFullYear();
|
|
self.currentMonth = self._initialDate.getMonth();
|
|
if (self.selectedDates.length > 0)
|
|
self.latestSelectedDateObj = self.selectedDates[0];
|
|
if (self.config.minTime !== void 0)
|
|
self.config.minTime = self.parseDate(self.config.minTime, "H:i");
|
|
if (self.config.maxTime !== void 0)
|
|
self.config.maxTime = self.parseDate(self.config.maxTime, "H:i");
|
|
self.minDateHasTime = !!self.config.minDate && (self.config.minDate.getHours() > 0 || self.config.minDate.getMinutes() > 0 || self.config.minDate.getSeconds() > 0);
|
|
self.maxDateHasTime = !!self.config.maxDate && (self.config.maxDate.getHours() > 0 || self.config.maxDate.getMinutes() > 0 || self.config.maxDate.getSeconds() > 0);
|
|
}
|
|
function setupInputs() {
|
|
self.input = getInputElem();
|
|
if (!self.input) {
|
|
self.config.errorHandler(new Error("Invalid input element specified"));
|
|
return;
|
|
}
|
|
self.input._type = self.input.type;
|
|
self.input.type = "text";
|
|
self.input.classList.add("flatpickr-input");
|
|
self._input = self.input;
|
|
if (self.config.altInput) {
|
|
self.altInput = createElement(self.input.nodeName, self.config.altInputClass);
|
|
self._input = self.altInput;
|
|
self.altInput.placeholder = self.input.placeholder;
|
|
self.altInput.disabled = self.input.disabled;
|
|
self.altInput.required = self.input.required;
|
|
self.altInput.tabIndex = self.input.tabIndex;
|
|
self.altInput.type = "text";
|
|
self.input.setAttribute("type", "hidden");
|
|
if (!self.config.static && self.input.parentNode)
|
|
self.input.parentNode.insertBefore(self.altInput, self.input.nextSibling);
|
|
}
|
|
if (!self.config.allowInput)
|
|
self._input.setAttribute("readonly", "readonly");
|
|
self._positionElement = self.config.positionElement || self._input;
|
|
}
|
|
function setupMobile() {
|
|
const inputType = self.config.enableTime ? self.config.noCalendar ? "time" : "datetime-local" : "date";
|
|
self.mobileInput = createElement("input", self.input.className + " flatpickr-mobile");
|
|
self.mobileInput.tabIndex = 1;
|
|
self.mobileInput.type = inputType;
|
|
self.mobileInput.disabled = self.input.disabled;
|
|
self.mobileInput.required = self.input.required;
|
|
self.mobileInput.placeholder = self.input.placeholder;
|
|
self.mobileFormatStr = inputType === "datetime-local" ? "Y-m-d\\TH:i:S" : inputType === "date" ? "Y-m-d" : "H:i:S";
|
|
if (self.selectedDates.length > 0) {
|
|
self.mobileInput.defaultValue = self.mobileInput.value = self.formatDate(self.selectedDates[0], self.mobileFormatStr);
|
|
}
|
|
if (self.config.minDate)
|
|
self.mobileInput.min = self.formatDate(self.config.minDate, "Y-m-d");
|
|
if (self.config.maxDate)
|
|
self.mobileInput.max = self.formatDate(self.config.maxDate, "Y-m-d");
|
|
if (self.input.getAttribute("step"))
|
|
self.mobileInput.step = String(self.input.getAttribute("step"));
|
|
self.input.type = "hidden";
|
|
if (self.altInput !== void 0)
|
|
self.altInput.type = "hidden";
|
|
try {
|
|
if (self.input.parentNode)
|
|
self.input.parentNode.insertBefore(self.mobileInput, self.input.nextSibling);
|
|
} catch (_a) {
|
|
}
|
|
bind(self.mobileInput, "change", (e) => {
|
|
self.setDate(getEventTarget(e).value, false, self.mobileFormatStr);
|
|
triggerEvent("onChange");
|
|
triggerEvent("onClose");
|
|
});
|
|
}
|
|
function toggle(e) {
|
|
if (self.isOpen === true)
|
|
return self.close();
|
|
self.open(e);
|
|
}
|
|
function triggerEvent(event, data) {
|
|
if (self.config === void 0)
|
|
return;
|
|
const hooks = self.config[event];
|
|
if (hooks !== void 0 && hooks.length > 0) {
|
|
for (let i = 0; hooks[i] && i < hooks.length; i++)
|
|
hooks[i](self.selectedDates, self.input.value, self, data);
|
|
}
|
|
if (event === "onChange") {
|
|
self.input.dispatchEvent(createEvent("change"));
|
|
self.input.dispatchEvent(createEvent("input"));
|
|
}
|
|
}
|
|
function createEvent(name) {
|
|
const e = document.createEvent("Event");
|
|
e.initEvent(name, true, true);
|
|
return e;
|
|
}
|
|
function isDateSelected(date) {
|
|
for (let i = 0; i < self.selectedDates.length; i++) {
|
|
if (compareDates(self.selectedDates[i], date) === 0)
|
|
return "" + i;
|
|
}
|
|
return false;
|
|
}
|
|
function isDateInRange(date) {
|
|
if (self.config.mode !== "range" || self.selectedDates.length < 2)
|
|
return false;
|
|
return compareDates(date, self.selectedDates[0]) >= 0 && compareDates(date, self.selectedDates[1]) <= 0;
|
|
}
|
|
function updateNavigationCurrentMonth() {
|
|
if (self.config.noCalendar || self.isMobile || !self.monthNav)
|
|
return;
|
|
self.yearElements.forEach((yearElement, i) => {
|
|
const d = new Date(self.currentYear, self.currentMonth, 1);
|
|
d.setMonth(self.currentMonth + i);
|
|
if (self.config.showMonths > 1 || self.config.monthSelectorType === "static") {
|
|
self.monthElements[i].textContent = monthToStr(d.getMonth(), self.config.shorthandCurrentMonth, self.l10n) + " ";
|
|
} else {
|
|
self.monthsDropdownContainer.value = d.getMonth().toString();
|
|
}
|
|
yearElement.value = d.getFullYear().toString();
|
|
});
|
|
self._hidePrevMonthArrow = self.config.minDate !== void 0 && (self.currentYear === self.config.minDate.getFullYear() ? self.currentMonth <= self.config.minDate.getMonth() : self.currentYear < self.config.minDate.getFullYear());
|
|
self._hideNextMonthArrow = self.config.maxDate !== void 0 && (self.currentYear === self.config.maxDate.getFullYear() ? self.currentMonth + 1 > self.config.maxDate.getMonth() : self.currentYear > self.config.maxDate.getFullYear());
|
|
}
|
|
function getDateStr(format) {
|
|
return self.selectedDates.map((dObj) => self.formatDate(dObj, format)).filter((d, i, arr) => self.config.mode !== "range" || self.config.enableTime || arr.indexOf(d) === i).join(self.config.mode !== "range" ? self.config.conjunction : self.l10n.rangeSeparator);
|
|
}
|
|
function updateValue(triggerChange2 = true) {
|
|
if (self.mobileInput !== void 0 && self.mobileFormatStr) {
|
|
self.mobileInput.value = self.latestSelectedDateObj !== void 0 ? self.formatDate(self.latestSelectedDateObj, self.mobileFormatStr) : "";
|
|
}
|
|
self.input.value = getDateStr(self.config.dateFormat);
|
|
if (self.altInput !== void 0) {
|
|
self.altInput.value = getDateStr(self.config.altFormat);
|
|
}
|
|
if (triggerChange2 !== false)
|
|
triggerEvent("onValueUpdate");
|
|
}
|
|
function onMonthNavClick(e) {
|
|
const eventTarget = getEventTarget(e);
|
|
const isPrevMonth = self.prevMonthNav.contains(eventTarget);
|
|
const isNextMonth = self.nextMonthNav.contains(eventTarget);
|
|
if (isPrevMonth || isNextMonth) {
|
|
changeMonth(isPrevMonth ? -1 : 1);
|
|
} else if (self.yearElements.indexOf(eventTarget) >= 0) {
|
|
eventTarget.select();
|
|
} else if (eventTarget.classList.contains("arrowUp")) {
|
|
self.changeYear(self.currentYear + 1);
|
|
} else if (eventTarget.classList.contains("arrowDown")) {
|
|
self.changeYear(self.currentYear - 1);
|
|
}
|
|
}
|
|
function timeWrapper(e) {
|
|
e.preventDefault();
|
|
const isKeyDown = e.type === "keydown", eventTarget = getEventTarget(e), input = eventTarget;
|
|
if (self.amPM !== void 0 && eventTarget === self.amPM) {
|
|
self.amPM.textContent = self.l10n.amPM[int(self.amPM.textContent === self.l10n.amPM[0])];
|
|
}
|
|
const min = parseFloat(input.getAttribute("min")), max = parseFloat(input.getAttribute("max")), step = parseFloat(input.getAttribute("step")), curValue = parseInt(input.value, 10), delta = e.delta || (isKeyDown ? e.which === 38 ? 1 : -1 : 0);
|
|
let newValue = curValue + step * delta;
|
|
if (typeof input.value !== "undefined" && input.value.length === 2) {
|
|
const isHourElem = input === self.hourElement, isMinuteElem = input === self.minuteElement;
|
|
if (newValue < min) {
|
|
newValue = max + newValue + int(!isHourElem) + (int(isHourElem) && int(!self.amPM));
|
|
if (isMinuteElem)
|
|
incrementNumInput(void 0, -1, self.hourElement);
|
|
} else if (newValue > max) {
|
|
newValue = input === self.hourElement ? newValue - max - int(!self.amPM) : min;
|
|
if (isMinuteElem)
|
|
incrementNumInput(void 0, 1, self.hourElement);
|
|
}
|
|
if (self.amPM && isHourElem && (step === 1 ? newValue + curValue === 23 : Math.abs(newValue - curValue) > step)) {
|
|
self.amPM.textContent = self.l10n.amPM[int(self.amPM.textContent === self.l10n.amPM[0])];
|
|
}
|
|
input.value = pad(newValue);
|
|
}
|
|
}
|
|
init();
|
|
return self;
|
|
}
|
|
function _flatpickr(nodeList, config) {
|
|
const nodes = Array.prototype.slice.call(nodeList).filter((x) => x instanceof HTMLElement);
|
|
const instances = [];
|
|
for (let i = 0; i < nodes.length; i++) {
|
|
const node = nodes[i];
|
|
try {
|
|
if (node.getAttribute("data-fp-omit") !== null)
|
|
continue;
|
|
if (node._flatpickr !== void 0) {
|
|
node._flatpickr.destroy();
|
|
node._flatpickr = void 0;
|
|
}
|
|
node._flatpickr = FlatpickrInstance(node, config || {});
|
|
instances.push(node._flatpickr);
|
|
} catch (e) {
|
|
console.error(e);
|
|
}
|
|
}
|
|
return instances.length === 1 ? instances[0] : instances;
|
|
}
|
|
if (typeof HTMLElement !== "undefined" && typeof HTMLCollection !== "undefined" && typeof NodeList !== "undefined") {
|
|
HTMLCollection.prototype.flatpickr = NodeList.prototype.flatpickr = function(config) {
|
|
return _flatpickr(this, config);
|
|
};
|
|
HTMLElement.prototype.flatpickr = function(config) {
|
|
return _flatpickr([this], config);
|
|
};
|
|
}
|
|
var flatpickr = function(selector, config) {
|
|
if (typeof selector === "string") {
|
|
return _flatpickr(window.document.querySelectorAll(selector), config);
|
|
} else if (selector instanceof Node) {
|
|
return _flatpickr([selector], config);
|
|
} else {
|
|
return _flatpickr(selector, config);
|
|
}
|
|
};
|
|
flatpickr.defaultConfig = {};
|
|
flatpickr.l10ns = {
|
|
en: Object.assign({}, default_default),
|
|
default: Object.assign({}, default_default)
|
|
};
|
|
flatpickr.localize = (l10n) => {
|
|
flatpickr.l10ns.default = Object.assign(Object.assign({}, flatpickr.l10ns.default), l10n);
|
|
};
|
|
flatpickr.setDefaults = (config) => {
|
|
flatpickr.defaultConfig = Object.assign(Object.assign({}, flatpickr.defaultConfig), config);
|
|
};
|
|
flatpickr.parseDate = createDateParser({});
|
|
flatpickr.formatDate = createDateFormatter({});
|
|
flatpickr.compareDates = compareDates;
|
|
if (typeof jQuery !== "undefined" && typeof jQuery.fn !== "undefined") {
|
|
jQuery.fn.flatpickr = function(config) {
|
|
return _flatpickr(this, config);
|
|
};
|
|
}
|
|
Date.prototype.fp_incr = function(days) {
|
|
return new Date(this.getFullYear(), this.getMonth(), this.getDate() + (typeof days === "string" ? parseInt(days, 10) : days));
|
|
};
|
|
if (typeof window !== "undefined") {
|
|
window.flatpickr = flatpickr;
|
|
}
|
|
var esm_default = flatpickr;
|
|
|
|
// src/ui/calendarPicker.ts
|
|
var import_obsidian3 = __toModule(require("obsidian"));
|
|
var import_obsidian_daily_notes_interface = __toModule(require_main());
|
|
var CalendarPicker = class {
|
|
constructor(plugin) {
|
|
this.picker = null;
|
|
this.plugin = plugin;
|
|
}
|
|
open() {
|
|
if (this.picker !== null && this.picker.isOpen) {
|
|
this.picker.destroy();
|
|
this.picker = null;
|
|
return;
|
|
}
|
|
if (document.querySelector(".obsidian42-jump-to-date"))
|
|
document.querySelectorAll(".obsidian42-jump-to-date").forEach((e) => e.remove());
|
|
this.initializePicker();
|
|
this.picker.shouldConfirmBeforeCreate = this.plugin.settings.shouldConfirmBeforeCreate;
|
|
let currentlySelectedDate = (0, import_obsidian3.moment)();
|
|
const activeView = this.plugin.app.workspace.getLeaf().view;
|
|
try {
|
|
if (activeView.file && (0, import_obsidian3.moment)(activeView.file.basename, (0, import_obsidian_daily_notes_interface.getDailyNoteSettings)().format, true).isValid()) {
|
|
currentlySelectedDate = (0, import_obsidian3.moment)(activeView.file.basename, (0, import_obsidian_daily_notes_interface.getDailyNoteSettings)().format, true);
|
|
}
|
|
} catch (e) {
|
|
console.log(e);
|
|
}
|
|
this.picker.setDate(currentlySelectedDate.format("Y-MM-D"));
|
|
this.picker.open();
|
|
const daySelected = document.querySelector(".obsidian42-jump-to-date .flatpickr-day.selected");
|
|
daySelected.focus();
|
|
daySelected.dispatchEvent(new KeyboardEvent("keydown", { "key": "ArrowRight" }));
|
|
daySelected.focus();
|
|
}
|
|
initializePicker() {
|
|
const startingDayInWeek = this.plugin.settings.firstDayOfWeekIsSunday ? 0 : 1;
|
|
if (this.picker !== null)
|
|
this.picker.destroy();
|
|
this.picker = esm_default(document.querySelector('div[aria-label="Jump-to-Date"]'), {
|
|
onChange: function(selectedDates, dateStr, instance) {
|
|
return __async(this, null, function* () {
|
|
yield instance.navigateToDNP(dateStr, instance.shouldConfirmBeforeCreate, instance.controlKeyPressed, instance.shiftKeyPressed);
|
|
instance.destroy();
|
|
});
|
|
},
|
|
disableMobile: true,
|
|
locale: { firstDayOfWeek: startingDayInWeek }
|
|
});
|
|
this.picker.calendarContainer.addClass("obsidian42-jump-to-date");
|
|
this.picker.calendarContainer.addEventListener("keydown", (e) => {
|
|
this.picker.controlKeyPressed = e.ctrlKey || e.metaKey;
|
|
this.picker.shiftKeyPressed = e.shiftKey;
|
|
});
|
|
this.picker.calendarContainer.addEventListener("keyup", (e) => {
|
|
if (e.key === "Enter") {
|
|
const newDate = (0, import_obsidian3.moment)(new Date(e.target.dateObj)).format("Y-MM-D");
|
|
this.picker.navigateToDNP(newDate, this.picker.shouldConfirmBeforeCreate, e.ctrlKey || e.metaKey, e.shiftKey);
|
|
this.picker.destroy();
|
|
this.picker = null;
|
|
} else {
|
|
this.picker.controlKeyPressed = e.ctrlKey || e.metaKey;
|
|
this.picker.shiftKeyPressed = e.shiftKey;
|
|
}
|
|
});
|
|
this.picker.daysContainer.addEventListener("click", (e) => {
|
|
this.picker.controlKeyPressed = e.ctrlKey || e.metaKey;
|
|
this.picker.shiftKeyPressed = e.shiftKey;
|
|
});
|
|
this.picker.daysContainer.addEventListener("contextmenu", (e) => {
|
|
const newDate = (0, import_obsidian3.moment)(new Date(e.target.dateObj)).format("Y-MM-D");
|
|
this.picker.navigateToDNP(newDate, this.picker.shouldConfirmBeforeCreate, true, this.picker.shiftKeyPressed);
|
|
this.picker.destroy();
|
|
});
|
|
this.picker.navigateToDNP = this.plugin.navigateToDNP;
|
|
this.picker.controlKeyPressed = false;
|
|
this.picker.shiftKeyPressed = false;
|
|
}
|
|
setFirstDayofWeek(dayOfWeek) {
|
|
this.picker.set("locale", { firstDayOfWeek: dayOfWeek });
|
|
}
|
|
};
|
|
|
|
// src/ui/datenlpModal.ts
|
|
var import_obsidian4 = __toModule(require("obsidian"));
|
|
var DateNLP_Modal = class extends import_obsidian4.Modal {
|
|
constructor(app2, plugin) {
|
|
super(app2);
|
|
this.plugin = plugin;
|
|
}
|
|
submitForm(dateStr, ctrlKey, shiftKey) {
|
|
return __async(this, null, function* () {
|
|
yield this.plugin.navigateToDNP(dateStr, this.plugin.settings.shouldConfirmBeforeCreate, ctrlKey, shiftKey);
|
|
this.close();
|
|
});
|
|
}
|
|
onOpen() {
|
|
let previewEl;
|
|
let dateInput = "";
|
|
let ctrlKey = false;
|
|
let shiftKey = false;
|
|
const getDateStr = () => {
|
|
const parsedDate = this.app.plugins.getPlugin("nldates-obsidian").parseDate(dateInput);
|
|
this.date = parsedDate.date;
|
|
const parsedDateString = parsedDate.formattedString === "Invalid date" ? "" : parsedDate.formattedString.replace("[[", "").replace("]]", "");
|
|
return parsedDateString;
|
|
};
|
|
this.contentEl.createEl("form", {}, (formEl) => {
|
|
const dateInputEl = new import_obsidian4.Setting(formEl).setName("Date of DNP to open").setDesc("").addText((textEl) => {
|
|
textEl.setPlaceholder("Natural Language Date");
|
|
textEl.onChange((value) => {
|
|
dateInput = value;
|
|
previewEl.setText(getDateStr());
|
|
});
|
|
textEl.inputEl.addEventListener("keydown", (e) => __async(this, null, function* () {
|
|
ctrlKey = e.ctrlKey || e.metaKey;
|
|
shiftKey = e.shiftKey;
|
|
if (ctrlKey && e.key === "Enter" && previewEl.getText().trim() !== " ") {
|
|
e.preventDefault();
|
|
}
|
|
}));
|
|
window.setTimeout(() => textEl.inputEl.focus(), 10);
|
|
});
|
|
previewEl = dateInputEl.descEl;
|
|
formEl.createDiv("modal-button-container", (buttonContainerEl) => {
|
|
buttonContainerEl.createEl("button", { attr: { type: "button" }, text: "Never mind" }).addEventListener("click", () => this.close());
|
|
buttonContainerEl.createEl("button", {
|
|
attr: { type: "submit" },
|
|
cls: "mod-cta",
|
|
text: "Goto to DNP"
|
|
});
|
|
});
|
|
formEl.addEventListener("submit", (e) => __async(this, null, function* () {
|
|
e.preventDefault();
|
|
if (previewEl.getText() !== "") {
|
|
const newDate = (0, import_obsidian4.moment)(this.date).format("YYYY-MM-DD");
|
|
yield this.submitForm(newDate, ctrlKey, shiftKey);
|
|
}
|
|
}));
|
|
});
|
|
}
|
|
};
|
|
|
|
// src/ui/confirmationModal.ts
|
|
var import_obsidian5 = __toModule(require("obsidian"));
|
|
var ConfirmationModal = class extends import_obsidian5.Modal {
|
|
constructor(app2, config) {
|
|
super(app2);
|
|
const { cta, onAccept, text, title, fileDate } = config;
|
|
this.contentEl.createEl("h2", { text: title });
|
|
const e = this.contentEl.createEl("p", { text });
|
|
e.id = "jumptodate-confirmdialog";
|
|
e.setAttr("fileDate", fileDate);
|
|
this.contentEl.createDiv("modal-button-container", (buttonsEl) => {
|
|
buttonsEl.createEl("button", { text: "Never mind" }).addEventListener("click", () => this.close());
|
|
const btnSumbit = buttonsEl.createEl("button", {
|
|
attr: { type: "submit" },
|
|
cls: "mod-cta",
|
|
text: cta
|
|
});
|
|
btnSumbit.addEventListener("click", (e2) => __async(this, null, function* () {
|
|
const dateStr = document.getElementById("jumptodate-confirmdialog").getAttr("filedate").toString();
|
|
yield onAccept(dateStr, e2);
|
|
this.close();
|
|
}));
|
|
setTimeout(() => {
|
|
btnSumbit.focus();
|
|
}, 50);
|
|
});
|
|
}
|
|
};
|
|
function createConfirmationDialog({
|
|
cta,
|
|
onAccept,
|
|
text,
|
|
title,
|
|
fileDate
|
|
}) {
|
|
new ConfirmationModal(window.app, { cta, onAccept, text, title, fileDate }).open();
|
|
}
|
|
|
|
// src/main.ts
|
|
var ThePlugin = class extends import_obsidian6.Plugin {
|
|
onload() {
|
|
return __async(this, null, function* () {
|
|
console.log("loading Obsidian42 Jump-to-Date plugin");
|
|
this.datePicker = new CalendarPicker(this);
|
|
yield this.loadSettings();
|
|
addIcons();
|
|
this.addCommand({
|
|
id: "open-JumpToDate-calendar",
|
|
name: "Date Picker",
|
|
checkCallback: (check) => {
|
|
if (check)
|
|
return this.settings.enableRibbon;
|
|
else
|
|
setTimeout(() => {
|
|
this.datePicker.open();
|
|
}, 250);
|
|
}
|
|
});
|
|
this.app.workspace.onLayoutReady(() => {
|
|
if (this.app.plugins.getPlugin("nldates-obsidian")) {
|
|
this.addCommand({
|
|
id: "open-JumpToDate-nlp",
|
|
name: "Natural Language Date",
|
|
callback: () => {
|
|
const dt = new DateNLP_Modal(this.app, this);
|
|
dt.open();
|
|
}
|
|
});
|
|
}
|
|
if (this.settings.enableRibbon)
|
|
this.showRibbonButton();
|
|
});
|
|
this.addSettingTab(new SettingsTab(this.app, this));
|
|
});
|
|
}
|
|
onunload() {
|
|
console.log("unloading Obsidian42 Jump-to-Date plugin");
|
|
}
|
|
loadSettings() {
|
|
return __async(this, null, function* () {
|
|
this.settings = Object.assign({}, DEFAULT_SETTINGS, yield this.loadData());
|
|
});
|
|
}
|
|
saveSettings() {
|
|
return __async(this, null, function* () {
|
|
yield this.saveData(this.settings);
|
|
});
|
|
}
|
|
showRibbonButton() {
|
|
this.ribbonIcon = this.addRibbonIcon("JumpToDate", "Jump-to-Date", () => __async(this, null, function* () {
|
|
return;
|
|
}));
|
|
setTimeout(() => {
|
|
const ribbonButton = document.querySelector('.side-dock-ribbon-action[aria-label="Jump-to-Date');
|
|
if (ribbonButton) {
|
|
ribbonButton.addEventListener("mouseup", (event) => __async(this, null, function* () {
|
|
event.preventDefault();
|
|
if (event.button === 2)
|
|
yield this.navigateToDNP((0, import_obsidian6.moment)().format("YYYY-MM-DD"), false, event.ctrlKey, event.shiftKey);
|
|
else
|
|
this.datePicker.open();
|
|
}));
|
|
}
|
|
}, 2e3);
|
|
}
|
|
setFirstDayofWeek(dayOfWeek) {
|
|
this.datePicker.setFirstDayofWeek(dayOfWeek);
|
|
}
|
|
navigateToDNP(dateStr, shouldConfirmBeforeCreate = true, newPane = false, newHorizontalPane = false) {
|
|
return __async(this, null, function* () {
|
|
const openFile = (fileToOpen, openInNewPane, openInHorizontalPane) => {
|
|
if (newPane && openInHorizontalPane) {
|
|
const newLeaf = app.workspace.splitActiveLeaf("horizontal");
|
|
newLeaf.openFile(fileToOpen, { active: true });
|
|
} else if (openInNewPane) {
|
|
const newLeaf = app.workspace.splitActiveLeaf("vertical");
|
|
newLeaf.openFile(fileToOpen, { active: true });
|
|
} else {
|
|
app.workspace.getLeaf().openFile(fileToOpen);
|
|
}
|
|
};
|
|
const dateForDNPToOpen = (0, import_obsidian6.moment)(new Date(dateStr + "T00:00:00"));
|
|
const dnpFileThatExistsInVault = (0, import_obsidian_daily_notes_interface2.getDailyNote)(dateForDNPToOpen, (0, import_obsidian_daily_notes_interface2.getAllDailyNotes)());
|
|
if (dnpFileThatExistsInVault != null) {
|
|
openFile(dnpFileThatExistsInVault, newPane, newHorizontalPane);
|
|
} else {
|
|
if (shouldConfirmBeforeCreate === true) {
|
|
createConfirmationDialog({
|
|
cta: "Create",
|
|
onAccept: (dateStr2) => __async(this, null, function* () {
|
|
const newDate = (0, import_obsidian6.moment)(new Date(dateStr2));
|
|
openFile(yield (0, import_obsidian_daily_notes_interface2.createDailyNote)(newDate), newPane, newHorizontalPane);
|
|
}),
|
|
text: `File ${dateStr} does not exist. Would you like to create it?`,
|
|
title: "New Daily Note",
|
|
fileDate: dateForDNPToOpen.format("YYYY-MM-DD") + "T00:00:00"
|
|
});
|
|
} else {
|
|
openFile(yield (0, import_obsidian_daily_notes_interface2.createDailyNote)(dateForDNPToOpen), newPane, newHorizontalPane);
|
|
}
|
|
}
|
|
});
|
|
}
|
|
};
|