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

Update Time zone manager in to a module

Supun Lakmalf9cf09a7cb96
diff --git a/modules/constants.js b/modules/constants.js
new file mode 100644
index 0000000..71850fe
--- /dev/null
+++ b/modules/constants.js
@@ -0,0 +1,80 @@
+// Calendar Constants
+
+// Default Color Palette
+export const DEFAULT_COLORS = ["#ff6b6b", "#ffd43b", "#4dabf7", "#63e6be", "#9775fa"];
+
+// View Types
+export const DEFAULT_VIEW = "month";
+export const VALID_VIEWS = new Set(["day", "week", "month", "year", "agenda"]);
+
+// Default Application State
+export const DEFAULT_STATE = {
+ t: "hash-calendar",
+ c: DEFAULT_COLORS,
+ e: [],
+ s: {
+ d: 0,
+ m: 0,
+ v: DEFAULT_VIEW,
+ l: "en",
+ r: 0,
+ },
+ timezones: [],
+ mp: { h: null, z: [], s: null, d: null },
+};
+
+// Timing Constants
+export const DEBOUNCE_MS = 500;
+export const TOAST_TIMEOUT_MS = 3200;
+export const TIMEZONE_UPDATE_INTERVAL_MS = 60000;
+
+// Length Limits
+export const MAX_TITLE_LENGTH = 60;
+export const MAX_EVENT_TITLE_LENGTH = 80;
+export const MAX_TZ_RESULTS = 12;
+
+// URL Constants
+export const URL_LENGTH_WARNING_THRESHOLD = 2000;
+
+// Messages
+export const TZ_EMPTY_MESSAGE = "No matches yet. Try a city, region, or UTC+5:30.";
+
+// Search/Filter Constants
+export const MIN_SEARCH_LENGTH = 2;
+
+// World Planner Constants
+export const PLANNER_HOURS_PER_DAY = 24;
+export const PLANNER_BUSINESS_HOUR_START = 8;
+export const PLANNER_BUSINESS_HOUR_END = 17;
+export const PLANNER_ACTIVE_HOUR_START = 18;
+export const PLANNER_ACTIVE_HOUR_END = 22;
+export const PLANNER_DEFAULT_ZONES = ["UTC", "America/New_York", "Asia/Tokyo", "Europe/London"];
+export const PLANNER_MAX_ZONES = 3;
+
+// Time Constants
+export const MINUTES_PER_HOUR = 60;
+export const MS_PER_MINUTE = 60000;
+export const MS_PER_HOUR = 3600000;
+export const MINUTES_PER_DAY = 1440;
+
+// Default Event Values
+export const DEFAULT_EVENT_DURATION = 60;
+
+// CSS Class Names
+export const CSS_CLASSES = {
+ HIDDEN: "hidden",
+ ACTIVE: "active",
+ IS_ACTIVE: "is-active",
+ IS_SELECTED: "is-selected",
+ IS_ACTIVE_TOGGLE: "is-active-toggle",
+ RIPPLE: "ripple",
+ VIEW_ANIMATE_OUT: "view-animate-out",
+ VIEW_ANIMATE_IN: "view-animate-in",
+};
+
+// Regex Patterns
+export const COLOR_REGEX = /^#?([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/;
+
+// Offset Parsing
+export const OFFSET_MAX_HOURS = 14;
+export const OFFSET_MAX_MINUTES = 59;
diff --git a/modules/timezoneManager.js b/modules/timezoneManager.js
index 64e3ace..d1729ad 100644
--- a/modules/timezoneManager.js
+++ b/modules/timezoneManager.js
@@ -1,3 +1,5 @@
+import { OFFSET_MAX_HOURS, OFFSET_MAX_MINUTES } from "./constants.js";
+
const supportedZones =
typeof Intl.supportedValuesOf === "function" ? Intl.supportedValuesOf("timeZone") : [];
@@ -95,3 +97,58 @@ export function isValidZone(zoneName) {
return false;
}
}
+
+export function getLocalZone() {
+ return Intl.DateTimeFormat().resolvedOptions().timeZone || "UTC";
+}
+
+export function parseOffsetSearchTerm(raw) {
+ if (!raw) return null;
+ let term = raw.toLowerCase().replace(/\s+/g, "");
+ let hasPrefix = false;
+ if (term.startsWith("utc")) {
+ term = term.slice(3);
+ hasPrefix = true;
+ } else if (term.startsWith("gmt")) {
+ term = term.slice(3);
+ hasPrefix = true;
+ }
+ if (!term) return null;
+
+ let sign = null;
+ if (term.startsWith("+") || term.startsWith("-")) {
+ sign = term[0];
+ term = term.slice(1);
+ }
+
+ const hasSeparator = term.includes(":") || term.includes(".");
+
+ let hours = null;
+ let minutes = null;
+ let hasMinutes = false;
+
+ if (hasSeparator) {
+ const parts = term.split(/[:.]/);
+ if (parts.length !== 2) return null;
+ hours = Number(parts[0]);
+ minutes = Number(parts[1]);
+ hasMinutes = parts[1].length > 0;
+ } else if (/^\d{1,2}$/.test(term)) {
+ hours = Number(term);
+ minutes = 0;
+ } else if (/^\d{3,4}$/.test(term)) {
+ const padded = term.padStart(4, "0");
+ hours = Number(padded.slice(0, 2));
+ minutes = Number(padded.slice(2));
+ hasMinutes = true;
+ } else {
+ return null;
+ }
+
+ if (!Number.isFinite(hours) || !Number.isFinite(minutes)) return null;
+ if (hours > OFFSET_MAX_HOURS || minutes > OFFSET_MAX_MINUTES) return null;
+
+ const signChar = sign || "+";
+ const value = `${signChar}${hours}:${String(minutes).padStart(2, "0")}`;
+ return { value, sign, hours, minutes, hasMinutes };
+}
diff --git a/modules/worldPlannerModule.js b/modules/worldPlannerModule.js
new file mode 100644
index 0000000..02a2cbd
--- /dev/null
+++ b/modules/worldPlannerModule.js
@@ -0,0 +1,503 @@
+import { getZoneInfo, isValidZone, AVAILABLE_ZONES, getLocalZone, parseOffsetSearchTerm } from "./timezoneManager.js";
+import { t } from "./i18n.js";
+import {
+ PLANNER_HOURS_PER_DAY,
+ PLANNER_BUSINESS_HOUR_START,
+ PLANNER_BUSINESS_HOUR_END,
+ PLANNER_ACTIVE_HOUR_START,
+ PLANNER_ACTIVE_HOUR_END,
+ PLANNER_DEFAULT_ZONES,
+ PLANNER_MAX_ZONES,
+ MAX_TZ_RESULTS,
+ MIN_SEARCH_LENGTH,
+ MS_PER_HOUR,
+ CSS_CLASSES,
+} from "./constants.js";
+
+export class WorldPlanner {
+ constructor({
+ getState,
+ updateState,
+ ensureEditable,
+ scheduleSave,
+ showToast,
+ closeMobileDrawer
+ } = {}) {
+ // Store dependencies
+ this.getState = getState;
+ this.updateState = updateState;
+ this.ensureEditable = ensureEditable;
+ this.scheduleSave = scheduleSave;
+ this.showToast = showToast;
+ this.closeMobileDrawer = closeMobileDrawer;
+
+ // Cache DOM elements
+ this.modal = document.getElementById("world-planner-modal");
+ this.closeBtn = document.getElementById("wp-close");
+ this.grid = document.getElementById("wp-grid");
+ this.addZoneInput = document.getElementById("wp-add-zone");
+ this.datePicker = document.getElementById("wp-date-picker");
+ this.formatToggle = document.getElementById("wp-format-toggle");
+ this.tzResultsList = document.getElementById("wp-tz-results");
+
+ // Bind methods
+ this.handleTzInput = this.handleTzInput.bind(this);
+ this.handleGridClick = this.handleGridClick.bind(this);
+ this.handleScrubberMove = this.handleScrubberMove.bind(this);
+ this.handleScrubberClick = this.handleScrubberClick.bind(this);
+ this.handleDateChange = this.handleDateChange.bind(this);
+ this.toggleFormat = this.toggleFormat.bind(this);
+
+ // Setup event listeners
+ this.bindEvents();
+ }
+
+ bindEvents() {
+ if (this.closeBtn) {
+ this.closeBtn.addEventListener("click", () => this.close());
+ }
+ if (this.addZoneInput) {
+ this.addZoneInput.addEventListener("input", this.handleTzInput);
+ }
+ if (this.datePicker) {
+ this.datePicker.addEventListener("change", this.handleDateChange);
+ }
+ if (this.formatToggle) {
+ this.formatToggle.addEventListener("click", this.toggleFormat);
+ }
+ if (this.grid) {
+ this.grid.addEventListener("mousemove", this.handleScrubberMove);
+ this.grid.addEventListener("click", (e) => {
+ this.handleScrubberClick(e);
+ this.handleGridClick(e);
+ });
+ }
+ }
+
+ isOpen() {
+ return this.modal && !this.modal.classList.contains(CSS_CLASSES.HIDDEN);
+ }
+
+ open() {
+ if (!this.modal) return;
+
+ const canEdit = typeof this.ensureEditable === "function"
+ ? this.ensureEditable({ silent: true })
+ : true;
+
+ const state = this.getState();
+
+ // Initialize state if empty
+ if ((!state.mp || (!state.mp.h && !state.mp.z.length)) && canEdit) {
+ const local = getLocalZone();
+ const newMp = {
+ h: local,
+ z: PLANNER_DEFAULT_ZONES.filter(z => z !== local).slice(0, PLANNER_MAX_ZONES),
+ s: null,
+ d: new Date().toISOString().split("T")[0],
+ f24: false
+ };
+ this.updateState("mp", newMp);
+ }
+
+ // Ensure f24 exists for legacy states
+ if (state.mp && state.mp.f24 === undefined && canEdit) {
+ this.updateState("mp", { ...state.mp, f24: false });
+ }
+
+ // Set date picker
+ if (this.datePicker && state.mp) {
+ this.datePicker.value = state.mp.d || new Date().toISOString().split("T")[0];
+ }
+
+ this.updateFormatBtn();
+ this.modal.classList.remove(CSS_CLASSES.HIDDEN);
+ this.render();
+ }
+
+ close() {
+ if (!this.modal) return;
+ this.modal.classList.add(CSS_CLASSES.HIDDEN);
+
+ if (typeof this.ensureEditable === "function"
+ && this.ensureEditable({ silent: true })
+ && typeof this.scheduleSave === "function") {
+ this.scheduleSave();
+ }
+ }
+
+ handleDateChange(e) {
+ if (!this.ensureEditable || !this.ensureEditable()) {
+ const state = this.getState();
+ e.target.value = (state.mp && state.mp.d) || new Date().toISOString().split("T")[0];
+ return;
+ }
+ const state = this.getState();
+ if (!state.mp) {
+ this.updateState("mp", { h: null, z: [], s: null, d: null, f24: false });
+ }
+ this.updateState("mp", { ...state.mp, d: e.target.value });
+ this.scheduleSave();
+ this.render();
+ }
+
+ handleTzInput(e) {
+ const term = e.target.value.trim().toLowerCase();
+ if (!this.tzResultsList) return;
+
+ if (term.length < MIN_SEARCH_LENGTH) {
+ this.tzResultsList.innerHTML = "";
+ this.tzResultsList.classList.add(CSS_CLASSES.HIDDEN);
+ return;
+ }
+
+ const state = this.getState();
+ const offsetQuery = parseOffsetSearchTerm(term);
+ const existing = new Set([state.mp.h, ...state.mp.z]);
+
+ const matches = AVAILABLE_ZONES.filter((zone) => {
+ if (existing.has(zone)) return false;
+ const zoneLower = zone.toLowerCase();
+ if (zoneLower.includes(term)) return true;
+
+ // Offset match
+ if (offsetQuery) {
+ const zoneOffset = getZoneInfo(zone).offset;
+ const normalized = `${offsetQuery.hours}:${String(offsetQuery.minutes).padStart(2, "0")}`;
+ if (offsetQuery.hasMinutes) {
+ if (offsetQuery.sign) return zoneOffset === `${offsetQuery.sign}${normalized}`;
+ return zoneOffset === `+${normalized}` || zoneOffset === `-${normalized}`;
+ }
+ if (offsetQuery.sign) return zoneOffset.startsWith(`${offsetQuery.sign}${offsetQuery.hours}`);
+ return zoneOffset.startsWith(`+${offsetQuery.hours}`) || zoneOffset.startsWith(`-${offsetQuery.hours}`);
+ }
+ return false;
+ }).slice(0, MAX_TZ_RESULTS);
+
+ this.renderTzResults(matches);
+ }
+
+ renderTzResults(results) {
+ if (!this.tzResultsList) return;
+ this.tzResultsList.innerHTML = "";
+
+ if (!results.length) {
+ this.tzResultsList.classList.add(CSS_CLASSES.HIDDEN);
+ return;
+ }
+
+ results.forEach(zone => {
+ const li = document.createElement("li");
+ const button = document.createElement("button");
+ button.type = "button";
+ button.className = "tz-result-btn";
+
+ const info = getZoneInfo(zone);
+ const name = document.createElement("span");
+ name.className = "tz-result-name";
+ name.textContent = zone;
+
+ const offset = document.createElement("span");
+ offset.className = "tz-result-offset";
+ offset.textContent = `UTC${info.offset}`;
+
+ button.append(name, offset);
+
+ button.addEventListener("click", () => {
+ this.addZone(zone);
+ this.tzResultsList.classList.add(CSS_CLASSES.HIDDEN);
+ if (this.addZoneInput) this.addZoneInput.value = "";
+ });
+
+ li.appendChild(button);
+ this.tzResultsList.appendChild(li);
+ });
+
+ this.tzResultsList.classList.remove(CSS_CLASSES.HIDDEN);
+ }
+
+ addZone(zone) {
+ if (!this.ensureEditable || !this.ensureEditable()) return;
+ const state = this.getState();
+ if (state.mp.h !== zone && !state.mp.z.includes(zone)) {
+ const newZ = [...state.mp.z, zone];
+ this.updateState("mp", { ...state.mp, z: newZ });
+ this.scheduleSave();
+ this.render();
+ }
+ }
+
+ handleGridClick(e) {
+ if (!this.ensureEditable || !this.ensureEditable()) return;
+ const btn = e.target.closest(".wp-control-btn");
+ if (!btn) return;
+
+ const action = btn.dataset.action;
+ const zone = btn.dataset.zone;
+ const state = this.getState();
+
+ if (action === "remove") {
+ const newZ = state.mp.z.filter(z => z !== zone);
+ this.updateState("mp", { ...state.mp, z: newZ });
+ this.scheduleSave();
+ this.render();
+ } else if (action === "promote") {
+ const oldHome = state.mp.h;
+ const newZ = state.mp.z.filter(z => z !== zone);
+ if (oldHome) newZ.unshift(oldHome);
+ this.updateState("mp", { ...state.mp, h: zone, z: newZ });
+ this.scheduleSave();
+ this.render();
+ }
+ }
+
+ getPlannerDate() {
+ const state = this.getState();
+ return state.mp.d ? new Date(state.mp.d) : new Date();
+ }
+
+ render() {
+ if (!this.grid) return;
+
+ this.grid.innerHTML = "";
+ const state = this.getState();
+
+ // 1. Build City Column
+ const cityCol = document.createElement("div");
+ cityCol.className = "city-col";
+
+ // Home Row
+ if (state.mp.h) {
+ cityCol.appendChild(this.createCityHeader(state.mp.h, true));
+ }
+
+ // Zones
+ state.mp.z.forEach(zone => {
+ cityCol.appendChild(this.createCityHeader(zone, false));
+ });
+
+ this.grid.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";
+ 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 = this.getPlannerDate();
+
+ if (state.mp.h) {
+ track.appendChild(this.createRow(state.mp.h, baseDate, true));
+ }
+ state.mp.z.forEach(zone => {
+ track.appendChild(this.createRow(zone, baseDate, false));
+ });
+
+ timelineCol.appendChild(track);
+ this.grid.appendChild(timelineCol);
+
+ // Restore selection if any
+ if (state.mp.s) {
+ this.updateScrubberPosition();
+ }
+ }
+
+ createCityHeader(zone, isHome) {
+ const div = document.createElement("div");
+ div.className = `wp-row-header${isHome ? " home-row" : ""}`;
+
+ const info = getZoneInfo(zone);
+
+ // 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="Make Home"><i class="fa-solid fa-arrow-up"></i></button>
+ <button class="wp-control-btn" data-action="remove" data-zone="${zone}" title="Remove"><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;
+
+ const badge = document.createElement("div");
+ badge.className = "wp-offset-badge";
+ badge.textContent = `UTC${info.offset}`;
+
+ div.append(badge, nameRow, timeRow);
+ return div;
+ }
+
+ createRow(zone, baseDate, isHome) {
+ const row = document.createElement("div");
+ row.className = "wp-row-cells";
+
+ const state = this.getState();
+ const homeZone = state.mp.h;
+ if (!homeZone) return row;
+
+ const homeInfo = getZoneInfo(homeZone);
+ const targetInfo = getZoneInfo(zone);
+
+ 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);
+ const tOff = parseOff(targetInfo.offset);
+ const diffMins = tOff - hOff;
+
+ const is24h = !!state.mp.f24;
+
+ for (let h = 0; h < PLANNER_HOURS_PER_DAY; h++) {
+ const cell = document.createElement("div");
+
+ let targetMins = (h * 60) + diffMins;
+ 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;
+
+ let cls = "wp-cell";
+ if (tHour >= PLANNER_BUSINESS_HOUR_START && tHour <= PLANNER_BUSINESS_HOUR_END) cls += " business";
+ else if (tHour >= PLANNER_ACTIVE_HOUR_START && tHour <= PLANNER_ACTIVE_HOUR_END) cls += " active";
+ else cls += " sleep";
+
+ if (tHour === 0 && tMin === 0) {
+ cls += " date-boundary";
+ }
+
+ cell.className = cls;
+ cell.dataset.h = h;
+
+ if (tHour === 0 && tMin === 0) {
+ const d = new Date(baseDate);
+ d.setDate(d.getDate() + dayShift);
+ cell.textContent = d.toLocaleDateString('en-US', { day: 'numeric', month: 'short' }).toUpperCase();
+ } else {
+ if (is24h) {
+ cell.textContent = tMin > 0 ? `${tHour}:${String(tMin).padStart(2, '0')}` : `${tHour}`;
+ } else {
+ const ampm = tHour >= 12 ? "pm" : "am";
+ const h12 = tHour % 12 || 12;
+ if (tMin > 0) {
+ cell.textContent = `${h12}:${String(tMin).padStart(2, '0')}`;
+ } else {
+ // Only show am/pm for home zone
+ cell.textContent = isHome ? `${h12} ${ampm}` : `${h12}`;
+ }
+ }
+ }
+ row.appendChild(cell);
+ }
+ return row;
+ }
+
+ handleScrubberMove(e) {
+ const track = this.grid ? this.grid.querySelector(".timeline-track") : null;
+ const ghost = document.getElementById("wp-ghost");
+ if (!track || !ghost) return;
+
+ const cell = e.target.closest(".wp-cell");
+ if (!cell) {
+ ghost.classList.add(CSS_CLASSES.HIDDEN);
+ return;
+ }
+
+ ghost.style.left = `${cell.offsetLeft}px`;
+ ghost.classList.remove(CSS_CLASSES.HIDDEN);
+ }
+
+ handleScrubberClick(e) {
+ if (!this.ensureEditable || !this.ensureEditable()) return;
+ const cell = e.target.closest(".wp-cell");
+ if (!cell) return;
+
+ const hIndex = Number(cell.dataset.h);
+ const baseDate = this.getPlannerDate();
+ const ts = baseDate.getTime() + (hIndex * MS_PER_HOUR);
+
+ const state = this.getState();
+ this.updateState("mp", { ...state.mp, s: ts });
+ this.scheduleSave();
+ this.updateScrubberPosition();
+ }
+
+ updateScrubberPosition() {
+ const scrubber = document.getElementById("wp-scrubber");
+ const state = this.getState();
+ if (!scrubber || !state.mp || !state.mp.s) {
+ if (scrubber) scrubber.classList.add(CSS_CLASSES.HIDDEN);
+ return;
+ }
+
+ const baseDate = this.getPlannerDate();
+ const diff = state.mp.s - baseDate.getTime();
+ const hIndex = Math.floor(diff / MS_PER_HOUR);
+
+ if (hIndex >= 0 && hIndex < PLANNER_HOURS_PER_DAY) {
+ const cell = this.grid ? this.grid.querySelector(`.wp-cell[data-h="${hIndex}"]`) : null;
+ if (cell) {
+ scrubber.style.left = `${cell.offsetLeft}px`;
+ scrubber.classList.remove(CSS_CLASSES.HIDDEN);
+ }
+ } else {
+ scrubber.classList.add(CSS_CLASSES.HIDDEN);
+ }
+ }
+
+ toggleFormat() {
+ if (!this.ensureEditable || !this.ensureEditable()) return;
+ const state = this.getState();
+ if (!state.mp) return;
+ this.updateState("mp", { ...state.mp, f24: !state.mp.f24 });
+ this.updateFormatBtn();
+ this.scheduleSave();
+ this.render();
+ }
+
+ updateFormatBtn() {
+ const btn = document.getElementById("wp-format-toggle");
+ const state = this.getState();
+ if (btn) {
+ btn.textContent = state.mp && state.mp.f24 ? "24h" : "12h";
+ }
+ }
+}
diff --git a/script.js b/script.js
index 4ff38bf..b900e0c 100644
--- a/script.js
+++ b/script.js
@@ -2,9 +2,10 @@ import { readStateFromHash, writeStateToHash, isEncryptedHash, clearHash } from
import { expandEvents } from "./modules/recurrenceEngine.js";
import { renderAgendaView } from "./modules/agendaRender.js";
import { FocusMode } from "./modules/focusMode.js";
+import { WorldPlanner } from "./modules/worldPlannerModule.js";
import { initQRCodeManager } from "./modules/qrCodeManager.js";
import { initCountdownWidget } from "./modules/countdownManager.js";
-import { AVAILABLE_ZONES, getZoneInfo, isValidZone } from "./modules/timezoneManager.js";
+import { AVAILABLE_ZONES, getZoneInfo, isValidZone, getLocalZone, parseOffsetSearchTerm } from "./modules/timezoneManager.js";
import {
formatDateKey,
getMonthGridRange,
@@ -26,29 +27,37 @@ import {
getTranslatedWeekday,
SUPPORTED_LANGUAGES,
} from "./modules/i18n.js";
+import {
+ DEFAULT_COLORS,
+ DEFAULT_VIEW,
+ VALID_VIEWS,
+ DEFAULT_STATE,
+ DEBOUNCE_MS,
+ TOAST_TIMEOUT_MS,
+ TIMEZONE_UPDATE_INTERVAL_MS,
+ MAX_TITLE_LENGTH,
+ MAX_EVENT_TITLE_LENGTH,
+ MAX_TZ_RESULTS,
+ URL_LENGTH_WARNING_THRESHOLD,
+ TZ_EMPTY_MESSAGE,
+ MIN_SEARCH_LENGTH,
+ PLANNER_HOURS_PER_DAY,
+ PLANNER_BUSINESS_HOUR_START,
+ PLANNER_BUSINESS_HOUR_END,
+ PLANNER_ACTIVE_HOUR_START,
+ PLANNER_ACTIVE_HOUR_END,
+ PLANNER_DEFAULT_ZONES,
+ PLANNER_MAX_ZONES,
+ MINUTES_PER_HOUR,
+ MS_PER_MINUTE,
+ MS_PER_HOUR,
+ DEFAULT_EVENT_DURATION,
+ CSS_CLASSES,
+ COLOR_REGEX,
+ OFFSET_MAX_HOURS,
+ OFFSET_MAX_MINUTES,
+} from "./modules/constants.js";
-const DEFAULT_COLORS = ["#ff6b6b", "#ffd43b", "#4dabf7", "#63e6be", "#9775fa"];
-const DEFAULT_VIEW = "month";
-const VALID_VIEWS = new Set(["day", "week", "month", "year", "agenda"]);
-const DEFAULT_STATE = {
- t: "hash-calendar",
- c: DEFAULT_COLORS,
- e: [],
- s: {
- d: 0,
- m: 0,
- v: DEFAULT_VIEW,
- l: "en",
- r: 0,
- },
- timezones: [],
- mp: { h: null, z: [], s: null, d: null },
-};
-
-const DEBOUNCE_MS = 500;
-const MAX_TITLE_LENGTH = 60;
-const MAX_TZ_RESULTS = 12;
-const TZ_EMPTY_MESSAGE = "No matches yet. Try a city, region, or UTC+5:30.";
let state = cloneState(DEFAULT_STATE);
let viewDate = startOfDay(new Date());
@@ -62,33 +71,34 @@ let editingIndex = null;
let passwordResolver = null;
let passwordMode = "unlock";
let focusMode = null;
+let worldPlanner = null;
let qrManager = null;
-let timezoneTimer = null;
-
-const ui = {};
-
-function isCalendarLocked() {
- return lockState.encrypted && !lockState.unlocked;
-}
-
-function isReadOnlyMode() {
- return !!(state && state.s && state.s.r);
-}
-
-function ensureEditable({ silent = false } = {}) {
- if (isCalendarLocked()) return false;
- if (isReadOnlyMode()) {
- if (!silent) {
- showToast(t("toast.readOnlyActive"), "info");
- }
- return false;
- }
- return true;
-}
-
-function cloneState(source) {
- return JSON.parse(JSON.stringify(source));
-}
+let timezoneTimer = null;
+
+const ui = {};
+
+function isCalendarLocked() {
+ return lockState.encrypted && !lockState.unlocked;
+}
+
+function isReadOnlyMode() {
+ return !!(state && state.s && state.s.r);
+}
+
+function ensureEditable({ silent = false } = {}) {
+ if (isCalendarLocked()) return false;
+ if (isReadOnlyMode()) {
+ if (!silent) {
+ showToast(t("toast.readOnlyActive"), "info");
+ }
+ return false;
+ }
+ return true;
+}
+
+function cloneState(source) {
+ return JSON.parse(JSON.stringify(source));
+}
function createRipple(event) {
const button = event.target.closest("button");
@@ -103,9 +113,9 @@ function createRipple(event) {
circle.style.width = circle.style.height = `${diameter}px`;
circle.style.left = `${event.clientX - rect.left - radius}px`;
circle.style.top = `${event.clientY - rect.top - radius}px`;
- circle.classList.add("ripple");
+ circle.classList.add(CSS_CLASSES.RIPPLE);
- const ripple = button.getElementsByClassName("ripple")[0];
+ const ripple = button.getElementsByClassName(CSS_CLASSES.RIPPLE)[0];
if (ripple) {
ripple.remove();
}
@@ -191,13 +201,13 @@ function normalizeState(raw) {
next.c = DEFAULT_COLORS.slice();
for (const [i, color] of Object.entries(raw.c)) {
const idx = Number(i);
- if (idx >= 0 && idx < next.c.length && typeof color === "string" && /^#?([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/.test(color)) {
+ if (idx >= 0 && idx < next.c.length && typeof color === "string" && COLOR_REGEX.test(color)) {
next.c[idx] = color.startsWith("#") ? color : `#${color}`;
}
}
} else if (Array.isArray(raw.c) && raw.c.length) {
next.c = raw.c
- .filter((color) => typeof color === "string" && /^#?([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/.test(color))
+ .filter((color) => typeof color === "string" && COLOR_REGEX.test(color))
.map((color) => (color.startsWith("#") ? color : `#${color}`));
if (!next.c.length) next.c = DEFAULT_COLORS.slice();
}
@@ -208,7 +218,7 @@ function normalizeState(raw) {
.map((entry) => {
const startMin = Number(entry[0]);
const duration = Math.max(0, Number(entry[1]) || 0);
- const title = String(entry[2] || "Untitled").slice(0, 80);
+ const title = String(entry[2] || "Untitled").slice(0, MAX_EVENT_TITLE_LENGTH);
const colorIndex = Math.max(0, Math.min(next.c.length - 1, Number(entry[3]) || 0));
const rule = ["d", "w", "m", "y"].includes(entry[4]) ? entry[4] : "";
const event = [startMin, duration, title, colorIndex];
@@ -218,15 +228,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.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 (Array.isArray(raw.timezones) || Array.isArray(raw.z) || Array.isArray(raw.tz)) {
@@ -255,11 +265,11 @@ function cacheElements() {
ui.nextMonth = document.getElementById("next-month");
ui.todayBtn = document.getElementById("today-btn");
ui.addEventBtn = document.getElementById("add-event");
- ui.copyLinkBtn = document.getElementById("copy-link");
- ui.shareQrBtn = document.getElementById("share-qr");
- ui.lockBtn = document.getElementById("lock-btn");
- ui.readOnlyBtn = document.getElementById("readonly-btn");
- ui.focusBtn = document.getElementById("focus-btn");
+ ui.copyLinkBtn = document.getElementById("copy-link");
+ ui.shareQrBtn = document.getElementById("share-qr");
+ ui.lockBtn = document.getElementById("lock-btn");
+ 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");
@@ -362,22 +372,16 @@ function cacheElements() {
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.mobileLangBtn = document.getElementById("mobile-language-btn");
+ ui.mobileWeekstartToggle = document.getElementById("mobile-weekstart-toggle");
+ ui.mobileThemeToggle = document.getElementById("mobile-theme-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");
ui.mobileLangDropdown = document.getElementById("mobile-language-dropdown");
// World Planner
ui.worldPlannerBtn = document.getElementById("world-planner-btn");
- ui.worldPlannerModal = document.getElementById("world-planner-modal");
- ui.wpClose = document.getElementById("wp-close");
- ui.wpAddZone = document.getElementById("wp-add-zone");
- ui.wpGrid = document.getElementById("wp-grid");
- ui.wpDatePicker = document.getElementById("wp-date-picker");
- ui.wpCopyLink = document.getElementById("wp-copy-link");
}
function showToast(message, type = "info") {
@@ -388,17 +392,13 @@ function showToast(message, type = "info") {
ui.toastContainer.appendChild(toast);
setTimeout(() => {
toast.remove();
- }, 3200);
+ }, TOAST_TIMEOUT_MS);
}
function hasStoredData() {
return (state.e && state.e.length) || (state.timezones && state.timezones.length);
}
-function getLocalZone() {
- return Intl.DateTimeFormat().resolvedOptions().timeZone || "UTC";
-}
-
function createTzCard(zoneId, isLocal) {
const data = getZoneInfo(zoneId);
const div = document.createElement("div");
@@ -452,11 +452,11 @@ function renderTimezones() {
});
}
-function addTimezone(zoneStr) {
- if (!ensureEditable()) return;
- if (!zoneStr || !isValidZone(zoneStr)) return;
- const localZone = getLocalZone();
- if (zoneStr === localZone) return;
+function addTimezone(zoneStr) {
+ if (!ensureEditable()) return;
+ if (!zoneStr || !isValidZone(zoneStr)) return;
+ const localZone = getLocalZone();
+ if (zoneStr === localZone) return;
if (!Array.isArray(state.timezones)) state.timezones = [];
if (state.timezones.includes(zoneStr)) return;
state.timezones.push(zoneStr);
@@ -464,11 +464,11 @@ function addTimezone(zoneStr) {
renderTimezones();
}
-function removeTimezone(zoneStr) {
- if (!ensureEditable()) return;
- if (!Array.isArray(state.timezones) || !zoneStr) return;
- state.timezones = state.timezones.filter((zone) => zone !== zoneStr);
- scheduleSave();
+function removeTimezone(zoneStr) {
+ if (!ensureEditable()) return;
+ if (!Array.isArray(state.timezones) || !zoneStr) return;
+ state.timezones = state.timezones.filter((zone) => zone !== zoneStr);
+ scheduleSave();
renderTimezones();
}
@@ -494,57 +494,6 @@ function renderTzResults(results) {
});
}
-function parseOffsetSearchTerm(raw) {
- if (!raw) return null;
- let term = raw.toLowerCase().replace(/\s+/g, "");
- let hasPrefix = false;
- if (term.startsWith("utc")) {
- term = term.slice(3);
- hasPrefix = true;
- } else if (term.startsWith("gmt")) {
- term = term.slice(3);
- hasPrefix = true;
- }
- if (!term) return null;
-
- let sign = null;
- if (term.startsWith("+") || term.startsWith("-")) {
- sign = term[0];
- term = term.slice(1);
- }
-
- const hasSeparator = term.includes(":") || term.includes(".");
-
- let hours = null;
- let minutes = null;
- let hasMinutes = false;
-
- if (hasSeparator) {
- const parts = term.split(/[:.]/);
- if (parts.length !== 2) return null;
- hours = Number(parts[0]);
- minutes = Number(parts[1]);
- hasMinutes = parts[1].length > 0;
- } else if (/^\d{1,2}$/.test(term)) {
- hours = Number(term);
- minutes = 0;
- } else if (/^\d{3,4}$/.test(term)) {
- const padded = term.padStart(4, "0");
- hours = Number(padded.slice(0, 2));
- minutes = Number(padded.slice(2));
- hasMinutes = true;
- } else {
- return null;
- }
-
- if (!Number.isFinite(hours) || !Number.isFinite(minutes)) return null;
- if (hours > 14 || minutes > 59) return null;
-
- const signChar = sign || "+";
- const value = `${signChar}${hours}:${String(minutes).padStart(2, "0")}`;
- return { value, sign, hours, minutes, hasMinutes };
-}
-
function handleTzSearch() {
if (!ui.tzSearch) return;
const term = ui.tzSearch.value.trim().toLowerCase();
@@ -552,14 +501,14 @@ function handleTzSearch() {
if (!AVAILABLE_ZONES.length) {
if (ui.tzEmpty) {
ui.tzEmpty.textContent = t("tz.notSupported");
- ui.tzEmpty.classList.remove("hidden");
+ ui.tzEmpty.classList.remove(CSS_CLASSES.HIDDEN);
}
renderTzResults([]);
return;
}
- if (term.length < 2 && !offsetQuery) {
+ if (term.length < MIN_SEARCH_LENGTH && !offsetQuery) {
renderTzResults([]);
- if (ui.tzEmpty) ui.tzEmpty.classList.add("hidden");
+ if (ui.tzEmpty) ui.tzEmpty.classList.add(CSS_CLASSES.HIDDEN);
return;
}
const localZone = getLocalZone();
@@ -587,17 +536,17 @@ function handleTzSearch() {
renderTzResults(matches);
if (ui.tzEmpty) {
ui.tzEmpty.textContent = TZ_EMPTY_MESSAGE;
- ui.tzEmpty.classList.toggle("hidden", matches.length > 0);
+ ui.tzEmpty.classList.toggle(CSS_CLASSES.HIDDEN, matches.length > 0);
}
}
-function openTzModal() {
- if (!ensureEditable()) return;
- if (!ui.tzModal) return;
- if (ui.tzSearch) ui.tzSearch.value = "";
+function openTzModal() {
+ if (!ensureEditable()) return;
+ if (!ui.tzModal) return;
+ if (ui.tzSearch) ui.tzSearch.value = "";
if (ui.tzEmpty) {
ui.tzEmpty.textContent = TZ_EMPTY_MESSAGE;
- ui.tzEmpty.classList.add("hidden");
+ ui.tzEmpty.classList.add(CSS_CLASSES.HIDDEN);
}
renderTzResults([]);
handleTzSearch();
@@ -643,7 +592,7 @@ function initTimezones() {
const delay = (60 - now.getSeconds()) * 1000;
window.setTimeout(() => {
renderTimezones();
- timezoneTimer = window.setInterval(renderTimezones, 60000);
+ timezoneTimer = window.setInterval(renderTimezones, TIMEZONE_UPDATE_INTERVAL_MS);
}, delay);
}
@@ -652,14 +601,14 @@ async function persistStateToHash() {
if (!hasStoredData()) {
if (window.location.hash) clearHash();
updateUrlLength();
- if (ui.jsonModal && !ui.jsonModal.classList.contains("hidden")) {
+ if (ui.jsonModal && !ui.jsonModal.classList.contains(CSS_CLASSES.HIDDEN)) {
updateJsonModal();
}
return;
}
await writeStateToHash(state, password);
updateUrlLength();
- if (ui.jsonModal && !ui.jsonModal.classList.contains("hidden")) {
+ if (ui.jsonModal && !ui.jsonModal.classList.contains(CSS_CLASSES.HIDDEN)) {
updateJsonModal();
}
}
@@ -685,7 +634,7 @@ function updateUrlLength() {
const length = window.location.hash.length;
if (ui.urlLength) ui.urlLength.textContent = String(length);
if (ui.mobileUrlLength) ui.mobileUrlLength.textContent = String(length);
- const warning = length > 2000 ? t("panel.urlWarning") : "";
+ const warning = length > URL_LENGTH_WARNING_THRESHOLD ? t("panel.urlWarning") : "";
if (ui.urlWarning) ui.urlWarning.textContent = warning;
if (ui.mobileUrlWarning) ui.mobileUrlWarning.textContent = warning;
}
@@ -731,13 +680,13 @@ function updateViewButtons() {
if (!ui.viewButtons || !ui.viewButtons.length) return;
ui.viewButtons.forEach((button) => {
const isActive = button.dataset.view === currentView;
- button.classList.toggle("active", isActive);
+ button.classList.toggle(CSS_CLASSES.ACTIVE, isActive);
button.setAttribute("aria-selected", isActive ? "true" : "false");
});
if (ui.mobileDrawerViewButtons && ui.mobileDrawerViewButtons.length) {
ui.mobileDrawerViewButtons.forEach((button) => {
const isActive = button.dataset.view === currentView;
- button.classList.toggle("active", isActive);
+ button.classList.toggle(CSS_CLASSES.ACTIVE, isActive);
button.setAttribute("aria-selected", isActive ? "true" : "false");
});
}
@@ -749,19 +698,19 @@ function setView(view) {
const grid = ui.calendarGrid;
if (grid) {
- grid.classList.add("view-animate-out");
+ grid.classList.add(CSS_CLASSES.VIEW_ANIMATE_OUT);
grid.addEventListener("animationend", function handleExit() {
- grid.classList.remove("view-animate-out");
+ grid.classList.remove(CSS_CLASSES.VIEW_ANIMATE_OUT);
grid.removeEventListener("animationend", handleExit);
-
+
currentView = view;
if (state && state.s) state.s.v = view;
updateViewButtons();
render();
-
- grid.classList.add("view-animate-in");
+
+ grid.classList.add(CSS_CLASSES.VIEW_ANIMATE_IN);
grid.addEventListener("animationend", function handleEnter() {
- grid.classList.remove("view-animate-in");
+ grid.classList.remove(CSS_CLASSES.VIEW_ANIMATE_IN);
grid.removeEventListener("animationend", handleEnter);
}, { once: true });
@@ -776,74 +725,74 @@ function setView(view) {
}
}
-function updateLockUI() {
- const isLocked = isCalendarLocked();
- const isReadOnly = isReadOnlyMode();
- const editDisabled = isLocked || isReadOnly;
-
- if (ui.lockBtn) {
- if (lockState.encrypted) {
- ui.lockBtn.textContent = t(isLocked ? "btn.unlock" : "btn.removeLock");
- } else {
- ui.lockBtn.textContent = t("btn.lock");
- }
- }
-
- if (ui.readOnlyBtn) {
- ui.readOnlyBtn.textContent = t(isReadOnly ? "btn.editMode" : "btn.readOnly");
- ui.readOnlyBtn.setAttribute("aria-pressed", isReadOnly ? "true" : "false");
- ui.readOnlyBtn.classList.toggle("is-active-toggle", isReadOnly);
- ui.readOnlyBtn.disabled = isLocked;
- }
-
- if (ui.mobileReadOnlyBtn) {
- const span = ui.mobileReadOnlyBtn.querySelector("span");
- if (span) {
- span.textContent = t(isReadOnly ? "btn.editMode" : "btn.readOnly");
- }
- ui.mobileReadOnlyBtn.setAttribute("aria-pressed", isReadOnly ? "true" : "false");
- ui.mobileReadOnlyBtn.classList.toggle("is-active-toggle", isReadOnly);
- ui.mobileReadOnlyBtn.disabled = isLocked;
- }
-
- if (ui.lockedOverlay) {
- ui.lockedOverlay.classList.toggle("hidden", !isLocked);
- }
-
- if (ui.titleInput) {
- ui.titleInput.readOnly = editDisabled;
- }
-
- [ui.addEventBtn, ui.addEventInline, ui.mobileAddEventInline, ui.mobileAddEvent, ui.importIcs, ui.mobileImportIcs, ui.clearAll, ui.mobileClearAll, ui.tzAddBtn, ui.mobileAddTzBtn].forEach((btn) => {
- if (btn) btn.disabled = editDisabled;
- });
-
- [ui.copyLinkBtn, ui.shareQrBtn, ui.mobileCopyLink, ui.mobileShareQr].forEach((btn) => {
- if (btn) btn.disabled = isLocked;
- });
-
- // Mobile lock/unlock button visibility
- if (ui.mobileLockBtn && ui.mobileUnlockBtn) {
+function updateLockUI() {
+ const isLocked = isCalendarLocked();
+ const isReadOnly = isReadOnlyMode();
+ const editDisabled = isLocked || isReadOnly;
+
+ if (ui.lockBtn) {
+ if (lockState.encrypted) {
+ ui.lockBtn.textContent = t(isLocked ? "btn.unlock" : "btn.removeLock");
+ } else {
+ ui.lockBtn.textContent = t("btn.lock");
+ }
+ }
+
+ if (ui.readOnlyBtn) {
+ ui.readOnlyBtn.textContent = t(isReadOnly ? "btn.editMode" : "btn.readOnly");
+ ui.readOnlyBtn.setAttribute("aria-pressed", isReadOnly ? "true" : "false");
+ ui.readOnlyBtn.classList.toggle(CSS_CLASSES.IS_ACTIVE_TOGGLE, isReadOnly);
+ ui.readOnlyBtn.disabled = isLocked;
+ }
+
+ if (ui.mobileReadOnlyBtn) {
+ const span = ui.mobileReadOnlyBtn.querySelector("span");
+ if (span) {
+ span.textContent = t(isReadOnly ? "btn.editMode" : "btn.readOnly");
+ }
+ ui.mobileReadOnlyBtn.setAttribute("aria-pressed", isReadOnly ? "true" : "false");
+ ui.mobileReadOnlyBtn.classList.toggle(CSS_CLASSES.IS_ACTIVE_TOGGLE, isReadOnly);
+ ui.mobileReadOnlyBtn.disabled = isLocked;
+ }
+
+ if (ui.lockedOverlay) {
+ ui.lockedOverlay.classList.toggle(CSS_CLASSES.HIDDEN, !isLocked);
+ }
+
+ if (ui.titleInput) {
+ ui.titleInput.readOnly = editDisabled;
+ }
+
+ [ui.addEventBtn, ui.addEventInline, ui.mobileAddEventInline, ui.mobileAddEvent, ui.importIcs, ui.mobileImportIcs, ui.clearAll, ui.mobileClearAll, ui.tzAddBtn, ui.mobileAddTzBtn].forEach((btn) => {
+ if (btn) btn.disabled = editDisabled;
+ });
+
+ [ui.copyLinkBtn, ui.shareQrBtn, ui.mobileCopyLink, ui.mobileShareQr].forEach((btn) => {
+ if (btn) btn.disabled = isLocked;
+ });
+
+ // Mobile lock/unlock button visibility
+ if (ui.mobileLockBtn && ui.mobileUnlockBtn) {
if (lockState.encrypted && lockState.unlocked) {
// Show unlock (remove-lock) button, hide lock
- ui.mobileLockBtn.classList.add("hidden");
- ui.mobileUnlockBtn.classList.remove("hidden");
+ ui.mobileLockBtn.classList.add(CSS_CLASSES.HIDDEN);
+ ui.mobileUnlockBtn.classList.remove(CSS_CLASSES.HIDDEN);
} else {
// Show lock button, hide unlock
- ui.mobileLockBtn.classList.remove("hidden");
- ui.mobileUnlockBtn.classList.add("hidden");
+ ui.mobileLockBtn.classList.remove(CSS_CLASSES.HIDDEN);
+ ui.mobileUnlockBtn.classList.add(CSS_CLASSES.HIDDEN);
}
- }
-
-}
-
-function handleReadOnlyToggle() {
- if (!state || !state.s || isCalendarLocked()) return;
- state.s.r = state.s.r ? 0 : 1;
- updateLockUI();
- scheduleSave();
- showToast(t(state.s.r ? "toast.readOnlyEnabled" : "toast.editModeEnabled"), "success");
-}
+ }
+
+}
+
+function handleReadOnlyToggle() {
+ if (!state || !state.s || isCalendarLocked()) return;
+ state.s.r = state.s.r ? 0 : 1;
+ updateLockUI();
+ scheduleSave();
+ showToast(t(state.s.r ? "toast.readOnlyEnabled" : "toast.editModeEnabled"), "success");
+}
function applyLanguageSelection(langCode) {
if (!SUPPORTED_LANGUAGES.some((lang) => lang.code === langCode)) return;
@@ -908,10 +857,10 @@ function initLanguageDropdown() {
}
document.addEventListener("click", (e) => {
- if (ui.langDropdown && !ui.langDropdown.classList.contains("hidden") && !ui.langDropdown.contains(e.target)) {
+ if (ui.langDropdown && !ui.langDropdown.classList.contains(CSS_CLASSES.HIDDEN) && !ui.langDropdown.contains(e.target)) {
closeLanguageDropdown(ui.langDropdown, ui.langBtn);
}
- if (ui.mobileLangDropdown && !ui.mobileLangDropdown.classList.contains("hidden") && !ui.mobileLangDropdown.contains(e.target)) {
+ if (ui.mobileLangDropdown && !ui.mobileLangDropdown.classList.contains(CSS_CLASSES.HIDDEN) && !ui.mobileLangDropdown.contains(e.target)) {
closeLanguageDropdown(ui.mobileLangDropdown, ui.mobileLangBtn);
}
});
@@ -919,13 +868,13 @@ function initLanguageDropdown() {
function toggleLanguageDropdown(dropdown, trigger) {
if (!dropdown || !trigger) return;
- const isHidden = dropdown.classList.contains("hidden");
+ const isHidden = dropdown.classList.contains(CSS_CLASSES.HIDDEN);
if (isHidden) {
// Close other dropdowns first
closeLanguageDropdown(ui.langDropdown, ui.langBtn);
closeLanguageDropdown(ui.mobileLangDropdown, ui.mobileLangBtn);
- dropdown.classList.remove("hidden");
+ dropdown.classList.remove(CSS_CLASSES.HIDDEN);
trigger.setAttribute("aria-expanded", "true");
} else {
closeLanguageDropdown(dropdown, trigger);
@@ -935,7 +884,7 @@ function toggleLanguageDropdown(dropdown, trigger) {
function closeLanguageDropdown(dropdown, trigger) {
const d = dropdown || ui.langDropdown;
const t = trigger || ui.langBtn;
- if (d) d.classList.add("hidden");
+ if (d) d.classList.add(CSS_CLASSES.HIDDEN);
if (t) t.setAttribute("aria-expanded", "false");
}
@@ -953,18 +902,18 @@ function updateLanguageUI() {
if (ui.langList) {
ui.langList.querySelectorAll(".dropdown-item").forEach((item) => {
- item.classList.toggle("active", item.dataset.lang === langCode);
+ item.classList.toggle(CSS_CLASSES.ACTIVE, item.dataset.lang === langCode);
});
}
if (ui.mobileLangList) {
ui.mobileLangList.querySelectorAll(".dropdown-item").forEach((item) => {
- item.classList.toggle("active", item.dataset.lang === langCode);
+ item.classList.toggle(CSS_CLASSES.ACTIVE, item.dataset.lang === langCode);
});
}
ui.langList.querySelectorAll(".dropdown-item").forEach((item) => {
- item.classList.toggle("active", item.dataset.lang === langCode);
+ item.classList.toggle(CSS_CLASSES.ACTIVE, item.dataset.lang === langCode);
});
// Re-translate components
@@ -1015,7 +964,7 @@ function render() {
ui.calendarGrid.style.gridTemplateRows = "";
}
if (ui.weekdayRow) {
- ui.weekdayRow.classList.toggle("hidden", currentView === "year" || currentView === "agenda");
+ ui.weekdayRow.classList.toggle(CSS_CLASSES.HIDDEN, currentView === "year" || currentView === "agenda");
}
if (currentView === "month") {
@@ -1117,7 +1066,7 @@ function render() {
renderEventList();
renderTimezones();
updateUrlLength();
- if (ui.jsonModal && !ui.jsonModal.classList.contains("hidden")) {
+ if (ui.jsonModal && !ui.jsonModal.classList.contains(CSS_CLASSES.HIDDEN)) {
updateJsonModal();
}
updateLockUI();
@@ -1183,10 +1132,10 @@ function handleSelectDay(date) {
if (currentView === "month") {
if (ui.calendarGrid) {
const previous = ui.calendarGrid.querySelector(".day-cell.is-selected");
- if (previous) previous.classList.remove("is-selected");
+ if (previous) previous.classList.remove(CSS_CLASSES.IS_SELECTED);
const key = formatDateKey(selectedDate);
const next = ui.calendarGrid.querySelector(`.day-cell[data-date="${key}"]`);
- if (next) next.classList.add("is-selected");
+ if (next) next.classList.add(CSS_CLASSES.IS_SELECTED);
}
renderEventList();
return;
@@ -1196,13 +1145,13 @@ function handleSelectDay(date) {
render();
}
-function openEventModal({ index = null, date = null } = {}) {
- if (!ensureEditable()) return;
- if (!ui.eventModal) return;
- editingIndex = index;
+function openEventModal({ index = null, date = null } = {}) {
+ if (!ensureEditable()) return;
+ if (!ui.eventModal) return;
+ editingIndex = index;
const isEditing = typeof index === "number";
ui.eventModalTitle.textContent = t(isEditing ? "modal.editEvent" : "modal.addEvent");
- ui.eventDelete.classList.toggle("hidden", !isEditing);
+ ui.eventDelete.classList.toggle(CSS_CLASSES.HIDDEN, !isEditing);
const baseDate = date || selectedDate;
const now = new Date();
@@ -1213,7 +1162,7 @@ function openEventModal({ index = null, date = null } = {}) {
now.getHours(),
now.getMinutes(),
);
- let duration = 60;
+ let duration = DEFAULT_EVENT_DURATION;
let title = "";
let color = state.c[0] || DEFAULT_COLORS[0];
let rule = "";
@@ -1223,7 +1172,7 @@ function openEventModal({ index = null, date = null } = {}) {
const entry = state.e[index];
if (entry) {
const [startMin, storedDuration, storedTitle, colorIndex, storedRule] = entry;
- startDate = new Date(startMin * 60000);
+ startDate = new Date(startMin * MS_PER_MINUTE);
duration = storedDuration || 0;
title = storedTitle || "";
color = state.c[colorIndex] || color;
@@ -1235,18 +1184,18 @@ function openEventModal({ index = null, date = null } = {}) {
ui.eventTitle.value = title;
ui.eventDate.value = formatDateKey(startDate);
ui.eventTime.value = startDate.toTimeString().slice(0, 5);
- ui.eventDuration.value = String(isAllDay ? 0 : duration || 60);
+ ui.eventDuration.value = String(isAllDay ? 0 : duration || DEFAULT_EVENT_DURATION);
ui.eventRecurrence.value = rule;
ui.eventColor.value = color;
ui.eventAllDay.checked = isAllDay;
toggleAllDay(isAllDay);
renderColorPalette(color);
- ui.eventModal.classList.remove("hidden");
+ ui.eventModal.classList.remove(CSS_CLASSES.HIDDEN);
}
function closeEventModal() {
- if (ui.eventModal) ui.eventModal.classList.add("hidden");
+ if (ui.eventModal) ui.eventModal.classList.add(CSS_CLASSES.HIDDEN);
}
function toggleAllDay(allDay) {
@@ -1256,7 +1205,7 @@ function toggleAllDay(allDay) {
if (allDay) {
ui.eventDuration.value = "0";
} else if (Number(ui.eventDuration.value) === 0) {
- ui.eventDuration.value = "60";
+ ui.eventDuration.value = String(DEFAULT_EVENT_DURATION);
}
}
@@ -1279,10 +1228,10 @@ function renderColorPalette(activeColor) {
});
}
-function saveEvent(event) {
- if (!ensureEditable()) return;
- event.preventDefault();
- if (!ui.eventTitle || !ui.eventDate) return;
+function saveEvent(event) {
+ if (!ensureEditable()) return;
+ event.preventDefault();
+ if (!ui.eventTitle || !ui.eventDate) return;
const title = ui.eventTitle.value.trim() || "Untitled";
const dateValue = ui.eventDate.value;
if (!dateValue) return;
@@ -1300,8 +1249,8 @@ function saveEvent(event) {
startDate = new Date(year, month - 1, day, hours, minutes);
}
- const startMin = Math.floor(startDate.getTime() / 60000);
- const duration = allDay ? 0 : Math.max(0, Number(ui.eventDuration.value) || 60);
+ const startMin = Math.floor(startDate.getTime() / MS_PER_MINUTE);
+ const duration = allDay ? 0 : Math.max(0, Number(ui.eventDuration.value) || DEFAULT_EVENT_DURATION);
const colorValue = ui.eventColor.value.toLowerCase();
let colorIndex = state.c.findIndex((color) => color.toLowerCase() === colorValue);
if (colorIndex === -1) {
@@ -1324,10 +1273,10 @@ function saveEvent(event) {
render();
}
-function deleteEvent() {
- if (!ensureEditable()) return;
- if (typeof editingIndex !== "number") return;
- const confirmed = window.confirm(t("confirm.deleteEvent"));
+function deleteEvent() {
+ if (!ensureEditable()) return;
+ if (typeof editingIndex !== "number") return;
+ const confirmed = window.confirm(t("confirm.deleteEvent"));
if (!confirmed) return;
state.e.splice(editingIndex, 1);
editingIndex = null;
@@ -1343,16 +1292,16 @@ function openPasswordModal({ mode, title, description, submitLabel }) {
ui.passwordDesc.textContent = description;
ui.passwordInput.value = "";
ui.passwordConfirm.value = "";
- ui.passwordError.classList.add("hidden");
+ ui.passwordError.classList.add(CSS_CLASSES.HIDDEN);
if (mode === "set") {
- ui.passwordConfirmField.classList.remove("hidden");
+ ui.passwordConfirmField.classList.remove(CSS_CLASSES.HIDDEN);
} else {
- ui.passwordConfirmField.classList.add("hidden");
+ ui.passwordConfirmField.classList.add(CSS_CLASSES.HIDDEN);
}
ui.passwordSubmit.textContent = submitLabel;
- ui.passwordModal.classList.remove("hidden");
+ ui.passwordModal.classList.remove(CSS_CLASSES.HIDDEN);
return new Promise((resolve) => {
passwordResolver = resolve;
@@ -1360,7 +1309,7 @@ function openPasswordModal({ mode, title, description, submitLabel }) {
}
function closePasswordModal() {
- if (ui.passwordModal) ui.passwordModal.classList.add("hidden");
+ if (ui.passwordModal) ui.passwordModal.classList.add(CSS_CLASSES.HIDDEN);
if (passwordResolver) {
passwordResolver(null);
passwordResolver = null;
@@ -1372,19 +1321,19 @@ function submitPassword() {
const value = ui.passwordInput.value.trim();
if (!value) {
ui.passwordError.textContent = t("password.required");
- ui.passwordError.classList.remove("hidden");
+ 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("hidden");
+ ui.passwordError.classList.remove(CSS_CLASSES.HIDDEN);
return;
}
}
- ui.passwordModal.classList.add("hidden");
+ ui.passwordModal.classList.add(CSS_CLASSES.HIDDEN);
passwordResolver(value);
passwordResolver = null;
}
@@ -1474,15 +1423,15 @@ function handleHashChange() {
loadStateFromHash().then(render);
}
-function handleTitleInput() {
- if (!ui.titleInput) return;
- if (!ensureEditable({ silent: true })) {
- ui.titleInput.value = state.t;
- return;
- }
- state.t = ui.titleInput.value.slice(0, MAX_TITLE_LENGTH);
- scheduleSave();
-}
+function handleTitleInput() {
+ if (!ui.titleInput) return;
+ if (!ensureEditable({ silent: true })) {
+ ui.titleInput.value = state.t;
+ return;
+ }
+ state.t = ui.titleInput.value.slice(0, MAX_TITLE_LENGTH);
+ scheduleSave();
+}
function handleThemeToggle() {
state.s.d = state.s.d ? 0 : 1;
@@ -1590,12 +1539,12 @@ function updateJsonModal() {
function openJsonModal() {
if (!ui.jsonModal) return;
updateJsonModal();
- ui.jsonModal.classList.remove("hidden");
+ ui.jsonModal.classList.remove(CSS_CLASSES.HIDDEN);
}
function closeJsonModal() {
if (!ui.jsonModal) return;
- ui.jsonModal.classList.add("hidden");
+ ui.jsonModal.classList.add(CSS_CLASSES.HIDDEN);
}
async function handleCopyJson() {
@@ -1628,15 +1577,15 @@ function handleExportJson() {
URL.revokeObjectURL(url);
}
-function handleImportIcsClick() {
- if (!ensureEditable()) return;
- if (ui.icsInput) ui.icsInput.click();
-}
-
-function handleIcsFile(event) {
- if (!ensureEditable()) return;
- const file = event.target.files && event.target.files[0];
- if (!file) return;
+function handleImportIcsClick() {
+ if (!ensureEditable()) return;
+ if (ui.icsInput) ui.icsInput.click();
+}
+
+function handleIcsFile(event) {
+ if (!ensureEditable()) return;
+ const file = event.target.files && event.target.files[0];
+ if (!file) return;
const reader = new FileReader();
reader.onload = () => {
const text = String(reader.result || "");
@@ -1649,10 +1598,10 @@ function handleIcsFile(event) {
imported.forEach((entry, idx) => {
const start = entry.start;
if (!start) return;
- const startMin = Math.floor(start.getTime() / 60000);
+ const startMin = Math.floor(start.getTime() / MS_PER_MINUTE);
let duration = 0;
if (entry.end) {
- duration = Math.max(0, Math.round((entry.end.getTime() - start.getTime()) / 60000));
+ duration = Math.max(0, Math.round((entry.end.getTime() - start.getTime()) / MS_PER_MINUTE));
}
if (entry.isAllDay) duration = 0;
const colorIndex = idx % colorCount;
@@ -1668,11 +1617,11 @@ function handleIcsFile(event) {
event.target.value = "";
}
-function handleClearAll() {
- if (!ensureEditable()) return;
- const confirmed = window.confirm(t("confirm.clearAll"));
- if (!confirmed) return;
- state.e = [];
+function handleClearAll() {
+ if (!ensureEditable()) return;
+ const confirmed = window.confirm(t("confirm.clearAll"));
+ if (!confirmed) return;
+ state.e = [];
scheduleSave();
render();
}
@@ -1689,11 +1638,11 @@ function bindEvents() {
}
if (ui.addEventBtn) ui.addEventBtn.addEventListener("click", () => openEventModal({ date: selectedDate }));
if (ui.addEventInline) ui.addEventInline.addEventListener("click", () => openEventModal({ date: selectedDate }));
- 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.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();
@@ -1734,16 +1683,16 @@ function bindEvents() {
}
function openMobileDrawer() {
- if (ui.mobileDrawer) ui.mobileDrawer.classList.add("is-active");
- if (ui.mobileDrawerBackdrop) ui.mobileDrawerBackdrop.classList.add("is-active");
+ if (ui.mobileDrawer) ui.mobileDrawer.classList.add(CSS_CLASSES.IS_ACTIVE);
+ if (ui.mobileDrawerBackdrop) ui.mobileDrawerBackdrop.classList.add(CSS_CLASSES.IS_ACTIVE);
document.body.style.overflow = "hidden";
const icon = ui.hamburgerBtn && ui.hamburgerBtn.querySelector("i");
if (icon) { icon.classList.remove("fa-bars"); icon.classList.add("fa-xmark"); }
}
function closeMobileDrawer() {
- if (ui.mobileDrawer) ui.mobileDrawer.classList.remove("is-active");
- if (ui.mobileDrawerBackdrop) ui.mobileDrawerBackdrop.classList.remove("is-active");
+ if (ui.mobileDrawer) ui.mobileDrawer.classList.remove(CSS_CLASSES.IS_ACTIVE);
+ if (ui.mobileDrawerBackdrop) ui.mobileDrawerBackdrop.classList.remove(CSS_CLASSES.IS_ACTIVE);
document.body.style.overflow = "";
const icon = ui.hamburgerBtn && ui.hamburgerBtn.querySelector("i");
if (icon) { icon.classList.add("fa-bars"); icon.classList.remove("fa-xmark"); }
@@ -1754,7 +1703,7 @@ function initResponsiveFeatures() {
if (ui.hamburgerBtn) {
ui.hamburgerBtn.addEventListener("click", (e) => {
e.stopPropagation();
- if (ui.mobileDrawer && ui.mobileDrawer.classList.contains("is-active")) {
+ if (ui.mobileDrawer && ui.mobileDrawer.classList.contains(CSS_CLASSES.IS_ACTIVE)) {
closeMobileDrawer();
} else {
openMobileDrawer();
@@ -1824,36 +1773,36 @@ function initResponsiveFeatures() {
if (ui.mobileWeekstartToggle) {
ui.mobileWeekstartToggle.addEventListener("click", handleWeekStartToggle);
}
- if (ui.mobileThemeToggle) {
- ui.mobileThemeToggle.addEventListener("click", handleThemeToggle);
- }
- if (ui.mobileReadOnlyBtn) {
- ui.mobileReadOnlyBtn.addEventListener("click", () => {
- handleReadOnlyToggle();
- closeMobileDrawer();
- });
- }
+ if (ui.mobileThemeToggle) {
+ ui.mobileThemeToggle.addEventListener("click", handleThemeToggle);
+ }
+ if (ui.mobileReadOnlyBtn) {
+ ui.mobileReadOnlyBtn.addEventListener("click", () => {
+ handleReadOnlyToggle();
+ closeMobileDrawer();
+ });
+ }
// Drawer world planner button
if (ui.mobileWorldPlannerBtn) {
ui.mobileWorldPlannerBtn.addEventListener("click", () => {
closeMobileDrawer();
- if (ui.worldPlannerBtn) ui.worldPlannerBtn.click();
+ worldPlanner.open();
});
}
// Existing mobile sidebar toggle logic (unchanged)
if (ui.mobileSidebarToggle) {
ui.mobileSidebarToggle.addEventListener("click", () => {
- if (ui.sidePanel.classList.contains("is-active")) {
- ui.sidePanel.classList.remove("is-active");
- ui.tzSidebar.classList.add("is-active");
+ if (ui.sidePanel.classList.contains(CSS_CLASSES.IS_ACTIVE)) {
+ ui.sidePanel.classList.remove(CSS_CLASSES.IS_ACTIVE);
+ ui.tzSidebar.classList.add(CSS_CLASSES.IS_ACTIVE);
ui.mobileSidebarToggle.querySelector("span").textContent = t("label.clock");
- } else if (ui.tzSidebar.classList.contains("is-active")) {
- ui.tzSidebar.classList.remove("is-active");
+ } else if (ui.tzSidebar.classList.contains(CSS_CLASSES.IS_ACTIVE)) {
+ ui.tzSidebar.classList.remove(CSS_CLASSES.IS_ACTIVE);
ui.mobileSidebarToggle.querySelector("span").textContent = t("label.details");
} else {
- ui.sidePanel.classList.add("is-active");
+ ui.sidePanel.classList.add(CSS_CLASSES.IS_ACTIVE);
ui.mobileSidebarToggle.querySelector("span").textContent = t("label.events");
}
});
@@ -1861,14 +1810,14 @@ function initResponsiveFeatures() {
if (ui.sidePanelClose) {
ui.sidePanelClose.addEventListener("click", () => {
- ui.sidePanel.classList.remove("is-active");
+ ui.sidePanel.classList.remove(CSS_CLASSES.IS_ACTIVE);
if (ui.mobileSidebarToggle) ui.mobileSidebarToggle.querySelector("span").textContent = t("label.details");
});
}
if (ui.tzSidebarClose) {
ui.tzSidebarClose.addEventListener("click", () => {
- ui.tzSidebar.classList.remove("is-active");
+ ui.tzSidebar.classList.remove(CSS_CLASSES.IS_ACTIVE);
if (ui.mobileSidebarToggle) ui.mobileSidebarToggle.querySelector("span").textContent = t("label.details");
});
}
@@ -1887,6 +1836,16 @@ async function init() {
fallbackColors: DEFAULT_COLORS,
onToggle: updateFocusButton,
});
+ worldPlanner = new WorldPlanner({
+ getState: () => state,
+ updateState: (key, value) => {
+ state[key] = value;
+ },
+ ensureEditable,
+ scheduleSave,
+ showToast,
+ closeMobileDrawer,
+ });
bindEvents();
initResponsiveFeatures();
await loadStateFromHash();
@@ -1898,7 +1857,9 @@ async function init() {
updateFocusButton(false);
render();
initTimezones();
- initWorldPlanner();
+ if (ui.worldPlannerBtn) {
+ ui.worldPlannerBtn.addEventListener("click", () => worldPlanner.open());
+ }
new AppLauncher();
if (isEncryptedHash() && !lockState.unlocked) {
@@ -1931,434 +1892,4 @@ if ('serviceWorker' in navigator) {
});
}
-/* --- 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("input", handleWpTzInput);
- ui.wpAddZone.addEventListener("keydown", (e) => {
- // Focus navigation for results? For now simple
- });
- }
-
- if (!ui.wpFormatToggle) {
- ui.wpFormatToggle = document.getElementById("wp-format-toggle");
- if (ui.wpFormatToggle) ui.wpFormatToggle.addEventListener("click", togglePlannerFormat);
- }
-
- 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 (!ensureEditable()) {
- e.target.value = (state.mp && state.mp.d) || new Date().toISOString().split("T")[0];
- return;
- }
- if (!state.mp) state.mp = { h: null, z: [], s: null, d: null, f24: false };
- state.mp.d = e.target.value;
- scheduleSave();
- renderWorldPlanner();
- });
- }
- // Copy Link removed from UI
-}
-
-function openWorldPlanner() {
- if (!ui.worldPlannerModal) return;
- const canEdit = ensureEditable({ silent: true });
-
- // Initialize state if empty
- if ((!state.mp || (!state.mp.h && !state.mp.z.length)) && canEdit) {
- 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],
- f24: false // Default to 12h
- };
- }
-
- // Ensure f24 exists for legacy states
- if (state.mp.f24 === undefined && canEdit) state.mp.f24 = false;
-
- // Set date picker
- if (ui.wpDatePicker) {
- ui.wpDatePicker.value = state.mp.d || new Date().toISOString().split("T")[0];
- }
-
- updatePlannerFormatBtn();
-
- ui.worldPlannerModal.classList.remove("hidden");
- renderWorldPlanner();
-}
-
-function closeWorldPlanner() {
- if (ui.worldPlannerModal) {
- ui.worldPlannerModal.classList.add("hidden");
- }
- if (ensureEditable({ silent: true })) {
- scheduleSave();
- }
-}
-
-function handleWpTzInput(e) {
- const term = e.target.value.trim().toLowerCase();
- const list = document.getElementById("wp-tz-results");
- if (!list) return;
-
- if (term.length < 2) {
- list.innerHTML = "";
- list.classList.add("hidden");
- return;
- }
-
- const offsetQuery = parseOffsetSearchTerm(term); // Reuse existing helper
- const existing = new Set([state.mp.h, ...state.mp.z]);
-
- const matches = AVAILABLE_ZONES.filter((zone) => {
- if (existing.has(zone)) return false;
- const zoneLower = zone.toLowerCase();
- if (zoneLower.includes(term)) return true;
-
- // Offset match reuse
- if (offsetQuery) {
- const zoneOffset = getZoneInfo(zone).offset;
- const normalized = `${offsetQuery.hours}:${String(offsetQuery.minutes).padStart(2, "0")}`;
- if (offsetQuery.hasMinutes) {
- if (offsetQuery.sign) return zoneOffset === `${offsetQuery.sign}${normalized}`;
- return zoneOffset === `+${normalized}` || zoneOffset === `-${normalized}`;
- }
- if (offsetQuery.sign) return zoneOffset.startsWith(`${offsetQuery.sign}${offsetQuery.hours}`);
- return zoneOffset.startsWith(`+${offsetQuery.hours}`) || zoneOffset.startsWith(`-${offsetQuery.hours}`);
- }
- return false;
- }).slice(0, 12);
-
- renderWpTzResults(matches);
-}
-
-function renderWpTzResults(results) {
- const list = document.getElementById("wp-tz-results");
- if (!list) return;
- list.innerHTML = "";
-
- if (!results.length) {
- list.classList.add("hidden");
- return;
- }
-
- results.forEach(zone => {
- const li = document.createElement("li");
- const button = document.createElement("button");
- button.type = "button";
- button.className = "tz-result-btn"; // Reuse existing style class
-
- const info = getZoneInfo(zone);
- const name = document.createElement("span");
- name.className = "tz-result-name";
- name.textContent = zone;
-
- const offset = document.createElement("span");
- offset.className = "tz-result-offset";
- offset.textContent = `UTC${info.offset}`;
-
- button.append(name, offset);
-
- button.addEventListener("click", () => {
- addPlannerZone(zone);
- list.classList.add("hidden");
- if (ui.wpAddZone) ui.wpAddZone.value = "";
- });
-
- li.appendChild(button);
- list.appendChild(li);
- });
-
- list.classList.remove("hidden");
-}
-
-function addPlannerZone(zone) {
- if (!ensureEditable()) return;
- if (state.mp.h !== zone && !state.mp.z.includes(zone)) {
- state.mp.z.push(zone);
- scheduleSave();
- renderWorldPlanner();
- }
-}
-
-function handlePlannerGridClick(e) {
- if (!ensureEditable()) return;
- // 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();
-
- 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) {
- 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="Make Home"><i class="fa-solid fa-arrow-up"></i></button>
- <button class="wp-control-btn" data-action="remove" data-zone="${zone}" title="Remove"><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";
-
- const homeZone = state.mp.h;
- if (!homeZone) return row;
-
- const homeInfo = getZoneInfo(homeZone);
- const targetInfo = getZoneInfo(zone);
-
- 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);
- const tOff = parseOff(targetInfo.offset);
- const diffMins = tOff - hOff;
-
- const is24h = !!state.mp.f24;
-
- for (let h = 0; h < 24; h++) {
- const cell = document.createElement("div");
-
- let targetMins = (h * 60) + diffMins;
- 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;
-
- let cls = "wp-cell";
- if (tHour >= 8 && tHour <= 17) cls += " business";
- else if (tHour >= 18 && tHour <= 22) cls += " active";
- else cls += " sleep";
-
- if (tHour === 0 && tMin === 0) {
- cls += " date-boundary";
- }
-
- cell.className = cls;
- cell.dataset.h = h;
-
- if (tHour === 0 && tMin === 0) {
- const d = new Date(baseDate);
- d.setDate(d.getDate() + dayShift);
- cell.textContent = d.toLocaleDateString('en-US', { day: 'numeric', month: 'short' }).toUpperCase();
- } else {
- if (is24h) {
- cell.textContent = tMin > 0 ? `${tHour}:${String(tMin).padStart(2,'0')}` : `${tHour}`;
- } else {
- const ampm = tHour >= 12 ? "pm" : "am";
- const h12 = tHour % 12 || 12;
- if (tMin > 0) {
- cell.textContent = `${h12}:${String(tMin).padStart(2,'0')}`;
- } else {
- // Only show am/pm for home zone or first occurrence
- cell.textContent = isHome ? `${h12} ${ampm}` : `${h12}`;
- }
- }
- }
- 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;
-
- const cell = e.target.closest(".wp-cell");
- if (!cell) {
- ghost.classList.add("hidden");
- return;
- }
-
- ghost.style.left = `${cell.offsetLeft}px`;
- ghost.classList.remove("hidden");
-}
-
-function handleScrubberClick(e) {
- if (!ensureEditable()) return;
- const cell = e.target.closest(".wp-cell");
- if (!cell) return;
-
- const hIndex = Number(cell.dataset.h);
- const baseDate = getPlannerDate();
- 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 || !state.mp.s) {
- if (scrubber) scrubber.classList.add("hidden");
- return;
- }
-
- const baseDate = getPlannerDate();
- const diff = state.mp.s - baseDate.getTime();
- const hIndex = Math.floor(diff / (3600 * 1000));
-
- if (hIndex >= 0 && hIndex < 24) {
- const cell = ui.wpGrid.querySelector(`.wp-cell[data-h="${hIndex}"]`);
- if (cell) {
- scrubber.style.left = `${cell.offsetLeft}px`;
- scrubber.classList.remove("hidden");
- }
- } else {
- scrubber.classList.add("hidden");
- }
-}
-
-function togglePlannerFormat() {
- if (!ensureEditable()) return;
- if (!state.mp) return;
- state.mp.f24 = !state.mp.f24;
- updatePlannerFormatBtn();
- scheduleSave();
- renderWorldPlanner();
-}
-
-function updatePlannerFormatBtn() {
- const btn = document.getElementById("wp-format-toggle");
- if (btn) {
- btn.textContent = state.mp && state.mp.f24 ? "24h" : "12h";
- }
-}