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

Add files via upload

Supun Lakmal Abesekarae5f80d7d3471
diff --git a/Caddyfile b/Caddyfile
new file mode 100644
index 0000000..685b213
--- /dev/null
+++ b/Caddyfile
@@ -0,0 +1,30 @@
+:80 {
+ # Serve all files from the current directory
+ file_server {
+ hide .git .gitignore .dockerignore Dockerfile docker-compose.yaml Caddyfile task.md
+ }
+
+ # Compress responses
+ encode gzip
+
+ # Set appropriate cache headers
+ @static {
+ path *.css *.js *.json *.png *.jpg *.jpeg *.gif *.svg *.ico *.woff *.woff2 *.ttf *.eot
+ }
+ header @static Cache-Control "public, max-age=31536000, immutable"
+
+ # Dynamic content (HTML) - don't cache
+ @html {
+ path_regexp ^.*\.html?$
+ }
+ header @html Cache-Control "public, max-age=0, must-revalidate"
+
+ # SPA support - rewrite all requests to index.html for hash-based routing
+ try_files {path} /index.html
+
+ # Log requests
+ log {
+ output stdout
+ format console
+ }
+}
diff --git a/Dockerfile b/Dockerfile
new file mode 100644
index 0000000..7e603b3
--- /dev/null
+++ b/Dockerfile
@@ -0,0 +1,31 @@
+# Multi-stage build for lightweight production image
+FROM node:18-alpine AS base
+
+WORKDIR /app
+
+# Copy only the necessary files for serving
+COPY index.html gallery.html styles.css gallery.css script.js templates.json ./
+COPY modules/ ./modules/
+COPY demo/ ./demo/
+COPY favicon.png logo.png ./
+
+# Use a lightweight web server to serve static files
+FROM caddy:2-alpine
+
+WORKDIR /srv
+
+# Copy the static files from the base stage
+COPY --from=base /app /srv
+
+# Copy a simple Caddyfile for serving
+COPY Caddyfile /etc/caddy/Caddyfile
+
+# Expose port 80 and 443 (for HTTPS support if needed)
+EXPOSE 80 443
+
+# Health check
+HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \
+ CMD wget --no-verbose --tries=1 --spider http://localhost/ || exit 1
+
+# Caddy will automatically start with the Caddyfile
+CMD ["caddy", "run", "--config", "/etc/caddy/Caddyfile"]
diff --git a/LICENSE b/LICENSE
new file mode 100644
index 0000000..f51b3de
--- /dev/null
+++ b/LICENSE
@@ -0,0 +1,21 @@
+MIT License
+
+Copyright (c) 2026 Supun Lakmal Abesekara
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/README.md b/README.md
new file mode 100644
index 0000000..cdc6451
--- /dev/null
+++ b/README.md
@@ -0,0 +1,52 @@
+# HashCal
+
+HashCal is a lightweight, client-only calendar. Your calendar state lives entirely in the URL hash, so sharing is as simple as copying the link. No backend, no accounts.
+
+## Features
+
+- URL-based storage with LZ-String compression
+- Day, week, month, and year views
+- Create, edit, and delete events
+- All-day events and duration-based events
+- Recurring events (daily, weekly, monthly, yearly)
+- Copy-link sharing
+- Export calendar to JSON
+- Import events from .ics files
+- Optional password lock (AES-GCM + PBKDF2)
+- Theme toggle (light/dark)
+- Week start toggle (Sunday/Monday)
+
+## How it works
+
+- The calendar state is serialized to JSON and compressed into the URL hash.
+- If a password is set, the compressed payload is encrypted using AES-GCM.
+- No data leaves the browser unless you share the link.
+
+Encrypted links start with `#ENC:`. Clearing the hash resets the calendar.
+
+## Getting started
+
+Open `index.html` in your browser.
+
+For clipboard and file import features, run a local server:
+
+```bash
+npx serve .
+```
+
+## Project structure
+
+- `index.html` - UI markup
+- `styles.css` - Styles
+- `script.js` - App logic
+- `modules/`
+ - `calendarRender.js` - Calendar rendering
+ - `recurrenceEngine.js` - Recurring event expansion
+ - `icsImporter.js` - .ics parsing
+ - `hashcalUrlManager.js` - URL read/write + compression
+ - `cryptoManager.js` - Encryption helpers
+ - `lz-string.min.js` - Compression library
+
+## License
+
+MIT. See `LICENSE`.
diff --git a/apple-touch-icon.png b/apple-touch-icon.png
new file mode 100644
index 0000000..7c5747d
Binary files /dev/null and b/apple-touch-icon.png differ
diff --git a/docker-compose.yaml b/docker-compose.yaml
new file mode 100644
index 0000000..c365418
--- /dev/null
+++ b/docker-compose.yaml
@@ -0,0 +1,28 @@
+services:
+ spreadsheet:
+ build:
+ context: .
+ dockerfile: Dockerfile
+ container_name: spreadsheet-app
+ ports:
+ - "${HOST_PORT_HTTP:-80}:80"
+ - "${HOST_PORT_HTTPS:-443}:443"
+ environment:
+ # Add any environment variables here if needed
+ TZ: UTC
+ restart: unless-stopped
+ healthcheck:
+ test: ["CMD", "wget", "--no-verbose", "--tries=1", "--spider", "http://localhost/"]
+ interval: 30s
+ timeout: 3s
+ retries: 3
+ start_period: 5s
+ # Optional: Mount local directory for development
+ #volumes:
+ # - ./:/srv:ro # Read-only mount for live development
+ networks:
+ - spreadsheet-network
+
+networks:
+ spreadsheet-network:
+ driver: bridge
diff --git a/favicon.ico b/favicon.ico
new file mode 100644
index 0000000..cceede8
Binary files /dev/null and b/favicon.ico differ
diff --git a/favicon.png b/favicon.png
new file mode 100644
index 0000000..441e737
Binary files /dev/null and b/favicon.png differ
diff --git a/index.html b/index.html
new file mode 100644
index 0000000..a034840
--- /dev/null
+++ b/index.html
@@ -0,0 +1,183 @@
+<!DOCTYPE html>
+<html lang="en">
+<head>
+ <meta charset="UTF-8">
+ <meta name="viewport" content="width=device-width, initial-scale=1">
+ <title>HashCal</title>
+ <link rel="icon" href="favicon.ico" type="image/x-icon">
+ <link rel="icon" href="favicon.png" type="image/png" sizes="32x32">
+ <link rel="apple-touch-icon" href="apple-touch-icon.png" sizes="180x180">
+ <link rel="preconnect" href="https://fonts.googleapis.com">
+ <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
+ <link href="https://fonts.googleapis.com/css2?family=Fraunces:wght@400;600;700&family=Space+Grotesk:wght@400;500;600&display=swap" rel="stylesheet">
+ <link rel="stylesheet" href="styles.css">
+</head>
+<body>
+ <div class="app">
+ <header class="topbar">
+ <div class="brand">
+ <div class="brand-mark">#</div>
+ <div class="brand-text">
+ <input id="calendar-title" class="title-input" type="text" maxlength="60" value="HashCal" aria-label="Calendar title">
+ <span class="brand-subtitle">Serverless privacy calendar. Your URL is the save file.</span>
+ </div>
+ </div>
+ <div class="top-actions">
+ <div class="nav-group">
+ <button id="prev-month" type="button" aria-label="Previous month">Prev</button>
+ <button id="today-btn" type="button">Today</button>
+ <button id="next-month" type="button" aria-label="Next month">Next</button>
+ </div>
+ <div class="view-toggle" role="tablist" aria-label="Calendar view">
+ <button type="button" data-view="day" role="tab" aria-selected="false">Day</button>
+ <button type="button" data-view="week" role="tab" aria-selected="false">Week</button>
+ <button type="button" data-view="month" role="tab" aria-selected="true">Month</button>
+ <button type="button" data-view="year" role="tab" aria-selected="false">Year</button>
+ </div>
+ <button id="add-event" type="button" class="primary">Add event</button>
+ <button id="copy-link" type="button">Copy link</button>
+ <button id="lock-btn" type="button">Lock</button>
+ </div>
+ </header>
+
+ <main class="layout">
+ <section class="calendar-panel">
+ <div class="panel-header">
+ <div>
+ <h2 id="month-label" class="month-label">Month 2026</h2>
+ <div class="panel-actions">
+ <button id="weekstart-toggle" type="button" class="ghost">Week starts Sunday</button>
+ <button id="theme-toggle" type="button" class="ghost">Theme: Light</button>
+ </div>
+ </div>
+ </div>
+ <div id="weekday-row" class="weekday-row"></div>
+ <div id="calendar-grid" class="calendar-grid" role="grid" aria-label="Calendar"></div>
+ <div id="locked-overlay" class="locked-overlay hidden">
+ <div class="locked-card">
+ <h3>Encrypted calendar</h3>
+ <p>Enter the password to unlock and edit this calendar.</p>
+ <button id="unlock-btn" type="button" class="primary">Unlock</button>
+ </div>
+ </div>
+ </section>
+
+ <aside class="side-panel">
+ <div class="side-card">
+ <h3 id="selected-date-label" class="side-title">Selected day</h3>
+ <div id="event-list" class="event-list"></div>
+ <button id="add-event-inline" type="button" class="ghost">Add event for this day</button>
+ </div>
+
+ <div class="side-card">
+ <h4 class="side-title">Share and export</h4>
+ <div class="status-row">
+ <span>URL length</span>
+ <strong id="url-length">0</strong>
+ </div>
+ <p id="url-warning" class="url-warning"></p>
+ <div class="stacked-actions">
+ <button id="export-json" type="button" class="ghost">Export JSON</button>
+ <button id="import-ics" type="button" class="ghost">Import .ics</button>
+ <input id="ics-input" type="file" accept=".ics,text/calendar" hidden>
+ </div>
+ </div>
+
+ <div class="side-card danger">
+ <h4 class="side-title">Danger zone</h4>
+ <button id="clear-all" type="button" class="danger-btn">Clear calendar</button>
+ </div>
+ </aside>
+ </main>
+ </div>
+
+ <div id="event-modal" class="modal hidden" role="dialog" aria-modal="true" aria-labelledby="event-modal-title">
+ <div class="modal-backdrop"></div>
+ <div class="modal-card">
+ <header class="modal-header">
+ <h3 id="event-modal-title">Add event</h3>
+ <button id="event-close" type="button" class="icon-btn" aria-label="Close">x</button>
+ </header>
+ <form id="event-form" class="modal-form">
+ <label class="field">
+ <span>Title</span>
+ <input id="event-title" type="text" maxlength="80" required>
+ </label>
+ <div class="field-row">
+ <label class="field">
+ <span>Date</span>
+ <input id="event-date" type="date" required>
+ </label>
+ <label class="field">
+ <span>Start</span>
+ <input id="event-time" type="time">
+ </label>
+ </div>
+ <div class="field-row">
+ <label class="field">
+ <span>Duration (mins)</span>
+ <input id="event-duration" type="number" min="0" step="5" value="60">
+ </label>
+ <label class="field checkbox-field">
+ <input id="event-all-day" type="checkbox">
+ <span>All day</span>
+ </label>
+ </div>
+ <label class="field">
+ <span>Recurrence</span>
+ <select id="event-recurrence">
+ <option value="">None</option>
+ <option value="d">Daily</option>
+ <option value="w">Weekly</option>
+ <option value="m">Monthly</option>
+ <option value="y">Yearly</option>
+ </select>
+ </label>
+ <label class="field">
+ <span>Color</span>
+ <input id="event-color" type="color" value="#ff6b6b">
+ </label>
+ <div id="color-palette" class="color-palette"></div>
+ <div class="modal-actions">
+ <button id="event-delete" type="button" class="ghost danger hidden">Delete</button>
+ <div class="modal-actions-right">
+ <button id="event-cancel" type="button" class="ghost">Cancel</button>
+ <button id="event-save" type="submit" class="primary">Save</button>
+ </div>
+ </div>
+ </form>
+ </div>
+ </div>
+
+ <div id="password-modal" class="modal hidden" role="dialog" aria-modal="true" aria-labelledby="password-title">
+ <div class="modal-backdrop"></div>
+ <div class="modal-card">
+ <header class="modal-header">
+ <h3 id="password-title">Unlock calendar</h3>
+ <button id="password-close" type="button" class="icon-btn" aria-label="Close">x</button>
+ </header>
+ <div class="modal-form">
+ <p id="password-desc" class="modal-note"></p>
+ <label class="field">
+ <span>Password</span>
+ <input id="password-input" type="password" autocomplete="new-password">
+ </label>
+ <label id="password-confirm-field" class="field hidden">
+ <span>Confirm password</span>
+ <input id="password-confirm" type="password" autocomplete="new-password">
+ </label>
+ <p id="password-error" class="modal-error hidden"></p>
+ <div class="modal-actions">
+ <button id="password-cancel" type="button" class="ghost">Cancel</button>
+ <button id="password-submit" type="button" class="primary">Unlock</button>
+ </div>
+ </div>
+ </div>
+ </div>
+
+ <div id="toast-container" class="toast-container" aria-live="polite" aria-atomic="true"></div>
+
+ <script src="modules/lz-string.min.js"></script>
+ <script type="module" src="script.js"></script>
+</body>
+</html>
diff --git a/logo.png b/logo.png
new file mode 100644
index 0000000..cd4cc89
Binary files /dev/null and b/logo.png differ
diff --git a/modules/calendarRender.js b/modules/calendarRender.js
new file mode 100644
index 0000000..0508bf1
--- /dev/null
+++ b/modules/calendarRender.js
@@ -0,0 +1,292 @@
+function pad(num) {
+ return String(num).padStart(2, "0");
+}
+
+export function formatDateKey(date) {
+ return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}`;
+}
+
+export function getMonthGridRange(viewDate, weekStartsOnMonday) {
+ const year = viewDate.getFullYear();
+ const month = viewDate.getMonth();
+ const firstOfMonth = new Date(year, month, 1);
+ const dayOfWeek = firstOfMonth.getDay();
+ const offset = weekStartsOnMonday ? (dayOfWeek + 6) % 7 : dayOfWeek;
+ const gridStart = new Date(year, month, 1 - offset);
+
+ const dates = [];
+ for (let i = 0; i < 42; i += 1) {
+ const date = new Date(gridStart.getFullYear(), gridStart.getMonth(), gridStart.getDate() + i);
+ dates.push(date);
+ }
+ const gridEnd = new Date(gridStart.getFullYear(), gridStart.getMonth(), gridStart.getDate() + 41, 23, 59, 59);
+ return { start: gridStart, end: gridEnd, dates };
+}
+
+export function getWeekRange(viewDate, weekStartsOnMonday) {
+ const anchor = new Date(viewDate.getFullYear(), viewDate.getMonth(), viewDate.getDate());
+ const dayOfWeek = anchor.getDay();
+ const offset = weekStartsOnMonday ? (dayOfWeek + 6) % 7 : dayOfWeek;
+ const start = new Date(anchor.getFullYear(), anchor.getMonth(), anchor.getDate() - offset);
+ const dates = [];
+ for (let i = 0; i < 7; i += 1) {
+ dates.push(new Date(start.getFullYear(), start.getMonth(), start.getDate() + i));
+ }
+ const end = new Date(start.getFullYear(), start.getMonth(), start.getDate() + 6, 23, 59, 59);
+ return { start, end, dates };
+}
+
+function formatWeekdayLabel(date) {
+ return date.toLocaleDateString(undefined, { weekday: "short" });
+}
+
+export function renderWeekdayHeaders(container, weekStartsOnMonday, mode = "month", dates = []) {
+ let labels = [];
+ if (mode === "day" && dates[0]) {
+ labels = [
+ dates[0].toLocaleDateString(undefined, {
+ weekday: "long",
+ month: "short",
+ day: "numeric",
+ }),
+ ];
+ } else if (mode === "week" && dates.length) {
+ labels = dates.map((date) => `${formatWeekdayLabel(date)} ${date.getDate()}`);
+ } else {
+ labels = weekStartsOnMonday
+ ? ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
+ : ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
+ }
+
+ container.innerHTML = "";
+ container.style.gridTemplateColumns = `repeat(${labels.length}, minmax(0, 1fr))`;
+ labels.forEach((label) => {
+ const cell = document.createElement("div");
+ cell.className = "weekday";
+ cell.textContent = label;
+ container.appendChild(cell);
+ });
+}
+
+export function renderCalendar({
+ container,
+ dates,
+ currentMonth,
+ selectedDate,
+ eventsByDay,
+ onSelectDay,
+ onEventClick,
+}) {
+ container.innerHTML = "";
+ const today = new Date();
+ const todayKey = formatDateKey(today);
+ const selectedKey = selectedDate ? formatDateKey(selectedDate) : null;
+
+ dates.forEach((date) => {
+ const key = formatDateKey(date);
+ const dayCell = document.createElement("div");
+ dayCell.className = "day-cell";
+ dayCell.setAttribute("role", "gridcell");
+ if (date.getMonth() !== currentMonth) dayCell.classList.add("is-outside");
+ if (key === todayKey) dayCell.classList.add("is-today");
+ if (selectedKey && key === selectedKey) dayCell.classList.add("is-selected");
+ dayCell.dataset.date = key;
+
+ const dayNumber = document.createElement("div");
+ dayNumber.className = "day-number";
+ dayNumber.textContent = String(date.getDate());
+ dayCell.appendChild(dayNumber);
+
+ const events = eventsByDay.get(key) || [];
+ const maxEvents = 3;
+ events.slice(0, maxEvents).forEach((event) => {
+ const chip = document.createElement("button");
+ chip.type = "button";
+ chip.className = "event-chip";
+ chip.style.background = event.color;
+ chip.style.borderColor = event.color;
+
+ const time = document.createElement("span");
+ time.className = "time";
+ time.textContent = event.isAllDay ? "All day" : event.timeLabel;
+ const title = document.createElement("span");
+ title.textContent = event.title;
+
+ chip.appendChild(time);
+ chip.appendChild(title);
+ chip.addEventListener("click", (e) => {
+ e.stopPropagation();
+ onEventClick(event);
+ });
+ dayCell.appendChild(chip);
+ });
+
+ if (events.length > maxEvents) {
+ const more = document.createElement("div");
+ more.className = "event-more";
+ more.textContent = `+${events.length - maxEvents} more`;
+ dayCell.appendChild(more);
+ }
+
+ dayCell.addEventListener("click", () => onSelectDay(date));
+ container.appendChild(dayCell);
+ });
+}
+
+function formatHourLabel(hour) {
+ const suffix = hour < 12 ? "AM" : "PM";
+ const display = hour % 12 || 12;
+ return `${display} ${suffix}`;
+}
+
+export function renderTimeGrid({ container, dates, occurrences, onSelectDay, onEventClick }) {
+ const dayKeys = dates.map((date) => formatDateKey(date));
+ const buckets = new Map();
+ dayKeys.forEach((key) => {
+ buckets.set(key, { allDay: [], hours: new Map() });
+ });
+
+ occurrences.forEach((occ) => {
+ const key = formatDateKey(new Date(occ.start));
+ const bucket = buckets.get(key);
+ if (!bucket) return;
+ if (occ.isAllDay) {
+ bucket.allDay.push(occ);
+ return;
+ }
+ const hour = new Date(occ.start).getHours();
+ if (!bucket.hours.has(hour)) bucket.hours.set(hour, []);
+ bucket.hours.get(hour).push(occ);
+ });
+
+ buckets.forEach((bucket) => {
+ bucket.allDay.sort((a, b) => a.start - b.start);
+ bucket.hours.forEach((list) => list.sort((a, b) => a.start - b.start));
+ });
+
+ container.innerHTML = "";
+ container.style.gridTemplateColumns = `72px repeat(${dates.length}, minmax(0, 1fr))`;
+ container.style.gridTemplateRows = `32px repeat(24, minmax(44px, 1fr))`;
+
+ const allDayLabel = document.createElement("div");
+ allDayLabel.className = "time-label all-day-label";
+ allDayLabel.textContent = "All day";
+ container.appendChild(allDayLabel);
+
+ dates.forEach((date) => {
+ const key = formatDateKey(date);
+ const cell = document.createElement("div");
+ cell.className = "time-cell all-day";
+ cell.dataset.date = key;
+ const bucket = buckets.get(key);
+ const events = bucket ? bucket.allDay : [];
+ events.slice(0, 2).forEach((event) => {
+ const chip = document.createElement("button");
+ chip.type = "button";
+ chip.className = "time-event";
+ chip.style.background = event.color;
+ chip.textContent = event.title;
+ chip.addEventListener("click", (e) => {
+ e.stopPropagation();
+ onEventClick(event);
+ });
+ cell.appendChild(chip);
+ });
+ if (events.length > 2) {
+ const more = document.createElement("div");
+ more.className = "event-more";
+ more.textContent = `+${events.length - 2} more`;
+ cell.appendChild(more);
+ }
+ cell.addEventListener("click", () => onSelectDay(date));
+ container.appendChild(cell);
+ });
+
+ for (let hour = 0; hour < 24; hour += 1) {
+ const label = document.createElement("div");
+ label.className = "time-label";
+ label.textContent = formatHourLabel(hour);
+ container.appendChild(label);
+
+ dates.forEach((date) => {
+ const key = formatDateKey(date);
+ const cell = document.createElement("div");
+ cell.className = "time-cell";
+ cell.dataset.date = key;
+ cell.dataset.hour = String(hour);
+ const bucket = buckets.get(key);
+ const events = bucket && bucket.hours.get(hour) ? bucket.hours.get(hour) : [];
+ events.slice(0, 3).forEach((event) => {
+ const chip = document.createElement("button");
+ chip.type = "button";
+ chip.className = "time-event";
+ chip.style.background = event.color;
+ chip.textContent = event.title;
+ chip.addEventListener("click", (e) => {
+ e.stopPropagation();
+ onEventClick(event);
+ });
+ cell.appendChild(chip);
+ });
+ if (events.length > 3) {
+ const more = document.createElement("div");
+ more.className = "event-more";
+ more.textContent = `+${events.length - 3} more`;
+ cell.appendChild(more);
+ }
+ cell.addEventListener("click", () => onSelectDay(date));
+ container.appendChild(cell);
+ });
+ }
+}
+
+export function renderYearView({ container, year, eventsByDay, selectedDate, weekStartsOnMonday, onSelectDay }) {
+ container.innerHTML = "";
+ container.style.gridTemplateColumns = "repeat(auto-fit, minmax(220px, 1fr))";
+ container.style.gridTemplateRows = "auto";
+
+ const labels = weekStartsOnMonday
+ ? ["M", "T", "W", "T", "F", "S", "S"]
+ : ["S", "M", "T", "W", "T", "F", "S"];
+
+ for (let month = 0; month < 12; month += 1) {
+ const wrapper = document.createElement("div");
+ wrapper.className = "mini-month";
+
+ const header = document.createElement("div");
+ header.className = "mini-title";
+ header.textContent = new Date(year, month, 1).toLocaleDateString(undefined, { month: "long" });
+ wrapper.appendChild(header);
+
+ const grid = document.createElement("div");
+ grid.className = "mini-grid";
+
+ labels.forEach((label) => {
+ const cell = document.createElement("div");
+ cell.className = "mini-weekday";
+ cell.textContent = label;
+ grid.appendChild(cell);
+ });
+
+ const { dates } = getMonthGridRange(new Date(year, month, 1), weekStartsOnMonday);
+ dates.forEach((date) => {
+ const key = formatDateKey(date);
+ const dayCell = document.createElement("button");
+ dayCell.type = "button";
+ dayCell.className = "mini-day";
+ if (date.getMonth() !== month) dayCell.classList.add("is-outside");
+ if (selectedDate && key === formatDateKey(selectedDate)) dayCell.classList.add("is-selected");
+ dayCell.textContent = String(date.getDate());
+ if (eventsByDay.has(key)) {
+ const dot = document.createElement("span");
+ dot.className = "mini-dot";
+ dayCell.appendChild(dot);
+ }
+ dayCell.addEventListener("click", () => onSelectDay(date));
+ grid.appendChild(dayCell);
+ });
+
+ wrapper.appendChild(grid);
+ container.appendChild(wrapper);
+ }
+}
diff --git a/modules/cryptoManager.js b/modules/cryptoManager.js
new file mode 100644
index 0000000..f8f34fc
--- /dev/null
+++ b/modules/cryptoManager.js
@@ -0,0 +1,72 @@
+const textEncoder = new TextEncoder();
+const textDecoder = new TextDecoder();
+
+function toBase64Url(bytes) {
+ let binary = "";
+ bytes.forEach((byte) => {
+ binary += String.fromCharCode(byte);
+ });
+ return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/g, "");
+}
+
+function fromBase64Url(value) {
+ const normalized = value.replace(/-/g, "+").replace(/_/g, "/");
+ const padded = normalized + "===".slice((normalized.length + 3) % 4);
+ const binary = atob(padded);
+ const bytes = new Uint8Array(binary.length);
+ for (let i = 0; i < binary.length; i += 1) {
+ bytes[i] = binary.charCodeAt(i);
+ }
+ return bytes;
+}
+
+async function deriveKey(password, salt) {
+ const keyMaterial = await crypto.subtle.importKey("raw", textEncoder.encode(password), "PBKDF2", false, [
+ "deriveKey",
+ ]);
+ return crypto.subtle.deriveKey(
+ {
+ name: "PBKDF2",
+ salt,
+ iterations: 150000,
+ hash: "SHA-256",
+ },
+ keyMaterial,
+ { name: "AES-GCM", length: 256 },
+ false,
+ ["encrypt", "decrypt"]
+ );
+}
+
+export async function encryptString(plaintext, password) {
+ const salt = crypto.getRandomValues(new Uint8Array(16));
+ const iv = crypto.getRandomValues(new Uint8Array(12));
+ const key = await deriveKey(password, salt);
+ const encrypted = await crypto.subtle.encrypt(
+ { name: "AES-GCM", iv },
+ key,
+ textEncoder.encode(plaintext)
+ );
+
+ const cipherBytes = new Uint8Array(encrypted);
+ return `${toBase64Url(salt)}.${toBase64Url(iv)}.${toBase64Url(cipherBytes)}`;
+}
+
+export async function decryptString(payload, password) {
+ const parts = payload.split(".");
+ if (parts.length !== 3) {
+ throw new Error("Invalid payload");
+ }
+ const [saltPart, ivPart, cipherPart] = parts;
+ const salt = fromBase64Url(saltPart);
+ const iv = fromBase64Url(ivPart);
+ const cipherBytes = fromBase64Url(cipherPart);
+
+ const key = await deriveKey(password, salt);
+ const decrypted = await crypto.subtle.decrypt(
+ { name: "AES-GCM", iv },
+ key,
+ cipherBytes
+ );
+ return textDecoder.decode(decrypted);
+}
diff --git a/modules/hashcalUrlManager.js b/modules/hashcalUrlManager.js
new file mode 100644
index 0000000..e7d4bf4
--- /dev/null
+++ b/modules/hashcalUrlManager.js
@@ -0,0 +1,59 @@
+import { decryptString, encryptString } from "./cryptoManager.js";
+
+const HASH_PREFIX = "ENC:";
+
+function ensureLzString() {
+ if (!window.LZString) {
+ throw new Error("LZString missing");
+ }
+ return window.LZString;
+}
+
+export function isEncryptedHash(hash = window.location.hash) {
+ const raw = hash.startsWith("#") ? hash.slice(1) : hash;
+ return raw.startsWith(HASH_PREFIX);
+}
+
+export async function readStateFromHash(password = null) {
+ const raw = window.location.hash.startsWith("#") ? window.location.hash.slice(1) : window.location.hash;
+ if (!raw) return null;
+
+ const lz = ensureLzString();
+ if (raw.startsWith(HASH_PREFIX)) {
+ if (!password) {
+ const error = new Error("Password required");
+ error.code = "PASSWORD_REQUIRED";
+ throw error;
+ }
+ const payload = raw.slice(HASH_PREFIX.length);
+ const compressed = await decryptString(payload, password);
+ const json = lz.decompressFromEncodedURIComponent(compressed);
+ if (!json) throw new Error("Decompression failed");
+ return JSON.parse(json);
+ }
+
+ const json = lz.decompressFromEncodedURIComponent(raw);
+ if (!json) throw new Error("Decompression failed");
+ return JSON.parse(json);
+}
+
+export async function writeStateToHash(state, password = null) {
+ const lz = ensureLzString();
+ const json = JSON.stringify(state);
+ const compressed = lz.compressToEncodedURIComponent(json);
+ let nextHash = compressed;
+
+ if (password) {
+ const encrypted = await encryptString(compressed, password);
+ nextHash = `${HASH_PREFIX}${encrypted}`;
+ }
+
+ if (window.location.hash !== `#${nextHash}`) {
+ history.replaceState(null, "", `#${nextHash}`);
+ }
+ return nextHash;
+}
+
+export function clearHash() {
+ history.replaceState(null, "", window.location.pathname);
+}
diff --git a/modules/icsImporter.js b/modules/icsImporter.js
new file mode 100644
index 0000000..7a293b8
--- /dev/null
+++ b/modules/icsImporter.js
@@ -0,0 +1,121 @@
+function unfoldLines(text) {
+ const rawLines = text.replace(/\r\n/g, "\n").split("\n");
+ const lines = [];
+ rawLines.forEach((line) => {
+ if (!line) return;
+ if (line.startsWith(" ") || line.startsWith("\t")) {
+ if (lines.length > 0) {
+ lines[lines.length - 1] += line.slice(1);
+ }
+ } else {
+ lines.push(line.trim());
+ }
+ });
+ return lines;
+}
+
+function parseIcsDate(value) {
+ if (!value) return null;
+ const dateOnly = /^\d{8}$/.test(value);
+ const hasTime = value.includes("T");
+
+ if (dateOnly) {
+ const year = Number(value.slice(0, 4));
+ const month = Number(value.slice(4, 6)) - 1;
+ const day = Number(value.slice(6, 8));
+ return { date: new Date(year, month, day), isAllDay: true };
+ }
+
+ if (hasTime) {
+ const match = value.match(/^(\d{4})(\d{2})(\d{2})T(\d{2})(\d{2})(\d{2})?(Z)?$/);
+ if (!match) return { date: new Date(value), isAllDay: false };
+ const [, y, m, d, hh, mm, ss = "00", z] = match;
+ const year = Number(y);
+ const month = Number(m) - 1;
+ const day = Number(d);
+ const hour = Number(hh);
+ const minute = Number(mm);
+ const second = Number(ss);
+ if (z) {
+ return { date: new Date(Date.UTC(year, month, day, hour, minute, second)), isAllDay: false };
+ }
+ return { date: new Date(year, month, day, hour, minute, second), isAllDay: false };
+ }
+
+ return { date: new Date(value), isAllDay: false };
+}
+
+function parseRRule(value) {
+ if (!value) return "";
+ const parts = value.split(";");
+ const freqPart = parts.find((part) => part.startsWith("FREQ="));
+ if (!freqPart) return "";
+ const freq = freqPart.split("=")[1];
+ if (!freq) return "";
+ if (freq === "DAILY") return "d";
+ if (freq === "WEEKLY") return "w";
+ if (freq === "MONTHLY") return "m";
+ if (freq === "YEARLY") return "y";
+ return "";
+}
+
+export function parseIcs(text) {
+ const lines = unfoldLines(text);
+ const events = [];
+ let current = null;
+
+ lines.forEach((line) => {
+ if (line === "BEGIN:VEVENT") {
+ current = {
+ title: "Untitled",
+ start: null,
+ end: null,
+ rule: "",
+ isAllDay: false,
+ };
+ return;
+ }
+
+ if (line === "END:VEVENT") {
+ if (current && current.start) {
+ events.push(current);
+ }
+ current = null;
+ return;
+ }
+
+ if (!current) return;
+
+ if (line.startsWith("SUMMARY")) {
+ const [, value] = line.split(":");
+ if (value) current.title = value.trim();
+ return;
+ }
+
+ if (line.startsWith("DTSTART")) {
+ const [, value] = line.split(":");
+ const parsed = parseIcsDate(value ? value.trim() : "");
+ if (parsed) {
+ current.start = parsed.date;
+ current.isAllDay = parsed.isAllDay;
+ }
+ return;
+ }
+
+ if (line.startsWith("DTEND")) {
+ const [, value] = line.split(":");
+ const parsed = parseIcsDate(value ? value.trim() : "");
+ if (parsed) {
+ current.end = parsed.date;
+ }
+ return;
+ }
+
+ if (line.startsWith("RRULE")) {
+ const [, value] = line.split(":");
+ current.rule = parseRRule(value ? value.trim() : "");
+ }
+ });
+
+ return events;
+}
diff --git a/modules/lz-string.min.js b/modules/lz-string.min.js
new file mode 100644
index 0000000..f7c26ae
--- /dev/null
+++ b/modules/lz-string.min.js
@@ -0,0 +1 @@
+var LZString=function(){var r=String.fromCharCode,o="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",n="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+-$",e={};function t(r,o){if(!e[r]){e[r]={};for(var n=0;n<r.length;n++)e[r][r.charAt(n)]=n}return e[r][o]}var i={compressToBase64:function(r){if(null==r)return"";var n=i._compress(r,6,function(r){return o.charAt(r)});switch(n.length%4){default:case 0:return n;case 1:return n+"===";case 2:return n+"==";case 3:return n+"="}},decompressFromBase64:function(r){return null==r?"":""==r?null:i._decompress(r.length,32,function(n){return t(o,r.charAt(n))})},compressToUTF16:function(o){return null==o?"":i._compress(o,15,function(o){return r(o+32)})+" "},decompressFromUTF16:function(r){return null==r?"":""==r?null:i._decompress(r.length,16384,function(o){return r.charCodeAt(o)-32})},compressToUint8Array:function(r){for(var o=i.compress(r),n=new Uint8Array(2*o.length),e=0,t=o.length;e<t;e++){var s=o.charCodeAt(e);n[2*e]=s>>>8,n[2*e+1]=s%256}return n},decompressFromUint8Array:function(o){if(null==o)return i.decompress(o);for(var n=new Array(o.length/2),e=0,t=n.length;e<t;e++)n[e]=256*o[2*e]+o[2*e+1];var s=[];return n.forEach(function(o){s.push(r(o))}),i.decompress(s.join(""))},compressToEncodedURIComponent:function(r){return null==r?"":i._compress(r,6,function(r){return n.charAt(r)})},decompressFromEncodedURIComponent:function(r){return null==r?"":""==r?null:(r=r.replace(/ /g,"+"),i._decompress(r.length,32,function(o){return t(n,r.charAt(o))}))},compress:function(o){return i._compress(o,16,function(o){return r(o)})},_compress:function(r,o,n){if(null==r)return"";var e,t,i,s={},u={},a="",p="",c="",l=2,f=3,h=2,d=[],m=0,v=0;for(i=0;i<r.length;i+=1)if(a=r.charAt(i),Object.prototype.hasOwnProperty.call(s,a)||(s[a]=f++,u[a]=!0),p=c+a,Object.prototype.hasOwnProperty.call(s,p))c=p;else{if(Object.prototype.hasOwnProperty.call(u,c)){if(c.charCodeAt(0)<256){for(e=0;e<h;e++)m<<=1,v==o-1?(v=0,d.push(n(m)),m=0):v++;for(t=c.charCodeAt(0),e=0;e<8;e++)m=m<<1|1&t,v==o-1?(v=0,d.push(n(m)),m=0):v++,t>>=1}else{for(t=1,e=0;e<h;e++)m=m<<1|t,v==o-1?(v=0,d.push(n(m)),m=0):v++,t=0;for(t=c.charCodeAt(0),e=0;e<16;e++)m=m<<1|1&t,v==o-1?(v=0,d.push(n(m)),m=0):v++,t>>=1}0==--l&&(l=Math.pow(2,h),h++),delete u[c]}else for(t=s[c],e=0;e<h;e++)m=m<<1|1&t,v==o-1?(v=0,d.push(n(m)),m=0):v++,t>>=1;0==--l&&(l=Math.pow(2,h),h++),s[p]=f++,c=String(a)}if(""!==c){if(Object.prototype.hasOwnProperty.call(u,c)){if(c.charCodeAt(0)<256){for(e=0;e<h;e++)m<<=1,v==o-1?(v=0,d.push(n(m)),m=0):v++;for(t=c.charCodeAt(0),e=0;e<8;e++)m=m<<1|1&t,v==o-1?(v=0,d.push(n(m)),m=0):v++,t>>=1}else{for(t=1,e=0;e<h;e++)m=m<<1|t,v==o-1?(v=0,d.push(n(m)),m=0):v++,t=0;for(t=c.charCodeAt(0),e=0;e<16;e++)m=m<<1|1&t,v==o-1?(v=0,d.push(n(m)),m=0):v++,t>>=1}0==--l&&(l=Math.pow(2,h),h++),delete u[c]}else for(t=s[c],e=0;e<h;e++)m=m<<1|1&t,v==o-1?(v=0,d.push(n(m)),m=0):v++,t>>=1;0==--l&&(l=Math.pow(2,h),h++)}for(t=2,e=0;e<h;e++)m=m<<1|1&t,v==o-1?(v=0,d.push(n(m)),m=0):v++,t>>=1;for(;;){if(m<<=1,v==o-1){d.push(n(m));break}v++}return d.join("")},decompress:function(r){return null==r?"":""==r?null:i._decompress(r.length,32768,function(o){return r.charCodeAt(o)})},_decompress:function(o,n,e){var t,i,s,u,a,p,c,l=[],f=4,h=4,d=3,m="",v=[],g={val:e(0),position:n,index:1};for(t=0;t<3;t+=1)l[t]=t;for(s=0,a=Math.pow(2,2),p=1;p!=a;)u=g.val&g.position,g.position>>=1,0==g.position&&(g.position=n,g.val=e(g.index++)),s|=(u>0?1:0)*p,p<<=1;switch(s){case 0:for(s=0,a=Math.pow(2,8),p=1;p!=a;)u=g.val&g.position,g.position>>=1,0==g.position&&(g.position=n,g.val=e(g.index++)),s|=(u>0?1:0)*p,p<<=1;c=r(s);break;case 1:for(s=0,a=Math.pow(2,16),p=1;p!=a;)u=g.val&g.position,g.position>>=1,0==g.position&&(g.position=n,g.val=e(g.index++)),s|=(u>0?1:0)*p,p<<=1;c=r(s);break;case 2:return""}for(l[3]=c,i=c,v.push(c);;){if(g.index>o)return"";for(s=0,a=Math.pow(2,d),p=1;p!=a;)u=g.val&g.position,g.position>>=1,0==g.position&&(g.position=n,g.val=e(g.index++)),s|=(u>0?1:0)*p,p<<=1;switch(c=s){case 0:for(s=0,a=Math.pow(2,8),p=1;p!=a;)u=g.val&g.position,g.position>>=1,0==g.position&&(g.position=n,g.val=e(g.index++)),s|=(u>0?1:0)*p,p<<=1;l[h++]=r(s),c=h-1,f--;break;case 1:for(s=0,a=Math.pow(2,16),p=1;p!=a;)u=g.val&g.position,g.position>>=1,0==g.position&&(g.position=n,g.val=e(g.index++)),s|=(u>0?1:0)*p,p<<=1;l[h++]=r(s),c=h-1,f--;break;case 2:return v.join("")}if(0==f&&(f=Math.pow(2,d),d++),l[c])m=l[c];else{if(c!==h)return null;m=i+i.charAt(0)}v.push(m),l[h++]=i+m.charAt(0),i=m,0==--f&&(f=Math.pow(2,d),d++)}}};return i}();"function"==typeof define&&define.amd?define(function(){return LZString}):"undefined"!=typeof module&&null!=module?module.exports=LZString:"undefined"!=typeof angular&&null!=angular&&angular.module("LZString",[]).factory("LZString",function(){return LZString});
\ No newline at end of file
diff --git a/modules/recurrenceEngine.js b/modules/recurrenceEngine.js
new file mode 100644
index 0000000..95ead7d
--- /dev/null
+++ b/modules/recurrenceEngine.js
@@ -0,0 +1,123 @@
+const MINUTE = 60000;
+const DAY = 86400000;
+
+function addDays(date, days) {
+ const next = new Date(date.getTime());
+ next.setDate(next.getDate() + days);
+ return next;
+}
+
+function addMonths(date, months) {
+ const next = new Date(date.getTime());
+ const day = next.getDate();
+ next.setMonth(next.getMonth() + months);
+ if (next.getDate() < day) {
+ next.setDate(0);
+ }
+ return next;
+}
+
+function addYears(date, years) {
+ const next = new Date(date.getTime());
+ const month = next.getMonth();
+ next.setFullYear(next.getFullYear() + years);
+ if (next.getMonth() !== month) {
+ next.setDate(0);
+ }
+ return next;
+}
+
+function getFirstOccurrence(start, rangeStart, rule) {
+ let current = new Date(start.getTime());
+ if (current >= rangeStart) return current;
+
+ if (rule === "d" || rule === "w") {
+ const step = rule === "d" ? 1 : 7;
+ const diffDays = Math.floor((rangeStart.getTime() - current.getTime()) / DAY);
+ const jumps = Math.floor(diffDays / step);
+ current = addDays(current, jumps * step);
+ while (current < rangeStart) {
+ current = addDays(current, step);
+ }
+ return current;
+ }
+
+ if (rule === "m") {
+ while (current < rangeStart) {
+ current = addMonths(current, 1);
+ }
+ return current;
+ }
+
+ if (rule === "y") {
+ while (current < rangeStart) {
+ current = addYears(current, 1);
+ }
+ }
+
+ return current;
+}
+
+function advanceOccurrence(date, rule) {
+ if (rule === "d") return addDays(date, 1);
+ if (rule === "w") return addDays(date, 7);
+ if (rule === "m") return addMonths(date, 1);
+ if (rule === "y") return addYears(date, 1);
+ return addDays(date, 1);
+}
+
+export function expandEvents(events, rangeStart, rangeEnd) {
+ const occurrences = [];
+ const rangeStartMs = rangeStart.getTime();
+ const rangeEndMs = rangeEnd.getTime();
+
+ events.forEach((event, index) => {
+ if (!Array.isArray(event)) return;
+ const startMin = Number(event[0]);
+ if (!Number.isFinite(startMin)) return;
+ const duration = Number(event[1]) || 0;
+ const title = String(event[2] || "Untitled");
+ const colorIndex = Number(event[3]) || 0;
+ const rule = event[4] || "";
+
+ const startMs = startMin * MINUTE;
+ const durationMs = duration * MINUTE;
+ const isAllDay = duration === 0;
+
+ if (!rule) {
+ const endMs = isAllDay ? startMs : startMs + durationMs;
+ if (startMs <= rangeEndMs && endMs >= rangeStartMs) {
+ occurrences.push({
+ start: startMs,
+ end: endMs,
+ title,
+ colorIndex,
+ rule: "",
+ sourceIndex: index,
+ isAllDay,
+ });
+ }
+ return;
+ }
+
+ let current = getFirstOccurrence(new Date(startMs), rangeStart, rule);
+ while (current.getTime() <= rangeEndMs) {
+ const currentMs = current.getTime();
+ const endMs = isAllDay ? currentMs : currentMs + durationMs;
+ if (currentMs <= rangeEndMs && endMs >= rangeStartMs) {
+ occurrences.push({
+ start: currentMs,
+ end: endMs,
+ title,
+ colorIndex,
+ rule,
+ sourceIndex: index,
+ isAllDay,
+ });
+ }
+ current = advanceOccurrence(current, rule);
+ }
+ });
+
+ return occurrences;
+}
diff --git a/netlify.toml b/netlify.toml
new file mode 100644
index 0000000..04c96a5
--- /dev/null
+++ b/netlify.toml
@@ -0,0 +1,5 @@
+[build]
+ functions = "netlify/functions"
+
+[functions]
+ node_bundler = "esbuild"
diff --git a/robots.txt b/robots.txt
new file mode 100644
index 0000000..9cdc5f9
--- /dev/null
+++ b/robots.txt
@@ -0,0 +1,4 @@
+User-agent: *
+Allow: /
+Sitemap: https://spreadsheetlive.netlify.app/sitemap.xml
+Sitemap: https://spreadsheetlive.netlify.app/sitemap.txt
diff --git a/script.js b/script.js
new file mode 100644
index 0000000..8672823
--- /dev/null
+++ b/script.js
@@ -0,0 +1,869 @@
+import { readStateFromHash, writeStateToHash, isEncryptedHash } from "./modules/hashcalUrlManager.js";
+import { expandEvents } from "./modules/recurrenceEngine.js";
+import {
+ formatDateKey,
+ getMonthGridRange,
+ getWeekRange,
+ renderCalendar,
+ renderTimeGrid,
+ renderWeekdayHeaders,
+ renderYearView,
+} from "./modules/calendarRender.js";
+import { parseIcs } from "./modules/icsImporter.js";
+
+const DEFAULT_COLORS = ["#ff6b6b", "#ffd43b", "#4dabf7", "#63e6be", "#9775fa"];
+const DEFAULT_STATE = {
+ t: "HashCal",
+ c: DEFAULT_COLORS,
+ e: [],
+ s: {
+ d: 0,
+ m: 0,
+ },
+};
+
+const DEBOUNCE_MS = 500;
+const MAX_TITLE_LENGTH = 60;
+
+let state = cloneState(DEFAULT_STATE);
+let viewDate = startOfDay(new Date());
+let selectedDate = startOfDay(new Date());
+let currentView = "month";
+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";
+
+const ui = {};
+
+function cloneState(source) {
+ return JSON.parse(JSON.stringify(source));
+}
+
+function startOfDay(date) {
+ return new Date(date.getFullYear(), date.getMonth(), date.getDate());
+}
+
+function addDays(date, days) {
+ const next = new Date(date.getTime());
+ next.setDate(next.getDate() + days);
+ return next;
+}
+
+function formatMonthLabel(date) {
+ return date.toLocaleDateString(undefined, { month: "long", year: "numeric" });
+}
+
+function formatDateLabel(date) {
+ return date.toLocaleDateString(undefined, { weekday: "long", month: "long", day: "numeric" });
+}
+
+function formatRangeLabel(start, end) {
+ const sameYear = start.getFullYear() === end.getFullYear();
+ const sameMonth = sameYear && start.getMonth() === end.getMonth();
+ if (sameMonth) {
+ return `${start.toLocaleDateString(undefined, {
+ month: "long",
+ })} ${start.getDate()}–${end.getDate()}, ${start.getFullYear()}`;
+ }
+ if (sameYear) {
+ return `${start.toLocaleDateString(undefined, {
+ month: "short",
+ day: "numeric",
+ })} – ${end.toLocaleDateString(undefined, {
+ month: "short",
+ day: "numeric",
+ })}, ${start.getFullYear()}`;
+ }
+ return `${start.toLocaleDateString(undefined, {
+ month: "short",
+ day: "numeric",
+ year: "numeric",
+ })} – ${end.toLocaleDateString(undefined, {
+ month: "short",
+ day: "numeric",
+ year: "numeric",
+ })}`;
+}
+
+function formatTime(date) {
+ return date.toLocaleTimeString(undefined, { hour: "2-digit", minute: "2-digit" });
+}
+
+function normalizeState(raw) {
+ const next = cloneState(DEFAULT_STATE);
+ if (!raw || typeof raw !== "object") return next;
+
+ if (typeof raw.t === "string") {
+ next.t = raw.t.slice(0, MAX_TITLE_LENGTH);
+ }
+
+ 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));
+ if (!next.c.length) next.c = DEFAULT_COLORS.slice();
+ }
+
+ if (Array.isArray(raw.e)) {
+ next.e = raw.e
+ .filter((entry) => Array.isArray(entry) && entry.length >= 4)
+ .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 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];
+ if (rule) event.push(rule);
+ return event;
+ })
+ .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;
+ }
+
+ return next;
+}
+
+function cacheElements() {
+ ui.titleInput = document.getElementById("calendar-title");
+ ui.prevMonth = document.getElementById("prev-month");
+ 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.lockBtn = document.getElementById("lock-btn");
+ ui.viewButtons = Array.from(document.querySelectorAll(".view-toggle button"));
+ ui.weekstartToggle = document.getElementById("weekstart-toggle");
+ ui.themeToggle = document.getElementById("theme-toggle");
+ ui.monthLabel = document.getElementById("month-label");
+ ui.weekdayRow = document.getElementById("weekday-row");
+ ui.calendarGrid = document.getElementById("calendar-grid");
+ ui.selectedDateLabel = document.getElementById("selected-date-label");
+ ui.eventList = document.getElementById("event-list");
+ ui.addEventInline = document.getElementById("add-event-inline");
+ ui.urlLength = document.getElementById("url-length");
+ ui.urlWarning = document.getElementById("url-warning");
+ ui.exportJson = document.getElementById("export-json");
+ ui.importIcs = document.getElementById("import-ics");
+ ui.icsInput = document.getElementById("ics-input");
+ ui.clearAll = document.getElementById("clear-all");
+ ui.lockedOverlay = document.getElementById("locked-overlay");
+ ui.unlockBtn = document.getElementById("unlock-btn");
+
+ ui.eventModal = document.getElementById("event-modal");
+ ui.eventForm = document.getElementById("event-form");
+ ui.eventModalTitle = document.getElementById("event-modal-title");
+ ui.eventClose = document.getElementById("event-close");
+ ui.eventCancel = document.getElementById("event-cancel");
+ ui.eventDelete = document.getElementById("event-delete");
+ ui.eventTitle = document.getElementById("event-title");
+ ui.eventDate = document.getElementById("event-date");
+ ui.eventTime = document.getElementById("event-time");
+ ui.eventDuration = document.getElementById("event-duration");
+ ui.eventAllDay = document.getElementById("event-all-day");
+ ui.eventRecurrence = document.getElementById("event-recurrence");
+ ui.eventColor = document.getElementById("event-color");
+ ui.colorPalette = document.getElementById("color-palette");
+
+ ui.passwordModal = document.getElementById("password-modal");
+ ui.passwordTitle = document.getElementById("password-title");
+ ui.passwordDesc = document.getElementById("password-desc");
+ ui.passwordInput = document.getElementById("password-input");
+ ui.passwordConfirmField = document.getElementById("password-confirm-field");
+ ui.passwordConfirm = document.getElementById("password-confirm");
+ ui.passwordError = document.getElementById("password-error");
+ ui.passwordClose = document.getElementById("password-close");
+ ui.passwordCancel = document.getElementById("password-cancel");
+ ui.passwordSubmit = document.getElementById("password-submit");
+
+ ui.toastContainer = document.getElementById("toast-container");
+}
+
+function showToast(message, type = "info") {
+ if (!ui.toastContainer) return;
+ const toast = document.createElement("div");
+ toast.className = `toast ${type}`.trim();
+ toast.textContent = message;
+ ui.toastContainer.appendChild(toast);
+ setTimeout(() => {
+ toast.remove();
+ }, 3200);
+}
+
+function scheduleSave() {
+ if (lockState.encrypted && !lockState.unlocked) return;
+ if (saveTimer) window.clearTimeout(saveTimer);
+ saveTimer = window.setTimeout(async () => {
+ await writeStateToHash(state, password);
+ updateUrlLength();
+ }, DEBOUNCE_MS);
+}
+
+function updateUrlLength() {
+ const length = window.location.hash.length;
+ if (ui.urlLength) ui.urlLength.textContent = String(length);
+ if (!ui.urlWarning) return;
+ if (length > 2000) {
+ ui.urlWarning.textContent = "Warning: long URLs may get truncated when shared.";
+ } else {
+ ui.urlWarning.textContent = "";
+ }
+}
+
+function updateTheme() {
+ document.body.dataset.theme = state.s.d ? "dark" : "light";
+ if (ui.themeToggle) {
+ ui.themeToggle.textContent = `Theme: ${state.s.d ? "Dark" : "Light"}`;
+ }
+}
+
+function updateWeekStartLabel() {
+ if (!ui.weekstartToggle) return;
+ ui.weekstartToggle.textContent = state.s.m ? "Week starts Monday" : "Week starts Sunday";
+}
+
+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.setAttribute("aria-selected", isActive ? "true" : "false");
+ });
+}
+
+function setView(view) {
+ if (!view) return;
+ currentView = view;
+ updateViewButtons();
+ render();
+}
+
+function updateLockUI() {
+ const isLocked = lockState.encrypted && !lockState.unlocked;
+ if (ui.lockBtn) {
+ if (lockState.encrypted) {
+ ui.lockBtn.textContent = isLocked ? "Unlock" : "Remove lock";
+ } else {
+ ui.lockBtn.textContent = "Lock";
+ }
+ }
+ if (ui.lockedOverlay) {
+ ui.lockedOverlay.classList.toggle("hidden", !isLocked);
+ }
+ const disabled = isLocked;
+ [ui.addEventBtn, ui.addEventInline, ui.copyLinkBtn].forEach((btn) => {
+ if (btn) btn.disabled = disabled;
+ });
+}
+
+function groupOccurrences(occurrences) {
+ const map = new Map();
+ occurrences.forEach((occ) => {
+ const key = formatDateKey(new Date(occ.start));
+ if (!map.has(key)) map.set(key, []);
+ map.get(key).push(occ);
+ });
+
+ map.forEach((list) => {
+ list.sort((a, b) => a.start - b.start);
+ });
+ return map;
+}
+
+function decorateOccurrences(occurrences) {
+ return occurrences.map((occ) => {
+ const color = state.c[occ.colorIndex] || DEFAULT_COLORS[0];
+ const timeLabel = occ.isAllDay ? "All day" : formatTime(new Date(occ.start));
+ return { ...occ, color, timeLabel };
+ });
+}
+
+function render() {
+ updateTheme();
+ updateWeekStartLabel();
+ if (ui.titleInput && document.activeElement !== ui.titleInput) {
+ ui.titleInput.value = state.t;
+ }
+
+ const weekStartsOnMonday = state.s.m === 1;
+ if (ui.calendarGrid) {
+ ui.calendarGrid.className = `calendar-grid ${currentView}-view`;
+ ui.calendarGrid.style.gridTemplateColumns = "";
+ ui.calendarGrid.style.gridTemplateRows = "";
+ }
+ if (ui.weekdayRow) {
+ ui.weekdayRow.classList.toggle("hidden", currentView === "year");
+ }
+
+ if (currentView === "month") {
+ const range = getMonthGridRange(viewDate, weekStartsOnMonday);
+ const expanded = expandEvents(state.e, range.start, range.end);
+ const decorated = decorateOccurrences(expanded);
+ occurrencesByDay = groupOccurrences(decorated);
+
+ if (ui.monthLabel) ui.monthLabel.textContent = formatMonthLabel(viewDate);
+ if (ui.weekdayRow) renderWeekdayHeaders(ui.weekdayRow, weekStartsOnMonday, "month");
+
+ if (ui.calendarGrid) {
+ renderCalendar({
+ container: ui.calendarGrid,
+ dates: range.dates,
+ currentMonth: viewDate.getMonth(),
+ selectedDate,
+ eventsByDay: occurrencesByDay,
+ onSelectDay: handleSelectDay,
+ onEventClick: (event) => openEventModal({ index: event.sourceIndex }),
+ });
+ }
+ } else if (currentView === "week") {
+ const range = getWeekRange(selectedDate, weekStartsOnMonday);
+ const expanded = expandEvents(state.e, range.start, range.end);
+ const decorated = decorateOccurrences(expanded);
+ occurrencesByDay = groupOccurrences(decorated);
+
+ if (ui.monthLabel) ui.monthLabel.textContent = formatRangeLabel(range.start, range.end);
+ if (ui.weekdayRow) renderWeekdayHeaders(ui.weekdayRow, weekStartsOnMonday, "week", range.dates);
+ if (ui.calendarGrid) {
+ renderTimeGrid({
+ container: ui.calendarGrid,
+ dates: range.dates,
+ occurrences: decorated,
+ onSelectDay: handleSelectDay,
+ onEventClick: (event) => openEventModal({ index: event.sourceIndex }),
+ });
+ }
+ } else if (currentView === "day") {
+ const start = startOfDay(selectedDate);
+ const end = new Date(start.getFullYear(), start.getMonth(), start.getDate(), 23, 59, 59);
+ const expanded = expandEvents(state.e, start, end);
+ const decorated = decorateOccurrences(expanded);
+ occurrencesByDay = groupOccurrences(decorated);
+
+ if (ui.monthLabel) ui.monthLabel.textContent = formatDateLabel(selectedDate);
+ if (ui.weekdayRow) renderWeekdayHeaders(ui.weekdayRow, weekStartsOnMonday, "day", [start]);
+ if (ui.calendarGrid) {
+ renderTimeGrid({
+ container: ui.calendarGrid,
+ dates: [start],
+ occurrences: decorated,
+ onSelectDay: handleSelectDay,
+ onEventClick: (event) => openEventModal({ index: event.sourceIndex }),
+ });
+ }
+ } else if (currentView === "year") {
+ const year = viewDate.getFullYear();
+ const start = new Date(year, 0, 1);
+ const end = new Date(year, 11, 31, 23, 59, 59);
+ const expanded = expandEvents(state.e, start, end);
+ const decorated = decorateOccurrences(expanded);
+ occurrencesByDay = groupOccurrences(decorated);
+
+ if (ui.monthLabel) ui.monthLabel.textContent = String(year);
+ if (ui.calendarGrid) {
+ renderYearView({
+ container: ui.calendarGrid,
+ year,
+ eventsByDay: occurrencesByDay,
+ selectedDate,
+ weekStartsOnMonday,
+ onSelectDay: handleSelectDay,
+ });
+ }
+ }
+
+ renderEventList();
+ updateUrlLength();
+ updateLockUI();
+}
+
+function renderEventList() {
+ if (!ui.eventList || !ui.selectedDateLabel) return;
+ ui.selectedDateLabel.textContent = formatDateLabel(selectedDate);
+ const key = formatDateKey(selectedDate);
+ const list = occurrencesByDay.get(key) || [];
+
+ ui.eventList.innerHTML = "";
+ if (!list.length) {
+ const empty = document.createElement("div");
+ empty.className = "event-item";
+ empty.textContent = "No events yet.";
+ ui.eventList.appendChild(empty);
+ return;
+ }
+
+ list.forEach((event) => {
+ const item = document.createElement("div");
+ item.className = "event-item";
+ item.dataset.index = String(event.sourceIndex);
+
+ const left = document.createElement("div");
+ left.className = "event-info";
+ const title = document.createElement("div");
+ title.className = "event-title";
+ title.textContent = event.title;
+ const time = document.createElement("div");
+ time.className = "event-time";
+ time.textContent = event.isAllDay ? "All day" : `${event.timeLabel}`;
+ left.appendChild(title);
+ left.appendChild(time);
+
+ const dot = document.createElement("div");
+ dot.className = "event-dot";
+ dot.style.background = event.color;
+
+ item.appendChild(left);
+ item.appendChild(dot);
+ item.addEventListener("click", () => openEventModal({ index: event.sourceIndex }));
+ ui.eventList.appendChild(item);
+ });
+}
+
+function handleSelectDay(date) {
+ selectedDate = startOfDay(date);
+ if (currentView === "month") {
+ if (date.getMonth() !== viewDate.getMonth() || date.getFullYear() !== viewDate.getFullYear()) {
+ viewDate = new Date(date.getFullYear(), date.getMonth(), 1);
+ }
+ } else {
+ viewDate = startOfDay(date);
+ }
+ render();
+}
+
+function openEventModal({ index = null, date = null } = {}) {
+ if (!ui.eventModal) return;
+ editingIndex = index;
+ const isEditing = typeof index === "number";
+ ui.eventModalTitle.textContent = isEditing ? "Edit event" : "Add event";
+ ui.eventDelete.classList.toggle("hidden", !isEditing);
+
+ const baseDate = date || selectedDate;
+ let startDate = new Date(baseDate.getFullYear(), baseDate.getMonth(), baseDate.getDate(), 9, 0);
+ let duration = 60;
+ let title = "";
+ let color = state.c[0] || DEFAULT_COLORS[0];
+ let rule = "";
+ let isAllDay = false;
+
+ if (isEditing) {
+ const entry = state.e[index];
+ if (entry) {
+ const [startMin, storedDuration, storedTitle, colorIndex, storedRule] = entry;
+ startDate = new Date(startMin * 60000);
+ duration = storedDuration || 0;
+ title = storedTitle || "";
+ color = state.c[colorIndex] || color;
+ rule = storedRule || "";
+ isAllDay = duration === 0;
+ }
+ }
+
+ 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.eventRecurrence.value = rule;
+ ui.eventColor.value = color;
+ ui.eventAllDay.checked = isAllDay;
+ toggleAllDay(isAllDay);
+ renderColorPalette(color);
+
+ ui.eventModal.classList.remove("hidden");
+}
+
+function closeEventModal() {
+ if (ui.eventModal) ui.eventModal.classList.add("hidden");
+}
+
+function toggleAllDay(allDay) {
+ if (!ui.eventTime || !ui.eventDuration) return;
+ ui.eventTime.disabled = allDay;
+ ui.eventDuration.disabled = allDay;
+ if (allDay) {
+ ui.eventDuration.value = "0";
+ } else if (Number(ui.eventDuration.value) === 0) {
+ ui.eventDuration.value = "60";
+ }
+}
+
+function renderColorPalette(activeColor) {
+ if (!ui.colorPalette) return;
+ ui.colorPalette.innerHTML = "";
+ state.c.forEach((color) => {
+ const swatch = document.createElement("button");
+ swatch.type = "button";
+ swatch.className = "color-swatch";
+ if (color.toLowerCase() === activeColor.toLowerCase()) {
+ swatch.classList.add("active");
+ }
+ swatch.style.background = color;
+ swatch.addEventListener("click", () => {
+ ui.eventColor.value = color;
+ renderColorPalette(color);
+ });
+ ui.colorPalette.appendChild(swatch);
+ });
+}
+
+function saveEvent(event) {
+ event.preventDefault();
+ if (!ui.eventTitle || !ui.eventDate) return;
+ const title = ui.eventTitle.value.trim() || "Untitled";
+ const dateValue = ui.eventDate.value;
+ if (!dateValue) return;
+
+ const [year, month, day] = dateValue.split("-").map(Number);
+ const allDay = ui.eventAllDay.checked;
+
+ let startDate;
+ if (allDay) {
+ startDate = new Date(year, month - 1, day);
+ } else {
+ const [rawHours, rawMinutes] = ui.eventTime.value.split(":").map(Number);
+ const hours = Number.isFinite(rawHours) ? rawHours : 9;
+ const minutes = Number.isFinite(rawMinutes) ? rawMinutes : 0;
+ 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 colorValue = ui.eventColor.value.toLowerCase();
+ let colorIndex = state.c.findIndex((color) => color.toLowerCase() === colorValue);
+ if (colorIndex === -1) {
+ state.c.push(colorValue);
+ colorIndex = state.c.length - 1;
+ }
+ const rule = ui.eventRecurrence.value;
+ const entry = [startMin, duration, title, colorIndex];
+ if (rule) entry.push(rule);
+
+ if (typeof editingIndex === "number") {
+ state.e[editingIndex] = entry;
+ } else {
+ state.e.push(entry);
+ }
+
+ selectedDate = startOfDay(startDate);
+ closeEventModal();
+ scheduleSave();
+ render();
+}
+
+function deleteEvent() {
+ if (typeof editingIndex !== "number") return;
+ const confirmed = window.confirm("Delete this event?");
+ if (!confirmed) return;
+ state.e.splice(editingIndex, 1);
+ editingIndex = null;
+ closeEventModal();
+ scheduleSave();
+ 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("hidden");
+
+ if (mode === "set") {
+ ui.passwordConfirmField.classList.remove("hidden");
+ } else {
+ ui.passwordConfirmField.classList.add("hidden");
+ }
+
+ ui.passwordSubmit.textContent = submitLabel;
+ ui.passwordModal.classList.remove("hidden");
+
+ return new Promise((resolve) => {
+ passwordResolver = resolve;
+ });
+}
+
+function closePasswordModal() {
+ if (ui.passwordModal) ui.passwordModal.classList.add("hidden");
+ if (passwordResolver) {
+ passwordResolver(null);
+ passwordResolver = null;
+ }
+}
+
+function submitPassword() {
+ if (!passwordResolver) return;
+ const value = ui.passwordInput.value.trim();
+ if (!value) {
+ ui.passwordError.textContent = "Password is required.";
+ ui.passwordError.classList.remove("hidden");
+ return;
+ }
+
+ if (passwordMode === "set") {
+ if (value !== ui.passwordConfirm.value.trim()) {
+ ui.passwordError.textContent = "Passwords do not match.";
+ ui.passwordError.classList.remove("hidden");
+ return;
+ }
+ }
+
+ ui.passwordModal.classList.add("hidden");
+ passwordResolver(value);
+ passwordResolver = null;
+}
+
+async function handleLockAction() {
+ if (lockState.encrypted && !lockState.unlocked) {
+ await attemptUnlock();
+ return;
+ }
+
+ if (lockState.encrypted && lockState.unlocked) {
+ const confirmed = window.confirm("Remove password protection? This will store data unencrypted in the URL.");
+ if (!confirmed) return;
+ password = null;
+ lockState = { encrypted: false, unlocked: true };
+ await writeStateToHash(state, null);
+ updateLockUI();
+ showToast("Lock removed", "success");
+ return;
+ }
+
+ const value = await openPasswordModal({
+ mode: "set",
+ title: "Set password",
+ description: "Add a password so only people with the link and password can read this calendar.",
+ submitLabel: "Set password",
+ });
+ if (!value) return;
+ password = value;
+ lockState = { encrypted: true, unlocked: true };
+ await writeStateToHash(state, password);
+ updateLockUI();
+ showToast("Calendar locked", "success");
+}
+
+async function attemptUnlock() {
+ const value = await openPasswordModal({
+ mode: "unlock",
+ title: "Unlock calendar",
+ description: "Enter the password to decrypt this calendar.",
+ submitLabel: "Unlock",
+ });
+ if (!value) return;
+ try {
+ const loaded = await readStateFromHash(value);
+ password = value;
+ lockState = { encrypted: true, unlocked: true };
+ state = normalizeState(loaded);
+ render();
+ showToast("Calendar unlocked", "success");
+ } catch (error) {
+ showToast("Incorrect password", "error");
+ lockState = { encrypted: true, unlocked: false };
+ updateLockUI();
+ }
+}
+
+async function loadStateFromHash() {
+ if (!window.location.hash) {
+ state = cloneState(DEFAULT_STATE);
+ return;
+ }
+
+ if (isEncryptedHash()) {
+ lockState = { encrypted: true, unlocked: false };
+ state = cloneState(DEFAULT_STATE);
+ updateLockUI();
+ return;
+ }
+
+ try {
+ const loaded = await readStateFromHash();
+ state = normalizeState(loaded);
+ } catch (error) {
+ state = cloneState(DEFAULT_STATE);
+ }
+}
+
+function handleHashChange() {
+ loadStateFromHash().then(render);
+}
+
+function handleTitleInput() {
+ if (!ui.titleInput) return;
+ state.t = ui.titleInput.value.slice(0, MAX_TITLE_LENGTH);
+ scheduleSave();
+}
+
+function handleThemeToggle() {
+ state.s.d = state.s.d ? 0 : 1;
+ updateTheme();
+ scheduleSave();
+}
+
+function handleWeekStartToggle() {
+ state.s.m = state.s.m ? 0 : 1;
+ render();
+ scheduleSave();
+}
+
+function shiftView(direction) {
+ if (currentView === "month") {
+ viewDate = new Date(viewDate.getFullYear(), viewDate.getMonth() + direction, 1);
+ } else if (currentView === "year") {
+ viewDate = new Date(viewDate.getFullYear() + direction, 0, 1);
+ } else if (currentView === "week") {
+ selectedDate = addDays(selectedDate, direction * 7);
+ viewDate = startOfDay(selectedDate);
+ } else if (currentView === "day") {
+ selectedDate = addDays(selectedDate, direction);
+ viewDate = startOfDay(selectedDate);
+ }
+ render();
+}
+
+function handlePrevMonth() {
+ shiftView(-1);
+}
+
+function handleNextMonth() {
+ shiftView(1);
+}
+
+function handleToday() {
+ const today = startOfDay(new Date());
+ viewDate = today;
+ selectedDate = today;
+ render();
+}
+
+async function handleCopyLink() {
+ try {
+ await navigator.clipboard.writeText(window.location.href);
+ showToast("Link copied", "success");
+ } catch (error) {
+ showToast("Unable to copy link", "error");
+ }
+}
+
+function handleExportJson() {
+ const blob = new Blob([JSON.stringify(state, null, 2)], { type: "application/json" });
+ const url = URL.createObjectURL(blob);
+ const link = document.createElement("a");
+ link.href = url;
+ link.download = "hashcal.json";
+ link.click();
+ URL.revokeObjectURL(url);
+}
+
+function handleImportIcsClick() {
+ if (ui.icsInput) ui.icsInput.click();
+}
+
+function handleIcsFile(event) {
+ const file = event.target.files && event.target.files[0];
+ if (!file) return;
+ const reader = new FileReader();
+ reader.onload = () => {
+ const text = String(reader.result || "");
+ const imported = parseIcs(text);
+ if (!imported.length) {
+ showToast("No events found", "error");
+ return;
+ }
+ const colorCount = state.c.length || 1;
+ imported.forEach((entry, idx) => {
+ const start = entry.start;
+ if (!start) return;
+ const startMin = Math.floor(start.getTime() / 60000);
+ let duration = 0;
+ if (entry.end) {
+ duration = Math.max(0, Math.round((entry.end.getTime() - start.getTime()) / 60000));
+ }
+ if (entry.isAllDay) duration = 0;
+ const colorIndex = idx % colorCount;
+ const event = [startMin, duration, entry.title || "Imported", colorIndex];
+ if (entry.rule) event.push(entry.rule);
+ state.e.push(event);
+ });
+ scheduleSave();
+ render();
+ showToast("Events imported", "success");
+ };
+ reader.readAsText(file);
+ event.target.value = "";
+}
+
+function handleClearAll() {
+ const confirmed = window.confirm("Clear all events? This cannot be undone.");
+ if (!confirmed) return;
+ state.e = [];
+ scheduleSave();
+ render();
+}
+
+function bindEvents() {
+ if (ui.titleInput) ui.titleInput.addEventListener("input", handleTitleInput);
+ if (ui.prevMonth) ui.prevMonth.addEventListener("click", handlePrevMonth);
+ if (ui.nextMonth) ui.nextMonth.addEventListener("click", handleNextMonth);
+ if (ui.todayBtn) ui.todayBtn.addEventListener("click", handleToday);
+ if (ui.viewButtons && ui.viewButtons.length) {
+ ui.viewButtons.forEach((button) => {
+ button.addEventListener("click", () => setView(button.dataset.view));
+ });
+ }
+ 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.lockBtn) ui.lockBtn.addEventListener("click", handleLockAction);
+ if (ui.weekstartToggle) ui.weekstartToggle.addEventListener("click", handleWeekStartToggle);
+ if (ui.themeToggle) ui.themeToggle.addEventListener("click", handleThemeToggle);
+ if (ui.unlockBtn) ui.unlockBtn.addEventListener("click", attemptUnlock);
+ if (ui.exportJson) ui.exportJson.addEventListener("click", handleExportJson);
+ if (ui.importIcs) ui.importIcs.addEventListener("click", handleImportIcsClick);
+ if (ui.icsInput) ui.icsInput.addEventListener("change", handleIcsFile);
+ if (ui.clearAll) ui.clearAll.addEventListener("click", handleClearAll);
+
+ if (ui.eventClose) ui.eventClose.addEventListener("click", closeEventModal);
+ if (ui.eventCancel) ui.eventCancel.addEventListener("click", closeEventModal);
+ if (ui.eventDelete) ui.eventDelete.addEventListener("click", deleteEvent);
+ if (ui.eventForm) ui.eventForm.addEventListener("submit", saveEvent);
+ if (ui.eventAllDay) ui.eventAllDay.addEventListener("change", (e) => toggleAllDay(e.target.checked));
+
+ if (ui.passwordClose) ui.passwordClose.addEventListener("click", closePasswordModal);
+ if (ui.passwordCancel) ui.passwordCancel.addEventListener("click", closePasswordModal);
+ if (ui.passwordSubmit) ui.passwordSubmit.addEventListener("click", submitPassword);
+
+ window.addEventListener("hashchange", handleHashChange);
+}
+
+async function init() {
+ cacheElements();
+ bindEvents();
+ await loadStateFromHash();
+
+ if (!window.location.hash) {
+ await writeStateToHash(state, null);
+ }
+
+ updateViewButtons();
+ render();
+
+ if (isEncryptedHash() && !lockState.unlocked) {
+ attemptUnlock();
+ }
+}
+
+if (document.readyState === "loading") {
+ document.addEventListener("DOMContentLoaded", init);
+} else {
+ init();
+}
diff --git a/sitemap.txt b/sitemap.txt
new file mode 100644
index 0000000..5a882ca
--- /dev/null
+++ b/sitemap.txt
@@ -0,0 +1 @@
+https://spreadsheetlive.netlify.app/
diff --git a/sitemap.xml b/sitemap.xml
new file mode 100644
index 0000000..0193811
--- /dev/null
+++ b/sitemap.xml
@@ -0,0 +1,7 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
+ <url>
+ <loc>https://spreadsheetlive.netlify.app/</loc>
+ <lastmod>2026-01-23</lastmod>
+ </url>
+</urlset>
diff --git a/styles.css b/styles.css
new file mode 100644
index 0000000..02a9f30
--- /dev/null
+++ b/styles.css
@@ -0,0 +1,781 @@
+:root {
+ color-scheme: light;
+ --font-body: "Space Grotesk", "Roboto", "Segoe UI", sans-serif;
+ --font-display: "Space Grotesk", "Roboto", "Segoe UI", sans-serif;
+ --bg: #f1f3f4;
+ --panel: #ffffff;
+ --panel-2: #fafafa;
+ --border: #dadce0;
+ --border-soft: #e6e6e6;
+ --text: #3c4043;
+ --muted: #5f6368;
+ --accent: #1a73e8;
+ --accent-soft: rgba(26, 115, 232, 0.12);
+ --accent-strong: #0b57d0;
+ --danger: #d93025;
+ --danger-ink: #ffffff;
+ --shadow-sm: 0 1px 2px rgba(60, 64, 67, 0.12);
+ --shadow-md: 0 2px 8px rgba(60, 64, 67, 0.16);
+}
+
+body[data-theme="dark"] {
+ color-scheme: dark;
+ --bg: #202124;
+ --panel: #2b2c2f;
+ --panel-2: #27272a;
+ --border: #3c4043;
+ --border-soft: #33363a;
+ --text: #e8eaed;
+ --muted: #9aa0a6;
+ --accent: #8ab4f8;
+ --accent-soft: rgba(138, 180, 248, 0.2);
+ --accent-strong: #a8c7fa;
+ --danger: #f28b82;
+ --danger-ink: #1f1f1f;
+ --shadow-sm: 0 1px 2px rgba(0, 0, 0, 0.3);
+ --shadow-md: 0 2px 8px rgba(0, 0, 0, 0.4);
+}
+
+* {
+ box-sizing: border-box;
+}
+
+html,
+body {
+ height: 100%;
+}
+
+body {
+ margin: 0;
+ font-family: var(--font-body);
+ background: var(--bg);
+ color: var(--text);
+ overflow: hidden;
+}
+
+button {
+ font-family: inherit;
+}
+
+.app {
+ height: 100vh;
+ display: flex;
+ flex-direction: column;
+}
+
+.topbar {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 16px;
+ padding: 0 20px;
+ height: 64px;
+ background: var(--panel);
+ border-bottom: 1px solid var(--border);
+ position: sticky;
+ top: 0;
+ z-index: 10;
+}
+
+.brand {
+ display: flex;
+ align-items: center;
+ gap: 12px;
+}
+
+.brand-mark {
+ width: 40px;
+ height: 40px;
+ border-radius: 10px;
+ background: var(--accent);
+ color: #fff;
+ display: grid;
+ place-items: center;
+ font-weight: 700;
+ font-family: var(--font-display);
+}
+
+.brand-text {
+ display: flex;
+ flex-direction: column;
+ gap: 2px;
+}
+
+.title-input {
+ font-family: var(--font-display);
+ font-size: 18px;
+ font-weight: 600;
+ color: var(--text);
+ border: none;
+ background: transparent;
+ padding: 0;
+ outline: none;
+}
+
+.brand-subtitle {
+ font-size: 0.78rem;
+ color: var(--muted);
+}
+
+.top-actions {
+ display: flex;
+ align-items: center;
+ gap: 10px;
+ flex-wrap: wrap;
+}
+
+.nav-group {
+ display: flex;
+ gap: 8px;
+}
+
+.view-toggle {
+ display: inline-flex;
+ align-items: center;
+ border: 1px solid var(--border);
+ background: var(--panel-2);
+ border-radius: 999px;
+ overflow: hidden;
+}
+
+button {
+ font-size: 0.85rem;
+ padding: 7px 14px;
+ border-radius: 6px;
+ border: 1px solid var(--border);
+ background: var(--panel);
+ color: var(--text);
+ cursor: pointer;
+ transition: background 0.15s ease, border-color 0.15s ease, box-shadow 0.15s ease;
+}
+
+button:hover {
+ background: var(--panel-2);
+ border-color: var(--border-soft);
+ box-shadow: var(--shadow-sm);
+}
+
+button:focus-visible {
+ outline: 2px solid var(--accent);
+ outline-offset: 2px;
+}
+
+button.primary {
+ background: var(--accent);
+ color: #fff;
+ border-color: transparent;
+ box-shadow: var(--shadow-sm);
+}
+
+button.primary:hover {
+ background: var(--accent-strong);
+}
+
+/* View toggle overrides */
+.view-toggle button {
+ border: none;
+ background: transparent;
+ color: var(--muted);
+ font-size: 0.78rem;
+ padding: 6px 12px;
+ box-shadow: none;
+}
+
+.view-toggle button:hover {
+ background: transparent;
+ box-shadow: none;
+}
+
+.view-toggle button.active {
+ background: var(--accent);
+ color: #fff;
+}
+
+button.ghost {
+ background: transparent;
+}
+
+button.danger,
+.danger-btn {
+ background: var(--danger);
+ color: var(--danger-ink);
+ border-color: transparent;
+}
+
+button:disabled {
+ opacity: 0.6;
+ cursor: not-allowed;
+ box-shadow: none;
+}
+
+.layout {
+ flex: 1;
+ min-height: 0;
+ display: grid;
+ grid-template-columns: 280px 1fr;
+}
+
+.side-panel {
+ order: -1;
+ background: var(--panel);
+ border-right: 1px solid var(--border);
+ padding: 16px;
+ display: flex;
+ flex-direction: column;
+ gap: 16px;
+ overflow-y: auto;
+}
+
+.calendar-panel {
+ background: var(--panel);
+ display: flex;
+ flex-direction: column;
+ min-height: 0;
+}
+
+.panel-header {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 16px;
+ padding: 16px 20px 12px;
+ border-bottom: 1px solid var(--border);
+}
+
+.month-label {
+ margin: 0 0 4px;
+ font-size: 1.4rem;
+ font-weight: 600;
+ font-family: var(--font-display);
+}
+
+.panel-actions {
+ display: flex;
+ gap: 8px;
+ flex-wrap: wrap;
+}
+
+.weekday-row {
+ display: grid;
+ grid-template-columns: repeat(7, minmax(0, 1fr));
+ border-bottom: 1px solid var(--border);
+ background: var(--panel);
+}
+
+.weekday-row.hidden {
+ display: none;
+}
+
+.weekday {
+ padding: 8px 12px;
+ text-align: center;
+ font-size: 0.72rem;
+ color: var(--muted);
+ text-transform: uppercase;
+ letter-spacing: 0.08em;
+}
+
+.calendar-grid {
+ flex: 1;
+ min-height: 0;
+ background: var(--panel);
+}
+
+.calendar-grid.month-view {
+ display: grid;
+ grid-template-columns: repeat(7, minmax(0, 1fr));
+ grid-template-rows: repeat(6, minmax(0, 1fr));
+ border-left: 1px solid var(--border);
+ border-top: 1px solid var(--border);
+}
+
+.day-cell {
+ border-right: 1px solid var(--border);
+ border-bottom: 1px solid var(--border);
+ padding: 8px 10px;
+ display: flex;
+ flex-direction: column;
+ gap: 6px;
+ cursor: pointer;
+ background: var(--panel);
+ transition: background 0.15s ease;
+}
+
+.day-cell:hover {
+ background: var(--panel-2);
+}
+
+.day-cell.is-outside {
+ background: var(--panel-2);
+ color: var(--muted);
+}
+
+.day-cell.is-today {
+ background: var(--accent-soft);
+}
+
+.day-cell.is-selected {
+ box-shadow: inset 0 0 0 2px var(--accent);
+}
+
+.day-number {
+ font-size: 0.72rem;
+ font-weight: 600;
+ color: inherit;
+ align-self: flex-end;
+}
+
+.event-chip {
+ border-radius: 4px;
+ padding: 2px 6px;
+ font-size: 0.7rem;
+ display: inline-flex;
+ align-items: center;
+ gap: 6px;
+ color: #fff;
+ border: none;
+ box-shadow: none;
+ overflow: hidden;
+ white-space: nowrap;
+ text-overflow: ellipsis;
+}
+
+.event-chip .time {
+ font-weight: 600;
+ font-size: 0.65rem;
+}
+
+.event-more {
+ font-size: 0.72rem;
+ color: var(--muted);
+}
+
+.calendar-grid.week-view,
+.calendar-grid.day-view {
+ display: grid;
+ border-left: 1px solid var(--border);
+ border-top: 1px solid var(--border);
+ background: var(--panel);
+}
+
+.time-label {
+ border-right: 1px solid var(--border);
+ border-bottom: 1px solid var(--border);
+ padding: 4px 6px;
+ font-size: 0.68rem;
+ color: var(--muted);
+ text-align: right;
+ background: var(--panel);
+}
+
+.time-label.all-day-label {
+ text-align: center;
+ font-weight: 600;
+}
+
+.time-cell {
+ border-right: 1px solid var(--border);
+ border-bottom: 1px solid var(--border);
+ padding: 4px;
+ background: var(--panel);
+ display: flex;
+ flex-direction: column;
+ gap: 4px;
+ overflow: hidden;
+}
+
+.time-cell.all-day {
+ background: var(--panel-2);
+}
+
+.time-event {
+ border-radius: 4px;
+ padding: 2px 6px;
+ font-size: 0.68rem;
+ color: #fff;
+ border: none;
+ text-align: left;
+ cursor: pointer;
+}
+
+.calendar-grid.year-view {
+ display: grid;
+ grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));
+ gap: 16px;
+ padding: 16px;
+ overflow: auto;
+ background: var(--bg);
+}
+
+.mini-month {
+ border: 1px solid var(--border);
+ background: var(--panel);
+ border-radius: 8px;
+ padding: 12px;
+ display: flex;
+ flex-direction: column;
+ gap: 8px;
+}
+
+.mini-title {
+ font-size: 0.9rem;
+ font-weight: 600;
+ color: var(--text);
+}
+
+.mini-grid {
+ display: grid;
+ grid-template-columns: repeat(7, minmax(0, 1fr));
+ gap: 4px;
+}
+
+.mini-weekday {
+ font-size: 0.6rem;
+ text-align: center;
+ color: var(--muted);
+ text-transform: uppercase;
+}
+
+.mini-day {
+ border: none;
+ background: transparent;
+ color: var(--text);
+ font-size: 0.65rem;
+ padding: 4px 0;
+ border-radius: 4px;
+ position: relative;
+}
+
+.mini-day.is-outside {
+ color: var(--muted);
+}
+
+.mini-day.is-selected {
+ background: var(--accent-soft);
+}
+
+.mini-day:hover {
+ background: var(--panel-2);
+}
+
+.mini-dot {
+ position: absolute;
+ bottom: 2px;
+ left: 50%;
+ width: 4px;
+ height: 4px;
+ background: var(--accent);
+ border-radius: 50%;
+ transform: translateX(-50%);
+}
+
+.side-card {
+ border: 1px solid var(--border);
+ border-radius: 8px;
+ padding: 12px;
+ background: var(--panel);
+ display: flex;
+ flex-direction: column;
+ gap: 10px;
+}
+
+.side-card.danger {
+ border-color: rgba(217, 48, 37, 0.4);
+}
+
+.side-title {
+ margin: 0;
+ font-size: 0.9rem;
+ font-weight: 600;
+}
+
+.event-list {
+ display: flex;
+ flex-direction: column;
+ gap: 8px;
+ min-height: 120px;
+}
+
+.event-item {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 10px;
+ padding: 8px 10px;
+ border-radius: 6px;
+ border: 1px solid var(--border-soft);
+ background: var(--panel-2);
+ cursor: pointer;
+}
+
+.event-item:hover {
+ border-color: var(--border);
+}
+
+.event-info {
+ display: flex;
+ flex-direction: column;
+ gap: 2px;
+}
+
+.event-title {
+ font-weight: 600;
+ font-size: 0.85rem;
+}
+
+.event-time {
+ font-size: 0.75rem;
+ color: var(--muted);
+}
+
+.event-dot {
+ width: 10px;
+ height: 10px;
+ border-radius: 50%;
+ flex-shrink: 0;
+}
+
+.status-row {
+ display: flex;
+ justify-content: space-between;
+ font-size: 0.8rem;
+ color: var(--muted);
+}
+
+.url-warning {
+ margin: 0;
+ font-size: 0.72rem;
+ color: var(--danger);
+}
+
+.stacked-actions {
+ display: flex;
+ flex-direction: column;
+ gap: 8px;
+}
+
+.modal {
+ position: fixed;
+ inset: 0;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ z-index: 20;
+}
+
+.modal.hidden {
+ display: none;
+}
+
+.modal-backdrop {
+ position: absolute;
+ inset: 0;
+ background: rgba(32, 33, 36, 0.6);
+}
+
+.modal-card {
+ position: relative;
+ background: var(--panel);
+ border: 1px solid var(--border);
+ border-radius: 12px;
+ padding: 20px;
+ width: min(520px, 92vw);
+ box-shadow: var(--shadow-md);
+}
+
+.modal-header {
+ display: flex;
+ justify-content: space-between;
+ align-items: center;
+ gap: 12px;
+ margin-bottom: 12px;
+}
+
+.icon-btn {
+ width: 32px;
+ height: 32px;
+ border-radius: 50%;
+ padding: 0;
+}
+
+.modal-form {
+ display: flex;
+ flex-direction: column;
+ gap: 12px;
+}
+
+.field {
+ display: flex;
+ flex-direction: column;
+ gap: 6px;
+ font-size: 0.8rem;
+ color: var(--muted);
+}
+
+.field input,
+.field select {
+ padding: 8px 10px;
+ border-radius: 6px;
+ border: 1px solid var(--border);
+ background: var(--panel-2);
+ color: var(--text);
+ font-size: 0.85rem;
+}
+
+.field input:focus,
+.field select:focus {
+ outline: 2px solid var(--accent-soft);
+ border-color: var(--accent);
+}
+
+.field-row {
+ display: grid;
+ grid-template-columns: repeat(2, minmax(0, 1fr));
+ gap: 12px;
+}
+
+.checkbox-field {
+ flex-direction: row;
+ align-items: center;
+ gap: 10px;
+ color: var(--text);
+}
+
+.color-palette {
+ display: flex;
+ gap: 8px;
+ flex-wrap: wrap;
+}
+
+.color-swatch {
+ width: 20px;
+ height: 20px;
+ border-radius: 50%;
+ border: 2px solid transparent;
+ cursor: pointer;
+}
+
+.color-swatch.active {
+ border-color: var(--accent);
+}
+
+.modal-actions {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 12px;
+ margin-top: 4px;
+}
+
+.modal-actions-right {
+ display: flex;
+ gap: 8px;
+}
+
+.modal-note {
+ margin: 0;
+ font-size: 0.78rem;
+ color: var(--muted);
+}
+
+.modal-error {
+ margin: 0;
+ font-size: 0.75rem;
+ color: var(--danger);
+}
+
+.locked-overlay {
+ position: absolute;
+ inset: 0;
+ display: grid;
+ place-items: center;
+ background: rgba(32, 33, 36, 0.4);
+ z-index: 5;
+}
+
+.locked-overlay.hidden {
+ display: none;
+}
+
+.locked-card {
+ background: var(--panel);
+ border: 1px solid var(--border);
+ border-radius: 12px;
+ padding: 20px;
+ text-align: center;
+ width: min(320px, 80%);
+ box-shadow: var(--shadow-md);
+}
+
+.toast-container {
+ position: fixed;
+ bottom: 24px;
+ right: 24px;
+ display: flex;
+ flex-direction: column;
+ gap: 10px;
+ z-index: 40;
+}
+
+.toast {
+ background: var(--panel);
+ color: var(--text);
+ padding: 10px 14px;
+ border-radius: 8px;
+ border: 1px solid var(--border);
+ box-shadow: var(--shadow-sm);
+ min-width: 200px;
+}
+
+.toast.success {
+ border-color: rgba(52, 168, 83, 0.6);
+}
+
+.toast.error {
+ border-color: rgba(217, 48, 37, 0.6);
+}
+
+.hidden {
+ display: none !important;
+}
+
+@media (max-width: 1024px) {
+ .layout {
+ grid-template-columns: 1fr;
+ }
+
+ .side-panel {
+ order: 0;
+ border-right: none;
+ border-bottom: 1px solid var(--border);
+ flex-direction: row;
+ flex-wrap: wrap;
+ }
+
+ .side-card {
+ flex: 1 1 280px;
+ }
+}
+
+@media (max-width: 720px) {
+ .topbar {
+ height: auto;
+ padding: 12px 16px;
+ flex-direction: column;
+ align-items: flex-start;
+ gap: 12px;
+ }
+
+ .layout {
+ grid-template-columns: 1fr;
+ }
+
+ .panel-header {
+ flex-direction: column;
+ align-items: flex-start;
+ }
+
+ .field-row {
+ grid-template-columns: 1fr;
+ }
+}