server and web app

This commit is contained in:
2026-05-31 23:08:53 -04:00
parent 438b3b29a2
commit b3364447a1
24 changed files with 2318 additions and 153 deletions

View File

@@ -1,4 +1,56 @@
(() => {
// Tab switching
document.querySelectorAll('.auth-tab-list').forEach(tabList => {
const tabs = tabList.querySelectorAll('[data-tab]');
const panels = tabList.closest('.auth-tabs').querySelectorAll('[data-tab-panel]');
tabs.forEach(tab => {
tab.addEventListener('click', () => {
const target = tab.dataset.tab;
tabs.forEach(t => {
t.classList.remove('is-active');
t.setAttribute('aria-selected', 'false');
});
tab.classList.add('is-active');
tab.setAttribute('aria-selected', 'true');
panels.forEach(p => {
if (p.dataset.tabPanel === target) {
p.classList.add('is-active');
p.hidden = false;
} else {
p.classList.remove('is-active');
p.hidden = true;
}
});
});
});
});
// Register toggle
const registerToggle = document.querySelector('[data-register-toggle]');
const registerPanel = document.querySelector('[data-register-panel]');
const loginSection = document.querySelector('[data-login-section]');
const registerCancel = document.querySelector('[data-register-cancel]');
if (registerToggle && registerPanel && loginSection) {
registerToggle.addEventListener('click', () => {
loginSection.hidden = true;
registerPanel.hidden = false;
});
}
if (registerCancel && registerPanel && loginSection) {
registerCancel.addEventListener('click', () => {
registerPanel.hidden = true;
loginSection.hidden = false;
// Clear any registration form status messages
document.querySelector('[data-passkey-register-status]').textContent = '';
document.querySelector('[data-register-status]').textContent = '';
});
}
const jsonHeaders = { "Content-Type": "application/json" };
const postJSON = async (url, body, options = {}) => {
@@ -95,35 +147,76 @@
}
});
const webAuthnErrorMessage = (error) => {
console.error("WebAuthn error:", error.name, error.message, error);
switch (error.name) {
case "NotAllowedError":
return "Passkey creation was cancelled or no authenticator is available. If you dismissed a prompt, try again. If no prompt appeared, your device may not support passkeys.";
case "NotSupportedError":
return "This browser or device does not support passkeys.";
case "SecurityError":
return "Passkeys require a secure context. Use https:// or localhost.";
case "InvalidStateError":
return "A passkey may already exist for this account.";
default:
return error.message || "Passkey failed. Check the console for details.";
}
};
const checkPasskeySupport = async () => {
if (!window.PublicKeyCredential) {
return { supported: false, reason: "Passkeys are not available in this browser." };
}
try {
if (PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable) {
const available = await PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable();
if (!available) {
return { supported: true, reason: "No platform authenticator found (e.g., Touch ID, Windows Hello). You can still use a security key if you have one." };
}
}
return { supported: true };
} catch {
return { supported: true };
}
};
document.querySelector("[data-passkey-register]")?.addEventListener("submit", async (event) => {
event.preventDefault();
if (!window.PublicKeyCredential) {
setStatus("[data-passkey-register-status]", "Passkeys are not available in this browser.", true);
const support = await checkPasskeySupport();
if (!support.supported) {
setStatus("[data-passkey-register-status]", support.reason, true);
return;
}
if (support.reason) {
console.warn("Passkey support:", support.reason);
}
try {
const begin = await postJSON("/api/auth/passkeys/register/begin", formJSON(event.currentTarget));
const credential = await navigator.credentials.create(normalizeCreateOptions(begin.options));
await postJSON(`/api/auth/passkeys/register/finish?challengeId=${encodeURIComponent(begin.challengeId)}`, credentialToJSON(credential));
setStatus("[data-passkey-register-status]", "Passkey created. Sign in with your passkey.");
} catch (error) {
setStatus("[data-passkey-register-status]", error.message, true);
setStatus("[data-passkey-register-status]", webAuthnErrorMessage(error), true);
}
});
document.querySelector("[data-passkey-login]")?.addEventListener("submit", async (event) => {
event.preventDefault();
if (!window.PublicKeyCredential) {
setStatus("[data-passkey-login-status]", "Passkeys are not available in this browser.", true);
const support = await checkPasskeySupport();
if (!support.supported) {
setStatus("[data-passkey-login-status]", support.reason, true);
return;
}
if (support.reason) {
console.warn("Passkey support:", support.reason);
}
try {
const begin = await postJSON("/api/auth/passkeys/login/begin", formJSON(event.currentTarget));
const credential = await navigator.credentials.get(normalizeRequestOptions(begin.options));
await postJSON(`/api/auth/passkeys/login/finish?challengeId=${encodeURIComponent(begin.challengeId)}`, credentialToJSON(credential));
window.location.href = authNext();
} catch (error) {
setStatus("[data-passkey-login-status]", error.message, true);
setStatus("[data-passkey-login-status]", webAuthnErrorMessage(error), true);
}
});

View File

@@ -0,0 +1,123 @@
(function () {
'use strict';
const documentPath = document.querySelector('[data-document-path]')?.dataset.documentPath;
const documentHash = document.querySelector('[data-document-hash]')?.dataset.documentHash;
const documentId = documentPath ? 'doc:' + documentPath.replace(/\.md$/, '') : null;
if (!documentId) return;
// Hash a paragraph's text content for anchoring
function hashParagraph(el) {
const text = (el.textContent || '').trim();
if (!text) return null;
// Simple hash: first 16 chars of base64 of char codes (deterministic)
let hash = 0;
for (let i = 0; i < text.length; i++) {
const char = text.charCodeAt(i);
hash = ((hash << 5) - hash) + char;
hash = hash & hash;
}
return 'h' + Math.abs(hash).toString(36);
}
function addCommentButton(el, hash) {
const btn = document.createElement('button');
btn.className = 'comment-anchor-btn';
btn.title = 'Add comment';
btn.innerHTML = '+';
btn.addEventListener('click', () => promptComment(el, hash));
el.appendChild(btn);
}
async function promptComment(el, anchorHash) {
const text = window.prompt('Comment on this paragraph:');
if (!text || !text.trim()) return;
try {
const res = await fetch('/api/comments', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
documentId,
versionHash: documentHash,
content: text.trim(),
anchorHash,
}),
});
if (!res.ok) throw new Error(await res.text());
// Refresh comments display
await loadCommentsForAnchor(el, anchorHash);
} catch (err) {
window.alert('Failed to post comment: ' + err.message);
}
}
async function loadCommentsForAnchor(el, anchorHash) {
try {
const res = await fetch(`/api/comments?document_id=${encodeURIComponent(documentId)}&anchor_hash=${encodeURIComponent(anchorHash)}`);
if (!res.ok) return;
const data = await res.json();
renderComments(el, data.comments || []);
} catch (err) {
console.error('load comments', err);
}
}
function renderComments(el, comments) {
// Remove existing comment list
const existing = el.querySelector('.comment-list');
if (existing) existing.remove();
if (!comments.length) return;
const list = document.createElement('div');
list.className = 'comment-list';
comments.forEach(c => {
const item = document.createElement('div');
item.className = 'comment-item';
item.innerHTML = `
<div class="comment-meta">
<strong>${escapeHtml(c.authorName || 'Anonymous')}</strong>
<time>${formatDate(c.createdAt)}</time>
</div>
<div class="comment-body">${escapeHtml(c.content)}</div>
`;
list.appendChild(item);
});
el.appendChild(list);
}
function escapeHtml(str) {
const div = document.createElement('div');
div.textContent = str;
return div.innerHTML;
}
function formatDate(iso) {
const d = new Date(iso);
return d.toLocaleString();
}
// Initialize: hash all paragraphs in markdown body
function init() {
const body = document.querySelector('.markdown-body');
if (!body) return;
const paragraphs = body.querySelectorAll('p, h1, h2, h3, h4, h5, h6, li, blockquote, pre');
paragraphs.forEach(el => {
const hash = hashParagraph(el);
if (!hash) return;
el.dataset.anchorHash = hash;
el.classList.add('commentable');
addCommentButton(el, hash);
loadCommentsForAnchor(el, hash);
});
}
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', init);
} else {
init();
}
})();

