removing author and cleaning js / css
This commit is contained in:
32
assets/scripts/application/theme-switcher.js
Normal file
32
assets/scripts/application/theme-switcher.js
Normal file
@@ -0,0 +1,32 @@
|
||||
/* Function for setting the theme */
|
||||
(function(){
|
||||
const root = document.documentElement;
|
||||
const storageKey = "theme";
|
||||
const themes = ["light", "dark", "dark-academia"];
|
||||
const labels = {
|
||||
"light": "Light",
|
||||
"dark": "Dark",
|
||||
"dark-academia": "Academia"
|
||||
};
|
||||
const saved = localStorage.getItem(storageKey);
|
||||
if (themes.includes(saved)) {
|
||||
root.setAttribute("data-theme", saved);
|
||||
}
|
||||
const btn = document.getElementById("theme-toggle");
|
||||
if (!btn) return;
|
||||
const updateButton = () => {
|
||||
const current = root.getAttribute("data-theme");
|
||||
const label = labels[current] || "Auto";
|
||||
btn.textContent = `Theme: ${label}`;
|
||||
btn.setAttribute("aria-label", `Current theme: ${label}. Switch theme.`);
|
||||
};
|
||||
updateButton();
|
||||
btn.addEventListener("click", () => {
|
||||
const current = root.getAttribute("data-theme");
|
||||
const index = themes.indexOf(current);
|
||||
const target = themes[index === -1 ? 1 : (index + 1) % themes.length];
|
||||
root.setAttribute("data-theme", target);
|
||||
localStorage.setItem(storageKey, target);
|
||||
updateButton();
|
||||
});
|
||||
})();
|
||||
File diff suppressed because it is too large
Load Diff
8
assets/scripts/bigger-picture.min.js
vendored
8
assets/scripts/bigger-picture.min.js
vendored
File diff suppressed because one or more lines are too long
@@ -1,196 +1,7 @@
|
||||
let pageSlug = null;
|
||||
|
||||
/* -----------------------------
|
||||
* DOM builders
|
||||
* ----------------------------- */
|
||||
|
||||
|
||||
function showReplyForm(container, parentId) {
|
||||
if (container.querySelector(".reply-form")) return;
|
||||
|
||||
const form = document.createElement("form");
|
||||
form.className = "reply-form";
|
||||
|
||||
form.innerHTML = `
|
||||
<input type="text" name="author" placeholder="Your name (optional)">
|
||||
<textarea name="content" required placeholder="Write a reply..."></textarea>
|
||||
<button type="submit">Post reply</button>
|
||||
`;
|
||||
|
||||
form.addEventListener("submit", async e => {
|
||||
e.preventDefault();
|
||||
|
||||
const author = form.author.value.trim();
|
||||
const content = form.content.value.trim();
|
||||
if (!content) return;
|
||||
|
||||
const ok = await postComment(author, content, parentId);
|
||||
if (ok) loadComments();
|
||||
else alert("Failed to post reply");
|
||||
});
|
||||
|
||||
container.appendChild(form);
|
||||
}
|
||||
|
||||
function createComment(comment) {
|
||||
const wrapper = document.createElement("div");
|
||||
wrapper.className = "comment";
|
||||
wrapper.dataset.id = comment.id;
|
||||
wrapper.id = `comment-${comment.id}`;
|
||||
|
||||
const author = document.createElement("strong");
|
||||
author.textContent = comment.author || "Anonymous";
|
||||
|
||||
const body = document.createElement("p");
|
||||
body.textContent = comment.content;
|
||||
|
||||
const time = document.createElement("time");
|
||||
time.className = "comment-date";
|
||||
time.dateTime = comment.created_at;
|
||||
time.textContent = new Date(comment.created_at).toLocaleString();
|
||||
|
||||
const replyBtn = document.createElement("button");
|
||||
replyBtn.className = "comment-reply";
|
||||
replyBtn.textContent = "Reply";
|
||||
replyBtn.onclick = () =>
|
||||
showReplyForm(wrapper, Number(comment.id));
|
||||
|
||||
wrapper.append(author, body, time, replyBtn);
|
||||
|
||||
if (comment.children?.length) {
|
||||
const replies = document.createElement("div");
|
||||
replies.className = "comment-children";
|
||||
|
||||
comment.children.forEach(child => {
|
||||
replies.appendChild(createComment(child));
|
||||
});
|
||||
|
||||
wrapper.appendChild(replies);
|
||||
}
|
||||
return wrapper;
|
||||
}
|
||||
|
||||
|
||||
|
||||
function buildCommentTree(comments) {
|
||||
const byId = {};
|
||||
const roots = [];
|
||||
|
||||
comments.forEach(comment => {
|
||||
comment.children = [];
|
||||
byId[comment.id] = comment;
|
||||
});
|
||||
|
||||
comments.forEach(comment => {
|
||||
if (comment.parent_id) {
|
||||
const parent = byId[comment.parent_id];
|
||||
if (parent) parent.children.push(comment);
|
||||
} else {
|
||||
roots.push(comment);
|
||||
}
|
||||
});
|
||||
|
||||
return roots;
|
||||
}
|
||||
|
||||
|
||||
/* -----------------------------
|
||||
* Rendering
|
||||
* ----------------------------- */
|
||||
|
||||
function renderComments(comments) {
|
||||
const list = document.getElementById("comments-list");
|
||||
list.innerHTML = "";
|
||||
|
||||
if (!comments.length) {
|
||||
const empty = document.createElement("p");
|
||||
empty.className = "comments-empty";
|
||||
empty.textContent = "No comments yet.";
|
||||
list.appendChild(empty);
|
||||
return;
|
||||
}
|
||||
|
||||
const tree = buildCommentTree(comments);
|
||||
tree.forEach(comment => list.appendChild(createComment(comment)));
|
||||
}
|
||||
|
||||
|
||||
/* -----------------------------
|
||||
* API
|
||||
* ----------------------------- */
|
||||
|
||||
async function fetchComments() {
|
||||
const res = await fetch(`/api/comments/${pageSlug}`);
|
||||
if (!res.ok) {
|
||||
console.error("Failed to fetch comments");
|
||||
return [];
|
||||
}
|
||||
return await res.json();
|
||||
}
|
||||
|
||||
async function postComment(author, content, parentId = null) {
|
||||
const res = await fetch("/api/comments", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
page_slug: pageSlug,
|
||||
author: author || null,
|
||||
content,
|
||||
parent_id: parentId
|
||||
})
|
||||
});
|
||||
|
||||
return res.ok;
|
||||
}
|
||||
|
||||
|
||||
|
||||
/* -----------------------------
|
||||
* Form handling
|
||||
* ----------------------------- */
|
||||
|
||||
function wireCommentForm() {
|
||||
const form = document.getElementById("comment-form");
|
||||
|
||||
form.addEventListener("submit", async event => {
|
||||
event.preventDefault();
|
||||
|
||||
const authorInput = form.querySelector("input[name='author']");
|
||||
const textarea = form.querySelector("textarea[name='content']");
|
||||
|
||||
const author = authorInput.value.trim();
|
||||
const content = textarea.value.trim();
|
||||
|
||||
if (!content) return;
|
||||
|
||||
const ok = await postComment(author, content);
|
||||
if (ok) {
|
||||
textarea.value = "";
|
||||
loadComments();
|
||||
} else {
|
||||
alert("Failed to post comment");
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
/* -----------------------------
|
||||
* Entry point
|
||||
* ----------------------------- */
|
||||
|
||||
async function loadComments() {
|
||||
const comments = await fetchComments();
|
||||
renderComments(comments);
|
||||
}
|
||||
|
||||
function initComments() {
|
||||
const section = document.getElementById("comments");
|
||||
if (!section) return;
|
||||
|
||||
pageSlug = section.dataset.slug;
|
||||
|
||||
wireCommentForm();
|
||||
loadComments();
|
||||
}
|
||||
|
||||
initComments();
|
||||
(function () {
|
||||
"use strict";
|
||||
var script = document.createElement("script");
|
||||
script.src = "/assets/scripts/features/comments.js";
|
||||
script.defer = true;
|
||||
document.head.appendChild(script);
|
||||
}());
|
||||
|
||||
@@ -1,240 +1,7 @@
|
||||
const STATES = [
|
||||
{ key: "completed", label: "Completed" },
|
||||
{ key: "manager_review", label: "Manager Review" },
|
||||
{ key: "in_progress", label: "In Progress" },
|
||||
{ key: "not_started", label: "Not Started" },
|
||||
{ key: "comments", label: "Comments" },
|
||||
];
|
||||
|
||||
const LEVELS = [
|
||||
{ key: "graduate", label: "Graduate" },
|
||||
{ key: "engineer", label: "Engineer" },
|
||||
];
|
||||
|
||||
let currentLevel = LEVELS[0].key;
|
||||
|
||||
function isMobile() {
|
||||
return window.matchMedia("(max-width: 600px)").matches;
|
||||
}
|
||||
|
||||
function renderLevelTabs() {
|
||||
const board = document.getElementById("kanban-board");
|
||||
if (!board || document.getElementById("level-tabs")) return;
|
||||
|
||||
const nav = document.createElement("div");
|
||||
nav.id = "level-tabs";
|
||||
|
||||
LEVELS.forEach(({ key, label }) => {
|
||||
const btn = document.createElement("button");
|
||||
btn.textContent = label;
|
||||
btn.dataset.level = key;
|
||||
btn.className = "level-tab" + (key === currentLevel ? " active" : "");
|
||||
btn.addEventListener("click", () => {
|
||||
currentLevel = key;
|
||||
document.querySelectorAll(".level-tab").forEach(b =>
|
||||
b.classList.toggle("active", b.dataset.level === key)
|
||||
);
|
||||
loadBoard();
|
||||
});
|
||||
nav.appendChild(btn);
|
||||
});
|
||||
|
||||
board.insertAdjacentElement("beforebegin", nav);
|
||||
|
||||
if (!document.getElementById("level-tab-styles")) {
|
||||
const style = document.createElement("style");
|
||||
style.id = "level-tab-styles";
|
||||
style.textContent = `
|
||||
#level-tabs {
|
||||
display: flex;
|
||||
gap: 0.5em;
|
||||
margin-bottom: 1em;
|
||||
}
|
||||
.level-tab {
|
||||
padding: 0.4em 1.2em;
|
||||
border: 1px solid #ccc;
|
||||
background: none;
|
||||
cursor: pointer;
|
||||
border-radius: 4px;
|
||||
font-size: 0.95em;
|
||||
}
|
||||
.level-tab.active {
|
||||
background: #333;
|
||||
color: #fff;
|
||||
border-color: #333;
|
||||
}
|
||||
`;
|
||||
document.head.appendChild(style);
|
||||
}
|
||||
}
|
||||
|
||||
function populateMobileControls(items) {
|
||||
if (!isMobile()) return;
|
||||
|
||||
const panel = document.getElementById("mobile-move-panel");
|
||||
const itemSelect = document.getElementById("move-item");
|
||||
const fromSelect = document.getElementById("move-from");
|
||||
const toSelect = document.getElementById("move-to");
|
||||
|
||||
itemSelect.innerHTML = "<option value=''>Select competency</option>";
|
||||
fromSelect.innerHTML = "<option value=''>From</option>";
|
||||
toSelect.innerHTML = "<option value=''>To</option>";
|
||||
|
||||
items.forEach((item) => {
|
||||
const opt = document.createElement("option");
|
||||
opt.value = item.id;
|
||||
opt.textContent = item.title;
|
||||
opt.dataset.state = item.state;
|
||||
itemSelect.appendChild(opt);
|
||||
});
|
||||
|
||||
STATES.forEach((s) => {
|
||||
fromSelect.appendChild(new Option(s.label, s.key));
|
||||
toSelect.appendChild(new Option(s.label, s.key));
|
||||
});
|
||||
|
||||
itemSelect.onchange = () => {
|
||||
const selected = itemSelect.selectedOptions[0];
|
||||
if (selected?.dataset.state) {
|
||||
fromSelect.value = selected.dataset.state;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
const moveConfirmBtn = document.getElementById("move-confirm");
|
||||
if (moveConfirmBtn) {
|
||||
moveConfirmBtn.addEventListener("click", async () => {
|
||||
const itemId = document.getElementById("move-item").value;
|
||||
const from = document.getElementById("move-from").value;
|
||||
const to = document.getElementById("move-to").value;
|
||||
|
||||
if (!itemId || !to) {
|
||||
alert("Select an item and target column");
|
||||
return;
|
||||
}
|
||||
|
||||
if (from === to) {
|
||||
alert("Item is already in that column");
|
||||
return;
|
||||
}
|
||||
|
||||
const res = await fetch(`/api/competencies/items/${itemId}/state`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ state: to }),
|
||||
});
|
||||
|
||||
if (res.ok) {
|
||||
loadBoard();
|
||||
} else {
|
||||
alert("Failed to move competency");
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
let draggedItemId = null;
|
||||
|
||||
function countByState(items) {
|
||||
return items.reduce((acc, item) => {
|
||||
acc[item.state] = (acc[item.state] || 0) + 1;
|
||||
return acc;
|
||||
}, {});
|
||||
}
|
||||
|
||||
async function updateProgress(items) {
|
||||
const total = items.length;
|
||||
const completed = items.filter(i => i.state === "completed").length;
|
||||
const percent = total === 0 ? 0 : Math.round((completed / total) * 100);
|
||||
|
||||
const fill = document.getElementById("progress-fill");
|
||||
const label = document.getElementById("progress-label");
|
||||
|
||||
if (fill) fill.style.width = `${percent}%`;
|
||||
if (label) label.textContent = `${percent}% completed`;
|
||||
}
|
||||
|
||||
function createCard(item) {
|
||||
const card = document.createElement("div");
|
||||
card.className = "kanban-card";
|
||||
card.draggable = true;
|
||||
card.dataset.id = item.id;
|
||||
card.textContent = item.title;
|
||||
|
||||
card.addEventListener("dragstart", () => {
|
||||
draggedItemId = item.id;
|
||||
card.classList.add("dragging");
|
||||
});
|
||||
|
||||
card.addEventListener("dragend", () => {
|
||||
draggedItemId = null;
|
||||
card.classList.remove("dragging");
|
||||
});
|
||||
|
||||
return card;
|
||||
}
|
||||
|
||||
function createColumn(state, items, counts) {
|
||||
const col = document.createElement("div");
|
||||
col.className = "kanban-column";
|
||||
col.dataset.state = state.key;
|
||||
|
||||
const header = document.createElement("h3");
|
||||
header.innerHTML = `
|
||||
<span class="kanban-title">${state.label}</span>
|
||||
<span class="kanban-count">${counts[state.key] || 0}</span>
|
||||
`;
|
||||
|
||||
const list = document.createElement("div");
|
||||
list.className = "kanban-list";
|
||||
|
||||
list.addEventListener("dragover", (e) => e.preventDefault());
|
||||
|
||||
list.addEventListener("drop", async () => {
|
||||
if (!draggedItemId) return;
|
||||
|
||||
const res = await fetch(`/api/competencies/items/${draggedItemId}/state`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ state: state.key }),
|
||||
});
|
||||
|
||||
if (res.ok) {
|
||||
loadBoard();
|
||||
} else {
|
||||
alert("Failed to update state");
|
||||
}
|
||||
});
|
||||
|
||||
items
|
||||
.filter((i) => i.state === state.key)
|
||||
.forEach((i) => list.appendChild(createCard(i)));
|
||||
|
||||
col.appendChild(header);
|
||||
col.appendChild(list);
|
||||
|
||||
return col;
|
||||
}
|
||||
|
||||
function renderBoard(items) {
|
||||
const board = document.getElementById("kanban-board");
|
||||
if (!board) return;
|
||||
board.innerHTML = "";
|
||||
|
||||
const counts = countByState(items);
|
||||
|
||||
STATES.forEach((state) => {
|
||||
board.appendChild(createColumn(state, items, counts));
|
||||
});
|
||||
}
|
||||
|
||||
async function loadBoard() {
|
||||
const res = await fetch(`/api/competencies/items?group=${currentLevel}`);
|
||||
const items = await res.json();
|
||||
|
||||
updateProgress(items);
|
||||
renderBoard(items);
|
||||
populateMobileControls(items);
|
||||
}
|
||||
|
||||
renderLevelTabs();
|
||||
loadBoard();
|
||||
(function () {
|
||||
"use strict";
|
||||
var script = document.createElement("script");
|
||||
script.src = "/assets/scripts/pages/competency-status-board.js";
|
||||
script.defer = true;
|
||||
document.head.appendChild(script);
|
||||
}());
|
||||
|
||||
196
assets/scripts/features/comments.js
Normal file
196
assets/scripts/features/comments.js
Normal file
@@ -0,0 +1,196 @@
|
||||
let pageSlug = null;
|
||||
|
||||
/* -----------------------------
|
||||
* DOM builders
|
||||
* ----------------------------- */
|
||||
|
||||
|
||||
function showReplyForm(container, parentId) {
|
||||
if (container.querySelector(".reply-form")) return;
|
||||
|
||||
const form = document.createElement("form");
|
||||
form.className = "reply-form";
|
||||
|
||||
form.innerHTML = `
|
||||
<input type="text" name="author" placeholder="Your name (optional)">
|
||||
<textarea name="content" required placeholder="Write a reply..."></textarea>
|
||||
<button type="submit">Post reply</button>
|
||||
`;
|
||||
|
||||
form.addEventListener("submit", async e => {
|
||||
e.preventDefault();
|
||||
|
||||
const author = form.author.value.trim();
|
||||
const content = form.content.value.trim();
|
||||
if (!content) return;
|
||||
|
||||
const ok = await postComment(author, content, parentId);
|
||||
if (ok) loadComments();
|
||||
else alert("Failed to post reply");
|
||||
});
|
||||
|
||||
container.appendChild(form);
|
||||
}
|
||||
|
||||
function createComment(comment) {
|
||||
const wrapper = document.createElement("div");
|
||||
wrapper.className = "comment";
|
||||
wrapper.dataset.id = comment.id;
|
||||
wrapper.id = `comment-${comment.id}`;
|
||||
|
||||
const author = document.createElement("strong");
|
||||
author.textContent = comment.author || "Anonymous";
|
||||
|
||||
const body = document.createElement("p");
|
||||
body.textContent = comment.content;
|
||||
|
||||
const time = document.createElement("time");
|
||||
time.className = "comment-date";
|
||||
time.dateTime = comment.created_at;
|
||||
time.textContent = new Date(comment.created_at).toLocaleString();
|
||||
|
||||
const replyBtn = document.createElement("button");
|
||||
replyBtn.className = "comment-reply";
|
||||
replyBtn.textContent = "Reply";
|
||||
replyBtn.onclick = () =>
|
||||
showReplyForm(wrapper, Number(comment.id));
|
||||
|
||||
wrapper.append(author, body, time, replyBtn);
|
||||
|
||||
if (comment.children?.length) {
|
||||
const replies = document.createElement("div");
|
||||
replies.className = "comment-children";
|
||||
|
||||
comment.children.forEach(child => {
|
||||
replies.appendChild(createComment(child));
|
||||
});
|
||||
|
||||
wrapper.appendChild(replies);
|
||||
}
|
||||
return wrapper;
|
||||
}
|
||||
|
||||
|
||||
|
||||
function buildCommentTree(comments) {
|
||||
const byId = {};
|
||||
const roots = [];
|
||||
|
||||
comments.forEach(comment => {
|
||||
comment.children = [];
|
||||
byId[comment.id] = comment;
|
||||
});
|
||||
|
||||
comments.forEach(comment => {
|
||||
if (comment.parent_id) {
|
||||
const parent = byId[comment.parent_id];
|
||||
if (parent) parent.children.push(comment);
|
||||
} else {
|
||||
roots.push(comment);
|
||||
}
|
||||
});
|
||||
|
||||
return roots;
|
||||
}
|
||||
|
||||
|
||||
/* -----------------------------
|
||||
* Rendering
|
||||
* ----------------------------- */
|
||||
|
||||
function renderComments(comments) {
|
||||
const list = document.getElementById("comments-list");
|
||||
list.innerHTML = "";
|
||||
|
||||
if (!comments.length) {
|
||||
const empty = document.createElement("p");
|
||||
empty.className = "comments-empty";
|
||||
empty.textContent = "No comments yet.";
|
||||
list.appendChild(empty);
|
||||
return;
|
||||
}
|
||||
|
||||
const tree = buildCommentTree(comments);
|
||||
tree.forEach(comment => list.appendChild(createComment(comment)));
|
||||
}
|
||||
|
||||
|
||||
/* -----------------------------
|
||||
* API
|
||||
* ----------------------------- */
|
||||
|
||||
async function fetchComments() {
|
||||
const res = await fetch(`/api/comments/${pageSlug}`);
|
||||
if (!res.ok) {
|
||||
console.error("Failed to fetch comments");
|
||||
return [];
|
||||
}
|
||||
return await res.json();
|
||||
}
|
||||
|
||||
async function postComment(author, content, parentId = null) {
|
||||
const res = await fetch("/api/comments", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
page_slug: pageSlug,
|
||||
author: author || null,
|
||||
content,
|
||||
parent_id: parentId
|
||||
})
|
||||
});
|
||||
|
||||
return res.ok;
|
||||
}
|
||||
|
||||
|
||||
|
||||
/* -----------------------------
|
||||
* Form handling
|
||||
* ----------------------------- */
|
||||
|
||||
function wireCommentForm() {
|
||||
const form = document.getElementById("comment-form");
|
||||
|
||||
form.addEventListener("submit", async event => {
|
||||
event.preventDefault();
|
||||
|
||||
const authorInput = form.querySelector("input[name='author']");
|
||||
const textarea = form.querySelector("textarea[name='content']");
|
||||
|
||||
const author = authorInput.value.trim();
|
||||
const content = textarea.value.trim();
|
||||
|
||||
if (!content) return;
|
||||
|
||||
const ok = await postComment(author, content);
|
||||
if (ok) {
|
||||
textarea.value = "";
|
||||
loadComments();
|
||||
} else {
|
||||
alert("Failed to post comment");
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
/* -----------------------------
|
||||
* Entry point
|
||||
* ----------------------------- */
|
||||
|
||||
async function loadComments() {
|
||||
const comments = await fetchComments();
|
||||
renderComments(comments);
|
||||
}
|
||||
|
||||
function initComments() {
|
||||
const section = document.getElementById("comments");
|
||||
if (!section) return;
|
||||
|
||||
pageSlug = section.dataset.slug;
|
||||
|
||||
wireCommentForm();
|
||||
loadComments();
|
||||
}
|
||||
|
||||
initComments();
|
||||
624
assets/scripts/features/hidden-details.js
Normal file
624
assets/scripts/features/hidden-details.js
Normal file
@@ -0,0 +1,624 @@
|
||||
(function () {
|
||||
"use strict";
|
||||
|
||||
/*
|
||||
* Hidden site details
|
||||
* -------------------
|
||||
* This file adds small hidden interactions across the site: footer notes,
|
||||
* click targets, search/keyboard secrets, rare messages, and page-specific
|
||||
* behavior for the hidden /play pages.
|
||||
*
|
||||
* How to add your own things:
|
||||
* - Add new text to EDITABLE CONTENT arrays such as `details`, `poems`,
|
||||
* `greetings`, or `lore`.
|
||||
* - Add search-triggered toast messages to `SEARCH_TOASTS`.
|
||||
* - Add search-triggered page redirects to `SEARCH_ROUTES`.
|
||||
* - Add typed keyboard phrases to `KEYBOARD_SECRETS` or `LONG_KEYBOARD_SECRETS`.
|
||||
* - Add a new feature by writing an `addYourFeature(memory)` function and
|
||||
* adding it to the `FEATURES` list at the bottom of the file.
|
||||
*/
|
||||
|
||||
// Storage keys. v1 is read once so old visitors keep their hidden progress.
|
||||
const STORAGE_KEY = "zxh_hidden_details_v2";
|
||||
const OLD_STORAGE_KEY = "zxh_hidden_details_v1";
|
||||
|
||||
// Shared page context. These are captured once so daily random picks stay stable.
|
||||
const now = new Date();
|
||||
const hour = now.getHours();
|
||||
const path = window.location.pathname;
|
||||
const state = readState();
|
||||
// -----------------------------
|
||||
// EDITABLE CONTENT
|
||||
// -----------------------------
|
||||
// Generated by the hidden narrative authoring page.
|
||||
// Friendly source of truth: assets/content/hidden-details.json
|
||||
|
||||
const familyLayers = [];
|
||||
|
||||
const details = [];
|
||||
|
||||
const poems = [];
|
||||
|
||||
const greetings = [];
|
||||
|
||||
const nightMessages = [];
|
||||
|
||||
const lore = {
|
||||
"quotes": [],
|
||||
"conversations": [],
|
||||
"journals": [],
|
||||
"warnings": [],
|
||||
"dreams": [],
|
||||
"cassettes": [],
|
||||
"fakeUsers": [],
|
||||
"seasonal": {},
|
||||
"homepageTakeovers": [],
|
||||
"roomLinks": []
|
||||
};
|
||||
|
||||
// Exact search text -> toast message.
|
||||
const SEARCH_TOASTS = {};
|
||||
|
||||
// Exact search text -> hidden page route.
|
||||
const SEARCH_ROUTES = {};
|
||||
|
||||
// Short typed phrases. Stored in sessionStorage as a rolling key chain.
|
||||
const KEYBOARD_SECRETS = [];
|
||||
|
||||
// Longer typed phrases and character names.
|
||||
const LONG_KEYBOARD_SECRETS = [];
|
||||
|
||||
|
||||
// -----------------------------
|
||||
// STATE HELPERS
|
||||
// -----------------------------
|
||||
|
||||
function readState() {
|
||||
let current = {};
|
||||
try {
|
||||
current = JSON.parse(localStorage.getItem(STORAGE_KEY) || "{}");
|
||||
} catch (_) {}
|
||||
if (!current.visits) {
|
||||
try {
|
||||
const oldState = JSON.parse(localStorage.getItem(OLD_STORAGE_KEY) || "{}");
|
||||
current = { ...oldState, migratedFromV1: true };
|
||||
localStorage.setItem(STORAGE_KEY, JSON.stringify(current));
|
||||
} catch (_) {}
|
||||
}
|
||||
return current;
|
||||
}
|
||||
|
||||
function writeState(next) {
|
||||
try {
|
||||
localStorage.setItem(STORAGE_KEY, JSON.stringify(next));
|
||||
} catch (_) {}
|
||||
}
|
||||
|
||||
function pick(list, salt) {
|
||||
const seed = hash(`${path}|${now.toDateString()}|${salt || ""}`);
|
||||
return list[seed % list.length];
|
||||
}
|
||||
|
||||
function hash(value) {
|
||||
let h = 2166136261;
|
||||
for (let i = 0; i < value.length; i += 1) {
|
||||
h ^= value.charCodeAt(i);
|
||||
h = Math.imul(h, 16777619);
|
||||
}
|
||||
return Math.abs(h >>> 0);
|
||||
}
|
||||
|
||||
// -----------------------------
|
||||
// UI HELPERS
|
||||
// -----------------------------
|
||||
|
||||
function hiddenMessageMarkup(message) {
|
||||
return `<span class="hidden-message-text">${escapeHtml(message)}</span>`;
|
||||
}
|
||||
|
||||
function setHiddenMessage(el, message) {
|
||||
delete el.dataset.hiddenCharacter;
|
||||
el.innerHTML = hiddenMessageMarkup(message);
|
||||
}
|
||||
|
||||
function toast(message, duration) {
|
||||
let el = document.querySelector(".hidden-toast");
|
||||
if (!el) {
|
||||
el = document.createElement("div");
|
||||
el.className = "hidden-toast";
|
||||
el.setAttribute("role", "status");
|
||||
document.body.appendChild(el);
|
||||
}
|
||||
setHiddenMessage(el, message);
|
||||
el.classList.add("is-visible");
|
||||
window.clearTimeout(el._timer);
|
||||
el._timer = window.setTimeout(() => el.classList.remove("is-visible"), duration || 5600);
|
||||
}
|
||||
|
||||
function redirectTo(route) {
|
||||
window.location.href = route;
|
||||
}
|
||||
|
||||
function runSecretAction(secret) {
|
||||
if (secret.route) redirectTo(secret.route);
|
||||
if (secret.message) toast(secret.message);
|
||||
if (secret.song) playTinySong();
|
||||
}
|
||||
|
||||
function layerForSearch(value) {
|
||||
if (value.includes("future")) return 4;
|
||||
if (value.includes("sensei") || value.includes("aphy")) return 3;
|
||||
return 2;
|
||||
}
|
||||
|
||||
function rememberVisit() {
|
||||
const visits = (state.visits || 0) + 1;
|
||||
const seen = Array.isArray(state.seen) ? state.seen : [];
|
||||
const pathCounts = { ...(state.pathCounts || {}) };
|
||||
pathCounts[path] = (pathCounts[path] || 0) + 1;
|
||||
const layerVisits = { ...(state.layerVisits || {}) };
|
||||
const next = {
|
||||
...state,
|
||||
visits,
|
||||
lastPath: path,
|
||||
pathCounts,
|
||||
layerVisits,
|
||||
seen: Array.from(new Set([...seen, path])).slice(-100),
|
||||
firstSeen: state.firstSeen || new Date().toISOString(),
|
||||
lastSeen: new Date().toISOString()
|
||||
};
|
||||
writeState(next);
|
||||
return next;
|
||||
}
|
||||
|
||||
function awardLayer(layer, reason) {
|
||||
const next = readState();
|
||||
next.layerVisits = { ...(next.layerVisits || {}) };
|
||||
next.layerVisits[layer] = (next.layerVisits[layer] || 0) + 1;
|
||||
next.lastLayerReason = reason;
|
||||
writeState(next);
|
||||
}
|
||||
|
||||
// -----------------------------
|
||||
// GLOBAL FEATURES
|
||||
// -----------------------------
|
||||
|
||||
function addFooterNote(memory) {
|
||||
const footer = document.querySelector("footer");
|
||||
if (!footer || !details.length) return;
|
||||
const note = document.createElement("p");
|
||||
note.className = "hidden-footer-note";
|
||||
const base = pick(details, "footer");
|
||||
setHiddenMessage(note, memory.visits > 4 ? `${base} You have passed through ${memory.visits} times.` : base);
|
||||
footer.appendChild(note);
|
||||
}
|
||||
|
||||
function addHomepageGreeting(memory) {
|
||||
const target = document.querySelector("#db-greeting");
|
||||
if (!target || !greetings.length) return;
|
||||
setHiddenMessage(target, pick(greetings, `greeting-${memory.visits}`));
|
||||
const extra = document.createElement("p");
|
||||
extra.className = "hidden-greeting";
|
||||
setHiddenMessage(extra, "");
|
||||
target.closest("div")?.appendChild(extra);
|
||||
}
|
||||
|
||||
function addWhispers() {
|
||||
// Event: click one of the tiny "?" marks appended to long paragraphs.
|
||||
const paragraphs = Array.from(document.querySelectorAll("main p, #content p, article p")).filter((p) => p.textContent.trim().length > 80);
|
||||
paragraphs.slice(0, 5).forEach((p, index) => {
|
||||
if ((hash(path + index) + index) % 3 !== 0) return;
|
||||
const mark = document.createElement("span");
|
||||
mark.className = "hidden-whisper";
|
||||
mark.tabIndex = 0;
|
||||
mark.textContent = " ?";
|
||||
const source = index % 2 ? poems : details;
|
||||
if (!source.length) return;
|
||||
mark.title = pick(source, `whisper-${index}`);
|
||||
mark.addEventListener("click", () => {
|
||||
awardLayer(index % 2 ? 2 : 1, "paragraph whisper");
|
||||
toast(mark.title);
|
||||
});
|
||||
p.appendChild(mark);
|
||||
});
|
||||
}
|
||||
|
||||
function addCornerObject() {
|
||||
// Event: click the small fixed button in the bottom-left corner.
|
||||
const object = document.createElement("button");
|
||||
object.className = "hidden-corner-object";
|
||||
object.type = "button";
|
||||
object.title = "hidden interaction";
|
||||
object.textContent = state.visits % 2 ? "*" : "~";
|
||||
document.body.appendChild(object);
|
||||
let clicks = 0;
|
||||
object.addEventListener("click", () => {
|
||||
clicks += 1;
|
||||
awardLayer(clicks > 3 ? 3 : 1, "corner object");
|
||||
toast("Hidden interaction recorded.");
|
||||
if (clicks === 7) window.location.href = "/play/left-behind.html";
|
||||
});
|
||||
}
|
||||
|
||||
function addLogoSearchAndKeyboardSecrets(memory) {
|
||||
// Events:
|
||||
// - Click `.site-brand` repeatedly on the homepage.
|
||||
// - Type exact words into `#search-input`.
|
||||
// - Type phrases anywhere on the page.
|
||||
const nav = document.querySelector(".site-brand");
|
||||
if (nav) {
|
||||
let taps = Number(sessionStorage.getItem("zxh_logo_taps") || 0);
|
||||
nav.addEventListener("click", (event) => {
|
||||
if (path === "/" || path === "/index.html") {
|
||||
event.preventDefault();
|
||||
taps += 1;
|
||||
sessionStorage.setItem("zxh_logo_taps", String(taps));
|
||||
awardLayer(taps >= 5 ? 3 : 1, "logo taps");
|
||||
toast(taps >= 5 ? "Hidden route available: /play/dream-corridor.html" : "Hidden interaction recorded.");
|
||||
if (taps >= 8) window.location.href = "/play/dream-corridor.html";
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
const search = document.querySelector("#search-input");
|
||||
if (search) {
|
||||
search.addEventListener("input", () => {
|
||||
const value = search.value.trim().toLowerCase();
|
||||
if (SEARCH_TOASTS[value]) toast(SEARCH_TOASTS[value]);
|
||||
if (SEARCH_ROUTES[value]) {
|
||||
awardLayer(layerForSearch(value), `search ${value}`);
|
||||
redirectTo(SEARCH_ROUTES[value]);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
document.addEventListener("keydown", (event) => {
|
||||
const key = event.key.toLowerCase();
|
||||
const chain = `${sessionStorage.getItem("zxh_key_chain") || ""}${key}`.slice(-18);
|
||||
sessionStorage.setItem("zxh_key_chain", chain);
|
||||
KEYBOARD_SECRETS
|
||||
.filter((secret) => chain.endsWith(secret.phrase))
|
||||
.forEach(runSecretAction);
|
||||
});
|
||||
|
||||
if (memory.seen?.length >= 6 && !state.travellerNoteShown) {
|
||||
window.setTimeout(() => {
|
||||
toast("Hidden path recorded.");
|
||||
writeState({ ...readState(), travellerNoteShown: true });
|
||||
}, 1600);
|
||||
}
|
||||
}
|
||||
|
||||
function addRareEvents() {
|
||||
if (hour >= 22 || hour < 5) {
|
||||
document.body.classList.add("hidden-late-night");
|
||||
if (nightMessages.length) window.setTimeout(() => toast(pick(nightMessages, "night"), 2200), 900);
|
||||
}
|
||||
const roll = Math.random();
|
||||
if (roll < 0.003) {
|
||||
window.setTimeout(() => showDriftNote("", ""), 1800);
|
||||
awardLayer(3, "rare sensei appearance");
|
||||
} else if (roll < 0.008) {
|
||||
window.setTimeout(() => toast("Hidden warning."), 2400);
|
||||
awardLayer(4, "future warning");
|
||||
}
|
||||
}
|
||||
|
||||
function showDriftNote(text, art) {
|
||||
const panel = document.createElement("aside");
|
||||
panel.className = "hidden-drift-note";
|
||||
panel.innerHTML = `<div class="hidden-drift-message">${hiddenMessageMarkup(text)}</div><pre>${escapeHtml(art)}</pre><button type="button">Close</button>`;
|
||||
panel.querySelector("button").addEventListener("click", () => panel.remove());
|
||||
document.body.appendChild(panel);
|
||||
}
|
||||
|
||||
function addSecretLinks() {
|
||||
[
|
||||
["/play/left-behind.html", "left behind"],
|
||||
["/play/dream-corridor.html", "dream corridor"],
|
||||
["/play/kitchen-light.html", "kitchen light"],
|
||||
...lore.roomLinks
|
||||
].forEach(([href, label], index) => {
|
||||
const link = document.createElement("a");
|
||||
link.className = "hidden-secret-link";
|
||||
link.href = href;
|
||||
link.textContent = label;
|
||||
link.style.left = `${index + 1}px`;
|
||||
document.body.appendChild(link);
|
||||
});
|
||||
}
|
||||
|
||||
function enhanceErrors() {
|
||||
if (document.title.match(/404|not found/i) || document.body.textContent.match(/404|not found/i)) {
|
||||
toast("Page not found.");
|
||||
}
|
||||
}
|
||||
|
||||
function addContinuity(memory) {
|
||||
const milestones = {
|
||||
64: "Hidden layer unlocked."
|
||||
};
|
||||
if (milestones[memory.visits] && !state[`milestone_${memory.visits}`]) {
|
||||
const layer = memory.visits >= 31 ? 4 : memory.visits >= 9 ? 3 : 2;
|
||||
awardLayer(layer, `visit milestone ${memory.visits}`);
|
||||
window.setTimeout(() => toast(milestones[memory.visits], 7000), 1200);
|
||||
writeState({ ...readState(), [`milestone_${memory.visits}`]: true });
|
||||
}
|
||||
|
||||
const count = memory.pathCounts?.[path] || 0;
|
||||
if ([3, 7, 12].includes(count)) {
|
||||
window.setTimeout(() => toast("Page revisit recorded.", 6400), 1700);
|
||||
}
|
||||
}
|
||||
|
||||
function addSeasonAndDates(memory) {
|
||||
const month = now.getMonth();
|
||||
const day = now.getDate();
|
||||
const season = month < 2 || month === 11 ? "winter" : month < 5 ? "spring" : month < 8 ? "summer" : "autumn";
|
||||
if (Math.random() < 0.18 && lore.seasonal[season]) window.setTimeout(() => toast(lore.seasonal[season], 5600), 2600);
|
||||
const first = memory.firstSeen ? new Date(memory.firstSeen) : null;
|
||||
if (first && memory.visits > 1 && first.getMonth() === month && first.getDate() === day) {
|
||||
window.setTimeout(() => toast("Visitor anniversary recorded.", 7000), 1400);
|
||||
}
|
||||
}
|
||||
|
||||
function addObjectConstellation() {
|
||||
// Event: click the small keepsake buttons along the bottom rail.
|
||||
const rail = document.createElement("div");
|
||||
rail.className = "hidden-object-rail";
|
||||
rail.setAttribute("aria-label", "Hidden objects");
|
||||
const objects = [
|
||||
["ring", "Hidden object recorded."],
|
||||
["bot", "Hidden object recorded."],
|
||||
["tea", "Hidden object recorded."],
|
||||
["crayon", "Hidden object recorded."],
|
||||
["clock", "Hidden object recorded."]
|
||||
];
|
||||
objects.forEach(([name, message]) => {
|
||||
const button = document.createElement("button");
|
||||
button.type = "button";
|
||||
button.className = `hidden-keepsake hidden-keepsake--${name}`;
|
||||
button.title = name;
|
||||
button.textContent = { ring: "o", bot: "#", tea: "u", crayon: "/", clock: ":" }[name];
|
||||
button.addEventListener("click", () => {
|
||||
const next = readState();
|
||||
next.keepsakes = Array.from(new Set([...(next.keepsakes || []), name]));
|
||||
writeState(next);
|
||||
awardLayer(next.keepsakes.length >= 3 ? 3 : 2, `keepsake ${name}`);
|
||||
toast(message);
|
||||
if (next.keepsakes.length >= objects.length) {
|
||||
window.setTimeout(() => toast("Hidden object set completed."), 1100);
|
||||
}
|
||||
});
|
||||
rail.appendChild(button);
|
||||
});
|
||||
document.body.appendChild(rail);
|
||||
}
|
||||
|
||||
function addWeatherWindow(memory) {
|
||||
// Event: click the small "window" button. This asks for browser geolocation.
|
||||
if (memory.visits < 3 || !("geolocation" in navigator)) return;
|
||||
const button = document.createElement("button");
|
||||
button.className = "hidden-weather-window";
|
||||
button.type = "button";
|
||||
button.title = "Check outside weather";
|
||||
button.textContent = "window";
|
||||
button.addEventListener("click", () => {
|
||||
toast("Checking outside weather.");
|
||||
navigator.geolocation.getCurrentPosition((pos) => {
|
||||
const { latitude, longitude } = pos.coords;
|
||||
fetch(`https://api.open-meteo.com/v1/forecast?latitude=${latitude.toFixed(3)}&longitude=${longitude.toFixed(3)}¤t=temperature_2m,precipitation&timezone=auto`)
|
||||
.then((res) => res.json())
|
||||
.then((data) => {
|
||||
const current = data.current || {};
|
||||
const rain = Number(current.precipitation || 0) > 0;
|
||||
const temp = Math.round(Number(current.temperature_2m));
|
||||
toast(rain ? `Outside: rain, ${temp}C.` : `Outside: ${temp}C.`);
|
||||
})
|
||||
.catch(() => toast("Weather check failed."));
|
||||
}, () => toast("No outside weather today."));
|
||||
});
|
||||
document.body.appendChild(button);
|
||||
}
|
||||
|
||||
function addOldWebLayer(memory) {
|
||||
if (Math.random() < 0.08 || memory.visits > 10) {
|
||||
const stamp = document.createElement("div");
|
||||
stamp.className = "hidden-oldweb-stamp";
|
||||
if (!lore.fakeUsers.length) return;
|
||||
stamp.title = pick(lore.fakeUsers, "fake-user");
|
||||
stamp.textContent = "best viewed with patience";
|
||||
stamp.addEventListener("click", () => {
|
||||
awardLayer(1, "old web stamp");
|
||||
toast(stamp.title);
|
||||
});
|
||||
document.body.appendChild(stamp);
|
||||
}
|
||||
const comments = document.querySelector("#comments");
|
||||
if (comments && lore.fakeUsers.length && !comments.querySelector(".hidden-guestbook-line")) {
|
||||
const line = document.createElement("p");
|
||||
line.className = "hidden-guestbook-line";
|
||||
setHiddenMessage(line, pick(lore.fakeUsers, "comment-lore"));
|
||||
comments.appendChild(line);
|
||||
}
|
||||
}
|
||||
|
||||
function addSourceRelics() {
|
||||
const marker = document.createComment("hidden-details");
|
||||
document.documentElement.appendChild(marker);
|
||||
document.querySelectorAll("img[alt=''], img:not([alt])").forEach((img, index) => {
|
||||
if (index > 2) return;
|
||||
img.alt = "Decorative image.";
|
||||
});
|
||||
}
|
||||
|
||||
function addLongKeyboardSecrets() {
|
||||
// Event: type longer hidden phrases anywhere on the page.
|
||||
document.addEventListener("keydown", (event) => {
|
||||
const chain = `${sessionStorage.getItem("zxh_second_chain") || ""}${event.key.toLowerCase()}`.slice(-24);
|
||||
sessionStorage.setItem("zxh_second_chain", chain);
|
||||
LONG_KEYBOARD_SECRETS
|
||||
.filter((secret) => chain.endsWith(secret.phrase))
|
||||
.forEach(runSecretAction);
|
||||
});
|
||||
}
|
||||
|
||||
function addPatienceRewards(memory) {
|
||||
// Event: no movement, key presses, scrolling, or clicking for 90 seconds.
|
||||
if (memory.visits < 2) return;
|
||||
let idleTimer = null;
|
||||
const startIdle = () => {
|
||||
window.clearTimeout(idleTimer);
|
||||
idleTimer = window.setTimeout(() => {
|
||||
awardLayer(5, "patience");
|
||||
toast("Idle moment recorded.", 7600);
|
||||
const next = readState();
|
||||
next.patientMoments = (next.patientMoments || 0) + 1;
|
||||
writeState(next);
|
||||
}, 90000);
|
||||
};
|
||||
["mousemove", "keydown", "scroll", "click"].forEach((name) => document.addEventListener(name, startIdle, { passive: true }));
|
||||
startIdle();
|
||||
}
|
||||
|
||||
function addRareSecondLayer() {
|
||||
const roll = Math.random();
|
||||
if ((path === "/" || path === "/index.html") && roll < 0.006) {
|
||||
document.body.classList.add("hidden-home-takeover");
|
||||
if (lore.homepageTakeovers.length) window.setTimeout(() => showDriftNote(pick(lore.homepageTakeovers, "takeover"), ""), 600);
|
||||
} else if (roll < 0.002) {
|
||||
window.setTimeout(() => showDriftNote("", ""), 1500);
|
||||
} else if (roll < 0.006) {
|
||||
if (lore.dreams.length) window.setTimeout(() => toast(pick(lore.dreams, "rare-dream"), 7600), 2000);
|
||||
} else if (roll < 0.014) {
|
||||
if (lore.warnings.length) window.setTimeout(() => toast(pick(lore.warnings, "rare-warning"), 6800), 2300);
|
||||
}
|
||||
}
|
||||
|
||||
function addFamilyLayerIndex(memory) {
|
||||
if (!path.includes("/play/family-layer-index")) return;
|
||||
const target = document.querySelector("[data-family-layer-index]");
|
||||
if (!target) return;
|
||||
const visits = readState().layerVisits || {};
|
||||
target.innerHTML = familyLayers.map((line, layer) => {
|
||||
const count = visits[layer] || 0;
|
||||
return `<li class="hidden-layer-message"><strong>${hiddenMessageMarkup(line)}</strong><br><span>local encounters: ${count}</span></li>`;
|
||||
}).join("");
|
||||
}
|
||||
|
||||
function addPageSpecificSecrets() {
|
||||
// Events only used by specific `/play/...` pages.
|
||||
if (path.includes("/play/cassette-log")) {
|
||||
document.querySelectorAll("[data-cassette]").forEach((button, index) => {
|
||||
button.addEventListener("click", () => {
|
||||
awardLayer(index >= 2 ? 4 : 2, "voice note");
|
||||
if (lore.cassettes.length) toast(lore.cassettes[index % lore.cassettes.length], 7600);
|
||||
playTinySong();
|
||||
});
|
||||
});
|
||||
}
|
||||
if (path.includes("/play/patience-game")) {
|
||||
const target = document.querySelector("[data-patience-target]");
|
||||
const count = document.querySelector("[data-patience-count]");
|
||||
if (target && count) {
|
||||
let seconds = 0;
|
||||
setInterval(() => {
|
||||
seconds += 1;
|
||||
count.textContent = String(seconds);
|
||||
if ([30, 90, 180].includes(seconds)) {
|
||||
setHiddenMessage(target, "Patience milestone recorded.");
|
||||
}
|
||||
}, 1000);
|
||||
}
|
||||
}
|
||||
if (path.includes("/play/terminal-cupboard")) {
|
||||
const input = document.querySelector("[data-cupboard-input]");
|
||||
const log = document.querySelector("[data-cupboard-log]");
|
||||
const commands = {
|
||||
help: "commands: layer, exit",
|
||||
layer: familyLayers.join("\n"),
|
||||
exit: "Closed."
|
||||
};
|
||||
input?.addEventListener("keydown", (event) => {
|
||||
if (event.key !== "Enter") return;
|
||||
const value = input.value.trim().toLowerCase();
|
||||
const line = document.createElement("p");
|
||||
setHiddenMessage(line, `> ${value}\n${commands[value] || "Unknown command."}`);
|
||||
log.appendChild(line);
|
||||
input.value = "";
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
function addInvisibleHoverSecrets() {
|
||||
document.querySelectorAll("h1, h2").forEach((heading, index) => {
|
||||
if (index > 5) return;
|
||||
heading.classList.add("hidden-hover-memory");
|
||||
const source = [...lore.quotes, ...lore.journals, ...poems];
|
||||
if (!source.length) return;
|
||||
heading.dataset.hiddenMemory = pick(source, `heading-${index}`);
|
||||
});
|
||||
}
|
||||
|
||||
function playTinySong() {
|
||||
try {
|
||||
const AudioContext = window.AudioContext || window.webkitAudioContext;
|
||||
if (!AudioContext) return;
|
||||
const ctx = new AudioContext();
|
||||
const notes = [392, 494, 440, 330, 392];
|
||||
notes.forEach((freq, index) => {
|
||||
const osc = ctx.createOscillator();
|
||||
const gain = ctx.createGain();
|
||||
osc.frequency.value = freq;
|
||||
osc.type = "sine";
|
||||
gain.gain.setValueAtTime(0.0001, ctx.currentTime + index * 0.18);
|
||||
gain.gain.exponentialRampToValueAtTime(0.05, ctx.currentTime + index * 0.18 + 0.03);
|
||||
gain.gain.exponentialRampToValueAtTime(0.0001, ctx.currentTime + index * 0.18 + 0.16);
|
||||
osc.connect(gain);
|
||||
gain.connect(ctx.destination);
|
||||
osc.start(ctx.currentTime + index * 0.18);
|
||||
osc.stop(ctx.currentTime + index * 0.18 + 0.18);
|
||||
});
|
||||
} catch (_) {}
|
||||
}
|
||||
|
||||
function escapeHtml(value) {
|
||||
return String(value).replace(/[&<>"']/g, (char) => ({
|
||||
"&": "&",
|
||||
"<": "<",
|
||||
">": ">",
|
||||
'"': """,
|
||||
"'": "'"
|
||||
}[char]));
|
||||
}
|
||||
|
||||
// Features run in this order on every page after the DOM is ready.
|
||||
// Each function receives the current `memory` object.
|
||||
const FEATURES = [
|
||||
addFooterNote,
|
||||
addHomepageGreeting,
|
||||
addWhispers,
|
||||
addCornerObject,
|
||||
addLogoSearchAndKeyboardSecrets,
|
||||
addRareEvents,
|
||||
addSecretLinks,
|
||||
enhanceErrors,
|
||||
addContinuity,
|
||||
addSeasonAndDates,
|
||||
addObjectConstellation,
|
||||
addWeatherWindow,
|
||||
addOldWebLayer,
|
||||
addSourceRelics,
|
||||
addLongKeyboardSecrets,
|
||||
addPatienceRewards,
|
||||
addRareSecondLayer,
|
||||
addFamilyLayerIndex,
|
||||
addPageSpecificSecrets,
|
||||
addInvisibleHoverSecrets
|
||||
];
|
||||
|
||||
document.addEventListener("DOMContentLoaded", () => {
|
||||
const memory = rememberVisit();
|
||||
FEATURES.forEach((addFeature) => addFeature(memory));
|
||||
});
|
||||
}());
|
||||
@@ -1,315 +1,7 @@
|
||||
document.addEventListener('DOMContentLoaded', () => {
|
||||
if (typeof window.BiggerPicture !== 'function') {
|
||||
console.error('[gallery-init] BiggerPicture not found. Check script path.');
|
||||
return;
|
||||
}
|
||||
const VIDEO_EXTENSIONS = ['mp4', 'webm', 'mov', 'm4v', 'ogv'];
|
||||
|
||||
const isVideo = (href) => {
|
||||
if (!href) return false;
|
||||
href = href.toLowerCase();
|
||||
return VIDEO_EXTENSIONS.some(ext => href.endsWith('.' + ext));
|
||||
};
|
||||
|
||||
// 1b) Convert MP4 links into inline <video> players
|
||||
// Convert video links into inline <video> players BUT keep the <a>
|
||||
const videoLinks = document.querySelectorAll('a[href]');
|
||||
videoLinks.forEach(a => {
|
||||
const href = a.getAttribute("href");
|
||||
if (!isVideo(href)) return;
|
||||
|
||||
const video = document.createElement("video");
|
||||
video.controls = true;
|
||||
video.preload = "metadata";
|
||||
video.style.maxWidth = "100%";
|
||||
video.style.borderRadius = "6px";
|
||||
|
||||
const source = document.createElement("source");
|
||||
source.src = href;
|
||||
source.type = "video/" + href.split('.').pop(); // guesses correct mime
|
||||
video.appendChild(source);
|
||||
|
||||
// Replace the link with the inline video
|
||||
a.parentNode.replaceChild(video, a);
|
||||
});
|
||||
|
||||
// 1) Wrap Org-exported images so they’re clickable
|
||||
const imgs = document.querySelectorAll('.figure img, img.org-svg');
|
||||
imgs.forEach((img) => {
|
||||
if (img.closest('a')) return; // already wrapped
|
||||
const a = document.createElement('a');
|
||||
const href = img.currentSrc || img.src;
|
||||
a.href = href;
|
||||
a.dataset.img = href; // lets BP pre-size/raster slides
|
||||
a.dataset.alt = img.alt || '';
|
||||
const setDims = () => {
|
||||
a.dataset.width = img.naturalWidth || img.width || 1920;
|
||||
a.dataset.height = img.naturalHeight || img.height || 1080;
|
||||
};
|
||||
if (img.complete) setDims(); else img.addEventListener('load', setDims);
|
||||
img.style.cursor = 'zoom-in';
|
||||
img.parentElement.insertBefore(a, img);
|
||||
a.appendChild(img);
|
||||
});
|
||||
|
||||
// 2) One global BP instance
|
||||
const bp = BiggerPicture({ target: document.body });
|
||||
|
||||
// SVG pan/zoom handle
|
||||
let activePanZoom = null;
|
||||
const destroyPanZoom = () => { try { activePanZoom?.destroy(); } catch(_){} activePanZoom = null; };
|
||||
|
||||
// Simple rotate state (for non-SVG images)
|
||||
let activeContainer = null;
|
||||
let currentRotation = 0;
|
||||
let rotateControls = null;
|
||||
|
||||
// 3) Build galleries per content container
|
||||
const containers = document.querySelectorAll('main, article, .content, body');
|
||||
containers.forEach((container) => {
|
||||
const links = Array.from(container.querySelectorAll(
|
||||
'.figure a, a:has(img.org-svg), a[href$=".mp4"], a[href$=".webm"], a[href$=".mov"], a[href$=".m4v"], a[href$=".ogv"]'
|
||||
));
|
||||
if (!links.length) return;
|
||||
|
||||
// Start the lightbox on click
|
||||
links.forEach((link, index) => {
|
||||
link.addEventListener('click', (e) => {
|
||||
e.preventDefault();
|
||||
document.querySelectorAll(".theme-toggle").forEach(el => {
|
||||
el.classList.add("hidden");
|
||||
});
|
||||
|
||||
bp.open({
|
||||
// IMPORTANT: pass the anchor ELEMENTS, not custom objects
|
||||
items: links,
|
||||
el: link,
|
||||
caption: (el) => el.querySelector('img')?.alt || el.title || '',
|
||||
maxZoom: 40, // for raster images (PNG/JPG); SVG handled separately
|
||||
|
||||
// Fade-out polish + cleanup
|
||||
onClose(containerEl) {
|
||||
destroyPanZoom();
|
||||
teardownRotation();
|
||||
if (containerEl) containerEl.classList.add('bp-fadeout');
|
||||
const themeToggle = document.querySelector(".theme-toggle");
|
||||
if (themeToggle) {
|
||||
themeToggle.classList.remove("hidden");
|
||||
}
|
||||
},
|
||||
|
||||
// Called once after open and on every slide change
|
||||
//onOpen(containerEl) { setupRotation(containerEl); enhanceSVG(containerEl); }
|
||||
onOpen(containerEl) {
|
||||
const linkEl = bp.currItem;
|
||||
const href = linkEl?.href || "";
|
||||
|
||||
if (href.endsWith(".mp4")) {
|
||||
// Turn off image rotation (not applicable for video)
|
||||
teardownRotation();
|
||||
|
||||
const htmlLayer = containerEl.querySelector(".bp-html");
|
||||
const imgLayer = containerEl.querySelector(".bp-img");
|
||||
|
||||
if (!htmlLayer) return;
|
||||
|
||||
// Hide the default image layer
|
||||
if (imgLayer) imgLayer.style.display = "none";
|
||||
|
||||
// Insert video player
|
||||
htmlLayer.innerHTML = `
|
||||
<video controls autoplay style="max-width:95vw; max-height:95vh">
|
||||
<source src="${href}" type="video/mp4">
|
||||
</video>
|
||||
`;
|
||||
|
||||
return; // Do not run image/SVG enhancements
|
||||
}
|
||||
|
||||
// Image behaviour
|
||||
setupRotation(containerEl);
|
||||
enhanceSVG(containerEl);
|
||||
} ,
|
||||
onUpdate(containerEl){ setupRotation(containerEl); enhanceSVG(containerEl); }
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
// 4) Simple rotate buttons for raster images
|
||||
function ensureRotateControls() {
|
||||
if (rotateControls) return rotateControls;
|
||||
|
||||
const wrapper = document.createElement('div');
|
||||
wrapper.className = 'bp-rotate-controls';
|
||||
Object.assign(wrapper.style, {
|
||||
position: 'fixed',
|
||||
bottom: '1.5rem',
|
||||
right: '1.5rem',
|
||||
display: 'flex',
|
||||
gap: '0.5rem',
|
||||
zIndex: '9999',
|
||||
pointerEvents: 'auto'
|
||||
});
|
||||
|
||||
const mkBtn = (label, title) => {
|
||||
const btn = document.createElement('button');
|
||||
btn.type = 'button';
|
||||
btn.textContent = label;
|
||||
btn.title = title;
|
||||
btn.setAttribute('aria-label', title);
|
||||
Object.assign(btn.style, {
|
||||
padding: '0.4rem 0.6rem',
|
||||
borderRadius: '999px',
|
||||
border: 'none',
|
||||
fontSize: '1.2rem',
|
||||
cursor: 'pointer',
|
||||
background: 'rgba(30,30,30,0.8)',
|
||||
color: '#fff'
|
||||
});
|
||||
return btn;
|
||||
};
|
||||
|
||||
const left = mkBtn('⟲', 'Rotate image 90° left');
|
||||
const right = mkBtn('⟳', 'Rotate image 90° right');
|
||||
|
||||
left.addEventListener('click', (e) => {
|
||||
e.stopPropagation(); // don’t close the lightbox
|
||||
if (!activeContainer) return;
|
||||
currentRotation = (currentRotation - 90 + 360) % 360;
|
||||
applyRotation();
|
||||
});
|
||||
|
||||
right.addEventListener('click', (e) => {
|
||||
e.stopPropagation();
|
||||
if (!activeContainer) return;
|
||||
currentRotation = (currentRotation + 90) % 360;
|
||||
applyRotation();
|
||||
});
|
||||
|
||||
wrapper.append(left, right);
|
||||
document.body.appendChild(wrapper);
|
||||
rotateControls = wrapper;
|
||||
return rotateControls;
|
||||
}
|
||||
|
||||
function ensureRotateWrapper() {
|
||||
if (!activeContainer) return null;
|
||||
|
||||
const imgRoot = activeContainer.querySelector('.bp-img');
|
||||
if (!imgRoot) return null;
|
||||
|
||||
let imgEl = imgRoot.querySelector('img');
|
||||
if (!imgEl) return null;
|
||||
|
||||
const src = (imgEl.currentSrc || imgEl.src || '').toLowerCase();
|
||||
// We only rotate raster images; SVGs are handled via svg-pan-zoom
|
||||
if (src.endsWith('.svg')) return null;
|
||||
|
||||
let wrapper = imgRoot.querySelector('.bp-rotate-wrapper');
|
||||
if (!wrapper) {
|
||||
wrapper = document.createElement('div');
|
||||
wrapper.className = 'bp-rotate-wrapper';
|
||||
wrapper.style.display = 'inline-block';
|
||||
wrapper.style.transformOrigin = 'center center';
|
||||
|
||||
imgRoot.appendChild(wrapper);
|
||||
wrapper.appendChild(imgEl);
|
||||
} else if (!wrapper.contains(imgEl)) {
|
||||
// Slide changed and BiggerPicture replaced the <img>
|
||||
wrapper.innerHTML = '';
|
||||
wrapper.appendChild(imgEl);
|
||||
}
|
||||
|
||||
return wrapper;
|
||||
}
|
||||
|
||||
function applyRotation() {
|
||||
const wrapper = ensureRotateWrapper();
|
||||
if (!wrapper) return;
|
||||
wrapper.style.transform = `rotate(${currentRotation}deg)`;
|
||||
}
|
||||
|
||||
function setupRotation(containerEl) {
|
||||
activeContainer = containerEl;
|
||||
currentRotation = 0;
|
||||
const controls = ensureRotateControls();
|
||||
controls.style.display = 'flex';
|
||||
applyRotation();
|
||||
}
|
||||
|
||||
function teardownRotation() {
|
||||
activeContainer = null;
|
||||
currentRotation = 0;
|
||||
if (rotateControls) {
|
||||
rotateControls.style.display = 'none';
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// 4) If current slide is an SVG, swap to inline + enable svg-pan-zoom
|
||||
async function enhanceSVG(containerEl) {
|
||||
try {
|
||||
destroyPanZoom();
|
||||
|
||||
const imgEl = containerEl.querySelector('.bp-img img');
|
||||
if (!imgEl) return;
|
||||
|
||||
const src = imgEl.currentSrc || imgEl.src || '';
|
||||
const isSVG = src.toLowerCase().endsWith('.svg');
|
||||
const htmlLayer = containerEl.querySelector('.bp-html');
|
||||
if (!isSVG || !htmlLayer) {
|
||||
// ensure any previous holder is removed and bitmap is visible
|
||||
const old = htmlLayer?.querySelector('.bp-svg-holder');
|
||||
if (old) old.remove();
|
||||
imgEl.style.visibility = '';
|
||||
return;
|
||||
}
|
||||
|
||||
// Create/clear holder
|
||||
let holder = htmlLayer.querySelector('.bp-svg-holder');
|
||||
if (!holder) {
|
||||
holder = document.createElement('div');
|
||||
holder.className = 'bp-svg-holder';
|
||||
holder.style.maxWidth = '95vw';
|
||||
holder.style.maxHeight = '95vh';
|
||||
htmlLayer.appendChild(holder);
|
||||
}
|
||||
holder.innerHTML = '';
|
||||
|
||||
// Hide the bitmap so only the inline SVG shows
|
||||
imgEl.style.visibility = 'hidden';
|
||||
|
||||
// Inline the SVG
|
||||
const res = await fetch(src, { cache: 'force-cache' });
|
||||
const text = await res.text();
|
||||
holder.innerHTML = text;
|
||||
|
||||
const svg = holder.querySelector('svg');
|
||||
if (!svg) { imgEl.style.visibility = ''; return; }
|
||||
|
||||
svg.style.maxWidth = '95vw';
|
||||
svg.style.maxHeight = '95vh';
|
||||
svg.style.display = 'block';
|
||||
|
||||
if (typeof window.svgPanZoom === 'function') {
|
||||
activePanZoom = svgPanZoom(svg, {
|
||||
zoomEnabled: true,
|
||||
controlIconsEnabled: true,
|
||||
fit: true,
|
||||
center: true,
|
||||
minZoom: 0.05,
|
||||
maxZoom: 400, // effectively "unlimited"
|
||||
zoomScaleSensitivity: 0.25,
|
||||
dblClickZoomEnabled: true
|
||||
});
|
||||
// Keep wheel inside lightbox
|
||||
holder.addEventListener('wheel', (e) => e.stopPropagation(), { passive: true });
|
||||
} else {
|
||||
console.warn('[gallery-init] svg-pan-zoom not loaded');
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('[gallery-init] SVG enhance failed:', err);
|
||||
}
|
||||
}
|
||||
});
|
||||
(function () {
|
||||
"use strict";
|
||||
var script = document.createElement("script");
|
||||
script.src = "/assets/scripts/ui/gallery-init.js";
|
||||
script.defer = true;
|
||||
document.head.appendChild(script);
|
||||
}());
|
||||
|
||||
@@ -1,691 +1,7 @@
|
||||
(function () {
|
||||
"use strict";
|
||||
|
||||
/*
|
||||
* Hidden site details
|
||||
* -------------------
|
||||
* This file adds small hidden interactions across the site: footer notes,
|
||||
* click targets, search/keyboard secrets, rare messages, and page-specific
|
||||
* behavior for the hidden /play pages.
|
||||
*
|
||||
* How to add your own things:
|
||||
* - Add new text to EDITABLE CONTENT arrays such as `details`, `poems`,
|
||||
* `greetings`, or `lore`.
|
||||
* - Add search-triggered toast messages to `SEARCH_TOASTS`.
|
||||
* - Add search-triggered page redirects to `SEARCH_ROUTES`.
|
||||
* - Add typed keyboard phrases to `KEYBOARD_SECRETS` or `LONG_KEYBOARD_SECRETS`.
|
||||
* - Add a new feature by writing an `addYourFeature(memory)` function and
|
||||
* adding it to the `FEATURES` list at the bottom of the file.
|
||||
*/
|
||||
|
||||
// Storage keys. v1 is read once so old visitors keep their hidden progress.
|
||||
const STORAGE_KEY = "zxh_hidden_details_v2";
|
||||
const OLD_STORAGE_KEY = "zxh_hidden_details_v1";
|
||||
|
||||
// Shared page context. These are captured once so daily random picks stay stable.
|
||||
const now = new Date();
|
||||
const hour = now.getHours();
|
||||
const path = window.location.pathname;
|
||||
const state = readState();
|
||||
const CHARACTER_AVATARS = {
|
||||
"lima": {
|
||||
avatar: "/assets/avatars/lima.jpg",
|
||||
fallback: "/assets/avatars/z.jpeg",
|
||||
aliases: ["lima"],
|
||||
glow: "#f2c58b"
|
||||
},
|
||||
"aphy": {
|
||||
avatar: "/assets/avatars/aphy.jpeg",
|
||||
fallback: "/assets/avatars/z.jpeg",
|
||||
aliases: ["aphy"],
|
||||
glow: "#9dd3a6"
|
||||
},
|
||||
"sensei chi": {
|
||||
avatar: "/assets/avatars/sensei-chi.jpeg",
|
||||
fallback: "/assets/avatars/z.jpeg",
|
||||
aliases: ["sensei chi", "sensei"],
|
||||
glow: "#9ccddd"
|
||||
},
|
||||
"young z": {
|
||||
avatar: "/assets/avatars/young-z.jpeg",
|
||||
fallback: "/assets/avatars/z.jpeg",
|
||||
aliases: ["young z", "young"],
|
||||
glow: "#f0b85c"
|
||||
},
|
||||
"future z": {
|
||||
avatar: "/assets/avatars/future-z.jpeg",
|
||||
fallback: "/assets/avatars/z.jpeg",
|
||||
aliases: ["future z", "future"],
|
||||
glow: "#c2a4ee"
|
||||
},
|
||||
"z": {
|
||||
avatar: "/assets/avatars/z.jpeg",
|
||||
fallback: "/assets/avatars/z.jpeg",
|
||||
aliases: ["z", "zaine"],
|
||||
glow: "#ead68e"
|
||||
}
|
||||
};
|
||||
|
||||
// -----------------------------
|
||||
// EDITABLE CONTENT
|
||||
// -----------------------------
|
||||
// Generated by the hidden narrative authoring page.
|
||||
// Friendly source of truth: assets/content/hidden-details.json
|
||||
|
||||
const familyLayers = [];
|
||||
|
||||
const details = [];
|
||||
|
||||
const poems = [];
|
||||
|
||||
const greetings = [];
|
||||
|
||||
const nightMessages = [];
|
||||
|
||||
const lore = {
|
||||
"quotes": [],
|
||||
"conversations": [],
|
||||
"journals": [],
|
||||
"warnings": [],
|
||||
"dreams": [],
|
||||
"cassettes": [],
|
||||
"fakeUsers": [],
|
||||
"seasonal": {},
|
||||
"homepageTakeovers": [],
|
||||
"roomLinks": []
|
||||
};
|
||||
|
||||
// Exact search text -> toast message.
|
||||
const SEARCH_TOASTS = {};
|
||||
|
||||
// Exact search text -> hidden page route.
|
||||
const SEARCH_ROUTES = {};
|
||||
|
||||
// Short typed phrases. Stored in sessionStorage as a rolling key chain.
|
||||
const KEYBOARD_SECRETS = [];
|
||||
|
||||
// Longer typed phrases and character names.
|
||||
const LONG_KEYBOARD_SECRETS = [];
|
||||
|
||||
|
||||
// -----------------------------
|
||||
// STATE HELPERS
|
||||
// -----------------------------
|
||||
|
||||
function readState() {
|
||||
let current = {};
|
||||
try {
|
||||
current = JSON.parse(localStorage.getItem(STORAGE_KEY) || "{}");
|
||||
} catch (_) {}
|
||||
if (!current.visits) {
|
||||
try {
|
||||
const oldState = JSON.parse(localStorage.getItem(OLD_STORAGE_KEY) || "{}");
|
||||
current = { ...oldState, migratedFromV1: true };
|
||||
localStorage.setItem(STORAGE_KEY, JSON.stringify(current));
|
||||
} catch (_) {}
|
||||
}
|
||||
return current;
|
||||
}
|
||||
|
||||
function writeState(next) {
|
||||
try {
|
||||
localStorage.setItem(STORAGE_KEY, JSON.stringify(next));
|
||||
} catch (_) {}
|
||||
}
|
||||
|
||||
function pick(list, salt) {
|
||||
const seed = hash(`${path}|${now.toDateString()}|${salt || ""}`);
|
||||
return list[seed % list.length];
|
||||
}
|
||||
|
||||
function hash(value) {
|
||||
let h = 2166136261;
|
||||
for (let i = 0; i < value.length; i += 1) {
|
||||
h ^= value.charCodeAt(i);
|
||||
h = Math.imul(h, 16777619);
|
||||
}
|
||||
return Math.abs(h >>> 0);
|
||||
}
|
||||
|
||||
// -----------------------------
|
||||
// UI HELPERS
|
||||
// -----------------------------
|
||||
|
||||
function characterForMessage(message) {
|
||||
const text = String(message || "").toLowerCase();
|
||||
return Object.entries(CHARACTER_AVATARS).find(([, config]) => {
|
||||
return (config.aliases || []).some((alias) => {
|
||||
const escaped = alias.toLowerCase().replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
||||
return new RegExp(`(^|[^a-z0-9-])${escaped}([^a-z0-9-]|$)`).test(text);
|
||||
});
|
||||
})?.[0] || "";
|
||||
}
|
||||
|
||||
function avatarMarkup(character) {
|
||||
const config = CHARACTER_AVATARS[character];
|
||||
if (!config) return "";
|
||||
return `<img class="hidden-message-avatar" src="${escapeHtml(config.avatar)}" alt="" loading="lazy" style="--hidden-avatar-glow:${escapeHtml(config.glow)}" onerror="this.onerror=null;this.src='${escapeHtml(config.fallback)}'">`;
|
||||
}
|
||||
|
||||
function hiddenMessageMarkup(message) {
|
||||
const character = characterForMessage(message);
|
||||
return character
|
||||
? `${avatarMarkup(character)}<span class="hidden-message-text">${escapeHtml(message)}</span>`
|
||||
: `<span class="hidden-message-text">${escapeHtml(message)}</span>`;
|
||||
}
|
||||
|
||||
function setHiddenMessage(el, message) {
|
||||
const character = characterForMessage(message);
|
||||
el.classList.toggle("has-hidden-avatar", Boolean(character));
|
||||
if (character) {
|
||||
el.dataset.hiddenCharacter = character;
|
||||
el.innerHTML = hiddenMessageMarkup(message);
|
||||
} else {
|
||||
delete el.dataset.hiddenCharacter;
|
||||
el.textContent = message;
|
||||
}
|
||||
}
|
||||
|
||||
function toast(message, duration) {
|
||||
let el = document.querySelector(".hidden-toast");
|
||||
if (!el) {
|
||||
el = document.createElement("div");
|
||||
el.className = "hidden-toast";
|
||||
el.setAttribute("role", "status");
|
||||
document.body.appendChild(el);
|
||||
}
|
||||
setHiddenMessage(el, message);
|
||||
el.classList.add("is-visible");
|
||||
window.clearTimeout(el._timer);
|
||||
el._timer = window.setTimeout(() => el.classList.remove("is-visible"), duration || 5600);
|
||||
}
|
||||
|
||||
function redirectTo(route) {
|
||||
window.location.href = route;
|
||||
}
|
||||
|
||||
function runSecretAction(secret) {
|
||||
if (secret.route) redirectTo(secret.route);
|
||||
if (secret.message) toast(secret.message);
|
||||
if (secret.song) playTinySong();
|
||||
}
|
||||
|
||||
function layerForSearch(value) {
|
||||
if (value.includes("future")) return 4;
|
||||
if (value.includes("sensei") || value.includes("aphy")) return 3;
|
||||
return 2;
|
||||
}
|
||||
|
||||
function rememberVisit() {
|
||||
const visits = (state.visits || 0) + 1;
|
||||
const seen = Array.isArray(state.seen) ? state.seen : [];
|
||||
const pathCounts = { ...(state.pathCounts || {}) };
|
||||
pathCounts[path] = (pathCounts[path] || 0) + 1;
|
||||
const layerVisits = { ...(state.layerVisits || {}) };
|
||||
const next = {
|
||||
...state,
|
||||
visits,
|
||||
lastPath: path,
|
||||
pathCounts,
|
||||
layerVisits,
|
||||
seen: Array.from(new Set([...seen, path])).slice(-100),
|
||||
firstSeen: state.firstSeen || new Date().toISOString(),
|
||||
lastSeen: new Date().toISOString()
|
||||
};
|
||||
writeState(next);
|
||||
return next;
|
||||
}
|
||||
|
||||
function awardLayer(layer, reason) {
|
||||
const next = readState();
|
||||
next.layerVisits = { ...(next.layerVisits || {}) };
|
||||
next.layerVisits[layer] = (next.layerVisits[layer] || 0) + 1;
|
||||
next.lastLayerReason = reason;
|
||||
writeState(next);
|
||||
}
|
||||
|
||||
// -----------------------------
|
||||
// GLOBAL FEATURES
|
||||
// -----------------------------
|
||||
|
||||
function addFooterNote(memory) {
|
||||
const footer = document.querySelector("footer");
|
||||
if (!footer || !details.length) return;
|
||||
const note = document.createElement("p");
|
||||
note.className = "hidden-footer-note";
|
||||
const base = pick(details, "footer");
|
||||
setHiddenMessage(note, memory.visits > 4 ? `${base} You have passed through ${memory.visits} times.` : base);
|
||||
footer.appendChild(note);
|
||||
}
|
||||
|
||||
function addHomepageGreeting(memory) {
|
||||
const target = document.querySelector("#db-greeting");
|
||||
if (!target || !greetings.length) return;
|
||||
setHiddenMessage(target, pick(greetings, `greeting-${memory.visits}`));
|
||||
const extra = document.createElement("p");
|
||||
extra.className = "hidden-greeting";
|
||||
setHiddenMessage(extra, "");
|
||||
target.closest("div")?.appendChild(extra);
|
||||
}
|
||||
|
||||
function addWhispers() {
|
||||
// Event: click one of the tiny "?" marks appended to long paragraphs.
|
||||
const paragraphs = Array.from(document.querySelectorAll("main p, #content p, article p")).filter((p) => p.textContent.trim().length > 80);
|
||||
paragraphs.slice(0, 5).forEach((p, index) => {
|
||||
if ((hash(path + index) + index) % 3 !== 0) return;
|
||||
const mark = document.createElement("span");
|
||||
mark.className = "hidden-whisper";
|
||||
mark.tabIndex = 0;
|
||||
mark.textContent = " ?";
|
||||
const source = index % 2 ? poems : details;
|
||||
if (!source.length) return;
|
||||
mark.title = pick(source, `whisper-${index}`);
|
||||
mark.addEventListener("click", () => {
|
||||
awardLayer(index % 2 ? 2 : 1, "paragraph whisper");
|
||||
toast(mark.title);
|
||||
});
|
||||
p.appendChild(mark);
|
||||
});
|
||||
}
|
||||
|
||||
function addCornerObject() {
|
||||
// Event: click the small fixed button in the bottom-left corner.
|
||||
const object = document.createElement("button");
|
||||
object.className = "hidden-corner-object";
|
||||
object.type = "button";
|
||||
object.title = "hidden interaction";
|
||||
object.textContent = state.visits % 2 ? "*" : "~";
|
||||
document.body.appendChild(object);
|
||||
let clicks = 0;
|
||||
object.addEventListener("click", () => {
|
||||
clicks += 1;
|
||||
awardLayer(clicks > 3 ? 3 : 1, "corner object");
|
||||
toast("Hidden interaction recorded.");
|
||||
if (clicks === 7) window.location.href = "/play/left-behind.html";
|
||||
});
|
||||
}
|
||||
|
||||
function addLogoSearchAndKeyboardSecrets(memory) {
|
||||
// Events:
|
||||
// - Click `.site-brand` repeatedly on the homepage.
|
||||
// - Type exact words into `#search-input`.
|
||||
// - Type phrases anywhere on the page.
|
||||
const nav = document.querySelector(".site-brand");
|
||||
if (nav) {
|
||||
let taps = Number(sessionStorage.getItem("zxh_logo_taps") || 0);
|
||||
nav.addEventListener("click", (event) => {
|
||||
if (path === "/" || path === "/index.html") {
|
||||
event.preventDefault();
|
||||
taps += 1;
|
||||
sessionStorage.setItem("zxh_logo_taps", String(taps));
|
||||
awardLayer(taps >= 5 ? 3 : 1, "logo taps");
|
||||
toast(taps >= 5 ? "Hidden route available: /play/dream-corridor.html" : "Hidden interaction recorded.");
|
||||
if (taps >= 8) window.location.href = "/play/dream-corridor.html";
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
const search = document.querySelector("#search-input");
|
||||
if (search) {
|
||||
search.addEventListener("input", () => {
|
||||
const value = search.value.trim().toLowerCase();
|
||||
if (SEARCH_TOASTS[value]) toast(SEARCH_TOASTS[value]);
|
||||
if (SEARCH_ROUTES[value]) {
|
||||
awardLayer(layerForSearch(value), `search ${value}`);
|
||||
redirectTo(SEARCH_ROUTES[value]);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
document.addEventListener("keydown", (event) => {
|
||||
const key = event.key.toLowerCase();
|
||||
const chain = `${sessionStorage.getItem("zxh_key_chain") || ""}${key}`.slice(-18);
|
||||
sessionStorage.setItem("zxh_key_chain", chain);
|
||||
KEYBOARD_SECRETS
|
||||
.filter((secret) => chain.endsWith(secret.phrase))
|
||||
.forEach(runSecretAction);
|
||||
});
|
||||
|
||||
if (memory.seen?.length >= 6 && !state.travellerNoteShown) {
|
||||
window.setTimeout(() => {
|
||||
toast("Hidden path recorded.");
|
||||
writeState({ ...readState(), travellerNoteShown: true });
|
||||
}, 1600);
|
||||
}
|
||||
}
|
||||
|
||||
function addRareEvents() {
|
||||
if (hour >= 22 || hour < 5) {
|
||||
document.body.classList.add("hidden-late-night");
|
||||
if (nightMessages.length) window.setTimeout(() => toast(pick(nightMessages, "night"), 2200), 900);
|
||||
}
|
||||
const roll = Math.random();
|
||||
if (roll < 0.003) {
|
||||
window.setTimeout(() => showDriftNote("", ""), 1800);
|
||||
awardLayer(3, "rare sensei appearance");
|
||||
} else if (roll < 0.008) {
|
||||
window.setTimeout(() => toast("Hidden warning."), 2400);
|
||||
awardLayer(4, "future warning");
|
||||
}
|
||||
}
|
||||
|
||||
function showDriftNote(text, art) {
|
||||
const panel = document.createElement("aside");
|
||||
panel.className = "hidden-drift-note";
|
||||
const character = characterForMessage(text);
|
||||
panel.innerHTML = `<div class="hidden-drift-message${character ? " has-hidden-avatar" : ""}">${hiddenMessageMarkup(text)}</div><pre>${escapeHtml(art)}</pre><button type="button">Close</button>`;
|
||||
panel.querySelector("button").addEventListener("click", () => panel.remove());
|
||||
document.body.appendChild(panel);
|
||||
}
|
||||
|
||||
function addSecretLinks() {
|
||||
[
|
||||
["/play/left-behind.html", "left behind"],
|
||||
["/play/dream-corridor.html", "dream corridor"],
|
||||
["/play/kitchen-light.html", "kitchen light"],
|
||||
...lore.roomLinks
|
||||
].forEach(([href, label], index) => {
|
||||
const link = document.createElement("a");
|
||||
link.className = "hidden-secret-link";
|
||||
link.href = href;
|
||||
link.textContent = label;
|
||||
link.style.left = `${index + 1}px`;
|
||||
document.body.appendChild(link);
|
||||
});
|
||||
}
|
||||
|
||||
function enhanceErrors() {
|
||||
if (document.title.match(/404|not found/i) || document.body.textContent.match(/404|not found/i)) {
|
||||
toast("Page not found.");
|
||||
}
|
||||
}
|
||||
|
||||
function addContinuity(memory) {
|
||||
const milestones = {
|
||||
64: "Hidden layer unlocked."
|
||||
};
|
||||
if (milestones[memory.visits] && !state[`milestone_${memory.visits}`]) {
|
||||
const layer = memory.visits >= 31 ? 4 : memory.visits >= 9 ? 3 : 2;
|
||||
awardLayer(layer, `visit milestone ${memory.visits}`);
|
||||
window.setTimeout(() => toast(milestones[memory.visits], 7000), 1200);
|
||||
writeState({ ...readState(), [`milestone_${memory.visits}`]: true });
|
||||
}
|
||||
|
||||
const count = memory.pathCounts?.[path] || 0;
|
||||
if ([3, 7, 12].includes(count)) {
|
||||
window.setTimeout(() => toast("Page revisit recorded.", 6400), 1700);
|
||||
}
|
||||
}
|
||||
|
||||
function addSeasonAndDates(memory) {
|
||||
const month = now.getMonth();
|
||||
const day = now.getDate();
|
||||
const season = month < 2 || month === 11 ? "winter" : month < 5 ? "spring" : month < 8 ? "summer" : "autumn";
|
||||
if (Math.random() < 0.18 && lore.seasonal[season]) window.setTimeout(() => toast(lore.seasonal[season], 5600), 2600);
|
||||
const first = memory.firstSeen ? new Date(memory.firstSeen) : null;
|
||||
if (first && memory.visits > 1 && first.getMonth() === month && first.getDate() === day) {
|
||||
window.setTimeout(() => toast("Visitor anniversary recorded.", 7000), 1400);
|
||||
}
|
||||
}
|
||||
|
||||
function addObjectConstellation() {
|
||||
// Event: click the small keepsake buttons along the bottom rail.
|
||||
const rail = document.createElement("div");
|
||||
rail.className = "hidden-object-rail";
|
||||
rail.setAttribute("aria-label", "Hidden objects");
|
||||
const objects = [
|
||||
["ring", "Hidden object recorded."],
|
||||
["bot", "Hidden object recorded."],
|
||||
["tea", "Hidden object recorded."],
|
||||
["crayon", "Hidden object recorded."],
|
||||
["clock", "Hidden object recorded."]
|
||||
];
|
||||
objects.forEach(([name, message]) => {
|
||||
const button = document.createElement("button");
|
||||
button.type = "button";
|
||||
button.className = `hidden-keepsake hidden-keepsake--${name}`;
|
||||
button.title = name;
|
||||
button.textContent = { ring: "o", bot: "#", tea: "u", crayon: "/", clock: ":" }[name];
|
||||
button.addEventListener("click", () => {
|
||||
const next = readState();
|
||||
next.keepsakes = Array.from(new Set([...(next.keepsakes || []), name]));
|
||||
writeState(next);
|
||||
awardLayer(next.keepsakes.length >= 3 ? 3 : 2, `keepsake ${name}`);
|
||||
toast(message);
|
||||
if (next.keepsakes.length >= objects.length) {
|
||||
window.setTimeout(() => toast("Hidden object set completed."), 1100);
|
||||
}
|
||||
});
|
||||
rail.appendChild(button);
|
||||
});
|
||||
document.body.appendChild(rail);
|
||||
}
|
||||
|
||||
function addWeatherWindow(memory) {
|
||||
// Event: click the small "window" button. This asks for browser geolocation.
|
||||
if (memory.visits < 3 || !("geolocation" in navigator)) return;
|
||||
const button = document.createElement("button");
|
||||
button.className = "hidden-weather-window";
|
||||
button.type = "button";
|
||||
button.title = "Check outside weather";
|
||||
button.textContent = "window";
|
||||
button.addEventListener("click", () => {
|
||||
toast("Checking outside weather.");
|
||||
navigator.geolocation.getCurrentPosition((pos) => {
|
||||
const { latitude, longitude } = pos.coords;
|
||||
fetch(`https://api.open-meteo.com/v1/forecast?latitude=${latitude.toFixed(3)}&longitude=${longitude.toFixed(3)}¤t=temperature_2m,precipitation&timezone=auto`)
|
||||
.then((res) => res.json())
|
||||
.then((data) => {
|
||||
const current = data.current || {};
|
||||
const rain = Number(current.precipitation || 0) > 0;
|
||||
const temp = Math.round(Number(current.temperature_2m));
|
||||
toast(rain ? `Outside: rain, ${temp}C.` : `Outside: ${temp}C.`);
|
||||
})
|
||||
.catch(() => toast("Weather check failed."));
|
||||
}, () => toast("No outside weather today."));
|
||||
});
|
||||
document.body.appendChild(button);
|
||||
}
|
||||
|
||||
function addOldWebLayer(memory) {
|
||||
if (Math.random() < 0.08 || memory.visits > 10) {
|
||||
const stamp = document.createElement("div");
|
||||
stamp.className = "hidden-oldweb-stamp";
|
||||
if (!lore.fakeUsers.length) return;
|
||||
stamp.title = pick(lore.fakeUsers, "fake-user");
|
||||
stamp.textContent = "best viewed with patience";
|
||||
stamp.addEventListener("click", () => {
|
||||
awardLayer(1, "old web stamp");
|
||||
toast(stamp.title);
|
||||
});
|
||||
document.body.appendChild(stamp);
|
||||
}
|
||||
const comments = document.querySelector("#comments");
|
||||
if (comments && lore.fakeUsers.length && !comments.querySelector(".hidden-guestbook-line")) {
|
||||
const line = document.createElement("p");
|
||||
line.className = "hidden-guestbook-line";
|
||||
setHiddenMessage(line, pick(lore.fakeUsers, "comment-lore"));
|
||||
comments.appendChild(line);
|
||||
}
|
||||
}
|
||||
|
||||
function addSourceRelics() {
|
||||
const marker = document.createComment("hidden-details");
|
||||
document.documentElement.appendChild(marker);
|
||||
document.querySelectorAll("img[alt=''], img:not([alt])").forEach((img, index) => {
|
||||
if (index > 2) return;
|
||||
img.alt = "Decorative image.";
|
||||
});
|
||||
}
|
||||
|
||||
function addLongKeyboardSecrets() {
|
||||
// Event: type longer hidden phrases anywhere on the page.
|
||||
document.addEventListener("keydown", (event) => {
|
||||
const chain = `${sessionStorage.getItem("zxh_second_chain") || ""}${event.key.toLowerCase()}`.slice(-24);
|
||||
sessionStorage.setItem("zxh_second_chain", chain);
|
||||
LONG_KEYBOARD_SECRETS
|
||||
.filter((secret) => chain.endsWith(secret.phrase))
|
||||
.forEach(runSecretAction);
|
||||
});
|
||||
}
|
||||
|
||||
function addPatienceRewards(memory) {
|
||||
// Event: no movement, key presses, scrolling, or clicking for 90 seconds.
|
||||
if (memory.visits < 2) return;
|
||||
let idleTimer = null;
|
||||
const startIdle = () => {
|
||||
window.clearTimeout(idleTimer);
|
||||
idleTimer = window.setTimeout(() => {
|
||||
awardLayer(5, "patience");
|
||||
toast("Idle moment recorded.", 7600);
|
||||
const next = readState();
|
||||
next.patientMoments = (next.patientMoments || 0) + 1;
|
||||
writeState(next);
|
||||
}, 90000);
|
||||
};
|
||||
["mousemove", "keydown", "scroll", "click"].forEach((name) => document.addEventListener(name, startIdle, { passive: true }));
|
||||
startIdle();
|
||||
}
|
||||
|
||||
function addRareSecondLayer() {
|
||||
const roll = Math.random();
|
||||
if ((path === "/" || path === "/index.html") && roll < 0.006) {
|
||||
document.body.classList.add("hidden-home-takeover");
|
||||
if (lore.homepageTakeovers.length) window.setTimeout(() => showDriftNote(pick(lore.homepageTakeovers, "takeover"), ""), 600);
|
||||
} else if (roll < 0.002) {
|
||||
window.setTimeout(() => showDriftNote("", ""), 1500);
|
||||
} else if (roll < 0.006) {
|
||||
if (lore.dreams.length) window.setTimeout(() => toast(pick(lore.dreams, "rare-dream"), 7600), 2000);
|
||||
} else if (roll < 0.014) {
|
||||
if (lore.warnings.length) window.setTimeout(() => toast(pick(lore.warnings, "rare-warning"), 6800), 2300);
|
||||
}
|
||||
}
|
||||
|
||||
function addFamilyLayerIndex(memory) {
|
||||
if (!path.includes("/play/family-layer-index")) return;
|
||||
const target = document.querySelector("[data-family-layer-index]");
|
||||
if (!target) return;
|
||||
const visits = readState().layerVisits || {};
|
||||
target.innerHTML = familyLayers.map((line, layer) => {
|
||||
const count = visits[layer] || 0;
|
||||
const character = characterForMessage(line);
|
||||
return `<li class="${character ? "hidden-layer-message" : ""}"><strong>${hiddenMessageMarkup(line)}</strong><br><span>local encounters: ${count}</span></li>`;
|
||||
}).join("");
|
||||
}
|
||||
|
||||
function addPageSpecificSecrets() {
|
||||
// Events only used by specific `/play/...` pages.
|
||||
if (path.includes("/play/cassette-log")) {
|
||||
document.querySelectorAll("[data-cassette]").forEach((button, index) => {
|
||||
button.addEventListener("click", () => {
|
||||
awardLayer(index >= 2 ? 4 : 2, "voice note");
|
||||
if (lore.cassettes.length) toast(lore.cassettes[index % lore.cassettes.length], 7600);
|
||||
playTinySong();
|
||||
});
|
||||
});
|
||||
}
|
||||
if (path.includes("/play/patience-game")) {
|
||||
const target = document.querySelector("[data-patience-target]");
|
||||
const count = document.querySelector("[data-patience-count]");
|
||||
if (target && count) {
|
||||
let seconds = 0;
|
||||
setInterval(() => {
|
||||
seconds += 1;
|
||||
count.textContent = String(seconds);
|
||||
if ([30, 90, 180].includes(seconds)) {
|
||||
setHiddenMessage(target, "Patience milestone recorded.");
|
||||
}
|
||||
}, 1000);
|
||||
}
|
||||
}
|
||||
if (path.includes("/play/terminal-cupboard")) {
|
||||
const input = document.querySelector("[data-cupboard-input]");
|
||||
const log = document.querySelector("[data-cupboard-log]");
|
||||
const commands = {
|
||||
help: "commands: layer, exit",
|
||||
layer: familyLayers.join("\n"),
|
||||
exit: "Closed."
|
||||
};
|
||||
input?.addEventListener("keydown", (event) => {
|
||||
if (event.key !== "Enter") return;
|
||||
const value = input.value.trim().toLowerCase();
|
||||
const line = document.createElement("p");
|
||||
setHiddenMessage(line, `> ${value}\n${commands[value] || "Unknown command."}`);
|
||||
log.appendChild(line);
|
||||
input.value = "";
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
function addInvisibleHoverSecrets() {
|
||||
document.querySelectorAll("h1, h2").forEach((heading, index) => {
|
||||
if (index > 5) return;
|
||||
heading.classList.add("hidden-hover-memory");
|
||||
const source = [...lore.quotes, ...lore.journals, ...poems];
|
||||
if (!source.length) return;
|
||||
heading.dataset.hiddenMemory = pick(source, `heading-${index}`);
|
||||
});
|
||||
}
|
||||
|
||||
function playTinySong() {
|
||||
try {
|
||||
const AudioContext = window.AudioContext || window.webkitAudioContext;
|
||||
if (!AudioContext) return;
|
||||
const ctx = new AudioContext();
|
||||
const notes = [392, 494, 440, 330, 392];
|
||||
notes.forEach((freq, index) => {
|
||||
const osc = ctx.createOscillator();
|
||||
const gain = ctx.createGain();
|
||||
osc.frequency.value = freq;
|
||||
osc.type = "sine";
|
||||
gain.gain.setValueAtTime(0.0001, ctx.currentTime + index * 0.18);
|
||||
gain.gain.exponentialRampToValueAtTime(0.05, ctx.currentTime + index * 0.18 + 0.03);
|
||||
gain.gain.exponentialRampToValueAtTime(0.0001, ctx.currentTime + index * 0.18 + 0.16);
|
||||
osc.connect(gain);
|
||||
gain.connect(ctx.destination);
|
||||
osc.start(ctx.currentTime + index * 0.18);
|
||||
osc.stop(ctx.currentTime + index * 0.18 + 0.18);
|
||||
});
|
||||
} catch (_) {}
|
||||
}
|
||||
|
||||
function escapeHtml(value) {
|
||||
return String(value).replace(/[&<>"']/g, (char) => ({
|
||||
"&": "&",
|
||||
"<": "<",
|
||||
">": ">",
|
||||
'"': """,
|
||||
"'": "'"
|
||||
}[char]));
|
||||
}
|
||||
|
||||
// Features run in this order on every page after the DOM is ready.
|
||||
// Each function receives the current `memory` object.
|
||||
const FEATURES = [
|
||||
addFooterNote,
|
||||
addHomepageGreeting,
|
||||
addWhispers,
|
||||
addCornerObject,
|
||||
addLogoSearchAndKeyboardSecrets,
|
||||
addRareEvents,
|
||||
addSecretLinks,
|
||||
enhanceErrors,
|
||||
addContinuity,
|
||||
addSeasonAndDates,
|
||||
addObjectConstellation,
|
||||
addWeatherWindow,
|
||||
addOldWebLayer,
|
||||
addSourceRelics,
|
||||
addLongKeyboardSecrets,
|
||||
addPatienceRewards,
|
||||
addRareSecondLayer,
|
||||
addFamilyLayerIndex,
|
||||
addPageSpecificSecrets,
|
||||
addInvisibleHoverSecrets
|
||||
];
|
||||
|
||||
document.addEventListener("DOMContentLoaded", () => {
|
||||
const memory = rememberVisit();
|
||||
FEATURES.forEach((addFeature) => addFeature(memory));
|
||||
});
|
||||
var script = document.createElement("script");
|
||||
script.src = "/assets/scripts/features/hidden-details.js";
|
||||
script.defer = true;
|
||||
document.head.appendChild(script);
|
||||
}());
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
2817
assets/scripts/mermaid.min.js
vendored
2817
assets/scripts/mermaid.min.js
vendored
File diff suppressed because one or more lines are too long
@@ -1,148 +1,7 @@
|
||||
(function () {
|
||||
const wall = document.getElementById("notes-wall");
|
||||
const form = document.getElementById("notes-form");
|
||||
const authorInput = document.getElementById("note-author");
|
||||
const contentInput = document.getElementById("note-content");
|
||||
const authorFilter = document.getElementById("notes-author-filter");
|
||||
let notesCache = [];
|
||||
|
||||
if (!wall) return;
|
||||
|
||||
function escapeHtml(str) {
|
||||
return str
|
||||
.replace(/&/g, "&")
|
||||
.replace(/</g, "<")
|
||||
.replace(/>/g, ">")
|
||||
.replace(/"/g, """)
|
||||
.replace(/'/g, "'");
|
||||
}
|
||||
|
||||
function renderNote(note) {
|
||||
const el = document.createElement("div");
|
||||
el.className = "note";
|
||||
|
||||
el.innerHTML = `
|
||||
<div class="note-meta">
|
||||
<span class="note-author">${escapeHtml(note.author_name)}</span>
|
||||
<time datetime="${note.created_at}">
|
||||
${new Date(note.created_at).toLocaleString()}
|
||||
</time>
|
||||
</div>
|
||||
<div class="note-content">
|
||||
${escapeHtml(note.content).replace(/\n/g, "<br>")}
|
||||
</div>
|
||||
`;
|
||||
|
||||
return el;
|
||||
}
|
||||
|
||||
function normaliseAuthor(author) {
|
||||
return (author || "").trim();
|
||||
}
|
||||
|
||||
function populateAuthorFilter(notes) {
|
||||
if (!authorFilter) return;
|
||||
|
||||
const previousValue = authorFilter.value;
|
||||
const authors = Array.from(
|
||||
new Set(notes.map(note => normaliseAuthor(note.author_name)).filter(Boolean))
|
||||
).sort((a, b) => a.localeCompare(b, undefined, { sensitivity: "base" }));
|
||||
|
||||
authorFilter.innerHTML = '<option value="">All authors</option>';
|
||||
|
||||
authors.forEach(author => {
|
||||
const option = document.createElement("option");
|
||||
option.value = author;
|
||||
option.textContent = author;
|
||||
authorFilter.appendChild(option);
|
||||
});
|
||||
|
||||
authorFilter.value = authors.includes(previousValue) ? previousValue : "";
|
||||
}
|
||||
|
||||
function renderNotes() {
|
||||
wall.innerHTML = "";
|
||||
|
||||
const selectedAuthor = authorFilter ? authorFilter.value : "";
|
||||
const notes = selectedAuthor
|
||||
? notesCache.filter(note => normaliseAuthor(note.author_name) === selectedAuthor)
|
||||
: notesCache;
|
||||
|
||||
if (notesCache.length === 0) {
|
||||
wall.innerHTML = "<p>No notes yet.</p>";
|
||||
return;
|
||||
}
|
||||
|
||||
if (notes.length === 0) {
|
||||
wall.innerHTML = "<p>No notes for this author.</p>";
|
||||
return;
|
||||
}
|
||||
|
||||
notes.forEach(note => {
|
||||
wall.appendChild(renderNote(note));
|
||||
});
|
||||
}
|
||||
|
||||
async function loadNotes() {
|
||||
wall.innerHTML = "<p>Loading notes…</p>";
|
||||
|
||||
try {
|
||||
const res = await fetch("/api/notes");
|
||||
if (!res.ok) throw new Error("Failed to fetch notes");
|
||||
|
||||
const notes = await res.json();
|
||||
notesCache = notes;
|
||||
populateAuthorFilter(notesCache);
|
||||
renderNotes();
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
wall.innerHTML = "<p>Could not load notes.</p>";
|
||||
}
|
||||
}
|
||||
|
||||
async function submitNote(e) {
|
||||
e.preventDefault();
|
||||
|
||||
const author = authorInput.value.trim();
|
||||
const content = contentInput.value.trim();
|
||||
|
||||
if (!author || !content) return;
|
||||
|
||||
form.querySelector("button").disabled = true;
|
||||
|
||||
try {
|
||||
const res = await fetch("/api/notes", {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({
|
||||
author_name: author,
|
||||
content: content,
|
||||
}),
|
||||
});
|
||||
|
||||
if (!res.ok) {
|
||||
const err = await res.json();
|
||||
throw new Error(err.detail || "Failed to post note");
|
||||
}
|
||||
|
||||
contentInput.value = "";
|
||||
await loadNotes();
|
||||
} catch (err) {
|
||||
alert(err.message);
|
||||
} finally {
|
||||
form.querySelector("button").disabled = false;
|
||||
}
|
||||
}
|
||||
|
||||
if (form) {
|
||||
form.addEventListener("submit", submitNote);
|
||||
}
|
||||
|
||||
if (authorFilter) {
|
||||
authorFilter.addEventListener("change", renderNotes);
|
||||
}
|
||||
|
||||
loadNotes();
|
||||
})();
|
||||
"use strict";
|
||||
var script = document.createElement("script");
|
||||
script.src = "/assets/scripts/pages/notes.js";
|
||||
script.defer = true;
|
||||
document.head.appendChild(script);
|
||||
}());
|
||||
|
||||
1008
assets/scripts/pages/ash-below-lake.js
Normal file
1008
assets/scripts/pages/ash-below-lake.js
Normal file
File diff suppressed because it is too large
Load Diff
240
assets/scripts/pages/competency-status-board.js
Normal file
240
assets/scripts/pages/competency-status-board.js
Normal file
@@ -0,0 +1,240 @@
|
||||
const STATES = [
|
||||
{ key: "completed", label: "Completed" },
|
||||
{ key: "manager_review", label: "Manager Review" },
|
||||
{ key: "in_progress", label: "In Progress" },
|
||||
{ key: "not_started", label: "Not Started" },
|
||||
{ key: "comments", label: "Comments" },
|
||||
];
|
||||
|
||||
const LEVELS = [
|
||||
{ key: "graduate", label: "Graduate" },
|
||||
{ key: "engineer", label: "Engineer" },
|
||||
];
|
||||
|
||||
let currentLevel = LEVELS[0].key;
|
||||
|
||||
function isMobile() {
|
||||
return window.matchMedia("(max-width: 600px)").matches;
|
||||
}
|
||||
|
||||
function renderLevelTabs() {
|
||||
const board = document.getElementById("kanban-board");
|
||||
if (!board || document.getElementById("level-tabs")) return;
|
||||
|
||||
const nav = document.createElement("div");
|
||||
nav.id = "level-tabs";
|
||||
|
||||
LEVELS.forEach(({ key, label }) => {
|
||||
const btn = document.createElement("button");
|
||||
btn.textContent = label;
|
||||
btn.dataset.level = key;
|
||||
btn.className = "level-tab" + (key === currentLevel ? " active" : "");
|
||||
btn.addEventListener("click", () => {
|
||||
currentLevel = key;
|
||||
document.querySelectorAll(".level-tab").forEach(b =>
|
||||
b.classList.toggle("active", b.dataset.level === key)
|
||||
);
|
||||
loadBoard();
|
||||
});
|
||||
nav.appendChild(btn);
|
||||
});
|
||||
|
||||
board.insertAdjacentElement("beforebegin", nav);
|
||||
|
||||
if (!document.getElementById("level-tab-styles")) {
|
||||
const style = document.createElement("style");
|
||||
style.id = "level-tab-styles";
|
||||
style.textContent = `
|
||||
#level-tabs {
|
||||
display: flex;
|
||||
gap: 0.5em;
|
||||
margin-bottom: 1em;
|
||||
}
|
||||
.level-tab {
|
||||
padding: 0.4em 1.2em;
|
||||
border: 1px solid #ccc;
|
||||
background: none;
|
||||
cursor: pointer;
|
||||
border-radius: 4px;
|
||||
font-size: 0.95em;
|
||||
}
|
||||
.level-tab.active {
|
||||
background: #333;
|
||||
color: #fff;
|
||||
border-color: #333;
|
||||
}
|
||||
`;
|
||||
document.head.appendChild(style);
|
||||
}
|
||||
}
|
||||
|
||||
function populateMobileControls(items) {
|
||||
if (!isMobile()) return;
|
||||
|
||||
const panel = document.getElementById("mobile-move-panel");
|
||||
const itemSelect = document.getElementById("move-item");
|
||||
const fromSelect = document.getElementById("move-from");
|
||||
const toSelect = document.getElementById("move-to");
|
||||
|
||||
itemSelect.innerHTML = "<option value=''>Select competency</option>";
|
||||
fromSelect.innerHTML = "<option value=''>From</option>";
|
||||
toSelect.innerHTML = "<option value=''>To</option>";
|
||||
|
||||
items.forEach((item) => {
|
||||
const opt = document.createElement("option");
|
||||
opt.value = item.id;
|
||||
opt.textContent = item.title;
|
||||
opt.dataset.state = item.state;
|
||||
itemSelect.appendChild(opt);
|
||||
});
|
||||
|
||||
STATES.forEach((s) => {
|
||||
fromSelect.appendChild(new Option(s.label, s.key));
|
||||
toSelect.appendChild(new Option(s.label, s.key));
|
||||
});
|
||||
|
||||
itemSelect.onchange = () => {
|
||||
const selected = itemSelect.selectedOptions[0];
|
||||
if (selected?.dataset.state) {
|
||||
fromSelect.value = selected.dataset.state;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
const moveConfirmBtn = document.getElementById("move-confirm");
|
||||
if (moveConfirmBtn) {
|
||||
moveConfirmBtn.addEventListener("click", async () => {
|
||||
const itemId = document.getElementById("move-item").value;
|
||||
const from = document.getElementById("move-from").value;
|
||||
const to = document.getElementById("move-to").value;
|
||||
|
||||
if (!itemId || !to) {
|
||||
alert("Select an item and target column");
|
||||
return;
|
||||
}
|
||||
|
||||
if (from === to) {
|
||||
alert("Item is already in that column");
|
||||
return;
|
||||
}
|
||||
|
||||
const res = await fetch(`/api/competencies/items/${itemId}/state`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ state: to }),
|
||||
});
|
||||
|
||||
if (res.ok) {
|
||||
loadBoard();
|
||||
} else {
|
||||
alert("Failed to move competency");
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
let draggedItemId = null;
|
||||
|
||||
function countByState(items) {
|
||||
return items.reduce((acc, item) => {
|
||||
acc[item.state] = (acc[item.state] || 0) + 1;
|
||||
return acc;
|
||||
}, {});
|
||||
}
|
||||
|
||||
async function updateProgress(items) {
|
||||
const total = items.length;
|
||||
const completed = items.filter(i => i.state === "completed").length;
|
||||
const percent = total === 0 ? 0 : Math.round((completed / total) * 100);
|
||||
|
||||
const fill = document.getElementById("progress-fill");
|
||||
const label = document.getElementById("progress-label");
|
||||
|
||||
if (fill) fill.style.width = `${percent}%`;
|
||||
if (label) label.textContent = `${percent}% completed`;
|
||||
}
|
||||
|
||||
function createCard(item) {
|
||||
const card = document.createElement("div");
|
||||
card.className = "kanban-card";
|
||||
card.draggable = true;
|
||||
card.dataset.id = item.id;
|
||||
card.textContent = item.title;
|
||||
|
||||
card.addEventListener("dragstart", () => {
|
||||
draggedItemId = item.id;
|
||||
card.classList.add("dragging");
|
||||
});
|
||||
|
||||
card.addEventListener("dragend", () => {
|
||||
draggedItemId = null;
|
||||
card.classList.remove("dragging");
|
||||
});
|
||||
|
||||
return card;
|
||||
}
|
||||
|
||||
function createColumn(state, items, counts) {
|
||||
const col = document.createElement("div");
|
||||
col.className = "kanban-column";
|
||||
col.dataset.state = state.key;
|
||||
|
||||
const header = document.createElement("h3");
|
||||
header.innerHTML = `
|
||||
<span class="kanban-title">${state.label}</span>
|
||||
<span class="kanban-count">${counts[state.key] || 0}</span>
|
||||
`;
|
||||
|
||||
const list = document.createElement("div");
|
||||
list.className = "kanban-list";
|
||||
|
||||
list.addEventListener("dragover", (e) => e.preventDefault());
|
||||
|
||||
list.addEventListener("drop", async () => {
|
||||
if (!draggedItemId) return;
|
||||
|
||||
const res = await fetch(`/api/competencies/items/${draggedItemId}/state`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ state: state.key }),
|
||||
});
|
||||
|
||||
if (res.ok) {
|
||||
loadBoard();
|
||||
} else {
|
||||
alert("Failed to update state");
|
||||
}
|
||||
});
|
||||
|
||||
items
|
||||
.filter((i) => i.state === state.key)
|
||||
.forEach((i) => list.appendChild(createCard(i)));
|
||||
|
||||
col.appendChild(header);
|
||||
col.appendChild(list);
|
||||
|
||||
return col;
|
||||
}
|
||||
|
||||
function renderBoard(items) {
|
||||
const board = document.getElementById("kanban-board");
|
||||
if (!board) return;
|
||||
board.innerHTML = "";
|
||||
|
||||
const counts = countByState(items);
|
||||
|
||||
STATES.forEach((state) => {
|
||||
board.appendChild(createColumn(state, items, counts));
|
||||
});
|
||||
}
|
||||
|
||||
async function loadBoard() {
|
||||
const res = await fetch(`/api/competencies/items?group=${currentLevel}`);
|
||||
const items = await res.json();
|
||||
|
||||
updateProgress(items);
|
||||
renderBoard(items);
|
||||
populateMobileControls(items);
|
||||
}
|
||||
|
||||
renderLevelTabs();
|
||||
loadBoard();
|
||||
313
assets/scripts/pages/home-dashboard.js
Normal file
313
assets/scripts/pages/home-dashboard.js
Normal file
@@ -0,0 +1,313 @@
|
||||
/* Home dashboard behaviour. All selectors are db-* scoped. */
|
||||
|
||||
(function () {
|
||||
"use strict";
|
||||
|
||||
function updateGreeting() {
|
||||
const el = document.getElementById("db-greeting");
|
||||
if (!el) return;
|
||||
|
||||
const hour = new Date().getHours();
|
||||
if (hour < 5) el.textContent = "Late session";
|
||||
else if (hour < 12) el.textContent = "Good morning";
|
||||
else if (hour < 17) el.textContent = "Good afternoon";
|
||||
else if (hour < 21) el.textContent = "Good evening";
|
||||
else el.textContent = "Evening review";
|
||||
}
|
||||
|
||||
function updateClock() {
|
||||
const el = document.getElementById("db-clock");
|
||||
if (!el) return;
|
||||
|
||||
el.textContent = new Intl.DateTimeFormat(undefined, {
|
||||
hour: "2-digit",
|
||||
minute: "2-digit",
|
||||
second: "2-digit",
|
||||
hour12: false,
|
||||
}).format(new Date());
|
||||
}
|
||||
|
||||
function getIsoWeek(date) {
|
||||
const d = new Date(Date.UTC(date.getFullYear(), date.getMonth(), date.getDate()));
|
||||
const dayNum = d.getUTCDay() || 7;
|
||||
d.setUTCDate(d.getUTCDate() + 4 - dayNum);
|
||||
const yearStart = new Date(Date.UTC(d.getUTCFullYear(), 0, 1));
|
||||
return Math.ceil(((d - yearStart) / 86400000 + 1) / 7);
|
||||
}
|
||||
|
||||
function updateStats() {
|
||||
const now = new Date();
|
||||
const year = now.getFullYear();
|
||||
const start = new Date(year, 0, 1);
|
||||
const nextYear = new Date(year + 1, 0, 1);
|
||||
const dayOfYear = Math.floor((now - start) / 86400000) + 1;
|
||||
const daysInYear = Math.round((nextYear - start) / 86400000);
|
||||
const daysLeft = Math.max(0, daysInYear - dayOfYear);
|
||||
const month = new Intl.DateTimeFormat(undefined, { month: "short" }).format(now);
|
||||
const pct = ((dayOfYear / daysInYear) * 100).toFixed(1);
|
||||
|
||||
setText("db-stat-day", dayOfYear);
|
||||
setText("db-stat-week", "W" + getIsoWeek(now));
|
||||
setText("db-stat-month", month);
|
||||
setText("db-stat-left", daysLeft);
|
||||
setText("db-year-pct", pct + "%");
|
||||
|
||||
const fill = document.getElementById("db-year-fill");
|
||||
if (fill) fill.style.width = pct + "%";
|
||||
}
|
||||
|
||||
function setText(id, value) {
|
||||
const el = document.getElementById(id);
|
||||
if (el) el.textContent = value;
|
||||
}
|
||||
|
||||
function escHtml(str) {
|
||||
return String(str)
|
||||
.replace(/&/g, "&")
|
||||
.replace(/</g, "<")
|
||||
.replace(/>/g, ">")
|
||||
.replace(/"/g, """);
|
||||
}
|
||||
|
||||
function escAttr(str) {
|
||||
return escHtml(str).replace(/'/g, "'");
|
||||
}
|
||||
|
||||
function normaliseHref(href, prefix) {
|
||||
if (!href || href.startsWith("http") || href.startsWith("#")) return null;
|
||||
if (href.startsWith("/")) return href;
|
||||
const base = (prefix || "").replace(/\/$/, "");
|
||||
if (!base || href.startsWith(base + "/")) return href;
|
||||
return base + "/" + href;
|
||||
}
|
||||
|
||||
function isTagLink(a) {
|
||||
const href = a.getAttribute("href") || "";
|
||||
return href.includes("/tags/") || Boolean(a.querySelector(".post-tag"));
|
||||
}
|
||||
|
||||
function extractLinks(doc, max, prefix) {
|
||||
const items = [];
|
||||
const seen = new Set();
|
||||
const links = doc.querySelectorAll("#content li a[href], .org-ul li a[href], ul li a[href]");
|
||||
|
||||
for (const a of links) {
|
||||
if (isTagLink(a)) continue;
|
||||
|
||||
const href = normaliseHref(a.getAttribute("href"), prefix);
|
||||
const title = a.textContent.trim();
|
||||
if (!href || !title || seen.has(href)) continue;
|
||||
|
||||
const li = a.closest("li");
|
||||
const dateMatch = li ? li.textContent.match(/\b\d{4}-\d{2}-\d{2}\b/) : null;
|
||||
seen.add(href);
|
||||
items.push({ href, title, date: dateMatch ? dateMatch[0] : null });
|
||||
if (items.length >= max) break;
|
||||
}
|
||||
|
||||
return items;
|
||||
}
|
||||
|
||||
function renderFeed(ulId, items) {
|
||||
const ul = document.getElementById(ulId);
|
||||
if (!ul || !items.length) return;
|
||||
|
||||
ul.innerHTML = items
|
||||
.map(({ href, title, date }) => (
|
||||
`<li class="db-feed__item">` +
|
||||
`<span class="db-feed__dot"></span>` +
|
||||
`<a href="${escHtml(href)}">${escHtml(title)}</a>` +
|
||||
(date ? `<span class="db-feed__meta">${escHtml(date)}</span>` : "") +
|
||||
`</li>`
|
||||
))
|
||||
.join("");
|
||||
}
|
||||
|
||||
async function loadFeed(listUrl, ulId, max, prefix) {
|
||||
try {
|
||||
const resp = await fetch(listUrl, { credentials: "same-origin" });
|
||||
if (!resp.ok) return;
|
||||
|
||||
const html = await resp.text();
|
||||
const doc = new DOMParser().parseFromString(html, "text/html");
|
||||
renderFeed(ulId, extractLinks(doc, max, prefix));
|
||||
} catch (_) {
|
||||
/* Fallback links remain in the HTML. */
|
||||
}
|
||||
}
|
||||
|
||||
function commentSlug(comment) {
|
||||
return comment.pageSlug || comment.page_slug || "";
|
||||
}
|
||||
|
||||
function commentDate(comment) {
|
||||
return comment.created_at || comment.createdAt || "";
|
||||
}
|
||||
|
||||
function commentHref(page, comment) {
|
||||
if (!page?.url) return null;
|
||||
if (!comment.id) return page.url + "#comments";
|
||||
return page.url + "#comment-" + encodeURIComponent(comment.id);
|
||||
}
|
||||
|
||||
function formatCommentDate(value) {
|
||||
const date = new Date(value);
|
||||
if (Number.isNaN(date.getTime())) return "";
|
||||
|
||||
return new Intl.DateTimeFormat(undefined, {
|
||||
month: "short",
|
||||
day: "2-digit",
|
||||
hour: "2-digit",
|
||||
minute: "2-digit",
|
||||
}).format(date);
|
||||
}
|
||||
|
||||
function commentExcerpt(content) {
|
||||
const text = String(content || "").replace(/\s+/g, " ").trim();
|
||||
if (text.length <= 150) return text;
|
||||
return text.slice(0, 147).trimEnd() + "...";
|
||||
}
|
||||
|
||||
function renderRecentComments(comments, pageMap) {
|
||||
const ul = document.getElementById("db-feed-comments");
|
||||
if (!ul) return;
|
||||
|
||||
if (!comments.length) {
|
||||
ul.innerHTML = (
|
||||
`<li class="db-comment-feed__item">` +
|
||||
`<span class="db-feed__dot"></span>` +
|
||||
`<div class="db-comment-feed__body">` +
|
||||
`<span class="db-comment-feed__empty">No comments yet.</span>` +
|
||||
`</div>` +
|
||||
`</li>`
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
ul.innerHTML = comments.map((comment) => {
|
||||
const slug = commentSlug(comment);
|
||||
const page = pageMap.get(slug);
|
||||
const title = page?.title || slug || "Unknown page";
|
||||
const href = commentHref(page, comment);
|
||||
const author = comment.author || "Anonymous";
|
||||
const date = formatCommentDate(commentDate(comment));
|
||||
const pageLink = href
|
||||
? `<a class="db-comment-feed__page" href="${escAttr(href)}">${escHtml(title)}</a>`
|
||||
: `<span class="db-comment-feed__page">${escHtml(title)}</span>`;
|
||||
|
||||
return (
|
||||
`<li class="db-comment-feed__item">` +
|
||||
`<span class="db-feed__dot"></span>` +
|
||||
`<div class="db-comment-feed__body">` +
|
||||
`<div class="db-comment-feed__top">` +
|
||||
`<strong>${escHtml(author)}</strong>` +
|
||||
`<span>on</span>` +
|
||||
pageLink +
|
||||
(date ? `<time datetime="${escAttr(commentDate(comment))}">${escHtml(date)}</time>` : "") +
|
||||
`</div>` +
|
||||
`<p>${escHtml(commentExcerpt(comment.content))}</p>` +
|
||||
`</div>` +
|
||||
`</li>`
|
||||
);
|
||||
}).join("");
|
||||
}
|
||||
|
||||
async function loadCommentPageMap() {
|
||||
try {
|
||||
const resp = await fetch("/assets/content/comment-pages.json", { credentials: "same-origin" });
|
||||
if (!resp.ok) return new Map();
|
||||
|
||||
const pages = await resp.json();
|
||||
return new Map(
|
||||
pages
|
||||
.filter((page) => page.slug && page.url)
|
||||
.map((page) => [page.slug, page])
|
||||
);
|
||||
} catch (_) {
|
||||
return new Map();
|
||||
}
|
||||
}
|
||||
|
||||
async function loadRecentComments() {
|
||||
const ul = document.getElementById("db-feed-comments");
|
||||
if (!ul) return;
|
||||
|
||||
const renderUnavailable = () => {
|
||||
ul.innerHTML = (
|
||||
`<li class="db-comment-feed__item">` +
|
||||
`<span class="db-feed__dot"></span>` +
|
||||
`<div class="db-comment-feed__body">` +
|
||||
`<span class="db-comment-feed__empty">Recent comments are unavailable.</span>` +
|
||||
`</div>` +
|
||||
`</li>`
|
||||
);
|
||||
};
|
||||
|
||||
try {
|
||||
const [pageMap, resp] = await Promise.all([
|
||||
loadCommentPageMap(),
|
||||
fetch("/api/comments", { credentials: "same-origin" }),
|
||||
]);
|
||||
if (!resp.ok) {
|
||||
renderUnavailable();
|
||||
return;
|
||||
}
|
||||
|
||||
const comments = await resp.json();
|
||||
const recent = comments
|
||||
.filter((comment) => commentDate(comment))
|
||||
.sort((a, b) => new Date(commentDate(b)) - new Date(commentDate(a)))
|
||||
.slice(0, 10);
|
||||
|
||||
renderRecentComments(recent, pageMap);
|
||||
} catch (_) {
|
||||
renderUnavailable();
|
||||
}
|
||||
}
|
||||
|
||||
function initCommandFilter() {
|
||||
const input = document.getElementById("db-command-search");
|
||||
const nav = document.getElementById("db-quicknav");
|
||||
if (!input || !nav) return;
|
||||
|
||||
const items = Array.from(nav.querySelectorAll(".db-qn-item"));
|
||||
const applyFilter = () => {
|
||||
const query = input.value.trim().toLowerCase();
|
||||
items.forEach((item) => {
|
||||
const haystack = [
|
||||
item.textContent,
|
||||
item.getAttribute("href"),
|
||||
item.dataset.keywords,
|
||||
].join(" ").toLowerCase();
|
||||
item.classList.toggle("is-hidden", Boolean(query && !haystack.includes(query)));
|
||||
});
|
||||
};
|
||||
|
||||
input.addEventListener("input", applyFilter);
|
||||
document.addEventListener("keydown", (event) => {
|
||||
if (event.key === "/" && !/^(input|textarea|select)$/i.test(event.target.tagName)) {
|
||||
event.preventDefault();
|
||||
input.focus();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function init() {
|
||||
updateGreeting();
|
||||
updateClock();
|
||||
updateStats();
|
||||
initCommandFilter();
|
||||
|
||||
setInterval(updateClock, 1000);
|
||||
loadFeed("/blogs/blogs-list.html", "db-feed-blogs", 6, "/blogs");
|
||||
loadFeed("/posts/posts-list.html", "db-feed-posts", 6, "/posts");
|
||||
loadFeed("/recently-updated.html", "db-feed-recent", 6, "");
|
||||
loadRecentComments();
|
||||
}
|
||||
|
||||
if (document.readyState === "loading") {
|
||||
document.addEventListener("DOMContentLoaded", init);
|
||||
} else {
|
||||
init();
|
||||
}
|
||||
})();
|
||||
148
assets/scripts/pages/notes.js
Normal file
148
assets/scripts/pages/notes.js
Normal file
@@ -0,0 +1,148 @@
|
||||
(function () {
|
||||
const wall = document.getElementById("notes-wall");
|
||||
const form = document.getElementById("notes-form");
|
||||
const authorInput = document.getElementById("note-author");
|
||||
const contentInput = document.getElementById("note-content");
|
||||
const authorFilter = document.getElementById("notes-author-filter");
|
||||
let notesCache = [];
|
||||
|
||||
if (!wall) return;
|
||||
|
||||
function escapeHtml(str) {
|
||||
return str
|
||||
.replace(/&/g, "&")
|
||||
.replace(/</g, "<")
|
||||
.replace(/>/g, ">")
|
||||
.replace(/"/g, """)
|
||||
.replace(/'/g, "'");
|
||||
}
|
||||
|
||||
function renderNote(note) {
|
||||
const el = document.createElement("div");
|
||||
el.className = "note";
|
||||
|
||||
el.innerHTML = `
|
||||
<div class="note-meta">
|
||||
<span class="note-author">${escapeHtml(note.author_name)}</span>
|
||||
<time datetime="${note.created_at}">
|
||||
${new Date(note.created_at).toLocaleString()}
|
||||
</time>
|
||||
</div>
|
||||
<div class="note-content">
|
||||
${escapeHtml(note.content).replace(/\n/g, "<br>")}
|
||||
</div>
|
||||
`;
|
||||
|
||||
return el;
|
||||
}
|
||||
|
||||
function normaliseAuthor(author) {
|
||||
return (author || "").trim();
|
||||
}
|
||||
|
||||
function populateAuthorFilter(notes) {
|
||||
if (!authorFilter) return;
|
||||
|
||||
const previousValue = authorFilter.value;
|
||||
const authors = Array.from(
|
||||
new Set(notes.map(note => normaliseAuthor(note.author_name)).filter(Boolean))
|
||||
).sort((a, b) => a.localeCompare(b, undefined, { sensitivity: "base" }));
|
||||
|
||||
authorFilter.innerHTML = '<option value="">All authors</option>';
|
||||
|
||||
authors.forEach(author => {
|
||||
const option = document.createElement("option");
|
||||
option.value = author;
|
||||
option.textContent = author;
|
||||
authorFilter.appendChild(option);
|
||||
});
|
||||
|
||||
authorFilter.value = authors.includes(previousValue) ? previousValue : "";
|
||||
}
|
||||
|
||||
function renderNotes() {
|
||||
wall.innerHTML = "";
|
||||
|
||||
const selectedAuthor = authorFilter ? authorFilter.value : "";
|
||||
const notes = selectedAuthor
|
||||
? notesCache.filter(note => normaliseAuthor(note.author_name) === selectedAuthor)
|
||||
: notesCache;
|
||||
|
||||
if (notesCache.length === 0) {
|
||||
wall.innerHTML = "<p>No notes yet.</p>";
|
||||
return;
|
||||
}
|
||||
|
||||
if (notes.length === 0) {
|
||||
wall.innerHTML = "<p>No notes for this author.</p>";
|
||||
return;
|
||||
}
|
||||
|
||||
notes.forEach(note => {
|
||||
wall.appendChild(renderNote(note));
|
||||
});
|
||||
}
|
||||
|
||||
async function loadNotes() {
|
||||
wall.innerHTML = "<p>Loading notes…</p>";
|
||||
|
||||
try {
|
||||
const res = await fetch("/api/notes");
|
||||
if (!res.ok) throw new Error("Failed to fetch notes");
|
||||
|
||||
const notes = await res.json();
|
||||
notesCache = notes;
|
||||
populateAuthorFilter(notesCache);
|
||||
renderNotes();
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
wall.innerHTML = "<p>Could not load notes.</p>";
|
||||
}
|
||||
}
|
||||
|
||||
async function submitNote(e) {
|
||||
e.preventDefault();
|
||||
|
||||
const author = authorInput.value.trim();
|
||||
const content = contentInput.value.trim();
|
||||
|
||||
if (!author || !content) return;
|
||||
|
||||
form.querySelector("button").disabled = true;
|
||||
|
||||
try {
|
||||
const res = await fetch("/api/notes", {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({
|
||||
author_name: author,
|
||||
content: content,
|
||||
}),
|
||||
});
|
||||
|
||||
if (!res.ok) {
|
||||
const err = await res.json();
|
||||
throw new Error(err.detail || "Failed to post note");
|
||||
}
|
||||
|
||||
contentInput.value = "";
|
||||
await loadNotes();
|
||||
} catch (err) {
|
||||
alert(err.message);
|
||||
} finally {
|
||||
form.querySelector("button").disabled = false;
|
||||
}
|
||||
}
|
||||
|
||||
if (form) {
|
||||
form.addEventListener("submit", submitNote);
|
||||
}
|
||||
|
||||
if (authorFilter) {
|
||||
authorFilter.addEventListener("change", renderNotes);
|
||||
}
|
||||
|
||||
loadNotes();
|
||||
})();
|
||||
866
assets/scripts/pages/play.js
Normal file
866
assets/scripts/pages/play.js
Normal file
@@ -0,0 +1,866 @@
|
||||
(function () {
|
||||
const $ = (sel, root = document) => root.querySelector(sel);
|
||||
const $$ = (sel, root = document) => Array.from(root.querySelectorAll(sel));
|
||||
const shuffle = (items) => items.map((value) => ({ value, sort: Math.random() })).sort((a, b) => a.sort - b.sort).map((item) => item.value);
|
||||
const quips = [
|
||||
"A margin note blinks, then pretends it did not.",
|
||||
"Somewhere, a bookmark changes its mind.",
|
||||
"The archive is pleased by unnecessary curiosity.",
|
||||
"A tiny bell rings in a room you have not built yet.",
|
||||
"The page remembers that you came here."
|
||||
];
|
||||
|
||||
document.addEventListener("DOMContentLoaded", () => {
|
||||
const root = $(".play-root[data-play-page]");
|
||||
if (!root) return;
|
||||
const page = root.dataset.playPage;
|
||||
const inits = { hub, memory, constellation, poem, bookshelf, recipe, timeline, ink, terminal, study, sigil, rpg };
|
||||
if (inits[page]) inits[page](root);
|
||||
});
|
||||
|
||||
function hub(root) {
|
||||
const links = $$(".play-grid a", root);
|
||||
const nodes = $$(".play-orbit__node", root);
|
||||
const title = $("#play-hub-title", root);
|
||||
const kind = $("#play-hub-kind", root);
|
||||
const desc = $("#play-hub-desc", root);
|
||||
const cta = $("#play-hub-link", root);
|
||||
const whisper = document.createElement("p");
|
||||
let active = 0;
|
||||
|
||||
whisper.className = "play-whisper";
|
||||
whisper.setAttribute("aria-live", "polite");
|
||||
$(".play-console__screen", root).appendChild(whisper);
|
||||
|
||||
nodes.forEach((node, index) => {
|
||||
const angle = (index / nodes.length) * Math.PI * 2 - Math.PI / 2;
|
||||
node.style.left = `${50 + Math.cos(angle) * 43}%`;
|
||||
node.style.top = `${50 + Math.sin(angle) * 43}%`;
|
||||
node.addEventListener("click", () => setActive(index));
|
||||
});
|
||||
|
||||
function setActive(index) {
|
||||
active = (index + links.length) % links.length;
|
||||
const link = links[active];
|
||||
links.forEach((item, i) => item.classList.toggle("is-active", i === active));
|
||||
nodes.forEach((item, i) => item.classList.toggle("is-active", i === active));
|
||||
title.textContent = link.querySelector("strong").textContent;
|
||||
kind.textContent = link.dataset.kind;
|
||||
desc.textContent = link.dataset.desc;
|
||||
cta.href = link.href;
|
||||
whisper.textContent = quips[active % quips.length];
|
||||
}
|
||||
|
||||
links.forEach((link, index) => {
|
||||
link.addEventListener("mouseenter", () => setActive(index));
|
||||
link.addEventListener("focus", () => setActive(index));
|
||||
});
|
||||
$("[data-play-prev]", root).addEventListener("click", () => setActive(active - 1));
|
||||
$("[data-play-next]", root).addEventListener("click", () => setActive(active + 1));
|
||||
$("[data-play-random]", root).addEventListener("click", () => setActive(Math.floor(Math.random() * links.length)));
|
||||
$(".play-orbit", root).addEventListener("dblclick", () => {
|
||||
whisper.textContent = "You knocked twice. The cabinet knocked once back.";
|
||||
root.classList.toggle("is-odd");
|
||||
});
|
||||
root.addEventListener("keydown", (event) => {
|
||||
if (event.key === "ArrowLeft") setActive(active - 1);
|
||||
if (event.key === "ArrowRight") setActive(active + 1);
|
||||
});
|
||||
setActive(0);
|
||||
}
|
||||
|
||||
function memory(root) {
|
||||
const symbols = ["Ink", "Lamp", "Tea", "Book", "Map", "Key"];
|
||||
const board = $("[data-memory-board]", root);
|
||||
const turnsEl = $("[data-memory-turns]", root);
|
||||
const matchesEl = $("[data-memory-matches]", root);
|
||||
const messageEl = $("[data-memory-message]", root);
|
||||
let open = [];
|
||||
let turns = 0;
|
||||
let matches = 0;
|
||||
let deck = [];
|
||||
|
||||
function render() {
|
||||
board.innerHTML = "";
|
||||
open = [];
|
||||
turns = 0;
|
||||
matches = 0;
|
||||
deck = shuffle([...symbols, ...symbols]);
|
||||
turnsEl.textContent = "0";
|
||||
matchesEl.textContent = "0";
|
||||
messageEl.textContent = "Cards are shuffled.";
|
||||
deck.forEach((symbol, index) => {
|
||||
const card = document.createElement("button");
|
||||
card.type = "button";
|
||||
card.className = "memory-card";
|
||||
card.dataset.symbol = symbol;
|
||||
card.textContent = "?";
|
||||
card.style.setProperty("--tilt", `${(index % 5) - 2}deg`);
|
||||
card.setAttribute("aria-label", "Hidden card");
|
||||
card.addEventListener("click", () => flip(card));
|
||||
board.appendChild(card);
|
||||
});
|
||||
}
|
||||
|
||||
function flip(card) {
|
||||
if (card.classList.contains("is-open") || card.classList.contains("is-matched") || open.length === 2) return;
|
||||
card.classList.add("is-open");
|
||||
card.textContent = card.dataset.symbol;
|
||||
card.setAttribute("aria-label", card.dataset.symbol);
|
||||
open.push(card);
|
||||
if (open.length !== 2) return;
|
||||
turns += 1;
|
||||
turnsEl.textContent = String(turns);
|
||||
const [a, b] = open;
|
||||
if (a.dataset.symbol === b.dataset.symbol) {
|
||||
a.classList.add("is-matched");
|
||||
b.classList.add("is-matched");
|
||||
open = [];
|
||||
matches += 1;
|
||||
matchesEl.textContent = String(matches);
|
||||
messageEl.textContent = matches === symbols.length ? `Cabinet solved in ${turns} turns.` : "A drawer clicks open.";
|
||||
} else {
|
||||
messageEl.textContent = "No match. The cabinet quietly re-files them.";
|
||||
setTimeout(() => {
|
||||
a.classList.remove("is-open");
|
||||
b.classList.remove("is-open");
|
||||
a.textContent = "?";
|
||||
b.textContent = "?";
|
||||
a.setAttribute("aria-label", "Hidden card");
|
||||
b.setAttribute("aria-label", "Hidden card");
|
||||
open = [];
|
||||
}, 650);
|
||||
}
|
||||
}
|
||||
|
||||
$("[data-memory-reset]", root).addEventListener("click", render);
|
||||
$("[data-memory-peek]", root).addEventListener("click", () => {
|
||||
const hidden = $$(".memory-card:not(.is-open):not(.is-matched)", root);
|
||||
hidden.forEach((card) => {
|
||||
card.textContent = card.dataset.symbol;
|
||||
card.classList.add("is-peeking");
|
||||
});
|
||||
messageEl.textContent = "A very brief lapse in scholarly discipline.";
|
||||
setTimeout(() => {
|
||||
hidden.forEach((card) => {
|
||||
if (!card.classList.contains("is-open") && !card.classList.contains("is-matched")) card.textContent = "?";
|
||||
card.classList.remove("is-peeking");
|
||||
});
|
||||
}, 900);
|
||||
});
|
||||
render();
|
||||
}
|
||||
|
||||
function constellation(root) {
|
||||
const canvas = $("[data-star-canvas]", root);
|
||||
const ctx = canvas.getContext("2d");
|
||||
const linesEl = $("[data-star-lines]", root);
|
||||
const nameEl = document.createElement("strong");
|
||||
const stars = Array.from({ length: 18 }, () => ({ x: 50 + Math.random() * 800, y: 45 + Math.random() * 430 }));
|
||||
const lines = [];
|
||||
let selected = null;
|
||||
nameEl.className = "play-live-note";
|
||||
linesEl.closest(".play-scorebar").appendChild(nameEl);
|
||||
|
||||
function draw() {
|
||||
ctx.clearRect(0, 0, canvas.width, canvas.height);
|
||||
ctx.fillStyle = "#18130f";
|
||||
ctx.fillRect(0, 0, canvas.width, canvas.height);
|
||||
ctx.strokeStyle = "rgba(219, 184, 104, 0.65)";
|
||||
ctx.lineWidth = 2;
|
||||
lines.forEach(([a, b]) => {
|
||||
ctx.beginPath();
|
||||
ctx.moveTo(stars[a].x, stars[a].y);
|
||||
ctx.lineTo(stars[b].x, stars[b].y);
|
||||
ctx.stroke();
|
||||
});
|
||||
stars.forEach((star, index) => {
|
||||
ctx.beginPath();
|
||||
ctx.fillStyle = index === selected ? "#f6d889" : "#fff8e8";
|
||||
ctx.arc(star.x, star.y, index === selected ? 7 : 4, 0, Math.PI * 2);
|
||||
ctx.fill();
|
||||
});
|
||||
linesEl.textContent = String(lines.length);
|
||||
if (lines.length >= 3) nameEl.textContent = `Named: ${pick(["The Patient Spoon", "The South Window", "The Tired Comet", "The Fifth Errand"])}`;
|
||||
}
|
||||
|
||||
canvas.addEventListener("click", (event) => {
|
||||
const rect = canvas.getBoundingClientRect();
|
||||
const x = ((event.clientX - rect.left) / rect.width) * canvas.width;
|
||||
const y = ((event.clientY - rect.top) / rect.height) * canvas.height;
|
||||
const hit = stars.findIndex((star) => Math.hypot(star.x - x, star.y - y) < 22);
|
||||
if (hit < 0) return;
|
||||
if (selected === null) selected = hit;
|
||||
else if (selected !== hit) {
|
||||
lines.push([selected, hit]);
|
||||
selected = hit;
|
||||
}
|
||||
draw();
|
||||
});
|
||||
$("[data-star-reset]", root).addEventListener("click", () => {
|
||||
lines.length = 0;
|
||||
selected = null;
|
||||
nameEl.textContent = "";
|
||||
draw();
|
||||
});
|
||||
draw();
|
||||
}
|
||||
|
||||
function poem(root) {
|
||||
const output = $("[data-poem-output]", root);
|
||||
const a = ["In the margin", "By the kettle", "Under the desk lamp", "Between two errands", "After the house quiets"];
|
||||
const b = ["a careful thought", "an old joke", "a stubborn question", "a useful mistake", "a bright scrap"];
|
||||
const c = ["learns to wait.", "asks for a second reading.", "finds its proper shelf.", "becomes tomorrow's note.", "keeps the page warm."];
|
||||
let count = 0;
|
||||
function make() {
|
||||
count += 1;
|
||||
output.innerHTML = `${pick(a)}<br>${pick(b)}<br>${pick(c)}`;
|
||||
output.dataset.stamp = count % 5 === 0 ? "approved by the margin" : "";
|
||||
}
|
||||
$("[data-poem-generate]", root).addEventListener("click", make);
|
||||
make();
|
||||
}
|
||||
|
||||
function bookshelf(root) {
|
||||
const titles = ["Algebra at Breakfast", "Cabinet of Weather", "Domestic Orbits", "Evening Margins", "Household Engines", "Zettels and Tea"];
|
||||
const shelf = $("[data-bookshelf]", root);
|
||||
const status = $("[data-bookshelf-status]", root);
|
||||
let sortedOnce = false;
|
||||
setupSortable(shelf, render, check);
|
||||
$("[data-bookshelf-shuffle]", root).addEventListener("click", () => render(shuffle(titles)));
|
||||
render(shuffle(titles));
|
||||
|
||||
function render(items) {
|
||||
shelf.innerHTML = "";
|
||||
items.forEach((title) => {
|
||||
const book = document.createElement("div");
|
||||
book.className = "book-spine";
|
||||
book.draggable = true;
|
||||
book.dataset.value = title;
|
||||
book.textContent = title;
|
||||
shelf.appendChild(book);
|
||||
});
|
||||
check();
|
||||
}
|
||||
function check() {
|
||||
const current = $$(".book-spine", shelf).map((book) => book.dataset.value);
|
||||
const sorted = current.join("|") === titles.join("|");
|
||||
status.textContent = sorted ? "Shelf sorted. A secret pamphlet slides out." : "Unsorted";
|
||||
if (sorted && !sortedOnce) {
|
||||
sortedOnce = true;
|
||||
const pamphlet = document.createElement("div");
|
||||
pamphlet.className = "booklet";
|
||||
pamphlet.textContent = "Pamphlet: On the Correct Order of Small Things";
|
||||
shelf.appendChild(pamphlet);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function recipe(root) {
|
||||
const wheel = $("[data-recipe-spin]", root);
|
||||
const result = $("[data-recipe-result]", root);
|
||||
const groups = [
|
||||
["Rice", "Flatbread", "Roast potatoes", "Noodles"],
|
||||
["Lemon chicken", "Spiced lentils", "Tomato eggs", "Pepper stew"],
|
||||
["Cucumber salad", "Mint yoghurt", "Pickled onions", "Charred greens"],
|
||||
["Serve with stories", "Eat outside", "Use the blue plates", "Make extra tea"]
|
||||
];
|
||||
let spin = 0;
|
||||
let feast = 0;
|
||||
wheel.addEventListener("click", () => {
|
||||
spin += 540 + Math.floor(Math.random() * 540);
|
||||
feast += 1;
|
||||
wheel.style.transform = `rotate(${spin}deg)`;
|
||||
result.innerHTML = groups.map((group) => `<li>${pick(group)}</li>`).join("") + (feast % 4 === 0 ? "<li>Bonus: someone gets the last crispy bit.</li>" : "");
|
||||
});
|
||||
wheel.click();
|
||||
}
|
||||
|
||||
function timeline(root) {
|
||||
const items = [
|
||||
{ year: "2022", text: "The personal web habit begins." },
|
||||
{ year: "2025", text: "Org publishing becomes the main site engine." },
|
||||
{ year: "2025", text: "Weekly reviews and career notes grow into a library." },
|
||||
{ year: "2026", text: "Dashboards, services, and authoring tools join the site." },
|
||||
{ year: "2026", text: "The play wing opens." }
|
||||
];
|
||||
const list = $("[data-timeline-list]", root);
|
||||
const status = $("[data-timeline-status]", root);
|
||||
const paradox = document.createElement("button");
|
||||
paradox.type = "button";
|
||||
paradox.textContent = "Paradox";
|
||||
$("[data-timeline-shuffle]", root).insertAdjacentElement("afterend", paradox);
|
||||
setupSortable(list, render, check);
|
||||
$("[data-timeline-shuffle]", root).addEventListener("click", () => render(shuffle(items)));
|
||||
paradox.addEventListener("click", () => render([...items].reverse()));
|
||||
render(shuffle(items));
|
||||
|
||||
function render(source) {
|
||||
list.innerHTML = "";
|
||||
source.forEach((item, index) => {
|
||||
const card = document.createElement("div");
|
||||
card.className = "timeline-card";
|
||||
card.draggable = true;
|
||||
card.dataset.value = String(items.indexOf(item));
|
||||
card.innerHTML = `<span>${item.year}</span><strong>${item.text}</strong>`;
|
||||
list.appendChild(card);
|
||||
});
|
||||
check();
|
||||
}
|
||||
function check() {
|
||||
const current = $$(".timeline-card", list).map((card) => Number(card.dataset.value));
|
||||
status.textContent = current.every((value, index) => value === index) ? "Timeline restored" : "Arrange the cards";
|
||||
}
|
||||
}
|
||||
|
||||
function ink(root) {
|
||||
const canvas = $("[data-ink-canvas]", root);
|
||||
const ctx = canvas.getContext("2d");
|
||||
const drops = [];
|
||||
let moon = false;
|
||||
function addDrop(x, y, heavy) {
|
||||
drops.push({ x, y, r: heavy ? 18 : 8, life: heavy ? 1.8 : 1, hue: 28 + Math.random() * 35 });
|
||||
}
|
||||
function pointer(event, heavy) {
|
||||
const rect = canvas.getBoundingClientRect();
|
||||
addDrop(((event.clientX - rect.left) / rect.width) * canvas.width, ((event.clientY - rect.top) / rect.height) * canvas.height, heavy);
|
||||
}
|
||||
canvas.addEventListener("pointermove", (event) => pointer(event, false));
|
||||
canvas.addEventListener("click", (event) => pointer(event, true));
|
||||
canvas.addEventListener("dblclick", () => {
|
||||
moon = !moon;
|
||||
});
|
||||
function frame() {
|
||||
ctx.fillStyle = "rgba(24, 19, 15, 0.16)";
|
||||
ctx.fillRect(0, 0, canvas.width, canvas.height);
|
||||
if (moon) {
|
||||
ctx.beginPath();
|
||||
ctx.fillStyle = "rgba(246, 216, 137, 0.72)";
|
||||
ctx.arc(760, 88, 34, 0, Math.PI * 2);
|
||||
ctx.fill();
|
||||
}
|
||||
drops.forEach((drop) => {
|
||||
drop.r += 0.7;
|
||||
drop.life -= 0.012;
|
||||
ctx.beginPath();
|
||||
ctx.strokeStyle = `hsla(${drop.hue}, 65%, 68%, ${Math.max(drop.life, 0)})`;
|
||||
ctx.lineWidth = 2;
|
||||
ctx.arc(drop.x, drop.y, drop.r, 0, Math.PI * 2);
|
||||
ctx.stroke();
|
||||
});
|
||||
for (let i = drops.length - 1; i >= 0; i -= 1) if (drops[i].life <= 0) drops.splice(i, 1);
|
||||
requestAnimationFrame(frame);
|
||||
}
|
||||
frame();
|
||||
}
|
||||
|
||||
function terminal(root) {
|
||||
const log = $("[data-terminal-log]", root);
|
||||
const form = $("[data-terminal-form]", root);
|
||||
const input = $("[data-terminal-input]", root);
|
||||
let kindness = 0;
|
||||
const responses = {
|
||||
help: "Commands: help, look, map, open drawer, read note, brew tea, hum, knock, save, inventory, clear",
|
||||
look: "A narrow archive room. A lamp hums. A drawer is labelled MAYBE IMPORTANT.",
|
||||
map: "You are between the reading desk, the family shelf, and the door back to Play.",
|
||||
"open drawer": "Inside: a brass key, a receipt, and a note folded twice.",
|
||||
"read note": "The note says: keep the site useful, but leave a few doors ajar.",
|
||||
"brew tea": "The room smells briefly of cardamom. Nothing else changes, which is enough.",
|
||||
hum: "You hum four careful notes. Something behind the wall hums five back.",
|
||||
knock: "Knock. Knock. ... A polite pause. Knock.",
|
||||
save: "You save your place in the archive. The archive saves its place in you.",
|
||||
inventory: "You are carrying: a brass key, a warm cup, and one unreasonable hope."
|
||||
};
|
||||
function write(text) {
|
||||
log.textContent += `${text}\n`;
|
||||
log.scrollTop = log.scrollHeight;
|
||||
}
|
||||
form.addEventListener("submit", (event) => {
|
||||
event.preventDefault();
|
||||
const cmd = input.value.trim().toLowerCase();
|
||||
if (!cmd) return;
|
||||
input.value = "";
|
||||
if (cmd === "clear") {
|
||||
log.textContent = "";
|
||||
return;
|
||||
}
|
||||
write(`> ${cmd}`);
|
||||
if (cmd === "pet book") {
|
||||
kindness += 1;
|
||||
write(kindness > 2 ? "The book follows you for exactly three pages." : "The book accepts this with suspicious dignity.");
|
||||
} else {
|
||||
write(responses[cmd] || "The archive declines to understand that command.");
|
||||
}
|
||||
});
|
||||
write("Archive terminal ready. Type help. The cursor is listening.");
|
||||
input.focus();
|
||||
}
|
||||
|
||||
function study(root) {
|
||||
const time = $("[data-study-time]", root);
|
||||
const scene = $("[data-study-scene]", root);
|
||||
let total = 300;
|
||||
let left = total;
|
||||
let timer = null;
|
||||
const note = document.createElement("div");
|
||||
note.className = "play-live-note";
|
||||
note.textContent = "The lamp is cold.";
|
||||
time.insertAdjacentElement("afterend", note);
|
||||
function draw() {
|
||||
const done = 1 - left / total;
|
||||
scene.style.setProperty("--lamp", String(0.18 + done * 0.72));
|
||||
scene.style.setProperty("--glow", `${done * 70}px`);
|
||||
const m = String(Math.floor(left / 60)).padStart(2, "0");
|
||||
const s = String(left % 60).padStart(2, "0");
|
||||
time.textContent = `${m}:${s}`;
|
||||
if (left === 0) note.textContent = "Focus complete. The desk looks proud.";
|
||||
else if (done > 0.66) note.textContent = "The page has warmed through.";
|
||||
else if (done > 0.33) note.textContent = "The lamp has settled into its work.";
|
||||
}
|
||||
function start() {
|
||||
if (timer) return;
|
||||
timer = setInterval(() => {
|
||||
left = Math.max(0, left - 1);
|
||||
draw();
|
||||
if (left === 0) pause();
|
||||
}, 1000);
|
||||
}
|
||||
function pause() {
|
||||
clearInterval(timer);
|
||||
timer = null;
|
||||
}
|
||||
$("[data-study-start]", root).addEventListener("click", start);
|
||||
$("[data-study-pause]", root).addEventListener("click", pause);
|
||||
$("[data-study-reset]", root).addEventListener("click", () => {
|
||||
pause();
|
||||
left = total;
|
||||
draw();
|
||||
});
|
||||
draw();
|
||||
}
|
||||
|
||||
function sigil(root) {
|
||||
const canvas = $("[data-sigil-canvas]", root);
|
||||
const ctx = canvas.getContext("2d");
|
||||
const initials = $("[data-sigil-initials]", root);
|
||||
const motto = $("[data-sigil-motto]", root);
|
||||
let wax = "#9c6b2f";
|
||||
const waxButton = document.createElement("button");
|
||||
waxButton.type = "button";
|
||||
waxButton.textContent = "New wax";
|
||||
$("[data-sigil-form]", root).appendChild(waxButton);
|
||||
function draw() {
|
||||
const text = (initials.value || "ZXH").toUpperCase();
|
||||
const phrase = motto.value || "Learn, make, remember";
|
||||
ctx.clearRect(0, 0, canvas.width, canvas.height);
|
||||
ctx.fillStyle = "#fbf7ec";
|
||||
ctx.fillRect(0, 0, canvas.width, canvas.height);
|
||||
ctx.translate(260, 260);
|
||||
ctx.strokeStyle = wax;
|
||||
ctx.lineWidth = 10;
|
||||
ctx.beginPath();
|
||||
ctx.arc(0, 0, 190, 0, Math.PI * 2);
|
||||
ctx.stroke();
|
||||
ctx.lineWidth = 2;
|
||||
for (let i = 0; i < 12; i += 1) {
|
||||
ctx.rotate(Math.PI / 6);
|
||||
ctx.beginPath();
|
||||
ctx.moveTo(0, -150);
|
||||
ctx.lineTo(0, -185);
|
||||
ctx.stroke();
|
||||
}
|
||||
ctx.rotate(-Math.PI * 2);
|
||||
ctx.fillStyle = "#2a2118";
|
||||
ctx.textAlign = "center";
|
||||
ctx.textBaseline = "middle";
|
||||
ctx.font = "900 94px Georgia, serif";
|
||||
ctx.fillText(text.slice(0, 4), 0, -10);
|
||||
ctx.font = "700 22px Georgia, serif";
|
||||
ctx.fillText(phrase.slice(0, 34), 0, 88);
|
||||
ctx.setTransform(1, 0, 0, 1, 0, 0);
|
||||
}
|
||||
waxButton.addEventListener("click", () => {
|
||||
wax = pick(["#9c6b2f", "#8a3f3f", "#486b57", "#3e5f8a", "#5f4b8b"]);
|
||||
draw();
|
||||
});
|
||||
$("[data-sigil-form]", root).addEventListener("submit", (event) => {
|
||||
event.preventDefault();
|
||||
draw();
|
||||
});
|
||||
initials.addEventListener("input", draw);
|
||||
motto.addEventListener("input", draw);
|
||||
draw();
|
||||
}
|
||||
|
||||
function rpg(root) {
|
||||
if (window.AshBelowLakeRpg) return window.AshBelowLakeRpg(root);
|
||||
const canvas = $("[data-rpg-canvas]", root);
|
||||
const ctx = canvas.getContext("2d");
|
||||
const els = {
|
||||
speaker: $("[data-rpg-speaker]", root),
|
||||
line: $("[data-rpg-line]", root),
|
||||
room: $("[data-rpg-room]", root),
|
||||
route: $("[data-rpg-route]", root),
|
||||
hearts: $("[data-rpg-hearts]", root),
|
||||
quests: $("[data-rpg-quests]", root),
|
||||
inventory: $("[data-rpg-inventory]", root),
|
||||
status: $("[data-rpg-status]", root)
|
||||
};
|
||||
const tile = 32;
|
||||
const saveSlot = "hollow-archive";
|
||||
const fallbackKey = "play:rpg:hollow-archive";
|
||||
const items = {
|
||||
lamp: { label: "Desk Lamp", room: "entrance", x: 10, y: 8, color: "#f2c94c" },
|
||||
page: { label: "Loose Page", room: "stacks", x: 18, y: 5, color: "#f7efe0" },
|
||||
key: { label: "Basement Key", room: "garden", x: 4, y: 11, color: "#d59b45" }
|
||||
};
|
||||
const npcs = {
|
||||
archivist: { name: "Archivist", room: "entrance", x: 6, y: 6, color: "#b98bff" },
|
||||
shade: { name: "Shy Shade", room: "stacks", x: 17, y: 9, color: "#6ed0d4" },
|
||||
gate: { name: "Iron Door", room: "garden", x: 19, y: 10, color: "#8a8f98" }
|
||||
};
|
||||
const rooms = {
|
||||
entrance: {
|
||||
name: "Entrance",
|
||||
floor: "#353029",
|
||||
exits: [{ x: 22, y: 7, to: "stacks", px: 1, py: 7 }],
|
||||
walls: rects([[0, 0, 24, 1], [0, 15, 24, 1], [0, 0, 1, 16], [23, 0, 1, 6], [23, 9, 1, 7], [8, 3, 1, 8], [14, 7, 5, 1]])
|
||||
},
|
||||
stacks: {
|
||||
name: "Stacks",
|
||||
floor: "#242d35",
|
||||
exits: [{ x: 0, y: 7, to: "entrance", px: 22, py: 7 }, { x: 23, y: 12, to: "garden", px: 1, py: 12 }],
|
||||
walls: rects([[0, 0, 24, 1], [0, 15, 24, 1], [0, 0, 1, 6], [0, 9, 1, 7], [23, 0, 1, 11], [23, 14, 1, 2], [4, 3, 2, 10], [10, 2, 2, 11], [16, 3, 2, 5]])
|
||||
},
|
||||
garden: {
|
||||
name: "Moon Garden",
|
||||
floor: "#21362e",
|
||||
exits: [{ x: 0, y: 12, to: "stacks", px: 22, py: 12 }],
|
||||
walls: rects([[0, 0, 24, 1], [0, 15, 24, 1], [0, 0, 1, 11], [0, 14, 1, 2], [23, 0, 1, 16], [7, 4, 10, 1], [7, 10, 1, 4], [13, 10, 1, 4]])
|
||||
}
|
||||
};
|
||||
let state = freshState();
|
||||
let running = false;
|
||||
|
||||
function freshState() {
|
||||
return {
|
||||
room: "entrance",
|
||||
player: { x: 3, y: 7, facing: "down" },
|
||||
inventory: [],
|
||||
flags: {},
|
||||
route: "Undecided",
|
||||
hearts: 3,
|
||||
ending: null,
|
||||
message: { speaker: "Archivist", line: "The archive waits. Find the lamp, help the shade, then decide what to do with the locked door." }
|
||||
};
|
||||
}
|
||||
|
||||
function rects(sources) {
|
||||
const set = new Set();
|
||||
sources.forEach(([x, y, w, h]) => {
|
||||
for (let yy = y; yy < y + h; yy += 1) for (let xx = x; xx < x + w; xx += 1) set.add(`${xx},${yy}`);
|
||||
});
|
||||
return set;
|
||||
}
|
||||
|
||||
function draw() {
|
||||
const room = rooms[state.room];
|
||||
ctx.fillStyle = "#14110e";
|
||||
ctx.fillRect(0, 0, canvas.width, canvas.height);
|
||||
for (let y = 0; y < 16; y += 1) {
|
||||
for (let x = 0; x < 24; x += 1) {
|
||||
ctx.fillStyle = room.walls.has(`${x},${y}`) ? "#181716" : room.floor;
|
||||
ctx.fillRect(x * tile, y * tile, tile, tile);
|
||||
ctx.strokeStyle = "rgba(255,255,255,0.035)";
|
||||
ctx.strokeRect(x * tile, y * tile, tile, tile);
|
||||
}
|
||||
}
|
||||
room.exits.forEach((exit) => drawGlyph(exit.x, exit.y, "#c48a41", "door"));
|
||||
Object.entries(items).forEach(([id, item]) => {
|
||||
if (item.room === state.room && !state.inventory.includes(id)) drawGlyph(item.x, item.y, item.color, "item");
|
||||
});
|
||||
Object.values(npcs).forEach((npc) => {
|
||||
if (npc.room === state.room) drawGlyph(npc.x, npc.y, npc.color, npc.name === "Iron Door" ? "doorNpc" : "npc");
|
||||
});
|
||||
drawPlayer();
|
||||
renderHud();
|
||||
requestAnimationFrame(draw);
|
||||
}
|
||||
|
||||
function drawGlyph(x, y, color, kind) {
|
||||
const px = x * tile;
|
||||
const py = y * tile;
|
||||
ctx.fillStyle = color;
|
||||
if (kind === "item") {
|
||||
ctx.fillRect(px + 10, py + 10, 12, 12);
|
||||
ctx.fillStyle = "rgba(255,255,255,0.45)";
|
||||
ctx.fillRect(px + 13, py + 7, 6, 6);
|
||||
} else if (kind === "door" || kind === "doorNpc") {
|
||||
ctx.fillRect(px + 7, py + 4, 18, 25);
|
||||
ctx.fillStyle = "#211812";
|
||||
ctx.fillRect(px + 20, py + 16, 3, 3);
|
||||
} else {
|
||||
ctx.beginPath();
|
||||
ctx.arc(px + 16, py + 12, 9, 0, Math.PI * 2);
|
||||
ctx.fill();
|
||||
ctx.fillRect(px + 8, py + 20, 16, 8);
|
||||
}
|
||||
}
|
||||
|
||||
function drawPlayer() {
|
||||
const px = state.player.x * tile;
|
||||
const py = state.player.y * tile;
|
||||
ctx.fillStyle = "#f35f5f";
|
||||
ctx.beginPath();
|
||||
ctx.moveTo(px + 16, py + 7);
|
||||
ctx.bezierCurveTo(px + 2, py + 2, px + 1, py + 22, px + 16, py + 28);
|
||||
ctx.bezierCurveTo(px + 31, py + 22, px + 30, py + 2, px + 16, py + 7);
|
||||
ctx.fill();
|
||||
ctx.fillStyle = "#fff8e8";
|
||||
ctx.fillRect(px + 11, py + 13, 4, 4);
|
||||
ctx.fillRect(px + 18, py + 13, 4, 4);
|
||||
}
|
||||
|
||||
function renderHud() {
|
||||
els.speaker.textContent = state.message.speaker;
|
||||
els.line.textContent = state.ending ? endingLine() : state.message.line;
|
||||
els.room.textContent = rooms[state.room].name;
|
||||
els.route.textContent = state.route;
|
||||
els.hearts.textContent = String(state.hearts);
|
||||
els.inventory.innerHTML = state.inventory.length
|
||||
? state.inventory.map((id) => `<li>${items[id].label}</li>`).join("")
|
||||
: "<li>Empty</li>";
|
||||
const questRows = [
|
||||
["Find a light", state.inventory.includes("lamp")],
|
||||
["Return the loose page to the shade", state.flags.shadeHelped],
|
||||
["Open, force, or leave the iron door", Boolean(state.ending)]
|
||||
];
|
||||
els.quests.innerHTML = questRows.map(([text, done]) => `<li class="${done ? "is-done" : ""}">${done ? "Done: " : ""}${text}</li>`).join("");
|
||||
}
|
||||
|
||||
function move(dx, dy, facing) {
|
||||
if (!running || state.ending) return;
|
||||
state.player.facing = facing;
|
||||
const nx = state.player.x + dx;
|
||||
const ny = state.player.y + dy;
|
||||
const room = rooms[state.room];
|
||||
const exit = room.exits.find((candidate) => candidate.x === nx && candidate.y === ny);
|
||||
if (exit) {
|
||||
state.room = exit.to;
|
||||
state.player.x = exit.px;
|
||||
state.player.y = exit.py;
|
||||
say("Narrator", `You enter ${rooms[state.room].name}.`);
|
||||
autosave();
|
||||
return;
|
||||
}
|
||||
if (nx < 0 || ny < 0 || nx > 23 || ny > 15 || room.walls.has(`${nx},${ny}`) || npcAt(nx, ny)) return;
|
||||
state.player.x = nx;
|
||||
state.player.y = ny;
|
||||
const item = itemAt(nx, ny);
|
||||
if (item) take(item);
|
||||
}
|
||||
|
||||
function act() {
|
||||
if (!running) return start();
|
||||
if (state.ending) return;
|
||||
const front = inFront();
|
||||
const npc = npcAt(front.x, front.y);
|
||||
if (npc) talk(npc);
|
||||
else {
|
||||
const here = itemAt(state.player.x, state.player.y);
|
||||
if (here) take(here);
|
||||
else say("Narrator", "Dust moves in the light. Nothing asks to be changed here.");
|
||||
}
|
||||
autosave();
|
||||
}
|
||||
|
||||
function inFront() {
|
||||
const delta = { up: [0, -1], down: [0, 1], left: [-1, 0], right: [1, 0] }[state.player.facing] || [0, 1];
|
||||
return { x: state.player.x + delta[0], y: state.player.y + delta[1] };
|
||||
}
|
||||
|
||||
function itemAt(x, y) {
|
||||
return Object.keys(items).find((id) => {
|
||||
const item = items[id];
|
||||
return item.room === state.room && item.x === x && item.y === y && !state.inventory.includes(id);
|
||||
});
|
||||
}
|
||||
|
||||
function npcAt(x, y) {
|
||||
return Object.keys(npcs).find((id) => {
|
||||
const npc = npcs[id];
|
||||
return npc.room === state.room && npc.x === x && npc.y === y;
|
||||
});
|
||||
}
|
||||
|
||||
function take(id) {
|
||||
state.inventory.push(id);
|
||||
if (id === "lamp") state.route = "Gentle";
|
||||
if (id === "key" && !state.flags.shadeHelped) state.route = "Power";
|
||||
say("Found", `${items[id].label} joined your inventory.`);
|
||||
}
|
||||
|
||||
function talk(id) {
|
||||
if (id === "archivist") {
|
||||
if (!state.inventory.includes("lamp")) say("Archivist", "Take the lamp from the lower desk. The stacks dislike being crossed in the dark.");
|
||||
else if (!state.flags.shadeHelped) say("Archivist", "A loose page has gone missing. The quiet reader in the stacks knows where it belongs.");
|
||||
else say("Archivist", "You have been kind to a forgotten page. The garden door will remember that.");
|
||||
}
|
||||
if (id === "shade") {
|
||||
if (!state.inventory.includes("page")) say("Shy Shade", "I lost the page with my name on it. It fell somewhere nearby.");
|
||||
else {
|
||||
state.flags.shadeHelped = true;
|
||||
state.inventory = state.inventory.filter((item) => item !== "page");
|
||||
state.route = "Mercy";
|
||||
say("Shy Shade", "You returned my page instead of keeping it. Take the honest route through the garden.");
|
||||
}
|
||||
}
|
||||
if (id === "gate") {
|
||||
if (state.flags.shadeHelped) end("mercy");
|
||||
else if (state.inventory.includes("key")) end("power");
|
||||
else end("quiet");
|
||||
}
|
||||
}
|
||||
|
||||
function end(kind) {
|
||||
state.ending = kind;
|
||||
state.route = kind === "mercy" ? "Mercy" : kind === "power" ? "Power" : "Quiet";
|
||||
say("Ending", endingLine());
|
||||
save();
|
||||
}
|
||||
|
||||
function endingLine() {
|
||||
if (state.ending === "mercy") return "Mercy ending: the iron door opens without a sound, and every returned page remembers your name.";
|
||||
if (state.ending === "power") return "Power ending: the key turns, but the archive grows colder around the missing page.";
|
||||
if (state.ending === "quiet") return "Quiet ending: you leave the locked door alone. Some mysteries stay intact.";
|
||||
return state.message.line;
|
||||
}
|
||||
|
||||
function say(speaker, line) {
|
||||
state.message = { speaker, line };
|
||||
}
|
||||
|
||||
function start() {
|
||||
running = true;
|
||||
say("Archivist", "Walk the archive. Speak gently, or take what you need. The route will notice.");
|
||||
els.status.textContent = "Started. Progress autosaves after room changes and actions.";
|
||||
}
|
||||
|
||||
async function save() {
|
||||
localStorage.setItem(fallbackKey, JSON.stringify(state));
|
||||
try {
|
||||
const response = await fetch(`/api/play/rpg/save/${saveSlot}`, {
|
||||
method: "PUT",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ payload: state })
|
||||
});
|
||||
if (!response.ok) throw new Error(`Save failed: ${response.status}`);
|
||||
els.status.textContent = "Saved to backend.";
|
||||
} catch (_error) {
|
||||
els.status.textContent = "Saved locally. Backend save API was not reachable.";
|
||||
}
|
||||
}
|
||||
|
||||
async function load() {
|
||||
try {
|
||||
const response = await fetch(`/api/play/rpg/save/${saveSlot}`);
|
||||
if (response.ok) {
|
||||
const data = await response.json();
|
||||
state = normalizeState(data.payload);
|
||||
running = true;
|
||||
els.status.textContent = "Loaded from backend.";
|
||||
return;
|
||||
}
|
||||
} catch (_error) {
|
||||
/* Fall through to local save. */
|
||||
}
|
||||
const local = localStorage.getItem(fallbackKey);
|
||||
if (local) {
|
||||
state = normalizeState(JSON.parse(local));
|
||||
running = true;
|
||||
els.status.textContent = "Loaded local save.";
|
||||
} else {
|
||||
els.status.textContent = "No save found.";
|
||||
}
|
||||
}
|
||||
|
||||
function normalizeState(candidate) {
|
||||
return Object.assign(freshState(), candidate || {}, {
|
||||
player: Object.assign(freshState().player, (candidate && candidate.player) || {}),
|
||||
inventory: Array.isArray(candidate && candidate.inventory) ? candidate.inventory.filter((id) => items[id]) : [],
|
||||
flags: Object.assign({}, (candidate && candidate.flags) || {}),
|
||||
message: Object.assign(freshState().message, (candidate && candidate.message) || {})
|
||||
});
|
||||
}
|
||||
|
||||
function autosave() {
|
||||
save();
|
||||
}
|
||||
|
||||
$("[data-rpg-start]", root).addEventListener("click", start);
|
||||
$("[data-rpg-save]", root).addEventListener("click", save);
|
||||
$("[data-rpg-load]", root).addEventListener("click", load);
|
||||
$("[data-rpg-reset]", root).addEventListener("click", async () => {
|
||||
state = freshState();
|
||||
running = false;
|
||||
localStorage.removeItem(fallbackKey);
|
||||
try {
|
||||
await fetch(`/api/play/rpg/save/${saveSlot}`, { method: "DELETE" });
|
||||
els.status.textContent = "Reset and cleared backend save.";
|
||||
} catch (_error) {
|
||||
els.status.textContent = "Reset locally. Backend save API was not reachable.";
|
||||
}
|
||||
});
|
||||
$("[data-rpg-act]", root).addEventListener("click", act);
|
||||
$$("[data-rpg-move]", root).forEach((button) => {
|
||||
const moves = { up: [0, -1, "up"], down: [0, 1, "down"], left: [-1, 0, "left"], right: [1, 0, "right"] };
|
||||
button.addEventListener("click", () => move(...moves[button.dataset.rpgMove]));
|
||||
});
|
||||
window.addEventListener("keydown", (event) => {
|
||||
if (!root.isConnected) return;
|
||||
const tag = event.target.tagName;
|
||||
if (tag === "INPUT" || tag === "TEXTAREA") return;
|
||||
const keys = {
|
||||
ArrowUp: [0, -1, "up"], w: [0, -1, "up"],
|
||||
ArrowDown: [0, 1, "down"], s: [0, 1, "down"],
|
||||
ArrowLeft: [-1, 0, "left"], a: [-1, 0, "left"],
|
||||
ArrowRight: [1, 0, "right"], d: [1, 0, "right"]
|
||||
};
|
||||
if (keys[event.key]) {
|
||||
event.preventDefault();
|
||||
move(...keys[event.key]);
|
||||
}
|
||||
if (event.key === " " || event.key === "Enter") {
|
||||
event.preventDefault();
|
||||
act();
|
||||
}
|
||||
});
|
||||
draw();
|
||||
load();
|
||||
}
|
||||
|
||||
function setupSortable(container, _render, after) {
|
||||
let dragged = null;
|
||||
container.addEventListener("dragstart", (event) => {
|
||||
dragged = event.target.closest("[draggable='true']");
|
||||
if (dragged) event.dataTransfer.effectAllowed = "move";
|
||||
});
|
||||
container.addEventListener("dragover", (event) => {
|
||||
event.preventDefault();
|
||||
const target = event.target.closest("[draggable='true']");
|
||||
if (!dragged || !target || target === dragged) return;
|
||||
const rect = target.getBoundingClientRect();
|
||||
const before = event.clientY < rect.top + rect.height / 2 || event.clientX < rect.left + rect.width / 2;
|
||||
container.insertBefore(dragged, before ? target : target.nextSibling);
|
||||
after();
|
||||
});
|
||||
container.addEventListener("dragend", () => {
|
||||
dragged = null;
|
||||
after();
|
||||
});
|
||||
}
|
||||
|
||||
function pick(items) {
|
||||
return items[Math.floor(Math.random() * items.length)];
|
||||
}
|
||||
})();
|
||||
398
assets/scripts/pages/sitemap-interactive.js
Normal file
398
assets/scripts/pages/sitemap-interactive.js
Normal file
@@ -0,0 +1,398 @@
|
||||
/**
|
||||
* sitemap-interactive.js
|
||||
* Drop into /assets/scripts/ — no .org changes required.
|
||||
*
|
||||
* Handles two page structures generated by org-publish:
|
||||
* 1. FLAT LIST — a top-level <ul class="org-ul"> (e.g. Sitemap)
|
||||
* 2. OUTLINE — <div class="outline-2/3"> with <h2>/<h3> headings and
|
||||
* nested <ul class="org-ul"> (e.g. "2025 List", "Blogs List")
|
||||
*
|
||||
* Activated on any page whose <h1 class="title"> matches SITEMAP_PATTERNS.
|
||||
*/
|
||||
|
||||
(function () {
|
||||
"use strict";
|
||||
|
||||
const SITEMAP_PATTERNS = ["sitemap", "list"];
|
||||
|
||||
function init() {
|
||||
const titleEl = document.querySelector("h1.title");
|
||||
if (!titleEl) return;
|
||||
const title = titleEl.textContent.trim().toLowerCase();
|
||||
if (!SITEMAP_PATTERNS.some((p) => title.includes(p))) return;
|
||||
|
||||
const contentDiv = document.getElementById("content");
|
||||
if (!contentDiv) return;
|
||||
|
||||
const hasOutline = !!contentDiv.querySelector(".outline-2, .outline-3");
|
||||
const topUl = !hasOutline && contentDiv.querySelector("ul.org-ul");
|
||||
if (!hasOutline && !topUl) return;
|
||||
|
||||
// ── Parsers ───────────────────────────────────────────────────────────
|
||||
|
||||
function parseLi(li) {
|
||||
const link = li.querySelector(":scope > a");
|
||||
const childUl = li.querySelector(":scope > ul");
|
||||
const textNode = Array.from(li.childNodes).find(
|
||||
(n) => n.nodeType === Node.TEXT_NODE && n.textContent.trim()
|
||||
);
|
||||
const tags = Array.from(li.querySelectorAll(".post-tag")).map((t) =>
|
||||
t.textContent.trim()
|
||||
);
|
||||
const dateEl = li.querySelector(".post-date");
|
||||
const date = dateEl ? dateEl.textContent.trim() : null;
|
||||
|
||||
return {
|
||||
label: link
|
||||
? link.textContent.trim()
|
||||
: textNode
|
||||
? textNode.textContent.trim()
|
||||
: li.childNodes[0]?.textContent?.trim() || "",
|
||||
href: link ? link.getAttribute("href") : null,
|
||||
tags,
|
||||
date,
|
||||
children: childUl ? parseUl(childUl) : [],
|
||||
};
|
||||
}
|
||||
|
||||
function parseUl(ul) {
|
||||
return Array.from(ul.children)
|
||||
.filter((li) => li.tagName === "LI")
|
||||
.map(parseLi);
|
||||
}
|
||||
|
||||
function parseFlatList() {
|
||||
return { tree: parseUl(topUl), replaceTarget: topUl, wrapOutline: false };
|
||||
}
|
||||
|
||||
function parseOutline() {
|
||||
const tree = [];
|
||||
const outline2s = contentDiv.querySelectorAll(":scope .outline-2");
|
||||
|
||||
if (outline2s.length === 0) {
|
||||
// Only outline-3 directly (flat month grouping without year wrapper)
|
||||
contentDiv.querySelectorAll(":scope .outline-3").forEach((section) => {
|
||||
const heading = section.querySelector("h3");
|
||||
const ul = section.querySelector("ul.org-ul");
|
||||
tree.push({
|
||||
label: heading ? heading.textContent.trim() : "Section",
|
||||
href: null, tags: [], date: null,
|
||||
children: ul ? parseUl(ul) : [],
|
||||
});
|
||||
});
|
||||
} else {
|
||||
outline2s.forEach((o2) => {
|
||||
const h2 = o2.querySelector(":scope > div > h2, :scope > h2");
|
||||
const groupNode = {
|
||||
label: h2 ? h2.textContent.trim() : "Group",
|
||||
href: null, tags: [], date: null,
|
||||
children: [],
|
||||
};
|
||||
const outline3s = o2.querySelectorAll(".outline-3");
|
||||
if (outline3s.length > 0) {
|
||||
outline3s.forEach((o3) => {
|
||||
const h3 = o3.querySelector(":scope > div > h3, :scope > h3");
|
||||
const ul = o3.querySelector("ul.org-ul");
|
||||
groupNode.children.push({
|
||||
label: h3 ? h3.textContent.trim() : "Month",
|
||||
href: null, tags: [], date: null,
|
||||
children: ul ? parseUl(ul) : [],
|
||||
});
|
||||
});
|
||||
} else {
|
||||
const ul = o2.querySelector("ul.org-ul");
|
||||
if (ul) groupNode.children = parseUl(ul);
|
||||
}
|
||||
tree.push(groupNode);
|
||||
});
|
||||
}
|
||||
|
||||
return { tree, replaceTarget: null, wrapOutline: true };
|
||||
}
|
||||
|
||||
const parsed = hasOutline ? parseOutline() : parseFlatList();
|
||||
const { tree } = parsed;
|
||||
if (!tree.length) return;
|
||||
|
||||
// ── Styles ────────────────────────────────────────────────────────────
|
||||
if (!document.getElementById("sm-styles")) {
|
||||
const style = document.createElement("style");
|
||||
style.id = "sm-styles";
|
||||
style.textContent = `
|
||||
.sitemap-interactive { font-family: inherit; margin: 1.5rem 0; }
|
||||
.sm-toolbar {
|
||||
display: flex; align-items: center; gap: .6rem;
|
||||
margin-bottom: 1rem; flex-wrap: wrap;
|
||||
}
|
||||
.sm-search {
|
||||
flex: 1; min-width: 160px; padding: .35rem .7rem;
|
||||
border: 1px solid var(--border, #444); border-radius: 4px;
|
||||
background: var(--bg, transparent); color: inherit; font-size: .9rem;
|
||||
}
|
||||
.sm-search:focus { outline: 2px solid var(--accent, #7aa2f7); outline-offset: 1px; }
|
||||
.sm-expand-all, .sm-collapse-all {
|
||||
padding: .3rem .65rem; border: 1px solid var(--border, #444);
|
||||
border-radius: 4px; background: transparent; color: inherit;
|
||||
font-size: .8rem; cursor: pointer; opacity: .75; transition: opacity .15s;
|
||||
}
|
||||
.sm-expand-all:hover, .sm-collapse-all:hover { opacity: 1; }
|
||||
|
||||
.sm-tree ul { list-style: none; margin: 0; padding: 0 0 0 1.4rem; }
|
||||
.sm-tree > ul { padding-left: 0; }
|
||||
.sm-tree li { margin: 0; }
|
||||
.sm-node {
|
||||
display: flex; align-items: center; gap: .4rem;
|
||||
padding: .2rem .3rem; border-radius: 4px;
|
||||
line-height: 1.5; transition: background .1s; flex-wrap: wrap;
|
||||
}
|
||||
.sm-node:hover { background: var(--hover-bg, rgba(122,162,247,.08)); }
|
||||
.sm-node.sm-hidden { display: none; }
|
||||
|
||||
.sm-toggle {
|
||||
width: 1.2rem; height: 1.2rem; display: inline-flex;
|
||||
align-items: center; justify-content: center;
|
||||
cursor: pointer; border: none; background: none; color: inherit;
|
||||
font-size: .7rem; opacity: .6;
|
||||
transition: transform .18s, opacity .15s;
|
||||
flex-shrink: 0; padding: 0; border-radius: 3px;
|
||||
}
|
||||
.sm-toggle:hover { opacity: 1; background: var(--hover-bg, rgba(122,162,247,.15)); }
|
||||
.sm-toggle.open { transform: rotate(90deg); }
|
||||
.sm-toggle-placeholder { width: 1.2rem; flex-shrink: 0; }
|
||||
|
||||
.sm-icon { font-size: .8rem; opacity: .5; flex-shrink: 0; }
|
||||
|
||||
.sm-label a { color: var(--link, inherit); text-decoration: none; font-size: .9rem; }
|
||||
.sm-label a:hover { text-decoration: underline; }
|
||||
.sm-label span { font-size: .9rem; font-weight: 600; opacity: .85; }
|
||||
|
||||
.sm-badge {
|
||||
font-size: .65rem; padding: .05rem .35rem; border-radius: 8px;
|
||||
background: var(--badge-bg, rgba(122,162,247,.15));
|
||||
color: var(--badge-fg, #7aa2f7); opacity: .8;
|
||||
}
|
||||
.sm-date { font-size: .75rem; opacity: .45; margin-left: .2rem; }
|
||||
.sm-tags { display: inline-flex; gap: .25rem; margin-left: .2rem; }
|
||||
.sm-tag {
|
||||
font-size: .65rem; padding: .05rem .3rem; border-radius: 8px;
|
||||
background: var(--tag-bg, rgba(160,200,120,.15));
|
||||
color: var(--tag-fg, #9ece6a); opacity: .85;
|
||||
}
|
||||
|
||||
.sm-children { overflow: hidden; }
|
||||
.sm-children.collapsed { display: none; }
|
||||
.sm-label mark {
|
||||
background: var(--mark-bg, rgba(255,200,50,.3));
|
||||
color: inherit; border-radius: 2px; padding: 0 1px;
|
||||
}
|
||||
.sm-count { font-size: .78rem; opacity: .45; margin-top: .8rem; }
|
||||
`;
|
||||
document.head.appendChild(style);
|
||||
}
|
||||
|
||||
// ── Widget scaffold ───────────────────────────────────────────────────
|
||||
const wrapper = document.createElement("div");
|
||||
wrapper.className = "sitemap-interactive";
|
||||
wrapper.innerHTML = `
|
||||
<div class="sm-toolbar">
|
||||
<input class="sm-search" type="search" placeholder="Filter pages…" aria-label="Filter" />
|
||||
<button class="sm-expand-all">⊞ Expand all</button>
|
||||
<button class="sm-collapse-all">⊟ Collapse all</button>
|
||||
</div>
|
||||
<div class="sm-tree" role="tree"></div>
|
||||
<p class="sm-count"></p>
|
||||
`;
|
||||
|
||||
const treeEl = wrapper.querySelector(".sm-tree");
|
||||
const searchEl = wrapper.querySelector(".sm-search");
|
||||
const countEl = wrapper.querySelector(".sm-count");
|
||||
|
||||
// ── Tree builder ──────────────────────────────────────────────────────
|
||||
function countLeaves(nodes) {
|
||||
let n = 0;
|
||||
for (const node of nodes) {
|
||||
if (!node.children || !node.children.length) n++;
|
||||
else n += countLeaves(node.children);
|
||||
}
|
||||
return n;
|
||||
}
|
||||
|
||||
function buildTree(nodes) {
|
||||
const ul = document.createElement("ul");
|
||||
for (const node of nodes) {
|
||||
const li = document.createElement("li");
|
||||
const row = document.createElement("div");
|
||||
row.className = "sm-node";
|
||||
const hasChildren = node.children && node.children.length > 0;
|
||||
|
||||
let childrenEl;
|
||||
if (hasChildren) {
|
||||
const toggle = document.createElement("button");
|
||||
toggle.className = "sm-toggle open";
|
||||
toggle.innerHTML = "▶";
|
||||
toggle.setAttribute("aria-expanded", "true");
|
||||
childrenEl = document.createElement("div");
|
||||
childrenEl.className = "sm-children";
|
||||
childrenEl.appendChild(buildTree(node.children));
|
||||
toggle.addEventListener("click", () => {
|
||||
childrenEl.classList.toggle("collapsed");
|
||||
toggle.classList.toggle("open");
|
||||
toggle.setAttribute("aria-expanded",
|
||||
String(!childrenEl.classList.contains("collapsed")));
|
||||
});
|
||||
row.appendChild(toggle);
|
||||
} else {
|
||||
const ph = document.createElement("span");
|
||||
ph.className = "sm-toggle-placeholder";
|
||||
row.appendChild(ph);
|
||||
}
|
||||
|
||||
const icon = document.createElement("span");
|
||||
icon.className = "sm-icon";
|
||||
icon.textContent = hasChildren ? "📂" : "📄";
|
||||
row.appendChild(icon);
|
||||
|
||||
const labelEl = document.createElement("span");
|
||||
labelEl.className = "sm-label";
|
||||
if (node.href) {
|
||||
const a = document.createElement("a");
|
||||
a.href = node.href;
|
||||
a.textContent = node.label;
|
||||
labelEl.appendChild(a);
|
||||
} else {
|
||||
const s = document.createElement("span");
|
||||
s.textContent = node.label;
|
||||
labelEl.appendChild(s);
|
||||
}
|
||||
row.appendChild(labelEl);
|
||||
|
||||
if (hasChildren) {
|
||||
const badge = document.createElement("span");
|
||||
badge.className = "sm-badge";
|
||||
badge.textContent = countLeaves(node.children);
|
||||
row.appendChild(badge);
|
||||
}
|
||||
|
||||
if (node.date) {
|
||||
const dateSpan = document.createElement("span");
|
||||
dateSpan.className = "sm-date";
|
||||
dateSpan.textContent = node.date;
|
||||
row.appendChild(dateSpan);
|
||||
}
|
||||
|
||||
if (node.tags && node.tags.length) {
|
||||
const tagsEl = document.createElement("span");
|
||||
tagsEl.className = "sm-tags";
|
||||
node.tags.forEach((t) => {
|
||||
const tag = document.createElement("span");
|
||||
tag.className = "sm-tag";
|
||||
tag.textContent = t;
|
||||
tagsEl.appendChild(tag);
|
||||
});
|
||||
row.appendChild(tagsEl);
|
||||
}
|
||||
|
||||
li.appendChild(row);
|
||||
if (hasChildren) li.appendChild(childrenEl);
|
||||
ul.appendChild(li);
|
||||
}
|
||||
return ul;
|
||||
}
|
||||
|
||||
treeEl.appendChild(buildTree(tree));
|
||||
|
||||
// ── Search / filter ───────────────────────────────────────────────────
|
||||
function escapeRe(s) {
|
||||
return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
||||
}
|
||||
|
||||
function filterTree(q) {
|
||||
const query = q.trim().toLowerCase();
|
||||
const re = query ? new RegExp(escapeRe(query), "gi") : null;
|
||||
let visible = 0;
|
||||
|
||||
function walk(ul) {
|
||||
let anyVisible = false;
|
||||
for (const li of ul.children) {
|
||||
const row = li.querySelector(":scope > .sm-node");
|
||||
const childrenDiv = li.querySelector(":scope > .sm-children");
|
||||
const labelEl = row.querySelector(".sm-label");
|
||||
const target = labelEl.querySelector("a") || labelEl.querySelector("span");
|
||||
const text = target.dataset.orig || target.textContent;
|
||||
target.dataset.orig = text;
|
||||
|
||||
let selfMatch = false;
|
||||
if (!query) {
|
||||
target.innerHTML = "";
|
||||
target.textContent = text;
|
||||
selfMatch = true;
|
||||
} else if (text.toLowerCase().includes(query)) {
|
||||
target.innerHTML = text.replace(re, (m) => `<mark>${m}</mark>`);
|
||||
selfMatch = true;
|
||||
} else {
|
||||
target.innerHTML = "";
|
||||
target.textContent = text;
|
||||
}
|
||||
|
||||
let childVisible = false;
|
||||
if (childrenDiv) {
|
||||
childVisible = walk(childrenDiv.querySelector("ul"));
|
||||
if (query) {
|
||||
childrenDiv.classList.toggle("collapsed", !childVisible && !selfMatch);
|
||||
const toggle = row.querySelector(".sm-toggle");
|
||||
if (toggle) toggle.classList.toggle("open", childVisible || selfMatch);
|
||||
}
|
||||
}
|
||||
|
||||
const show = !query || selfMatch || childVisible;
|
||||
row.classList.toggle("sm-hidden", !show);
|
||||
if (show) {
|
||||
anyVisible = true;
|
||||
if (!childrenDiv) visible++;
|
||||
}
|
||||
}
|
||||
return anyVisible;
|
||||
}
|
||||
|
||||
walk(treeEl.querySelector("ul"));
|
||||
countEl.textContent = query
|
||||
? `${visible} page${visible !== 1 ? "s" : ""} matching "${query}"`
|
||||
: "";
|
||||
}
|
||||
|
||||
searchEl.addEventListener("input", (e) => filterTree(e.target.value));
|
||||
|
||||
wrapper.querySelector(".sm-expand-all").addEventListener("click", () => {
|
||||
treeEl.querySelectorAll(".sm-children").forEach((el) => el.classList.remove("collapsed"));
|
||||
treeEl.querySelectorAll(".sm-toggle").forEach((el) => {
|
||||
el.classList.add("open");
|
||||
el.setAttribute("aria-expanded", "true");
|
||||
});
|
||||
});
|
||||
wrapper.querySelector(".sm-collapse-all").addEventListener("click", () => {
|
||||
treeEl.querySelectorAll(".sm-children").forEach((el) => el.classList.add("collapsed"));
|
||||
treeEl.querySelectorAll(".sm-toggle").forEach((el) => {
|
||||
el.classList.remove("open");
|
||||
el.setAttribute("aria-expanded", "false");
|
||||
});
|
||||
});
|
||||
|
||||
// ── Inject into page ──────────────────────────────────────────────────
|
||||
if (parsed.wrapOutline) {
|
||||
// Hide original outline divs (direct children of content only)
|
||||
contentDiv.querySelectorAll(":scope > .outline-2, :scope > .outline-3")
|
||||
.forEach((el) => (el.style.display = "none"));
|
||||
// Insert after title + optional intro <p>
|
||||
const insertAfter = contentDiv.querySelector(":scope > p") || titleEl;
|
||||
insertAfter.insertAdjacentElement("afterend", wrapper);
|
||||
} else {
|
||||
parsed.replaceTarget.replaceWith(wrapper);
|
||||
}
|
||||
}
|
||||
|
||||
if (document.readyState === "loading") {
|
||||
document.addEventListener("DOMContentLoaded", init);
|
||||
} else {
|
||||
init();
|
||||
}
|
||||
})();
|
||||
1787
assets/scripts/pages/wird-tracker.js
Normal file
1787
assets/scripts/pages/wird-tracker.js
Normal file
File diff suppressed because it is too large
Load Diff
@@ -1,866 +1,7 @@
|
||||
(function () {
|
||||
const $ = (sel, root = document) => root.querySelector(sel);
|
||||
const $$ = (sel, root = document) => Array.from(root.querySelectorAll(sel));
|
||||
const shuffle = (items) => items.map((value) => ({ value, sort: Math.random() })).sort((a, b) => a.sort - b.sort).map((item) => item.value);
|
||||
const quips = [
|
||||
"A margin note blinks, then pretends it did not.",
|
||||
"Somewhere, a bookmark changes its mind.",
|
||||
"The archive is pleased by unnecessary curiosity.",
|
||||
"A tiny bell rings in a room you have not built yet.",
|
||||
"The page remembers that you came here."
|
||||
];
|
||||
|
||||
document.addEventListener("DOMContentLoaded", () => {
|
||||
const root = $(".play-root[data-play-page]");
|
||||
if (!root) return;
|
||||
const page = root.dataset.playPage;
|
||||
const inits = { hub, memory, constellation, poem, bookshelf, recipe, timeline, ink, terminal, study, sigil, rpg };
|
||||
if (inits[page]) inits[page](root);
|
||||
});
|
||||
|
||||
function hub(root) {
|
||||
const links = $$(".play-grid a", root);
|
||||
const nodes = $$(".play-orbit__node", root);
|
||||
const title = $("#play-hub-title", root);
|
||||
const kind = $("#play-hub-kind", root);
|
||||
const desc = $("#play-hub-desc", root);
|
||||
const cta = $("#play-hub-link", root);
|
||||
const whisper = document.createElement("p");
|
||||
let active = 0;
|
||||
|
||||
whisper.className = "play-whisper";
|
||||
whisper.setAttribute("aria-live", "polite");
|
||||
$(".play-console__screen", root).appendChild(whisper);
|
||||
|
||||
nodes.forEach((node, index) => {
|
||||
const angle = (index / nodes.length) * Math.PI * 2 - Math.PI / 2;
|
||||
node.style.left = `${50 + Math.cos(angle) * 43}%`;
|
||||
node.style.top = `${50 + Math.sin(angle) * 43}%`;
|
||||
node.addEventListener("click", () => setActive(index));
|
||||
});
|
||||
|
||||
function setActive(index) {
|
||||
active = (index + links.length) % links.length;
|
||||
const link = links[active];
|
||||
links.forEach((item, i) => item.classList.toggle("is-active", i === active));
|
||||
nodes.forEach((item, i) => item.classList.toggle("is-active", i === active));
|
||||
title.textContent = link.querySelector("strong").textContent;
|
||||
kind.textContent = link.dataset.kind;
|
||||
desc.textContent = link.dataset.desc;
|
||||
cta.href = link.href;
|
||||
whisper.textContent = quips[active % quips.length];
|
||||
}
|
||||
|
||||
links.forEach((link, index) => {
|
||||
link.addEventListener("mouseenter", () => setActive(index));
|
||||
link.addEventListener("focus", () => setActive(index));
|
||||
});
|
||||
$("[data-play-prev]", root).addEventListener("click", () => setActive(active - 1));
|
||||
$("[data-play-next]", root).addEventListener("click", () => setActive(active + 1));
|
||||
$("[data-play-random]", root).addEventListener("click", () => setActive(Math.floor(Math.random() * links.length)));
|
||||
$(".play-orbit", root).addEventListener("dblclick", () => {
|
||||
whisper.textContent = "You knocked twice. The cabinet knocked once back.";
|
||||
root.classList.toggle("is-odd");
|
||||
});
|
||||
root.addEventListener("keydown", (event) => {
|
||||
if (event.key === "ArrowLeft") setActive(active - 1);
|
||||
if (event.key === "ArrowRight") setActive(active + 1);
|
||||
});
|
||||
setActive(0);
|
||||
}
|
||||
|
||||
function memory(root) {
|
||||
const symbols = ["Ink", "Lamp", "Tea", "Book", "Map", "Key"];
|
||||
const board = $("[data-memory-board]", root);
|
||||
const turnsEl = $("[data-memory-turns]", root);
|
||||
const matchesEl = $("[data-memory-matches]", root);
|
||||
const messageEl = $("[data-memory-message]", root);
|
||||
let open = [];
|
||||
let turns = 0;
|
||||
let matches = 0;
|
||||
let deck = [];
|
||||
|
||||
function render() {
|
||||
board.innerHTML = "";
|
||||
open = [];
|
||||
turns = 0;
|
||||
matches = 0;
|
||||
deck = shuffle([...symbols, ...symbols]);
|
||||
turnsEl.textContent = "0";
|
||||
matchesEl.textContent = "0";
|
||||
messageEl.textContent = "Cards are shuffled.";
|
||||
deck.forEach((symbol, index) => {
|
||||
const card = document.createElement("button");
|
||||
card.type = "button";
|
||||
card.className = "memory-card";
|
||||
card.dataset.symbol = symbol;
|
||||
card.textContent = "?";
|
||||
card.style.setProperty("--tilt", `${(index % 5) - 2}deg`);
|
||||
card.setAttribute("aria-label", "Hidden card");
|
||||
card.addEventListener("click", () => flip(card));
|
||||
board.appendChild(card);
|
||||
});
|
||||
}
|
||||
|
||||
function flip(card) {
|
||||
if (card.classList.contains("is-open") || card.classList.contains("is-matched") || open.length === 2) return;
|
||||
card.classList.add("is-open");
|
||||
card.textContent = card.dataset.symbol;
|
||||
card.setAttribute("aria-label", card.dataset.symbol);
|
||||
open.push(card);
|
||||
if (open.length !== 2) return;
|
||||
turns += 1;
|
||||
turnsEl.textContent = String(turns);
|
||||
const [a, b] = open;
|
||||
if (a.dataset.symbol === b.dataset.symbol) {
|
||||
a.classList.add("is-matched");
|
||||
b.classList.add("is-matched");
|
||||
open = [];
|
||||
matches += 1;
|
||||
matchesEl.textContent = String(matches);
|
||||
messageEl.textContent = matches === symbols.length ? `Cabinet solved in ${turns} turns.` : "A drawer clicks open.";
|
||||
} else {
|
||||
messageEl.textContent = "No match. The cabinet quietly re-files them.";
|
||||
setTimeout(() => {
|
||||
a.classList.remove("is-open");
|
||||
b.classList.remove("is-open");
|
||||
a.textContent = "?";
|
||||
b.textContent = "?";
|
||||
a.setAttribute("aria-label", "Hidden card");
|
||||
b.setAttribute("aria-label", "Hidden card");
|
||||
open = [];
|
||||
}, 650);
|
||||
}
|
||||
}
|
||||
|
||||
$("[data-memory-reset]", root).addEventListener("click", render);
|
||||
$("[data-memory-peek]", root).addEventListener("click", () => {
|
||||
const hidden = $$(".memory-card:not(.is-open):not(.is-matched)", root);
|
||||
hidden.forEach((card) => {
|
||||
card.textContent = card.dataset.symbol;
|
||||
card.classList.add("is-peeking");
|
||||
});
|
||||
messageEl.textContent = "A very brief lapse in scholarly discipline.";
|
||||
setTimeout(() => {
|
||||
hidden.forEach((card) => {
|
||||
if (!card.classList.contains("is-open") && !card.classList.contains("is-matched")) card.textContent = "?";
|
||||
card.classList.remove("is-peeking");
|
||||
});
|
||||
}, 900);
|
||||
});
|
||||
render();
|
||||
}
|
||||
|
||||
function constellation(root) {
|
||||
const canvas = $("[data-star-canvas]", root);
|
||||
const ctx = canvas.getContext("2d");
|
||||
const linesEl = $("[data-star-lines]", root);
|
||||
const nameEl = document.createElement("strong");
|
||||
const stars = Array.from({ length: 18 }, () => ({ x: 50 + Math.random() * 800, y: 45 + Math.random() * 430 }));
|
||||
const lines = [];
|
||||
let selected = null;
|
||||
nameEl.className = "play-live-note";
|
||||
linesEl.closest(".play-scorebar").appendChild(nameEl);
|
||||
|
||||
function draw() {
|
||||
ctx.clearRect(0, 0, canvas.width, canvas.height);
|
||||
ctx.fillStyle = "#18130f";
|
||||
ctx.fillRect(0, 0, canvas.width, canvas.height);
|
||||
ctx.strokeStyle = "rgba(219, 184, 104, 0.65)";
|
||||
ctx.lineWidth = 2;
|
||||
lines.forEach(([a, b]) => {
|
||||
ctx.beginPath();
|
||||
ctx.moveTo(stars[a].x, stars[a].y);
|
||||
ctx.lineTo(stars[b].x, stars[b].y);
|
||||
ctx.stroke();
|
||||
});
|
||||
stars.forEach((star, index) => {
|
||||
ctx.beginPath();
|
||||
ctx.fillStyle = index === selected ? "#f6d889" : "#fff8e8";
|
||||
ctx.arc(star.x, star.y, index === selected ? 7 : 4, 0, Math.PI * 2);
|
||||
ctx.fill();
|
||||
});
|
||||
linesEl.textContent = String(lines.length);
|
||||
if (lines.length >= 3) nameEl.textContent = `Named: ${pick(["The Patient Spoon", "The South Window", "The Tired Comet", "The Fifth Errand"])}`;
|
||||
}
|
||||
|
||||
canvas.addEventListener("click", (event) => {
|
||||
const rect = canvas.getBoundingClientRect();
|
||||
const x = ((event.clientX - rect.left) / rect.width) * canvas.width;
|
||||
const y = ((event.clientY - rect.top) / rect.height) * canvas.height;
|
||||
const hit = stars.findIndex((star) => Math.hypot(star.x - x, star.y - y) < 22);
|
||||
if (hit < 0) return;
|
||||
if (selected === null) selected = hit;
|
||||
else if (selected !== hit) {
|
||||
lines.push([selected, hit]);
|
||||
selected = hit;
|
||||
}
|
||||
draw();
|
||||
});
|
||||
$("[data-star-reset]", root).addEventListener("click", () => {
|
||||
lines.length = 0;
|
||||
selected = null;
|
||||
nameEl.textContent = "";
|
||||
draw();
|
||||
});
|
||||
draw();
|
||||
}
|
||||
|
||||
function poem(root) {
|
||||
const output = $("[data-poem-output]", root);
|
||||
const a = ["In the margin", "By the kettle", "Under the desk lamp", "Between two errands", "After the house quiets"];
|
||||
const b = ["a careful thought", "an old joke", "a stubborn question", "a useful mistake", "a bright scrap"];
|
||||
const c = ["learns to wait.", "asks for a second reading.", "finds its proper shelf.", "becomes tomorrow's note.", "keeps the page warm."];
|
||||
let count = 0;
|
||||
function make() {
|
||||
count += 1;
|
||||
output.innerHTML = `${pick(a)}<br>${pick(b)}<br>${pick(c)}`;
|
||||
output.dataset.stamp = count % 5 === 0 ? "approved by the margin" : "";
|
||||
}
|
||||
$("[data-poem-generate]", root).addEventListener("click", make);
|
||||
make();
|
||||
}
|
||||
|
||||
function bookshelf(root) {
|
||||
const titles = ["Algebra at Breakfast", "Cabinet of Weather", "Domestic Orbits", "Evening Margins", "Household Engines", "Zettels and Tea"];
|
||||
const shelf = $("[data-bookshelf]", root);
|
||||
const status = $("[data-bookshelf-status]", root);
|
||||
let sortedOnce = false;
|
||||
setupSortable(shelf, render, check);
|
||||
$("[data-bookshelf-shuffle]", root).addEventListener("click", () => render(shuffle(titles)));
|
||||
render(shuffle(titles));
|
||||
|
||||
function render(items) {
|
||||
shelf.innerHTML = "";
|
||||
items.forEach((title) => {
|
||||
const book = document.createElement("div");
|
||||
book.className = "book-spine";
|
||||
book.draggable = true;
|
||||
book.dataset.value = title;
|
||||
book.textContent = title;
|
||||
shelf.appendChild(book);
|
||||
});
|
||||
check();
|
||||
}
|
||||
function check() {
|
||||
const current = $$(".book-spine", shelf).map((book) => book.dataset.value);
|
||||
const sorted = current.join("|") === titles.join("|");
|
||||
status.textContent = sorted ? "Shelf sorted. A secret pamphlet slides out." : "Unsorted";
|
||||
if (sorted && !sortedOnce) {
|
||||
sortedOnce = true;
|
||||
const pamphlet = document.createElement("div");
|
||||
pamphlet.className = "booklet";
|
||||
pamphlet.textContent = "Pamphlet: On the Correct Order of Small Things";
|
||||
shelf.appendChild(pamphlet);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function recipe(root) {
|
||||
const wheel = $("[data-recipe-spin]", root);
|
||||
const result = $("[data-recipe-result]", root);
|
||||
const groups = [
|
||||
["Rice", "Flatbread", "Roast potatoes", "Noodles"],
|
||||
["Lemon chicken", "Spiced lentils", "Tomato eggs", "Pepper stew"],
|
||||
["Cucumber salad", "Mint yoghurt", "Pickled onions", "Charred greens"],
|
||||
["Serve with stories", "Eat outside", "Use the blue plates", "Make extra tea"]
|
||||
];
|
||||
let spin = 0;
|
||||
let feast = 0;
|
||||
wheel.addEventListener("click", () => {
|
||||
spin += 540 + Math.floor(Math.random() * 540);
|
||||
feast += 1;
|
||||
wheel.style.transform = `rotate(${spin}deg)`;
|
||||
result.innerHTML = groups.map((group) => `<li>${pick(group)}</li>`).join("") + (feast % 4 === 0 ? "<li>Bonus: someone gets the last crispy bit.</li>" : "");
|
||||
});
|
||||
wheel.click();
|
||||
}
|
||||
|
||||
function timeline(root) {
|
||||
const items = [
|
||||
{ year: "2022", text: "The personal web habit begins." },
|
||||
{ year: "2025", text: "Org publishing becomes the main site engine." },
|
||||
{ year: "2025", text: "Weekly reviews and career notes grow into a library." },
|
||||
{ year: "2026", text: "Dashboards, services, and authoring tools join the site." },
|
||||
{ year: "2026", text: "The play wing opens." }
|
||||
];
|
||||
const list = $("[data-timeline-list]", root);
|
||||
const status = $("[data-timeline-status]", root);
|
||||
const paradox = document.createElement("button");
|
||||
paradox.type = "button";
|
||||
paradox.textContent = "Paradox";
|
||||
$("[data-timeline-shuffle]", root).insertAdjacentElement("afterend", paradox);
|
||||
setupSortable(list, render, check);
|
||||
$("[data-timeline-shuffle]", root).addEventListener("click", () => render(shuffle(items)));
|
||||
paradox.addEventListener("click", () => render([...items].reverse()));
|
||||
render(shuffle(items));
|
||||
|
||||
function render(source) {
|
||||
list.innerHTML = "";
|
||||
source.forEach((item, index) => {
|
||||
const card = document.createElement("div");
|
||||
card.className = "timeline-card";
|
||||
card.draggable = true;
|
||||
card.dataset.value = String(items.indexOf(item));
|
||||
card.innerHTML = `<span>${item.year}</span><strong>${item.text}</strong>`;
|
||||
list.appendChild(card);
|
||||
});
|
||||
check();
|
||||
}
|
||||
function check() {
|
||||
const current = $$(".timeline-card", list).map((card) => Number(card.dataset.value));
|
||||
status.textContent = current.every((value, index) => value === index) ? "Timeline restored" : "Arrange the cards";
|
||||
}
|
||||
}
|
||||
|
||||
function ink(root) {
|
||||
const canvas = $("[data-ink-canvas]", root);
|
||||
const ctx = canvas.getContext("2d");
|
||||
const drops = [];
|
||||
let moon = false;
|
||||
function addDrop(x, y, heavy) {
|
||||
drops.push({ x, y, r: heavy ? 18 : 8, life: heavy ? 1.8 : 1, hue: 28 + Math.random() * 35 });
|
||||
}
|
||||
function pointer(event, heavy) {
|
||||
const rect = canvas.getBoundingClientRect();
|
||||
addDrop(((event.clientX - rect.left) / rect.width) * canvas.width, ((event.clientY - rect.top) / rect.height) * canvas.height, heavy);
|
||||
}
|
||||
canvas.addEventListener("pointermove", (event) => pointer(event, false));
|
||||
canvas.addEventListener("click", (event) => pointer(event, true));
|
||||
canvas.addEventListener("dblclick", () => {
|
||||
moon = !moon;
|
||||
});
|
||||
function frame() {
|
||||
ctx.fillStyle = "rgba(24, 19, 15, 0.16)";
|
||||
ctx.fillRect(0, 0, canvas.width, canvas.height);
|
||||
if (moon) {
|
||||
ctx.beginPath();
|
||||
ctx.fillStyle = "rgba(246, 216, 137, 0.72)";
|
||||
ctx.arc(760, 88, 34, 0, Math.PI * 2);
|
||||
ctx.fill();
|
||||
}
|
||||
drops.forEach((drop) => {
|
||||
drop.r += 0.7;
|
||||
drop.life -= 0.012;
|
||||
ctx.beginPath();
|
||||
ctx.strokeStyle = `hsla(${drop.hue}, 65%, 68%, ${Math.max(drop.life, 0)})`;
|
||||
ctx.lineWidth = 2;
|
||||
ctx.arc(drop.x, drop.y, drop.r, 0, Math.PI * 2);
|
||||
ctx.stroke();
|
||||
});
|
||||
for (let i = drops.length - 1; i >= 0; i -= 1) if (drops[i].life <= 0) drops.splice(i, 1);
|
||||
requestAnimationFrame(frame);
|
||||
}
|
||||
frame();
|
||||
}
|
||||
|
||||
function terminal(root) {
|
||||
const log = $("[data-terminal-log]", root);
|
||||
const form = $("[data-terminal-form]", root);
|
||||
const input = $("[data-terminal-input]", root);
|
||||
let kindness = 0;
|
||||
const responses = {
|
||||
help: "Commands: help, look, map, open drawer, read note, brew tea, hum, knock, save, inventory, clear",
|
||||
look: "A narrow archive room. A lamp hums. A drawer is labelled MAYBE IMPORTANT.",
|
||||
map: "You are between the reading desk, the family shelf, and the door back to Play.",
|
||||
"open drawer": "Inside: a brass key, a receipt, and a note folded twice.",
|
||||
"read note": "The note says: keep the site useful, but leave a few doors ajar.",
|
||||
"brew tea": "The room smells briefly of cardamom. Nothing else changes, which is enough.",
|
||||
hum: "You hum four careful notes. Something behind the wall hums five back.",
|
||||
knock: "Knock. Knock. ... A polite pause. Knock.",
|
||||
save: "You save your place in the archive. The archive saves its place in you.",
|
||||
inventory: "You are carrying: a brass key, a warm cup, and one unreasonable hope."
|
||||
};
|
||||
function write(text) {
|
||||
log.textContent += `${text}\n`;
|
||||
log.scrollTop = log.scrollHeight;
|
||||
}
|
||||
form.addEventListener("submit", (event) => {
|
||||
event.preventDefault();
|
||||
const cmd = input.value.trim().toLowerCase();
|
||||
if (!cmd) return;
|
||||
input.value = "";
|
||||
if (cmd === "clear") {
|
||||
log.textContent = "";
|
||||
return;
|
||||
}
|
||||
write(`> ${cmd}`);
|
||||
if (cmd === "pet book") {
|
||||
kindness += 1;
|
||||
write(kindness > 2 ? "The book follows you for exactly three pages." : "The book accepts this with suspicious dignity.");
|
||||
} else {
|
||||
write(responses[cmd] || "The archive declines to understand that command.");
|
||||
}
|
||||
});
|
||||
write("Archive terminal ready. Type help. The cursor is listening.");
|
||||
input.focus();
|
||||
}
|
||||
|
||||
function study(root) {
|
||||
const time = $("[data-study-time]", root);
|
||||
const scene = $("[data-study-scene]", root);
|
||||
let total = 300;
|
||||
let left = total;
|
||||
let timer = null;
|
||||
const note = document.createElement("div");
|
||||
note.className = "play-live-note";
|
||||
note.textContent = "The lamp is cold.";
|
||||
time.insertAdjacentElement("afterend", note);
|
||||
function draw() {
|
||||
const done = 1 - left / total;
|
||||
scene.style.setProperty("--lamp", String(0.18 + done * 0.72));
|
||||
scene.style.setProperty("--glow", `${done * 70}px`);
|
||||
const m = String(Math.floor(left / 60)).padStart(2, "0");
|
||||
const s = String(left % 60).padStart(2, "0");
|
||||
time.textContent = `${m}:${s}`;
|
||||
if (left === 0) note.textContent = "Focus complete. The desk looks proud.";
|
||||
else if (done > 0.66) note.textContent = "The page has warmed through.";
|
||||
else if (done > 0.33) note.textContent = "The lamp has settled into its work.";
|
||||
}
|
||||
function start() {
|
||||
if (timer) return;
|
||||
timer = setInterval(() => {
|
||||
left = Math.max(0, left - 1);
|
||||
draw();
|
||||
if (left === 0) pause();
|
||||
}, 1000);
|
||||
}
|
||||
function pause() {
|
||||
clearInterval(timer);
|
||||
timer = null;
|
||||
}
|
||||
$("[data-study-start]", root).addEventListener("click", start);
|
||||
$("[data-study-pause]", root).addEventListener("click", pause);
|
||||
$("[data-study-reset]", root).addEventListener("click", () => {
|
||||
pause();
|
||||
left = total;
|
||||
draw();
|
||||
});
|
||||
draw();
|
||||
}
|
||||
|
||||
function sigil(root) {
|
||||
const canvas = $("[data-sigil-canvas]", root);
|
||||
const ctx = canvas.getContext("2d");
|
||||
const initials = $("[data-sigil-initials]", root);
|
||||
const motto = $("[data-sigil-motto]", root);
|
||||
let wax = "#9c6b2f";
|
||||
const waxButton = document.createElement("button");
|
||||
waxButton.type = "button";
|
||||
waxButton.textContent = "New wax";
|
||||
$("[data-sigil-form]", root).appendChild(waxButton);
|
||||
function draw() {
|
||||
const text = (initials.value || "ZXH").toUpperCase();
|
||||
const phrase = motto.value || "Learn, make, remember";
|
||||
ctx.clearRect(0, 0, canvas.width, canvas.height);
|
||||
ctx.fillStyle = "#fbf7ec";
|
||||
ctx.fillRect(0, 0, canvas.width, canvas.height);
|
||||
ctx.translate(260, 260);
|
||||
ctx.strokeStyle = wax;
|
||||
ctx.lineWidth = 10;
|
||||
ctx.beginPath();
|
||||
ctx.arc(0, 0, 190, 0, Math.PI * 2);
|
||||
ctx.stroke();
|
||||
ctx.lineWidth = 2;
|
||||
for (let i = 0; i < 12; i += 1) {
|
||||
ctx.rotate(Math.PI / 6);
|
||||
ctx.beginPath();
|
||||
ctx.moveTo(0, -150);
|
||||
ctx.lineTo(0, -185);
|
||||
ctx.stroke();
|
||||
}
|
||||
ctx.rotate(-Math.PI * 2);
|
||||
ctx.fillStyle = "#2a2118";
|
||||
ctx.textAlign = "center";
|
||||
ctx.textBaseline = "middle";
|
||||
ctx.font = "900 94px Georgia, serif";
|
||||
ctx.fillText(text.slice(0, 4), 0, -10);
|
||||
ctx.font = "700 22px Georgia, serif";
|
||||
ctx.fillText(phrase.slice(0, 34), 0, 88);
|
||||
ctx.setTransform(1, 0, 0, 1, 0, 0);
|
||||
}
|
||||
waxButton.addEventListener("click", () => {
|
||||
wax = pick(["#9c6b2f", "#8a3f3f", "#486b57", "#3e5f8a", "#5f4b8b"]);
|
||||
draw();
|
||||
});
|
||||
$("[data-sigil-form]", root).addEventListener("submit", (event) => {
|
||||
event.preventDefault();
|
||||
draw();
|
||||
});
|
||||
initials.addEventListener("input", draw);
|
||||
motto.addEventListener("input", draw);
|
||||
draw();
|
||||
}
|
||||
|
||||
function rpg(root) {
|
||||
if (window.AshBelowLakeRpg) return window.AshBelowLakeRpg(root);
|
||||
const canvas = $("[data-rpg-canvas]", root);
|
||||
const ctx = canvas.getContext("2d");
|
||||
const els = {
|
||||
speaker: $("[data-rpg-speaker]", root),
|
||||
line: $("[data-rpg-line]", root),
|
||||
room: $("[data-rpg-room]", root),
|
||||
route: $("[data-rpg-route]", root),
|
||||
hearts: $("[data-rpg-hearts]", root),
|
||||
quests: $("[data-rpg-quests]", root),
|
||||
inventory: $("[data-rpg-inventory]", root),
|
||||
status: $("[data-rpg-status]", root)
|
||||
};
|
||||
const tile = 32;
|
||||
const saveSlot = "hollow-archive";
|
||||
const fallbackKey = "play:rpg:hollow-archive";
|
||||
const items = {
|
||||
lamp: { label: "Desk Lamp", room: "entrance", x: 10, y: 8, color: "#f2c94c" },
|
||||
page: { label: "Loose Page", room: "stacks", x: 18, y: 5, color: "#f7efe0" },
|
||||
key: { label: "Basement Key", room: "garden", x: 4, y: 11, color: "#d59b45" }
|
||||
};
|
||||
const npcs = {
|
||||
archivist: { name: "Archivist", room: "entrance", x: 6, y: 6, color: "#b98bff" },
|
||||
shade: { name: "Shy Shade", room: "stacks", x: 17, y: 9, color: "#6ed0d4" },
|
||||
gate: { name: "Iron Door", room: "garden", x: 19, y: 10, color: "#8a8f98" }
|
||||
};
|
||||
const rooms = {
|
||||
entrance: {
|
||||
name: "Entrance",
|
||||
floor: "#353029",
|
||||
exits: [{ x: 22, y: 7, to: "stacks", px: 1, py: 7 }],
|
||||
walls: rects([[0, 0, 24, 1], [0, 15, 24, 1], [0, 0, 1, 16], [23, 0, 1, 6], [23, 9, 1, 7], [8, 3, 1, 8], [14, 7, 5, 1]])
|
||||
},
|
||||
stacks: {
|
||||
name: "Stacks",
|
||||
floor: "#242d35",
|
||||
exits: [{ x: 0, y: 7, to: "entrance", px: 22, py: 7 }, { x: 23, y: 12, to: "garden", px: 1, py: 12 }],
|
||||
walls: rects([[0, 0, 24, 1], [0, 15, 24, 1], [0, 0, 1, 6], [0, 9, 1, 7], [23, 0, 1, 11], [23, 14, 1, 2], [4, 3, 2, 10], [10, 2, 2, 11], [16, 3, 2, 5]])
|
||||
},
|
||||
garden: {
|
||||
name: "Moon Garden",
|
||||
floor: "#21362e",
|
||||
exits: [{ x: 0, y: 12, to: "stacks", px: 22, py: 12 }],
|
||||
walls: rects([[0, 0, 24, 1], [0, 15, 24, 1], [0, 0, 1, 11], [0, 14, 1, 2], [23, 0, 1, 16], [7, 4, 10, 1], [7, 10, 1, 4], [13, 10, 1, 4]])
|
||||
}
|
||||
};
|
||||
let state = freshState();
|
||||
let running = false;
|
||||
|
||||
function freshState() {
|
||||
return {
|
||||
room: "entrance",
|
||||
player: { x: 3, y: 7, facing: "down" },
|
||||
inventory: [],
|
||||
flags: {},
|
||||
route: "Undecided",
|
||||
hearts: 3,
|
||||
ending: null,
|
||||
message: { speaker: "Archivist", line: "The archive waits. Find the lamp, help the shade, then decide what to do with the locked door." }
|
||||
};
|
||||
}
|
||||
|
||||
function rects(sources) {
|
||||
const set = new Set();
|
||||
sources.forEach(([x, y, w, h]) => {
|
||||
for (let yy = y; yy < y + h; yy += 1) for (let xx = x; xx < x + w; xx += 1) set.add(`${xx},${yy}`);
|
||||
});
|
||||
return set;
|
||||
}
|
||||
|
||||
function draw() {
|
||||
const room = rooms[state.room];
|
||||
ctx.fillStyle = "#14110e";
|
||||
ctx.fillRect(0, 0, canvas.width, canvas.height);
|
||||
for (let y = 0; y < 16; y += 1) {
|
||||
for (let x = 0; x < 24; x += 1) {
|
||||
ctx.fillStyle = room.walls.has(`${x},${y}`) ? "#181716" : room.floor;
|
||||
ctx.fillRect(x * tile, y * tile, tile, tile);
|
||||
ctx.strokeStyle = "rgba(255,255,255,0.035)";
|
||||
ctx.strokeRect(x * tile, y * tile, tile, tile);
|
||||
}
|
||||
}
|
||||
room.exits.forEach((exit) => drawGlyph(exit.x, exit.y, "#c48a41", "door"));
|
||||
Object.entries(items).forEach(([id, item]) => {
|
||||
if (item.room === state.room && !state.inventory.includes(id)) drawGlyph(item.x, item.y, item.color, "item");
|
||||
});
|
||||
Object.values(npcs).forEach((npc) => {
|
||||
if (npc.room === state.room) drawGlyph(npc.x, npc.y, npc.color, npc.name === "Iron Door" ? "doorNpc" : "npc");
|
||||
});
|
||||
drawPlayer();
|
||||
renderHud();
|
||||
requestAnimationFrame(draw);
|
||||
}
|
||||
|
||||
function drawGlyph(x, y, color, kind) {
|
||||
const px = x * tile;
|
||||
const py = y * tile;
|
||||
ctx.fillStyle = color;
|
||||
if (kind === "item") {
|
||||
ctx.fillRect(px + 10, py + 10, 12, 12);
|
||||
ctx.fillStyle = "rgba(255,255,255,0.45)";
|
||||
ctx.fillRect(px + 13, py + 7, 6, 6);
|
||||
} else if (kind === "door" || kind === "doorNpc") {
|
||||
ctx.fillRect(px + 7, py + 4, 18, 25);
|
||||
ctx.fillStyle = "#211812";
|
||||
ctx.fillRect(px + 20, py + 16, 3, 3);
|
||||
} else {
|
||||
ctx.beginPath();
|
||||
ctx.arc(px + 16, py + 12, 9, 0, Math.PI * 2);
|
||||
ctx.fill();
|
||||
ctx.fillRect(px + 8, py + 20, 16, 8);
|
||||
}
|
||||
}
|
||||
|
||||
function drawPlayer() {
|
||||
const px = state.player.x * tile;
|
||||
const py = state.player.y * tile;
|
||||
ctx.fillStyle = "#f35f5f";
|
||||
ctx.beginPath();
|
||||
ctx.moveTo(px + 16, py + 7);
|
||||
ctx.bezierCurveTo(px + 2, py + 2, px + 1, py + 22, px + 16, py + 28);
|
||||
ctx.bezierCurveTo(px + 31, py + 22, px + 30, py + 2, px + 16, py + 7);
|
||||
ctx.fill();
|
||||
ctx.fillStyle = "#fff8e8";
|
||||
ctx.fillRect(px + 11, py + 13, 4, 4);
|
||||
ctx.fillRect(px + 18, py + 13, 4, 4);
|
||||
}
|
||||
|
||||
function renderHud() {
|
||||
els.speaker.textContent = state.message.speaker;
|
||||
els.line.textContent = state.ending ? endingLine() : state.message.line;
|
||||
els.room.textContent = rooms[state.room].name;
|
||||
els.route.textContent = state.route;
|
||||
els.hearts.textContent = String(state.hearts);
|
||||
els.inventory.innerHTML = state.inventory.length
|
||||
? state.inventory.map((id) => `<li>${items[id].label}</li>`).join("")
|
||||
: "<li>Empty</li>";
|
||||
const questRows = [
|
||||
["Find a light", state.inventory.includes("lamp")],
|
||||
["Return the loose page to the shade", state.flags.shadeHelped],
|
||||
["Open, force, or leave the iron door", Boolean(state.ending)]
|
||||
];
|
||||
els.quests.innerHTML = questRows.map(([text, done]) => `<li class="${done ? "is-done" : ""}">${done ? "Done: " : ""}${text}</li>`).join("");
|
||||
}
|
||||
|
||||
function move(dx, dy, facing) {
|
||||
if (!running || state.ending) return;
|
||||
state.player.facing = facing;
|
||||
const nx = state.player.x + dx;
|
||||
const ny = state.player.y + dy;
|
||||
const room = rooms[state.room];
|
||||
const exit = room.exits.find((candidate) => candidate.x === nx && candidate.y === ny);
|
||||
if (exit) {
|
||||
state.room = exit.to;
|
||||
state.player.x = exit.px;
|
||||
state.player.y = exit.py;
|
||||
say("Narrator", `You enter ${rooms[state.room].name}.`);
|
||||
autosave();
|
||||
return;
|
||||
}
|
||||
if (nx < 0 || ny < 0 || nx > 23 || ny > 15 || room.walls.has(`${nx},${ny}`) || npcAt(nx, ny)) return;
|
||||
state.player.x = nx;
|
||||
state.player.y = ny;
|
||||
const item = itemAt(nx, ny);
|
||||
if (item) take(item);
|
||||
}
|
||||
|
||||
function act() {
|
||||
if (!running) return start();
|
||||
if (state.ending) return;
|
||||
const front = inFront();
|
||||
const npc = npcAt(front.x, front.y);
|
||||
if (npc) talk(npc);
|
||||
else {
|
||||
const here = itemAt(state.player.x, state.player.y);
|
||||
if (here) take(here);
|
||||
else say("Narrator", "Dust moves in the light. Nothing asks to be changed here.");
|
||||
}
|
||||
autosave();
|
||||
}
|
||||
|
||||
function inFront() {
|
||||
const delta = { up: [0, -1], down: [0, 1], left: [-1, 0], right: [1, 0] }[state.player.facing] || [0, 1];
|
||||
return { x: state.player.x + delta[0], y: state.player.y + delta[1] };
|
||||
}
|
||||
|
||||
function itemAt(x, y) {
|
||||
return Object.keys(items).find((id) => {
|
||||
const item = items[id];
|
||||
return item.room === state.room && item.x === x && item.y === y && !state.inventory.includes(id);
|
||||
});
|
||||
}
|
||||
|
||||
function npcAt(x, y) {
|
||||
return Object.keys(npcs).find((id) => {
|
||||
const npc = npcs[id];
|
||||
return npc.room === state.room && npc.x === x && npc.y === y;
|
||||
});
|
||||
}
|
||||
|
||||
function take(id) {
|
||||
state.inventory.push(id);
|
||||
if (id === "lamp") state.route = "Gentle";
|
||||
if (id === "key" && !state.flags.shadeHelped) state.route = "Power";
|
||||
say("Found", `${items[id].label} joined your inventory.`);
|
||||
}
|
||||
|
||||
function talk(id) {
|
||||
if (id === "archivist") {
|
||||
if (!state.inventory.includes("lamp")) say("Archivist", "Take the lamp from the lower desk. The stacks dislike being crossed in the dark.");
|
||||
else if (!state.flags.shadeHelped) say("Archivist", "A loose page has gone missing. The quiet reader in the stacks knows where it belongs.");
|
||||
else say("Archivist", "You have been kind to a forgotten page. The garden door will remember that.");
|
||||
}
|
||||
if (id === "shade") {
|
||||
if (!state.inventory.includes("page")) say("Shy Shade", "I lost the page with my name on it. It fell somewhere nearby.");
|
||||
else {
|
||||
state.flags.shadeHelped = true;
|
||||
state.inventory = state.inventory.filter((item) => item !== "page");
|
||||
state.route = "Mercy";
|
||||
say("Shy Shade", "You returned my page instead of keeping it. Take the honest route through the garden.");
|
||||
}
|
||||
}
|
||||
if (id === "gate") {
|
||||
if (state.flags.shadeHelped) end("mercy");
|
||||
else if (state.inventory.includes("key")) end("power");
|
||||
else end("quiet");
|
||||
}
|
||||
}
|
||||
|
||||
function end(kind) {
|
||||
state.ending = kind;
|
||||
state.route = kind === "mercy" ? "Mercy" : kind === "power" ? "Power" : "Quiet";
|
||||
say("Ending", endingLine());
|
||||
save();
|
||||
}
|
||||
|
||||
function endingLine() {
|
||||
if (state.ending === "mercy") return "Mercy ending: the iron door opens without a sound, and every returned page remembers your name.";
|
||||
if (state.ending === "power") return "Power ending: the key turns, but the archive grows colder around the missing page.";
|
||||
if (state.ending === "quiet") return "Quiet ending: you leave the locked door alone. Some mysteries stay intact.";
|
||||
return state.message.line;
|
||||
}
|
||||
|
||||
function say(speaker, line) {
|
||||
state.message = { speaker, line };
|
||||
}
|
||||
|
||||
function start() {
|
||||
running = true;
|
||||
say("Archivist", "Walk the archive. Speak gently, or take what you need. The route will notice.");
|
||||
els.status.textContent = "Started. Progress autosaves after room changes and actions.";
|
||||
}
|
||||
|
||||
async function save() {
|
||||
localStorage.setItem(fallbackKey, JSON.stringify(state));
|
||||
try {
|
||||
const response = await fetch(`/api/play/rpg/save/${saveSlot}`, {
|
||||
method: "PUT",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ payload: state })
|
||||
});
|
||||
if (!response.ok) throw new Error(`Save failed: ${response.status}`);
|
||||
els.status.textContent = "Saved to backend.";
|
||||
} catch (_error) {
|
||||
els.status.textContent = "Saved locally. Backend save API was not reachable.";
|
||||
}
|
||||
}
|
||||
|
||||
async function load() {
|
||||
try {
|
||||
const response = await fetch(`/api/play/rpg/save/${saveSlot}`);
|
||||
if (response.ok) {
|
||||
const data = await response.json();
|
||||
state = normalizeState(data.payload);
|
||||
running = true;
|
||||
els.status.textContent = "Loaded from backend.";
|
||||
return;
|
||||
}
|
||||
} catch (_error) {
|
||||
/* Fall through to local save. */
|
||||
}
|
||||
const local = localStorage.getItem(fallbackKey);
|
||||
if (local) {
|
||||
state = normalizeState(JSON.parse(local));
|
||||
running = true;
|
||||
els.status.textContent = "Loaded local save.";
|
||||
} else {
|
||||
els.status.textContent = "No save found.";
|
||||
}
|
||||
}
|
||||
|
||||
function normalizeState(candidate) {
|
||||
return Object.assign(freshState(), candidate || {}, {
|
||||
player: Object.assign(freshState().player, (candidate && candidate.player) || {}),
|
||||
inventory: Array.isArray(candidate && candidate.inventory) ? candidate.inventory.filter((id) => items[id]) : [],
|
||||
flags: Object.assign({}, (candidate && candidate.flags) || {}),
|
||||
message: Object.assign(freshState().message, (candidate && candidate.message) || {})
|
||||
});
|
||||
}
|
||||
|
||||
function autosave() {
|
||||
save();
|
||||
}
|
||||
|
||||
$("[data-rpg-start]", root).addEventListener("click", start);
|
||||
$("[data-rpg-save]", root).addEventListener("click", save);
|
||||
$("[data-rpg-load]", root).addEventListener("click", load);
|
||||
$("[data-rpg-reset]", root).addEventListener("click", async () => {
|
||||
state = freshState();
|
||||
running = false;
|
||||
localStorage.removeItem(fallbackKey);
|
||||
try {
|
||||
await fetch(`/api/play/rpg/save/${saveSlot}`, { method: "DELETE" });
|
||||
els.status.textContent = "Reset and cleared backend save.";
|
||||
} catch (_error) {
|
||||
els.status.textContent = "Reset locally. Backend save API was not reachable.";
|
||||
}
|
||||
});
|
||||
$("[data-rpg-act]", root).addEventListener("click", act);
|
||||
$$("[data-rpg-move]", root).forEach((button) => {
|
||||
const moves = { up: [0, -1, "up"], down: [0, 1, "down"], left: [-1, 0, "left"], right: [1, 0, "right"] };
|
||||
button.addEventListener("click", () => move(...moves[button.dataset.rpgMove]));
|
||||
});
|
||||
window.addEventListener("keydown", (event) => {
|
||||
if (!root.isConnected) return;
|
||||
const tag = event.target.tagName;
|
||||
if (tag === "INPUT" || tag === "TEXTAREA") return;
|
||||
const keys = {
|
||||
ArrowUp: [0, -1, "up"], w: [0, -1, "up"],
|
||||
ArrowDown: [0, 1, "down"], s: [0, 1, "down"],
|
||||
ArrowLeft: [-1, 0, "left"], a: [-1, 0, "left"],
|
||||
ArrowRight: [1, 0, "right"], d: [1, 0, "right"]
|
||||
};
|
||||
if (keys[event.key]) {
|
||||
event.preventDefault();
|
||||
move(...keys[event.key]);
|
||||
}
|
||||
if (event.key === " " || event.key === "Enter") {
|
||||
event.preventDefault();
|
||||
act();
|
||||
}
|
||||
});
|
||||
draw();
|
||||
load();
|
||||
}
|
||||
|
||||
function setupSortable(container, _render, after) {
|
||||
let dragged = null;
|
||||
container.addEventListener("dragstart", (event) => {
|
||||
dragged = event.target.closest("[draggable='true']");
|
||||
if (dragged) event.dataTransfer.effectAllowed = "move";
|
||||
});
|
||||
container.addEventListener("dragover", (event) => {
|
||||
event.preventDefault();
|
||||
const target = event.target.closest("[draggable='true']");
|
||||
if (!dragged || !target || target === dragged) return;
|
||||
const rect = target.getBoundingClientRect();
|
||||
const before = event.clientY < rect.top + rect.height / 2 || event.clientX < rect.left + rect.width / 2;
|
||||
container.insertBefore(dragged, before ? target : target.nextSibling);
|
||||
after();
|
||||
});
|
||||
container.addEventListener("dragend", () => {
|
||||
dragged = null;
|
||||
after();
|
||||
});
|
||||
}
|
||||
|
||||
function pick(items) {
|
||||
return items[Math.floor(Math.random() * items.length)];
|
||||
}
|
||||
})();
|
||||
"use strict";
|
||||
var script = document.createElement("script");
|
||||
script.src = "/assets/scripts/pages/play.js";
|
||||
script.defer = true;
|
||||
document.head.appendChild(script);
|
||||
}());
|
||||
|
||||
@@ -1,341 +1,17 @@
|
||||
|
||||
|
||||
/* Event listener function for the COPY BUTTON */
|
||||
document.addEventListener("DOMContentLoaded", function () {
|
||||
document.querySelectorAll("pre.src").forEach(function (codeBlock) {
|
||||
const button = document.createElement("button");
|
||||
button.innerText = "Copy";
|
||||
button.className = "copy-btn";
|
||||
|
||||
// Append button inside <pre>
|
||||
codeBlock.appendChild(button);
|
||||
|
||||
button.addEventListener("click", function () {
|
||||
const text = codeBlock.innerText.replace(button.innerText, ""); // exclude button text
|
||||
navigator.clipboard.writeText(text.trim()).then(() => {
|
||||
button.innerText = "Copied!";
|
||||
setTimeout(() => (button.innerText = "Copy"), 1500);
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
/* Event listener for footnotes and sidenotes*/
|
||||
document.addEventListener("DOMContentLoaded", () => {
|
||||
document.querySelectorAll('a.footref[href^="#fn"]').forEach(ref => {
|
||||
const sup = ref.closest("sup") || ref;
|
||||
// idempotent: don't insert twice
|
||||
if (sup.nextElementSibling && sup.nextElementSibling.classList?.contains("footnote-sidenote")) return;
|
||||
|
||||
const targetId = ref.getAttribute("href").replace(/^#/, ""); // works for fn.2 or fn2
|
||||
|
||||
const anchor = document.getElementById(targetId);
|
||||
if (!anchor) return;
|
||||
|
||||
const footdef = anchor.closest(".footdef") || anchor.parentElement;
|
||||
if (!footdef) return;
|
||||
|
||||
// 1) Prefer leaf paragraphs to avoid div+p duplication
|
||||
let paras = footdef.querySelectorAll("p.footpara");
|
||||
if (!paras.length) {
|
||||
// fallback: any .footpara elements that don't contain another .footpara
|
||||
paras = footdef.querySelectorAll(".footpara:not(:has(.footpara))");
|
||||
}
|
||||
|
||||
// 2) Build HTML, de-duplicating by text content
|
||||
let parts = [];
|
||||
if (paras.length) {
|
||||
const seen = new Set();
|
||||
parts = Array.from(paras).map(p => {
|
||||
const txt = p.textContent.trim().replace(/\s+/g, " ");
|
||||
if (seen.has(txt)) return "";
|
||||
seen.add(txt);
|
||||
return p.innerHTML.trim();
|
||||
}).filter(Boolean);
|
||||
}
|
||||
|
||||
// 3) Fallback: clean full block if no paras found
|
||||
if (!parts.length) {
|
||||
const clone = footdef.cloneNode(true);
|
||||
clone.querySelectorAll("sup.footnum, a[role='doc-backlink']").forEach(n => n.remove());
|
||||
parts = [clone.innerHTML.trim()];
|
||||
}
|
||||
|
||||
// 4) Insert the sidenote
|
||||
const sn = document.createElement("span");
|
||||
sn.className = "sidenote footnote-sidenote";
|
||||
sn.setAttribute("data-fn", (ref.textContent || "").trim());
|
||||
sn.innerHTML = parts.join(" ");
|
||||
|
||||
sup.insertAdjacentElement("afterend", sn);
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
/* Function for setting the theme */
|
||||
(function(){
|
||||
const root = document.documentElement;
|
||||
const storageKey = "theme";
|
||||
const themes = ["light", "dark", "dark-academia"];
|
||||
const labels = {
|
||||
"light": "Light",
|
||||
"dark": "Dark",
|
||||
"dark-academia": "Academia"
|
||||
};
|
||||
const saved = localStorage.getItem(storageKey);
|
||||
if (themes.includes(saved)) {
|
||||
root.setAttribute("data-theme", saved);
|
||||
}
|
||||
const btn = document.getElementById("theme-toggle");
|
||||
if (!btn) return;
|
||||
const updateButton = () => {
|
||||
const current = root.getAttribute("data-theme");
|
||||
const label = labels[current] || "Auto";
|
||||
btn.textContent = `Theme: ${label}`;
|
||||
btn.setAttribute("aria-label", `Current theme: ${label}. Switch theme.`);
|
||||
};
|
||||
updateButton();
|
||||
btn.addEventListener("click", () => {
|
||||
const current = root.getAttribute("data-theme");
|
||||
const index = themes.indexOf(current);
|
||||
const target = themes[index === -1 ? 1 : (index + 1) % themes.length];
|
||||
root.setAttribute("data-theme", target);
|
||||
localStorage.setItem(storageKey, target);
|
||||
updateButton();
|
||||
});
|
||||
})();
|
||||
|
||||
|
||||
// Simple, timezone-safe if you pass UTC (…Z) in the datetime
|
||||
document.addEventListener('DOMContentLoaded', () => {
|
||||
const els = document.querySelectorAll('time.countdown');
|
||||
if (!els.length) return;
|
||||
|
||||
const plural = (n, w) => `${n} ${w}${n === 1 ? '' : 's'}`;
|
||||
|
||||
const render = (el) => {
|
||||
const raw = el.getAttribute('datetime');
|
||||
const label = el.dataset.label || '';
|
||||
const target = new Date(raw); // Prefer ISO like 2025-12-31T00:00:00Z
|
||||
if (isNaN(target)) { el.textContent = '—'; return; }
|
||||
|
||||
const now = new Date();
|
||||
let diff = target - now;
|
||||
|
||||
if (diff <= 0) {
|
||||
el.textContent = `${label ? label + ' ' : ''}today`;
|
||||
el.classList.add('expired');
|
||||
return;
|
||||
}
|
||||
|
||||
const d = Math.floor(diff / 86400000); diff -= d * 86400000;
|
||||
const h = Math.floor(diff / 3600000); diff -= h * 3600000;
|
||||
const m = Math.floor(diff / 60000); diff -= m * 60000;
|
||||
const s = Math.floor(diff / 1000);
|
||||
|
||||
const pieces = [];
|
||||
if (d) pieces.push(plural(d, 'day'));
|
||||
pieces.push(`${h}h ${m}m ${s}s`);
|
||||
|
||||
el.textContent = `${label ? label + ' in : ' : ''}${pieces.join(' ')}`;
|
||||
};
|
||||
|
||||
const tick = () => els.forEach(render);
|
||||
tick();
|
||||
setInterval(tick, 1000); // update every second
|
||||
});
|
||||
|
||||
|
||||
|
||||
/* Event listener for scrolling and changing the active label on the TOC */
|
||||
document.addEventListener("DOMContentLoaded", () => {
|
||||
const toc = document.querySelector("#text-table-of-contents");
|
||||
if (!toc) { console.warn("No #text-table-of-contents found"); return; }
|
||||
|
||||
const links = toc.querySelectorAll('a[href^="#"]'); // '^=' is a starts with operator.
|
||||
// <a href="#introduction">Intro</a> matches
|
||||
if (!links.length) { console.warn("No ToC links found"); return; }
|
||||
|
||||
// Map: id -> link
|
||||
const linkById = new Map();
|
||||
links.forEach(a => {
|
||||
const id = decodeURIComponent(a.getAttribute("href").slice(1));
|
||||
const el = document.getElementById(id);
|
||||
if (el) linkById.set(id, a);
|
||||
});
|
||||
if (!linkById.size) { console.warn("No matching headings with IDs"); return; }
|
||||
|
||||
// Headings to observe (h2–h4 usually)
|
||||
const headings = [...document.querySelectorAll("h2[id], h3[id], h4[id]")]
|
||||
.filter(h => linkById.has(h.id));
|
||||
|
||||
// Helper to mark active
|
||||
const setActive = (id) => {
|
||||
links.forEach(a => {
|
||||
const active = a.getAttribute("href") === `#${id}`;
|
||||
a.classList.toggle("is-active", active);
|
||||
if (active) a.setAttribute("aria-current", "true");
|
||||
else a.removeAttribute("aria-current");
|
||||
});
|
||||
};
|
||||
|
||||
// Calculate sticky header offset in px
|
||||
const headerOffsetPx = 6.5 * parseFloat(getComputedStyle(document.documentElement).fontSize);
|
||||
|
||||
// Track visible headings (id -> distance from top)
|
||||
const visible = new Map();
|
||||
|
||||
const observer = new IntersectionObserver((entries) => {
|
||||
entries.forEach(entry => {
|
||||
const id = entry.target.id;
|
||||
if (entry.isIntersecting) {
|
||||
// How far from the top (after header offset)
|
||||
const dist = entry.target.getBoundingClientRect().top - headerOffsetPx;
|
||||
visible.set(id, dist);
|
||||
} else {
|
||||
visible.delete(id);
|
||||
}
|
||||
});
|
||||
|
||||
if (visible.size) {
|
||||
// Choose the heading closest to the top (>= -headerOffset)
|
||||
const topMost = [...visible.entries()]
|
||||
.sort((a,b) => Math.abs(a[1]) - Math.abs(b[1]))[0][0];
|
||||
setActive(topMost);
|
||||
// console.log("Active:", topMost, visible);
|
||||
}
|
||||
}, {
|
||||
root: null, // track relative to viewport
|
||||
rootMargin: `-${headerOffsetPx}px 0px -70% 0px`,
|
||||
threshold: [0, 0.01, 0.1] // fire as soon as it enters
|
||||
});
|
||||
|
||||
headings.forEach(h => observer.observe(h));
|
||||
|
||||
// Initial highlight (in case load mid‑page)
|
||||
let bestId = null, bestDist = Infinity;
|
||||
headings.forEach(h => {
|
||||
const top = h.getBoundingClientRect().top - headerOffsetPx;
|
||||
const dist = top < 0 ? Math.abs(top) : top + 1e6;
|
||||
if (dist < bestDist) { bestDist = dist; bestId = h.id; }
|
||||
});
|
||||
if (bestId) setActive(bestId);
|
||||
|
||||
// smooth-scroll ToC clicks
|
||||
toc.addEventListener("click", (e) => {
|
||||
const a = e.target.closest('a[href^="#"]');
|
||||
if (!a) return;
|
||||
const id = decodeURIComponent(a.hash.slice(1));
|
||||
const el = document.getElementById(id);
|
||||
if (!el) return;
|
||||
e.preventDefault();
|
||||
el.scrollIntoView({ behavior: "smooth", block: "start" });
|
||||
el.setAttribute("tabindex", "-1");
|
||||
el.focus({ preventScroll: true });
|
||||
history.pushState(null, "", `#${id}`);
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
// Make Mermaid diagrams use the active site theme and zoom controls.
|
||||
(function () {
|
||||
function cssVar(name, fallback) {
|
||||
const value = getComputedStyle(document.documentElement).getPropertyValue(name).trim();
|
||||
return value || fallback;
|
||||
}
|
||||
"use strict";
|
||||
|
||||
function mermaidConfig() {
|
||||
return {
|
||||
startOnLoad: false,
|
||||
theme: "base",
|
||||
themeVariables: {
|
||||
background: cssVar("--bg", "#faf9f6"),
|
||||
mainBkg: cssVar("--surface", "#ffffff"),
|
||||
primaryColor: cssVar("--surface", "#ffffff"),
|
||||
primaryTextColor: cssVar("--fg", "#000000"),
|
||||
primaryBorderColor: cssVar("--accent", "#2563eb"),
|
||||
secondaryColor: cssVar("--surface-soft", "#f3f1eb"),
|
||||
tertiaryColor: cssVar("--bg", "#faf9f6"),
|
||||
clusterBkg: cssVar("--surface-soft", "#f3f1eb"),
|
||||
clusterBorder: cssVar("--border", "#d7d7d7"),
|
||||
lineColor: cssVar("--border", "#d7d7d7"),
|
||||
textColor: cssVar("--fg", "#000000"),
|
||||
edgeLabelBackground: cssVar("--surface", "#ffffff"),
|
||||
fontFamily: cssVar("--font-body", "Noto, system-ui, sans-serif")
|
||||
},
|
||||
flowchart: {
|
||||
htmlLabels: true,
|
||||
curve: "basis"
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
function decodeMermaidSource(source) {
|
||||
const textarea = document.createElement("textarea");
|
||||
textarea.innerHTML = source;
|
||||
return textarea.value.trim();
|
||||
}
|
||||
|
||||
async function renderMermaid() {
|
||||
if (!window.mermaid) return;
|
||||
const diagrams = document.querySelectorAll(".mermaid");
|
||||
if (!diagrams.length) return;
|
||||
|
||||
diagrams.forEach((el) => {
|
||||
if (!el.dataset.source) {
|
||||
el.dataset.source = decodeMermaidSource(el.textContent || el.innerHTML);
|
||||
}
|
||||
el.removeAttribute("data-processed");
|
||||
el.innerHTML = el.dataset.source;
|
||||
});
|
||||
|
||||
mermaid.initialize(mermaidConfig());
|
||||
await mermaid.run({ querySelector: ".mermaid" });
|
||||
wrapMermaidDiagrams();
|
||||
}
|
||||
|
||||
function wrapMermaidDiagrams() {
|
||||
document.querySelectorAll(".mermaid").forEach((el) => {
|
||||
if (el.closest(".mermaid-container")) return;
|
||||
|
||||
const container = document.createElement("div");
|
||||
container.className = "mermaid-container";
|
||||
if ((el.dataset.source || "").includes('root(["zxh"])')) {
|
||||
container.classList.add("mermaid-container--site-map");
|
||||
}
|
||||
const controls = document.createElement("div");
|
||||
controls.className = "mermaid-zoom-controls";
|
||||
controls.innerHTML = `
|
||||
<button class="zoom-in" type="button" aria-label="Zoom in">+</button>
|
||||
<button class="zoom-out" type="button" aria-label="Zoom out">-</button>
|
||||
`;
|
||||
|
||||
el.replaceWith(container);
|
||||
container.appendChild(controls);
|
||||
container.appendChild(el);
|
||||
|
||||
let scale = 1;
|
||||
const setScale = (next) => {
|
||||
const svg = container.querySelector(".mermaid svg");
|
||||
if (!svg) return;
|
||||
scale = Math.max(0.2, Math.min(3, next));
|
||||
svg.style.transform = `scale(${scale})`;
|
||||
};
|
||||
|
||||
controls.querySelector(".zoom-in").addEventListener("click", () => setScale(scale + 0.1));
|
||||
controls.querySelector(".zoom-out").addEventListener("click", () => setScale(scale - 0.1));
|
||||
container.addEventListener("wheel", (e) => {
|
||||
if (!e.ctrlKey) return;
|
||||
e.preventDefault();
|
||||
setScale(scale + (e.deltaY < 0 ? 0.05 : -0.05));
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
if (document.readyState === "loading") {
|
||||
document.addEventListener("DOMContentLoaded", renderMermaid);
|
||||
} else {
|
||||
renderMermaid();
|
||||
}
|
||||
})();
|
||||
[
|
||||
"/assets/scripts/ui/copy-buttons.js",
|
||||
"/assets/scripts/ui/footnote-sidenotes.js",
|
||||
"/assets/scripts/application/theme-switcher.js",
|
||||
"/assets/scripts/ui/countdown.js",
|
||||
"/assets/scripts/ui/toc-active-link.js",
|
||||
"/assets/scripts/ui/mermaid-diagrams.js"
|
||||
].forEach(function (src) {
|
||||
var script = document.createElement("script");
|
||||
script.src = src;
|
||||
script.defer = true;
|
||||
document.head.appendChild(script);
|
||||
});
|
||||
}());
|
||||
|
||||
@@ -1,398 +1,7 @@
|
||||
/**
|
||||
* sitemap-interactive.js
|
||||
* Drop into /assets/scripts/ — no .org changes required.
|
||||
*
|
||||
* Handles two page structures generated by org-publish:
|
||||
* 1. FLAT LIST — a top-level <ul class="org-ul"> (e.g. Sitemap)
|
||||
* 2. OUTLINE — <div class="outline-2/3"> with <h2>/<h3> headings and
|
||||
* nested <ul class="org-ul"> (e.g. "2025 List", "Blogs List")
|
||||
*
|
||||
* Activated on any page whose <h1 class="title"> matches SITEMAP_PATTERNS.
|
||||
*/
|
||||
|
||||
(function () {
|
||||
"use strict";
|
||||
|
||||
const SITEMAP_PATTERNS = ["sitemap", "list"];
|
||||
|
||||
function init() {
|
||||
const titleEl = document.querySelector("h1.title");
|
||||
if (!titleEl) return;
|
||||
const title = titleEl.textContent.trim().toLowerCase();
|
||||
if (!SITEMAP_PATTERNS.some((p) => title.includes(p))) return;
|
||||
|
||||
const contentDiv = document.getElementById("content");
|
||||
if (!contentDiv) return;
|
||||
|
||||
const hasOutline = !!contentDiv.querySelector(".outline-2, .outline-3");
|
||||
const topUl = !hasOutline && contentDiv.querySelector("ul.org-ul");
|
||||
if (!hasOutline && !topUl) return;
|
||||
|
||||
// ── Parsers ───────────────────────────────────────────────────────────
|
||||
|
||||
function parseLi(li) {
|
||||
const link = li.querySelector(":scope > a");
|
||||
const childUl = li.querySelector(":scope > ul");
|
||||
const textNode = Array.from(li.childNodes).find(
|
||||
(n) => n.nodeType === Node.TEXT_NODE && n.textContent.trim()
|
||||
);
|
||||
const tags = Array.from(li.querySelectorAll(".post-tag")).map((t) =>
|
||||
t.textContent.trim()
|
||||
);
|
||||
const dateEl = li.querySelector(".post-date");
|
||||
const date = dateEl ? dateEl.textContent.trim() : null;
|
||||
|
||||
return {
|
||||
label: link
|
||||
? link.textContent.trim()
|
||||
: textNode
|
||||
? textNode.textContent.trim()
|
||||
: li.childNodes[0]?.textContent?.trim() || "",
|
||||
href: link ? link.getAttribute("href") : null,
|
||||
tags,
|
||||
date,
|
||||
children: childUl ? parseUl(childUl) : [],
|
||||
};
|
||||
}
|
||||
|
||||
function parseUl(ul) {
|
||||
return Array.from(ul.children)
|
||||
.filter((li) => li.tagName === "LI")
|
||||
.map(parseLi);
|
||||
}
|
||||
|
||||
function parseFlatList() {
|
||||
return { tree: parseUl(topUl), replaceTarget: topUl, wrapOutline: false };
|
||||
}
|
||||
|
||||
function parseOutline() {
|
||||
const tree = [];
|
||||
const outline2s = contentDiv.querySelectorAll(":scope .outline-2");
|
||||
|
||||
if (outline2s.length === 0) {
|
||||
// Only outline-3 directly (flat month grouping without year wrapper)
|
||||
contentDiv.querySelectorAll(":scope .outline-3").forEach((section) => {
|
||||
const heading = section.querySelector("h3");
|
||||
const ul = section.querySelector("ul.org-ul");
|
||||
tree.push({
|
||||
label: heading ? heading.textContent.trim() : "Section",
|
||||
href: null, tags: [], date: null,
|
||||
children: ul ? parseUl(ul) : [],
|
||||
});
|
||||
});
|
||||
} else {
|
||||
outline2s.forEach((o2) => {
|
||||
const h2 = o2.querySelector(":scope > div > h2, :scope > h2");
|
||||
const groupNode = {
|
||||
label: h2 ? h2.textContent.trim() : "Group",
|
||||
href: null, tags: [], date: null,
|
||||
children: [],
|
||||
};
|
||||
const outline3s = o2.querySelectorAll(".outline-3");
|
||||
if (outline3s.length > 0) {
|
||||
outline3s.forEach((o3) => {
|
||||
const h3 = o3.querySelector(":scope > div > h3, :scope > h3");
|
||||
const ul = o3.querySelector("ul.org-ul");
|
||||
groupNode.children.push({
|
||||
label: h3 ? h3.textContent.trim() : "Month",
|
||||
href: null, tags: [], date: null,
|
||||
children: ul ? parseUl(ul) : [],
|
||||
});
|
||||
});
|
||||
} else {
|
||||
const ul = o2.querySelector("ul.org-ul");
|
||||
if (ul) groupNode.children = parseUl(ul);
|
||||
}
|
||||
tree.push(groupNode);
|
||||
});
|
||||
}
|
||||
|
||||
return { tree, replaceTarget: null, wrapOutline: true };
|
||||
}
|
||||
|
||||
const parsed = hasOutline ? parseOutline() : parseFlatList();
|
||||
const { tree } = parsed;
|
||||
if (!tree.length) return;
|
||||
|
||||
// ── Styles ────────────────────────────────────────────────────────────
|
||||
if (!document.getElementById("sm-styles")) {
|
||||
const style = document.createElement("style");
|
||||
style.id = "sm-styles";
|
||||
style.textContent = `
|
||||
.sitemap-interactive { font-family: inherit; margin: 1.5rem 0; }
|
||||
.sm-toolbar {
|
||||
display: flex; align-items: center; gap: .6rem;
|
||||
margin-bottom: 1rem; flex-wrap: wrap;
|
||||
}
|
||||
.sm-search {
|
||||
flex: 1; min-width: 160px; padding: .35rem .7rem;
|
||||
border: 1px solid var(--border, #444); border-radius: 4px;
|
||||
background: var(--bg, transparent); color: inherit; font-size: .9rem;
|
||||
}
|
||||
.sm-search:focus { outline: 2px solid var(--accent, #7aa2f7); outline-offset: 1px; }
|
||||
.sm-expand-all, .sm-collapse-all {
|
||||
padding: .3rem .65rem; border: 1px solid var(--border, #444);
|
||||
border-radius: 4px; background: transparent; color: inherit;
|
||||
font-size: .8rem; cursor: pointer; opacity: .75; transition: opacity .15s;
|
||||
}
|
||||
.sm-expand-all:hover, .sm-collapse-all:hover { opacity: 1; }
|
||||
|
||||
.sm-tree ul { list-style: none; margin: 0; padding: 0 0 0 1.4rem; }
|
||||
.sm-tree > ul { padding-left: 0; }
|
||||
.sm-tree li { margin: 0; }
|
||||
.sm-node {
|
||||
display: flex; align-items: center; gap: .4rem;
|
||||
padding: .2rem .3rem; border-radius: 4px;
|
||||
line-height: 1.5; transition: background .1s; flex-wrap: wrap;
|
||||
}
|
||||
.sm-node:hover { background: var(--hover-bg, rgba(122,162,247,.08)); }
|
||||
.sm-node.sm-hidden { display: none; }
|
||||
|
||||
.sm-toggle {
|
||||
width: 1.2rem; height: 1.2rem; display: inline-flex;
|
||||
align-items: center; justify-content: center;
|
||||
cursor: pointer; border: none; background: none; color: inherit;
|
||||
font-size: .7rem; opacity: .6;
|
||||
transition: transform .18s, opacity .15s;
|
||||
flex-shrink: 0; padding: 0; border-radius: 3px;
|
||||
}
|
||||
.sm-toggle:hover { opacity: 1; background: var(--hover-bg, rgba(122,162,247,.15)); }
|
||||
.sm-toggle.open { transform: rotate(90deg); }
|
||||
.sm-toggle-placeholder { width: 1.2rem; flex-shrink: 0; }
|
||||
|
||||
.sm-icon { font-size: .8rem; opacity: .5; flex-shrink: 0; }
|
||||
|
||||
.sm-label a { color: var(--link, inherit); text-decoration: none; font-size: .9rem; }
|
||||
.sm-label a:hover { text-decoration: underline; }
|
||||
.sm-label span { font-size: .9rem; font-weight: 600; opacity: .85; }
|
||||
|
||||
.sm-badge {
|
||||
font-size: .65rem; padding: .05rem .35rem; border-radius: 8px;
|
||||
background: var(--badge-bg, rgba(122,162,247,.15));
|
||||
color: var(--badge-fg, #7aa2f7); opacity: .8;
|
||||
}
|
||||
.sm-date { font-size: .75rem; opacity: .45; margin-left: .2rem; }
|
||||
.sm-tags { display: inline-flex; gap: .25rem; margin-left: .2rem; }
|
||||
.sm-tag {
|
||||
font-size: .65rem; padding: .05rem .3rem; border-radius: 8px;
|
||||
background: var(--tag-bg, rgba(160,200,120,.15));
|
||||
color: var(--tag-fg, #9ece6a); opacity: .85;
|
||||
}
|
||||
|
||||
.sm-children { overflow: hidden; }
|
||||
.sm-children.collapsed { display: none; }
|
||||
.sm-label mark {
|
||||
background: var(--mark-bg, rgba(255,200,50,.3));
|
||||
color: inherit; border-radius: 2px; padding: 0 1px;
|
||||
}
|
||||
.sm-count { font-size: .78rem; opacity: .45; margin-top: .8rem; }
|
||||
`;
|
||||
document.head.appendChild(style);
|
||||
}
|
||||
|
||||
// ── Widget scaffold ───────────────────────────────────────────────────
|
||||
const wrapper = document.createElement("div");
|
||||
wrapper.className = "sitemap-interactive";
|
||||
wrapper.innerHTML = `
|
||||
<div class="sm-toolbar">
|
||||
<input class="sm-search" type="search" placeholder="Filter pages…" aria-label="Filter" />
|
||||
<button class="sm-expand-all">⊞ Expand all</button>
|
||||
<button class="sm-collapse-all">⊟ Collapse all</button>
|
||||
</div>
|
||||
<div class="sm-tree" role="tree"></div>
|
||||
<p class="sm-count"></p>
|
||||
`;
|
||||
|
||||
const treeEl = wrapper.querySelector(".sm-tree");
|
||||
const searchEl = wrapper.querySelector(".sm-search");
|
||||
const countEl = wrapper.querySelector(".sm-count");
|
||||
|
||||
// ── Tree builder ──────────────────────────────────────────────────────
|
||||
function countLeaves(nodes) {
|
||||
let n = 0;
|
||||
for (const node of nodes) {
|
||||
if (!node.children || !node.children.length) n++;
|
||||
else n += countLeaves(node.children);
|
||||
}
|
||||
return n;
|
||||
}
|
||||
|
||||
function buildTree(nodes) {
|
||||
const ul = document.createElement("ul");
|
||||
for (const node of nodes) {
|
||||
const li = document.createElement("li");
|
||||
const row = document.createElement("div");
|
||||
row.className = "sm-node";
|
||||
const hasChildren = node.children && node.children.length > 0;
|
||||
|
||||
let childrenEl;
|
||||
if (hasChildren) {
|
||||
const toggle = document.createElement("button");
|
||||
toggle.className = "sm-toggle open";
|
||||
toggle.innerHTML = "▶";
|
||||
toggle.setAttribute("aria-expanded", "true");
|
||||
childrenEl = document.createElement("div");
|
||||
childrenEl.className = "sm-children";
|
||||
childrenEl.appendChild(buildTree(node.children));
|
||||
toggle.addEventListener("click", () => {
|
||||
childrenEl.classList.toggle("collapsed");
|
||||
toggle.classList.toggle("open");
|
||||
toggle.setAttribute("aria-expanded",
|
||||
String(!childrenEl.classList.contains("collapsed")));
|
||||
});
|
||||
row.appendChild(toggle);
|
||||
} else {
|
||||
const ph = document.createElement("span");
|
||||
ph.className = "sm-toggle-placeholder";
|
||||
row.appendChild(ph);
|
||||
}
|
||||
|
||||
const icon = document.createElement("span");
|
||||
icon.className = "sm-icon";
|
||||
icon.textContent = hasChildren ? "📂" : "📄";
|
||||
row.appendChild(icon);
|
||||
|
||||
const labelEl = document.createElement("span");
|
||||
labelEl.className = "sm-label";
|
||||
if (node.href) {
|
||||
const a = document.createElement("a");
|
||||
a.href = node.href;
|
||||
a.textContent = node.label;
|
||||
labelEl.appendChild(a);
|
||||
} else {
|
||||
const s = document.createElement("span");
|
||||
s.textContent = node.label;
|
||||
labelEl.appendChild(s);
|
||||
}
|
||||
row.appendChild(labelEl);
|
||||
|
||||
if (hasChildren) {
|
||||
const badge = document.createElement("span");
|
||||
badge.className = "sm-badge";
|
||||
badge.textContent = countLeaves(node.children);
|
||||
row.appendChild(badge);
|
||||
}
|
||||
|
||||
if (node.date) {
|
||||
const dateSpan = document.createElement("span");
|
||||
dateSpan.className = "sm-date";
|
||||
dateSpan.textContent = node.date;
|
||||
row.appendChild(dateSpan);
|
||||
}
|
||||
|
||||
if (node.tags && node.tags.length) {
|
||||
const tagsEl = document.createElement("span");
|
||||
tagsEl.className = "sm-tags";
|
||||
node.tags.forEach((t) => {
|
||||
const tag = document.createElement("span");
|
||||
tag.className = "sm-tag";
|
||||
tag.textContent = t;
|
||||
tagsEl.appendChild(tag);
|
||||
});
|
||||
row.appendChild(tagsEl);
|
||||
}
|
||||
|
||||
li.appendChild(row);
|
||||
if (hasChildren) li.appendChild(childrenEl);
|
||||
ul.appendChild(li);
|
||||
}
|
||||
return ul;
|
||||
}
|
||||
|
||||
treeEl.appendChild(buildTree(tree));
|
||||
|
||||
// ── Search / filter ───────────────────────────────────────────────────
|
||||
function escapeRe(s) {
|
||||
return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
||||
}
|
||||
|
||||
function filterTree(q) {
|
||||
const query = q.trim().toLowerCase();
|
||||
const re = query ? new RegExp(escapeRe(query), "gi") : null;
|
||||
let visible = 0;
|
||||
|
||||
function walk(ul) {
|
||||
let anyVisible = false;
|
||||
for (const li of ul.children) {
|
||||
const row = li.querySelector(":scope > .sm-node");
|
||||
const childrenDiv = li.querySelector(":scope > .sm-children");
|
||||
const labelEl = row.querySelector(".sm-label");
|
||||
const target = labelEl.querySelector("a") || labelEl.querySelector("span");
|
||||
const text = target.dataset.orig || target.textContent;
|
||||
target.dataset.orig = text;
|
||||
|
||||
let selfMatch = false;
|
||||
if (!query) {
|
||||
target.innerHTML = "";
|
||||
target.textContent = text;
|
||||
selfMatch = true;
|
||||
} else if (text.toLowerCase().includes(query)) {
|
||||
target.innerHTML = text.replace(re, (m) => `<mark>${m}</mark>`);
|
||||
selfMatch = true;
|
||||
} else {
|
||||
target.innerHTML = "";
|
||||
target.textContent = text;
|
||||
}
|
||||
|
||||
let childVisible = false;
|
||||
if (childrenDiv) {
|
||||
childVisible = walk(childrenDiv.querySelector("ul"));
|
||||
if (query) {
|
||||
childrenDiv.classList.toggle("collapsed", !childVisible && !selfMatch);
|
||||
const toggle = row.querySelector(".sm-toggle");
|
||||
if (toggle) toggle.classList.toggle("open", childVisible || selfMatch);
|
||||
}
|
||||
}
|
||||
|
||||
const show = !query || selfMatch || childVisible;
|
||||
row.classList.toggle("sm-hidden", !show);
|
||||
if (show) {
|
||||
anyVisible = true;
|
||||
if (!childrenDiv) visible++;
|
||||
}
|
||||
}
|
||||
return anyVisible;
|
||||
}
|
||||
|
||||
walk(treeEl.querySelector("ul"));
|
||||
countEl.textContent = query
|
||||
? `${visible} page${visible !== 1 ? "s" : ""} matching "${query}"`
|
||||
: "";
|
||||
}
|
||||
|
||||
searchEl.addEventListener("input", (e) => filterTree(e.target.value));
|
||||
|
||||
wrapper.querySelector(".sm-expand-all").addEventListener("click", () => {
|
||||
treeEl.querySelectorAll(".sm-children").forEach((el) => el.classList.remove("collapsed"));
|
||||
treeEl.querySelectorAll(".sm-toggle").forEach((el) => {
|
||||
el.classList.add("open");
|
||||
el.setAttribute("aria-expanded", "true");
|
||||
});
|
||||
});
|
||||
wrapper.querySelector(".sm-collapse-all").addEventListener("click", () => {
|
||||
treeEl.querySelectorAll(".sm-children").forEach((el) => el.classList.add("collapsed"));
|
||||
treeEl.querySelectorAll(".sm-toggle").forEach((el) => {
|
||||
el.classList.remove("open");
|
||||
el.setAttribute("aria-expanded", "false");
|
||||
});
|
||||
});
|
||||
|
||||
// ── Inject into page ──────────────────────────────────────────────────
|
||||
if (parsed.wrapOutline) {
|
||||
// Hide original outline divs (direct children of content only)
|
||||
contentDiv.querySelectorAll(":scope > .outline-2, :scope > .outline-3")
|
||||
.forEach((el) => (el.style.display = "none"));
|
||||
// Insert after title + optional intro <p>
|
||||
const insertAfter = contentDiv.querySelector(":scope > p") || titleEl;
|
||||
insertAfter.insertAdjacentElement("afterend", wrapper);
|
||||
} else {
|
||||
parsed.replaceTarget.replaceWith(wrapper);
|
||||
}
|
||||
}
|
||||
|
||||
if (document.readyState === "loading") {
|
||||
document.addEventListener("DOMContentLoaded", init);
|
||||
} else {
|
||||
init();
|
||||
}
|
||||
})();
|
||||
var script = document.createElement("script");
|
||||
script.src = "/assets/scripts/pages/sitemap-interactive.js";
|
||||
script.defer = true;
|
||||
document.head.appendChild(script);
|
||||
}());
|
||||
|
||||
34
assets/scripts/svg-pan-zoom.min.js
vendored
34
assets/scripts/svg-pan-zoom.min.js
vendored
File diff suppressed because one or more lines are too long
19
assets/scripts/ui/copy-buttons.js
Normal file
19
assets/scripts/ui/copy-buttons.js
Normal file
@@ -0,0 +1,19 @@
|
||||
/* Event listener function for the COPY BUTTON */
|
||||
document.addEventListener("DOMContentLoaded", function () {
|
||||
document.querySelectorAll("pre.src").forEach(function (codeBlock) {
|
||||
const button = document.createElement("button");
|
||||
button.innerText = "Copy";
|
||||
button.className = "copy-btn";
|
||||
|
||||
// Append button inside <pre>
|
||||
codeBlock.appendChild(button);
|
||||
|
||||
button.addEventListener("click", function () {
|
||||
const text = codeBlock.innerText.replace(button.innerText, ""); // exclude button text
|
||||
navigator.clipboard.writeText(text.trim()).then(() => {
|
||||
button.innerText = "Copied!";
|
||||
setTimeout(() => (button.innerText = "Copy"), 1500);
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
38
assets/scripts/ui/countdown.js
Normal file
38
assets/scripts/ui/countdown.js
Normal file
@@ -0,0 +1,38 @@
|
||||
// Simple, timezone-safe if you pass UTC (…Z) in the datetime
|
||||
document.addEventListener('DOMContentLoaded', () => {
|
||||
const els = document.querySelectorAll('time.countdown');
|
||||
if (!els.length) return;
|
||||
|
||||
const plural = (n, w) => `${n} ${w}${n === 1 ? '' : 's'}`;
|
||||
|
||||
const render = (el) => {
|
||||
const raw = el.getAttribute('datetime');
|
||||
const label = el.dataset.label || '';
|
||||
const target = new Date(raw); // Prefer ISO like 2025-12-31T00:00:00Z
|
||||
if (isNaN(target)) { el.textContent = '—'; return; }
|
||||
|
||||
const now = new Date();
|
||||
let diff = target - now;
|
||||
|
||||
if (diff <= 0) {
|
||||
el.textContent = `${label ? label + ' ' : ''}today`;
|
||||
el.classList.add('expired');
|
||||
return;
|
||||
}
|
||||
|
||||
const d = Math.floor(diff / 86400000); diff -= d * 86400000;
|
||||
const h = Math.floor(diff / 3600000); diff -= h * 3600000;
|
||||
const m = Math.floor(diff / 60000); diff -= m * 60000;
|
||||
const s = Math.floor(diff / 1000);
|
||||
|
||||
const pieces = [];
|
||||
if (d) pieces.push(plural(d, 'day'));
|
||||
pieces.push(`${h}h ${m}m ${s}s`);
|
||||
|
||||
el.textContent = `${label ? label + ' in : ' : ''}${pieces.join(' ')}`;
|
||||
};
|
||||
|
||||
const tick = () => els.forEach(render);
|
||||
tick();
|
||||
setInterval(tick, 1000); // update every second
|
||||
});
|
||||
50
assets/scripts/ui/footnote-sidenotes.js
Normal file
50
assets/scripts/ui/footnote-sidenotes.js
Normal file
@@ -0,0 +1,50 @@
|
||||
/* Event listener for footnotes and sidenotes*/
|
||||
document.addEventListener("DOMContentLoaded", () => {
|
||||
document.querySelectorAll('a.footref[href^="#fn"]').forEach(ref => {
|
||||
const sup = ref.closest("sup") || ref;
|
||||
// idempotent: don't insert twice
|
||||
if (sup.nextElementSibling && sup.nextElementSibling.classList?.contains("footnote-sidenote")) return;
|
||||
|
||||
const targetId = ref.getAttribute("href").replace(/^#/, ""); // works for fn.2 or fn2
|
||||
|
||||
const anchor = document.getElementById(targetId);
|
||||
if (!anchor) return;
|
||||
|
||||
const footdef = anchor.closest(".footdef") || anchor.parentElement;
|
||||
if (!footdef) return;
|
||||
|
||||
// 1) Prefer leaf paragraphs to avoid div+p duplication
|
||||
let paras = footdef.querySelectorAll("p.footpara");
|
||||
if (!paras.length) {
|
||||
// fallback: any .footpara elements that don't contain another .footpara
|
||||
paras = footdef.querySelectorAll(".footpara:not(:has(.footpara))");
|
||||
}
|
||||
|
||||
// 2) Build HTML, de-duplicating by text content
|
||||
let parts = [];
|
||||
if (paras.length) {
|
||||
const seen = new Set();
|
||||
parts = Array.from(paras).map(p => {
|
||||
const txt = p.textContent.trim().replace(/\s+/g, " ");
|
||||
if (seen.has(txt)) return "";
|
||||
seen.add(txt);
|
||||
return p.innerHTML.trim();
|
||||
}).filter(Boolean);
|
||||
}
|
||||
|
||||
// 3) Fallback: clean full block if no paras found
|
||||
if (!parts.length) {
|
||||
const clone = footdef.cloneNode(true);
|
||||
clone.querySelectorAll("sup.footnum, a[role='doc-backlink']").forEach(n => n.remove());
|
||||
parts = [clone.innerHTML.trim()];
|
||||
}
|
||||
|
||||
// 4) Insert the sidenote
|
||||
const sn = document.createElement("span");
|
||||
sn.className = "sidenote footnote-sidenote";
|
||||
sn.setAttribute("data-fn", (ref.textContent || "").trim());
|
||||
sn.innerHTML = parts.join(" ");
|
||||
|
||||
sup.insertAdjacentElement("afterend", sn);
|
||||
});
|
||||
});
|
||||
315
assets/scripts/ui/gallery-init.js
Normal file
315
assets/scripts/ui/gallery-init.js
Normal file
@@ -0,0 +1,315 @@
|
||||
document.addEventListener('DOMContentLoaded', () => {
|
||||
if (typeof window.BiggerPicture !== 'function') {
|
||||
console.error('[gallery-init] BiggerPicture not found. Check script path.');
|
||||
return;
|
||||
}
|
||||
const VIDEO_EXTENSIONS = ['mp4', 'webm', 'mov', 'm4v', 'ogv'];
|
||||
|
||||
const isVideo = (href) => {
|
||||
if (!href) return false;
|
||||
href = href.toLowerCase();
|
||||
return VIDEO_EXTENSIONS.some(ext => href.endsWith('.' + ext));
|
||||
};
|
||||
|
||||
// 1b) Convert MP4 links into inline <video> players
|
||||
// Convert video links into inline <video> players BUT keep the <a>
|
||||
const videoLinks = document.querySelectorAll('a[href]');
|
||||
videoLinks.forEach(a => {
|
||||
const href = a.getAttribute("href");
|
||||
if (!isVideo(href)) return;
|
||||
|
||||
const video = document.createElement("video");
|
||||
video.controls = true;
|
||||
video.preload = "metadata";
|
||||
video.style.maxWidth = "100%";
|
||||
video.style.borderRadius = "6px";
|
||||
|
||||
const source = document.createElement("source");
|
||||
source.src = href;
|
||||
source.type = "video/" + href.split('.').pop(); // guesses correct mime
|
||||
video.appendChild(source);
|
||||
|
||||
// Replace the link with the inline video
|
||||
a.parentNode.replaceChild(video, a);
|
||||
});
|
||||
|
||||
// 1) Wrap Org-exported images so they’re clickable
|
||||
const imgs = document.querySelectorAll('.figure img, img.org-svg');
|
||||
imgs.forEach((img) => {
|
||||
if (img.closest('a')) return; // already wrapped
|
||||
const a = document.createElement('a');
|
||||
const href = img.currentSrc || img.src;
|
||||
a.href = href;
|
||||
a.dataset.img = href; // lets BP pre-size/raster slides
|
||||
a.dataset.alt = img.alt || '';
|
||||
const setDims = () => {
|
||||
a.dataset.width = img.naturalWidth || img.width || 1920;
|
||||
a.dataset.height = img.naturalHeight || img.height || 1080;
|
||||
};
|
||||
if (img.complete) setDims(); else img.addEventListener('load', setDims);
|
||||
img.style.cursor = 'zoom-in';
|
||||
img.parentElement.insertBefore(a, img);
|
||||
a.appendChild(img);
|
||||
});
|
||||
|
||||
// 2) One global BP instance
|
||||
const bp = BiggerPicture({ target: document.body });
|
||||
|
||||
// SVG pan/zoom handle
|
||||
let activePanZoom = null;
|
||||
const destroyPanZoom = () => { try { activePanZoom?.destroy(); } catch(_){} activePanZoom = null; };
|
||||
|
||||
// Simple rotate state (for non-SVG images)
|
||||
let activeContainer = null;
|
||||
let currentRotation = 0;
|
||||
let rotateControls = null;
|
||||
|
||||
// 3) Build galleries per content container
|
||||
const containers = document.querySelectorAll('main, article, .content, body');
|
||||
containers.forEach((container) => {
|
||||
const links = Array.from(container.querySelectorAll(
|
||||
'.figure a, a:has(img.org-svg), a[href$=".mp4"], a[href$=".webm"], a[href$=".mov"], a[href$=".m4v"], a[href$=".ogv"]'
|
||||
));
|
||||
if (!links.length) return;
|
||||
|
||||
// Start the lightbox on click
|
||||
links.forEach((link, index) => {
|
||||
link.addEventListener('click', (e) => {
|
||||
e.preventDefault();
|
||||
document.querySelectorAll(".theme-toggle").forEach(el => {
|
||||
el.classList.add("hidden");
|
||||
});
|
||||
|
||||
bp.open({
|
||||
// IMPORTANT: pass the anchor ELEMENTS, not custom objects
|
||||
items: links,
|
||||
el: link,
|
||||
caption: (el) => el.querySelector('img')?.alt || el.title || '',
|
||||
maxZoom: 40, // for raster images (PNG/JPG); SVG handled separately
|
||||
|
||||
// Fade-out polish + cleanup
|
||||
onClose(containerEl) {
|
||||
destroyPanZoom();
|
||||
teardownRotation();
|
||||
if (containerEl) containerEl.classList.add('bp-fadeout');
|
||||
const themeToggle = document.querySelector(".theme-toggle");
|
||||
if (themeToggle) {
|
||||
themeToggle.classList.remove("hidden");
|
||||
}
|
||||
},
|
||||
|
||||
// Called once after open and on every slide change
|
||||
//onOpen(containerEl) { setupRotation(containerEl); enhanceSVG(containerEl); }
|
||||
onOpen(containerEl) {
|
||||
const linkEl = bp.currItem;
|
||||
const href = linkEl?.href || "";
|
||||
|
||||
if (href.endsWith(".mp4")) {
|
||||
// Turn off image rotation (not applicable for video)
|
||||
teardownRotation();
|
||||
|
||||
const htmlLayer = containerEl.querySelector(".bp-html");
|
||||
const imgLayer = containerEl.querySelector(".bp-img");
|
||||
|
||||
if (!htmlLayer) return;
|
||||
|
||||
// Hide the default image layer
|
||||
if (imgLayer) imgLayer.style.display = "none";
|
||||
|
||||
// Insert video player
|
||||
htmlLayer.innerHTML = `
|
||||
<video controls autoplay style="max-width:95vw; max-height:95vh">
|
||||
<source src="${href}" type="video/mp4">
|
||||
</video>
|
||||
`;
|
||||
|
||||
return; // Do not run image/SVG enhancements
|
||||
}
|
||||
|
||||
// Image behaviour
|
||||
setupRotation(containerEl);
|
||||
enhanceSVG(containerEl);
|
||||
} ,
|
||||
onUpdate(containerEl){ setupRotation(containerEl); enhanceSVG(containerEl); }
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
// 4) Simple rotate buttons for raster images
|
||||
function ensureRotateControls() {
|
||||
if (rotateControls) return rotateControls;
|
||||
|
||||
const wrapper = document.createElement('div');
|
||||
wrapper.className = 'bp-rotate-controls';
|
||||
Object.assign(wrapper.style, {
|
||||
position: 'fixed',
|
||||
bottom: '1.5rem',
|
||||
right: '1.5rem',
|
||||
display: 'flex',
|
||||
gap: '0.5rem',
|
||||
zIndex: '9999',
|
||||
pointerEvents: 'auto'
|
||||
});
|
||||
|
||||
const mkBtn = (label, title) => {
|
||||
const btn = document.createElement('button');
|
||||
btn.type = 'button';
|
||||
btn.textContent = label;
|
||||
btn.title = title;
|
||||
btn.setAttribute('aria-label', title);
|
||||
Object.assign(btn.style, {
|
||||
padding: '0.4rem 0.6rem',
|
||||
borderRadius: '999px',
|
||||
border: 'none',
|
||||
fontSize: '1.2rem',
|
||||
cursor: 'pointer',
|
||||
background: 'rgba(30,30,30,0.8)',
|
||||
color: '#fff'
|
||||
});
|
||||
return btn;
|
||||
};
|
||||
|
||||
const left = mkBtn('⟲', 'Rotate image 90° left');
|
||||
const right = mkBtn('⟳', 'Rotate image 90° right');
|
||||
|
||||
left.addEventListener('click', (e) => {
|
||||
e.stopPropagation(); // don’t close the lightbox
|
||||
if (!activeContainer) return;
|
||||
currentRotation = (currentRotation - 90 + 360) % 360;
|
||||
applyRotation();
|
||||
});
|
||||
|
||||
right.addEventListener('click', (e) => {
|
||||
e.stopPropagation();
|
||||
if (!activeContainer) return;
|
||||
currentRotation = (currentRotation + 90) % 360;
|
||||
applyRotation();
|
||||
});
|
||||
|
||||
wrapper.append(left, right);
|
||||
document.body.appendChild(wrapper);
|
||||
rotateControls = wrapper;
|
||||
return rotateControls;
|
||||
}
|
||||
|
||||
function ensureRotateWrapper() {
|
||||
if (!activeContainer) return null;
|
||||
|
||||
const imgRoot = activeContainer.querySelector('.bp-img');
|
||||
if (!imgRoot) return null;
|
||||
|
||||
let imgEl = imgRoot.querySelector('img');
|
||||
if (!imgEl) return null;
|
||||
|
||||
const src = (imgEl.currentSrc || imgEl.src || '').toLowerCase();
|
||||
// We only rotate raster images; SVGs are handled via svg-pan-zoom
|
||||
if (src.endsWith('.svg')) return null;
|
||||
|
||||
let wrapper = imgRoot.querySelector('.bp-rotate-wrapper');
|
||||
if (!wrapper) {
|
||||
wrapper = document.createElement('div');
|
||||
wrapper.className = 'bp-rotate-wrapper';
|
||||
wrapper.style.display = 'inline-block';
|
||||
wrapper.style.transformOrigin = 'center center';
|
||||
|
||||
imgRoot.appendChild(wrapper);
|
||||
wrapper.appendChild(imgEl);
|
||||
} else if (!wrapper.contains(imgEl)) {
|
||||
// Slide changed and BiggerPicture replaced the <img>
|
||||
wrapper.innerHTML = '';
|
||||
wrapper.appendChild(imgEl);
|
||||
}
|
||||
|
||||
return wrapper;
|
||||
}
|
||||
|
||||
function applyRotation() {
|
||||
const wrapper = ensureRotateWrapper();
|
||||
if (!wrapper) return;
|
||||
wrapper.style.transform = `rotate(${currentRotation}deg)`;
|
||||
}
|
||||
|
||||
function setupRotation(containerEl) {
|
||||
activeContainer = containerEl;
|
||||
currentRotation = 0;
|
||||
const controls = ensureRotateControls();
|
||||
controls.style.display = 'flex';
|
||||
applyRotation();
|
||||
}
|
||||
|
||||
function teardownRotation() {
|
||||
activeContainer = null;
|
||||
currentRotation = 0;
|
||||
if (rotateControls) {
|
||||
rotateControls.style.display = 'none';
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// 4) If current slide is an SVG, swap to inline + enable svg-pan-zoom
|
||||
async function enhanceSVG(containerEl) {
|
||||
try {
|
||||
destroyPanZoom();
|
||||
|
||||
const imgEl = containerEl.querySelector('.bp-img img');
|
||||
if (!imgEl) return;
|
||||
|
||||
const src = imgEl.currentSrc || imgEl.src || '';
|
||||
const isSVG = src.toLowerCase().endsWith('.svg');
|
||||
const htmlLayer = containerEl.querySelector('.bp-html');
|
||||
if (!isSVG || !htmlLayer) {
|
||||
// ensure any previous holder is removed and bitmap is visible
|
||||
const old = htmlLayer?.querySelector('.bp-svg-holder');
|
||||
if (old) old.remove();
|
||||
imgEl.style.visibility = '';
|
||||
return;
|
||||
}
|
||||
|
||||
// Create/clear holder
|
||||
let holder = htmlLayer.querySelector('.bp-svg-holder');
|
||||
if (!holder) {
|
||||
holder = document.createElement('div');
|
||||
holder.className = 'bp-svg-holder';
|
||||
holder.style.maxWidth = '95vw';
|
||||
holder.style.maxHeight = '95vh';
|
||||
htmlLayer.appendChild(holder);
|
||||
}
|
||||
holder.innerHTML = '';
|
||||
|
||||
// Hide the bitmap so only the inline SVG shows
|
||||
imgEl.style.visibility = 'hidden';
|
||||
|
||||
// Inline the SVG
|
||||
const res = await fetch(src, { cache: 'force-cache' });
|
||||
const text = await res.text();
|
||||
holder.innerHTML = text;
|
||||
|
||||
const svg = holder.querySelector('svg');
|
||||
if (!svg) { imgEl.style.visibility = ''; return; }
|
||||
|
||||
svg.style.maxWidth = '95vw';
|
||||
svg.style.maxHeight = '95vh';
|
||||
svg.style.display = 'block';
|
||||
|
||||
if (typeof window.svgPanZoom === 'function') {
|
||||
activePanZoom = svgPanZoom(svg, {
|
||||
zoomEnabled: true,
|
||||
controlIconsEnabled: true,
|
||||
fit: true,
|
||||
center: true,
|
||||
minZoom: 0.05,
|
||||
maxZoom: 400, // effectively "unlimited"
|
||||
zoomScaleSensitivity: 0.25,
|
||||
dblClickZoomEnabled: true
|
||||
});
|
||||
// Keep wheel inside lightbox
|
||||
holder.addEventListener('wheel', (e) => e.stopPropagation(), { passive: true });
|
||||
} else {
|
||||
console.warn('[gallery-init] svg-pan-zoom not loaded');
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('[gallery-init] SVG enhance failed:', err);
|
||||
}
|
||||
}
|
||||
});
|
||||
101
assets/scripts/ui/mermaid-diagrams.js
Normal file
101
assets/scripts/ui/mermaid-diagrams.js
Normal file
@@ -0,0 +1,101 @@
|
||||
// Make Mermaid diagrams use the active site theme and zoom controls.
|
||||
(function () {
|
||||
function cssVar(name, fallback) {
|
||||
const value = getComputedStyle(document.documentElement).getPropertyValue(name).trim();
|
||||
return value || fallback;
|
||||
}
|
||||
|
||||
function mermaidConfig() {
|
||||
return {
|
||||
startOnLoad: false,
|
||||
theme: "base",
|
||||
themeVariables: {
|
||||
background: cssVar("--bg", "#faf9f6"),
|
||||
mainBkg: cssVar("--surface", "#ffffff"),
|
||||
primaryColor: cssVar("--surface", "#ffffff"),
|
||||
primaryTextColor: cssVar("--fg", "#000000"),
|
||||
primaryBorderColor: cssVar("--accent", "#2563eb"),
|
||||
secondaryColor: cssVar("--surface-soft", "#f3f1eb"),
|
||||
tertiaryColor: cssVar("--bg", "#faf9f6"),
|
||||
clusterBkg: cssVar("--surface-soft", "#f3f1eb"),
|
||||
clusterBorder: cssVar("--border", "#d7d7d7"),
|
||||
lineColor: cssVar("--border", "#d7d7d7"),
|
||||
textColor: cssVar("--fg", "#000000"),
|
||||
edgeLabelBackground: cssVar("--surface", "#ffffff"),
|
||||
fontFamily: cssVar("--font-body", "Noto, system-ui, sans-serif")
|
||||
},
|
||||
flowchart: {
|
||||
htmlLabels: true,
|
||||
curve: "basis"
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
function decodeMermaidSource(source) {
|
||||
const textarea = document.createElement("textarea");
|
||||
textarea.innerHTML = source;
|
||||
return textarea.value.trim();
|
||||
}
|
||||
|
||||
async function renderMermaid() {
|
||||
if (!window.mermaid) return;
|
||||
const diagrams = document.querySelectorAll(".mermaid");
|
||||
if (!diagrams.length) return;
|
||||
|
||||
diagrams.forEach((el) => {
|
||||
if (!el.dataset.source) {
|
||||
el.dataset.source = decodeMermaidSource(el.textContent || el.innerHTML);
|
||||
}
|
||||
el.removeAttribute("data-processed");
|
||||
el.innerHTML = el.dataset.source;
|
||||
});
|
||||
|
||||
mermaid.initialize(mermaidConfig());
|
||||
await mermaid.run({ querySelector: ".mermaid" });
|
||||
wrapMermaidDiagrams();
|
||||
}
|
||||
|
||||
function wrapMermaidDiagrams() {
|
||||
document.querySelectorAll(".mermaid").forEach((el) => {
|
||||
if (el.closest(".mermaid-container")) return;
|
||||
|
||||
const container = document.createElement("div");
|
||||
container.className = "mermaid-container";
|
||||
if ((el.dataset.source || "").includes('root(["zxh"])')) {
|
||||
container.classList.add("mermaid-container--site-map");
|
||||
}
|
||||
const controls = document.createElement("div");
|
||||
controls.className = "mermaid-zoom-controls";
|
||||
controls.innerHTML = `
|
||||
<button class="zoom-in" type="button" aria-label="Zoom in">+</button>
|
||||
<button class="zoom-out" type="button" aria-label="Zoom out">-</button>
|
||||
`;
|
||||
|
||||
el.replaceWith(container);
|
||||
container.appendChild(controls);
|
||||
container.appendChild(el);
|
||||
|
||||
let scale = 1;
|
||||
const setScale = (next) => {
|
||||
const svg = container.querySelector(".mermaid svg");
|
||||
if (!svg) return;
|
||||
scale = Math.max(0.2, Math.min(3, next));
|
||||
svg.style.transform = `scale(${scale})`;
|
||||
};
|
||||
|
||||
controls.querySelector(".zoom-in").addEventListener("click", () => setScale(scale + 0.1));
|
||||
controls.querySelector(".zoom-out").addEventListener("click", () => setScale(scale - 0.1));
|
||||
container.addEventListener("wheel", (e) => {
|
||||
if (!e.ctrlKey) return;
|
||||
e.preventDefault();
|
||||
setScale(scale + (e.deltaY < 0 ? 0.05 : -0.05));
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
if (document.readyState === "loading") {
|
||||
document.addEventListener("DOMContentLoaded", renderMermaid);
|
||||
} else {
|
||||
renderMermaid();
|
||||
}
|
||||
})();
|
||||
88
assets/scripts/ui/toc-active-link.js
Normal file
88
assets/scripts/ui/toc-active-link.js
Normal file
@@ -0,0 +1,88 @@
|
||||
/* Event listener for scrolling and changing the active label on the TOC */
|
||||
document.addEventListener("DOMContentLoaded", () => {
|
||||
const toc = document.querySelector("#text-table-of-contents");
|
||||
if (!toc) { console.warn("No #text-table-of-contents found"); return; }
|
||||
|
||||
const links = toc.querySelectorAll('a[href^="#"]'); // '^=' is a starts with operator.
|
||||
// <a href="#introduction">Intro</a> matches
|
||||
if (!links.length) { console.warn("No ToC links found"); return; }
|
||||
|
||||
// Map: id -> link
|
||||
const linkById = new Map();
|
||||
links.forEach(a => {
|
||||
const id = decodeURIComponent(a.getAttribute("href").slice(1));
|
||||
const el = document.getElementById(id);
|
||||
if (el) linkById.set(id, a);
|
||||
});
|
||||
if (!linkById.size) { console.warn("No matching headings with IDs"); return; }
|
||||
|
||||
// Headings to observe (h2–h4 usually)
|
||||
const headings = [...document.querySelectorAll("h2[id], h3[id], h4[id]")]
|
||||
.filter(h => linkById.has(h.id));
|
||||
|
||||
// Helper to mark active
|
||||
const setActive = (id) => {
|
||||
links.forEach(a => {
|
||||
const active = a.getAttribute("href") === `#${id}`;
|
||||
a.classList.toggle("is-active", active);
|
||||
if (active) a.setAttribute("aria-current", "true");
|
||||
else a.removeAttribute("aria-current");
|
||||
});
|
||||
};
|
||||
|
||||
// Calculate sticky header offset in px
|
||||
const headerOffsetPx = 6.5 * parseFloat(getComputedStyle(document.documentElement).fontSize);
|
||||
|
||||
// Track visible headings (id -> distance from top)
|
||||
const visible = new Map();
|
||||
|
||||
const observer = new IntersectionObserver((entries) => {
|
||||
entries.forEach(entry => {
|
||||
const id = entry.target.id;
|
||||
if (entry.isIntersecting) {
|
||||
// How far from the top (after header offset)
|
||||
const dist = entry.target.getBoundingClientRect().top - headerOffsetPx;
|
||||
visible.set(id, dist);
|
||||
} else {
|
||||
visible.delete(id);
|
||||
}
|
||||
});
|
||||
|
||||
if (visible.size) {
|
||||
// Choose the heading closest to the top (>= -headerOffset)
|
||||
const topMost = [...visible.entries()]
|
||||
.sort((a,b) => Math.abs(a[1]) - Math.abs(b[1]))[0][0];
|
||||
setActive(topMost);
|
||||
// console.log("Active:", topMost, visible);
|
||||
}
|
||||
}, {
|
||||
root: null, // track relative to viewport
|
||||
rootMargin: `-${headerOffsetPx}px 0px -70% 0px`,
|
||||
threshold: [0, 0.01, 0.1] // fire as soon as it enters
|
||||
});
|
||||
|
||||
headings.forEach(h => observer.observe(h));
|
||||
|
||||
// Initial highlight (in case load mid‑page)
|
||||
let bestId = null, bestDist = Infinity;
|
||||
headings.forEach(h => {
|
||||
const top = h.getBoundingClientRect().top - headerOffsetPx;
|
||||
const dist = top < 0 ? Math.abs(top) : top + 1e6;
|
||||
if (dist < bestDist) { bestDist = dist; bestId = h.id; }
|
||||
});
|
||||
if (bestId) setActive(bestId);
|
||||
|
||||
// smooth-scroll ToC clicks
|
||||
toc.addEventListener("click", (e) => {
|
||||
const a = e.target.closest('a[href^="#"]');
|
||||
if (!a) return;
|
||||
const id = decodeURIComponent(a.hash.slice(1));
|
||||
const el = document.getElementById(id);
|
||||
if (!el) return;
|
||||
e.preventDefault();
|
||||
el.scrollIntoView({ behavior: "smooth", block: "start" });
|
||||
el.setAttribute("tabindex", "-1");
|
||||
el.focus({ preventScroll: true });
|
||||
history.pushState(null, "", `#${id}`);
|
||||
});
|
||||
});
|
||||
1
assets/scripts/vendor/bigger-picture.min.js
vendored
Normal file
1
assets/scripts/vendor/bigger-picture.min.js
vendored
Normal file
File diff suppressed because one or more lines are too long
3475
assets/scripts/vendor/lunr.js
vendored
Normal file
3475
assets/scripts/vendor/lunr.js
vendored
Normal file
File diff suppressed because it is too large
Load Diff
2811
assets/scripts/vendor/mermaid.min.js
vendored
Normal file
2811
assets/scripts/vendor/mermaid.min.js
vendored
Normal file
File diff suppressed because one or more lines are too long
27
assets/scripts/vendor/svg-pan-zoom.min.js
vendored
Normal file
27
assets/scripts/vendor/svg-pan-zoom.min.js
vendored
Normal file
File diff suppressed because one or more lines are too long
File diff suppressed because it is too large
Load Diff
@@ -1,313 +1,7 @@
|
||||
/* Home dashboard behaviour. All selectors are db-* scoped. */
|
||||
|
||||
(function () {
|
||||
"use strict";
|
||||
|
||||
function updateGreeting() {
|
||||
const el = document.getElementById("db-greeting");
|
||||
if (!el) return;
|
||||
|
||||
const hour = new Date().getHours();
|
||||
if (hour < 5) el.textContent = "Late session";
|
||||
else if (hour < 12) el.textContent = "Good morning";
|
||||
else if (hour < 17) el.textContent = "Good afternoon";
|
||||
else if (hour < 21) el.textContent = "Good evening";
|
||||
else el.textContent = "Evening review";
|
||||
}
|
||||
|
||||
function updateClock() {
|
||||
const el = document.getElementById("db-clock");
|
||||
if (!el) return;
|
||||
|
||||
el.textContent = new Intl.DateTimeFormat(undefined, {
|
||||
hour: "2-digit",
|
||||
minute: "2-digit",
|
||||
second: "2-digit",
|
||||
hour12: false,
|
||||
}).format(new Date());
|
||||
}
|
||||
|
||||
function getIsoWeek(date) {
|
||||
const d = new Date(Date.UTC(date.getFullYear(), date.getMonth(), date.getDate()));
|
||||
const dayNum = d.getUTCDay() || 7;
|
||||
d.setUTCDate(d.getUTCDate() + 4 - dayNum);
|
||||
const yearStart = new Date(Date.UTC(d.getUTCFullYear(), 0, 1));
|
||||
return Math.ceil(((d - yearStart) / 86400000 + 1) / 7);
|
||||
}
|
||||
|
||||
function updateStats() {
|
||||
const now = new Date();
|
||||
const year = now.getFullYear();
|
||||
const start = new Date(year, 0, 1);
|
||||
const nextYear = new Date(year + 1, 0, 1);
|
||||
const dayOfYear = Math.floor((now - start) / 86400000) + 1;
|
||||
const daysInYear = Math.round((nextYear - start) / 86400000);
|
||||
const daysLeft = Math.max(0, daysInYear - dayOfYear);
|
||||
const month = new Intl.DateTimeFormat(undefined, { month: "short" }).format(now);
|
||||
const pct = ((dayOfYear / daysInYear) * 100).toFixed(1);
|
||||
|
||||
setText("db-stat-day", dayOfYear);
|
||||
setText("db-stat-week", "W" + getIsoWeek(now));
|
||||
setText("db-stat-month", month);
|
||||
setText("db-stat-left", daysLeft);
|
||||
setText("db-year-pct", pct + "%");
|
||||
|
||||
const fill = document.getElementById("db-year-fill");
|
||||
if (fill) fill.style.width = pct + "%";
|
||||
}
|
||||
|
||||
function setText(id, value) {
|
||||
const el = document.getElementById(id);
|
||||
if (el) el.textContent = value;
|
||||
}
|
||||
|
||||
function escHtml(str) {
|
||||
return String(str)
|
||||
.replace(/&/g, "&")
|
||||
.replace(/</g, "<")
|
||||
.replace(/>/g, ">")
|
||||
.replace(/"/g, """);
|
||||
}
|
||||
|
||||
function escAttr(str) {
|
||||
return escHtml(str).replace(/'/g, "'");
|
||||
}
|
||||
|
||||
function normaliseHref(href, prefix) {
|
||||
if (!href || href.startsWith("http") || href.startsWith("#")) return null;
|
||||
if (href.startsWith("/")) return href;
|
||||
const base = (prefix || "").replace(/\/$/, "");
|
||||
if (!base || href.startsWith(base + "/")) return href;
|
||||
return base + "/" + href;
|
||||
}
|
||||
|
||||
function isTagLink(a) {
|
||||
const href = a.getAttribute("href") || "";
|
||||
return href.includes("/tags/") || Boolean(a.querySelector(".post-tag"));
|
||||
}
|
||||
|
||||
function extractLinks(doc, max, prefix) {
|
||||
const items = [];
|
||||
const seen = new Set();
|
||||
const links = doc.querySelectorAll("#content li a[href], .org-ul li a[href], ul li a[href]");
|
||||
|
||||
for (const a of links) {
|
||||
if (isTagLink(a)) continue;
|
||||
|
||||
const href = normaliseHref(a.getAttribute("href"), prefix);
|
||||
const title = a.textContent.trim();
|
||||
if (!href || !title || seen.has(href)) continue;
|
||||
|
||||
const li = a.closest("li");
|
||||
const dateMatch = li ? li.textContent.match(/\b\d{4}-\d{2}-\d{2}\b/) : null;
|
||||
seen.add(href);
|
||||
items.push({ href, title, date: dateMatch ? dateMatch[0] : null });
|
||||
if (items.length >= max) break;
|
||||
}
|
||||
|
||||
return items;
|
||||
}
|
||||
|
||||
function renderFeed(ulId, items) {
|
||||
const ul = document.getElementById(ulId);
|
||||
if (!ul || !items.length) return;
|
||||
|
||||
ul.innerHTML = items
|
||||
.map(({ href, title, date }) => (
|
||||
`<li class="db-feed__item">` +
|
||||
`<span class="db-feed__dot"></span>` +
|
||||
`<a href="${escHtml(href)}">${escHtml(title)}</a>` +
|
||||
(date ? `<span class="db-feed__meta">${escHtml(date)}</span>` : "") +
|
||||
`</li>`
|
||||
))
|
||||
.join("");
|
||||
}
|
||||
|
||||
async function loadFeed(listUrl, ulId, max, prefix) {
|
||||
try {
|
||||
const resp = await fetch(listUrl, { credentials: "same-origin" });
|
||||
if (!resp.ok) return;
|
||||
|
||||
const html = await resp.text();
|
||||
const doc = new DOMParser().parseFromString(html, "text/html");
|
||||
renderFeed(ulId, extractLinks(doc, max, prefix));
|
||||
} catch (_) {
|
||||
/* Fallback links remain in the HTML. */
|
||||
}
|
||||
}
|
||||
|
||||
function commentSlug(comment) {
|
||||
return comment.pageSlug || comment.page_slug || "";
|
||||
}
|
||||
|
||||
function commentDate(comment) {
|
||||
return comment.created_at || comment.createdAt || "";
|
||||
}
|
||||
|
||||
function commentHref(page, comment) {
|
||||
if (!page?.url) return null;
|
||||
if (!comment.id) return page.url + "#comments";
|
||||
return page.url + "#comment-" + encodeURIComponent(comment.id);
|
||||
}
|
||||
|
||||
function formatCommentDate(value) {
|
||||
const date = new Date(value);
|
||||
if (Number.isNaN(date.getTime())) return "";
|
||||
|
||||
return new Intl.DateTimeFormat(undefined, {
|
||||
month: "short",
|
||||
day: "2-digit",
|
||||
hour: "2-digit",
|
||||
minute: "2-digit",
|
||||
}).format(date);
|
||||
}
|
||||
|
||||
function commentExcerpt(content) {
|
||||
const text = String(content || "").replace(/\s+/g, " ").trim();
|
||||
if (text.length <= 150) return text;
|
||||
return text.slice(0, 147).trimEnd() + "...";
|
||||
}
|
||||
|
||||
function renderRecentComments(comments, pageMap) {
|
||||
const ul = document.getElementById("db-feed-comments");
|
||||
if (!ul) return;
|
||||
|
||||
if (!comments.length) {
|
||||
ul.innerHTML = (
|
||||
`<li class="db-comment-feed__item">` +
|
||||
`<span class="db-feed__dot"></span>` +
|
||||
`<div class="db-comment-feed__body">` +
|
||||
`<span class="db-comment-feed__empty">No comments yet.</span>` +
|
||||
`</div>` +
|
||||
`</li>`
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
ul.innerHTML = comments.map((comment) => {
|
||||
const slug = commentSlug(comment);
|
||||
const page = pageMap.get(slug);
|
||||
const title = page?.title || slug || "Unknown page";
|
||||
const href = commentHref(page, comment);
|
||||
const author = comment.author || "Anonymous";
|
||||
const date = formatCommentDate(commentDate(comment));
|
||||
const pageLink = href
|
||||
? `<a class="db-comment-feed__page" href="${escAttr(href)}">${escHtml(title)}</a>`
|
||||
: `<span class="db-comment-feed__page">${escHtml(title)}</span>`;
|
||||
|
||||
return (
|
||||
`<li class="db-comment-feed__item">` +
|
||||
`<span class="db-feed__dot"></span>` +
|
||||
`<div class="db-comment-feed__body">` +
|
||||
`<div class="db-comment-feed__top">` +
|
||||
`<strong>${escHtml(author)}</strong>` +
|
||||
`<span>on</span>` +
|
||||
pageLink +
|
||||
(date ? `<time datetime="${escAttr(commentDate(comment))}">${escHtml(date)}</time>` : "") +
|
||||
`</div>` +
|
||||
`<p>${escHtml(commentExcerpt(comment.content))}</p>` +
|
||||
`</div>` +
|
||||
`</li>`
|
||||
);
|
||||
}).join("");
|
||||
}
|
||||
|
||||
async function loadCommentPageMap() {
|
||||
try {
|
||||
const resp = await fetch("/assets/content/comment-pages.json", { credentials: "same-origin" });
|
||||
if (!resp.ok) return new Map();
|
||||
|
||||
const pages = await resp.json();
|
||||
return new Map(
|
||||
pages
|
||||
.filter((page) => page.slug && page.url)
|
||||
.map((page) => [page.slug, page])
|
||||
);
|
||||
} catch (_) {
|
||||
return new Map();
|
||||
}
|
||||
}
|
||||
|
||||
async function loadRecentComments() {
|
||||
const ul = document.getElementById("db-feed-comments");
|
||||
if (!ul) return;
|
||||
|
||||
const renderUnavailable = () => {
|
||||
ul.innerHTML = (
|
||||
`<li class="db-comment-feed__item">` +
|
||||
`<span class="db-feed__dot"></span>` +
|
||||
`<div class="db-comment-feed__body">` +
|
||||
`<span class="db-comment-feed__empty">Recent comments are unavailable.</span>` +
|
||||
`</div>` +
|
||||
`</li>`
|
||||
);
|
||||
};
|
||||
|
||||
try {
|
||||
const [pageMap, resp] = await Promise.all([
|
||||
loadCommentPageMap(),
|
||||
fetch("/api/comments", { credentials: "same-origin" }),
|
||||
]);
|
||||
if (!resp.ok) {
|
||||
renderUnavailable();
|
||||
return;
|
||||
}
|
||||
|
||||
const comments = await resp.json();
|
||||
const recent = comments
|
||||
.filter((comment) => commentDate(comment))
|
||||
.sort((a, b) => new Date(commentDate(b)) - new Date(commentDate(a)))
|
||||
.slice(0, 10);
|
||||
|
||||
renderRecentComments(recent, pageMap);
|
||||
} catch (_) {
|
||||
renderUnavailable();
|
||||
}
|
||||
}
|
||||
|
||||
function initCommandFilter() {
|
||||
const input = document.getElementById("db-command-search");
|
||||
const nav = document.getElementById("db-quicknav");
|
||||
if (!input || !nav) return;
|
||||
|
||||
const items = Array.from(nav.querySelectorAll(".db-qn-item"));
|
||||
const applyFilter = () => {
|
||||
const query = input.value.trim().toLowerCase();
|
||||
items.forEach((item) => {
|
||||
const haystack = [
|
||||
item.textContent,
|
||||
item.getAttribute("href"),
|
||||
item.dataset.keywords,
|
||||
].join(" ").toLowerCase();
|
||||
item.classList.toggle("is-hidden", Boolean(query && !haystack.includes(query)));
|
||||
});
|
||||
};
|
||||
|
||||
input.addEventListener("input", applyFilter);
|
||||
document.addEventListener("keydown", (event) => {
|
||||
if (event.key === "/" && !/^(input|textarea|select)$/i.test(event.target.tagName)) {
|
||||
event.preventDefault();
|
||||
input.focus();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function init() {
|
||||
updateGreeting();
|
||||
updateClock();
|
||||
updateStats();
|
||||
initCommandFilter();
|
||||
|
||||
setInterval(updateClock, 1000);
|
||||
loadFeed("/blogs/blogs-list.html", "db-feed-blogs", 6, "/blogs");
|
||||
loadFeed("/posts/posts-list.html", "db-feed-posts", 6, "/posts");
|
||||
loadFeed("/recently-updated.html", "db-feed-recent", 6, "");
|
||||
loadRecentComments();
|
||||
}
|
||||
|
||||
if (document.readyState === "loading") {
|
||||
document.addEventListener("DOMContentLoaded", init);
|
||||
} else {
|
||||
init();
|
||||
}
|
||||
})();
|
||||
var script = document.createElement("script");
|
||||
script.src = "/assets/scripts/pages/home-dashboard.js";
|
||||
script.defer = true;
|
||||
document.head.appendChild(script);
|
||||
}());
|
||||
|
||||
Reference in New Issue
Block a user