Skip to content

lightweight, client-only calendar web application. All data persists in the URL hash for instant sharing, No backend required. Optional AES-GCM password protection keeps shared links locked without a server

JavaScript

Refactor world planner logic and enhance notification features

Supun Lakmal780926acc1e6
diff --git a/index.html b/index.html
index 881e78e..4518fb4 100644
--- a/index.html
+++ b/index.html
@@ -180,6 +180,7 @@
<button id="weekstart-toggle" type="button" data-i18n="settings.weekStartsSunday">Week starts
Sunday</button>
<button id="theme-toggle" type="button" data-i18n="settings.themeLight">Theme: Light</button>
+ <button id="notify-toggle" type="button" data-i18n="settings.notificationsOff">Notifications: Off</button>
<div class="dropdown-container lang-selector">
<button id="language-btn" class="dropdown-trigger" type="button" aria-haspopup="listbox"
aria-expanded="false">
@@ -608,6 +609,9 @@
<button id="mobile-theme-toggle" type="button" class="mobile-drawer-item">
<i class="fa-solid fa-circle-half-stroke"></i> <span>Theme: Light</span>
</button>
+ <button id="mobile-notify-toggle" type="button" class="mobile-drawer-item">
+ <i class="fa-solid fa-bell"></i> <span data-i18n="settings.notificationsOff">Notifications: Off</span>
+ </button>
<button id="mobile-readonly-btn" type="button" class="mobile-drawer-item" aria-pressed="false">
<i class="fa-solid fa-pen"></i> <span data-i18n="btn.readOnly">Read only</span>
</button>
diff --git a/json.html b/json.html
index 73e361f..add1380 100644
--- a/json.html
+++ b/json.html
@@ -161,9 +161,11 @@
}
const json = JSON.stringify(parsed);
- const compressed = window.LZString.compressToEncodedURIComponent(json); const target = `${window.location.origin}/#${compressed}`;
+ const compressed = window.LZString.compressToEncodedURIComponent(json);
+ const targetUrl = new URL("./", window.location.href);
+ targetUrl.hash = compressed;
status.textContent = "Redirecting to calendar...";
- window.location.replace(target);
+ window.location.replace(targetUrl.toString());
})();
</script>
</body>
diff --git a/locales/en.js b/locales/en.js
index 2cbfa1d..336cd5c 100644
--- a/locales/en.js
+++ b/locales/en.js
@@ -117,6 +117,10 @@ export default {
"settings.weekStartsMonday": "Week starts Monday",
"settings.themeLight": "Theme: Light",
"settings.themeDark": "Theme: Dark",
+ "settings.notificationsOff": "Notifications: Off",
+ "settings.notificationsOn": "Notifications: On",
+ "settings.notificationsBlocked": "Notifications: Blocked",
+ "settings.notificationsUnsupported": "Notifications unsupported",
"settings.language": "Language",
// Language names
@@ -138,6 +142,9 @@ export default {
"toast.readOnlyEnabled": "Read-only mode enabled",
"toast.editModeEnabled": "Edit mode enabled",
"toast.readOnlyActive": "Read-only mode is on. Switch back to edit mode to make changes.",
+ "toast.notificationsEnabled": "30-minute reminders enabled",
+ "toast.notificationsDisabled": "30-minute reminders disabled",
+ "toast.notificationsBlocked": "Browser notifications are blocked for this site",
"toast.incorrectPassword": "Incorrect password",
"toast.unableToCopyLink": "Unable to copy link",
"toast.unableToCopyJson": "Unable to copy JSON",
@@ -184,6 +191,10 @@ export default {
"countdown.startsAt": "Starts at {{time}}",
"countdown.starts": "Starts {{date}} at {{time}}",
+ // Browser notifications
+ "notify.upcomingTitle": "{{title}} starts soon",
+ "notify.upcomingBody": "Starts at {{time}} (in 30 minutes)",
+
// Agenda view
"agenda.title": "Agenda",
"agenda.rangeLabel": "Agenda · {{range}}",
diff --git a/locales/it.js b/locales/it.js
index 24ef9dc..495e923 100644
--- a/locales/it.js
+++ b/locales/it.js
@@ -117,6 +117,10 @@ export default {
'settings.weekStartsMonday': 'La settimana inizia lunedì',
'settings.themeLight': 'Tema: Chiaro',
'settings.themeDark': 'Tema: Scuro',
+ 'settings.notificationsOff': 'Notifiche: Disattivate',
+ 'settings.notificationsOn': 'Notifiche: Attive',
+ 'settings.notificationsBlocked': 'Notifiche: Bloccate',
+ 'settings.notificationsUnsupported': 'Notifiche non supportate',
'settings.language': 'Lingua',
// Language names
@@ -138,6 +142,9 @@ export default {
'toast.readOnlyEnabled': 'Modalita sola lettura attivata',
'toast.editModeEnabled': 'Modalita modifica attivata',
'toast.readOnlyActive': 'La modalita sola lettura e attiva. Torna alla modalita modifica per fare cambiamenti.',
+ 'toast.notificationsEnabled': 'Promemoria a 30 minuti attivati',
+ 'toast.notificationsDisabled': 'Promemoria a 30 minuti disattivati',
+ 'toast.notificationsBlocked': 'Le notifiche del browser sono bloccate per questo sito',
'toast.incorrectPassword': 'Password errata',
'toast.unableToCopyLink': 'Impossibile copiare il link',
'toast.unableToCopyJson': 'Impossibile copiare il JSON',
@@ -183,6 +190,10 @@ export default {
'countdown.upNext': 'Prossimo',
'countdown.startsAt': 'Inizia alle {{time}}',
'countdown.starts': 'Inizia il {{date}} alle {{time}}',
+
+ // Browser notifications
+ 'notify.upcomingTitle': '{{title}} sta per iniziare',
+ 'notify.upcomingBody': 'Inizia alle {{time}} (tra 30 minuti)',
// Agenda view
'agenda.title': 'Agenda',
diff --git a/locales/si.js b/locales/si.js
index b6767af..28bdec8 100644
--- a/locales/si.js
+++ b/locales/si.js
@@ -117,6 +117,10 @@ export default {
"settings.weekStartsMonday": "සතිය සඳුදා ආරම්භ වේ",
"settings.themeLight": "තේමාව: ආලෝකය",
"settings.themeDark": "තේමාව: අඳුරු",
+ "settings.notificationsOff": "Notifications: Off",
+ "settings.notificationsOn": "Notifications: On",
+ "settings.notificationsBlocked": "Notifications: Blocked",
+ "settings.notificationsUnsupported": "Notifications unsupported",
"settings.language": "භාෂාව",
// Language names
@@ -138,6 +142,9 @@ export default {
"toast.readOnlyEnabled": "Read-only mode enabled",
"toast.editModeEnabled": "Edit mode enabled",
"toast.readOnlyActive": "Read-only mode is on. Switch back to edit mode to make changes.",
+ "toast.notificationsEnabled": "30-minute reminders enabled",
+ "toast.notificationsDisabled": "30-minute reminders disabled",
+ "toast.notificationsBlocked": "Browser notifications are blocked for this site",
"toast.incorrectPassword": "වැරදි මුරපදයක්",
"toast.unableToCopyLink": "සබැඳිය පිටපත් කළ නොහැක",
"toast.unableToCopyJson": "JSON පිටපත් කළ නොහැක",
@@ -184,6 +191,10 @@ export default {
"countdown.startsAt": "{{time}} ට ආරම්භ වේ",
"countdown.starts": "{{date}} {{time}} ට ආරම්භ වේ",
+ // Browser notifications
+ "notify.upcomingTitle": "{{title}} starts soon",
+ "notify.upcomingBody": "Starts at {{time}} (in 30 minutes)",
+
// Agenda view
"agenda.title": "න්‍යාය පත්‍රය",
"agenda.rangeLabel": "න්‍යාය පත්‍රය · {{range}}",
diff --git a/locales/ta.js b/locales/ta.js
index 6a3dd63..5092b93 100644
--- a/locales/ta.js
+++ b/locales/ta.js
@@ -117,6 +117,10 @@ export default {
'settings.weekStartsMonday': 'வாரம் திங்கட்கிழமை தொடங்குகிறது',
'settings.themeLight': 'தோற்றம்: வெளிச்சம்',
'settings.themeDark': 'தோற்றம்: இருள்',
+ 'settings.notificationsOff': 'Notifications: Off',
+ 'settings.notificationsOn': 'Notifications: On',
+ 'settings.notificationsBlocked': 'Notifications: Blocked',
+ 'settings.notificationsUnsupported': 'Notifications unsupported',
'settings.language': 'மொழி',
// Language names
@@ -138,6 +142,9 @@ export default {
'toast.readOnlyEnabled': 'Read-only mode enabled',
'toast.editModeEnabled': 'Edit mode enabled',
'toast.readOnlyActive': 'Read-only mode is on. Switch back to edit mode to make changes.',
+ 'toast.notificationsEnabled': '30-minute reminders enabled',
+ 'toast.notificationsDisabled': '30-minute reminders disabled',
+ 'toast.notificationsBlocked': 'Browser notifications are blocked for this site',
'toast.incorrectPassword': 'தவறான கடவுச்சொல்',
'toast.unableToCopyLink': 'இணைப்பை நகலெடுக்க முடியவில்லை',
'toast.unableToCopyJson': 'JSON ஐ நகலெடுக்க முடியவில்லை',
@@ -184,6 +191,10 @@ export default {
'countdown.startsAt': '{{time}} மணிக்கு தொடங்குகிறது',
'countdown.starts': '{{date}} அன்று {{time}} மணிக்கு தொடங்குகிறது',
+ // Browser notifications
+ 'notify.upcomingTitle': '{{title}} starts soon',
+ 'notify.upcomingBody': 'Starts at {{time}} (in 30 minutes)',
+
// Agenda view
'agenda.title': 'நிகழ்ச்சி நிரல்',
'agenda.rangeLabel': 'நிகழ்ச்சி நிரல் · {{range}}',
diff --git a/modules/constants.js b/modules/constants.js
index 954314c..0e3e749 100644
--- a/modules/constants.js
+++ b/modules/constants.js
@@ -18,6 +18,7 @@ export const DEFAULT_STATE = {
v: DEFAULT_VIEW,
l: "en",
r: 0,
+ n: 0,
},
mp: { h: null, z: ["UTC"], s: null, d: null, f24: false },
};
@@ -26,6 +27,8 @@ export const DEFAULT_STATE = {
export const DEBOUNCE_MS = 500;
export const TOAST_TIMEOUT_MS = 3200;
export const TIMEZONE_UPDATE_INTERVAL_MS = 60000;
+export const NOTIFICATION_CHECK_INTERVAL_MS = 60000;
+export const NOTIFICATION_LEAD_MINUTES = 30;
// Length Limits
export const MAX_TITLE_LENGTH = 60;
diff --git a/modules/hashcalUrlManager.js b/modules/hashcalUrlManager.js
index aec607c..06559cb 100644
--- a/modules/hashcalUrlManager.js
+++ b/modules/hashcalUrlManager.js
@@ -5,7 +5,7 @@ const HASH_PREFIX = "ENC:";
const DEFAULT_TITLE = "hash-calendar";
const DEFAULT_COLORS = ["#ff6b6b", "#ffd43b", "#4dabf7", "#63e6be", "#9775fa"];
-const DEFAULT_SETTINGS = { d: 0, m: 0, v: "month", l: "en", r: 0 };
+const DEFAULT_SETTINGS = { d: 0, m: 0, v: "month", l: "en", r: 0, n: 0 };
function arraysEqual(a, b) {
return a.length === b.length && a.every((v, i) => v === b[i]);
@@ -44,15 +44,16 @@ function compactState(state) {
});
}
- if (state.s) {
- const mini = {};
- if (state.s.d !== DEFAULT_SETTINGS.d) mini.d = state.s.d;
- if (state.s.m !== DEFAULT_SETTINGS.m) mini.m = state.s.m;
- if (typeof state.s.v === "string" && state.s.v !== DEFAULT_SETTINGS.v) mini.v = state.s.v;
- if (typeof state.s.l === "string" && state.s.l !== DEFAULT_SETTINGS.l) mini.l = state.s.l;
- if (Number(state.s.r || 0) !== DEFAULT_SETTINGS.r) mini.r = state.s.r;
- if (Object.keys(mini).length) out.s = mini;
- }
+ if (state.s) {
+ const mini = {};
+ if (state.s.d !== DEFAULT_SETTINGS.d) mini.d = state.s.d;
+ if (state.s.m !== DEFAULT_SETTINGS.m) mini.m = state.s.m;
+ if (typeof state.s.v === "string" && state.s.v !== DEFAULT_SETTINGS.v) mini.v = state.s.v;
+ if (typeof state.s.l === "string" && state.s.l !== DEFAULT_SETTINGS.l) mini.l = state.s.l;
+ if (Number(state.s.r || 0) !== DEFAULT_SETTINGS.r) mini.r = state.s.r;
+ if (Number(state.s.n || 0) !== DEFAULT_SETTINGS.n) mini.n = state.s.n;
+ if (Object.keys(mini).length) out.s = mini;
+ }
if (state.mp) {
const mp = state.mp;
@@ -129,6 +130,7 @@ export async function writeStateToHash(state, password = null) {
return nextHash;
}
-export function clearHash() {
- history.replaceState(null, "", window.location.pathname);
-}
+export function clearHash() {
+ const search = window.location.search || "";
+ history.replaceState(null, "", `${window.location.pathname}${search}`);
+}
diff --git a/modules/modalManager.js b/modules/modalManager.js
new file mode 100644
index 0000000..d03ee34
--- /dev/null
+++ b/modules/modalManager.js
@@ -0,0 +1,135 @@
+export function createPasswordModalController({ ui, hiddenClass, t }) {
+ const safeHiddenClass = hiddenClass || "hidden";
+ let passwordMode = "unlock";
+ let passwordResolver = null;
+
+ function open({ mode, title, description, submitLabel }) {
+ if (!ui || !ui.passwordModal) return Promise.resolve(null);
+
+ if (passwordResolver) {
+ passwordResolver(null);
+ passwordResolver = null;
+ }
+
+ passwordMode = mode;
+ if (ui.passwordTitle) ui.passwordTitle.textContent = title;
+ if (ui.passwordDesc) ui.passwordDesc.textContent = description;
+ if (ui.passwordInput) ui.passwordInput.value = "";
+ if (ui.passwordConfirm) ui.passwordConfirm.value = "";
+ if (ui.passwordError) ui.passwordError.classList.add(safeHiddenClass);
+
+ if (ui.passwordConfirmField) {
+ if (mode === "set") {
+ ui.passwordConfirmField.classList.remove(safeHiddenClass);
+ } else {
+ ui.passwordConfirmField.classList.add(safeHiddenClass);
+ }
+ }
+
+ if (ui.passwordSubmit) ui.passwordSubmit.textContent = submitLabel;
+ ui.passwordModal.classList.remove(safeHiddenClass);
+
+ return new Promise((resolve) => {
+ passwordResolver = resolve;
+ });
+ }
+
+ function close() {
+ if (!ui || !ui.passwordModal) return;
+ ui.passwordModal.classList.add(safeHiddenClass);
+ if (passwordResolver) {
+ passwordResolver(null);
+ passwordResolver = null;
+ }
+ }
+
+ function submit() {
+ if (!passwordResolver) return;
+
+ const value = ui && ui.passwordInput ? ui.passwordInput.value.trim() : "";
+ if (!value) {
+ if (ui && ui.passwordError) {
+ ui.passwordError.textContent = t("password.required");
+ ui.passwordError.classList.remove(safeHiddenClass);
+ }
+ return;
+ }
+
+ if (passwordMode === "set") {
+ const confirmValue = ui && ui.passwordConfirm ? ui.passwordConfirm.value.trim() : "";
+ if (value !== confirmValue) {
+ if (ui && ui.passwordError) {
+ ui.passwordError.textContent = t("password.mismatch");
+ ui.passwordError.classList.remove(safeHiddenClass);
+ }
+ return;
+ }
+ }
+
+ if (ui && ui.passwordModal) {
+ ui.passwordModal.classList.add(safeHiddenClass);
+ }
+ passwordResolver(value);
+ passwordResolver = null;
+ }
+
+ return { open, close, submit };
+}
+
+export function createJsonModalController({
+ ui,
+ hiddenClass,
+ t,
+ showToast,
+ getState,
+ getHash,
+} = {}) {
+ const safeHiddenClass = hiddenClass || "hidden";
+
+ function isOpen() {
+ return !!(ui && ui.jsonModal && !ui.jsonModal.classList.contains(safeHiddenClass));
+ }
+
+ function update() {
+ if (!ui) return;
+ if (ui.jsonOutput && typeof getState === "function") {
+ ui.jsonOutput.value = JSON.stringify(getState(), null, 2);
+ }
+ if (ui.jsonHash && typeof getHash === "function") {
+ ui.jsonHash.value = getHash();
+ }
+ }
+
+ function open() {
+ if (!ui || !ui.jsonModal) return;
+ update();
+ ui.jsonModal.classList.remove(safeHiddenClass);
+ }
+
+ function close() {
+ if (!ui || !ui.jsonModal) return;
+ ui.jsonModal.classList.add(safeHiddenClass);
+ }
+
+ async function copyJson() {
+ if (!ui || !ui.jsonOutput) return;
+ try {
+ await navigator.clipboard.writeText(ui.jsonOutput.value);
+ if (typeof showToast === "function") showToast(t("toast.jsonCopied"), "success");
+ } catch (error) {
+ if (typeof showToast === "function") showToast(t("toast.unableToCopyJson"), "error");
+ }
+ }
+
+ async function copyHash() {
+ if (!ui || !ui.jsonHash) return;
+ try {
+ await navigator.clipboard.writeText(ui.jsonHash.value);
+ if (typeof showToast === "function") showToast(t("toast.hashCopied"), "success");
+ } catch (error) {
+ if (typeof showToast === "function") showToast(t("toast.unableToCopyHash"), "error");
+ }
+ }
+
+ return { isOpen, update, open, close, copyJson, copyHash };
+}
diff --git a/modules/pathImportManager.js b/modules/pathImportManager.js
new file mode 100644
index 0000000..0360aed
--- /dev/null
+++ b/modules/pathImportManager.js
@@ -0,0 +1,93 @@
+function isPathDateSegment(yearText, monthText, dayText) {
+ if (!/^\d{4}$/.test(yearText) || !/^\d{1,2}$/.test(monthText) || !/^\d{1,2}$/.test(dayText)) {
+ return false;
+ }
+
+ const year = Number(yearText);
+ const month = Number(monthText);
+ const day = Number(dayText);
+ if (month < 1 || month > 12 || day < 1 || day > 31) return false;
+
+ const date = new Date(year, month - 1, day);
+ return date.getFullYear() === year && date.getMonth() === month - 1 && date.getDate() === day;
+}
+
+function getAppBasePath(pathname) {
+ const segments = String(pathname || "").split("/").filter(Boolean);
+ let startIndex = -1;
+
+ for (let i = 0; i <= segments.length - 3; i += 1) {
+ if (isPathDateSegment(segments[i], segments[i + 1], segments[i + 2])) {
+ startIndex = i;
+ break;
+ }
+ }
+
+ if (startIndex === -1) {
+ return pathname || "/";
+ }
+
+ const baseSegments = segments.slice(0, startIndex);
+ return `/${baseSegments.join("/")}${baseSegments.length ? "/" : ""}`;
+}
+
+function cleanUrlAfterImport(creationSource, locationObj = window.location, historyObj = window.history) {
+ const search = locationObj.search || "";
+ if (creationSource === "hash") {
+ historyObj.replaceState({}, "", `${locationObj.pathname}${search}`);
+ } else if (creationSource === "pathname") {
+ const hash = locationObj.hash || "";
+ const basePath = getAppBasePath(locationObj.pathname);
+ historyObj.pushState({}, "", `${basePath}${search}${hash}`);
+ }
+}
+
+export function getCreationHashPath(locationObj = window.location) {
+ const rawHash = locationObj.hash.startsWith("#") ? locationObj.hash.slice(1) : locationObj.hash;
+ if (!rawHash || rawHash === "/") return "";
+ return rawHash.startsWith("/") ? rawHash : "";
+}
+
+export async function importEventsFromPath({
+ locationObj = window.location,
+ historyObj = window.history,
+ parsePathToEventEntries,
+ isCalendarLocked,
+ isReadOnlyMode,
+ onEntriesImported,
+ onFirstEntryImported,
+ clearPendingSave,
+ persistStateToHash,
+} = {}) {
+ if (typeof isCalendarLocked === "function" && isCalendarLocked()) return 0;
+ if (typeof isReadOnlyMode === "function" && isReadOnlyMode()) return 0;
+ if (typeof parsePathToEventEntries !== "function") return 0;
+
+ let entries = parsePathToEventEntries(locationObj.pathname);
+ let creationSource = entries.length ? "pathname" : null;
+
+ if (!entries.length) {
+ const hashPath = getCreationHashPath(locationObj);
+ if (hashPath) {
+ entries = parsePathToEventEntries(hashPath);
+ creationSource = entries.length ? "hash" : null;
+ }
+ }
+
+ if (!entries.length) return 0;
+
+ if (typeof onEntriesImported === "function") {
+ onEntriesImported(entries);
+ }
+
+ const firstStartMin = Number(entries[0][0]);
+ if (Number.isFinite(firstStartMin) && typeof onFirstEntryImported === "function") {
+ onFirstEntryImported(firstStartMin);
+ }
+
+ cleanUrlAfterImport(creationSource, locationObj, historyObj);
+
+ if (typeof clearPendingSave === "function") clearPendingSave();
+ if (typeof persistStateToHash === "function") await persistStateToHash();
+ return entries.length;
+}
diff --git a/modules/stateSaveManager.js b/modules/stateSaveManager.js
new file mode 100644
index 0000000..935a3d2
--- /dev/null
+++ b/modules/stateSaveManager.js
@@ -0,0 +1,75 @@
+export class StateSaveManager {
+ constructor({
+ getLockState,
+ hasStoredData,
+ clearHash,
+ writeStateToHash,
+ getState,
+ getPassword,
+ updateUrlLength,
+ onAfterPersist = null,
+ debounceMs = 500,
+ } = {}) {
+ this.getLockState = getLockState;
+ this.hasStoredData = hasStoredData;
+ this.clearHash = clearHash;
+ this.writeStateToHash = writeStateToHash;
+ this.getState = getState;
+ this.getPassword = getPassword;
+ this.updateUrlLength = updateUrlLength;
+ this.onAfterPersist = onAfterPersist;
+ this.debounceMs = debounceMs;
+ this.saveTimer = null;
+ }
+
+ isLocked() {
+ const lockState = typeof this.getLockState === "function" ? this.getLockState() : null;
+ return !!(lockState && lockState.encrypted && !lockState.unlocked);
+ }
+
+ async persistStateToHash() {
+ if (this.isLocked()) return;
+
+ const hasData = typeof this.hasStoredData === "function" ? this.hasStoredData() : false;
+ if (!hasData) {
+ if (window.location.hash && typeof this.clearHash === "function") {
+ this.clearHash();
+ }
+ if (typeof this.updateUrlLength === "function") this.updateUrlLength();
+ if (typeof this.onAfterPersist === "function") this.onAfterPersist();
+ return;
+ }
+
+ if (typeof this.writeStateToHash === "function" && typeof this.getState === "function") {
+ const state = this.getState();
+ const password = typeof this.getPassword === "function" ? this.getPassword() : null;
+ await this.writeStateToHash(state, password);
+ }
+
+ if (typeof this.updateUrlLength === "function") this.updateUrlLength();
+ if (typeof this.onAfterPersist === "function") this.onAfterPersist();
+ }
+
+ clearPendingSave() {
+ if (!this.saveTimer) return;
+ window.clearTimeout(this.saveTimer);
+ this.saveTimer = null;
+ }
+
+ scheduleSave() {
+ if (this.isLocked()) return;
+
+ const hasData = typeof this.hasStoredData === "function" ? this.hasStoredData() : false;
+ if (!hasData) {
+ this.clearPendingSave();
+ this.persistStateToHash();
+ return;
+ }
+
+ this.clearPendingSave();
+ this.saveTimer = window.setTimeout(() => {
+ this.saveTimer = null;
+ this.persistStateToHash();
+ }, this.debounceMs);
+ }
+}
diff --git a/planner_logic.js b/planner_logic.js
deleted file mode 100644
index 15b872c..0000000
--- a/planner_logic.js
+++ /dev/null
@@ -1,452 +0,0 @@
-
-/* --- World Planner Logic --- */
-
-function initWorldPlanner() {
- if (ui.worldPlannerBtn) {
- ui.worldPlannerBtn.addEventListener("click", openWorldPlanner);
- }
- if (ui.wpClose) {
- ui.wpClose.addEventListener("click", closeWorldPlanner);
- }
- if (ui.wpAddZone) {
- ui.wpAddZone.addEventListener("keydown", (e) => {
- if (e.key === "Enter") handlePlannerAddZone();
- });
- }
- if (ui.wpGrid) {
- ui.wpGrid.addEventListener("mousemove", handleScrubberMove);
- ui.wpGrid.addEventListener("click", handleScrubberClick);
- ui.wpGrid.addEventListener("click", handlePlannerGridClick);
- }
- if (ui.wpDatePicker) {
- ui.wpDatePicker.addEventListener("change", (e) => {
- if (!state.mp) state.mp = { h: null, z: [], s: null, d: null };
- state.mp.d = e.target.value;
- scheduleSave();
- renderWorldPlanner();
- });
- }
- if (ui.wpCopyLink) {
- ui.wpCopyLink.addEventListener("click", handleCopyLink);
- }
-}
-
-function openWorldPlanner() {
- if (!ui.worldPlannerModal) return;
-
- // Initialize state if empty
- if (!state.mp || (!state.mp.home && !state.mp.z.length)) {
- const local = getLocalZone();
- state.mp = {
- h: local,
- z: ["UTC", "America/New_York", "Asia/Tokyo", "Europe/London"].filter(z => z !== local).slice(0, 3),
- s: null,
- d: new Date().toISOString().split("T")[0]
- };
- }
-
- // Set date picker
- if (ui.wpDatePicker) {
- ui.wpDatePicker.value = state.mp.d || new Date().toISOString().split("T")[0];
- }
-
- ui.worldPlannerModal.classList.remove("hidden");
- renderWorldPlanner();
-}
-
-function closeWorldPlanner() {
- if (ui.worldPlannerModal) {
- ui.worldPlannerModal.classList.add("hidden");
- }
- scheduleSave();
-}
-
-function handlePlannerAddZone() {
- const val = ui.wpAddZone.value.trim();
- if (!val) return;
- // Simple search match for now
- const match = AVAILABLE_ZONES.find(z => z.toLowerCase().includes(val.toLowerCase()));
-
- if (match) {
- if (state.mp.h !== match && !state.mp.z.includes(match)) {
- state.mp.z.push(match);
- scheduleSave();
- renderWorldPlanner();
- ui.wpAddZone.value = "";
- }
- } else {
- showToast(t("planner.notFound"), "error");
- }
-}
-
-function handlePlannerGridClick(e) {
- // Handle remove/promote buttons
- const btn = e.target.closest(".wp-control-btn");
- if (!btn) return;
-
- const action = btn.dataset.action;
- const zone = btn.dataset.zone;
-
- if (action === "remove") {
- state.mp.z = state.mp.z.filter(z => z !== zone);
- scheduleSave();
- renderWorldPlanner();
- } else if (action === "promote") {
- const oldHome = state.mp.h;
- state.mp.h = zone;
- state.mp.z = state.mp.z.filter(z => z !== zone);
- if (oldHome) state.mp.z.unshift(oldHome);
- scheduleSave();
- renderWorldPlanner();
- }
-}
-
-function getPlannerDate() {
- return state.mp.d ? new Date(state.mp.d) : new Date();
-}
-
-function renderWorldPlanner() {
- if (!ui.wpGrid) return;
-
- ui.wpGrid.innerHTML = "";
-
- // 1. Build City Column
- const cityCol = document.createElement("div");
- cityCol.className = "city-col";
-
- // Home Row
- if (state.mp.h) {
- cityCol.appendChild(createPlannerCityHeader(state.mp.h, true));
- }
-
- // Zones
- state.mp.z.forEach(zone => {
- cityCol.appendChild(createPlannerCityHeader(zone, false));
- });
-
- ui.wpGrid.appendChild(cityCol);
-
- // 2. Build Timeline Column
- const timelineCol = document.createElement("div");
- timelineCol.className = "timeline-col";
-
- const track = document.createElement("div");
- track.className = "timeline-track";
-
- // Scrubber Overlay
- const scrubber = document.createElement("div");
- scrubber.className = "scrubber-overlay hidden"; // Hidden until hover/select
- scrubber.id = "wp-scrubber";
- track.appendChild(scrubber);
-
- const ghost = document.createElement("div");
- ghost.className = "ghost-scrubber hidden";
- ghost.id = "wp-ghost";
- track.appendChild(ghost);
-
- // Render Rows
- const baseDate = getPlannerDate(); // This is "Day 0" at 00:00 relative to Home Zone?
- // Actually WTB usually shows 24h starting from "now" or 00:00 of selected day.
- // Let's stick to 00:00 - 23:00 of the selected date in HOME zone.
-
- if (state.mp.h) {
- track.appendChild(createPlannerRow(state.mp.h, baseDate, true));
- }
- state.mp.z.forEach(zone => {
- track.appendChild(createPlannerRow(zone, baseDate, false));
- });
-
- timelineCol.appendChild(track);
- ui.wpGrid.appendChild(timelineCol);
-
- // Restore selection if any
- if (state.mp.s) {
- // If selected time exists, position scrubber
- // Calculate which slot index corresponds to state.mp.s (timestamp)
- // But wait, the grid is fixed 0-23h of the HOME DAY.
- // So 's' must be converted to an hour index relative to Home 00:00.
-
- // We update logic later. For now, let's just render.
- updateScrubberPositionFromState();
- }
-}
-
-function createPlannerCityHeader(zone, isHome) {
- const div = document.createElement("div");
- div.className = `wp-row-header${isHome ? " home-row" : ""}`;
-
- const info = getZoneInfo(zone); // existing helper
-
- // Controls
- if (!isHome) {
- const controls = document.createElement("div");
- controls.className = "wp-row-controls";
- controls.innerHTML = `
- <button class="wp-control-btn" data-action="promote" data-zone="${zone}" title="${t('planner.homeTitle')}"><i class="fa-solid fa-arrow-up"></i></button>
- <button class="wp-control-btn" data-action="remove" data-zone="${zone}" title="${t('planner.removeTitle')}"><i class="fa-solid fa-xmark"></i></button>
- `;
- div.appendChild(controls);
- } else {
- // Home icon
- const icon = document.createElement("div");
- icon.style.position = "absolute";
- icon.style.top = "6px";
- icon.style.right = "6px";
- icon.innerHTML = `<i class="fa-solid fa-house wp-home-icon"></i>`;
- div.appendChild(icon);
- }
-
- const nameRow = document.createElement("div");
- nameRow.className = "wp-city-name";
- nameRow.textContent = info.name;
-
- const timeRow = document.createElement("div");
- timeRow.className = "wp-city-time";
- timeRow.textContent = info.time; // Current time
-
- const badge = document.createElement("div");
- badge.className = "wp-offset-badge";
- badge.textContent = `UTC${info.offset}`;
-
- div.append(badge, nameRow, timeRow);
- return div;
-}
-
-function createPlannerRow(zone, baseDate, isHome) {
- const row = document.createElement("div");
- row.className = "wp-row-cells";
-
- // Calculate offset relative to Home
- // This is tricky. simpler to just iterate 0..23 hours of the Base Date in Home Zone,
- // and convert each to the target Zone.
-
- const homeZone = state.mp.h;
- if (!homeZone) return row;
-
- // Construct the 24 hours in Home Zone
- // Helper to format date in specific zone
- const fmt = (date, z) => new Intl.DateTimeFormat("en-US", {
- timeZone: z,
- hour: "numeric",
- hour12: true,
- weekday: "short",
- day: "numeric",
- month: "short"
- });
-
- const getParts = (date, z) => {
- const parts = new Intl.DateTimeFormat("en-US", {
- timeZone: z,
- hour: "numeric",
- hourCycle: "h23",
- weekday: "short",
- day: "numeric",
- month: "short"
- }).formatToParts(date);
- const p = {};
- parts.forEach(x => p[x.type] = x.value);
- return p;
- };
-
- const year = baseDate.getFullYear();
- const month = baseDate.getMonth();
- const day = baseDate.getDate();
-
- for (let h = 0; h < 24; h++) {
- const cell = document.createElement("div");
-
- // Create a date object that corresponds to Year-Month-Day Hour:00:00 in HOME zone.
- // We can't just new Date() because that uses local.
- // We need to find the timestamp that corresponds to that wall time.
- // Hack: use a library or localized string parsing.
- // Since we don't have Moment/Luxon, we use the "date string hack".
-
- const isoString = `${year}-${String(month+1).padStart(2,'0')}-${String(day).padStart(2,'0')}T${String(h).padStart(2,'0')}:00:00`;
- // Create date as if it's UTC, then shift by offset? No.
- // Use formatToParts on a guessed timestamp until it matches? Expensive.
-
- // Easier approach:
- // 1. Get offset of Home Zone for that date.
- // 2. Get offset of Target Zone.
- // 3. Difference is the shift.
-
- // Actually, simply iterating standard UTC timestamps starting from the Home Zone's start of day is safest.
- // Let's find Home Zone's start of day timestamp.
- const homeStartStr = new Date(year, month, day).toLocaleString("en-US", { timeZone: homeZone });
- // This doesn't give me the timestamp.
-
- // Let's just mock it by iterating 24 hours from a base UTC time and adjusting display?
- // No, "Exact Match" requires correct hours.
-
- // Efficient Native way:
- // Create an arbitrary UTC date. Format it to Home Zone. See if it matches 00:00.
- // Better:
- // `new Date(string)` parses as local.
- // Use `toLocaleString` to get the wall time in a zone.
-
- // Optimization:
- // Just loop 0..23 integers.
- // For the Home Row, cells are just 0..23.
- // For Other Rows:
- // Calculate offset diff.
- // TargetHour = (HomeHour - HomeOffset + TargetOffset) % 24.
-
- // Getting offsets in JS native is `getTimezoneOffset` but that's only for local.
- // For arbitrary zones, we can use the formatted string 'GMT-5' etc from `getZoneInfo` helper.
- // Helper `getZoneInfo(zone)` returns `{ offset: "+05:30", ... }`.
-
- const homeInfo = getZoneInfo(homeZone);
- const targetInfo = getZoneInfo(zone);
-
- // Parse offsets to minutes
- const parseOff = (s) => {
- const sign = s[0] === '-' ? -1 : 1;
- const [hh, mm] = s.slice(1).split(':').map(Number);
- return sign * (hh * 60 + mm);
- };
-
- const hOff = parseOff(homeInfo.offset); // e.g. +330
- const tOff = parseOff(targetInfo.offset); // e.g. -300
-
- const diffMins = tOff - hOff; // Difference in minutes
-
- // Target time in minutes from start of day = (h * 60) + diffMins
- let targetMins = (h * 60) + diffMins;
-
- // Normalize to day boundaries
- let dayShift = 0;
- if (targetMins < 0) {
- targetMins += 24 * 60;
- dayShift = -1;
- } else if (targetMins >= 24 * 60) {
- targetMins -= 24 * 60;
- dayShift = 1;
- }
-
- const tHour = Math.floor(targetMins / 60);
- const tMin = targetMins % 60; // Usually 0 or 30 or 45
-
- // Class logic
- let cls = "wp-cell";
- // Business: 9-17 (Standard) or 8-18? Req says 8-17 business, 18-22 active.
- // Using Target Hour.
- if (tHour >= 8 && tHour <= 17) cls += " business";
- else if (tHour >= 18 && tHour <= 22) cls += " active";
- else cls += " sleep";
-
- if (dayShift !== 0 && h === 0) {
- // Start of row shows date if different?
- }
-
- // Crossing midnight logic for cell style
- if (tHour === 0 && tMin === 0) {
- cls += " date-boundary";
- // Show date
- // Calculate date string
- // If dayShift is 1, it's Next Day.
- }
-
- cell.className = cls;
- cell.dataset.h = h; // Home Hour index
-
- // Content
- if (tHour === 0 && tMin === 0) {
- // Show date abbrev
- const d = new Date(baseDate);
- d.setDate(d.getDate() + dayShift);
- const translatedMonth = getTranslatedMonthName(d, true);
- cell.textContent = `${translatedMonth} ${d.getDate()}`.toUpperCase();
- } else {
- // Format: "9 am" or "14:30"
- let label = "";
- const ampm = tHour >= 12 ? "pm" : "am";
- const h12 = tHour % 12 || 12;
- if (tMin > 0) {
- label = `${h12}:${String(tMin).padStart(2,'0')}`; // Space tight
- } else {
- label = `${h12} ${ampm}`;
- }
- // Compact for cells
- if (isHome) {
- cell.textContent = tMin > 0 ? `${h12}:${tMin}` : `${h12} ${ampm}`;
- } else {
- cell.textContent = tMin > 0 ? `${h12}:${tMin}` : `${h12}`; // Just number for comparison rows to save space?
- }
- }
-
- row.appendChild(cell);
- }
-
- return row;
-}
-
-function handleScrubberMove(e) {
- const track = ui.wpGrid.querySelector(".timeline-track");
- const ghost = document.getElementById("wp-ghost");
- if (!track || !ghost) return;
-
- // Calculate index
- const rect = track.getBoundingClientRect();
- const x = e.clientX - rect.left - track.scrollLeft; // Adjust for scroll?
- // Wait, track scrolls. `e.clientX` is viewport. `rect.left` is viewport.
- // Inside `timeline-col`, `timeline-track` might be wide.
- // Actually the hover is relative to the `timeline-truck` element?
-
- // The event listener is on `wpGrid`.
- // We need to find the `.wp-cell` under mouse.
- const cell = e.target.closest(".wp-cell");
- if (!cell) {
- ghost.classList.add("hidden");
- return;
- }
-
- const widthStr = window.getComputedStyle(cell).width; // e.g. "40px"
- // Actually simpler: cell.offsetLeft
- ghost.style.left = `${cell.offsetLeft}px`;
- ghost.classList.remove("hidden");
-}
-
-function handleScrubberClick(e) {
- const cell = e.target.closest(".wp-cell");
- if (!cell) return;
-
- const hIndex = cell.dataset.h;
- // Set selection state
- // Convert hIndex (0..23) of Home Zone to Timestamp
- // We need a timestamp for persistence.
- // timestamp = startOfBaseDate(HomeZone) + hIndex * 3600 * 1000
-
- // For now simple numeric logic? The schema calls for 'sel' as timestamp.
- const baseDate = getPlannerDate();
- // Assume HomeZone start of day + hIndex hours.
- // Approximation for prototype:
- const ts = baseDate.getTime() + (hIndex * 3600 * 1000);
-
- state.mp.s = ts;
- scheduleSave();
-
- updateScrubberPositionFromState();
-}
-
-function updateScrubberPositionFromState() {
- const scrubber = document.getElementById("wp-scrubber");
- if (!scrubber || !state.mp.s) {
- if (scrubber) scrubber.classList.add("hidden");
- return;
- }
-
- // Convert state.mp.s to hour index
- const baseDate = getPlannerDate();
- const diff = state.mp.s - baseDate.getTime();
- const hIndex = Math.floor(diff / (3600 * 1000));
-
- if (hIndex >= 0 && hIndex < 24) {
- // Find a cell with this index
- // Since all rows are aligned, any row's cell works.
- const cell = ui.wpGrid.querySelector(`.wp-cell[data-h="${hIndex}"]`);
- if (cell) {
- scrubber.style.left = `${cell.offsetLeft}px`;
- scrubber.classList.remove("hidden");
- }
- }
-}
diff --git a/script.js b/script.js
index 20aa763..7e05ae6 100644
--- a/script.js
+++ b/script.js
@@ -9,51 +9,58 @@ import {
renderWeekdayHeaders,
renderYearView,
} from "./modules/calendarRender.js";
-import {
- COLOR_REGEX,
- CSS_CLASSES,
- DEBOUNCE_MS,
- DEFAULT_COLORS,
- DEFAULT_EVENT_DURATION,
- DEFAULT_STATE,
- DEFAULT_VIEW,
- MAX_EVENT_TITLE_LENGTH,
- MAX_TITLE_LENGTH,
- MAX_TZ_RESULTS,
- MIN_SEARCH_LENGTH,
- MS_PER_MINUTE,
- TIMEZONE_UPDATE_INTERVAL_MS,
- TOAST_TIMEOUT_MS,
- TZ_EMPTY_MESSAGE,
- URL_LENGTH_WARNING_THRESHOLD,
+import {
+ COLOR_REGEX,
+ CSS_CLASSES,
+ DEBOUNCE_MS,
+ DEFAULT_COLORS,
+ DEFAULT_EVENT_DURATION,
+ DEFAULT_STATE,
+ DEFAULT_VIEW,
+ MAX_EVENT_TITLE_LENGTH,
+ MAX_TITLE_LENGTH,
+ MAX_TZ_RESULTS,
+ MIN_SEARCH_LENGTH,
+ NOTIFICATION_CHECK_INTERVAL_MS,
+ NOTIFICATION_LEAD_MINUTES,
+ MS_PER_MINUTE,
+ TIMEZONE_UPDATE_INTERVAL_MS,
+ TOAST_TIMEOUT_MS,
+ TZ_EMPTY_MESSAGE,
+ URL_LENGTH_WARNING_THRESHOLD,
VALID_VIEWS,
} from "./modules/constants.js";
import { initCountdownWidget } from "./modules/countdownManager.js";
import { FocusMode } from "./modules/focusMode.js";
import { clearHash, isEncryptedHash, readStateFromHash, writeStateToHash } from "./modules/hashcalUrlManager.js";
import { getCurrentLanguage, getCurrentLocale, getTranslatedMonthName, getTranslatedWeekday, setLanguage, SUPPORTED_LANGUAGES, t } from "./modules/i18n.js";
-import { parseIcs } from "./modules/icsImporter.js";
-import { initQRCodeManager } from "./modules/qrCodeManager.js";
-import { expandEvents } from "./modules/recurrenceEngine.js";
-import { AVAILABLE_ZONES, getLocalZone, getZoneInfo, isValidZone, parseOffsetSearchTerm } from "./modules/timezoneManager.js";
-import { parsePathToEventEntries } from "./modules/urlPathEventParser.js";
-import { WorldPlanner } from "./modules/worldPlannerModule.js";
+import { parseIcs } from "./modules/icsImporter.js";
+import { createJsonModalController, createPasswordModalController } from "./modules/modalManager.js";
+import { getCreationHashPath, importEventsFromPath as importEventsFromPathFromLocation } from "./modules/pathImportManager.js";
+import { initQRCodeManager } from "./modules/qrCodeManager.js";
+import { expandEvents } from "./modules/recurrenceEngine.js";
+import { StateSaveManager } from "./modules/stateSaveManager.js";
+import { AVAILABLE_ZONES, getLocalZone, getZoneInfo, isValidZone, parseOffsetSearchTerm } from "./modules/timezoneManager.js";
+import { parsePathToEventEntries } from "./modules/urlPathEventParser.js";
+import { WorldPlanner } from "./modules/worldPlannerModule.js";
let state = cloneState(DEFAULT_STATE);
let viewDate = startOfDay(new Date());
let selectedDate = startOfDay(new Date());
-let currentView = DEFAULT_VIEW;
-let password = null;
-let lockState = { encrypted: false, unlocked: true };
-let saveTimer = null;
-let occurrencesByDay = new Map();
-let editingIndex = null;
-let passwordResolver = null;
-let passwordMode = "unlock";
-let focusMode = null;
-let worldPlanner = null;
-let qrManager = null;
-let timezoneTimer = null;
+let currentView = DEFAULT_VIEW;
+let password = null;
+let lockState = { encrypted: false, unlocked: true };
+let occurrencesByDay = new Map();
+let editingIndex = null;
+let focusMode = null;
+let worldPlanner = null;
+let qrManager = null;
+let timezoneTimer = null;
+let saveManager = null;
+let passwordModalController = null;
+let jsonModalController = null;
+let notificationTimer = null;
+const notifiedOccurrences = new Map();
const ui = {};
@@ -61,9 +68,13 @@ function isCalendarLocked() {
return lockState.encrypted && !lockState.unlocked;
}
-function isReadOnlyMode() {
- return !!(state && state.s && state.s.r);
-}
+function isReadOnlyMode() {
+ return !!(state && state.s && state.s.r);
+}
+
+function isNotificationEnabled() {
+ return !!(state && state.s && state.s.n);
+}
function ensureEditable({ silent = false } = {}) {
if (isCalendarLocked()) return false;
@@ -206,14 +217,15 @@ function normalizeState(raw) {
.filter((entry) => Number.isFinite(entry[0]));
}
- if (raw.s && typeof raw.s === "object") {
- next.s.d = raw.s.d ? 1 : 0;
- next.s.m = raw.s.m ? 1 : 0;
- next.s.r = raw.s.r ? 1 : 0;
- next.s.v = getStoredView(raw.s.v);
- if (raw.s.l && typeof raw.s.l === "string") {
- const allowed = SUPPORTED_LANGUAGES.map((lang) => lang.code);
- next.s.l = allowed.includes(raw.s.l) ? raw.s.l : "en";
+ if (raw.s && typeof raw.s === "object") {
+ next.s.d = raw.s.d ? 1 : 0;
+ next.s.m = raw.s.m ? 1 : 0;
+ next.s.r = raw.s.r ? 1 : 0;
+ next.s.n = raw.s.n ? 1 : 0;
+ next.s.v = getStoredView(raw.s.v);
+ if (raw.s.l && typeof raw.s.l === "string") {
+ const allowed = SUPPORTED_LANGUAGES.map((lang) => lang.code);
+ next.s.l = allowed.includes(raw.s.l) ? raw.s.l : "en";
}
}
@@ -268,9 +280,10 @@ function cacheElements() {
ui.readOnlyBtn = document.getElementById("readonly-btn");
ui.focusBtn = document.getElementById("focus-btn");
ui.viewButtons = Array.from(document.querySelectorAll(".view-toggle button"));
- ui.weekstartToggle = document.getElementById("weekstart-toggle");
- ui.themeToggle = document.getElementById("theme-toggle");
- ui.langBtn = document.getElementById("language-btn");
+ ui.weekstartToggle = document.getElementById("weekstart-toggle");
+ ui.themeToggle = document.getElementById("theme-toggle");
+ ui.notifyToggle = document.getElementById("notify-toggle");
+ ui.langBtn = document.getElementById("language-btn");
ui.langList = document.getElementById("language-list");
ui.currentLang = document.getElementById("current-lang");
ui.langDropdown = document.getElementById("language-dropdown");
@@ -373,9 +386,10 @@ function cacheElements() {
ui.mobileShareExportSection = document.getElementById("mobile-share-export-section");
ui.mobileDangerZoneSection = document.getElementById("mobile-danger-zone-section");
ui.mobileDrawerViewButtons = Array.from(document.querySelectorAll(".mobile-drawer-view-toggle [data-view]"));
- ui.mobileWeekstartToggle = document.getElementById("mobile-weekstart-toggle");
- ui.mobileThemeToggle = document.getElementById("mobile-theme-toggle");
- ui.mobileReadOnlyBtn = document.getElementById("mobile-readonly-btn");
+ ui.mobileWeekstartToggle = document.getElementById("mobile-weekstart-toggle");
+ ui.mobileThemeToggle = document.getElementById("mobile-theme-toggle");
+ ui.mobileNotifyToggle = document.getElementById("mobile-notify-toggle");
+ ui.mobileReadOnlyBtn = document.getElementById("mobile-readonly-btn");
ui.mobileLangBtn = document.getElementById("mobile-language-btn");
ui.mobileLangList = document.getElementById("mobile-language-list");
ui.mobileCurrentLang = document.getElementById("mobile-current-lang");
@@ -396,9 +410,9 @@ function showToast(message, type = "info") {
}, TOAST_TIMEOUT_MS);
}
-function hasStoredData() {
- return !!((state.e && state.e.length) || (state.mp && state.mp.z && state.mp.z.length > 1) || isReadOnlyMode());
-}
+function hasStoredData() {
+ return !!((state.e && state.e.length) || (state.mp && state.mp.z && state.mp.z.length > 1) || isReadOnlyMode() || isNotificationEnabled());
+}
function createTzCard(zoneId, isLocal, isUTC = false) {
const data = getZoneInfo(zoneId);
@@ -610,39 +624,20 @@ function initTimezones() {
}, delay);
}
-async function persistStateToHash() {
- if (lockState.encrypted && !lockState.unlocked) return;
- if (!hasStoredData()) {
- if (window.location.hash) clearHash();
- updateUrlLength();
- if (ui.jsonModal && !ui.jsonModal.classList.contains(CSS_CLASSES.HIDDEN)) {
- updateJsonModal();
- }
- return;
- }
- await writeStateToHash(state, password);
- updateUrlLength();
- if (ui.jsonModal && !ui.jsonModal.classList.contains(CSS_CLASSES.HIDDEN)) {
- updateJsonModal();
- }
-}
-
-function scheduleSave() {
- if (lockState.encrypted && !lockState.unlocked) return;
- if (!hasStoredData()) {
- if (saveTimer) {
- window.clearTimeout(saveTimer);
- saveTimer = null;
- }
- persistStateToHash();
- return;
- }
- if (saveTimer) window.clearTimeout(saveTimer);
- saveTimer = window.setTimeout(() => {
- saveTimer = null;
- persistStateToHash();
- }, DEBOUNCE_MS);
-}
+async function persistStateToHash() {
+ if (!saveManager) return;
+ await saveManager.persistStateToHash();
+}
+
+function scheduleSave() {
+ if (!saveManager) return;
+ saveManager.scheduleSave();
+}
+
+function clearPendingSave() {
+ if (!saveManager) return;
+ saveManager.clearPendingSave();
+}
function updateUrlLength() {
const length = window.location.hash.length;
@@ -674,14 +669,145 @@ function syncTopbarHeight() {
document.documentElement.style.setProperty("--topbar-plus-quick", `${topbarH + quickH}px`);
}
-function updateWeekStartLabel() {
- const label = t(state.s.m ? "settings.weekStartsMonday" : "settings.weekStartsSunday");
- if (ui.weekstartToggle) ui.weekstartToggle.textContent = label;
- if (ui.mobileWeekstartToggle) {
- const span = ui.mobileWeekstartToggle.querySelector("span");
- if (span) span.textContent = label;
- }
-}
+function updateWeekStartLabel() {
+ const label = t(state.s.m ? "settings.weekStartsMonday" : "settings.weekStartsSunday");
+ if (ui.weekstartToggle) ui.weekstartToggle.textContent = label;
+ if (ui.mobileWeekstartToggle) {
+ const span = ui.mobileWeekstartToggle.querySelector("span");
+ if (span) span.textContent = label;
+ }
+}
+
+function supportsBrowserNotifications() {
+ return typeof window !== "undefined" && "Notification" in window;
+}
+
+function updateNotificationToggleLabel() {
+ let key = "settings.notificationsOff";
+ if (!supportsBrowserNotifications()) {
+ key = "settings.notificationsUnsupported";
+ } else if (Notification.permission === "denied") {
+ key = "settings.notificationsBlocked";
+ } else if (isNotificationEnabled() && Notification.permission === "granted") {
+ key = "settings.notificationsOn";
+ }
+
+ const label = t(key);
+ if (ui.notifyToggle) ui.notifyToggle.textContent = label;
+ if (ui.mobileNotifyToggle) {
+ const span = ui.mobileNotifyToggle.querySelector("span");
+ if (span) span.textContent = label;
+ }
+}
+
+function stopNotificationWatcher() {
+ if (notificationTimer) {
+ window.clearInterval(notificationTimer);
+ notificationTimer = null;
+ }
+}
+
+function pruneNotifiedOccurrences(nowMs) {
+ const expiryMs = nowMs - NOTIFICATION_LEAD_MINUTES * MS_PER_MINUTE;
+ for (const [key, startMs] of notifiedOccurrences.entries()) {
+ if (startMs < expiryMs) {
+ notifiedOccurrences.delete(key);
+ }
+ }
+}
+
+function showUpcomingEventNotification(occurrence) {
+ if (!supportsBrowserNotifications() || Notification.permission !== "granted") return;
+ const title = t("notify.upcomingTitle", { title: occurrence.title || "Untitled" });
+ const timeLabel = formatTime(new Date(occurrence.start));
+ const body = t("notify.upcomingBody", { time: timeLabel });
+ const notification = new Notification(title, {
+ body,
+ tag: `hashcal-${occurrence.sourceIndex}-${occurrence.start}`,
+ });
+
+ notification.onclick = () => {
+ window.focus();
+ const eventDate = startOfDay(new Date(occurrence.start));
+ selectedDate = eventDate;
+ viewDate = eventDate;
+ render();
+ notification.close();
+ };
+}
+
+function runNotificationCheck() {
+ if (!supportsBrowserNotifications()) return;
+ if (!isNotificationEnabled()) return;
+ if (Notification.permission !== "granted") return;
+
+ const nowMs = Date.now();
+ const leadMs = NOTIFICATION_LEAD_MINUTES * MS_PER_MINUTE;
+ const rangeStartMs = nowMs + leadMs - NOTIFICATION_CHECK_INTERVAL_MS;
+ const rangeEndMs = nowMs + leadMs + NOTIFICATION_CHECK_INTERVAL_MS;
+
+ pruneNotifiedOccurrences(nowMs);
+
+ const occurrences = expandEvents(state.e || [], new Date(rangeStartMs), new Date(rangeEndMs));
+ occurrences
+ .filter((occ) => !occ.isAllDay && occ.start >= rangeStartMs && occ.start <= rangeEndMs)
+ .forEach((occ) => {
+ const key = `${occ.sourceIndex}:${occ.start}`;
+ if (notifiedOccurrences.has(key)) return;
+ notifiedOccurrences.set(key, occ.start);
+ showUpcomingEventNotification(occ);
+ });
+}
+
+function syncNotificationWatcher() {
+ stopNotificationWatcher();
+ if (!supportsBrowserNotifications()) return;
+ if (!isNotificationEnabled()) return;
+ if (Notification.permission !== "granted") return;
+
+ runNotificationCheck();
+ notificationTimer = window.setInterval(runNotificationCheck, NOTIFICATION_CHECK_INTERVAL_MS);
+}
+
+async function handleNotificationToggle() {
+ if (!ensureEditable()) return;
+ if (!supportsBrowserNotifications()) {
+ showToast(t("settings.notificationsUnsupported"), "error");
+ updateNotificationToggleLabel();
+ return;
+ }
+
+ if (isNotificationEnabled()) {
+ state.s.n = 0;
+ stopNotificationWatcher();
+ scheduleSave();
+ updateNotificationToggleLabel();
+ showToast(t("toast.notificationsDisabled"), "info");
+ return;
+ }
+
+ if (Notification.permission === "denied") {
+ showToast(t("toast.notificationsBlocked"), "error");
+ updateNotificationToggleLabel();
+ return;
+ }
+
+ let permission = Notification.permission;
+ if (permission !== "granted") {
+ permission = await Notification.requestPermission();
+ }
+ if (permission !== "granted") {
+ if (permission === "denied") showToast(t("toast.notificationsBlocked"), "error");
+ updateNotificationToggleLabel();
+ return;
+ }
+
+ state.s.n = 1;
+ scheduleSave();
+ updateNotificationToggleLabel();
+ syncNotificationWatcher();
+ showToast(t("toast.notificationsEnabled"), "success");
+}
function updateFocusButton(isActive) {
if (!ui.focusBtn) return;
@@ -785,15 +911,17 @@ function updateLockUI() {
ui.titleInput.readOnly = editDisabled;
}
- [
- ui.addEventBtn,
- ui.addEventInline,
- ui.mobileAddEventInline,
- ui.mobileAddEvent,
- ui.importIcs,
- ui.mobileImportIcs,
- ui.clearAll,
- ui.mobileClearAll,
+ [
+ ui.addEventBtn,
+ ui.addEventInline,
+ ui.mobileAddEventInline,
+ ui.mobileAddEvent,
+ ui.notifyToggle,
+ ui.mobileNotifyToggle,
+ ui.importIcs,
+ ui.mobileImportIcs,
+ ui.clearAll,
+ ui.mobileClearAll,
ui.tzAddBtn,
ui.mobileAddTzBtn,
].forEach((btn) => {
@@ -1006,13 +1134,14 @@ function decorateOccurrences(occurrences) {
});
}
-function render() {
- updateTheme();
- updateWeekStartLabel();
- // Dropdown UI is updated via updateLanguageUI which is called separately
- if (ui.titleInput && document.activeElement !== ui.titleInput) {
- ui.titleInput.value = state.t;
- }
+function render() {
+ updateTheme();
+ updateWeekStartLabel();
+ updateNotificationToggleLabel();
+ // Dropdown UI is updated via updateLanguageUI which is called separately
+ if (ui.titleInput && document.activeElement !== ui.titleInput) {
+ ui.titleInput.value = state.t;
+ }
const weekStartsOnMonday = state.s.m === 1;
if (ui.calendarGrid) {
@@ -1350,58 +1479,20 @@ function deleteEvent() {
render();
}
-function openPasswordModal({ mode, title, description, submitLabel }) {
- if (!ui.passwordModal) return Promise.resolve(null);
- passwordMode = mode;
- ui.passwordTitle.textContent = title;
- ui.passwordDesc.textContent = description;
- ui.passwordInput.value = "";
- ui.passwordConfirm.value = "";
- ui.passwordError.classList.add(CSS_CLASSES.HIDDEN);
-
- if (mode === "set") {
- ui.passwordConfirmField.classList.remove(CSS_CLASSES.HIDDEN);
- } else {
- ui.passwordConfirmField.classList.add(CSS_CLASSES.HIDDEN);
- }
-
- ui.passwordSubmit.textContent = submitLabel;
- ui.passwordModal.classList.remove(CSS_CLASSES.HIDDEN);
-
- return new Promise((resolve) => {
- passwordResolver = resolve;
- });
-}
-
-function closePasswordModal() {
- if (ui.passwordModal) ui.passwordModal.classList.add(CSS_CLASSES.HIDDEN);
- if (passwordResolver) {
- passwordResolver(null);
- passwordResolver = null;
- }
-}
-
-function submitPassword() {
- if (!passwordResolver) return;
- const value = ui.passwordInput.value.trim();
- if (!value) {
- ui.passwordError.textContent = t("password.required");
- ui.passwordError.classList.remove(CSS_CLASSES.HIDDEN);
- return;
- }
-
- if (passwordMode === "set") {
- if (value !== ui.passwordConfirm.value.trim()) {
- ui.passwordError.textContent = t("password.mismatch");
- ui.passwordError.classList.remove(CSS_CLASSES.HIDDEN);
- return;
- }
- }
-
- ui.passwordModal.classList.add(CSS_CLASSES.HIDDEN);
- passwordResolver(value);
- passwordResolver = null;
-}
+function openPasswordModal({ mode, title, description, submitLabel }) {
+ if (!passwordModalController) return Promise.resolve(null);
+ return passwordModalController.open({ mode, title, description, submitLabel });
+}
+
+function closePasswordModal() {
+ if (!passwordModalController) return;
+ passwordModalController.close();
+}
+
+function submitPassword() {
+ if (!passwordModalController) return;
+ passwordModalController.submit();
+}
async function handleLockAction() {
if (lockState.encrypted && !lockState.unlocked) {
@@ -1434,7 +1525,7 @@ async function handleLockAction() {
showToast(t("toast.calendarLocked"), "success");
}
-async function attemptUnlock() {
+async function attemptUnlock() {
const value = await openPasswordModal({
mode: "unlock",
title: t("modal.unlockCalendar"),
@@ -1446,101 +1537,67 @@ async function attemptUnlock() {
const loaded = await readStateFromHash(value);
password = value;
lockState = { encrypted: true, unlocked: true };
- state = normalizeState(loaded);
- if (state.s.l) setLanguage(state.s.l);
- applyStoredView();
- await importEventsFromPath();
- render();
+ state = normalizeState(loaded);
+ if (state.s.l) setLanguage(state.s.l);
+ applyStoredView();
+ syncNotificationWatcher();
+ await importEventsFromPath();
+ render();
showToast(t("toast.calendarUnlocked"), "success");
- } catch (error) {
- showToast(t("toast.incorrectPassword"), "error");
- lockState = { encrypted: true, unlocked: false };
- updateLockUI();
- }
-}
-
-async function loadStateFromHash() {
- if (!window.location.hash || getCreationHashPath()) {
+ } catch (error) {
+ showToast(t("toast.incorrectPassword"), "error");
+ lockState = { encrypted: true, unlocked: false };
+ updateLockUI();
+ syncNotificationWatcher();
+ }
+}
+
+async function loadStateFromHash() {
+ if (!window.location.hash || getCreationHashPath()) {
state = cloneState(DEFAULT_STATE);
// Initialize language from local storage if no hash
- state.s.l = getCurrentLanguage();
- applyStoredView();
- return;
- }
+ state.s.l = getCurrentLanguage();
+ applyStoredView();
+ syncNotificationWatcher();
+ return;
+ }
if (isEncryptedHash()) {
- lockState = { encrypted: true, unlocked: false };
- state = cloneState(DEFAULT_STATE);
- updateLockUI();
- return;
- }
+ lockState = { encrypted: true, unlocked: false };
+ state = cloneState(DEFAULT_STATE);
+ updateLockUI();
+ syncNotificationWatcher();
+ return;
+ }
try {
const loaded = await readStateFromHash();
state = normalizeState(loaded);
if (state.s.l) setLanguage(state.s.l);
- } catch (error) {
- state = cloneState(DEFAULT_STATE);
- }
- applyStoredView();
-}
-
-function getCreationHashPath() {
- const rawHash = window.location.hash.startsWith("#") ? window.location.hash.slice(1) : window.location.hash;
- if (!rawHash || rawHash === "/") return "";
- return rawHash.startsWith("/") ? rawHash : "";
-}
-
-function cleanUrlAfterImport(creationSource) {
- const search = window.location.search || "";
- if (creationSource === "hash") {
- // Remove the human-readable hash
- window.history.replaceState({}, "", `${window.location.pathname}${search}`);
- } else if (creationSource === "pathname") {
- // Remove the human-readable pathname and redirect to root
- const hash = window.location.hash || "";
- window.history.pushState({}, "", `/${search}${hash}`);
- }
-}
-
-async function importEventsFromPath() {
- if (isCalendarLocked() || isReadOnlyMode()) return 0;
-
- // Check pathname first
- let entries = parsePathToEventEntries(window.location.pathname);
- let creationSource = entries.length ? "pathname" : null;
-
- // Check hash second (only if pathname didn't have readable data)
- if (!entries.length) {
- const hashPath = getCreationHashPath();
- if (hashPath) {
- entries = parsePathToEventEntries(hashPath);
- creationSource = entries.length ? "hash" : null;
- }
- }
-
- if (!entries.length) return 0;
-
- // USER DEFINITION: any readable pattern import is source === "path"
- const source = "path";
- state.e.push(...entries);
-
- const firstStartMin = Number(entries[0][0]);
- if (Number.isFinite(firstStartMin)) {
- const firstDate = startOfDay(new Date(firstStartMin * MS_PER_MINUTE));
- selectedDate = firstDate;
- viewDate = firstDate;
- }
-
- // Always clean the URL and persist to compressed hash for "path" source
- cleanUrlAfterImport(creationSource);
- if (saveTimer) {
- window.clearTimeout(saveTimer);
- saveTimer = null;
- }
- await persistStateToHash();
- return entries.length;
-}
+ } catch (error) {
+ state = cloneState(DEFAULT_STATE);
+ }
+ applyStoredView();
+ syncNotificationWatcher();
+}
+
+async function importEventsFromPath() {
+ return importEventsFromPathFromLocation({
+ parsePathToEventEntries,
+ isCalendarLocked,
+ isReadOnlyMode,
+ onEntriesImported: (entries) => {
+ state.e.push(...entries);
+ },
+ onFirstEntryImported: (firstStartMin) => {
+ const firstDate = startOfDay(new Date(firstStartMin * MS_PER_MINUTE));
+ selectedDate = firstDate;
+ viewDate = firstDate;
+ },
+ clearPendingSave,
+ persistStateToHash,
+ });
+}
function handleHashChange() {
loadStateFromHash().then(() => {
@@ -1654,45 +1711,30 @@ function handleFocusToggle() {
}
}
-function updateJsonModal() {
- if (ui.jsonOutput) {
- ui.jsonOutput.value = JSON.stringify(state, null, 2);
- }
- if (ui.jsonHash) {
- ui.jsonHash.value = window.location.hash || "";
- }
-}
-
-function openJsonModal() {
- if (!ui.jsonModal) return;
- updateJsonModal();
- ui.jsonModal.classList.remove(CSS_CLASSES.HIDDEN);
-}
-
-function closeJsonModal() {
- if (!ui.jsonModal) return;
- ui.jsonModal.classList.add(CSS_CLASSES.HIDDEN);
-}
-
-async function handleCopyJson() {
- if (!ui.jsonOutput) return;
- try {
- await navigator.clipboard.writeText(ui.jsonOutput.value);
- showToast(t("toast.jsonCopied"), "success");
- } catch (error) {
- showToast(t("toast.unableToCopyJson"), "error");
- }
-}
-
-async function handleCopyHash() {
- if (!ui.jsonHash) return;
- try {
- await navigator.clipboard.writeText(ui.jsonHash.value);
- showToast(t("toast.hashCopied"), "success");
- } catch (error) {
- showToast(t("toast.unableToCopyHash"), "error");
- }
-}
+function updateJsonModal() {
+ if (!jsonModalController) return;
+ jsonModalController.update();
+}
+
+function openJsonModal() {
+ if (!jsonModalController) return;
+ jsonModalController.open();
+}
+
+function closeJsonModal() {
+ if (!jsonModalController) return;
+ jsonModalController.close();
+}
+
+async function handleCopyJson() {
+ if (!jsonModalController) return;
+ await jsonModalController.copyJson();
+}
+
+async function handleCopyHash() {
+ if (!jsonModalController) return;
+ await jsonModalController.copyHash();
+}
function handleExportJson() {
const blob = new Blob([JSON.stringify(state, null, 2)], { type: "application/json" });
@@ -1803,11 +1845,12 @@ function bindEvents() {
if (ui.copyLinkBtn) ui.copyLinkBtn.addEventListener("click", handleCopyLink);
if (ui.shareQrBtn) ui.shareQrBtn.addEventListener("click", handleShareQr);
if (ui.lockBtn) ui.lockBtn.addEventListener("click", handleLockAction);
- if (ui.readOnlyBtn) ui.readOnlyBtn.addEventListener("click", handleReadOnlyToggle);
- if (ui.focusBtn) ui.focusBtn.addEventListener("click", handleFocusToggle);
- if (ui.weekstartToggle) ui.weekstartToggle.addEventListener("click", handleWeekStartToggle);
- if (ui.themeToggle) ui.themeToggle.addEventListener("click", handleThemeToggle);
- initLanguageDropdown();
+ if (ui.readOnlyBtn) ui.readOnlyBtn.addEventListener("click", handleReadOnlyToggle);
+ if (ui.focusBtn) ui.focusBtn.addEventListener("click", handleFocusToggle);
+ if (ui.weekstartToggle) ui.weekstartToggle.addEventListener("click", handleWeekStartToggle);
+ if (ui.themeToggle) ui.themeToggle.addEventListener("click", handleThemeToggle);
+ if (ui.notifyToggle) ui.notifyToggle.addEventListener("click", handleNotificationToggle);
+ initLanguageDropdown();
if (ui.unlockBtn) ui.unlockBtn.addEventListener("click", attemptUnlock);
if (ui.viewJson) ui.viewJson.addEventListener("click", openJsonModal);
if (ui.exportJson) ui.exportJson.addEventListener("click", handleExportJson);
@@ -1847,9 +1890,14 @@ function bindEvents() {
});
}
- window.addEventListener("hashchange", handleHashChange);
- window.addEventListener("resize", syncTopbarHeight);
-}
+ window.addEventListener("hashchange", handleHashChange);
+ window.addEventListener("resize", syncTopbarHeight);
+ document.addEventListener("visibilitychange", () => {
+ if (document.hidden) return;
+ updateNotificationToggleLabel();
+ runNotificationCheck();
+ });
+}
function openMobileDrawer() {
if (ui.mobileDrawer) ui.mobileDrawer.classList.add(CSS_CLASSES.IS_ACTIVE);
@@ -1945,12 +1993,15 @@ function initResponsiveFeatures() {
}
// Drawer settings buttons
- if (ui.mobileWeekstartToggle) {
- ui.mobileWeekstartToggle.addEventListener("click", handleWeekStartToggle);
- }
- if (ui.mobileThemeToggle) {
- ui.mobileThemeToggle.addEventListener("click", handleThemeToggle);
- }
+ if (ui.mobileWeekstartToggle) {
+ ui.mobileWeekstartToggle.addEventListener("click", handleWeekStartToggle);
+ }
+ if (ui.mobileThemeToggle) {
+ ui.mobileThemeToggle.addEventListener("click", handleThemeToggle);
+ }
+ if (ui.mobileNotifyToggle) {
+ ui.mobileNotifyToggle.addEventListener("click", handleNotificationToggle);
+ }
if (ui.mobileReadOnlyBtn) {
ui.mobileReadOnlyBtn.addEventListener("click", () => {
handleReadOnlyToggle();
@@ -1998,13 +2049,41 @@ function initResponsiveFeatures() {
}
}
-async function init() {
- cacheElements();
- syncTopbarHeight();
- qrManager = initQRCodeManager({
- onBeforeOpen: persistStateToHash,
- onCopyLink: handleCopyLink,
- showToast,
+async function init() {
+ cacheElements();
+ syncTopbarHeight();
+ passwordModalController = createPasswordModalController({
+ ui,
+ hiddenClass: CSS_CLASSES.HIDDEN,
+ t,
+ });
+ jsonModalController = createJsonModalController({
+ ui,
+ hiddenClass: CSS_CLASSES.HIDDEN,
+ t,
+ showToast,
+ getState: () => state,
+ getHash: () => window.location.hash || "",
+ });
+ saveManager = new StateSaveManager({
+ getLockState: () => lockState,
+ hasStoredData,
+ clearHash,
+ writeStateToHash,
+ getState: () => state,
+ getPassword: () => password,
+ updateUrlLength,
+ onAfterPersist: () => {
+ if (jsonModalController && jsonModalController.isOpen()) {
+ jsonModalController.update();
+ }
+ },
+ debounceMs: DEBOUNCE_MS,
+ });
+ qrManager = initQRCodeManager({
+ onBeforeOpen: persistStateToHash,
+ onCopyLink: handleCopyLink,
+ showToast,
});
focusMode = new FocusMode({
getState: () => state,
diff --git a/sw.js b/sw.js
index 023fd77..167fb42 100644
--- a/sw.js
+++ b/sw.js
@@ -1,4 +1,4 @@
-const CACHE_NAME = 'hash-calendar-v3';
+const CACHE_NAME = 'hash-calendar-v5';
const ASSETS_TO_CACHE = [
'./',
'./index.html',
@@ -19,8 +19,11 @@ const ASSETS_TO_CACHE = [
'./modules/focusMode.js',
'./modules/hashcalUrlManager.js',
'./modules/icsImporter.js',
+ './modules/modalManager.js',
+ './modules/pathImportManager.js',
'./modules/qrCodeManager.js',
'./modules/recurrenceEngine.js',
+ './modules/stateSaveManager.js',
'./modules/timezoneManager.js',
// External resources (Font Awesome, Fonts)
'https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.2/css/all.min.css',