View File

@@ -0,0 +1,123 @@
(function () {
'use strict';
const bell = document.querySelector('[data-notification-bell]');
if (!bell) return;
const countEl = bell.querySelector('[data-unread-count]');
const dropdown = bell.querySelector('[data-notification-dropdown]');
let isOpen = false;
bell.addEventListener('click', () => {
isOpen = !isOpen;
dropdown.hidden = !isOpen;
if (isOpen) loadNotifications();
});
document.addEventListener('click', (e) => {
if (!bell.contains(e.target)) {
isOpen = false;
dropdown.hidden = true;
}
});
async function updateBell() {
try {
const res = await fetch('/api/notifications/bell');
if (!res.ok) return;
const data = await res.json();
const count = data.unreadCount || 0;
countEl.textContent = count > 99 ? '99+' : String(count);
countEl.hidden = count === 0;
bell.classList.toggle('has-unread', count > 0);
} catch (err) {
console.error('bell update', err);
}
}
async function loadNotifications() {
try {
const res = await fetch('/api/notifications?limit=20');
if (!res.ok) return;
const data = await res.json();
renderNotifications(data.notifications || []);
} catch (err) {
console.error('load notifications', err);
}
}
function renderNotifications(notifications) {
const list = dropdown.querySelector('ul');
if (!list) return;
list.innerHTML = '';
if (!notifications.length) {
list.innerHTML = '<li class="notification-empty">No notifications</li>';
return;
}
notifications.forEach(n => {
const li = document.createElement('li');
li.className = n.readAt ? 'notification-item is-read' : 'notification-item';
li.innerHTML = `
<div class="notification-message">${escapeHtml(n.message)}</div>
<time class="notification-time">${formatDate(n.createdAt)}</time>
`;
if (!n.readAt) {
li.addEventListener('click', () => markRead(n.id));
}
list.appendChild(li);
});
// Add "Mark all read" button
const footer = document.createElement('li');
footer.className = 'notification-footer';
const btn = document.createElement('button');
btn.textContent = 'Mark all read';
btn.addEventListener('click', markAllRead);
footer.appendChild(btn);
list.appendChild(footer);
}
async function markRead(id) {
try {
await fetch(`/api/notifications/${id}/read`, { method: 'POST' });
updateBell();
loadNotifications();
} catch (err) {
console.error('mark read', err);
}
}
async function markAllRead() {
try {
await fetch('/api/notifications/read-all', { method: 'POST' });
updateBell();
loadNotifications();
} catch (err) {
console.error('mark all read', err);
}
}
function escapeHtml(str) {
const div = document.createElement('div');
div.textContent = str;
return div.innerHTML;
}
function formatDate(iso) {
const d = new Date(iso);
return d.toLocaleString();
}
// Listen for WebSocket notification events
if (window.__cairnquireRealtime) {
window.__cairnquireRealtime.on('notification', () => {
updateBell();
});
}
// Poll every 60s as fallback
setInterval(updateBell, 60000);
updateBell();
})();

