1285 lines
46 KiB
JavaScript
1285 lines
46 KiB
JavaScript
'use strict';
|
||
|
||
const {
|
||
Plugin, BasesView, Modal, Setting, PluginSettingTab, Notice, setIcon, normalizePath,
|
||
} = require('obsidian');
|
||
|
||
const VIEW_ID = 'bases-calendar';
|
||
const MIN = 60000;
|
||
const DAY_MS = 86400000;
|
||
const PRESET_COLORS = ['#e5484d', '#f76b15', '#f5c518', '#30a46c', '#12a594', '#0091ff', '#6e56cf', '#d6409f', '#8b8d98'];
|
||
const PALETTE = ['#8e44ad', '#2980b9', '#16a085', '#d35400', '#c0392b', '#7f8c8d', '#27ae60', '#f39c12', '#e84393', '#0984e3'];
|
||
|
||
const DEFAULT_SETTINGS = {
|
||
folder: 'Kalender',
|
||
snapMinutes: 15,
|
||
dayStartHour: 6,
|
||
dayEndHour: 22,
|
||
hourHeight: 48,
|
||
weekStart: 1,
|
||
statusColors: {
|
||
Offen: '#2980b9',
|
||
'In Arbeit': '#f39c12',
|
||
Erledigt: '#27ae60',
|
||
Wichtig: '#c0392b',
|
||
},
|
||
};
|
||
|
||
/* ---------- Hilfsfunktionen: Datum ---------- */
|
||
|
||
const pad = (n) => String(n).padStart(2, '0');
|
||
const fmtDate = (d) => `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`;
|
||
const fmtDateTime = (d) => `${fmtDate(d)}T${pad(d.getHours())}:${pad(d.getMinutes())}`;
|
||
const fmtTime = (d) => `${pad(d.getHours())}:${pad(d.getMinutes())}`;
|
||
const startOfDay = (d) => new Date(d.getFullYear(), d.getMonth(), d.getDate());
|
||
const addDays = (d, n) => { const r = new Date(d); r.setDate(r.getDate() + n); return r; };
|
||
const isWeekend = (d) => d.getDay() === 0 || d.getDay() === 6;
|
||
const dayDiff = (a, b) => Math.round((startOfDay(a) - startOfDay(b)) / DAY_MS);
|
||
const minutesOf = (d) => d.getHours() * 60 + d.getMinutes();
|
||
|
||
function parseDT(value) {
|
||
if (value === undefined || value === null) return null;
|
||
const m = String(value).trim().match(/^(\d{4})-(\d{2})-(\d{2})(?:[T ](\d{2}):(\d{2}))?/);
|
||
if (!m) return null;
|
||
return {
|
||
date: new Date(+m[1], +m[2] - 1, +m[3], +(m[4] || 0), +(m[5] || 0)),
|
||
hasTime: m[4] !== undefined,
|
||
};
|
||
}
|
||
|
||
function isoWeek(d) {
|
||
const t = new Date(Date.UTC(d.getFullYear(), d.getMonth(), d.getDate()));
|
||
t.setUTCDate(t.getUTCDate() + 4 - (t.getUTCDay() || 7));
|
||
const y0 = new Date(Date.UTC(t.getUTCFullYear(), 0, 1));
|
||
return Math.ceil(((t - y0) / DAY_MS + 1) / 7);
|
||
}
|
||
|
||
function isBar(ev) {
|
||
return ev.allDay || startOfDay(ev.start).getTime() !== startOfDay(new Date(ev.end.getTime() - 1)).getTime();
|
||
}
|
||
|
||
function timeRange(ev) {
|
||
if (ev.allDay) return '';
|
||
const sameDay = dayDiff(ev.end, ev.start) === 0 || (ev.end.getHours() === 0 && ev.end.getMinutes() === 0 && dayDiff(ev.end, ev.start) === 1);
|
||
if (!sameDay) return `${fmtDate(ev.start)} ${fmtTime(ev.start)} – ${fmtDate(ev.end)} ${fmtTime(ev.end)}`;
|
||
return `${fmtTime(ev.start)}–${fmtTime(ev.end)}`;
|
||
}
|
||
|
||
/* ---------- Hilfsfunktionen: Farben ---------- */
|
||
|
||
function hexToRgb(hex) {
|
||
if (typeof hex !== 'string') return null;
|
||
let h = hex.trim().replace('#', '');
|
||
if (h.length === 3) h = h.split('').map((c) => c + c).join('');
|
||
if (!/^[0-9a-f]{6}$/i.test(h)) return null;
|
||
return [parseInt(h.slice(0, 2), 16), parseInt(h.slice(2, 4), 16), parseInt(h.slice(4, 6), 16)];
|
||
}
|
||
|
||
function contrastFg(hex) {
|
||
const rgb = hexToRgb(hex);
|
||
if (!rgb) return '#ffffff';
|
||
return (0.299 * rgb[0] + 0.587 * rgb[1] + 0.114 * rgb[2]) > 160 ? '#1a1a1a' : '#ffffff';
|
||
}
|
||
|
||
function setColor(el, color) {
|
||
if (!hexToRgb(color)) return;
|
||
el.style.setProperty('--bc-color', color);
|
||
el.style.setProperty('--bc-fg', contrastFg(color));
|
||
}
|
||
|
||
/* ---------- Hilfsfunktionen: Notiz-Inhalt ---------- */
|
||
|
||
function splitFrontmatter(text) {
|
||
const m = text.match(/^---\r?\n[\s\S]*?\r?\n---[ \t]*(?:\r?\n|$)/);
|
||
return m ? [m[0], text.slice(m[0].length)] : ['', text];
|
||
}
|
||
|
||
function findSection(lines, heading) {
|
||
const re = new RegExp(`^##\\s+${heading}\\s*$`, 'i');
|
||
return lines.findIndex((l) => re.test(l));
|
||
}
|
||
|
||
function getSection(lines, heading) {
|
||
const idx = findSection(lines, heading);
|
||
if (idx < 0) return '';
|
||
let j = idx + 1;
|
||
while (j < lines.length && !/^#{1,2}\s/.test(lines[j])) j++;
|
||
return lines.slice(idx + 1, j).join('\n').trim();
|
||
}
|
||
|
||
function setSection(lines, heading, value) {
|
||
const block = value ? value.replace(/\r\n/g, '\n').split('\n') : [];
|
||
const idx = findSection(lines, heading);
|
||
if (idx < 0) {
|
||
while (lines.length && lines[lines.length - 1].trim() === '') lines.pop();
|
||
if (lines.length) lines.push('');
|
||
lines.push(`## ${heading}`, ...block, '');
|
||
return lines;
|
||
}
|
||
let j = idx + 1;
|
||
while (j < lines.length && !/^#{1,2}\s/.test(lines[j])) j++;
|
||
lines.splice(idx + 1, j - idx - 1, ...block, '');
|
||
return lines;
|
||
}
|
||
|
||
function applyBody(text, title, description) {
|
||
const [fm, body] = splitFrontmatter(text);
|
||
let lines = body.replace(/\r\n/g, '\n').split('\n');
|
||
lines = setSection(lines, 'Titel', title);
|
||
lines = setSection(lines, 'Beschreibung', description);
|
||
return fm + lines.join('\n');
|
||
}
|
||
|
||
const TASK_RE = /^\s*[-*+]\s+\[([ xX])\]\s*(.*?)\r?$/;
|
||
|
||
function parseDescription(desc) {
|
||
let t = 0;
|
||
return desc.split(/\r?\n/).filter((l) => l.trim()).map((l) => {
|
||
const m = l.match(TASK_RE);
|
||
return m ? { task: true, done: m[1] !== ' ', text: m[2], index: t++ } : { task: false, text: l.trim() };
|
||
});
|
||
}
|
||
|
||
function normStatus(v) {
|
||
if (Array.isArray(v)) return v.map((s) => String(s).trim()).filter(Boolean);
|
||
if (v === undefined || v === null || v === '') return [];
|
||
return [String(v).trim()];
|
||
}
|
||
|
||
function fmStrings(start, end, allDay) {
|
||
return allDay
|
||
? { start: fmtDate(start), end: fmtDate(addDays(end, -1)) }
|
||
: { start: fmtDateTime(start), end: fmtDateTime(end) };
|
||
}
|
||
|
||
function readEvent(file, fm, content) {
|
||
const s = parseDT(fm.start);
|
||
if (!s) return null;
|
||
const allDay = fm.allDay === true || String(fm.allDay).toLowerCase() === 'true' || !s.hasTime;
|
||
const e = fm.end ? parseDT(fm.end) : null;
|
||
let start;
|
||
let end;
|
||
if (allDay) {
|
||
start = startOfDay(s.date);
|
||
let ed = e ? startOfDay(e.date) : start;
|
||
if (ed < start) ed = start;
|
||
end = addDays(ed, 1);
|
||
} else {
|
||
start = s.date;
|
||
end = e && e.date > start ? e.date : new Date(start.getTime() + 60 * MIN);
|
||
}
|
||
return {
|
||
file,
|
||
title: (content && content.title) || file.basename,
|
||
description: (content && content.description) || '',
|
||
start,
|
||
end,
|
||
allDay,
|
||
color: typeof fm.color === 'string' ? fm.color : '',
|
||
status: normStatus(fm.status),
|
||
};
|
||
}
|
||
|
||
/* ---------- Dialog ---------- */
|
||
|
||
class EventModal extends Modal {
|
||
constructor(app, plugin, data, handlers) {
|
||
super(app);
|
||
this.plugin = plugin;
|
||
this.data = data;
|
||
this.h = handlers;
|
||
this.deleteArmed = false;
|
||
}
|
||
|
||
onOpen() {
|
||
const { contentEl, data, plugin } = this;
|
||
contentEl.empty();
|
||
contentEl.classList.add('bc-modal');
|
||
this.titleEl.setText(data.isNew ? 'Neuer Termin' : 'Termin bearbeiten');
|
||
|
||
const lastDay = data.allDay ? addDays(data.end, -1) : data.end;
|
||
const f = {
|
||
title: data.title,
|
||
description: data.description,
|
||
allDay: data.allDay,
|
||
sDate: fmtDate(data.start),
|
||
sTime: fmtTime(data.start),
|
||
eDate: fmtDate(lastDay),
|
||
eTime: fmtTime(data.end),
|
||
color: data.color || '',
|
||
status: [...data.status],
|
||
};
|
||
this.f = f;
|
||
|
||
new Setting(contentEl).setName('Titel').addText((t) => {
|
||
t.setPlaceholder('Titel des Termins').setValue(f.title).onChange((v) => { f.title = v; });
|
||
t.inputEl.addEventListener('keydown', (e) => { if (e.key === 'Enter') this.save(); });
|
||
setTimeout(() => t.inputEl.focus(), 0);
|
||
});
|
||
|
||
contentEl.createDiv({ cls: 'bc-field-label', text: 'Beschreibung' });
|
||
const ta = contentEl.createEl('textarea');
|
||
ta.value = f.description;
|
||
ta.addEventListener('input', () => { f.description = ta.value; });
|
||
|
||
new Setting(contentEl).setName('Ganztägig').addToggle((t) => t.setValue(f.allDay).onChange((v) => {
|
||
f.allDay = v;
|
||
sTime.style.display = v ? 'none' : '';
|
||
eTime.style.display = v ? 'none' : '';
|
||
}));
|
||
|
||
contentEl.createDiv({ cls: 'bc-field-label', text: 'Zeitraum' });
|
||
const mkRow = (label, dateKey, timeKey) => {
|
||
const row = contentEl.createDiv('bc-row');
|
||
row.createSpan({ text: label }).style.minWidth = '40px';
|
||
const d = row.createEl('input', { type: 'date' });
|
||
d.value = f[dateKey];
|
||
d.addEventListener('change', () => { f[dateKey] = d.value; });
|
||
const t = row.createEl('input', { type: 'time' });
|
||
t.value = f[timeKey];
|
||
t.addEventListener('change', () => { f[timeKey] = t.value; });
|
||
t.style.display = f.allDay ? 'none' : '';
|
||
return t;
|
||
};
|
||
const sTime = mkRow('Von', 'sDate', 'sTime');
|
||
const eTime = mkRow('Bis', 'eDate', 'eTime');
|
||
|
||
contentEl.createDiv({ cls: 'bc-field-label', text: 'Farbe' });
|
||
const sw = contentEl.createDiv('bc-swatches');
|
||
const picker = sw.createEl('input', { type: 'color' });
|
||
picker.value = hexToRgb(f.color) ? f.color : '#3b82f6';
|
||
const marks = [];
|
||
const refreshMarks = () => marks.forEach(([el, c]) => el.classList.toggle('is-on', c === f.color));
|
||
PRESET_COLORS.forEach((c) => {
|
||
const el = sw.createDiv('bc-swatch');
|
||
el.style.background = c;
|
||
el.addEventListener('click', () => { f.color = c; picker.value = c; refreshMarks(); });
|
||
marks.push([el, c]);
|
||
});
|
||
picker.addEventListener('input', () => { f.color = picker.value; refreshMarks(); });
|
||
const none = sw.createEl('button', { text: 'Keine' });
|
||
none.addEventListener('click', () => { f.color = ''; refreshMarks(); });
|
||
refreshMarks();
|
||
|
||
contentEl.createDiv({ cls: 'bc-field-label', text: 'Status' });
|
||
const box = contentEl.createDiv('bc-status-box');
|
||
const drawPills = () => {
|
||
box.empty();
|
||
const names = [...new Set([...plugin.knownStatuses(), ...f.status])];
|
||
names.forEach((n) => {
|
||
const p = box.createSpan({ cls: 'bc-pill bc-pill-toggle', text: n });
|
||
plugin.stylePill(p, n);
|
||
p.classList.toggle('is-on', f.status.includes(n));
|
||
p.addEventListener('click', () => {
|
||
f.status = f.status.includes(n) ? f.status.filter((s) => s !== n) : [...f.status, n];
|
||
drawPills();
|
||
});
|
||
});
|
||
};
|
||
drawPills();
|
||
const addRow = contentEl.createDiv('bc-row');
|
||
const statusInput = addRow.createEl('input', { type: 'text', placeholder: 'Neuer Status (Enter)' });
|
||
statusInput.style.width = 'auto';
|
||
statusInput.style.flex = '1';
|
||
const addStatus = () => {
|
||
const v = statusInput.value.trim();
|
||
if (v && !f.status.includes(v)) f.status.push(v);
|
||
statusInput.value = '';
|
||
drawPills();
|
||
};
|
||
statusInput.addEventListener('keydown', (e) => {
|
||
if (e.key === 'Enter') { e.preventDefault(); e.stopPropagation(); addStatus(); }
|
||
});
|
||
addRow.createEl('button', { text: 'Hinzufügen' }).addEventListener('click', addStatus);
|
||
|
||
const buttons = contentEl.createDiv('bc-buttons');
|
||
if (!data.isNew) {
|
||
const del = buttons.createEl('button', { text: 'Löschen', cls: 'mod-warning' });
|
||
del.addEventListener('click', async () => {
|
||
if (!this.deleteArmed) {
|
||
this.deleteArmed = true;
|
||
del.setText('Wirklich löschen?');
|
||
return;
|
||
}
|
||
await this.h.onDelete();
|
||
this.close();
|
||
});
|
||
buttons.createEl('button', { text: 'Notiz öffnen' }).addEventListener('click', () => {
|
||
this.close();
|
||
this.app.workspace.getLeaf('tab').openFile(data.file);
|
||
});
|
||
}
|
||
buttons.createDiv('bc-spacer');
|
||
buttons.createEl('button', { text: 'Abbrechen' }).addEventListener('click', () => this.close());
|
||
buttons.createEl('button', { text: 'Speichern', cls: 'mod-cta' }).addEventListener('click', () => this.save());
|
||
}
|
||
|
||
async save() {
|
||
const f = this.f;
|
||
const s = parseDT(f.allDay ? f.sDate : `${f.sDate}T${f.sTime || '00:00'}`);
|
||
if (!s) { new Notice('Bitte ein gültiges Startdatum angeben.'); return; }
|
||
const start = f.allDay ? startOfDay(s.date) : s.date;
|
||
const e = parseDT(f.allDay ? f.eDate : `${f.eDate}T${f.eTime || '00:00'}`);
|
||
let end;
|
||
if (f.allDay) {
|
||
let ed = e ? startOfDay(e.date) : start;
|
||
if (ed < start) ed = start;
|
||
end = addDays(ed, 1);
|
||
} else {
|
||
end = e ? e.date : start;
|
||
if (end <= start) end = new Date(start.getTime() + 60 * MIN);
|
||
}
|
||
const title = f.title.replace(/\s*\n\s*/g, ' ').trim() || 'Neuer Termin';
|
||
await this.h.onSave({
|
||
title,
|
||
description: f.description.trim(),
|
||
start,
|
||
end,
|
||
allDay: f.allDay,
|
||
color: f.color,
|
||
status: f.status,
|
||
});
|
||
this.close();
|
||
}
|
||
|
||
onClose() { this.contentEl.empty(); }
|
||
}
|
||
|
||
/* ---------- Kalenderansicht ---------- */
|
||
|
||
class CalendarView extends (BasesView || Object) {
|
||
constructor(controller, parentEl, plugin) {
|
||
super(controller);
|
||
this.type = VIEW_ID;
|
||
this.plugin = plugin;
|
||
this.root = parentEl.createDiv('bc-root');
|
||
this.cursor = startOfDay(new Date());
|
||
this.mode = 'month';
|
||
this.hideWeekend = false;
|
||
this.showDesc = true;
|
||
this.cfg = {};
|
||
this.files = [];
|
||
this.events = [];
|
||
this.busy = false;
|
||
this.dirty = false;
|
||
this.timer = null;
|
||
this.scrollEl = null;
|
||
plugin.views.add(this);
|
||
|
||
const cache = plugin.app.metadataCache;
|
||
this.registerEvent(cache.on('changed', (file) => {
|
||
plugin.pending.delete(file.path);
|
||
this.scheduleRender();
|
||
}));
|
||
this.registerEvent(plugin.app.vault.on('delete', () => this.scheduleRender()));
|
||
}
|
||
|
||
onunload() {
|
||
this.plugin.views.delete(this);
|
||
window.clearTimeout(this.timer);
|
||
}
|
||
|
||
onDataUpdated() {
|
||
this.syncConfig();
|
||
this.files = this.entryFiles();
|
||
this.render();
|
||
}
|
||
|
||
syncConfig() {
|
||
const get = (k) => (this.config && typeof this.config.get === 'function' ? this.config.get(k) : undefined);
|
||
const mode = get('viewMode');
|
||
const hide = get('hideWeekend');
|
||
const desc = get('showDescription');
|
||
if (mode !== this.cfg.mode) { this.cfg.mode = mode; if (mode) this.mode = mode; }
|
||
if (hide !== this.cfg.hide) { this.cfg.hide = hide; if (hide !== undefined && hide !== null) this.hideWeekend = !!hide; }
|
||
if (desc !== this.cfg.desc) { this.cfg.desc = desc; if (desc !== undefined && desc !== null) this.showDesc = !!desc; }
|
||
}
|
||
|
||
saveConfig(key, value, cfgKey) {
|
||
this.cfg[cfgKey] = value;
|
||
try {
|
||
if (this.config && typeof this.config.set === 'function') this.config.set(key, value);
|
||
} catch (e) { /* Konfiguration nicht schreibbar */ }
|
||
}
|
||
|
||
entryFiles() {
|
||
const seen = new Set();
|
||
const out = [];
|
||
const data = this.data || {};
|
||
const entries = data.groupedData ? data.groupedData.flatMap((g) => g.entries) : (data.data || []);
|
||
for (const e of entries) {
|
||
if (!e || !e.file || seen.has(e.file.path)) continue;
|
||
seen.add(e.file.path);
|
||
out.push(e.file);
|
||
}
|
||
return out;
|
||
}
|
||
|
||
buildEvents() {
|
||
const { app } = this.plugin;
|
||
const out = [];
|
||
for (const f of this.files) {
|
||
if (!app.vault.getAbstractFileByPath(f.path)) continue;
|
||
const cache = app.metadataCache.getFileCache(f);
|
||
const fm = Object.assign({}, (cache && cache.frontmatter) || {}, this.plugin.pending.get(f.path) || {});
|
||
const ev = readEvent(f, fm, this.plugin.contentCache.get(f.path));
|
||
if (!ev) continue;
|
||
ev.status.forEach((s) => this.plugin.seenStatuses.add(s));
|
||
out.push(ev);
|
||
}
|
||
return out;
|
||
}
|
||
|
||
scheduleRender() {
|
||
window.clearTimeout(this.timer);
|
||
this.timer = window.setTimeout(() => this.render(), 30);
|
||
}
|
||
|
||
async refreshContent() {
|
||
const { app, contentCache } = this.plugin;
|
||
const stale = this.files.filter((f) => {
|
||
const c = contentCache.get(f.path);
|
||
if (c && c.mtime === f.stat.mtime) return false;
|
||
const cache = app.metadataCache.getFileCache(f);
|
||
return !!(cache && cache.frontmatter && cache.frontmatter.start);
|
||
});
|
||
if (!stale.length) return;
|
||
await Promise.all(stale.map((f) => this.plugin.loadContent(f)));
|
||
if (this.root.isConnected) this.scheduleRender();
|
||
}
|
||
|
||
render() {
|
||
if (this.busy) { this.dirty = true; return; }
|
||
this.dirty = false;
|
||
const prevScroll = this.scrollEl ? this.scrollEl.scrollTop : null;
|
||
this.scrollEl = null;
|
||
this.root.empty();
|
||
this.events = this.buildEvents();
|
||
this.renderToolbar();
|
||
const body = this.root.createDiv('bc-body');
|
||
if (this.mode === 'month') this.renderMonth(body);
|
||
else this.renderTime(body, this.mode === 'week' ? 7 : 3, prevScroll);
|
||
this.refreshContent();
|
||
}
|
||
|
||
/* --- Toolbar --- */
|
||
|
||
renderToolbar() {
|
||
const bar = this.root.createDiv('bc-toolbar');
|
||
const nav = bar.createDiv('bc-btn-group');
|
||
const prev = nav.createEl('button', { attr: { 'aria-label': 'Zurück' } });
|
||
setIcon(prev, 'chevron-left');
|
||
nav.createEl('button', { text: 'Heute' }).addEventListener('click', () => {
|
||
this.cursor = startOfDay(new Date());
|
||
this.render();
|
||
});
|
||
const next = nav.createEl('button', { attr: { 'aria-label': 'Weiter' } });
|
||
setIcon(next, 'chevron-right');
|
||
prev.addEventListener('click', () => this.navigate(-1));
|
||
next.addEventListener('click', () => this.navigate(1));
|
||
bar.createDiv({ cls: 'bc-label', text: this.label() });
|
||
bar.createDiv('bc-spacer');
|
||
|
||
const label = bar.createEl('label', { cls: 'bc-weekend-toggle' });
|
||
const cb = label.createEl('input', { type: 'checkbox' });
|
||
cb.checked = this.hideWeekend;
|
||
label.createSpan({ text: 'Wochenende ausblenden' });
|
||
cb.addEventListener('change', () => {
|
||
this.hideWeekend = cb.checked;
|
||
this.saveConfig('hideWeekend', cb.checked, 'hide');
|
||
this.render();
|
||
});
|
||
|
||
const modes = bar.createDiv('bc-btn-group');
|
||
[['month', 'Monat'], ['week', 'Woche'], ['threeDay', '3 Tage']].forEach(([key, text]) => {
|
||
const b = modes.createEl('button', { text });
|
||
b.classList.toggle('is-active', this.mode === key);
|
||
b.addEventListener('click', () => {
|
||
this.mode = key;
|
||
this.saveConfig('viewMode', key, 'mode');
|
||
this.render();
|
||
});
|
||
});
|
||
|
||
const add = bar.createEl('button', { text: 'Neu', cls: 'mod-cta' });
|
||
add.addEventListener('click', () => {
|
||
const now = new Date();
|
||
const start = new Date(now.getFullYear(), now.getMonth(), now.getDate(), now.getHours() + 1, 0);
|
||
this.openCreate(start, new Date(start.getTime() + 60 * MIN), false);
|
||
});
|
||
}
|
||
|
||
label() {
|
||
const c = this.cursor;
|
||
if (this.mode === 'month') return c.toLocaleDateString('de-DE', { month: 'long', year: 'numeric' });
|
||
const days = this.timeDays(this.mode === 'week' ? 7 : 3);
|
||
const a = days[0];
|
||
const b = days[days.length - 1];
|
||
const range = `${a.toLocaleDateString('de-DE', { day: 'numeric', month: 'short' })} – ${b.toLocaleDateString('de-DE', { day: 'numeric', month: 'short', year: 'numeric' })}`;
|
||
return this.mode === 'week' ? `KW ${isoWeek(days[Math.floor(days.length / 2)])} · ${range}` : range;
|
||
}
|
||
|
||
navigate(dir) {
|
||
const c = this.cursor;
|
||
if (this.mode === 'month') {
|
||
this.cursor = new Date(c.getFullYear(), c.getMonth() + dir, 1);
|
||
} else if (this.mode === 'week') {
|
||
this.cursor = addDays(c, 7 * dir);
|
||
} else if (dir > 0) {
|
||
const ds = this.timeDays(3);
|
||
this.cursor = addDays(ds[ds.length - 1], 1);
|
||
} else {
|
||
let d = addDays(this.timeDays(3)[0], -1);
|
||
let n = 0;
|
||
let first = d;
|
||
while (n < 3) {
|
||
if (!this.hideWeekend || !isWeekend(d)) { first = d; n++; }
|
||
if (n < 3) d = addDays(d, -1);
|
||
}
|
||
this.cursor = first;
|
||
}
|
||
this.render();
|
||
}
|
||
|
||
visibleDays(start, n) {
|
||
const out = [];
|
||
for (let i = 0; i < n; i++) {
|
||
const d = addDays(start, i);
|
||
if (!this.hideWeekend || !isWeekend(d)) out.push(d);
|
||
}
|
||
return out;
|
||
}
|
||
|
||
timeDays(count) {
|
||
if (count === 7) {
|
||
const c = this.cursor;
|
||
const ws = this.plugin.settings.weekStart;
|
||
return this.visibleDays(addDays(c, -((c.getDay() - ws + 7) % 7)), 7);
|
||
}
|
||
const out = [];
|
||
let d = this.cursor;
|
||
while (out.length < count) {
|
||
if (!this.hideWeekend || !isWeekend(d)) out.push(d);
|
||
d = addDays(d, 1);
|
||
}
|
||
return out;
|
||
}
|
||
|
||
/* --- Monat --- */
|
||
|
||
renderMonth(body) {
|
||
const c = this.cursor;
|
||
const ws = this.plugin.settings.weekStart;
|
||
const first = new Date(c.getFullYear(), c.getMonth(), 1);
|
||
const gridStart = addDays(first, -((first.getDay() - ws + 7) % 7));
|
||
const last = new Date(c.getFullYear(), c.getMonth() + 1, 0);
|
||
const weeks = [];
|
||
for (let d = gridStart; d <= last; d = addDays(d, 7)) weeks.push(d);
|
||
|
||
const head = body.createDiv('bc-month-head');
|
||
const heads = this.visibleDays(gridStart, 7);
|
||
head.style.gridTemplateColumns = `repeat(${heads.length}, minmax(0, 1fr))`;
|
||
heads.forEach((d) => head.createDiv({ cls: 'bc-dow', text: d.toLocaleDateString('de-DE', { weekday: 'short' }) }));
|
||
|
||
const grid = body.createDiv('bc-month');
|
||
weeks.forEach((w) => this.renderSpanRow(grid, this.visibleDays(w, 7), { numbers: true, month: c.getMonth() }));
|
||
}
|
||
|
||
/* Zeile mit Tageszellen und zeilenübergreifenden Balken */
|
||
renderSpanRow(parent, days, opts) {
|
||
const n = days.length;
|
||
const segs = this.segments(days, opts.filter);
|
||
const laneCount = this.assignLanes(segs);
|
||
const offset = opts.numbers ? 1 : 0;
|
||
const total = offset + laneCount + 1;
|
||
const row = parent.createDiv({ cls: opts.numbers ? 'bc-weekrow' : ['bc-weekrow', 'bc-allday-row'] });
|
||
row.style.gridTemplateColumns = `repeat(${n}, minmax(0, 1fr))`;
|
||
row.style.gridTemplateRows = `${opts.numbers ? 'auto ' : ''}${'auto '.repeat(laneCount)}minmax(4px, 1fr)`;
|
||
const today = startOfDay(new Date()).getTime();
|
||
|
||
days.forEach((d, i) => {
|
||
const cell = row.createDiv({ cls: 'bc-cell', attr: { 'data-date': fmtDate(d) } });
|
||
cell.style.gridColumn = String(i + 1);
|
||
cell.style.gridRow = `1 / span ${total}`;
|
||
if (isWeekend(d)) cell.classList.add('is-weekend');
|
||
if (opts.numbers && d.getMonth() !== opts.month) cell.classList.add('is-other');
|
||
cell.addEventListener('pointerdown', (e) => this.beginSelectDay(e));
|
||
if (opts.numbers) {
|
||
const num = row.createDiv({ cls: 'bc-daynum' });
|
||
num.style.gridColumn = String(i + 1);
|
||
num.style.gridRow = '1';
|
||
const label = d.getDate() === 1 ? d.toLocaleDateString('de-DE', { day: 'numeric', month: 'short' }) : String(d.getDate());
|
||
num.createSpan({ text: label });
|
||
if (d.getTime() === today) num.classList.add('is-today');
|
||
}
|
||
});
|
||
|
||
segs.forEach((s) => {
|
||
const ev = s.ev;
|
||
const bar = isBar(ev);
|
||
const el = row.createDiv({ cls: ['bc-event', 'bc-chip', bar ? 'bc-bar' : 'bc-dot'] });
|
||
el.style.gridColumn = `${s.from + 1} / ${s.to + 2}`;
|
||
el.style.gridRow = String(offset + s.lane + 1);
|
||
if (s.contL) el.classList.add('is-cont-l');
|
||
if (s.contR) el.classList.add('is-cont-r');
|
||
el.setAttribute('title', [timeRange(ev), ev.title, ev.description].filter(Boolean).join('\n'));
|
||
this.fillEvent(el, ev, { time: !bar ? fmtTime(ev.start) : '' });
|
||
el.addEventListener('pointerdown', (e) => this.beginMove(e, ev, el));
|
||
});
|
||
}
|
||
|
||
segments(days, filter) {
|
||
const segs = [];
|
||
for (const ev of this.events) {
|
||
if (filter && !filter(ev)) continue;
|
||
const sd = startOfDay(ev.start);
|
||
const ed = startOfDay(new Date(ev.end.getTime() - 1));
|
||
let from = -1;
|
||
let to = -1;
|
||
days.forEach((d, i) => {
|
||
if (d >= sd && d <= ed) { if (from < 0) from = i; to = i; }
|
||
});
|
||
if (from < 0) continue;
|
||
segs.push({ ev, from, to, contL: sd < days[from], contR: ed > days[to] });
|
||
}
|
||
return segs;
|
||
}
|
||
|
||
assignLanes(segs) {
|
||
segs.sort((a, b) => (a.from - b.from) || ((b.to - b.from) - (a.to - a.from)) || (a.ev.start - b.ev.start));
|
||
const ends = [];
|
||
for (const s of segs) {
|
||
let l = ends.findIndex((e) => e < s.from);
|
||
if (l < 0) { l = ends.length; ends.push(-1); }
|
||
ends[l] = s.to;
|
||
s.lane = l;
|
||
}
|
||
return ends.length;
|
||
}
|
||
|
||
fillEvent(el, ev, o) {
|
||
setColor(el, ev.color);
|
||
const head = el.createDiv('bc-ev-head');
|
||
if (o.time) head.createSpan({ cls: 'bc-ev-time', text: o.time });
|
||
head.createSpan({ cls: 'bc-ev-title', text: ev.title });
|
||
if (ev.status.length) {
|
||
const holder = o.block ? el.createDiv('bc-pills') : head.createSpan('bc-pills');
|
||
ev.status.forEach((s) => {
|
||
const p = holder.createSpan({ cls: 'bc-pill', text: s });
|
||
this.plugin.stylePill(p, s);
|
||
});
|
||
}
|
||
if (this.showDesc && ev.description) this.renderDescription(el, ev);
|
||
}
|
||
|
||
renderDescription(el, ev) {
|
||
const box = el.createDiv('bc-ev-desc');
|
||
parseDescription(ev.description).forEach((item) => {
|
||
if (!item.task) {
|
||
box.createDiv({ cls: 'bc-desc-line', text: item.text });
|
||
return;
|
||
}
|
||
const row = box.createDiv({ cls: item.done ? ['bc-desc-line', 'bc-task', 'is-done'] : ['bc-desc-line', 'bc-task'] });
|
||
const cb = row.createEl('input', { type: 'checkbox' });
|
||
cb.checked = item.done;
|
||
cb.addEventListener('pointerdown', (e) => e.stopPropagation());
|
||
cb.addEventListener('click', (e) => e.stopPropagation());
|
||
cb.addEventListener('change', () => this.plugin.toggleTask(ev.file, item.index, cb.checked));
|
||
row.createSpan({ cls: 'bc-desc-text', text: item.text });
|
||
});
|
||
}
|
||
|
||
/* --- Woche / 3 Tage --- */
|
||
|
||
renderTime(body, count, prevScroll) {
|
||
const s = this.plugin.settings;
|
||
const hh = s.hourHeight;
|
||
const startH = Math.min(s.dayStartHour, 23);
|
||
const endH = Math.max(s.dayEndHour, startH + 1);
|
||
const days = this.timeDays(count);
|
||
const n = days.length;
|
||
const cols = `repeat(${n}, minmax(0, 1fr))`;
|
||
const totalH = (endH - startH) * hh;
|
||
const today = startOfDay(new Date()).getTime();
|
||
|
||
const scroll = body.createDiv('bc-tg');
|
||
scroll.style.setProperty('--bc-hh', `${hh}px`);
|
||
this.scrollEl = scroll;
|
||
|
||
const sticky = scroll.createDiv('bc-tg-sticky');
|
||
const hrow = sticky.createDiv('bc-tg-head');
|
||
hrow.createDiv('bc-gutter');
|
||
const hdays = hrow.createDiv({ cls: ['bc-tg-days', 'bc-head-days'] });
|
||
hdays.style.gridTemplateColumns = cols;
|
||
days.forEach((d) => {
|
||
const h = hdays.createDiv({ cls: 'bc-dayhead', text: d.toLocaleDateString('de-DE', { weekday: 'short', day: 'numeric', month: 'numeric' }) });
|
||
if (d.getTime() === today) h.classList.add('is-today');
|
||
});
|
||
|
||
const arow = sticky.createDiv('bc-tg-allday');
|
||
arow.createDiv({ cls: 'bc-gutter', text: 'Ganztag' });
|
||
const awrap = arow.createDiv('bc-tg-days');
|
||
this.renderSpanRow(awrap, days, { numbers: false, filter: (ev) => ev.allDay });
|
||
|
||
const tbody = scroll.createDiv('bc-tg-body');
|
||
const gut = tbody.createDiv({ cls: ['bc-gutter', 'bc-hours'] });
|
||
for (let h = startH; h < endH; h++) {
|
||
const l = gut.createDiv({ cls: 'bc-hour-label', text: `${pad(h)}:00` });
|
||
l.style.height = `${hh}px`;
|
||
}
|
||
const colsEl = tbody.createDiv({ cls: ['bc-tg-days', 'bc-cols'] });
|
||
colsEl.style.gridTemplateColumns = cols;
|
||
days.forEach((d) => {
|
||
const col = colsEl.createDiv({ cls: 'bc-col', attr: { 'data-date': fmtDate(d) } });
|
||
col.style.height = `${totalH}px`;
|
||
if (isWeekend(d)) col.classList.add('is-weekend');
|
||
col.addEventListener('pointerdown', (e) => { if (e.target === col) this.beginSelectTime(e); });
|
||
this.layoutDay(col, d, startH, endH);
|
||
if (d.getTime() === today) {
|
||
const m = minutesOf(new Date());
|
||
if (m >= startH * 60 && m <= endH * 60) {
|
||
const line = col.createDiv('bc-now');
|
||
line.style.top = `${((m - startH * 60) * hh) / 60}px`;
|
||
}
|
||
}
|
||
});
|
||
|
||
scroll.scrollTop = prevScroll !== null && prevScroll !== undefined
|
||
? prevScroll
|
||
: Math.max(0, (8 - startH) * hh);
|
||
}
|
||
|
||
layoutDay(col, day, startH, endH) {
|
||
const hh = this.plugin.settings.hourHeight;
|
||
const dayStartMin = startH * 60;
|
||
const dayEndMin = endH * 60;
|
||
const d0 = startOfDay(day);
|
||
const d1 = addDays(d0, 1);
|
||
const items = [];
|
||
for (const ev of this.events) {
|
||
if (ev.allDay || ev.end <= d0 || ev.start >= d1) continue;
|
||
const sMin = ev.start >= d0 ? minutesOf(ev.start) : 0;
|
||
const endsHere = ev.end < d1;
|
||
const eMin = endsHere ? minutesOf(ev.end) : 1440;
|
||
const vs = Math.max(sMin, dayStartMin);
|
||
const ve = Math.min(eMin, dayEndMin);
|
||
if (ve <= vs) continue;
|
||
items.push({ ev, vs, ve, canResize: endsHere && ve === eMin });
|
||
}
|
||
items.sort((a, b) => (a.vs - b.vs) || (b.ve - a.ve));
|
||
|
||
let cluster = [];
|
||
let clusterEnd = -1;
|
||
let colEnds = [];
|
||
const flush = () => { cluster.forEach((it) => { it.cols = colEnds.length; }); cluster = []; colEnds = []; };
|
||
for (const it of items) {
|
||
if (cluster.length && it.vs >= clusterEnd) flush();
|
||
let c = colEnds.findIndex((e) => e <= it.vs);
|
||
if (c < 0) { c = colEnds.length; colEnds.push(0); }
|
||
colEnds[c] = it.ve;
|
||
it.col = c;
|
||
cluster.push(it);
|
||
clusterEnd = Math.max(clusterEnd, it.ve);
|
||
}
|
||
flush();
|
||
|
||
for (const it of items) {
|
||
const ev = it.ev;
|
||
const el = col.createDiv({ cls: ['bc-event', 'bc-tevent'] });
|
||
el.style.top = `${((it.vs - dayStartMin) * hh) / 60}px`;
|
||
el.style.height = `${Math.max(((it.ve - it.vs) * hh) / 60 - 1, 18)}px`;
|
||
el.style.left = `calc(${it.col} / ${it.cols} * 100% + 1px)`;
|
||
el.style.width = `calc(100% / ${it.cols} - 3px)`;
|
||
el.setAttribute('title', [timeRange(ev), ev.title, ev.description].filter(Boolean).join('\n'));
|
||
this.fillEvent(el, ev, { time: timeRange(ev), block: true });
|
||
el.addEventListener('pointerdown', (e) => this.beginMove(e, ev, el));
|
||
if (it.canResize) {
|
||
const h = el.createDiv('bc-resize');
|
||
h.addEventListener('pointerdown', (e) => this.beginResize(e, ev, el));
|
||
}
|
||
}
|
||
}
|
||
|
||
/* --- Interaktion --- */
|
||
|
||
dayElAt(x, y, doc) {
|
||
return doc.elementsFromPoint(x, y).find((e) => e.classList.contains('bc-cell') || e.classList.contains('bc-col'));
|
||
}
|
||
|
||
openCreate(start, end, allDay) {
|
||
new EventModal(this.plugin.app, this.plugin, {
|
||
isNew: true, title: '', description: '', start, end, allDay, color: '', status: [],
|
||
}, {
|
||
onSave: (d) => this.plugin.createEvent(d),
|
||
}).open();
|
||
}
|
||
|
||
openEdit(ev) {
|
||
new EventModal(this.plugin.app, this.plugin, Object.assign({ isNew: false }, ev), {
|
||
onSave: (d) => this.plugin.updateEvent(ev.file, d),
|
||
onDelete: () => this.plugin.deleteEvent(ev.file),
|
||
}).open();
|
||
}
|
||
|
||
finishInteraction() {
|
||
this.busy = false;
|
||
this.render();
|
||
}
|
||
|
||
beginSelectDay(down) {
|
||
if (down.button !== 0) return;
|
||
const doc = down.target.ownerDocument;
|
||
const cellDate = (el) => parseDT(el.dataset.date).date;
|
||
const anchorEl = this.dayElAt(down.clientX, down.clientY, doc);
|
||
if (!anchorEl || !anchorEl.classList.contains('bc-cell')) return;
|
||
down.preventDefault();
|
||
this.busy = true;
|
||
const anchor = cellDate(anchorEl);
|
||
let cur = anchor;
|
||
const cells = [...this.root.querySelectorAll('.bc-cell')];
|
||
const draw = () => {
|
||
const lo = anchor < cur ? anchor : cur;
|
||
const hi = anchor < cur ? cur : anchor;
|
||
cells.forEach((c) => {
|
||
const d = cellDate(c);
|
||
c.classList.toggle('bc-sel-cell', d >= lo && d <= hi);
|
||
});
|
||
};
|
||
draw();
|
||
const onMove = (e) => {
|
||
const el = this.dayElAt(e.clientX, e.clientY, doc);
|
||
if (el && el.classList.contains('bc-cell')) { cur = cellDate(el); draw(); }
|
||
};
|
||
const stop = () => {
|
||
doc.removeEventListener('pointermove', onMove);
|
||
doc.removeEventListener('pointerup', onUp);
|
||
doc.removeEventListener('keydown', onKey);
|
||
};
|
||
const onUp = () => {
|
||
stop();
|
||
const lo = anchor < cur ? anchor : cur;
|
||
const hi = anchor < cur ? cur : anchor;
|
||
this.finishInteraction();
|
||
this.openCreate(lo, addDays(hi, 1), true);
|
||
};
|
||
const onKey = (e) => { if (e.key === 'Escape') { stop(); this.finishInteraction(); } };
|
||
doc.addEventListener('pointermove', onMove);
|
||
doc.addEventListener('pointerup', onUp);
|
||
doc.addEventListener('keydown', onKey);
|
||
}
|
||
|
||
beginSelectTime(down) {
|
||
if (down.button !== 0) return;
|
||
const doc = down.target.ownerDocument;
|
||
const s = this.plugin.settings;
|
||
const snap = s.snapMinutes;
|
||
const hh = s.hourHeight;
|
||
const startMin = Math.min(s.dayStartHour, 23) * 60;
|
||
const endMin = Math.max(s.dayEndHour, Math.min(s.dayStartHour, 23) + 1) * 60;
|
||
|
||
const timeAt = (x, y) => {
|
||
const col = doc.elementsFromPoint(x, y).find((e) => e.classList.contains('bc-col'));
|
||
if (!col) return null;
|
||
const rect = col.getBoundingClientRect();
|
||
let m = startMin + ((y - rect.top) / hh) * 60;
|
||
m = Math.max(startMin, Math.min(endMin - snap, m));
|
||
m = Math.floor(m / snap) * snap;
|
||
const d = parseDT(col.dataset.date).date;
|
||
return new Date(d.getFullYear(), d.getMonth(), d.getDate(), 0, m);
|
||
};
|
||
const anchor = timeAt(down.clientX, down.clientY);
|
||
if (!anchor) return;
|
||
down.preventDefault();
|
||
this.busy = true;
|
||
let cur = anchor;
|
||
let moved = false;
|
||
const cols = [...this.root.querySelectorAll('.bc-col')];
|
||
const range = () => {
|
||
const lo = anchor < cur ? anchor : cur;
|
||
const hi = anchor < cur ? cur : anchor;
|
||
return [lo, moved ? new Date(hi.getTime() + snap * MIN) : new Date(lo.getTime() + 60 * MIN)];
|
||
};
|
||
const draw = () => {
|
||
this.root.querySelectorAll('.bc-sel').forEach((e) => e.remove());
|
||
const [lo, hi] = range();
|
||
cols.forEach((c) => {
|
||
const d0 = parseDT(c.dataset.date).date;
|
||
const d1 = addDays(d0, 1);
|
||
const a = lo > d0 ? lo : d0;
|
||
const b = hi < d1 ? hi : d1;
|
||
if (b <= a) return;
|
||
const aMin = Math.max(minutesOf(a), startMin);
|
||
const bMin = b >= d1 ? 1440 : minutesOf(b);
|
||
const el = c.createDiv('bc-sel');
|
||
el.style.top = `${((aMin - startMin) * hh) / 60}px`;
|
||
el.style.height = `${(Math.max(bMin - aMin, snap) * hh) / 60}px`;
|
||
});
|
||
};
|
||
draw();
|
||
const onMove = (e) => {
|
||
const t = timeAt(e.clientX, e.clientY);
|
||
if (!t) return;
|
||
cur = t;
|
||
if (cur.getTime() !== anchor.getTime()) moved = true;
|
||
draw();
|
||
};
|
||
const stop = () => {
|
||
doc.removeEventListener('pointermove', onMove);
|
||
doc.removeEventListener('pointerup', onUp);
|
||
doc.removeEventListener('keydown', onKey);
|
||
};
|
||
const onUp = () => {
|
||
stop();
|
||
const [lo, hi] = range();
|
||
this.finishInteraction();
|
||
this.openCreate(lo, hi, false);
|
||
};
|
||
const onKey = (e) => { if (e.key === 'Escape') { stop(); this.finishInteraction(); } };
|
||
doc.addEventListener('pointermove', onMove);
|
||
doc.addEventListener('pointerup', onUp);
|
||
doc.addEventListener('keydown', onKey);
|
||
}
|
||
|
||
beginMove(down, ev, el) {
|
||
if (down.button !== 0) return;
|
||
down.preventDefault();
|
||
down.stopPropagation();
|
||
const doc = el.ownerDocument;
|
||
const s = this.plugin.settings;
|
||
const hh = s.hourHeight;
|
||
const snap = s.snapMinutes;
|
||
const inGrid = el.classList.contains('bc-tevent');
|
||
const x0 = down.clientX;
|
||
const y0 = down.clientY;
|
||
const anchorEl = this.dayElAt(x0, y0, doc);
|
||
let moved = false;
|
||
let dd = 0;
|
||
let mm = 0;
|
||
let targetEl = anchorEl;
|
||
let highlighted = null;
|
||
|
||
const onMove = (e) => {
|
||
if (!moved) {
|
||
if (Math.hypot(e.clientX - x0, e.clientY - y0) < 5) return;
|
||
moved = true;
|
||
this.busy = true;
|
||
el.classList.add('bc-dragging');
|
||
}
|
||
const t = this.dayElAt(e.clientX, e.clientY, doc);
|
||
if (t) targetEl = t;
|
||
dd = targetEl && anchorEl ? dayDiff(parseDT(targetEl.dataset.date).date, parseDT(anchorEl.dataset.date).date) : 0;
|
||
if (inGrid) {
|
||
mm = Math.round(((e.clientY - y0) / hh) * 60 / snap) * snap;
|
||
const dx = targetEl && anchorEl ? targetEl.getBoundingClientRect().left - anchorEl.getBoundingClientRect().left : 0;
|
||
el.style.transform = `translate(${dx}px, ${(mm * hh) / 60}px)`;
|
||
} else {
|
||
mm = 0;
|
||
el.style.transform = `translate(${e.clientX - x0}px, ${e.clientY - y0}px)`;
|
||
if (highlighted) highlighted.classList.remove('bc-drop-target');
|
||
highlighted = targetEl && targetEl.classList.contains('bc-cell') ? targetEl : null;
|
||
if (highlighted) highlighted.classList.add('bc-drop-target');
|
||
}
|
||
};
|
||
const stop = () => {
|
||
doc.removeEventListener('pointermove', onMove);
|
||
doc.removeEventListener('pointerup', onUp);
|
||
doc.removeEventListener('keydown', onKey);
|
||
if (highlighted) highlighted.classList.remove('bc-drop-target');
|
||
};
|
||
const onUp = () => {
|
||
stop();
|
||
if (!moved) { this.openEdit(ev); return; }
|
||
if (dd !== 0 || mm !== 0) {
|
||
const shift = (d) => {
|
||
const r = new Date(d);
|
||
r.setDate(r.getDate() + dd);
|
||
r.setMinutes(r.getMinutes() + mm);
|
||
return r;
|
||
};
|
||
this.plugin.updateTimes(ev, shift(ev.start), shift(ev.end));
|
||
}
|
||
this.finishInteraction();
|
||
};
|
||
const onKey = (e) => { if (e.key === 'Escape') { stop(); this.finishInteraction(); } };
|
||
doc.addEventListener('pointermove', onMove);
|
||
doc.addEventListener('pointerup', onUp);
|
||
doc.addEventListener('keydown', onKey);
|
||
}
|
||
|
||
beginResize(down, ev, el) {
|
||
if (down.button !== 0) return;
|
||
down.preventDefault();
|
||
down.stopPropagation();
|
||
const doc = el.ownerDocument;
|
||
const s = this.plugin.settings;
|
||
const hh = s.hourHeight;
|
||
const snap = s.snapMinutes;
|
||
const y0 = down.clientY;
|
||
const h0 = el.offsetHeight;
|
||
const minMm = -((ev.end - ev.start) / MIN - snap);
|
||
let mm = 0;
|
||
this.busy = true;
|
||
const onMove = (e) => {
|
||
mm = Math.max(minMm, Math.round(((e.clientY - y0) / hh) * 60 / snap) * snap);
|
||
el.style.height = `${Math.max(h0 + (mm * hh) / 60, 12)}px`;
|
||
};
|
||
const stop = () => {
|
||
doc.removeEventListener('pointermove', onMove);
|
||
doc.removeEventListener('pointerup', onUp);
|
||
doc.removeEventListener('keydown', onKey);
|
||
};
|
||
const onUp = () => {
|
||
stop();
|
||
if (mm !== 0) this.plugin.updateTimes(ev, ev.start, new Date(ev.end.getTime() + mm * MIN));
|
||
this.finishInteraction();
|
||
};
|
||
const onKey = (e) => { if (e.key === 'Escape') { stop(); this.finishInteraction(); } };
|
||
doc.addEventListener('pointermove', onMove);
|
||
doc.addEventListener('pointerup', onUp);
|
||
doc.addEventListener('keydown', onKey);
|
||
}
|
||
}
|
||
|
||
/* ---------- Einstellungen ---------- */
|
||
|
||
class CalendarSettingTab extends PluginSettingTab {
|
||
constructor(app, plugin) {
|
||
super(app, plugin);
|
||
this.plugin = plugin;
|
||
}
|
||
|
||
display() {
|
||
const { containerEl } = this;
|
||
const p = this.plugin;
|
||
const s = p.settings;
|
||
containerEl.empty();
|
||
|
||
new Setting(containerEl)
|
||
.setName('Ordner für neue Termine')
|
||
.setDesc('Neue Termin-Notizen werden hier angelegt. Die Base sollte auf diesen Ordner filtern.')
|
||
.addText((t) => t.setValue(s.folder).onChange(async (v) => { s.folder = v.trim(); await p.saveSettings(); }));
|
||
|
||
new Setting(containerEl)
|
||
.setName('Raster (Minuten)')
|
||
.setDesc('Einrasten beim Aufziehen, Verschieben und Ändern der Dauer.')
|
||
.addDropdown((d) => {
|
||
[5, 10, 15, 30, 60].forEach((m) => d.addOption(String(m), String(m)));
|
||
d.setValue(String(s.snapMinutes)).onChange(async (v) => { s.snapMinutes = +v; await p.saveSettings(); });
|
||
});
|
||
|
||
new Setting(containerEl)
|
||
.setName('Tagesbeginn')
|
||
.setDesc('Erste angezeigte Stunde in Wochen- und 3-Tage-Ansicht.')
|
||
.addSlider((sl) => sl.setLimits(0, 23, 1).setValue(s.dayStartHour).setDynamicTooltip()
|
||
.onChange(async (v) => { s.dayStartHour = v; await p.saveSettings(); }));
|
||
|
||
new Setting(containerEl)
|
||
.setName('Tagesende')
|
||
.addSlider((sl) => sl.setLimits(1, 24, 1).setValue(s.dayEndHour).setDynamicTooltip()
|
||
.onChange(async (v) => { s.dayEndHour = v; await p.saveSettings(); }));
|
||
|
||
new Setting(containerEl)
|
||
.setName('Stundenhöhe (px)')
|
||
.addSlider((sl) => sl.setLimits(30, 120, 6).setValue(s.hourHeight).setDynamicTooltip()
|
||
.onChange(async (v) => { s.hourHeight = v; await p.saveSettings(); }));
|
||
|
||
new Setting(containerEl)
|
||
.setName('Wochenstart')
|
||
.addDropdown((d) => {
|
||
d.addOption('1', 'Montag').addOption('0', 'Sonntag');
|
||
d.setValue(String(s.weekStart)).onChange(async (v) => { s.weekStart = +v; await p.saveSettings(); });
|
||
});
|
||
|
||
new Setting(containerEl).setName('Status-Flags').setHeading();
|
||
Object.keys(s.statusColors).forEach((name) => {
|
||
new Setting(containerEl)
|
||
.setName(name)
|
||
.addColorPicker((c) => c.setValue(s.statusColors[name]).onChange(async (v) => { s.statusColors[name] = v; await p.saveSettings(); }))
|
||
.addExtraButton((b) => b.setIcon('trash').setTooltip('Entfernen').onClick(async () => {
|
||
delete s.statusColors[name];
|
||
await p.saveSettings();
|
||
this.display();
|
||
}));
|
||
});
|
||
|
||
let newName = '';
|
||
new Setting(containerEl)
|
||
.setName('Neuer Status')
|
||
.addText((t) => t.setPlaceholder('Name').onChange((v) => { newName = v.trim(); }))
|
||
.addButton((b) => b.setButtonText('Hinzufügen').onClick(async () => {
|
||
if (!newName || s.statusColors[newName]) return;
|
||
s.statusColors[newName] = p.statusColor(newName);
|
||
await p.saveSettings();
|
||
this.display();
|
||
}));
|
||
}
|
||
}
|
||
|
||
/* ---------- Plugin ---------- */
|
||
|
||
module.exports = class BasesCalendarPlugin extends Plugin {
|
||
async onload() {
|
||
const saved = await this.loadData();
|
||
this.settings = Object.assign({}, DEFAULT_SETTINGS, saved);
|
||
this.settings.statusColors = Object.assign({}, saved && saved.statusColors ? saved.statusColors : DEFAULT_SETTINGS.statusColors);
|
||
this.contentCache = new Map();
|
||
this.pending = new Map();
|
||
this.views = new Set();
|
||
this.seenStatuses = new Set();
|
||
|
||
this.addSettingTab(new CalendarSettingTab(this.app, this));
|
||
|
||
if (!BasesView || typeof this.registerBasesView !== 'function') {
|
||
new Notice('Bases Kalender: Obsidian 1.10 oder neuer ist erforderlich.');
|
||
return;
|
||
}
|
||
|
||
this.registerBasesView(VIEW_ID, {
|
||
name: 'Kalender',
|
||
icon: 'lucide-calendar-days',
|
||
factory: (controller, containerEl) => new CalendarView(controller, containerEl, this),
|
||
options: () => [
|
||
{
|
||
type: 'dropdown',
|
||
displayName: 'Ansicht',
|
||
key: 'viewMode',
|
||
default: 'month',
|
||
options: { month: 'Monat', week: 'Woche', threeDay: '3 Tage' },
|
||
},
|
||
{ type: 'toggle', displayName: 'Wochenende ausblenden', key: 'hideWeekend', default: false },
|
||
{ type: 'toggle', displayName: 'Beschreibung anzeigen', key: 'showDescription', default: true },
|
||
],
|
||
});
|
||
}
|
||
|
||
async saveSettings() {
|
||
await this.saveData(this.settings);
|
||
this.refreshViews();
|
||
}
|
||
|
||
refreshViews() {
|
||
for (const v of [...this.views]) {
|
||
if (!v.root.isConnected) this.views.delete(v);
|
||
else v.scheduleRender();
|
||
}
|
||
}
|
||
|
||
knownStatuses() {
|
||
return [...new Set([...Object.keys(this.settings.statusColors), ...this.seenStatuses])];
|
||
}
|
||
|
||
statusColor(name) {
|
||
const c = this.settings.statusColors[name];
|
||
if (c) return c;
|
||
let h = 0;
|
||
for (const ch of name) h = (h * 31 + ch.charCodeAt(0)) >>> 0;
|
||
return PALETTE[h % PALETTE.length];
|
||
}
|
||
|
||
stylePill(el, name) {
|
||
const c = this.statusColor(name);
|
||
el.style.setProperty('--pc', c);
|
||
el.style.setProperty('--pf', contrastFg(c));
|
||
}
|
||
|
||
setPending(path, fm) {
|
||
this.pending.set(path, Object.assign({}, this.pending.get(path) || {}, fm));
|
||
window.setTimeout(() => this.pending.delete(path), 4000);
|
||
this.refreshViews();
|
||
}
|
||
|
||
async loadContent(file) {
|
||
const mtime = file.stat.mtime;
|
||
let text;
|
||
try { text = await this.app.vault.read(file); } catch (e) { return; }
|
||
const lines = splitFrontmatter(text)[1].split(/\r?\n/);
|
||
this.contentCache.set(file.path, {
|
||
mtime,
|
||
title: getSection(lines, 'Titel').replace(/\s*\n\s*/g, ' '),
|
||
description: getSection(lines, 'Beschreibung'),
|
||
});
|
||
}
|
||
|
||
async ensureFolder(folder) {
|
||
const parts = normalizePath(folder).split('/').filter(Boolean);
|
||
let path = '';
|
||
for (const part of parts) {
|
||
path = path ? `${path}/${part}` : part;
|
||
if (!this.app.vault.getAbstractFileByPath(path)) await this.app.vault.createFolder(path);
|
||
}
|
||
}
|
||
|
||
async createEvent(d) {
|
||
const { vault } = this.app;
|
||
const folder = (this.settings.folder || '').trim();
|
||
if (folder) await this.ensureFolder(folder);
|
||
const safe = d.title.replace(/[\\/:*?"<>|#^[\]]/g, '').trim().slice(0, 80) || 'Termin';
|
||
const base = `${safe} ${fmtDate(d.start)}`;
|
||
const prefix = folder ? `${normalizePath(folder)}/` : '';
|
||
let path = `${prefix}${base}.md`;
|
||
for (let i = 2; vault.getAbstractFileByPath(path); i++) path = `${prefix}${base} ${i}.md`;
|
||
|
||
const t = fmStrings(d.start, d.end, d.allDay);
|
||
const yaml = ['---', `start: ${t.start}`, `end: ${t.end}`, `allDay: ${d.allDay}`];
|
||
if (hexToRgb(d.color)) yaml.push(`color: ${JSON.stringify(d.color)}`);
|
||
if (d.status.length) {
|
||
yaml.push('status:');
|
||
d.status.forEach((s) => yaml.push(` - ${JSON.stringify(s)}`));
|
||
}
|
||
yaml.push('---', '## Titel', d.title, '', '## Beschreibung', d.description, '');
|
||
const file = await vault.create(path, yaml.join('\n'));
|
||
this.contentCache.set(file.path, { mtime: file.stat.mtime, title: d.title, description: d.description });
|
||
this.refreshViews();
|
||
return file;
|
||
}
|
||
|
||
async updateEvent(file, d) {
|
||
const t = fmStrings(d.start, d.end, d.allDay);
|
||
const color = hexToRgb(d.color) ? d.color : '';
|
||
this.contentCache.set(file.path, { mtime: 0, title: d.title, description: d.description });
|
||
this.setPending(file.path, { start: t.start, end: t.end, allDay: d.allDay, color, status: d.status });
|
||
await this.app.fileManager.processFrontMatter(file, (fm) => {
|
||
fm.start = t.start;
|
||
fm.end = t.end;
|
||
fm.allDay = d.allDay;
|
||
if (color) fm.color = color; else delete fm.color;
|
||
if (d.status.length) fm.status = d.status; else delete fm.status;
|
||
});
|
||
await this.app.vault.process(file, (text) => applyBody(text, d.title, d.description));
|
||
}
|
||
|
||
async toggleTask(file, index, done) {
|
||
const mark = done ? '[x]' : '[ ]';
|
||
await this.app.vault.process(file, (text) => {
|
||
const [fm, body] = splitFrontmatter(text);
|
||
const lines = body.split('\n');
|
||
const idx = findSection(lines, 'Beschreibung');
|
||
if (idx < 0) return text;
|
||
let n = 0;
|
||
for (let i = idx + 1; i < lines.length && !/^#{1,2}\s/.test(lines[i]); i++) {
|
||
if (TASK_RE.test(lines[i]) && n++ === index) {
|
||
lines[i] = lines[i].replace(/\[[ xX]\]/, mark);
|
||
break;
|
||
}
|
||
}
|
||
return fm + lines.join('\n');
|
||
});
|
||
await this.loadContent(file);
|
||
this.refreshViews();
|
||
}
|
||
|
||
async updateTimes(ev, start, end) {
|
||
const t = fmStrings(start, end, ev.allDay);
|
||
this.setPending(ev.file.path, { start: t.start, end: t.end, allDay: ev.allDay });
|
||
await this.app.fileManager.processFrontMatter(ev.file, (fm) => {
|
||
fm.start = t.start;
|
||
fm.end = t.end;
|
||
});
|
||
}
|
||
|
||
async deleteEvent(file) {
|
||
await this.app.fileManager.trashFile(file);
|
||
this.refreshViews();
|
||
}
|
||
};
|