2140 lines
77 KiB
JavaScript
2140 lines
77 KiB
JavaScript
(() => {
|
||
"use strict";
|
||
const app = document.querySelector("#calendar-app");
|
||
if (!app) return;
|
||
const $ = (id) => document.getElementById(id),
|
||
ja = document.documentElement.lang.startsWith("ja");
|
||
const t = (a, b) => (ja ? a : b),
|
||
API = "/_/api/v1/extension/organizer.calendar/",
|
||
DAV = "/_/api/v1/caldav/";
|
||
let calendars = [],
|
||
enabled = [],
|
||
current = null,
|
||
actor = "",
|
||
active = false,
|
||
publicAllowed = false,
|
||
events = [],
|
||
generation = 0,
|
||
abort = null;
|
||
const calendarTimezone = app.dataset.timezone || "UTC";
|
||
const compactScreen = matchMedia('(max-width: 650px), (max-width: 950px) and (pointer: coarse)');
|
||
const touchScreen = matchMedia('(pointer: coarse)');
|
||
// Dynamic browser chrome / keyboard on iOS. Do not interfere with pinch zoom.
|
||
function updateVisibleViewport() {
|
||
const viewport=window.visualViewport;
|
||
if(viewport && viewport.scale!==1)return;
|
||
app.style.setProperty('--calendar-visual-height',(viewport?.height||innerHeight)+'px');
|
||
app.style.setProperty('--calendar-visual-top',(viewport?.offsetTop||0)+'px');
|
||
}
|
||
window.visualViewport?.addEventListener('resize',updateVisibleViewport);
|
||
window.visualViewport?.addEventListener('scroll',updateVisibleViewport);
|
||
window.addEventListener('resize',updateVisibleViewport);
|
||
updateVisibleViewport();
|
||
const zoneFormatter = new Intl.DateTimeFormat("en-CA", {
|
||
timeZone: calendarTimezone,
|
||
year: "numeric",
|
||
month: "2-digit",
|
||
day: "2-digit",
|
||
hour: "2-digit",
|
||
minute: "2-digit",
|
||
second: "2-digit",
|
||
hourCycle: "h23",
|
||
});
|
||
const timeScales = [40, 60, 90, 120, 180, 240];
|
||
const calendarViews = new Set([
|
||
"year",
|
||
"month",
|
||
"week",
|
||
"week/list",
|
||
"day",
|
||
"timeline",
|
||
"events",
|
||
]);
|
||
let timeScale = 1,
|
||
movePending = false,
|
||
cancelDrag = null;
|
||
const cache = new Map(); // Per-tab only; never persist private schedules to localStorage.
|
||
function viewPreferenceKey() {
|
||
// The preference contains only a layout name. Calendar names, event data,
|
||
// selected dates and credentials never enter browser-persistent storage.
|
||
return "pageswiki.calendar.view.v1:" +
|
||
(actor || app.dataset.actor || "anonymous");
|
||
}
|
||
function preferredView() {
|
||
try {
|
||
const value = localStorage.getItem(viewPreferenceKey());
|
||
return calendarViews.has(value) ? value : "week";
|
||
} catch (_) {
|
||
return "week";
|
||
}
|
||
}
|
||
function rememberView(value) {
|
||
if (!calendarViews.has(value)) return;
|
||
try {
|
||
localStorage.setItem(viewPreferenceKey(), value);
|
||
} catch (_) {}
|
||
}
|
||
const node = (tag, text, cls) => {
|
||
const e = document.createElement(tag);
|
||
if (text !== undefined) e.textContent = text;
|
||
if (cls) e.className = cls;
|
||
return e;
|
||
};
|
||
const pad = (n) => String(n).padStart(2, "0"),
|
||
ymd = (d) =>
|
||
`${d.getFullYear()}/${pad(d.getMonth() + 1)}/${pad(d.getDate())}`;
|
||
const dateOnly = (d) =>
|
||
`${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`;
|
||
function zoneParts(value) {
|
||
const parts = {};
|
||
zoneFormatter.formatToParts(value).forEach((part) => {
|
||
if (part.type !== "literal") parts[part.type] = Number(part.value);
|
||
});
|
||
return parts;
|
||
}
|
||
const zoneDateOnly = (value) => {
|
||
const p = zoneParts(value);
|
||
return `${p.year}-${pad(p.month)}-${pad(p.day)}`;
|
||
};
|
||
const zoneMinutes = (value) => {
|
||
const p = zoneParts(value);
|
||
return p.hour * 60 + p.minute + p.second / 60;
|
||
};
|
||
const zonedText = (value, options) =>
|
||
new Intl.DateTimeFormat(undefined, {
|
||
...options,
|
||
timeZone: calendarTimezone,
|
||
}).format(value);
|
||
function calendarToday() {
|
||
const p = zoneParts(new Date());
|
||
return new Date(p.year, p.month - 1, p.day);
|
||
}
|
||
// Convert a wall-clock value in the configured calendar timezone into an
|
||
// instant. Iterative offset correction avoids depending on the browser's
|
||
// own timezone. Ambiguous/nonexistent DST times are left for the explicit
|
||
// event editor rather than silently choosing a different instant.
|
||
function zonedInstant(day, minutes, rejectAmbiguous = true) {
|
||
const [year, month, date] = day.split("-").map(Number),
|
||
hour = Math.floor(minutes / 60),
|
||
minute = Math.floor(minutes % 60),
|
||
wanted = Date.UTC(year, month - 1, date, hour, minute);
|
||
let candidate = wanted;
|
||
for (let i = 0; i < 4; i++) {
|
||
const p = zoneParts(new Date(candidate));
|
||
const actual = Date.UTC(p.year, p.month - 1, p.day, p.hour, p.minute);
|
||
const correction = wanted - actual;
|
||
candidate += correction;
|
||
if (!correction) break;
|
||
}
|
||
const value = new Date(candidate),
|
||
p = zoneParts(value);
|
||
if (
|
||
p.year !== year ||
|
||
p.month !== month ||
|
||
p.day !== date ||
|
||
p.hour !== hour ||
|
||
p.minute !== minute
|
||
)
|
||
return null;
|
||
if (rejectAmbiguous) {
|
||
for (const offset of [-120, -90, -60, -30, 30, 60, 90, 120]) {
|
||
const other = new Date(candidate + offset * 60000),
|
||
q = zoneParts(other);
|
||
if (
|
||
q.year === year &&
|
||
q.month === month &&
|
||
q.day === date &&
|
||
q.hour === hour &&
|
||
q.minute === minute
|
||
)
|
||
return null;
|
||
}
|
||
}
|
||
return value;
|
||
}
|
||
function dayBounds(day) {
|
||
const civil = new Date(day + "T00:00:00"),
|
||
next = dateOnly(dayAdd(civil, 1));
|
||
return {
|
||
start: zonedInstant(day, 0, false),
|
||
end: zonedInstant(next, 0, false),
|
||
};
|
||
}
|
||
const snapMinutes = (pixels = timeScales[timeScale]) =>
|
||
pixels >= 180 ? 5 : pixels >= 120 ? 10 : 15;
|
||
const link = (label, href) => {
|
||
const a = node("a", label);
|
||
a.href = href;
|
||
return a;
|
||
};
|
||
const dayAdd = (d, n) =>
|
||
new Date(d.getFullYear(), d.getMonth(), d.getDate() + n);
|
||
const xml = (s) =>
|
||
s.replace(
|
||
/[<>&"']/g,
|
||
(c) =>
|
||
({
|
||
"<": "<",
|
||
">": ">",
|
||
"&": "&",
|
||
'"': """,
|
||
"'": "'",
|
||
})[c],
|
||
);
|
||
const stamp = (d) =>
|
||
d
|
||
.toISOString()
|
||
.replace(/[-:]/g, "")
|
||
.replace(/\.\d{3}Z$/, "Z");
|
||
async function request(url, options = {}) {
|
||
const r = await fetch(url, {
|
||
credentials: "same-origin",
|
||
cache: "no-store",
|
||
signal: abort?.signal,
|
||
...options,
|
||
});
|
||
if (!r.ok) {
|
||
const text = await r.text();
|
||
let message = text;
|
||
try {
|
||
message = JSON.parse(text).error || text;
|
||
} catch {}
|
||
throw new Error(message || String(r.status));
|
||
}
|
||
return r;
|
||
}
|
||
const api = async (path, method = "GET", body) => {
|
||
const r = await request(API + path, {
|
||
method,
|
||
headers: { "Content-Type": "application/json" },
|
||
body: body === undefined ? undefined : JSON.stringify(body),
|
||
});
|
||
if (r.status === 204) return null;
|
||
return r.json();
|
||
};
|
||
function pathFor(d, view) {
|
||
let path = "/v/plan/cal/" + ymd(d);
|
||
if (view === "year") path = path.slice(0, 16);
|
||
else if (view === "month") path = path.slice(0, 19);
|
||
else if (view !== "day") path += "/" + view;
|
||
return (
|
||
path +
|
||
(new URLSearchParams(location.search).has("calendar") && enabled.length
|
||
? "?calendar=" +
|
||
enabled.map((c) => encodeURIComponent(c.pretty_name)).join(",")
|
||
: "")
|
||
);
|
||
}
|
||
function route() {
|
||
const path = location.pathname;
|
||
const p = path.split("/");
|
||
const now = calendarToday();
|
||
if (path.startsWith("/v/plan/event/"))
|
||
return {
|
||
view: "detail",
|
||
uid: decodeURIComponent(path.slice("/v/plan/event/".length)),
|
||
date: now,
|
||
};
|
||
if (path.startsWith("/v/event/") && path.endsWith("/edit"))
|
||
return {
|
||
view: "edit",
|
||
uid: decodeURIComponent(path.slice("/v/event/".length, -5)),
|
||
date: now,
|
||
};
|
||
if (path === "/v/event/new") return { view: "new", date: now };
|
||
if (p[3] === "cal") {
|
||
return {
|
||
view:
|
||
p[7] === "week" && p[8] === "list"
|
||
? "week/list"
|
||
: p[7] || (p[6] ? "day" : p[5] ? "month" : "year"),
|
||
date: new Date(+p[4], p[5] ? +p[5] - 1 : 0, p[6] ? +p[6] : 1),
|
||
};
|
||
}
|
||
return { view: preferredView(), date: now };
|
||
}
|
||
function period(r) {
|
||
let start = new Date(
|
||
r.date.getFullYear(),
|
||
r.date.getMonth(),
|
||
r.date.getDate(),
|
||
),
|
||
end;
|
||
if (r.view === "year") {
|
||
start = new Date(start.getFullYear(), 0, 1);
|
||
end = new Date(start.getFullYear() + 1, 0, 1);
|
||
} else if (r.view === "month") {
|
||
start = new Date(start.getFullYear(), start.getMonth(), 1);
|
||
start = dayAdd(start, -((start.getDay() + 6) % 7));
|
||
end = dayAdd(start, 42);
|
||
} else if (r.view === "week" || r.view === "week/list") {
|
||
start = dayAdd(start, -((start.getDay() + 6) % 7));
|
||
end = dayAdd(start, 7);
|
||
} else end = dayAdd(start, r.view === "events" ? 31 : 1);
|
||
return { start, end };
|
||
}
|
||
function eventDate(e, key) {
|
||
const value = e[key];
|
||
if (e.all_day) {
|
||
const [y, m, d] = value.slice(0, 10).split("-").map(Number);
|
||
return new Date(y, m - 1, d);
|
||
}
|
||
return new Date(value);
|
||
}
|
||
function inDay(e, d) {
|
||
if (e.all_day) {
|
||
const day = dateOnly(d),
|
||
next = dateOnly(dayAdd(d, 1));
|
||
return e.start.slice(0, 10) < next && e.end.slice(0, 10) > day;
|
||
}
|
||
const bounds = dayBounds(dateOnly(d)),
|
||
start = new Date(e.start),
|
||
end = new Date(e.end);
|
||
return (
|
||
start < bounds.end &&
|
||
(end > bounds.start || (+start === +end && start >= bounds.start))
|
||
);
|
||
}
|
||
function eventLink(e) {
|
||
const calendar = calendars.find((c) => c.id === e.calendar_id) || current;
|
||
const a = link(
|
||
(e.all_day
|
||
? ""
|
||
: zonedText(new Date(e.start), {
|
||
hour: "2-digit",
|
||
minute: "2-digit",
|
||
}) + " ") + (e.summary || t("無題", "Untitled")),
|
||
"/v/plan/event/" +
|
||
encodeURIComponent(e.uid) +
|
||
"?calendar=" +
|
||
encodeURIComponent(calendar.pretty_name),
|
||
);
|
||
a.className = "calendar-event";
|
||
a.title = calendar.name + " · " + (e.summary || "");
|
||
if (enabled.length > 1) a.prepend(node("span", calendar.name + " · "));
|
||
return a;
|
||
}
|
||
function toolbar(r) {
|
||
const nav = $("calendar-nav");
|
||
nav.replaceChildren();
|
||
const labels = {
|
||
year: t("年", "Year"),
|
||
month: t("月", "Month"),
|
||
week: t("週", "Week"),
|
||
"week/list": t("週リスト", "Week list"),
|
||
day: t("日", "Day"),
|
||
timeline: t("時間軸", "Timeline"),
|
||
events: t("予定一覧", "Events"),
|
||
};
|
||
const view = labels[r.view] ? r.view : "month";
|
||
let prev, next;
|
||
if (view === "year") {
|
||
prev = new Date(r.date.getFullYear() - 1, 0, 1);
|
||
next = new Date(r.date.getFullYear() + 1, 0, 1);
|
||
} else if (view === "month") {
|
||
prev = new Date(r.date.getFullYear(), r.date.getMonth() - 1, 1);
|
||
next = new Date(r.date.getFullYear(), r.date.getMonth() + 1, 1);
|
||
} else {
|
||
const n =
|
||
view === "week" || view === "week/list"
|
||
? 7
|
||
: view === "events"
|
||
? 31
|
||
: 1;
|
||
prev = dayAdd(r.date, -n);
|
||
next = dayAdd(r.date, n);
|
||
}
|
||
nav.append(
|
||
link("‹", pathFor(prev, view)),
|
||
link(t("今日", "Today"), pathFor(calendarToday(), view)),
|
||
link("›", pathFor(next, view)),
|
||
);
|
||
for (const [key, label] of Object.entries(labels)) {
|
||
const a = link(label, pathFor(r.date, key));
|
||
a.className='calendar-view-link';
|
||
if (key === view) a.setAttribute("aria-current", "page");
|
||
nav.append(a);
|
||
}
|
||
const viewSelect=node('select');viewSelect.className='calendar-mobile-view';viewSelect.setAttribute('aria-label',t('表示形式','View'));
|
||
for(const [key,label] of Object.entries(labels)){const o=node('option',label);o.value=key;viewSelect.append(o);}
|
||
viewSelect.value=view;viewSelect.onchange=()=>navigate(pathFor(r.date,viewSelect.value));
|
||
const input = node("input");
|
||
input.type = "date";
|
||
input.value = dateOnly(r.date);
|
||
input.setAttribute("aria-label", t("日付へ移動", "Go to date"));
|
||
input.onchange = () => {
|
||
if (input.value)
|
||
navigate(pathFor(new Date(input.value + "T00:00:00"), view));
|
||
};
|
||
nav.append(input);
|
||
nav.append(viewSelect);
|
||
$("calendar-heading").textContent = current
|
||
? enabled.map((c) => c.name).join(" / ") +
|
||
" · " +
|
||
(view === "year" ? r.date.getFullYear() : dateOnly(r.date))
|
||
: t("カレンダー", "Calendar");
|
||
$("calendar-new").textContent = t("+ 予定", "+ Event");
|
||
$("calendar-new").href = pathFor(r.date, "new");
|
||
$("calendar-new").hidden = !enabled.some((c) => canWrite(c));
|
||
$("calendar-settings").hidden = !current || current.owner !== actor;
|
||
$("calendar-source-settings").hidden = !current || current.owner !== actor;
|
||
}
|
||
function canWrite(c = current) {
|
||
return (
|
||
active &&
|
||
c &&
|
||
!c.read_only &&
|
||
(c.owner === actor || c.members?.[actor] === "write" || c.can_write)
|
||
);
|
||
}
|
||
async function loadEvents(start, end, signal, calendar, budget = 5000) {
|
||
// DATE values use UTC civil dates. Widen the query one day, then filter in
|
||
// the display timezone, so all-day events at either boundary are retained.
|
||
const startBound = dayBounds(dateOnly(start)).start,
|
||
endBound = dayBounds(dateOnly(end)).start,
|
||
lo = new Date(startBound.getTime() - 86400000),
|
||
hi = new Date(endBound.getTime() + 86400000);
|
||
const body = `<c:calendar-query xmlns:d="DAV:" xmlns:c="urn:ietf:params:xml:ns:caldav"><d:prop><d:getetag/></d:prop><c:filter><c:comp-filter name="VCALENDAR"><c:comp-filter name="VEVENT"><c:time-range start="${stamp(lo)}" end="${stamp(hi)}"/></c:comp-filter></c:comp-filter></c:filter></c:calendar-query>`;
|
||
const response = await request(DAV + calendar.id + "/", {
|
||
method: "REPORT",
|
||
headers: { "Content-Type": "application/xml", Depth: "1" },
|
||
body,
|
||
signal,
|
||
});
|
||
const doc = new DOMParser().parseFromString(
|
||
await response.text(),
|
||
"application/xml",
|
||
);
|
||
if (doc.querySelector("parsererror"))
|
||
throw new Error("Invalid calendar REPORT");
|
||
const entries = Array.from(
|
||
doc.getElementsByTagNameNS("DAV:", "response"),
|
||
).map((n) => ({
|
||
href: n.getElementsByTagNameNS("DAV:", "href")[0]?.textContent,
|
||
etag: n.getElementsByTagNameNS("DAV:", "getetag")[0]?.textContent,
|
||
}));
|
||
const result = [];
|
||
if (entries.length > budget)
|
||
throw new Error(
|
||
t(
|
||
"表示上限の5000件を超えます。期間またはカレンダーを絞ってください。",
|
||
"More than 5000 events. Narrow the date range or calendar selection.",
|
||
),
|
||
);
|
||
let cursor = 0;
|
||
const selected = calendar.id;
|
||
await Promise.all(
|
||
Array.from({ length: Math.min(4, entries.length) }, async () => {
|
||
while (cursor < entries.length) {
|
||
const row = entries[cursor++];
|
||
if (!row.href?.startsWith(DAV + selected + "/") || !row.etag)
|
||
throw new Error("Invalid resource");
|
||
let item = cache.get(row.href);
|
||
if (!item || item.etag !== row.etag) {
|
||
const filename = row.href.split("/").pop();
|
||
const res = await request(
|
||
API +
|
||
"calendars/" +
|
||
selected +
|
||
"/events?resource=" +
|
||
encodeURIComponent(filename),
|
||
{ signal },
|
||
);
|
||
item = await res.json();
|
||
cache.set(row.href, item);
|
||
}
|
||
result.push({ ...item, calendar_id: calendar.id });
|
||
}
|
||
}),
|
||
);
|
||
if (cache.size > 10000) cache.clear();
|
||
return result.sort(
|
||
(a, b) => a.start.localeCompare(b.start) || a.uid.localeCompare(b.uid),
|
||
);
|
||
}
|
||
function monthGrid(date, small = false) {
|
||
const wrap = node("section"),
|
||
grid = node("div", undefined, "calendar-month");
|
||
if (small) {
|
||
const h = node("h2");
|
||
h.append(
|
||
link(
|
||
date.toLocaleDateString([], { month: "long" }),
|
||
pathFor(date, "month"),
|
||
),
|
||
);
|
||
wrap.append(h);
|
||
}
|
||
const names = ja
|
||
? ["月", "火", "水", "木", "金", "土", "日"]
|
||
: ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"];
|
||
names.forEach((n) => grid.append(node("div", n, "calendar-weekday")));
|
||
const first = new Date(date.getFullYear(), date.getMonth(), 1),
|
||
start = dayAdd(first, -((first.getDay() + 6) % 7));
|
||
for (let i = 0; i < 42; i++) {
|
||
const d = dayAdd(start, i),
|
||
cell = node("div", undefined, "calendar-day");
|
||
if (d.getMonth() !== date.getMonth()) cell.classList.add("outside");
|
||
if (dateOnly(d) === dateOnly(calendarToday()))
|
||
cell.classList.add("today");
|
||
cell.append(link(String(d.getDate()), pathFor(d, "day")));
|
||
const found = events.filter((e) => inDay(e, d));
|
||
if (small) {
|
||
if (found.length)
|
||
cell.append(node("span", String(found.length), "calendar-dot"));
|
||
} else {
|
||
if(found.length){const count=link(t(found.length+'件',found.length+' events'),pathFor(d,'day'));count.className='calendar-mobile-count';count.setAttribute('aria-label',dateOnly(d)+' · '+count.textContent);cell.append(count);}
|
||
found.slice(0, 5).forEach((e) => cell.append(eventLink(e)));
|
||
if (found.length > 5)
|
||
cell.append(link("+" + (found.length - 5), pathFor(d, "day")));
|
||
}
|
||
grid.append(cell);
|
||
}
|
||
wrap.append(grid);
|
||
return wrap;
|
||
}
|
||
function render(r) {
|
||
const content = $("calendar-content");
|
||
content.replaceChildren();
|
||
if (r.view === "year") {
|
||
const year = node("div", undefined, "calendar-year");
|
||
for (let m = 0; m < 12; m++)
|
||
year.append(monthGrid(new Date(r.date.getFullYear(), m, 1), true));
|
||
content.append(year);
|
||
} else if (r.view === "month") content.append(monthGrid(r.date));
|
||
else if (r.view === "week" || r.view === "day") content.append(timeGrid(r));
|
||
else if (r.view === "week/list") {
|
||
const week = node("div", undefined, "calendar-week"),
|
||
{ start } = period(r);
|
||
for (let i = 0; i < 7; i++) {
|
||
const d = dayAdd(start, i),
|
||
heading = node("header", undefined, "calendar-week-heading");
|
||
heading.append(
|
||
link(
|
||
d.toLocaleDateString([], {
|
||
weekday: "short",
|
||
month: "numeric",
|
||
day: "numeric",
|
||
}),
|
||
pathFor(d, "day"),
|
||
),
|
||
);
|
||
week.append(heading);
|
||
}
|
||
for (let i = 0; i < 7; i++) {
|
||
const d = dayAdd(start, i),
|
||
col = node("section");
|
||
events
|
||
.filter((e) => inDay(e, d))
|
||
.forEach((e) => col.append(eventLink(e)));
|
||
week.append(col);
|
||
}
|
||
content.append(week);
|
||
} else if (r.view === "timeline") {
|
||
const box = node("div", undefined, "calendar-timeline");
|
||
const header = node("div", undefined, "calendar-track");
|
||
for (let h = 0; h < 24; h++) {
|
||
const label = node("span", pad(h));
|
||
label.style.position = "absolute";
|
||
label.style.left = (h / 24) * 100 + "%";
|
||
header.append(label);
|
||
}
|
||
box.append(header);
|
||
const { start } = period(r),
|
||
bounds = dayBounds(dateOnly(start)),
|
||
rangeStart = bounds.start,
|
||
rangeEnd = bounds.end;
|
||
events
|
||
.filter((e) => inDay(e, start))
|
||
.forEach((e) => {
|
||
const row = node("div", undefined, "calendar-track"),
|
||
a = eventLink(e);
|
||
row.dataset.start = e.start;
|
||
row.dataset.uid = e.uid;
|
||
const lo = new Date(
|
||
Math.max(+rangeStart, +eventDate(e, "start")),
|
||
),
|
||
hi = new Date(Math.min(+rangeEnd, +eventDate(e, "end")));
|
||
a.style.left =
|
||
((lo - rangeStart) / (rangeEnd - rangeStart)) * 100 + "%";
|
||
a.style.width =
|
||
Math.max(1, ((hi - lo) / (rangeEnd - rangeStart)) * 100) + "%";
|
||
const c = calendars.find((c) => c.id === e.calendar_id) || current;
|
||
if (!e.all_day && canWrite(c)) {
|
||
const handle = node("button", "↔", "calendar-timeline-handle");
|
||
handle.type = "button";
|
||
handle.setAttribute(
|
||
"aria-label",
|
||
t(
|
||
"ドラッグで時刻変更。左右キーで15分移動",
|
||
"Drag to reschedule. Left/right keys move by 15 minutes",
|
||
),
|
||
);
|
||
handle.style.left = a.style.left;
|
||
handle.style.width = a.style.width;
|
||
handle.onkeydown = (ev) => {
|
||
if (!["ArrowLeft", "ArrowRight"].includes(ev.key)) return;
|
||
ev.preventDefault();
|
||
rescheduleEvent(
|
||
e,
|
||
c,
|
||
new Date(
|
||
+new Date(e.start) +
|
||
(ev.key === "ArrowLeft" ? -1 : 1) * 900000,
|
||
),
|
||
);
|
||
};
|
||
handle.onpointerdown = (ev) => {
|
||
if (ev.button !== 0 || movePending) return;
|
||
ev.preventDefault();
|
||
cancelDrag?.();
|
||
const x = ev.clientX,
|
||
rect = row.getBoundingClientRect(),
|
||
left = a.style.left;
|
||
let delta = 0;
|
||
handle.setPointerCapture(ev.pointerId);
|
||
const cleanup = () => {
|
||
handle.removeEventListener("pointermove", move);
|
||
handle.removeEventListener("pointerup", up);
|
||
handle.removeEventListener("pointercancel", cleanup);
|
||
handle.removeEventListener("lostpointercapture", cleanup);
|
||
document.removeEventListener("keydown", escape);
|
||
a.style.left = left;
|
||
handle.style.left = left;
|
||
row.classList.remove("moving");
|
||
if (handle.hasPointerCapture(ev.pointerId))
|
||
handle.releasePointerCapture(ev.pointerId);
|
||
if (cancelDrag === cleanup) cancelDrag = null;
|
||
};
|
||
const move = (moveEvent) => {
|
||
delta =
|
||
Math.round(
|
||
(((moveEvent.clientX - x) / rect.width) *
|
||
(rangeEnd - rangeStart)) /
|
||
900000,
|
||
) * 900000;
|
||
const next =
|
||
((lo - rangeStart + delta) / (rangeEnd - rangeStart)) *
|
||
100;
|
||
a.style.left = next + "%";
|
||
handle.style.left = next + "%";
|
||
row.classList.add("moving");
|
||
handle.title = new Date(
|
||
+new Date(e.start) + delta,
|
||
).toLocaleString();
|
||
};
|
||
const up = () => {
|
||
const next = new Date(+new Date(e.start) + delta);
|
||
cleanup();
|
||
if (delta) rescheduleEvent(e, c, next);
|
||
};
|
||
const escape = (event) => {
|
||
if (event.key === "Escape") {
|
||
event.preventDefault();
|
||
cleanup();
|
||
}
|
||
};
|
||
cancelDrag = cleanup;
|
||
handle.addEventListener("pointermove", move);
|
||
handle.addEventListener("pointerup", up);
|
||
handle.addEventListener("pointercancel", cleanup);
|
||
handle.addEventListener("lostpointercapture", cleanup);
|
||
document.addEventListener("keydown", escape);
|
||
};
|
||
row.append(handle);
|
||
}
|
||
row.append(a);
|
||
box.append(row);
|
||
});
|
||
content.append(box);
|
||
} else {
|
||
const table = node("table", undefined, "calendar-list");
|
||
const head = node("tr");
|
||
[t("日時", "When"), t("予定", "Event"), t("場所", "Location")].forEach(
|
||
(v) => head.append(node("th", v)),
|
||
);
|
||
table.append(head);
|
||
const { start, end } = period(r),
|
||
rangeStart = dayBounds(dateOnly(start)).start,
|
||
rangeEnd = dayBounds(dateOnly(end)).start;
|
||
events
|
||
.filter(
|
||
(e) =>
|
||
(e.all_day
|
||
? e.start.slice(0, 10) < dateOnly(end)
|
||
: eventDate(e, "start") < rangeEnd) &&
|
||
(e.all_day
|
||
? e.end.slice(0, 10) > dateOnly(start)
|
||
: eventDate(e, "end") > rangeStart || inDay(e, start)),
|
||
)
|
||
.forEach((e) => {
|
||
const row = node("tr"),
|
||
cell = node("td");
|
||
cell.append(eventLink(e));
|
||
row.append(
|
||
node(
|
||
"td",
|
||
e.all_day
|
||
? e.start.slice(0, 10)
|
||
: zonedText(new Date(e.start), {
|
||
dateStyle: "medium",
|
||
timeStyle: "short",
|
||
}),
|
||
),
|
||
cell,
|
||
node("td", e.location),
|
||
);
|
||
table.append(row);
|
||
});
|
||
content.append(table);
|
||
}
|
||
}
|
||
function timeGrid(r) {
|
||
const wrap = node("section", undefined, "calendar-time-view");
|
||
const controls = node(
|
||
"div",
|
||
undefined,
|
||
"calendar-toolbar calendar-time-controls",
|
||
);
|
||
const less = node("button", "−"),
|
||
more = node("button", "+");
|
||
less.type = more.type = "button";
|
||
less.setAttribute("aria-label", t("時間軸を縮小", "Zoom out"));
|
||
more.setAttribute("aria-label", t("時間軸を拡大", "Zoom in"));
|
||
less.dataset.calendarZoom = "out";
|
||
more.dataset.calendarZoom = "in";
|
||
less.disabled = timeScale === 0;
|
||
more.disabled = timeScale === timeScales.length - 1;
|
||
const pixels = timeScales[timeScale],
|
||
step = snapMinutes(pixels);
|
||
controls.append(
|
||
less,
|
||
node("span", Math.round((pixels / 60) * 100) + "%"),
|
||
more,
|
||
node(
|
||
"span",
|
||
t(
|
||
`${step}分単位 · ${calendarTimezone}`,
|
||
`${step}-minute steps · ${calendarTimezone}`,
|
||
), 'calendar-time-meta',
|
||
),
|
||
);
|
||
controls.lastElementChild.dataset.short=t(`${step}分単位`,`${step} min`);
|
||
controls.lastElementChild.title=calendarTimezone;
|
||
const touchEdit=node('button',t('編集操作','Edit gestures'),'calendar-touch-edit');touchEdit.type='button';touchEdit.setAttribute('aria-pressed','false');touchEdit.title=t('ON: 移動・伸縮・範囲選択、OFF: スクロール','On: move, resize and select. Off: scroll.');
|
||
touchEdit.onclick=()=>{cancelDrag?.();const value=wrap.classList.toggle('calendar-touch-editing');touchEdit.setAttribute('aria-pressed',String(value));};
|
||
if(enabled.some(c=>canWrite(c)))controls.append(touchEdit);
|
||
const scroll = node("div", undefined, "calendar-time-scroll"),
|
||
grid = node("div", undefined, "calendar-time-grid");
|
||
const days = r.view === "week" ? 7 : 1,
|
||
{ start } = period(r);
|
||
grid.style.setProperty("--calendar-days", days);
|
||
grid.dataset.days=String(days);
|
||
grid.style.setProperty("--hour-height", pixels + "px");
|
||
grid.style.setProperty("--snap-height", (pixels * step) / 60 + "px");
|
||
grid.dataset.snapMinutes = String(step);
|
||
grid.append(
|
||
node(
|
||
"div",
|
||
t("時刻", "Time"),
|
||
"calendar-time-heading calendar-time-corner",
|
||
),
|
||
);
|
||
for (let i = 0; i < days; i++) {
|
||
const day = dayAdd(start, i),
|
||
heading = node("div", undefined, "calendar-time-heading");
|
||
heading.append(
|
||
link(
|
||
day.toLocaleDateString(ja?'ja':'en', {
|
||
weekday: "short",
|
||
month: "numeric",
|
||
day: "numeric",
|
||
}),
|
||
pathFor(day, "day"),
|
||
),
|
||
);
|
||
grid.append(heading);
|
||
}
|
||
grid.append(node("div", t("終日", "All day"), "calendar-all-day-label"));
|
||
for (let i = 0; i < days; i++) {
|
||
const day = dayAdd(start, i),
|
||
cell = node("div", undefined, "calendar-all-day");
|
||
events
|
||
.filter((e) => e.all_day && inDay(e, day))
|
||
.forEach((e) => cell.append(eventLink(e)));
|
||
grid.append(cell);
|
||
}
|
||
const axis = node("div", undefined, "calendar-time-axis");
|
||
for (let h = 0; h < 24; h++) {
|
||
const label = node("span", pad(h) + ":00");
|
||
label.style.top = h * pixels + "px";
|
||
axis.append(label);
|
||
}
|
||
grid.append(axis);
|
||
const columns = [];
|
||
for (let i = 0; i < days; i++) {
|
||
const day = dayAdd(start, i),
|
||
column = node("div", undefined, "calendar-time-column");
|
||
column.dataset.date = dateOnly(day);
|
||
columns.push(column);
|
||
grid.append(column);
|
||
const entries = events
|
||
.filter((e) => !e.all_day && inDay(e, day))
|
||
.map((e) => {
|
||
const begin = new Date(e.start),
|
||
end = new Date(e.end),
|
||
bounds = dayBounds(dateOnly(day));
|
||
const from =
|
||
begin <= bounds.start
|
||
? 0
|
||
: zoneMinutes(begin);
|
||
const actualTo = end >= bounds.end ? 1440 : zoneMinutes(end),
|
||
displayTo = Math.max(
|
||
from + Math.max(step, ((touchScreen.matches?44:22) * 60) / pixels),
|
||
actualTo,
|
||
),
|
||
overlapTo = Math.max(from + 0.001, displayTo);
|
||
return {
|
||
event: e,
|
||
from,
|
||
actualTo,
|
||
overlapTo,
|
||
displayTo,
|
||
segment: new Date(Math.max(+begin, +bounds.start)),
|
||
startsHere: begin >= bounds.start && begin < bounds.end,
|
||
endsHere: end > bounds.start && end <= bounds.end,
|
||
};
|
||
})
|
||
.sort((a, b) => a.from - b.from || b.overlapTo - a.overlapTo);
|
||
// Interval groups use distinct lanes, including transitive overlaps.
|
||
let group = [],
|
||
end = -1;
|
||
const finish = () => {
|
||
const lanes = [];
|
||
for (const entry of group) {
|
||
let lane = lanes.findIndex((to) => to <= entry.from);
|
||
if (lane < 0) lane = lanes.length;
|
||
lanes[lane] = entry.overlapTo;
|
||
entry.lane = lane;
|
||
}
|
||
for (const entry of group) {
|
||
const e = entry.event,
|
||
card = node("div", undefined, "calendar-time-event");
|
||
card.dataset.uid = e.uid;
|
||
card.dataset.calendar = e.calendar_id;
|
||
card.dataset.start = e.start;
|
||
card.dataset.end = e.end;
|
||
card.style.top = (entry.from / 60) * pixels + "px";
|
||
card.style.height =
|
||
Math.max(
|
||
12,
|
||
((Math.min(1440, entry.displayTo) - entry.from) / 60) * pixels,
|
||
) + "px";
|
||
card.style.left = (entry.lane / lanes.length) * 100 + "%";
|
||
card.style.width = 100 / lanes.length + "%";
|
||
const a = eventLink(e);
|
||
a.draggable = false;
|
||
card.append(a);
|
||
const calendar =
|
||
calendars.find((c) => c.id === e.calendar_id) || current;
|
||
if (canWrite(calendar)) {
|
||
if (entry.startsHere) {
|
||
const top = node("button", undefined, "calendar-resize-handle calendar-resize-start");
|
||
top.type = "button";
|
||
top.setAttribute(
|
||
"aria-label",
|
||
t(
|
||
`開始時刻を変更。上下キーで${step}分`,
|
||
`Change start time. Arrow keys use ${step} minutes`,
|
||
),
|
||
);
|
||
card.prepend(top);
|
||
attachEventResize(top, card, entry, column, pixels, calendar, "start", step);
|
||
}
|
||
const handle = node("button", undefined, "calendar-move-handle");
|
||
handle.type = "button";
|
||
handle.setAttribute(
|
||
"aria-label",
|
||
t(
|
||
`中央をドラッグして移動。上下キーで${step}分`,
|
||
`Drag the middle to move. Arrow keys use ${step} minutes`,
|
||
),
|
||
);
|
||
handle.title = handle.getAttribute("aria-label");
|
||
card.append(handle);
|
||
attachEventMove(
|
||
card,
|
||
handle,
|
||
entry,
|
||
column,
|
||
columns,
|
||
pixels,
|
||
calendar,
|
||
step,
|
||
);
|
||
if (entry.endsHere) {
|
||
const bottom = node("button", undefined, "calendar-resize-handle calendar-resize-end");
|
||
bottom.type = "button";
|
||
bottom.setAttribute(
|
||
"aria-label",
|
||
t(
|
||
`終了時刻を変更。上下キーで${step}分`,
|
||
`Change end time. Arrow keys use ${step} minutes`,
|
||
),
|
||
);
|
||
card.append(bottom);
|
||
attachEventResize(bottom, card, entry, column, pixels, calendar, "end", step);
|
||
}
|
||
}
|
||
column.append(card);
|
||
}
|
||
group = [];
|
||
end = -1;
|
||
};
|
||
for (const entry of entries) {
|
||
if (group.length && entry.from >= end) finish();
|
||
group.push(entry);
|
||
end = Math.max(end, entry.overlapTo);
|
||
}
|
||
finish();
|
||
if (enabled.some((calendar) => canWrite(calendar)))
|
||
attachRangeCreation(column, pixels, step);
|
||
}
|
||
scroll.append(grid);
|
||
wrap.append(controls, scroll);
|
||
if(days===7){
|
||
const strip=node('nav',undefined,'calendar-mobile-days');strip.setAttribute('aria-label',t('週内の日を選択','Choose day of week'));
|
||
let requestedDay=null;
|
||
const buttons=[];for(let i=0;i<7;i++){const date=dayAdd(start,i),button=node('button');button.type='button';button.append(node('small',date.toLocaleDateString(ja?'ja':'en',{weekday:'short'})),node('span',String(date.getDate())));button.setAttribute('aria-label',dateOnly(date));button.onclick=()=>{requestedDay=i;scroll.scrollLeft=columns[i].offsetLeft-axis.offsetWidth;updateDay();};buttons.push(button);strip.append(button);}
|
||
let frame=0;const updateDay=()=>{frame=0;const i=requestedDay??Math.max(0,Math.min(6,Math.round(scroll.scrollLeft/columns[0].offsetWidth)));buttons.forEach((b,index)=>b.setAttribute('aria-pressed',String(index===i)));};
|
||
scroll.addEventListener('pointerdown',()=>{requestedDay=null;},{passive:true});scroll.addEventListener('wheel',()=>{requestedDay=null;},{passive:true});
|
||
scroll.addEventListener('scroll',()=>{if(!frame)frame=requestAnimationFrame(updateDay);},{passive:true});wrap.insertBefore(strip,scroll);
|
||
requestAnimationFrame(()=>{if(!scroll.isConnected)return;if(compactScreen.matches&&!scroll.dataset.positioned){const index=Math.max(0,Math.min(6,Math.round((r.date-start)/86400000)));scroll.scrollLeft=columns[index].offsetLeft-axis.offsetWidth;}updateDay();});
|
||
}
|
||
const zoom = (delta) => {
|
||
if (movePending) return;
|
||
cancelDrag?.();
|
||
const old = scroll.scrollTop / pixels;
|
||
const oldLeft=scroll.scrollLeft;
|
||
timeScale = Math.max(
|
||
0,
|
||
Math.min(timeScales.length - 1, timeScale + delta),
|
||
);
|
||
render(r);
|
||
const next = $("calendar-content").querySelector(".calendar-time-scroll");
|
||
if (next) {next.scrollTop = old * timeScales[timeScale];next.scrollLeft=oldLeft;next.dataset.positioned='true';}
|
||
};
|
||
less.onclick = () => zoom(-1);
|
||
more.onclick = () => zoom(1);
|
||
requestAnimationFrame(() => {
|
||
if (scroll.isConnected && scroll.scrollTop === 0)
|
||
scroll.scrollTop = 8 * pixels;
|
||
});
|
||
return wrap;
|
||
}
|
||
async function updateEventTimes(e, calendar, start, end) {
|
||
if (movePending || !canWrite(calendar)) return;
|
||
const oldStart = new Date(e.start),
|
||
oldEnd = new Date(e.end);
|
||
if (+oldStart === +start && +oldEnd === +end) return;
|
||
if (end < start) {
|
||
$("calendar-status").textContent = t(
|
||
"終了時刻は開始時刻以降にしてください。",
|
||
"End time must not precede start time.",
|
||
);
|
||
return;
|
||
}
|
||
const viewGeneration = generation;
|
||
movePending = true;
|
||
cancelDrag?.();
|
||
$("calendar-status").textContent = t("時刻を保存中…", "Saving time…");
|
||
try {
|
||
const updated = await api("calendars/" + calendar.id + "/events", "POST", {
|
||
uid: e.uid,
|
||
etag: e.etag,
|
||
summary: e.summary,
|
||
description: e.description,
|
||
location: e.location,
|
||
all_day: false,
|
||
start: start.toISOString(),
|
||
end: end.toISOString(),
|
||
});
|
||
if (generation === viewGeneration) {
|
||
updated.calendar_id = e.calendar_id || calendar.id;
|
||
events = events
|
||
.map((item) =>
|
||
item.uid === e.uid && item.calendar_id === updated.calendar_id
|
||
? updated
|
||
: item,
|
||
)
|
||
.sort(
|
||
(a, b) =>
|
||
a.start.localeCompare(b.start) ||
|
||
a.calendar_id.localeCompare(b.calendar_id) ||
|
||
a.uid.localeCompare(b.uid),
|
||
);
|
||
for (const [href, item] of cache)
|
||
if (item.uid === e.uid) cache.delete(href);
|
||
const oldScroll = $("calendar-content").querySelector(
|
||
".calendar-time-scroll",
|
||
),
|
||
top = oldScroll?.scrollTop || 0,
|
||
left = oldScroll?.scrollLeft || 0;
|
||
render(route());
|
||
const nextScroll = $("calendar-content").querySelector(
|
||
".calendar-time-scroll",
|
||
);
|
||
if (nextScroll) {
|
||
nextScroll.scrollTop = top;
|
||
nextScroll.scrollLeft = left;
|
||
nextScroll.dataset.positioned='true';
|
||
}
|
||
$("calendar-status").textContent = "";
|
||
}
|
||
} catch (error) {
|
||
if (generation === viewGeneration)
|
||
$("calendar-status").textContent =
|
||
t(
|
||
"時刻を変更できませんでした。再読込してください:",
|
||
"Unable to change time. Reload: ",
|
||
) + error.message;
|
||
} finally {
|
||
movePending = false;
|
||
}
|
||
}
|
||
function rescheduleEvent(e, calendar, start) {
|
||
const delta = +start - +new Date(e.start);
|
||
return updateEventTimes(
|
||
e,
|
||
calendar,
|
||
start,
|
||
new Date(+new Date(e.end) + delta),
|
||
);
|
||
}
|
||
function instantAt(day, minutes) {
|
||
if (minutes < 1440) return zonedInstant(day, minutes);
|
||
const civil = new Date(day + "T00:00:00");
|
||
return zonedInstant(dateOnly(dayAdd(civil, 1)), 0);
|
||
}
|
||
function attachEventMove(
|
||
card,
|
||
handle,
|
||
entry,
|
||
column,
|
||
columns,
|
||
pixels,
|
||
calendar,
|
||
step,
|
||
) {
|
||
handle.addEventListener("keydown", (event) => {
|
||
if (event.key !== "ArrowUp" && event.key !== "ArrowDown") return;
|
||
event.preventDefault();
|
||
if (movePending) return;
|
||
const start = new Date(entry.event.start);
|
||
start.setTime(
|
||
+start + (event.key === "ArrowUp" ? -1 : 1) * step * 60000,
|
||
);
|
||
rescheduleEvent(entry.event, calendar, start);
|
||
});
|
||
card.addEventListener("pointerdown", (event) => {
|
||
if (event.button !== 0 || movePending) return;
|
||
if(event.pointerType==='touch'&&!card.closest('.calendar-touch-editing'))return;
|
||
if (event.target.closest(".calendar-resize-handle")) return;
|
||
cancelDrag?.();
|
||
card.setPointerCapture(event.pointerId);
|
||
const origin = { x: event.clientX, y: event.clientY },
|
||
originalTop = card.style.top,
|
||
originalLeft = card.style.left,
|
||
originalWidth = card.style.width;
|
||
const grab =
|
||
((event.clientY - column.getBoundingClientRect().top) / pixels) * 60 -
|
||
entry.from;
|
||
let moved = false,
|
||
target = null,
|
||
targetTime = null;
|
||
const cleanup = () => {
|
||
card.removeEventListener("pointermove", move);
|
||
card.removeEventListener("pointerup", up);
|
||
card.removeEventListener("pointercancel", cancel);
|
||
card.removeEventListener("lostpointercapture", cancel);
|
||
document.removeEventListener("keydown", escape);
|
||
card.classList.remove("moving", "calendar-drag-invalid");
|
||
columns.forEach((candidate) =>
|
||
candidate.classList.remove("calendar-drop-target"),
|
||
);
|
||
card.style.top = originalTop;
|
||
card.style.left = originalLeft;
|
||
card.style.width = originalWidth;
|
||
card.style.transform = "";
|
||
if (card.parentNode !== column) column.append(card);
|
||
if (card.hasPointerCapture(event.pointerId))
|
||
card.releasePointerCapture(event.pointerId);
|
||
if (cancelDrag === cancel) cancelDrag = null;
|
||
};
|
||
const cancel = () => cleanup(),
|
||
escape = (e) => {
|
||
if (e.key === "Escape") {
|
||
e.preventDefault();
|
||
cancel();
|
||
}
|
||
};
|
||
const move = (e) => {
|
||
if (
|
||
!moved &&
|
||
Math.hypot(e.clientX - origin.x, e.clientY - origin.y) < 5
|
||
)
|
||
return;
|
||
moved = true;
|
||
e.preventDefault();
|
||
card.classList.add("moving");
|
||
target = columns.find((c) => {
|
||
const box = c.getBoundingClientRect();
|
||
return (
|
||
e.clientX >= box.left &&
|
||
e.clientX <= box.right &&
|
||
e.clientY >= box.top &&
|
||
e.clientY <= box.bottom
|
||
);
|
||
});
|
||
columns.forEach((candidate) =>
|
||
candidate.classList.toggle(
|
||
"calendar-drop-target",
|
||
candidate === target,
|
||
),
|
||
);
|
||
if (!target) {
|
||
targetTime = null;
|
||
card.classList.add("calendar-drag-invalid");
|
||
return;
|
||
}
|
||
const box = target.getBoundingClientRect();
|
||
const minutes = Math.max(
|
||
0,
|
||
Math.min(
|
||
1440 - step,
|
||
Math.round(
|
||
(((e.clientY - box.top) / pixels) * 60 - grab) / step,
|
||
) * step,
|
||
),
|
||
);
|
||
const candidate = instantAt(target.dataset.date, minutes);
|
||
if (!candidate) {
|
||
targetTime = null;
|
||
card.classList.add("calendar-drag-invalid");
|
||
return;
|
||
}
|
||
card.classList.remove("calendar-drag-invalid");
|
||
targetTime = new Date(
|
||
+new Date(entry.event.start) + (+candidate - +entry.segment),
|
||
);
|
||
card.style.top = (minutes / 60) * pixels + "px";
|
||
card.style.left = "0";
|
||
card.style.width = "100%";
|
||
// Keep the captured pointer element in its original DOM parent.
|
||
card.style.transform =
|
||
"translateX(" +
|
||
(box.left - column.getBoundingClientRect().left) +
|
||
"px)";
|
||
handle.title = zonedText(candidate, {
|
||
dateStyle: "medium",
|
||
timeStyle: "short",
|
||
});
|
||
};
|
||
const up = () => {
|
||
const next = moved ? targetTime : null;
|
||
if (moved)
|
||
card.addEventListener("click", (click) => click.preventDefault(), {
|
||
capture: true,
|
||
once: true,
|
||
});
|
||
card.style.transform = "";
|
||
cleanup();
|
||
if (next) rescheduleEvent(entry.event, calendar, next);
|
||
else if (moved)
|
||
$("calendar-status").textContent = t(
|
||
"移動先を確定できません。編集画面で時刻を指定してください。",
|
||
"Cannot resolve target time. Use the event editor.",
|
||
);
|
||
};
|
||
cancelDrag = cancel;
|
||
card.addEventListener("pointermove", move);
|
||
card.addEventListener("pointerup", up);
|
||
card.addEventListener("pointercancel", cancel);
|
||
card.addEventListener("lostpointercapture", cancel);
|
||
document.addEventListener("keydown", escape);
|
||
});
|
||
}
|
||
function attachEventResize(
|
||
handle,
|
||
card,
|
||
entry,
|
||
column,
|
||
pixels,
|
||
calendar,
|
||
edge,
|
||
step,
|
||
) {
|
||
const apply = (delta) => {
|
||
if (movePending) return;
|
||
const start = new Date(entry.event.start),
|
||
end = new Date(entry.event.end);
|
||
if (edge === "start") start.setTime(+start + delta * 60000);
|
||
else end.setTime(+end + delta * 60000);
|
||
if (end < start || end - start < step * 60000) return;
|
||
updateEventTimes(entry.event, calendar, start, end);
|
||
};
|
||
handle.addEventListener("keydown", (event) => {
|
||
if (event.key !== "ArrowUp" && event.key !== "ArrowDown") return;
|
||
event.preventDefault();
|
||
apply((event.key === "ArrowUp" ? -1 : 1) * step);
|
||
});
|
||
handle.addEventListener("pointerdown", (event) => {
|
||
if (event.button !== 0 || movePending) return;
|
||
if(event.pointerType==='touch'&&!card.closest('.calendar-touch-editing'))return;
|
||
event.preventDefault();
|
||
event.stopPropagation();
|
||
cancelDrag?.();
|
||
handle.setPointerCapture(event.pointerId);
|
||
const originalTop = card.style.top,
|
||
originalHeight = card.style.height,
|
||
originalStart = new Date(entry.event.start),
|
||
originalEnd = new Date(entry.event.end);
|
||
let targetTime = null,
|
||
moved = false;
|
||
const cleanup = () => {
|
||
handle.removeEventListener("pointermove", move);
|
||
handle.removeEventListener("pointerup", up);
|
||
handle.removeEventListener("pointercancel", cancel);
|
||
handle.removeEventListener("lostpointercapture", cancel);
|
||
document.removeEventListener("keydown", escape);
|
||
card.classList.remove("moving", "resizing", "resizing-start", "resizing-end");
|
||
card.style.top = originalTop;
|
||
card.style.height = originalHeight;
|
||
if (handle.hasPointerCapture(event.pointerId))
|
||
handle.releasePointerCapture(event.pointerId);
|
||
if (cancelDrag === cancel) cancelDrag = null;
|
||
};
|
||
const cancel = () => cleanup(),
|
||
escape = (e) => {
|
||
if (e.key === "Escape") {
|
||
e.preventDefault();
|
||
cancel();
|
||
}
|
||
},
|
||
move = (e) => {
|
||
const box = column.getBoundingClientRect(),
|
||
minutes = Math.max(
|
||
0,
|
||
Math.min(
|
||
1440,
|
||
Math.round(((e.clientY - box.top) / pixels) * 60 / step) *
|
||
step,
|
||
),
|
||
),
|
||
candidate = instantAt(column.dataset.date, minutes);
|
||
if (!candidate) {
|
||
targetTime = null;
|
||
return;
|
||
}
|
||
if (
|
||
(edge === "start" && originalEnd - candidate < step * 60000) ||
|
||
(edge === "end" && candidate - originalStart < step * 60000)
|
||
) {
|
||
targetTime = null;
|
||
return;
|
||
}
|
||
moved = true;
|
||
targetTime = candidate;
|
||
card.classList.add("moving", "resizing", "resizing-" + edge);
|
||
if (edge === "start") {
|
||
card.style.top = (minutes / 60) * pixels + "px";
|
||
card.style.height =
|
||
Math.max(12, ((entry.actualTo - minutes) / 60) * pixels) +
|
||
"px";
|
||
} else {
|
||
card.style.height =
|
||
Math.max(12, ((minutes - entry.from) / 60) * pixels) + "px";
|
||
}
|
||
handle.title = zonedText(candidate, {
|
||
dateStyle: "medium",
|
||
timeStyle: "short",
|
||
});
|
||
},
|
||
up = () => {
|
||
const value = moved ? targetTime : null;
|
||
cleanup();
|
||
if (!value) return;
|
||
updateEventTimes(
|
||
entry.event,
|
||
calendar,
|
||
edge === "start" ? value : originalStart,
|
||
edge === "end" ? value : originalEnd,
|
||
);
|
||
};
|
||
cancelDrag = cancel;
|
||
handle.addEventListener("pointermove", move);
|
||
handle.addEventListener("pointerup", up);
|
||
handle.addEventListener("pointercancel", cancel);
|
||
handle.addEventListener("lostpointercapture", cancel);
|
||
document.addEventListener("keydown", escape);
|
||
});
|
||
}
|
||
function attachRangeCreation(column, pixels, step) {
|
||
column.addEventListener("pointerdown", (event) => {
|
||
if (event.button !== 0 || event.target !== column || movePending) return;
|
||
if(event.pointerType==='touch'&&!column.closest('.calendar-touch-editing'))return;
|
||
cancelDrag?.();
|
||
event.preventDefault();
|
||
column.setPointerCapture(event.pointerId);
|
||
const box = column.getBoundingClientRect(),
|
||
minuteAt = (clientY) =>
|
||
Math.max(
|
||
0,
|
||
Math.min(
|
||
1440,
|
||
Math.round(((clientY - box.top) / pixels) * 60 / step) * step,
|
||
),
|
||
),
|
||
origin = Math.min(1440 - step, minuteAt(event.clientY)),
|
||
selection = node("div", undefined, "calendar-time-selection");
|
||
let current = origin,
|
||
moved = false;
|
||
selection.setAttribute("aria-hidden", "true");
|
||
column.classList.add("selecting");
|
||
column.append(selection);
|
||
const draw = () => {
|
||
const from = current < origin ? current : origin,
|
||
to = current < origin ? origin : Math.max(origin + step, current),
|
||
clock = (minutes) =>
|
||
minutes >= 1440
|
||
? "24:00"
|
||
: pad(Math.floor(minutes / 60)) + ":" + pad(minutes % 60);
|
||
selection.style.top = (from / 60) * pixels + "px";
|
||
selection.style.height =
|
||
Math.max(8, ((Math.min(1440, to) - from) / 60) * pixels) + "px";
|
||
selection.textContent = clock(from) + "–" + clock(to);
|
||
};
|
||
draw();
|
||
const cleanup = () => {
|
||
column.removeEventListener("pointermove", move);
|
||
column.removeEventListener("pointerup", up);
|
||
column.removeEventListener("pointercancel", cancel);
|
||
column.removeEventListener("lostpointercapture", cancel);
|
||
document.removeEventListener("keydown", escape);
|
||
selection.remove();
|
||
column.classList.remove("selecting");
|
||
if (column.hasPointerCapture(event.pointerId))
|
||
column.releasePointerCapture(event.pointerId);
|
||
if (cancelDrag === cancel) cancelDrag = null;
|
||
};
|
||
const cancel = () => cleanup(),
|
||
escape = (e) => {
|
||
if (e.key === "Escape") {
|
||
e.preventDefault();
|
||
cancel();
|
||
}
|
||
},
|
||
move = (e) => {
|
||
const next = minuteAt(e.clientY);
|
||
if (!moved && Math.abs(e.clientY - event.clientY) < 4) return;
|
||
moved = true;
|
||
current = next <= origin ? Math.max(0, next) : Math.min(1440, next);
|
||
draw();
|
||
},
|
||
up = () => {
|
||
if (!moved) {
|
||
cleanup();
|
||
return;
|
||
}
|
||
const from = current < origin ? current : origin,
|
||
to = current < origin ? origin : Math.max(origin + step, current),
|
||
start = instantAt(column.dataset.date, from),
|
||
end = instantAt(column.dataset.date, Math.min(1440, to));
|
||
cleanup();
|
||
if (!start || !end || end <= start) {
|
||
$("calendar-status").textContent = t(
|
||
"この範囲はタイムゾーン上で選択できません。",
|
||
"This range is unavailable in the configured timezone.",
|
||
);
|
||
return;
|
||
}
|
||
editEvent(
|
||
null,
|
||
new Date(column.dataset.date + "T00:00:00"),
|
||
{ start, end },
|
||
);
|
||
};
|
||
cancelDrag = cancel;
|
||
column.addEventListener("pointermove", move);
|
||
column.addEventListener("pointerup", up);
|
||
column.addEventListener("pointercancel", cancel);
|
||
column.addEventListener("lostpointercapture", cancel);
|
||
document.addEventListener("keydown", escape);
|
||
});
|
||
}
|
||
function field(label, name, type, value = "", required = false) {
|
||
const l = node("label", label),
|
||
i = node(type === "textarea" ? "textarea" : "input");
|
||
i.name = name;
|
||
if (type !== "textarea") i.type = type;
|
||
if (type === "checkbox") i.checked = !!value;
|
||
else i.value = value;
|
||
i.required = required;
|
||
l.append(i);
|
||
$("calendar-fields").append(l);
|
||
return i;
|
||
}
|
||
function dialog(title, save, build, submit) {
|
||
$("calendar-dialog-title").textContent = title;
|
||
$("calendar-fields").replaceChildren();
|
||
$("calendar-form-error").textContent = "";
|
||
$("calendar-submit").textContent = save;
|
||
$("calendar-cancel").textContent = t("閉じる", "Close");
|
||
build();
|
||
$("calendar-form").onsubmit = async (e) => {
|
||
e.preventDefault();
|
||
$("calendar-submit").disabled = true;
|
||
try {
|
||
await submit(new FormData(e.target));
|
||
$("calendar-dialog").close();
|
||
} catch (err) {
|
||
$("calendar-form-error").textContent = err.message;
|
||
} finally {
|
||
$("calendar-submit").disabled = false;
|
||
}
|
||
};
|
||
$("calendar-dialog").showModal();
|
||
}
|
||
function editEvent(item, date, selectedRange = null) {
|
||
if (!(item ? canWrite() : enabled.some((c) => canWrite(c))))
|
||
throw new Error(t("編集権限がありません", "No write permission"));
|
||
const originRoute = route(),
|
||
creationReturnView = calendarViews.has(originRoute.view)
|
||
? originRoute.view
|
||
: preferredView(),
|
||
creationReturnHref = calendarViews.has(originRoute.view)
|
||
? location.pathname + location.search
|
||
: pathFor(date, creationReturnView),
|
||
initialStart =
|
||
selectedRange?.start || zonedInstant(dateOnly(date), 9 * 60, false),
|
||
initialEnd =
|
||
selectedRange?.end || zonedInstant(dateOnly(date), 10 * 60, false),
|
||
initial = item || {
|
||
uid: "",
|
||
summary: "",
|
||
description: "",
|
||
location: "",
|
||
all_day: false,
|
||
start: initialStart.toISOString(),
|
||
end: initialEnd.toISOString(),
|
||
};
|
||
const local = (s) => {
|
||
const p = zoneParts(new Date(s));
|
||
return `${p.year}-${pad(p.month)}-${pad(p.day)}T${pad(p.hour)}:${pad(p.minute)}`;
|
||
};
|
||
dialog(
|
||
t("予定を編集", "Edit event"),
|
||
t("保存", "Save"),
|
||
() => {
|
||
field(t("タイトル", "Title"), "summary", "text", initial.summary, true);
|
||
if (!item) {
|
||
const label = node(
|
||
"label",
|
||
t("作成先カレンダー", "Destination calendar"),
|
||
),
|
||
select = node("select");
|
||
select.name = "destination";
|
||
for (const c of enabled.filter((c) => canWrite(c))) {
|
||
const o = node("option", c.name + " (" + c.pretty_name + ")");
|
||
o.value = c.id;
|
||
select.append(o);
|
||
}
|
||
label.append(select);
|
||
$("calendar-fields").append(label);
|
||
}
|
||
const all = field(
|
||
t("終日(終了日を含む)", "All day (including end date)"),
|
||
"all_day",
|
||
"checkbox",
|
||
initial.all_day,
|
||
);
|
||
const start = field(
|
||
t("開始", "Start"),
|
||
"start",
|
||
initial.all_day ? "date" : "datetime-local",
|
||
initial.all_day ? initial.start.slice(0, 10) : local(initial.start),
|
||
true,
|
||
),
|
||
end = field(
|
||
t("終了", "End"),
|
||
"end",
|
||
initial.all_day ? "date" : "datetime-local",
|
||
initial.all_day ? new Date(Date.parse(initial.end) - 86400000).toISOString().slice(0, 10) : local(initial.end),
|
||
true,
|
||
);
|
||
all.onchange = () => {
|
||
for (const input of [start, end]) {
|
||
const v = input.value.slice(0, 10);
|
||
input.type = all.checked ? "date" : "datetime-local";
|
||
input.value = all.checked ? v : v + "T09:00";
|
||
}
|
||
};
|
||
field(t("場所", "Location"), "location", "text", initial.location);
|
||
field(
|
||
t("説明", "Description"),
|
||
"description",
|
||
"textarea",
|
||
initial.description,
|
||
);
|
||
$("calendar-fields").append(
|
||
node(
|
||
"p",
|
||
t(
|
||
"設定済みのタイムゾーン:",
|
||
"Configured timezone: ",
|
||
) + calendarTimezone,
|
||
),
|
||
);
|
||
},
|
||
async (form) => {
|
||
const all = form.has("all_day");
|
||
if (all && form.get("end") < form.get("start"))
|
||
throw new Error(t("終了日は開始日以降を指定してください", "End date must be on or after start date"));
|
||
const destination = item
|
||
? current
|
||
: enabled.find((c) => c.id === form.get("destination"));
|
||
if (!destination || !canWrite(destination))
|
||
throw new Error(t("編集権限がありません", "No write permission"));
|
||
const parseWall = (value) => {
|
||
const [day, clock] = value.split("T"),
|
||
[hour, minute] = clock.split(":").map(Number),
|
||
instant = zonedInstant(day, hour * 60 + minute);
|
||
if (!instant)
|
||
throw new Error(
|
||
t(
|
||
"タイムゾーン上で存在しない、または重複する時刻です。別の時刻を指定してください。",
|
||
"This wall time is nonexistent or ambiguous in the configured timezone.",
|
||
),
|
||
);
|
||
return instant;
|
||
};
|
||
const startValue = all
|
||
? new Date(form.get("start") + "T00:00:00Z")
|
||
: parseWall(form.get("start")),
|
||
endValue = all
|
||
? new Date(Date.parse(form.get("end") + "T00:00:00Z") + 86400000)
|
||
: parseWall(form.get("end"));
|
||
if (endValue < startValue)
|
||
throw new Error(
|
||
t(
|
||
"終了時刻は開始時刻以降を指定してください",
|
||
"End time must be on or after start time",
|
||
),
|
||
);
|
||
const body = {
|
||
uid: initial.uid,
|
||
etag: initial.etag || "",
|
||
summary: form.get("summary"),
|
||
description: form.get("description"),
|
||
location: form.get("location"),
|
||
all_day: all,
|
||
start: startValue.toISOString(),
|
||
end: endValue.toISOString(),
|
||
};
|
||
const e = await api(
|
||
"calendars/" + destination.id + "/events",
|
||
"POST",
|
||
body,
|
||
);
|
||
if (!item) {
|
||
cache.clear();
|
||
history.replaceState(null, "", creationReturnHref);
|
||
await load();
|
||
return;
|
||
}
|
||
navigate(
|
||
"/v/plan/event/" +
|
||
encodeURIComponent(e.uid) +
|
||
"?calendar=" +
|
||
encodeURIComponent(destination.pretty_name),
|
||
);
|
||
},
|
||
);
|
||
}
|
||
async function details(r) {
|
||
const g = generation;
|
||
const e = await api(
|
||
"calendars/" + current.id + "/events?uid=" + encodeURIComponent(r.uid),
|
||
);
|
||
if (g !== generation) return;
|
||
const content = $("calendar-content"),
|
||
article = node("article", undefined, "calendar-detail");
|
||
article.append(node("h2", e.summary || t("無題", "Untitled")));
|
||
const dl = node("dl");
|
||
for (const [key, value] of [
|
||
[
|
||
t("開始", "Start"),
|
||
e.all_day
|
||
? e.start.slice(0, 10)
|
||
: zonedText(new Date(e.start), {
|
||
dateStyle: "medium",
|
||
timeStyle: "short",
|
||
}),
|
||
],
|
||
[
|
||
e.all_day ? t("終了日(含む)", "End date (inclusive)") : t("終了", "End"),
|
||
e.all_day
|
||
? new Date(Date.parse(e.end) - 86400000).toISOString().slice(0, 10)
|
||
: zonedText(new Date(e.end), {
|
||
dateStyle: "medium",
|
||
timeStyle: "short",
|
||
}),
|
||
],
|
||
[t("場所", "Location"), e.location],
|
||
])
|
||
dl.append(node("dt", key), node("dd", value));
|
||
article.append(dl, node("p", e.description));
|
||
if (canWrite()) {
|
||
const nav = node("nav", undefined, "calendar-toolbar");
|
||
nav.append(
|
||
link(
|
||
t("編集", "Edit"),
|
||
"/v/event/" +
|
||
encodeURIComponent(e.uid) +
|
||
"/edit?calendar=" +
|
||
encodeURIComponent(current.pretty_name),
|
||
),
|
||
);
|
||
const del = node("button", t("削除", "Delete"));
|
||
del.onclick = async () => {
|
||
if (!confirm(t("この予定を削除しますか?", "Delete this event?")))
|
||
return;
|
||
try {
|
||
await request(
|
||
DAV +
|
||
current.id +
|
||
"/" +
|
||
btoa(String.fromCharCode(...new TextEncoder().encode(e.uid)))
|
||
.replace(/\+/g, "-")
|
||
.replace(/\//g, "_")
|
||
.replace(/=+$/, "") +
|
||
".ics",
|
||
{ method: "DELETE", headers: { "If-Match": e.etag } },
|
||
);
|
||
const p = zoneParts(new Date(e.start));
|
||
navigate(pathFor(new Date(p.year, p.month - 1, p.day), "month"));
|
||
} catch (err) {
|
||
$("calendar-status").textContent = err.message;
|
||
}
|
||
};
|
||
nav.append(del);
|
||
article.append(nav);
|
||
}
|
||
content.replaceChildren(article);
|
||
if (r.view === "edit") editEvent(e, new Date(e.start));
|
||
}
|
||
async function load() {
|
||
cancelDrag?.();
|
||
const g = ++generation;
|
||
abort?.abort();
|
||
abort = new AbortController();
|
||
$("calendar-status").textContent = t("読み込み中…", "Loading…");
|
||
try {
|
||
const data = await api("calendars");
|
||
if (g !== generation) return;
|
||
calendars = data.calendars;
|
||
if (actor !== data.actor) cache.clear();
|
||
actor = data.actor;
|
||
active = data.active;
|
||
publicAllowed = data.public_allowed;
|
||
let selected = new URLSearchParams(location.search).get("calendar");
|
||
const r = route();
|
||
rememberView(r.view);
|
||
if (!selected && (r.view === "detail" || r.view === "edit")) {
|
||
const resolved = await api("event?uid=" + encodeURIComponent(r.uid));
|
||
if (g !== generation) return;
|
||
selected = calendars.find(
|
||
(c) => c.id === resolved.calendar,
|
||
)?.pretty_name;
|
||
const u = new URL(location.href);
|
||
u.searchParams.set("calendar", selected);
|
||
history.replaceState(null, "", u.pathname + u.search);
|
||
}
|
||
if (selected !== null) {
|
||
const names = selected.split(",");
|
||
if (names.length > 32 || names.some((n) => !n))
|
||
throw new Error(
|
||
t("カレンダー指定が不正です", "Invalid calendar selection"),
|
||
);
|
||
enabled = names.map((n) =>
|
||
calendars.find((c) => c.pretty_name === n || c.id === n),
|
||
);
|
||
if (enabled.some((c) => !c))
|
||
throw new Error(
|
||
t(
|
||
"カレンダーが見つからないか閲覧権限がありません",
|
||
"Calendar unavailable",
|
||
),
|
||
);
|
||
enabled = [...new Map(enabled.map((c) => [c.id, c])).values()];
|
||
history.replaceState(
|
||
null,
|
||
"",
|
||
location.pathname +
|
||
"?calendar=" +
|
||
enabled.map((c) => encodeURIComponent(c.pretty_name)).join(","),
|
||
);
|
||
} else {
|
||
enabled = (data.defaults || [])
|
||
.map((id) => calendars.find((c) => c.id === id))
|
||
.filter(Boolean);
|
||
if (!enabled.length && calendars.length) enabled = [calendars[0]];
|
||
}
|
||
current = enabled[0] || null;
|
||
if ((r.view === "detail" || r.view === "edit") && enabled.length !== 1)
|
||
throw new Error(
|
||
t(
|
||
"詳細表示ではカレンダーを1つ指定してください",
|
||
"Select one calendar for event details",
|
||
),
|
||
);
|
||
const select = $("calendar-select");
|
||
select.replaceChildren();
|
||
calendars.forEach((c) => {
|
||
const o = node("option", c.name);
|
||
o.value = c.id;
|
||
select.append(o);
|
||
});
|
||
if (current) select.value = current.id;
|
||
$("calendar-create").hidden = !active;
|
||
toolbar(r);
|
||
if (!current) {
|
||
cache.clear();
|
||
$("calendar-content").replaceChildren(
|
||
node(
|
||
"p",
|
||
selected
|
||
? t(
|
||
"カレンダーが見つからないか、閲覧権限がありません。",
|
||
"Calendar unavailable.",
|
||
)
|
||
: t(
|
||
"+ からカレンダーを作成してください。",
|
||
"Create a calendar using +.",
|
||
),
|
||
),
|
||
);
|
||
$("calendar-status").textContent = "";
|
||
return;
|
||
}
|
||
if (r.view === "detail" || r.view === "edit") await details(r);
|
||
else if (r.view === "new") {
|
||
render({ ...r, view: "day" });
|
||
editEvent(null, r.date);
|
||
} else {
|
||
const range = period(r);
|
||
const result = [];
|
||
// Sequential calendars; at most four event bodies in flight globally.
|
||
for (const c of enabled)
|
||
result.push(
|
||
...(await loadEvents(
|
||
range.start,
|
||
range.end,
|
||
abort.signal,
|
||
c,
|
||
5000 - result.length,
|
||
)),
|
||
);
|
||
result.sort(
|
||
(a, b) =>
|
||
a.start.localeCompare(b.start) ||
|
||
a.calendar_id.localeCompare(b.calendar_id) ||
|
||
a.uid.localeCompare(b.uid),
|
||
);
|
||
if (g !== generation) return;
|
||
events = result;
|
||
render(r);
|
||
}
|
||
$("calendar-status").textContent = "";
|
||
} catch (err) {
|
||
if (err.name !== "AbortError" && g === generation) {
|
||
cache.clear();
|
||
$("calendar-content").replaceChildren();
|
||
$("calendar-status").textContent = err.message;
|
||
}
|
||
}
|
||
}
|
||
function navigate(href) {
|
||
cancelDrag?.();
|
||
$("calendar-dialog").close();
|
||
history.pushState(null, "", href);
|
||
load();
|
||
}
|
||
app.addEventListener("click", (e) => {
|
||
const a = e.target.closest("a");
|
||
if (
|
||
!a ||
|
||
e.ctrlKey ||
|
||
e.metaKey ||
|
||
e.shiftKey ||
|
||
e.altKey ||
|
||
e.button !== 0
|
||
)
|
||
return;
|
||
const u = new URL(a.href);
|
||
if (
|
||
u.origin === location.origin &&
|
||
(u.pathname.startsWith("/v/plan") || u.pathname.startsWith("/v/event/"))
|
||
) {
|
||
e.preventDefault();
|
||
navigate(u.pathname + u.search);
|
||
}
|
||
});
|
||
window.addEventListener("popstate", load);
|
||
$("calendar-refresh").onclick = load;
|
||
const sourceButton = node("button", t("外部同期", "External sync"));
|
||
sourceButton.type = "button";
|
||
sourceButton.id = "calendar-source-settings";
|
||
$("calendar-settings").after(sourceButton);
|
||
sourceButton.onclick = () =>
|
||
dialog(
|
||
t(
|
||
"外部カレンダーの読み取り同期",
|
||
"External calendar read-only synchronization",
|
||
),
|
||
t("保存", "Save"),
|
||
() => {
|
||
const source = current.source || {};
|
||
const label = node("label", t("取得方式", "Protocol")),
|
||
kind = node("select");
|
||
kind.name = "source_kind";
|
||
for (const [value, text] of [
|
||
["ics", "ICS"],
|
||
["caldav", "CalDAV (REPORT / multiget)"],
|
||
]) {
|
||
const option = node("option", text);
|
||
option.value = value;
|
||
kind.append(option);
|
||
}
|
||
kind.value = source.kind || "ics";
|
||
label.append(kind);
|
||
$("calendar-fields").append(label);
|
||
field(
|
||
t(
|
||
"HTTPS URL(CalDAVはカレンダーcollection)",
|
||
"HTTPS URL (calendar collection for CalDAV)",
|
||
),
|
||
"source_url",
|
||
"url",
|
||
source.url || "",
|
||
true,
|
||
);
|
||
field(
|
||
t(
|
||
"外部サービスのユーザー名(任意)",
|
||
"External service username (optional)",
|
||
),
|
||
"source_username",
|
||
"text",
|
||
).autocomplete = "off";
|
||
field(
|
||
t(
|
||
"外部サービスのパスワード(空欄で保持)",
|
||
"External service password (blank to retain)",
|
||
),
|
||
"source_password",
|
||
"password",
|
||
).autocomplete = "new-password";
|
||
if (source.has_credential)
|
||
field(
|
||
t("保存した認証情報を削除", "Clear saved credentials"),
|
||
"clear_credential",
|
||
"checkbox",
|
||
false,
|
||
);
|
||
$("calendar-fields").append(
|
||
node(
|
||
"p",
|
||
t(
|
||
"CalDAVは過去90日〜未来275日を読み取り同期します。外部への書き込みは行いません。",
|
||
"CalDAV imports the previous 90 and next 275 days. It never writes to the external server.",
|
||
),
|
||
),
|
||
);
|
||
const interval = field(
|
||
t("読み取り間隔(分)", "Polling interval (minutes)"),
|
||
"interval",
|
||
"number",
|
||
source.interval_seconds ? source.interval_seconds / 60 : 60,
|
||
true,
|
||
);
|
||
interval.min = "1";
|
||
interval.max = "10080";
|
||
interval.step = "1";
|
||
field(
|
||
t("同期を有効化", "Enable synchronization"),
|
||
"source_enabled",
|
||
"checkbox",
|
||
source.enabled ?? true,
|
||
);
|
||
$("calendar-fields").append(
|
||
node(
|
||
"p",
|
||
t(
|
||
"新しい空のカレンダーに設定してください。外部予定は読み取り専用です。HTTPSの公開アドレスのみ取得します。Outlookのタイムゾーン、RRULE、例外日・追加日・変更/取消回を同期期間内へ展開します。未対応形式はエラーになり、前回の予定を保持します。",
|
||
"Use a new empty calendar. Imported events are read-only. Only public HTTPS addresses are fetched. Outlook timezones, RRULE, excluded/added dates, and moved or cancelled instances are expanded within the synchronization window. Unsupported forms fail without replacing previous events.",
|
||
),
|
||
),
|
||
);
|
||
if (source.checked_at_ms)
|
||
$("calendar-fields").append(
|
||
node(
|
||
"p",
|
||
t("最終確認:", "Last checked: ") +
|
||
new Date(source.checked_at_ms).toLocaleString(),
|
||
),
|
||
);
|
||
if (source.success_at_ms)
|
||
$("calendar-fields").append(
|
||
node(
|
||
"p",
|
||
t("最終成功:", "Last successful check: ") +
|
||
new Date(source.success_at_ms).toLocaleString(),
|
||
),
|
||
);
|
||
if (source.error) $("calendar-fields").append(node("p", source.error));
|
||
if (source.enabled) {
|
||
const sync = node("button", t("今すぐ同期", "Synchronize now"));
|
||
sync.type = "button";
|
||
sync.onclick = async () => {
|
||
sync.disabled = true;
|
||
try {
|
||
await api("calendars/" + current.id + "/source", "POST", {});
|
||
$("calendar-form-error").textContent = t(
|
||
"同期をキューに追加しました。閉じて更新すると結果を確認できます。",
|
||
"Synchronization queued. Close and refresh to check the result.",
|
||
);
|
||
} catch (e) {
|
||
$("calendar-form-error").textContent = e.message;
|
||
} finally {
|
||
sync.disabled = false;
|
||
}
|
||
};
|
||
$("calendar-fields").append(sync);
|
||
}
|
||
},
|
||
async (form) => {
|
||
await api("calendars/" + current.id + "/source", "PUT", {
|
||
url: form.get("source_url"),
|
||
kind: form.get("source_kind"),
|
||
username: form.get("source_username"),
|
||
password: form.get("source_password"),
|
||
clear_credential: form.has("clear_credential"),
|
||
interval_seconds: Number(form.get("interval")) * 60,
|
||
enabled: form.has("source_enabled"),
|
||
version: current.version,
|
||
});
|
||
cache.clear();
|
||
load();
|
||
},
|
||
);
|
||
const displayButton = node("button", t("表示設定", "Display settings"));
|
||
displayButton.type = "button";
|
||
displayButton.id = "calendar-display-settings";
|
||
$("calendar-select").before(displayButton);
|
||
displayButton.onclick = () =>
|
||
dialog(
|
||
t("表示するカレンダー", "Visible calendars"),
|
||
t("適用", "Apply"),
|
||
() => {
|
||
for (const c of calendars)
|
||
field(
|
||
c.name + " (" + c.pretty_name + ")",
|
||
"visible:" + c.id,
|
||
"checkbox",
|
||
enabled.some((e) => e.id === c.id),
|
||
);
|
||
if (actor) {
|
||
const settingsLink=node('a',t('既定のカレンダーは個人設定で変更','Change default calendars in personal settings'));
|
||
settingsLink.href='/-/sys/config?panel=organizer#organizer-calendar-defaults';
|
||
$("calendar-fields").append(settingsLink);
|
||
}
|
||
$("calendar-fields").append(
|
||
node(
|
||
"p",
|
||
t(
|
||
"複数選択できます。作成先は新規予定で選択します。",
|
||
"Select multiple calendars. Choose a destination when creating an event.",
|
||
),
|
||
),
|
||
);
|
||
},
|
||
async (form) => {
|
||
const selected = calendars.filter((c) => form.has("visible:" + c.id));
|
||
if (!selected.length || selected.length > 32)
|
||
throw new Error(
|
||
t("1〜32個のカレンダーを選択してください", "Select 1–32 calendars"),
|
||
);
|
||
const base = ["detail", "edit", "new"].includes(route().view)
|
||
? "/v/plan"
|
||
: location.pathname;
|
||
navigate(
|
||
base +
|
||
"?calendar=" +
|
||
selected.map((c) => encodeURIComponent(c.pretty_name)).join(","),
|
||
);
|
||
},
|
||
);
|
||
$("calendar-select").onchange = () => {
|
||
cache.clear();
|
||
const u = new URL(location.href);
|
||
u.searchParams.set(
|
||
"calendar",
|
||
calendars.find((c) => c.id === $("calendar-select").value).pretty_name,
|
||
);
|
||
navigate(u.pathname + u.search);
|
||
};
|
||
document
|
||
.querySelectorAll("[data-close]")
|
||
.forEach((b) => (b.onclick = () => $("calendar-dialog").close()));
|
||
$("calendar-create").onclick = () =>
|
||
dialog(
|
||
t("カレンダーを作成", "Create calendar"),
|
||
t("作成", "Create"),
|
||
() => {
|
||
field(t("名前", "Name"), "name", "text", "", true);
|
||
field("pretty_name", "pretty_name", "text", "", true);
|
||
},
|
||
async (form) => {
|
||
const c = await api("calendars", "POST", {
|
||
name: form.get("name"),
|
||
pretty_name: form.get("pretty_name"),
|
||
});
|
||
navigate("/v/plan?calendar=" + encodeURIComponent(c.pretty_name));
|
||
},
|
||
);
|
||
$("calendar-settings").onclick = () =>
|
||
dialog(
|
||
t("カレンダー設定", "Calendar settings"),
|
||
t("保存", "Save"),
|
||
() => {
|
||
field(t("名前", "Name"), "name", "text", current.name, true);
|
||
field("pretty_name", "pretty_name", "text", current.pretty_name, true);
|
||
const publication = field(
|
||
t("匿名での閲覧を許可", "Allow public reading"),
|
||
"public",
|
||
"checkbox",
|
||
current.public && publicAllowed,
|
||
);
|
||
publication.disabled = !publicAllowed;
|
||
if (!publicAllowed)
|
||
$("calendar-fields").append(
|
||
node(
|
||
"p",
|
||
t(
|
||
"ドメイン管理者による公開許可が必要です。",
|
||
"Publication requires the Domain administrator to allow public access.",
|
||
),
|
||
),
|
||
);
|
||
field(
|
||
t(
|
||
"コラボレータ(ユーザー名 または UUID:read / UUID:write、1行1件)",
|
||
"Collaborators (username or UUID:read / UUID:write, one per line)",
|
||
),
|
||
"members",
|
||
"textarea",
|
||
Object.entries(current.members || {})
|
||
.map(([id, role]) => id + ":" + role)
|
||
.join("\n"),
|
||
);
|
||
$("calendar-fields").append(
|
||
node(
|
||
"p",
|
||
t(
|
||
"公開すると説明・場所を含む全予定が閲覧可能になります。",
|
||
"Publishing exposes all events, including descriptions and locations.",
|
||
),
|
||
),
|
||
);
|
||
const remove = node(
|
||
"button",
|
||
t("カレンダーを削除", "Delete calendar"),
|
||
"calendar-delete-button",
|
||
);
|
||
remove.type = "button";
|
||
remove.onclick = async () => {
|
||
const target = current;
|
||
if (
|
||
!target ||
|
||
!confirm(
|
||
t(
|
||
`「${target.name}」とすべての予定を完全に削除しますか?`,
|
||
`Permanently delete “${target.name}” and all its events?`,
|
||
),
|
||
)
|
||
)
|
||
return;
|
||
remove.disabled = true;
|
||
$("calendar-form-error").textContent = "";
|
||
try {
|
||
await api(
|
||
"calendars/" + target.id + "/settings",
|
||
"DELETE",
|
||
{ version: target.version },
|
||
);
|
||
cache.clear();
|
||
$("calendar-dialog").close();
|
||
navigate("/v/plan");
|
||
} catch (error) {
|
||
$("calendar-form-error").textContent = error.message;
|
||
remove.disabled = false;
|
||
}
|
||
};
|
||
$("calendar-fields").append(remove);
|
||
},
|
||
async (form) => {
|
||
const members = {};
|
||
for (const line of String(form.get("members"))
|
||
.split("\n")
|
||
.map((l) => l.trim())
|
||
.filter(Boolean)) {
|
||
const i = line.lastIndexOf(":");
|
||
if (i < 1) throw new Error("username:read / username:write");
|
||
members[line.slice(0, i)] = line.slice(i + 1);
|
||
}
|
||
await api("calendars/" + current.id + "/settings", "PUT", {
|
||
name: form.get("name"),
|
||
pretty_name: form.get("pretty_name"),
|
||
public: form.has("public"),
|
||
members,
|
||
version: current.version,
|
||
});
|
||
cache.clear();
|
||
if (new URLSearchParams(location.search).has("calendar")) {
|
||
navigate(
|
||
location.pathname +
|
||
"?calendar=" +
|
||
enabled
|
||
.map((c) =>
|
||
encodeURIComponent(
|
||
c.id === current.id
|
||
? form.get("pretty_name")
|
||
: c.pretty_name,
|
||
),
|
||
)
|
||
.join(","),
|
||
);
|
||
} else load();
|
||
},
|
||
);
|
||
const mobileActions=node('details',undefined,'calendar-mobile-actions'),mobileSummary=node('summary','⋯'),mobilePanel=node('div');
|
||
mobileSummary.setAttribute('aria-label',t('カレンダーの設定・管理','Calendar settings and management'));mobileActions.append(mobileSummary,mobilePanel);
|
||
for(const [id,label] of [['calendar-display-settings',t('表示カレンダー','Visible calendars')],['calendar-settings',t('カレンダー設定','Calendar settings')],['calendar-create',t('カレンダーを追加','Add calendar')],['calendar-source-settings',t('外部同期設定','External sync settings')]]){const b=node('button',label);b.type='button';b.dataset.source=id;b.onclick=()=>{mobileActions.open=false;$(id).click();};mobilePanel.append(b);}
|
||
mobileActions.addEventListener('toggle',()=>{if(mobileActions.open)mobilePanel.querySelectorAll('button').forEach(b=>{b.hidden=$(b.dataset.source).hidden;b.disabled=$(b.dataset.source).disabled;});});
|
||
$('calendar-new').after(mobileActions);
|
||
document.addEventListener('click',e=>{if(!mobileActions.contains(e.target))mobileActions.open=false;});
|
||
document.addEventListener('keydown',e=>{if(e.key==='Escape'&&mobileActions.open){mobileActions.open=false;mobileSummary.focus();}});
|
||
load();
|
||
})();
|