View File

@@ -1,4 +1,23 @@
(function () {
const realtimeCallbacks = {
notification: [],
};
window.__cairnquireRealtime = {
on: function (event, cb) {
if (realtimeCallbacks[event]) {
realtimeCallbacks[event].push(cb);
}
},
off: function (event, cb) {
if (realtimeCallbacks[event]) {
realtimeCallbacks[event] = realtimeCallbacks[event].filter(function (c) {
return c !== cb;
});
}
},
};
const notice = document.querySelector("[data-version-notice]");
const reload = document.querySelector("[data-version-reload]");
const offlineNotice = document.querySelector("[data-offline-notice]");
@@ -300,6 +319,13 @@
return;
}
if (payload.type === "notification") {
realtimeCallbacks.notification.forEach(function (cb) {
cb(payload.data);
});
return;
}
if (payload.type !== "document_version" || !payload.data) {
return;
}

View File

@@ -106,45 +106,61 @@ code {
.site-nav {
display: flex;
gap: 1.25rem;
gap: 0.5rem;
}
.site-nav a {
display: inline-flex;
align-items: center;
justify-content: center;
width: 36px;
height: 36px;
border-radius: 50%;
color: inherit;
text-decoration: none;
font-size: 0.95rem;
transition: background 0.15s;
}
.site-nav a:hover {
background: rgba(0, 0, 0, 0.06);
}
.site-nav a svg {
display: block;
}
.site-search {
position: relative;
display: flex;
align-items: center;
gap: 0.5rem;
flex: 1;
max-width: 320px;
margin: 0 1rem;
}
.site-search__icon {
position: absolute;
left: 0.6rem;
z-index: 1;
color: var(--muted);
pointer-events: none;
}
.site-search input {
width: 100%;
padding: 0.45rem 0.75rem;
padding: 0.4rem 0.75rem 0.4rem 2rem;
border: 1px solid var(--border);
border-radius: 0;
background: var(--panel-strong);
border-radius: 999px;
background: rgba(255, 255, 255, 0.6);
font: inherit;
font-size: 0.9rem;
font-size: 0.825rem;
transition: border-color 0.15s, background 0.15s;
}
.site-search input:focus {
outline: 2px solid var(--accent-soft);
outline: none;
border-color: var(--accent);
}
.site-search button {
padding: 0.45rem 0.6rem;
border: 1px solid var(--border);
border-radius: var(--radius-sm);
background: var(--panel-strong);
cursor: pointer;
font-size: 0.9rem;
}
.site-main {
@@ -250,11 +266,30 @@ code {
cursor: pointer;
}
.btn-primary,
.auth-form button[type="submit"],
.account-header button {
border-color: color-mix(in srgb, var(--accent) 50%, var(--border));
background: var(--accent);
color: white;
padding: 0.85rem 1.75rem;
min-height: 3rem;
font-size: 1.05rem;
font-weight: 600;
box-shadow: 0 4px 12px color-mix(in srgb, var(--accent) 30%, transparent);
transition: background 0.15s ease, box-shadow 0.15s ease, transform 0.1s ease;
}
.btn-primary:hover,
.auth-form button[type="submit"]:hover {
background: color-mix(in srgb, var(--accent) 85%, black);
box-shadow: 0 6px 16px color-mix(in srgb, var(--accent) 40%, transparent);
}
.btn-primary:active,
.auth-form button[type="submit"]:active {
transform: translateY(1px);
box-shadow: 0 2px 6px color-mix(in srgb, var(--accent) 30%, transparent);
}
.auth-details {
@@ -289,6 +324,123 @@ code {
color: var(--muted);
}
/* Auth tabs */
.auth-tabs {
margin-bottom: 1.5rem;
}
.auth-tab-list {
display: flex;
gap: 0;
border-bottom: 1px solid var(--border);
margin-bottom: 1rem;
}
.auth-tab {
padding: 0.5rem 1rem;
border: 0;
border-bottom: 2px solid transparent;
background: transparent;
color: var(--muted);
font: inherit;
font-size: 0.9rem;
cursor: pointer;
transition: color 0.15s ease, border-color 0.15s ease;
}
.auth-tab:hover {
color: var(--text);
}
.auth-tab.is-active {
color: var(--accent);
border-bottom-color: var(--accent);
font-weight: 600;
}
.auth-tab-panel {
display: none;
}
.auth-tab-panel.is-active {
display: block;
}
/* Register CTA */
.auth-register-cta {
margin-top: 1.5rem;
padding-top: 1.5rem;
border-top: 1px solid var(--border);
text-align: center;
}
.btn-cta {
display: inline-flex;
align-items: center;
justify-content: center;
gap: 0.5rem;
width: 100%;
padding: 1rem 2rem;
min-height: 3.5rem;
border: 2px solid var(--accent);
border-radius: var(--radius-sm);
background: var(--accent);
color: white;
font: inherit;
font-size: 1.15rem;
font-weight: 700;
letter-spacing: 0.01em;
cursor: pointer;
box-shadow: 0 6px 20px color-mix(in srgb, var(--accent) 35%, transparent);
transition: background 0.15s ease, box-shadow 0.15s ease, transform 0.1s ease;
}
.btn-cta:hover {
background: color-mix(in srgb, var(--accent) 85%, black);
box-shadow: 0 8px 24px color-mix(in srgb, var(--accent) 45%, transparent);
}
.btn-cta:active {
transform: translateY(2px);
box-shadow: 0 3px 10px color-mix(in srgb, var(--accent) 35%, transparent);
}
.auth-register-panel {
padding: 0;
border: none;
background: transparent;
}
.auth-register-cancel {
margin-top: 1.5rem;
padding-top: 1.5rem;
border-top: 1px solid var(--border);
text-align: center;
}
.btn-secondary {
display: inline-flex;
align-items: center;
justify-content: center;
gap: 0.5rem;
padding: 0.65rem 1.25rem;
min-height: 2.6rem;
border: 1px solid var(--border);
border-radius: var(--radius-sm);
background: transparent;
color: var(--muted);
font: inherit;
font-size: 0.95rem;
cursor: pointer;
transition: color 0.15s ease, border-color 0.15s ease, background 0.15s ease;
}
.btn-secondary:hover {
color: var(--text);
border-color: var(--muted);
background: var(--panel);
}
.account-header {
display: flex;
align-items: center;
@@ -1595,3 +1747,74 @@ code {
background: oklch(0.705 0.165 55 / 0.07);
}
}
/* Comments */
.commentable {
position: relative;
}
.commentable:hover {
background: var(--accent-soft);
}
.comment-anchor-btn {
position: absolute;
right: -1.5rem;
top: 0.25rem;
width: 1.2rem;
height: 1.2rem;
display: flex;
align-items: center;
justify-content: center;
padding: 0;
border: 1px solid var(--border);
border-radius: 50%;
background: var(--panel-strong);
color: var(--accent);
font-size: 0.8rem;
font-weight: 700;
cursor: pointer;
opacity: 0;
transition: opacity 0.15s ease;
}
.commentable:hover .comment-anchor-btn {
opacity: 1;
}
.comment-list {
margin-top: 0.5rem;
padding: 0.5rem;
border: 1px solid var(--border);
border-radius: var(--radius-sm);
background: var(--panel);
}
.comment-item {
padding: 0.5rem 0;
border-bottom: 1px solid var(--border);
}
.comment-item:last-child {
border-bottom: 0;
}
.comment-meta {
display: flex;
align-items: center;
gap: 0.5rem;
margin-bottom: 0.25rem;
font-size: 0.8rem;
color: var(--muted);
}
.comment-meta strong {
color: var(--text);
}
.comment-body {
font-size: 0.9rem;
line-height: 1.5;
}