3192 lines
190 KiB
HTML
3192 lines
190 KiB
HTML
<!DOCTYPE html>
|
||
<html lang="en">
|
||
<head>
|
||
<meta charset="UTF-8">
|
||
<meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover">
|
||
<title>BrainFeed</title>
|
||
<meta name="description" content="The private feed for your brain. Capture anything, find it again.">
|
||
<meta name="theme-color" content="#6042e8">
|
||
<meta name="apple-mobile-web-app-capable" content="yes">
|
||
<meta name="mobile-web-app-capable" content="yes">
|
||
<meta name="apple-mobile-web-app-status-bar-style" content="default">
|
||
<meta name="apple-mobile-web-app-title" content="BrainFeed">
|
||
<link rel="manifest" href="manifest.json">
|
||
<link rel="icon" type="image/png" sizes="32x32" href="favicon-32.png">
|
||
<link rel="apple-touch-icon" href="apple-touch-icon.png">
|
||
<style>
|
||
:root {
|
||
--bg: #f6f5fb;
|
||
--surface: #ffffff;
|
||
--surface-2: #efedf7;
|
||
--border: #e2dff0;
|
||
--text: #1c1a29;
|
||
--muted: #6d6a80;
|
||
--accent: #6042e8;
|
||
--accent-soft: #ece8ff;
|
||
--accent-text: #ffffff;
|
||
--danger: #d6384b;
|
||
--warn: #b86e00;
|
||
--ok: #1d8a5c;
|
||
--shadow: 0 1px 2px rgba(28, 26, 41, .06), 0 4px 16px rgba(28, 26, 41, .05);
|
||
--radius: 14px;
|
||
color-scheme: light;
|
||
}
|
||
@media (prefers-color-scheme: dark) {
|
||
:root:not([data-theme="light"]) {
|
||
--bg: #121118; --surface: #1c1b25; --surface-2: #262433; --border: #33304a;
|
||
--text: #ecebf5; --muted: #9a97b0; --accent: #8e76ff; --accent-soft: #2b2550;
|
||
--accent-text: #120f26; --danger: #ff6b7c; --warn: #f0a640; --ok: #4fcf94;
|
||
--shadow: 0 1px 2px rgba(0,0,0,.3), 0 4px 16px rgba(0,0,0,.25);
|
||
color-scheme: dark;
|
||
}
|
||
}
|
||
:root[data-theme="dark"] {
|
||
--bg: #121118; --surface: #1c1b25; --surface-2: #262433; --border: #33304a;
|
||
--text: #ecebf5; --muted: #9a97b0; --accent: #8e76ff; --accent-soft: #2b2550;
|
||
--accent-text: #120f26; --danger: #ff6b7c; --warn: #f0a640; --ok: #4fcf94;
|
||
--shadow: 0 1px 2px rgba(0,0,0,.3), 0 4px 16px rgba(0,0,0,.25);
|
||
color-scheme: dark;
|
||
}
|
||
* { box-sizing: border-box; }
|
||
html, body { margin: 0; }
|
||
body {
|
||
background: var(--bg); color: var(--text);
|
||
font: 15px/1.5 -apple-system, BlinkMacSystemFont, "SF Pro Text", "Segoe UI", Roboto, sans-serif;
|
||
-webkit-font-smoothing: antialiased;
|
||
overflow-x: hidden;
|
||
}
|
||
button, input, textarea, select { font: inherit; color: inherit; }
|
||
button { cursor: pointer; }
|
||
a { color: var(--accent); }
|
||
.hidden { display: none !important; }
|
||
|
||
/* ---------- Review mode ---------- */
|
||
.review .scopes { display: grid; gap: 8px; margin-top: 12px; }
|
||
.review .scopes button { display: flex; align-items: center; gap: 10px; text-align: left; border: 1px solid var(--border); background: var(--surface); color: var(--text); border-radius: 12px; padding: 12px 14px; font: inherit; cursor: pointer; }
|
||
.review .scopes button:hover { border-color: var(--accent); }
|
||
.review .scopes button:disabled { opacity: .5; cursor: default; border-color: var(--border); }
|
||
.review .scopes .n { margin-left: auto; color: var(--muted); font-size: 13px; }
|
||
.review-progress { height: 4px; border-radius: 4px; background: var(--surface-2); overflow: hidden; margin: 10px 0 14px; }
|
||
.review-progress span { display: block; height: 100%; background: var(--accent); transition: width .2s; }
|
||
.review-card { border: 1px solid var(--border); border-radius: 14px; padding: 16px; background: var(--surface); min-height: 140px; max-height: 46vh; overflow-y: auto; touch-action: pan-y; transition: transform .18s, opacity .18s; user-select: none; }
|
||
.review-card .note-body { pointer-events: none; }
|
||
.review-card.gone-left { transform: translateX(-110%) rotate(-6deg); opacity: 0; }
|
||
.review-card.gone-right { transform: translateX(110%) rotate(6deg); opacity: 0; }
|
||
.review-meta { font-size: 12px; color: var(--muted); margin-top: 10px; display: flex; gap: 8px; flex-wrap: wrap; }
|
||
.review-actions { display: grid; grid-template-columns: repeat(4, 1fr); gap: 8px; margin-top: 14px; }
|
||
.review-actions button { display: grid; justify-items: center; gap: 2px; border: 1px solid var(--border); background: var(--surface); color: var(--text); border-radius: 12px; padding: 10px 4px; font: inherit; font-size: 13px; cursor: pointer; }
|
||
.review-actions button:hover { background: var(--surface-2); }
|
||
.review-actions button.primary { background: var(--accent); border-color: var(--accent); color: var(--accent-text); }
|
||
.review-actions kbd { font: 11px ui-monospace, monospace; color: inherit; opacity: .6; }
|
||
.review-when { display: flex; gap: 6px; flex-wrap: wrap; margin-top: 10px; }
|
||
.review-foot { display: flex; align-items: center; gap: 8px; margin-top: 12px; font-size: 12px; color: var(--muted); }
|
||
.review-foot .spacer { flex: 1; }
|
||
.review-swipe { display: none; }
|
||
@media (hover: none) { .review-actions kbd, .review-keys { display: none; } .review-swipe { display: inline; } }
|
||
|
||
/* ---------- Tag suggestions ---------- */
|
||
.tag-ac { position: fixed; z-index: 45; min-width: 180px; max-width: min(300px, calc(100vw - 32px)); background: var(--surface); border: 1px solid var(--border); border-radius: 10px; box-shadow: var(--shadow); padding: 4px; }
|
||
.tag-ac button { display: flex; width: 100%; align-items: center; gap: 8px; border: 0; background: none; color: var(--text); font: inherit; font-size: 14px; text-align: left; padding: 7px 10px; border-radius: 7px; cursor: pointer; }
|
||
.tag-ac button.on { background: var(--accent-soft); }
|
||
.tag-ac .t { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||
.tag-ac button b { color: var(--accent); font-weight: 600; }
|
||
.tag-ac .n { margin-left: auto; color: var(--muted); font-size: 12px; }
|
||
|
||
/* ---------- Seasonal themes ---------- */
|
||
header::after { content: ''; position: absolute; left: 0; right: 0; bottom: -1px; height: 3px; background: var(--season-stripe, none); pointer-events: none; }
|
||
#season-emoji { font-size: 15px; margin-left: 2px; }
|
||
#season-fx { position: fixed; inset: 0; pointer-events: none; z-index: 15; overflow: hidden; }
|
||
#season-fx span { position: absolute; top: -32px; animation: bf-fall linear infinite; will-change: transform; }
|
||
@keyframes bf-fall { to { transform: translate(40px, 110vh) rotate(300deg); } }
|
||
@media (prefers-reduced-motion: reduce) { #season-fx { display: none; } }
|
||
|
||
/* ---------- Auth ---------- */
|
||
#auth {
|
||
min-height: 100vh; display: flex; align-items: center; justify-content: center; padding: 24px 16px;
|
||
}
|
||
.auth-card {
|
||
width: 100%; max-width: 380px; background: var(--surface); border: 1px solid var(--border);
|
||
border-radius: 20px; padding: 32px 24px; box-shadow: var(--shadow); text-align: center;
|
||
}
|
||
.auth-card img { width: 64px; height: 64px; border-radius: 16px; }
|
||
.auth-card h1 { margin: 12px 0 4px; font-size: 24px; }
|
||
.auth-card p { margin: 0 0 20px; color: var(--muted); }
|
||
.auth-card form { display: grid; gap: 10px; text-align: left; }
|
||
.field {
|
||
width: 100%; padding: 11px 13px; border-radius: 10px; border: 1px solid var(--border);
|
||
background: var(--surface-2); outline: none;
|
||
}
|
||
.field:focus { border-color: var(--accent); }
|
||
.btn {
|
||
border: 0; border-radius: 10px; padding: 10px 16px; font-weight: 600;
|
||
background: var(--accent); color: var(--accent-text);
|
||
}
|
||
.btn:disabled { opacity: .5; cursor: default; }
|
||
.btn.ghost { background: transparent; color: var(--accent); }
|
||
.btn.small { padding: 6px 12px; font-size: 13px; }
|
||
.auth-msg { min-height: 20px; font-size: 13px; color: var(--danger); margin-top: 4px; }
|
||
.auth-msg.ok { color: var(--ok); }
|
||
|
||
/* ---------- Shell ---------- */
|
||
header {
|
||
position: sticky; top: 0; z-index: 20; background: color-mix(in srgb, var(--bg) 88%, transparent);
|
||
backdrop-filter: blur(12px); -webkit-backdrop-filter: blur(12px);
|
||
border-bottom: 1px solid var(--border);
|
||
padding: calc(env(safe-area-inset-top) + 10px) 16px 10px;
|
||
}
|
||
.header-row { display: flex; align-items: center; gap: 10px; max-width: 1180px; margin: 0 auto; }
|
||
.brand { display: flex; align-items: center; gap: 8px; font-weight: 700; font-size: 17px; flex-shrink: 0; }
|
||
.brand img { width: 28px; height: 28px; border-radius: 8px; }
|
||
.search { flex: 1; min-width: 0; position: relative; }
|
||
.search input { padding-left: 34px; }
|
||
.search svg { position: absolute; left: 11px; top: 50%; transform: translateY(-50%); color: var(--muted); }
|
||
.icon-btn {
|
||
width: 38px; height: 38px; border-radius: 10px; border: 1px solid var(--border); background: var(--surface);
|
||
display: inline-flex; align-items: center; justify-content: center; flex-shrink: 0; position: relative;
|
||
}
|
||
.icon-btn:hover { border-color: var(--accent); }
|
||
.tabs { display: flex; gap: 4px; max-width: 1180px; margin: 10px auto 0; }
|
||
.tab {
|
||
border: 0; background: transparent; padding: 6px 12px; border-radius: 999px; color: var(--muted); font-weight: 600;
|
||
display: inline-flex; align-items: center; gap: 6px;
|
||
}
|
||
.tab.active { background: var(--accent-soft); color: var(--accent); }
|
||
.badge {
|
||
background: var(--danger); color: #fff; font-size: 11px; font-weight: 700; border-radius: 999px;
|
||
min-width: 18px; height: 18px; padding: 0 5px; display: inline-flex; align-items: center; justify-content: center;
|
||
}
|
||
.menu {
|
||
position: absolute; right: 0; top: 44px; background: var(--surface); border: 1px solid var(--border);
|
||
border-radius: 12px; box-shadow: var(--shadow); padding: 6px; min-width: 210px; z-index: 30; text-align: left;
|
||
}
|
||
.menu button {
|
||
display: block; width: 100%; text-align: left; border: 0; background: transparent; padding: 9px 12px; border-radius: 8px;
|
||
}
|
||
.menu button:hover { background: var(--surface-2); }
|
||
.menu .who { padding: 8px 12px; font-size: 12px; color: var(--muted); border-bottom: 1px solid var(--border); margin-bottom: 4px; word-break: break-all; }
|
||
|
||
main { max-width: 1180px; margin: 0 auto; padding: 16px 16px 80px; display: grid; grid-template-columns: 220px minmax(0, 1fr); gap: 24px; }
|
||
main.wide { grid-template-columns: minmax(0, 1fr); }
|
||
@media (max-width: 820px) { main { grid-template-columns: minmax(0, 1fr); gap: 12px; } }
|
||
|
||
/* ---------- Tags sidebar ---------- */
|
||
aside { position: sticky; top: 120px; align-self: start; max-height: calc(100vh - 140px); overflow-y: auto; }
|
||
aside h3 { font-size: 12px; text-transform: uppercase; letter-spacing: .06em; color: var(--muted); margin: 0 0 8px 10px; }
|
||
.tag-list { display: flex; flex-direction: column; gap: 2px; }
|
||
.tag-item {
|
||
display: flex; justify-content: space-between; align-items: center; border: 0; background: transparent;
|
||
padding: 7px 10px; border-radius: 8px; text-align: left; color: var(--text);
|
||
}
|
||
.tag-item:hover { background: var(--surface-2); }
|
||
.tag-item.active { background: var(--accent-soft); color: var(--accent); font-weight: 600; }
|
||
.tag-item .n { color: var(--muted); font-size: 12px; }
|
||
@media (max-width: 820px) {
|
||
aside { position: static; max-height: none; overflow: visible; }
|
||
aside h3 { display: none; }
|
||
.tag-list { flex-direction: row; overflow-x: auto; gap: 6px; padding-bottom: 4px; scrollbar-width: none; }
|
||
.tag-list::-webkit-scrollbar { display: none; }
|
||
.tag-item { flex-shrink: 0; border: 1px solid var(--border); background: var(--surface); border-radius: 999px; padding: 5px 12px; gap: 6px; }
|
||
}
|
||
|
||
/* ---------- Composer ---------- */
|
||
.composer {
|
||
background: var(--surface); border: 1px solid var(--border); border-radius: var(--radius);
|
||
box-shadow: var(--shadow); padding: 12px; margin-bottom: 18px;
|
||
}
|
||
.composer:focus-within { border-color: var(--accent); }
|
||
.composer textarea {
|
||
width: 100%; border: 0; outline: none; resize: none; background: transparent; min-height: 44px; max-height: 320px;
|
||
padding: 4px 4px;
|
||
}
|
||
.composer-bar { display: flex; align-items: center; gap: 6px; margin-top: 6px; }
|
||
/* Phones: an empty, idle composer shrinks to one line; tapping it brings back the tools. */
|
||
@media (max-width: 820px) {
|
||
.composer.collapsed { padding: 6px 12px; box-shadow: none; }
|
||
.composer.collapsed textarea { min-height: 32px; height: 32px !important; padding-top: 6px; }
|
||
.composer.collapsed .composer-bar, .composer.collapsed .pending-files { display: none; }
|
||
}
|
||
.composer-bar .spacer { flex: 1; }
|
||
.composer-bar .hint { font-size: 12px; color: var(--muted); }
|
||
.tool {
|
||
border: 0; background: transparent; color: var(--muted); width: 34px; height: 34px; border-radius: 8px;
|
||
display: inline-flex; align-items: center; justify-content: center;
|
||
}
|
||
.tool:hover { background: var(--surface-2); color: var(--text); }
|
||
.tool.on { background: var(--accent-soft); color: var(--accent); }
|
||
#mic-btn.listening { background: var(--danger, #d33); color: #fff; animation: bf-pulse 1.2s ease-in-out infinite; }
|
||
@keyframes bf-pulse { 50% { box-shadow: 0 0 0 6px color-mix(in srgb, var(--danger, #d33) 25%, transparent); } }
|
||
@media (prefers-reduced-motion: reduce) { #mic-btn.listening { animation: none; } }
|
||
.remind-row { display: flex; flex-wrap: wrap; gap: 6px; align-items: center; padding: 8px 4px 2px; border-top: 1px dashed var(--border); margin-top: 8px; }
|
||
.remind-row .field { width: auto; padding: 6px 10px; font-size: 14px; }
|
||
.chip {
|
||
border: 1px solid var(--border); background: var(--surface-2); border-radius: 999px; padding: 4px 10px; font-size: 13px;
|
||
}
|
||
.chip:hover { border-color: var(--accent); }
|
||
.chip.on { background: var(--accent-soft); border-color: var(--accent); color: var(--accent); font-weight: 600; }
|
||
.pending-files { display: flex; flex-wrap: wrap; gap: 6px; margin-top: 8px; }
|
||
.pending-files .chip { display: inline-flex; align-items: center; gap: 4px; }
|
||
.pending-files .chip button { border: 0; background: none; padding: 0 2px; color: var(--muted); }
|
||
|
||
/* ---------- Feed ---------- */
|
||
.status-line { display: flex; align-items: center; gap: 8px; margin: -6px 0 14px; color: var(--muted); font-size: 13px; flex-wrap: wrap; }
|
||
.day { font-size: 12px; font-weight: 700; text-transform: uppercase; letter-spacing: .06em; color: var(--muted); margin: 18px 4px 8px; }
|
||
.day:first-child { margin-top: 0; }
|
||
.note {
|
||
background: var(--surface); border: 1px solid var(--border); border-radius: var(--radius); padding: 12px 14px 8px;
|
||
margin-bottom: 8px; position: relative;
|
||
}
|
||
.note.pinned { border-color: color-mix(in srgb, var(--accent) 45%, var(--border)); }
|
||
.note.queued { opacity: .65; border-style: dashed; }
|
||
.note-body { white-space: pre-wrap; word-wrap: break-word; overflow-wrap: anywhere; }
|
||
.note-body a { word-break: break-all; }
|
||
.hashtag {
|
||
border: 0; background: var(--accent-soft); color: var(--accent); border-radius: 6px; padding: 0 5px; font-weight: 600; font-size: .93em;
|
||
}
|
||
.note-meta { display: flex; align-items: center; gap: 8px; margin-top: 6px; font-size: 12px; color: var(--muted); }
|
||
.note-meta .spacer { flex: 1; }
|
||
.src { border: 1px solid var(--border); border-radius: 999px; padding: 0 7px; font-size: 11px; text-transform: lowercase; }
|
||
.note-actions { display: flex; gap: 2px; opacity: .45; transition: opacity .15s; }
|
||
.note-body.folded { max-height: 15.5em; overflow: hidden; -webkit-mask-image: linear-gradient(#000 70%, transparent); mask-image: linear-gradient(#000 70%, transparent); }
|
||
.more-btn { border: 0; background: none; color: var(--accent); font: inherit; font-size: 13px; font-weight: 600; padding: 4px 0; cursor: pointer; }
|
||
.note:hover .note-actions, .note:focus-within .note-actions { opacity: 1; }
|
||
@media (hover: none) { .note-actions { opacity: 1; } }
|
||
.note-actions .tool { width: 28px; height: 28px; }
|
||
.note-actions .tool.pin-on { color: var(--accent); }
|
||
.note-menu { position: absolute; right: 8px; top: calc(100% - 6px); z-index: 25; min-width: 200px; background: var(--surface); border: 1px solid var(--border); border-radius: 12px; box-shadow: var(--shadow); padding: 4px; }
|
||
.note-menu.up { top: auto; bottom: 34px; }
|
||
.note-menu button { display: flex; align-items: center; gap: 10px; width: 100%; border: 0; background: none; color: var(--text); font: inherit; font-size: 14px; text-align: left; padding: 8px 10px; border-radius: 8px; cursor: pointer; }
|
||
.note-menu button:hover, .note-menu button:focus-visible { background: var(--surface-2); outline: none; }
|
||
.note-menu button svg { color: var(--muted); flex-shrink: 0; }
|
||
.note-menu button.danger, .note-menu button.danger svg { color: var(--danger); }
|
||
.extra-tags { display: flex; gap: 4px; flex-wrap: wrap; margin-top: 6px; }
|
||
.attach { display: flex; gap: 6px; flex-wrap: wrap; margin-top: 8px; }
|
||
.attach img { width: 120px; height: 120px; object-fit: cover; border-radius: 10px; border: 1px solid var(--border); background: var(--surface-2); cursor: zoom-in; }
|
||
.attach a.file { display: inline-flex; align-items: center; gap: 6px; padding: 6px 10px; border-radius: 8px; background: var(--surface-2); text-decoration: none; color: var(--text); font-size: 13px; }
|
||
.edit-box textarea { width: 100%; min-height: 80px; resize: vertical; }
|
||
.edit-box .row { display: flex; gap: 6px; justify-content: flex-end; margin-top: 6px; }
|
||
.empty { text-align: center; color: var(--muted); padding: 48px 16px; }
|
||
.empty strong { display: block; color: var(--text); font-size: 17px; margin-bottom: 4px; }
|
||
.load-more { display: block; margin: 16px auto; }
|
||
|
||
/* ---------- Compact layout (menu → Layout: Compact) ---------- */
|
||
/* Each day's notes become one connected list with hairline dividers. */
|
||
.compact .day { margin: 12px 4px 5px; font-size: 11px; }
|
||
.compact .day:first-child { margin-top: 0; }
|
||
.compact .note { border-radius: 0; margin: 0; padding: 7px 12px 3px; font-size: 14.5px; line-height: 1.4; }
|
||
.compact .note + .note { border-top: 0; }
|
||
.compact .note-meta .src { display: none; }
|
||
.compact .note-meta > span:first-child { white-space: nowrap; }
|
||
.compact .day + .note, .compact #feed > .note:first-child { border-top-left-radius: 12px; border-top-right-radius: 12px; }
|
||
.compact .note:has(+ .day), .compact .note:has(+ .load-more), .compact .note:last-child { border-bottom-left-radius: 12px; border-bottom-right-radius: 12px; }
|
||
.compact .note.pinned { border-color: var(--border); background: color-mix(in srgb, var(--accent) 5%, var(--surface)); }
|
||
.compact .note-meta { margin-top: 1px; font-size: 11px; min-height: 22px; }
|
||
.compact .note-actions .tool { width: 22px; height: 22px; }
|
||
.compact .note-actions .tool svg { width: 14px; height: 14px; }
|
||
.compact .note-body.folded { max-height: 7.2em; }
|
||
.compact .note-body .h1 { font-size: 1.12em; margin: 0 0 2px; }
|
||
.compact .check-item { padding: 1px 0; gap: 7px; }
|
||
.compact .check-item input { width: 15px; height: 15px; }
|
||
.compact .add-item { padding: 2px 0 2px 22px; font-size: 13px; }
|
||
.compact .attach { margin-top: 5px; }
|
||
.compact .attach img { width: 64px; height: 64px; border-radius: 7px; }
|
||
.compact .extra-tags { margin-top: 3px; }
|
||
.compact .composer { margin-bottom: 12px; }
|
||
|
||
/* ---------- Checklists ---------- */
|
||
.checklist { margin: 4px 0 2px; white-space: normal; }
|
||
.check-item { display: flex; gap: 9px; align-items: flex-start; padding: 3px 0; cursor: pointer; }
|
||
.check-item input { width: 18px; height: 18px; margin: 2px 0 0; accent-color: var(--accent); flex-shrink: 0; cursor: pointer; }
|
||
.check-item span { white-space: pre-wrap; overflow-wrap: anywhere; }
|
||
.check-item.done span { text-decoration: line-through; color: var(--muted); }
|
||
.check-done { margin-top: 2px; }
|
||
.check-done summary { font-size: 12px; color: var(--muted); cursor: pointer; padding: 3px 0; list-style-position: inside; }
|
||
.add-item { width: 100%; border: 0; border-bottom: 1px dashed var(--border); background: transparent; outline: none; padding: 5px 0 4px 27px; font-size: 14px; color: var(--text); }
|
||
.add-item:focus { border-bottom-color: var(--accent); }
|
||
.progress { font-weight: 600; }
|
||
|
||
/* ---------- Headings, entries, nesting ---------- */
|
||
.note-body .h1 { font-size: 1.28em; font-weight: 700; line-height: 1.3; margin: 2px 0 4px; }
|
||
.note-body .h2 { font-size: 1.08em; font-weight: 700; margin: 8px 0 2px; }
|
||
.note-body .h3 { font-weight: 600; margin: 6px 0 2px; }
|
||
.note-body .stamp { font-size: 12px; font-weight: 600; color: var(--muted); border-top: 1px solid var(--border); margin: 10px 0 2px; padding-top: 6px; }
|
||
.note-body .stamp:first-child { border-top: 0; margin-top: 0; padding-top: 0; }
|
||
.append-box { margin-top: 8px; display: grid; gap: 6px; }
|
||
.append-box textarea { width: 100%; min-height: 56px; resize: vertical; }
|
||
.append-box .row { display: flex; gap: 6px; justify-content: flex-end; }
|
||
.kids-btn { border: 1px solid var(--border); background: var(--surface-2); border-radius: 999px; padding: 0 9px; font-size: 12px; font-weight: 600; color: var(--accent); }
|
||
.kids-btn:hover { border-color: var(--accent); }
|
||
.children { margin: 10px 0 2px; padding-left: 12px; border-left: 2px solid var(--accent-soft); display: grid; gap: 6px; }
|
||
.children .note { margin: 0; padding: 9px 12px 5px; font-size: 14px; background: var(--bg); }
|
||
.children .add-inside { font-size: 14px; padding: 7px 10px; }
|
||
.in-parent { border: 0; background: none; padding: 0; font-size: 12px; color: var(--accent); cursor: pointer; }
|
||
.picker-list { display: grid; gap: 6px; max-height: 50vh; overflow-y: auto; margin-top: 10px; }
|
||
.picker-list button { text-align: left; border: 1px solid var(--border); background: var(--surface); border-radius: 10px; padding: 9px 12px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||
.picker-list button:hover { border-color: var(--accent); }
|
||
|
||
/* ---------- Board ---------- */
|
||
.column.drop { outline: 2px solid var(--accent); outline-offset: -2px; background: var(--accent-soft); }
|
||
.column.archive-zone { background: transparent; border: 2px dashed var(--border); align-items: center; justify-content: center; color: var(--muted); text-align: center; font-size: 13px; gap: 6px; }
|
||
.column.archive-zone svg { width: 22px; height: 22px; }
|
||
.board.moving .column { cursor: pointer; }
|
||
.board.moving .column:hover { outline: 2px solid var(--accent); outline-offset: -2px; }
|
||
#view-board article.note[draggable="true"] { cursor: grab; }
|
||
.column .note-meta { flex-wrap: wrap; }
|
||
.column .note-meta > span:first-child { white-space: nowrap; }
|
||
.column .note-actions { display: none; }
|
||
.column .note:hover .note-actions, .column .note:focus-within .note-actions { display: flex; }
|
||
@media (hover: none) { .column .note-actions { display: flex; } }
|
||
#view-board article.note.dragging { opacity: .4; }
|
||
.board-head { display: flex; align-items: center; gap: 10px; margin-bottom: 12px; flex-wrap: wrap; }
|
||
.board-head h2 { margin: 0; font-size: 18px; }
|
||
.board-picker { background: var(--surface); border: 1px solid var(--border); border-radius: var(--radius); padding: 14px; margin-bottom: 14px; }
|
||
.board-picker p { margin: 0 0 10px; color: var(--muted); font-size: 14px; }
|
||
.board-picker .chips { display: flex; flex-wrap: wrap; gap: 6px; margin-bottom: 12px; }
|
||
.board { display: grid; grid-auto-flow: column; grid-auto-columns: minmax(260px, 1fr); gap: 12px; overflow-x: auto; padding-bottom: 8px; scroll-snap-type: x mandatory; }
|
||
.column { background: var(--surface-2); border-radius: var(--radius); padding: 10px; scroll-snap-align: start; min-height: 200px; display: flex; flex-direction: column; }
|
||
.column h4 { margin: 2px 4px 10px; display: flex; justify-content: space-between; font-size: 14px; }
|
||
.column h4 span { color: var(--muted); font-weight: 500; }
|
||
.column .quick { margin-bottom: 8px; font-size: 14px; padding: 8px 10px; background: var(--surface); }
|
||
.column .note { padding: 10px 12px 6px; font-size: 14px; }
|
||
.column-list { overflow-y: auto; max-height: 70vh; }
|
||
@media (max-width: 820px) { .board { grid-auto-columns: 82%; } }
|
||
|
||
/* ---------- Reminders ---------- */
|
||
.rem-section h3 { font-size: 12px; text-transform: uppercase; letter-spacing: .06em; color: var(--muted); margin: 20px 4px 8px; }
|
||
.rem { display: flex; gap: 12px; align-items: flex-start; background: var(--surface); border: 1px solid var(--border); border-radius: var(--radius); padding: 12px 14px; margin-bottom: 8px; }
|
||
.rem.overdue { border-color: color-mix(in srgb, var(--danger) 50%, var(--border)); }
|
||
.rem.done .rem-text { text-decoration: line-through; color: var(--muted); }
|
||
.rem-check {
|
||
width: 22px; height: 22px; border-radius: 50%; border: 2px solid var(--border); background: transparent; flex-shrink: 0; margin-top: 1px;
|
||
display: inline-flex; align-items: center; justify-content: center; padding: 0;
|
||
}
|
||
.rem-check:hover { border-color: var(--ok); }
|
||
.rem.done .rem-check { background: var(--ok); border-color: var(--ok); color: #fff; }
|
||
.rem-main { flex: 1; min-width: 0; }
|
||
.rem-text { overflow-wrap: anywhere; }
|
||
.rem-when { font-size: 13px; color: var(--muted); margin-top: 2px; display: flex; gap: 8px; flex-wrap: wrap; align-items: center; }
|
||
.rem.overdue .rem-when .due { color: var(--danger); font-weight: 600; }
|
||
.rem.projected { background: transparent; border-style: dashed; }
|
||
.rem.projected .rem-text { color: var(--muted); }
|
||
.rem-edit { display: grid; gap: 6px; width: 100%; }
|
||
.rem-edit .row { display: flex; gap: 6px; flex-wrap: wrap; }
|
||
.rem-edit .field { padding: 7px 10px; font-size: 14px; }
|
||
.rem-edit .row .field { width: auto; flex: 1; min-width: 150px; }
|
||
|
||
/* ---------- Date picker (specific-dates reminders) ---------- */
|
||
.dp { width: 100%; max-width: 330px; }
|
||
.dp-head { display: flex; align-items: center; gap: 6px; margin: 4px 0; font-weight: 600; font-size: 14px; }
|
||
.dp-head span { flex: 1; text-align: center; }
|
||
.dp-head button { border: 1px solid var(--border); background: var(--surface); border-radius: 8px; width: 28px; height: 28px; }
|
||
.dp-grid { display: grid; grid-template-columns: repeat(7, 1fr); gap: 3px; }
|
||
.dp-grid .dow { font-size: 10px; color: var(--muted); text-align: center; font-weight: 700; }
|
||
.dp-grid button { border: 1px solid transparent; background: var(--surface-2); border-radius: 8px; height: 32px; font-size: 13px; }
|
||
.dp-grid button.on { background: var(--accent); color: var(--accent-text); font-weight: 700; }
|
||
.dp-grid button.past { opacity: .4; }
|
||
.dp-grid button.blank { visibility: hidden; }
|
||
.dp-foot { display: flex; gap: 8px; align-items: center; margin-top: 6px; font-size: 13px; color: var(--muted); flex-wrap: wrap; }
|
||
.dp-foot input { width: auto; padding: 5px 8px; }
|
||
|
||
/* ---------- Calendar ---------- */
|
||
.cal-wrap { display: grid; grid-template-columns: minmax(0, 1.35fr) minmax(0, 1fr); gap: 22px; align-items: start; }
|
||
@media (max-width: 820px) { .cal-wrap { grid-template-columns: minmax(0, 1fr); gap: 14px; } }
|
||
.cal-head { display: flex; align-items: center; gap: 6px; margin-bottom: 10px; }
|
||
.cal-head h2 { margin: 0 6px; font-size: 18px; flex: 1; }
|
||
.cal-head .icon-btn { width: 34px; height: 34px; }
|
||
.cal-grid { display: grid; grid-template-columns: repeat(7, minmax(0, 1fr)); gap: 4px; }
|
||
.cal-dow { font-size: 11px; font-weight: 700; color: var(--muted); text-align: center; text-transform: uppercase; letter-spacing: .05em; padding-bottom: 2px; }
|
||
.cal-day { border: 1px solid var(--border); background: var(--surface); border-radius: 10px; min-height: 74px; padding: 5px 6px; text-align: left; display: flex; flex-direction: column; gap: 3px; cursor: pointer; }
|
||
.cal-day:hover { border-color: var(--accent); }
|
||
.cal-day.other { opacity: .45; }
|
||
.cal-day.today .num { background: var(--accent); color: var(--accent-text); }
|
||
.cal-day.selected { border-color: var(--accent); box-shadow: 0 0 0 2px var(--accent-soft); }
|
||
.cal-day .num { font-size: 13px; font-weight: 600; width: 24px; height: 24px; border-radius: 50%; display: inline-flex; align-items: center; justify-content: center; }
|
||
.cal-dots { display: flex; flex-wrap: wrap; gap: 3px; }
|
||
.cal-dot { font-size: 10px; font-weight: 700; border-radius: 999px; padding: 0 6px; line-height: 16px; }
|
||
.cal-dot.r { background: var(--accent-soft); color: var(--accent); }
|
||
.cal-dot.r.over { background: color-mix(in srgb, var(--danger) 18%, transparent); color: var(--danger); }
|
||
.cal-dot.r.done { background: var(--surface-2); color: var(--muted); }
|
||
.cal-dot.n { background: var(--surface-2); color: var(--muted); }
|
||
@media (max-width: 820px) {
|
||
.cal-day { min-height: 50px; padding: 3px; align-items: center; }
|
||
.cal-day .num { font-size: 12px; width: 22px; height: 22px; }
|
||
.cal-dot { padding: 0 4px; font-size: 9px; line-height: 14px; }
|
||
}
|
||
.cal-agenda h3 { margin: 0 0 10px; font-size: 16px; display: flex; align-items: center; gap: 8px; }
|
||
.cal-agenda h3 .spacer { flex: 1; }
|
||
.cal-agenda h4 { font-size: 12px; text-transform: uppercase; letter-spacing: .06em; color: var(--muted); margin: 16px 2px 8px; }
|
||
.cal-agenda .note { font-size: 14px; }
|
||
.cal-modes { display: inline-flex; border: 1px solid var(--border); border-radius: 999px; padding: 2px; }
|
||
.cal-modes button { border: 0; background: transparent; border-radius: 999px; padding: 3px 10px; font-size: 13px; font-weight: 600; color: var(--muted); }
|
||
.cal-modes button.on { background: var(--accent-soft); color: var(--accent); }
|
||
.week { display: grid; grid-template-columns: repeat(7, minmax(0, 1fr)); gap: 6px; }
|
||
.week-day { border: 1px solid var(--border); background: var(--surface); border-radius: 12px; padding: 8px; min-height: 220px; display: flex; flex-direction: column; gap: 5px; cursor: pointer; }
|
||
.week-day.today { border-color: var(--accent); }
|
||
.week-day.selected { box-shadow: 0 0 0 2px var(--accent-soft); border-color: var(--accent); }
|
||
.week-day h5 { margin: 0 0 2px; font-size: 12px; color: var(--muted); text-transform: uppercase; letter-spacing: .04em; }
|
||
.week-day h5 b { display: block; font-size: 18px; color: var(--text); letter-spacing: 0; }
|
||
.wk-item { font-size: 12px; border-radius: 8px; padding: 4px 6px; background: var(--accent-soft); color: var(--text); overflow-wrap: anywhere; }
|
||
.wk-item.over { background: color-mix(in srgb, var(--danger) 16%, transparent); }
|
||
.wk-item.done, .wk-item.proj { background: var(--surface-2); color: var(--muted); }
|
||
.wk-item .t { font-weight: 700; color: var(--accent); margin-right: 4px; }
|
||
.wk-notes { font-size: 11px; color: var(--muted); margin-top: auto; }
|
||
@media (max-width: 820px) {
|
||
.week { grid-template-columns: minmax(0, 1fr); }
|
||
.week-day { min-height: 0; flex-direction: row; flex-wrap: wrap; align-items: center; }
|
||
.week-day h5 { width: 64px; margin: 0; } .week-day h5 b { display: inline; font-size: 15px; margin-left: 4px; }
|
||
.wk-notes { margin-top: 0; }
|
||
}
|
||
.move-banner { background: var(--accent); color: var(--accent-text); border-radius: 12px; padding: 8px 12px; margin-bottom: 10px; display: flex; gap: 10px; align-items: center; font-size: 14px; font-weight: 600; }
|
||
.move-banner span { flex: 1; }
|
||
.move-banner button { border: 0; background: rgba(255,255,255,.2); color: inherit; border-radius: 8px; padding: 4px 10px; font-weight: 700; }
|
||
.cal-day.drop, .week-day.drop { border-color: var(--accent); background: var(--accent-soft); }
|
||
.rem[draggable="true"] { cursor: grab; }
|
||
|
||
.notice { background: var(--accent-soft); color: var(--text); border-radius: 12px; padding: 10px 14px; font-size: 13px; margin-bottom: 14px; }
|
||
|
||
/* ---------- Settings ---------- */
|
||
.modal-back { position: fixed; inset: 0; background: rgba(10, 8, 20, .45); z-index: 40; display: flex; align-items: flex-start; justify-content: center; padding: calc(env(safe-area-inset-top) + 40px) 16px 16px; overflow-y: auto; }
|
||
.modal { width: 100%; max-width: 560px; background: var(--surface); border: 1px solid var(--border); border-radius: 18px; box-shadow: var(--shadow); padding: 20px; }
|
||
.modal h2 { margin: 0 0 4px; font-size: 18px; display: flex; align-items: center; }
|
||
.modal h2 .spacer { flex: 1; }
|
||
.modal h3 { margin: 22px 0 6px; font-size: 14px; }
|
||
.modal p.help { margin: 0 0 10px; color: var(--muted); font-size: 13px; }
|
||
.modal .row { display: flex; gap: 8px; flex-wrap: wrap; }
|
||
.modal .row .field { flex: 1; min-width: 0; }
|
||
.agent { border: 1px solid var(--border); border-radius: 12px; padding: 10px 12px; margin-bottom: 8px; display: flex; gap: 10px; align-items: center; }
|
||
.agent .info { flex: 1; min-width: 0; font-size: 13px; color: var(--muted); }
|
||
.agent .info strong { color: var(--text); font-size: 14px; }
|
||
.agent code { font-size: 12px; overflow-wrap: anywhere; }
|
||
.agent.revoked { opacity: .55; }
|
||
.pill-ok { color: var(--ok); font-weight: 600; }
|
||
|
||
/* ---------- Misc ---------- */
|
||
.toast-wrap { position: fixed; left: 50%; bottom: calc(env(safe-area-inset-bottom) + 20px); transform: translateX(-50%); z-index: 50; display: grid; gap: 8px; width: min(420px, calc(100vw - 32px)); }
|
||
.toast { background: var(--text); color: var(--bg); padding: 10px 14px; border-radius: 12px; box-shadow: var(--shadow); display: flex; align-items: center; gap: 10px; font-size: 14px; }
|
||
.toast span { flex: 1; }
|
||
.toast button { border: 0; background: transparent; color: var(--accent); font-weight: 700; filter: brightness(1.3); }
|
||
.lightbox { position: fixed; inset: 0; background: rgba(0,0,0,.85); z-index: 60; display: flex; align-items: center; justify-content: center; padding: 16px; cursor: zoom-out; }
|
||
.lightbox img { max-width: 100%; max-height: 100%; border-radius: 8px; }
|
||
.spinner { width: 18px; height: 18px; border: 2px solid var(--border); border-top-color: var(--accent); border-radius: 50%; animation: spin .8s linear infinite; display: inline-block; }
|
||
@keyframes spin { to { transform: rotate(360deg); } }
|
||
.offline-pill { background: var(--warn); color: #fff; border-radius: 999px; padding: 1px 8px; font-size: 12px; font-weight: 600; }
|
||
mark { background: color-mix(in srgb, var(--warn) 30%, transparent); color: inherit; border-radius: 3px; }
|
||
</style>
|
||
</head>
|
||
<body>
|
||
|
||
<!-- ============ Auth ============ -->
|
||
<section id="auth" class="hidden">
|
||
<div class="auth-card">
|
||
<img src="icon-192.png" alt="">
|
||
<h1>BrainFeed</h1>
|
||
<p>The private feed for your brain.</p>
|
||
<form id="auth-form" method="post" action="#">
|
||
<input class="field" type="email" id="auth-email" name="username" placeholder="Email" autocomplete="username" autocapitalize="off" spellcheck="false" required>
|
||
<input class="field" type="password" id="auth-pass" name="password" placeholder="Password" autocomplete="current-password" minlength="8" required>
|
||
<button class="btn" type="submit" id="auth-submit">Sign in</button>
|
||
<button class="btn ghost small" type="button" id="auth-forgot">Forgot password?</button>
|
||
<button class="btn ghost small" type="button" id="auth-toggle">First time? Create your account</button>
|
||
<div class="auth-msg" id="auth-msg"></div>
|
||
</form>
|
||
<form id="reset-form" class="hidden" method="post" action="#">
|
||
<p style="margin:0 0 4px">Choose a new password.</p>
|
||
<!-- Tells the password manager which account the new password belongs to. -->
|
||
<input type="email" id="reset-user" name="username" autocomplete="username" readonly hidden>
|
||
<input class="field" type="password" id="reset-pass" name="new-password" placeholder="New password (8+ characters)" autocomplete="new-password" minlength="8" required>
|
||
<input class="field" type="password" id="reset-pass2" placeholder="Repeat new password" autocomplete="new-password" minlength="8" required>
|
||
<button class="btn" type="submit" id="reset-submit">Save new password</button>
|
||
<div class="auth-msg" id="reset-msg"></div>
|
||
</form>
|
||
</div>
|
||
</section>
|
||
|
||
<!-- ============ App ============ -->
|
||
<div id="app" class="hidden">
|
||
<header>
|
||
<div class="header-row">
|
||
<div class="brand"><img src="favicon-32.png" alt=""><span>BrainFeed</span><span id="season-emoji" aria-hidden="true"></span></div>
|
||
<label class="search">
|
||
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round"><circle cx="11" cy="11" r="7"/><path d="m20 20-3.5-3.5"/></svg>
|
||
<input class="field" id="search" type="search" placeholder="Search notes or #tag" autocomplete="off">
|
||
</label>
|
||
<div style="position:relative">
|
||
<button class="icon-btn" id="menu-btn" aria-label="Menu">
|
||
<svg width="18" height="18" viewBox="0 0 24 24" fill="currentColor"><circle cx="12" cy="5" r="2"/><circle cx="12" cy="12" r="2"/><circle cx="12" cy="19" r="2"/></svg>
|
||
</button>
|
||
<div class="menu hidden" id="menu">
|
||
<div class="who" id="who"></div>
|
||
<button data-action="theme">Theme: <span id="theme-label">Auto</span></button>
|
||
<button data-action="tagbar">Tag bar: <span id="tagbar-label">Full</span></button>
|
||
<button data-action="density">Layout: <span id="density-label">Comfortable</span></button>
|
||
<button data-action="review">Review notes</button>
|
||
<button data-action="notify">Notifications…</button>
|
||
<button data-action="settings">Settings & connected agents</button>
|
||
<button data-action="export">Export all notes (JSON)</button>
|
||
<button data-action="signout">Sign out</button>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
<nav class="tabs">
|
||
<button class="tab active" data-view="feed">Feed</button>
|
||
<button class="tab" data-view="board">Board</button>
|
||
<button class="tab" data-view="reminders">Reminders <span class="badge hidden" id="rem-badge"></span></button>
|
||
<button class="tab" data-view="calendar">Calendar</button>
|
||
</nav>
|
||
</header>
|
||
|
||
<main id="main">
|
||
<aside id="aside">
|
||
<h3>Tags</h3>
|
||
<div class="tag-list" id="tag-list"></div>
|
||
</aside>
|
||
|
||
<section id="view-feed">
|
||
<div class="composer" id="composer">
|
||
<textarea id="compose" rows="1" placeholder="What's on your mind? Use #tags to file it…"></textarea>
|
||
<div class="pending-files" id="pending-files"></div>
|
||
<div class="remind-row hidden" id="remind-row">
|
||
<input class="field" type="datetime-local" id="remind-at">
|
||
<select class="field" id="remind-repeat">
|
||
<option value="">Once</option>
|
||
<option value="daily">Every day</option>
|
||
<option value="weekdays">Weekdays</option>
|
||
<option value="weekly">Every week</option>
|
||
<option value="monthly">Every month</option>
|
||
<option value="yearly">Every year</option>
|
||
<option value="dates">Specific dates…</option>
|
||
</select>
|
||
<div id="compose-dates" class="hidden" style="width:100%"></div>
|
||
<button class="chip" data-quick="1h">In 1 hour</button>
|
||
<button class="chip" data-quick="tonight">Tonight 8pm</button>
|
||
<button class="chip" data-quick="tomorrow">Tomorrow 9am</button>
|
||
<button class="chip" data-quick="monday">Monday 9am</button>
|
||
</div>
|
||
<div class="composer-bar">
|
||
<button class="tool" id="attach-btn" title="Attach photo or file" aria-label="Attach">
|
||
<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="m21.4 11.1-9.2 9.2a6 6 0 0 1-8.5-8.5l9.2-9.2a4 4 0 0 1 5.7 5.7l-9.2 9.2a2 2 0 0 1-2.8-2.8l8.5-8.5"/></svg>
|
||
</button>
|
||
<button class="tool" id="remind-btn" title="Make it a reminder" aria-label="Reminder">
|
||
<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M6 8a6 6 0 0 1 12 0c0 7 3 9 3 9H3s3-2 3-9"/><path d="M10.3 21a1.9 1.9 0 0 0 3.4 0"/></svg>
|
||
</button>
|
||
<button class="tool" id="heading-btn" title="Heading (tap again for a smaller one)" aria-label="Heading">
|
||
<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round"><path d="M6 4v16"/><path d="M18 4v16"/><path d="M6 12h12"/></svg>
|
||
</button>
|
||
<button class="tool" id="list-btn" title="Add a checklist item (Enter adds the next one)" aria-label="Checklist">
|
||
<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="m3 17 2 2 4-4"/><path d="m3 7 2 2 4-4"/><path d="M13 6h8"/><path d="M13 12h8"/><path d="M13 18h8"/></svg>
|
||
</button>
|
||
<button class="tool hidden" id="mic-btn" title="Dictate a note" aria-label="Dictate">
|
||
<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="9" y="2" width="6" height="12" rx="3"/><path d="M5 11a7 7 0 0 0 14 0"/><path d="M12 18v4"/></svg>
|
||
</button>
|
||
<input type="file" id="file-input" multiple class="hidden" accept="image/*,application/pdf,text/*,.doc,.docx,.xls,.xlsx,.csv,.zip">
|
||
<span class="spacer"></span>
|
||
<span class="hint" id="compose-hint">Enter to save · Shift+Enter for new line</span>
|
||
<button class="btn small" id="send-btn">Save</button>
|
||
</div>
|
||
</div>
|
||
<div class="status-line" id="status-line"></div>
|
||
<div id="feed"></div>
|
||
<button class="btn ghost load-more hidden" id="load-more">Load more</button>
|
||
</section>
|
||
|
||
<section id="view-board" class="hidden"></section>
|
||
<section id="view-reminders" class="hidden"></section>
|
||
<section id="view-calendar" class="hidden"></section>
|
||
</main>
|
||
</div>
|
||
|
||
<div class="toast-wrap" id="toasts"></div>
|
||
|
||
<script src="supabase.js"></script>
|
||
<script>
|
||
'use strict';
|
||
// ------------------------------------------------------------------
|
||
// Config. The publishable key is safe in public code: row-level
|
||
// security means it can only touch the signed-in user's own rows.
|
||
// ------------------------------------------------------------------
|
||
const SUPABASE_URL = 'https://bzvibdjrknqvmurwjroq.supabase.co';
|
||
const SUPABASE_KEY = 'sb_publishable__ybJKWB4JLb19YgGdW8LCg_Z4Xu5iSW';
|
||
const PAGE = 50;
|
||
const BUCKET = 'attachments';
|
||
const LS = { queue: 'bf-queue', cache: 'bf-cache', theme: 'bf-theme', alerted: 'bf-alerted', season: 'bf-season', seasonFx: 'bf-season-fx', tagbar: 'bf-tagbar', pushOn: 'bf-push-on', density: 'bf-density' };
|
||
|
||
// A password-reset email link lands here with #...type=recovery; note it before
|
||
// the client reads (and clears) the hash.
|
||
let recovering = /type=recovery/.test(location.hash);
|
||
const sb = supabase.createClient(SUPABASE_URL, SUPABASE_KEY, { auth: { persistSession: true, autoRefreshToken: true } });
|
||
|
||
const state = {
|
||
user: null, view: 'feed',
|
||
notes: [], hasMore: false, loading: false,
|
||
tag: null, pinned: false, archived: false, todo: false, archivedCount: 0, query: '',
|
||
appending: null, expanded: new Set(), children: {}, childCounts: {}, parentTitles: {},
|
||
remEditing: null, cal: { month: null, selected: null, notes: [], mode: 'month', moving: null }, dp: {},
|
||
tags: [], settings: null, reminders: [],
|
||
files: [], remindMode: false, editing: null, editBase: null, editDraft: null, openBodies: new Set(),
|
||
boardNotes: {}, boardPicking: false, pickTags: [], boardMoving: null,
|
||
agents: [],
|
||
};
|
||
|
||
const $ = (s) => document.querySelector(s);
|
||
const esc = (s) => String(s ?? '').replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c]));
|
||
const lsGet = (k, d) => { try { const v = localStorage.getItem(k); return v == null ? d : JSON.parse(v); } catch { return d; } };
|
||
const lsSet = (k, v) => { try { localStorage.setItem(k, JSON.stringify(v)); } catch {} };
|
||
|
||
// ------------------------------------------------------------------
|
||
// Toasts
|
||
// ------------------------------------------------------------------
|
||
function toast(msg, action, onAction, ms = 4000) {
|
||
const el = document.createElement('div');
|
||
el.className = 'toast';
|
||
el.innerHTML = `<span>${esc(msg)}</span>` + (action ? `<button>${esc(action)}</button>` : '');
|
||
$('#toasts').appendChild(el);
|
||
let done = false;
|
||
const close = () => { if (!done) { done = true; el.remove(); } };
|
||
if (action) el.querySelector('button').onclick = () => { close(); onAction(); };
|
||
setTimeout(close, ms);
|
||
return close;
|
||
}
|
||
|
||
// ------------------------------------------------------------------
|
||
// Theme
|
||
// ------------------------------------------------------------------
|
||
// ------------------------------------------------------------------
|
||
// Seasonal themes: a palette per month for light and dark (all checked
|
||
// for WCAG AA contrast), a header stripe, an emoji and optional particles.
|
||
// ------------------------------------------------------------------
|
||
const SEASONS = {"jan": {"name": "Winter", "emoji": "⛄", "stripe": "linear-gradient(90deg,#9ec9f0,#e8f2fc,#9ec9f0)", "particles": "❄️", "empty": "Quiet as fresh snow.", "light": {"bg": "#f2f6fb", "surface": "#ffffff", "surface-2": "#e6eef8", "border": "#d3e0ef", "accent": "#2763a6", "accent-soft": "#e0ebf8", "accent-text": "#ffffff"}, "dark": {"bg": "#0e131a", "surface": "#17202b", "surface-2": "#202c3a", "border": "#2c3a4d", "accent": "#86bbf0", "accent-soft": "#1c3149", "accent-text": "#0a1622"}}, "feb": {"name": "Valentine's", "emoji": "💘", "stripe": "linear-gradient(90deg,#e91e63,#f8bbd0,#e91e63)", "particles": "", "empty": "Nothing here yet. Write something you love.", "light": {"bg": "#fbf4f6", "surface": "#ffffff", "surface-2": "#f6e5eb", "border": "#efd2dc", "accent": "#b8154f", "accent-soft": "#fbe0e9", "accent-text": "#ffffff"}, "dark": {"bg": "#170f13", "surface": "#22161c", "surface-2": "#2e1d25", "border": "#45293a", "accent": "#f592b6", "accent-soft": "#3e1f2d", "accent-text": "#2a0b18"}}, "mar": {"name": "St. Patrick's", "emoji": "🍀", "stripe": "linear-gradient(90deg,#1e7d3a,#f2c94c,#1e7d3a)", "particles": "", "empty": "Your feed is empty. Feeling lucky?", "light": {"bg": "#f3f8f3", "surface": "#ffffff", "surface-2": "#e2efe4", "border": "#cde2d0", "accent": "#1b7034", "accent-soft": "#ddeee1", "accent-text": "#ffffff"}, "dark": {"bg": "#0e1510", "surface": "#16201a", "surface-2": "#1f2c23", "border": "#2c3e31", "accent": "#72d290", "accent-soft": "#1a3524", "accent-text": "#0a1a0f"}}, "apr": {"name": "Spring", "emoji": "🌷", "stripe": "linear-gradient(90deg,#c3a6f0,#a8e6cf,#f7c8e0)", "particles": "", "empty": "Fresh start. Plant an idea.", "light": {"bg": "#f7f5fb", "surface": "#ffffff", "surface-2": "#eee7f8", "border": "#ddd2ef", "accent": "#6f45ba", "accent-soft": "#ece3fa", "accent-text": "#ffffff"}, "dark": {"bg": "#131119", "surface": "#1d1a26", "surface-2": "#282336", "border": "#3a3350", "accent": "#c6abf6", "accent-soft": "#30264a", "accent-text": "#160f26"}}, "may": {"name": "Bloom", "emoji": "🌸", "stripe": "linear-gradient(90deg,#f28b6b,#7cc576,#f28b6b)", "particles": "", "empty": "Nothing blooming yet. Add a thought.", "light": {"bg": "#fbf6f3", "surface": "#ffffff", "surface-2": "#f6e8e1", "border": "#ecd5c9", "accent": "#b2462f", "accent-soft": "#fbe4dd", "accent-text": "#ffffff"}, "dark": {"bg": "#17110f", "surface": "#221a17", "surface-2": "#2e231f", "border": "#46342c", "accent": "#f4a089", "accent-soft": "#3d2620", "accent-text": "#2a110a"}}, "jun": {"name": "Summer", "emoji": "☀️", "stripe": "linear-gradient(90deg,#ffd166,#6ec3f4,#ffd166)", "particles": "", "empty": "Clear skies. Nothing here yet.", "light": {"bg": "#fbfaf0", "surface": "#ffffff", "surface-2": "#f3efd8", "border": "#e6dfbb", "accent": "#1c6ea6", "accent-soft": "#dfeef9", "accent-text": "#ffffff"}, "dark": {"bg": "#12130f", "surface": "#1b1d17", "surface-2": "#262920", "border": "#3a3d2d", "accent": "#ffd166", "accent-soft": "#3a3317", "accent-text": "#1d1600"}}, "jul": {"name": "Fourth of July", "emoji": "🎆", "stripe": "linear-gradient(90deg,#b22234 0 33%,#ffffff 33% 66%,#3c3b6e 66%)", "particles": "", "empty": "Nothing here yet. Light it up!", "light": {"bg": "#f5f7fb", "surface": "#ffffff", "surface-2": "#e8ecf6", "border": "#d5dcec", "accent": "#b22234", "accent-soft": "#fae1e5", "accent-text": "#ffffff"}, "dark": {"bg": "#0e1220", "surface": "#161c2e", "surface-2": "#1f2740", "border": "#2e3a5a", "accent": "#ff7a88", "accent-soft": "#3a1e2a", "accent-text": "#2a0a10"}}, "aug": {"name": "Beach", "emoji": "🏖️", "stripe": "linear-gradient(90deg,#1aa3a8,#f1dcae,#1aa3a8)", "particles": "", "empty": "Nothing but sand here. Add a note.", "light": {"bg": "#faf7f0", "surface": "#ffffff", "surface-2": "#e2f1ef", "border": "#d6e6e2", "accent": "#0d7275", "accent-soft": "#d8efed", "accent-text": "#ffffff"}, "dark": {"bg": "#0e1616", "surface": "#162121", "surface-2": "#1f2d2d", "border": "#2e4343", "accent": "#62d6d2", "accent-soft": "#173535", "accent-text": "#062020"}}, "sep": {"name": "Football season", "emoji": "🏈", "stripe": "repeating-linear-gradient(90deg,#2e7d32 0 22px,#ffffff 22px 24px)", "particles": "", "empty": "Empty field. Kick something off.", "light": {"bg": "#f3f6f0", "surface": "#ffffff", "surface-2": "#e5ebdf", "border": "#d1dbc7", "accent": "#6b3f22", "accent-soft": "#f0e3d6", "accent-text": "#ffffff"}, "dark": {"bg": "#0f140e", "surface": "#182016", "surface-2": "#222c1f", "border": "#34432f", "accent": "#d29a6c", "accent-soft": "#3a2a1d", "accent-text": "#1d1208"}}, "oct": {"name": "Halloween", "emoji": "🎃", "stripe": "repeating-linear-gradient(90deg,#ff8a1f 0 18px,#111 18px 36px)", "particles": "🦇", "preferDark": true, "empty": "Nothing here… spooky 👻", "light": {"bg": "#fdf6ee", "surface": "#ffffff", "surface-2": "#f8e8d6", "border": "#efd5b9", "accent": "#9e4600", "accent-soft": "#fde8d3", "accent-text": "#ffffff"}, "dark": {"bg": "#0d0b0a", "surface": "#1a1612", "surface-2": "#26201a", "border": "#3b3025", "accent": "#ff8a1f", "accent-soft": "#3d250e", "accent-text": "#1a0d00"}}, "nov": {"name": "Harvest", "emoji": "🦃", "stripe": "linear-gradient(90deg,#a0522d,#e8a35a,#7a5c2e)", "particles": "🍂", "empty": "Nothing to harvest yet. Add a note.", "light": {"bg": "#faf5ef", "surface": "#ffffff", "surface-2": "#f2e5d6", "border": "#e5d0b8", "accent": "#984a26", "accent-soft": "#f7e2d2", "accent-text": "#ffffff"}, "dark": {"bg": "#15100c", "surface": "#201913", "surface-2": "#2c2219", "border": "#43331f", "accent": "#eaa860", "accent-soft": "#3b2915", "accent-text": "#1f1203"}}, "dec": {"name": "Holidays", "emoji": "🎄", "stripe": "repeating-linear-gradient(90deg,#b3202a 0 14px,#ffffff 14px 18px,#1b6b3a 18px 32px,#ffffff 32px 36px)", "particles": "❄️", "empty": "All quiet. Add a note to the list.", "light": {"bg": "#f5f8f5", "surface": "#ffffff", "surface-2": "#e5eee6", "border": "#d2e1d4", "accent": "#1a6638", "accent-soft": "#dfeee2", "accent-text": "#ffffff"}, "dark": {"bg": "#0d1310", "surface": "#151e19", "surface-2": "#1e2a23", "border": "#2d3e34", "accent": "#ee6a6f", "accent-soft": "#3b1c1f", "accent-text": "#22070a"}}};
|
||
const MONTH_KEYS = ['jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep', 'oct', 'nov', 'dec'];
|
||
const SEASON_VARS = ['bg', 'surface', 'surface-2', 'border', 'accent', 'accent-soft', 'accent-text'];
|
||
|
||
function currentSeason() {
|
||
const pick = lsGet(LS.season, 'auto');
|
||
if (pick === 'off') return null;
|
||
const key = pick === 'auto' ? MONTH_KEYS[new Date().getMonth()] : pick;
|
||
return SEASONS[key] ? { key, ...SEASONS[key] } : null;
|
||
}
|
||
function isDarkMode() {
|
||
const t = document.documentElement.getAttribute('data-theme');
|
||
return t ? t === 'dark' : matchMedia('(prefers-color-scheme: dark)').matches;
|
||
}
|
||
|
||
function applySeason() {
|
||
const se = currentSeason(), root = document.documentElement;
|
||
for (const v of SEASON_VARS) root.style.removeProperty('--' + v);
|
||
root.style.removeProperty('--season-stripe');
|
||
root.dataset.season = se ? se.key : 'off';
|
||
if (se) {
|
||
const pal = se[isDarkMode() ? 'dark' : 'light'];
|
||
for (const v of SEASON_VARS) root.style.setProperty('--' + v, pal[v]);
|
||
root.style.setProperty('--season-stripe', se.stripe);
|
||
}
|
||
const em = $('#season-emoji'); if (em) { em.textContent = se ? se.emoji : ''; em.title = se ? se.name : ''; }
|
||
const meta = document.querySelector('meta[name="theme-color"]');
|
||
if (meta) meta.content = getComputedStyle(root).getPropertyValue('--accent').trim() || '#6042e8';
|
||
renderSeasonFx(se);
|
||
}
|
||
|
||
function renderSeasonFx(se) {
|
||
let layer = document.getElementById('season-fx');
|
||
const on = se && se.particles && lsGet(LS.seasonFx, true) && !matchMedia('(prefers-reduced-motion: reduce)').matches;
|
||
if (!on) { layer?.remove(); return; }
|
||
if (layer && layer.dataset.k === se.key) return;
|
||
layer?.remove();
|
||
layer = document.createElement('div');
|
||
layer.id = 'season-fx'; layer.dataset.k = se.key; layer.setAttribute('aria-hidden', 'true');
|
||
const count = se.key === 'oct' ? 5 : 14;
|
||
for (let i = 0; i < count; i++) {
|
||
const p = document.createElement('span');
|
||
p.textContent = se.particles;
|
||
p.style.left = (Math.random() * 100) + '%';
|
||
p.style.fontSize = (10 + Math.random() * 12) + 'px';
|
||
p.style.opacity = (0.22 + Math.random() * 0.3).toFixed(2);
|
||
p.style.animationDuration = (se.key === 'oct' ? 16 : 10) + Math.random() * 10 + 's';
|
||
p.style.animationDelay = (-Math.random() * 20) + 's';
|
||
layer.appendChild(p);
|
||
}
|
||
document.body.appendChild(layer);
|
||
}
|
||
|
||
function applyTheme() {
|
||
const t = lsGet(LS.theme, 'auto');
|
||
// Some seasons (Halloween) look best dark: "Auto" follows the season's lead.
|
||
const effective = t === 'auto' && currentSeason()?.preferDark ? 'dark' : t;
|
||
if (effective === 'auto') document.documentElement.removeAttribute('data-theme');
|
||
else document.documentElement.setAttribute('data-theme', effective);
|
||
const l = $('#theme-label'); if (l) l.textContent = t[0].toUpperCase() + t.slice(1);
|
||
applySeason();
|
||
}
|
||
matchMedia('(prefers-color-scheme: dark)').addEventListener?.('change', applySeason);
|
||
// Roll over to the next month's theme without a reload.
|
||
let seasonMonth = new Date().getMonth();
|
||
const checkSeasonRollover = () => { if (new Date().getMonth() !== seasonMonth) { seasonMonth = new Date().getMonth(); applyTheme(); } };
|
||
setInterval(checkSeasonRollover, 3600e3);
|
||
document.addEventListener('visibilitychange', () => { if (!document.hidden) checkSeasonRollover(); });
|
||
applyTheme();
|
||
|
||
// ------------------------------------------------------------------
|
||
// Auth
|
||
// ------------------------------------------------------------------
|
||
let signupMode = false;
|
||
$('#auth-toggle').onclick = () => {
|
||
signupMode = !signupMode;
|
||
$('#auth-submit').textContent = signupMode ? 'Create account' : 'Sign in';
|
||
$('#auth-toggle').textContent = signupMode ? 'Have an account? Sign in' : 'First time? Create your account';
|
||
$('#auth-pass').autocomplete = signupMode ? 'new-password' : 'current-password';
|
||
$('#auth-msg').textContent = '';
|
||
};
|
||
$('#auth-form').onsubmit = async (e) => {
|
||
e.preventDefault();
|
||
const email = $('#auth-email').value.trim(), password = $('#auth-pass').value;
|
||
const msg = $('#auth-msg'); msg.className = 'auth-msg'; msg.textContent = '';
|
||
$('#auth-submit').disabled = true;
|
||
try {
|
||
if (signupMode) {
|
||
const { data, error } = await sb.auth.signUp({ email, password, options: { emailRedirectTo: location.origin + location.pathname } });
|
||
if (error) throw error;
|
||
if (!data.session) {
|
||
msg.className = 'auth-msg ok';
|
||
msg.textContent = 'Account created. Check your email to confirm it, then sign in here.';
|
||
}
|
||
} else {
|
||
const { error } = await sb.auth.signInWithPassword({ email, password });
|
||
if (error) throw error;
|
||
}
|
||
} catch (err) {
|
||
msg.textContent = /closed/i.test(err.message) || /Database error/i.test(err.message)
|
||
? 'Signups are closed for this BrainFeed.'
|
||
: err.code === 'invalid_credentials' ? 'Wrong email or password. Use "Forgot password?" below if you need a new one.' : err.message;
|
||
} finally { $('#auth-submit').disabled = false; }
|
||
};
|
||
|
||
$('#auth-forgot').onclick = async () => {
|
||
const email = $('#auth-email').value.trim();
|
||
const msg = $('#auth-msg'); msg.className = 'auth-msg';
|
||
if (!email) { msg.textContent = 'Enter your email above first.'; $('#auth-email').focus(); return; }
|
||
$('#auth-forgot').disabled = true;
|
||
const { error } = await sb.auth.resetPasswordForEmail(email, { redirectTo: location.origin + location.pathname });
|
||
$('#auth-forgot').disabled = false;
|
||
if (error) { msg.textContent = /rate/i.test(error.message) ? 'Too many emails sent. Wait a few minutes and try again.' : error.message; return; }
|
||
msg.className = 'auth-msg ok';
|
||
msg.textContent = 'If that email has an account, a reset link is on its way. Open it on this device.';
|
||
};
|
||
|
||
function showReset() {
|
||
sb.auth.getSession().then(({ data }) => { $('#reset-user').value = data.session?.user?.email || ''; });
|
||
$('#app').classList.add('hidden');
|
||
$('#auth').classList.remove('hidden');
|
||
$('#auth-form').classList.add('hidden');
|
||
$('#reset-form').classList.remove('hidden');
|
||
$('#reset-pass').focus();
|
||
}
|
||
|
||
$('#reset-form').onsubmit = async (e) => {
|
||
e.preventDefault();
|
||
const a = $('#reset-pass').value, b = $('#reset-pass2').value;
|
||
const msg = $('#reset-msg'); msg.className = 'auth-msg';
|
||
if (a !== b) { msg.textContent = 'Passwords don\'t match.'; return; }
|
||
$('#reset-submit').disabled = true;
|
||
// Clear the flag first: updateUser fires USER_UPDATED before it resolves.
|
||
recovering = false;
|
||
const { error } = await sb.auth.updateUser({ password: a });
|
||
$('#reset-submit').disabled = false;
|
||
if (error) {
|
||
recovering = true;
|
||
msg.textContent = error.code === 'same_password'
|
||
? 'That is already your password. Reload the page to continue.' : error.message;
|
||
return;
|
||
}
|
||
$('#reset-form').classList.add('hidden');
|
||
$('#auth-form').classList.remove('hidden');
|
||
toast('Password updated');
|
||
const { data } = await sb.auth.getSession();
|
||
if (data.session) { state.user = data.session.user; startApp(); }
|
||
};
|
||
|
||
sb.auth.onAuthStateChange((event, session) => {
|
||
const u = session?.user || null;
|
||
if (event === 'PASSWORD_RECOVERY') recovering = true;
|
||
if (event === 'USER_UPDATED') return;
|
||
if (u && recovering) { setTimeout(showReset, 0); return; }
|
||
if (u && (!state.user || state.user.id !== u.id)) { state.user = u; setTimeout(startApp, 0); }
|
||
else if (!u && event === 'SIGNED_OUT') { state.user = null; showAuth(); }
|
||
else if (!u && event === 'INITIAL_SESSION') showAuth();
|
||
});
|
||
|
||
function showAuth() {
|
||
$('#app').classList.add('hidden');
|
||
$('#auth').classList.remove('hidden');
|
||
}
|
||
|
||
// ------------------------------------------------------------------
|
||
// App start
|
||
// ------------------------------------------------------------------
|
||
let realtime = null, reminderTimer = null;
|
||
async function startApp() {
|
||
try { navigator.storage?.persist?.(); } catch {}
|
||
$('#auth').classList.add('hidden');
|
||
applyTagBar(); applyDensity();
|
||
$('#app').classList.remove('hidden');
|
||
$('#who').textContent = state.user.email;
|
||
|
||
// Instant paint from cache, then fetch fresh
|
||
const cached = lsGet(LS.cache, null);
|
||
if (cached && cached.uid === state.user.id) { state.notes = cached.notes; renderFeed(); }
|
||
|
||
await Promise.all([loadSettings(), loadTags(), loadNotes(true), loadReminders()]);
|
||
await flushQueue();
|
||
await handleIncoming();
|
||
subscribe();
|
||
if (!reminderTimer) reminderTimer = setInterval(checkDueReminders, 30000);
|
||
checkDueReminders();
|
||
}
|
||
|
||
function subscribe() {
|
||
if (realtime) sb.removeChannel(realtime);
|
||
realtime = sb.channel('bf-' + state.user.id)
|
||
.on('postgres_changes', { event: '*', schema: 'public', table: 'notes', filter: `user_id=eq.${state.user.id}` }, onNoteChange)
|
||
.on('postgres_changes', { event: '*', schema: 'public', table: 'reminders', filter: `user_id=eq.${state.user.id}` }, () => loadReminders())
|
||
.subscribe();
|
||
}
|
||
|
||
function onNoteChange({ eventType, new: row, old }) {
|
||
if (eventType === 'DELETE') {
|
||
state.notes = state.notes.filter((n) => n.id !== old.id);
|
||
} else if (eventType === 'INSERT') {
|
||
if (!state.notes.some((n) => n.id === row.id) && matchesFilter(row)) state.notes.unshift(row);
|
||
} else if (eventType === 'UPDATE') {
|
||
const i = state.notes.findIndex((n) => n.id === row.id);
|
||
if (i >= 0) { if (matchesFilter(row)) state.notes[i] = row; else state.notes.splice(i, 1); }
|
||
}
|
||
if (state.editing == null) { renderFeed(); if (state.view === 'board') loadBoard(); }
|
||
scheduleTagRefresh();
|
||
scheduleNestingRefresh();
|
||
if (state.view === 'calendar') { clearTimeout(calTimer); calTimer = setTimeout(loadCalendarNotes, 500); }
|
||
}
|
||
|
||
let tagTimer = null;
|
||
function scheduleTagRefresh() { clearTimeout(tagTimer); tagTimer = setTimeout(loadTags, 600); }
|
||
|
||
// ------------------------------------------------------------------
|
||
// Data: notes
|
||
// ------------------------------------------------------------------
|
||
function parseQuery(q) {
|
||
const words = [], tags = [];
|
||
for (const w of q.trim().split(/\s+/).filter(Boolean)) {
|
||
if (/^#[A-Za-z][\w-]*$/.test(w)) tags.push(w.slice(1).toLowerCase());
|
||
else words.push(w);
|
||
}
|
||
return { words, tags };
|
||
}
|
||
|
||
const OPEN_ITEM_RE = /^\s*[-*] \[ \]/m;
|
||
|
||
const isMainFeed = () => !state.tag && !state.pinned && !state.archived && !state.todo && !state.query;
|
||
|
||
function matchesFilter(n) {
|
||
// Notes inside another note live under their parent, not in the main feed.
|
||
if (n.parent_id && isMainFeed()) return false;
|
||
if (state.todo && !n.tags.includes('todo') && !OPEN_ITEM_RE.test(n.body)) return false;
|
||
// Archived notes only show in the Archived view, or when searching.
|
||
if (state.archived ? !n.archived_at : (n.archived_at && !state.query)) return false;
|
||
if (state.tag && !n.tags.includes(state.tag)) return false;
|
||
if (state.pinned && !n.pinned) return false;
|
||
const { words, tags } = parseQuery(state.query);
|
||
if (tags.some((t) => !n.tags.includes(t))) return false;
|
||
const b = n.body.toLowerCase();
|
||
return words.every((w) => b.includes(w.toLowerCase()));
|
||
}
|
||
|
||
// Each load gets a number; only the newest one may show its results, so a slow
|
||
// earlier search can never replace a newer one. "Load more" waits for the current load.
|
||
let loadSeq = 0;
|
||
async function loadNotes(reset) {
|
||
if (!reset && state.loading) return;
|
||
const seq = ++loadSeq;
|
||
state.loading = true;
|
||
if (reset) renderStatus(true);
|
||
const offset = reset ? 0 : state.notes.length;
|
||
let q = sb.from('notes').select(NOTE_SELECT)
|
||
.order('created_at', { ascending: false }).range(offset, offset + PAGE - 1);
|
||
if (isMainFeed()) q = q.is('parent_id', null);
|
||
if (state.archived) q = q.not('archived_at', 'is', null);
|
||
else if (!state.query) q = q.is('archived_at', null);
|
||
if (state.todo) q = q.or('tags.cs.{todo},body.like.*[ ]*');
|
||
if (state.tag) q = q.contains('tags', [state.tag]);
|
||
if (state.pinned) q = q.eq('pinned', true);
|
||
const { words, tags } = parseQuery(state.query);
|
||
if (tags.length) q = q.contains('tags', tags);
|
||
for (const w of words) q = q.ilike('body', `%${w.replace(/[%_\\]/g, '\\$&')}%`);
|
||
const { data, error } = await q;
|
||
if (seq !== loadSeq) return; // a newer load replaced this one
|
||
state.loading = false;
|
||
if (error) {
|
||
renderStatus(false, navigator.onLine ? 'Couldn\'t load notes: ' + error.message : null);
|
||
return;
|
||
}
|
||
await loadNestingInfo(data);
|
||
if (seq !== loadSeq) return;
|
||
state.notes = reset ? data : state.notes.concat(data);
|
||
state.hasMore = data.length === PAGE;
|
||
if (!state.tag && !state.pinned && !state.archived && !state.todo && !state.query) lsSet(LS.cache, { uid: state.user.id, notes: state.notes.slice(0, PAGE) });
|
||
renderFeed();
|
||
}
|
||
|
||
const NOTE_SELECT = 'id,body,tags,source,pinned,attachments,archived_at,parent_id,created_at,updated_at';
|
||
const firstLine = (body) => (body.split('\n').find((l) => l.trim()) || '').replace(/^#{1,3} |^[-*] \[[ xX]\] /, '').slice(0, 60);
|
||
|
||
// Child counts for notes on screen, and titles of parents for notes shown outside them.
|
||
async function loadNestingInfo(notes) {
|
||
const ids = notes.filter((n) => !n.parent_id).map((n) => n.id);
|
||
const parentIds = [...new Set(notes.map((n) => n.parent_id).filter((p) => p && !state.parentTitles[p]))];
|
||
const [counts, parents] = await Promise.all([
|
||
ids.length ? sb.rpc('child_counts', { p_ids: ids }) : { data: [] },
|
||
parentIds.length ? sb.from('notes').select('id,body').in('id', parentIds) : { data: [] },
|
||
]);
|
||
for (const id of ids) delete state.childCounts[id];
|
||
for (const r of counts.data || []) state.childCounts[r.parent_id] = Number(r.count);
|
||
for (const p of parents.data || []) state.parentTitles[p.id] = firstLine(p.body);
|
||
}
|
||
|
||
async function loadChildren(parentId) {
|
||
const { data } = await sb.from('notes').select(NOTE_SELECT).eq('parent_id', parentId).order('created_at');
|
||
state.children[parentId] = data || [];
|
||
state.childCounts[parentId] = state.children[parentId].length;
|
||
}
|
||
|
||
let nestTimer = null;
|
||
function scheduleNestingRefresh() {
|
||
clearTimeout(nestTimer);
|
||
nestTimer = setTimeout(async () => {
|
||
await Promise.all([loadNestingInfo(state.notes), ...[...state.expanded].map(loadChildren)]);
|
||
if (state.editing == null) rerender();
|
||
}, 500);
|
||
}
|
||
|
||
async function loadTags() {
|
||
const [{ data, error }, { data: archived }] = await Promise.all([sb.rpc('tag_counts'), sb.rpc('archived_count')]);
|
||
if (!error) { state.tags = data; state.archivedCount = Number(archived) || 0; renderTags(); }
|
||
}
|
||
|
||
async function loadSettings() {
|
||
let { data } = await sb.from('settings').select('*').maybeSingle();
|
||
if (!data) {
|
||
const tz = Intl.DateTimeFormat().resolvedOptions().timeZone || 'America/Los_Angeles';
|
||
({ data } = await sb.from('settings').insert({ timezone: tz }).select().single());
|
||
}
|
||
state.settings = data || { board_tags: [] };
|
||
}
|
||
|
||
function newId() {
|
||
return crypto.randomUUID ? crypto.randomUUID()
|
||
: 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => { const r = Math.random() * 16 | 0; return (c === 'x' ? r : (r & 3 | 8)).toString(16); });
|
||
}
|
||
|
||
// Returns true when the note is saved (or safely queued offline), false when it wasn't,
|
||
// so the caller can put the draft back.
|
||
async function addNote(body, files = [], source = 'web') {
|
||
const id = newId();
|
||
const created_at = new Date().toISOString();
|
||
const optimistic = { id, body, tags: localTags(body), source, pinned: false, attachments: [], created_at, _queued: !navigator.onLine };
|
||
if (matchesFilter(optimistic)) { state.notes.unshift(optimistic); renderFeed(); }
|
||
|
||
if (!navigator.onLine) {
|
||
// Files can't wait in the offline queue, so a note with files isn't taken while offline.
|
||
if (files.length) { state.notes = state.notes.filter((n) => n.id !== id); renderFeed(); toast('You\'re offline. Notes with files need a connection.'); return false; }
|
||
queuePush({ id, body, source, created_at });
|
||
return true;
|
||
}
|
||
const attachments = [];
|
||
try {
|
||
for (const f of files) attachments.push(await uploadFile(id, f));
|
||
const { data, error } = await sb.from('notes').insert({ id, body, source, attachments, created_at }).select().single();
|
||
if (error) throw error;
|
||
replaceNote(data);
|
||
scheduleTagRefresh();
|
||
return true;
|
||
} catch (err) {
|
||
const network = !navigator.onLine || /fetch|network/i.test(err.message);
|
||
if (network && !files.length) {
|
||
queuePush({ id, body, source, created_at });
|
||
markQueued(id);
|
||
return true;
|
||
}
|
||
// Files that uploaded before the failure would be left behind; remove them (the draft
|
||
// keeps the originals, so a retry uploads them again cleanly).
|
||
if (attachments.length) sb.storage.from(BUCKET).remove(attachments.map((a) => a.path)).catch(() => {});
|
||
state.notes = state.notes.filter((n) => n.id !== id); renderFeed();
|
||
toast(network ? 'Lost connection while uploading. Your note is back in the box; try again when you\'re online.' : 'Couldn\'t save: ' + err.message + '. Your note is back in the box.');
|
||
return false;
|
||
}
|
||
}
|
||
|
||
function localTags(body) {
|
||
const out = new Set();
|
||
body.replace(/(^|[^&\w])#([A-Za-z][\w-]*)/g, (_, a, t) => out.add(t.toLowerCase()));
|
||
return [...out].sort();
|
||
}
|
||
|
||
function replaceNote(row) {
|
||
const i = state.notes.findIndex((n) => n.id === row.id);
|
||
if (i >= 0) state.notes[i] = row;
|
||
for (const k in state.boardNotes) state.boardNotes[k] = state.boardNotes[k].map((n) => (n.id === row.id ? row : n));
|
||
for (const k in state.children) state.children[k] = state.children[k].map((n) => (n.id === row.id ? row : n));
|
||
state.cal.notes = state.cal.notes.map((n) => (n.id === row.id ? row : n));
|
||
rerender();
|
||
}
|
||
function findNote(id) { return state.notes.find((n) => n.id === id) || Object.values(state.children).flat().find((n) => n.id === id) || Object.values(state.boardNotes).flat().find((n) => n.id === id) || state.cal.notes.find((n) => n.id === id); }
|
||
function rerender() { renderFeed(); if (state.view === 'board') renderBoard(); if (state.view === 'calendar') renderCalendar(); focusEdit(); }
|
||
function focusEdit() { const et = $('#edit-text'); if (et && document.activeElement !== et) { et.focus(); et.setSelectionRange(et.value.length, et.value.length); } }
|
||
function markQueued(id) { const n = state.notes.find((x) => x.id === id); if (n) { n._queued = true; renderFeed(); } }
|
||
|
||
// Offline queue ------------------------------------------------------
|
||
function queuePush(item) { const q = lsGet(LS.queue, []); q.push(item); lsSet(LS.queue, q); renderStatus(); }
|
||
async function flushQueue() {
|
||
const q = lsGet(LS.queue, []);
|
||
if (!q.length || !navigator.onLine) return;
|
||
const left = [];
|
||
for (const item of q) {
|
||
const { data, error } = await sb.from('notes').upsert(item, { onConflict: 'id', ignoreDuplicates: true }).select().maybeSingle();
|
||
if (error) left.push(item);
|
||
else if (data) replaceNote(data);
|
||
}
|
||
lsSet(LS.queue, left);
|
||
if (q.length > left.length) { toast(`Synced ${q.length - left.length} offline note${q.length - left.length > 1 ? 's' : ''}`); scheduleTagRefresh(); loadNotes(true); }
|
||
renderStatus();
|
||
}
|
||
window.addEventListener('online', () => { flushQueue(); renderStatus(); });
|
||
window.addEventListener('offline', () => renderStatus());
|
||
|
||
// Attachments --------------------------------------------------------
|
||
async function shrinkImage(file) {
|
||
if (!/^image\/(jpeg|png|webp|heic|heif)$/i.test(file.type) || file.size < 600 * 1024) return file;
|
||
try {
|
||
const bmp = await createImageBitmap(file);
|
||
const max = 2000, scale = Math.min(1, max / Math.max(bmp.width, bmp.height));
|
||
const c = document.createElement('canvas');
|
||
c.width = Math.round(bmp.width * scale); c.height = Math.round(bmp.height * scale);
|
||
c.getContext('2d').drawImage(bmp, 0, 0, c.width, c.height);
|
||
const blob = await new Promise((r) => c.toBlob(r, 'image/jpeg', 0.85));
|
||
if (!blob || blob.size >= file.size) return file;
|
||
return new File([blob], file.name.replace(/\.\w+$/, '') + '.jpg', { type: 'image/jpeg' });
|
||
} catch { return file; }
|
||
}
|
||
|
||
async function uploadFile(noteId, file) {
|
||
file = await shrinkImage(file);
|
||
const safe = file.name.replace(/[^\w.-]+/g, '_').slice(-80) || 'file';
|
||
const path = `${state.user.id}/${noteId}/${Date.now()}-${safe}`;
|
||
const { error } = await sb.storage.from(BUCKET).upload(path, file, { contentType: file.type || 'application/octet-stream' });
|
||
if (error) throw error;
|
||
return { path, name: file.name, type: file.type, size: file.size };
|
||
}
|
||
|
||
const urlCache = new Map();
|
||
async function signUrls(paths) {
|
||
const need = paths.filter((p) => { const c = urlCache.get(p); return !c || c.exp < Date.now(); });
|
||
if (!need.length) return;
|
||
const { data } = await sb.storage.from(BUCKET).createSignedUrls(need, 3600);
|
||
for (const d of data || []) if (d.signedUrl) urlCache.set(d.path, { url: d.signedUrl, exp: Date.now() + 3500e3 });
|
||
}
|
||
|
||
async function hydrateAttachments(root) {
|
||
const els = [...root.querySelectorAll('[data-path]')];
|
||
if (!els.length) return;
|
||
await signUrls([...new Set(els.map((e) => e.dataset.path))]);
|
||
for (const el of els) {
|
||
const c = urlCache.get(el.dataset.path); if (!c) continue;
|
||
if (el.tagName === 'IMG') el.src = c.url; else el.href = c.url;
|
||
}
|
||
}
|
||
|
||
// ------------------------------------------------------------------
|
||
// Rendering: feed
|
||
// ------------------------------------------------------------------
|
||
function dayLabel(d) {
|
||
const today = new Date(); today.setHours(0, 0, 0, 0);
|
||
const x = new Date(d); x.setHours(0, 0, 0, 0);
|
||
const diff = Math.round((today - x) / 864e5);
|
||
if (diff === 0) return 'Today';
|
||
if (diff === 1) return 'Yesterday';
|
||
if (diff < 7) return x.toLocaleDateString(undefined, { weekday: 'long' });
|
||
return x.toLocaleDateString(undefined, { month: 'long', day: 'numeric', year: x.getFullYear() === today.getFullYear() ? undefined : 'numeric' });
|
||
}
|
||
const timeLabel = (d) => new Date(d).toLocaleTimeString(undefined, { hour: 'numeric', minute: '2-digit' });
|
||
|
||
function highlight(html) {
|
||
const { words } = parseQuery(state.query);
|
||
if (!words.length) return html;
|
||
const re = new RegExp('(' + words.map((w) => esc(w).replace(/[.*+?^${}()|[\]\\]/g, '\\$&')).join('|') + ')', 'gi');
|
||
// only touch text outside tags
|
||
return html.replace(/(^|>)([^<]+)/g, (_, a, text) => a + text.replace(re, '<mark>$1</mark>'));
|
||
}
|
||
|
||
function formatBody(body) {
|
||
const parts = body.split(/(https?:\/\/[^\s<>"]+)/g);
|
||
return parts.map((p, i) => {
|
||
if (i % 2 === 1) {
|
||
const m = p.match(/^(.*?)([.,;:!?)\]]*)$/);
|
||
const url = m[1], trail = m[2];
|
||
return `<a href="${esc(url)}" target="_blank" rel="noopener">${esc(url.replace(/^https?:\/\/(www\.)?/, ''))}</a>${esc(trail)}`;
|
||
}
|
||
return esc(p).replace(/(^|[^&\w;])#([A-Za-z][\w-]*)/g, (_, a, t) => `${a}<button class="hashtag" data-tag="${esc(t.toLowerCase())}">#${esc(t)}</button>`);
|
||
}).join('');
|
||
}
|
||
|
||
const ICON = {
|
||
pin: '<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 17v5"/><path d="M9 10.8a2 2 0 0 1-1.1 1.8l-1.8.9A2 2 0 0 0 5 15.2V16a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1v-.8a2 2 0 0 0-1.1-1.8l-1.8-.9A2 2 0 0 1 15 10.8V7a1 1 0 0 1 1-1 2 2 0 0 0 0-4H8a2 2 0 0 0 0 4 1 1 0 0 1 1 1z"/></svg>',
|
||
copy: '<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="8" y="8" width="13" height="13" rx="2"/><path d="M4 16V5a2 2 0 0 1 2-2h11"/></svg>',
|
||
edit: '<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 20h9"/><path d="M16.4 3.6a2.1 2.1 0 1 1 3 3L7 19l-4 1 1-4Z"/></svg>',
|
||
bell: '<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M6 8a6 6 0 0 1 12 0c0 7 3 9 3 9H3s3-2 3-9"/><path d="M10.3 21a1.9 1.9 0 0 0 3.4 0"/></svg>',
|
||
move: '<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="4" width="18" height="17" rx="2"/><path d="M3 9h18M8 2v4M16 2v4M10 15h6M14 13l2 2-2 2"/></svg>',
|
||
plus: '<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="9"/><path d="M12 8v8M8 12h8"/></svg>',
|
||
folder: '<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M4 20h16a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z"/><path d="M12 10v6M9 13l3 3 3-3"/></svg>',
|
||
folderOut: '<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M4 20h16a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z"/><path d="M12 16v-6M9 13l3-3 3 3"/></svg>',
|
||
archive: '<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="2" y="3" width="20" height="5" rx="1"/><path d="M4 8v11a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8"/><path d="M10 12h4"/></svg>',
|
||
dots: '<svg width="15" height="15" viewBox="0 0 24 24" fill="currentColor"><circle cx="5" cy="12" r="2"/><circle cx="12" cy="12" r="2"/><circle cx="19" cy="12" r="2"/></svg>',
|
||
trash: '<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M3 6h18"/><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6"/><path d="M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/></svg>',
|
||
file: '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><path d="M14 2v6h6"/></svg>',
|
||
check: '<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="3.5" stroke-linecap="round" stroke-linejoin="round"><path d="M20 6 9 17l-5-5"/></svg>',
|
||
};
|
||
|
||
// ------------------------------------------------------------------
|
||
// Checklists: lines like "- [ ] milk" / "- [x] eggs" anywhere in a note.
|
||
// Stored as plain text, so every source (Hermes, iPhone, search) works.
|
||
// ------------------------------------------------------------------
|
||
const CHECK_RE = /^\s*[-*] \[([ xX])\] ?(.*)$/;
|
||
// "# Title", "## Section", "### Small" (a space after the #s, so #tags never match)
|
||
const HEAD_RE = /^(#{1,3}) (\S.*)$/;
|
||
// Entry stamps written by "Add to this note": "— Oct 4, 8:30 PM"
|
||
const STAMP_RE = /^(— [A-Z][a-z]{2} \d{1,2}, \d{1,2}:\d{2}\s?[AP]M)$/;
|
||
|
||
function checklistItems(body) {
|
||
return body.split('\n').map((l, i) => { const m = l.match(CHECK_RE); return m && { i, done: m[1] !== ' ', text: m[2] }; }).filter(Boolean);
|
||
}
|
||
|
||
function progressLabel(body) {
|
||
const items = checklistItems(body);
|
||
if (!items.length) return '';
|
||
return `<span class="progress">${items.filter((x) => x.done).length}/${items.length} done</span>`;
|
||
}
|
||
|
||
function renderBody(body) {
|
||
const out = [];
|
||
let text = [], block = null;
|
||
const flushText = () => {
|
||
const t = text.join('\n').replace(/^\n+|\n+$/g, '');
|
||
if (t) out.push(`<div>${formatBody(t)}</div>`);
|
||
text = [];
|
||
};
|
||
const flushBlock = () => { if (block) out.push(checklistHtml(block)); block = null; };
|
||
body.split('\n').forEach((line, i) => {
|
||
const m = line.match(CHECK_RE);
|
||
if (m) { flushText(); (block ||= []).push({ i, done: m[1] !== ' ', text: m[2] }); return; }
|
||
flushBlock();
|
||
const h = line.match(HEAD_RE);
|
||
if (h) { flushText(); out.push(`<div class="h${h[1].length}">${formatBody(h[2])}</div>`); return; }
|
||
const st = line.match(STAMP_RE);
|
||
if (st) { flushText(); out.push(`<div class="stamp">${esc(st[1])}</div>`); return; }
|
||
text.push(line);
|
||
});
|
||
flushText(); flushBlock();
|
||
return out.join('');
|
||
}
|
||
|
||
function checklistHtml(items) {
|
||
const row = (x) => `<label class="check-item${x.done ? ' done' : ''}"><input type="checkbox" data-check="${x.i}"${x.done ? ' checked' : ''}><span>${formatBody(x.text) || ' '}</span></label>`;
|
||
const open = items.filter((x) => !x.done), done = items.filter((x) => x.done);
|
||
return `<div class="checklist">${open.map(row).join('')}`
|
||
+ (done.length ? `<details class="check-done"${open.length ? '' : ' open'}><summary>${done.length} completed</summary>${done.map(row).join('')}</details>` : '')
|
||
+ `<input class="add-item" data-add-after="${items[items.length - 1].i}" placeholder="+ Add item" enterkeyhint="done"></div>`;
|
||
}
|
||
|
||
// Redraws replace the DOM; keep the cursor in an "+ Add item" box (and what's typed in it).
|
||
function withAddFocus(draw) {
|
||
const a = document.activeElement;
|
||
const SEL = '[data-add-after], [data-append], [data-add-inside]';
|
||
const info = a && a.matches && a.matches(SEL) ? (() => {
|
||
const card = a.closest('[data-id]');
|
||
return { id: card?.dataset.id, view: a.closest('#view-board') ? 'board' : 'feed', idx: [...card.querySelectorAll(SEL)].indexOf(a), value: a.value, caret: a.selectionStart };
|
||
})() : null;
|
||
draw();
|
||
const root = (info?.view === 'board') ? $('#view-board') : $('#feed');
|
||
if (!info) {
|
||
if (state.appendFocus) {
|
||
const ap = root?.querySelector('[data-append]');
|
||
if (ap) { state.appendFocus = false; ap.focus(); }
|
||
}
|
||
return;
|
||
}
|
||
const el = root?.querySelectorAll(`[data-id="${info.id}"] ${SEL.split(', ').join(`, [data-id="${info.id}"] `)}`)[info.idx];
|
||
if (el) { el.value = info.value; el.focus(); try { el.setSelectionRange(info.caret, info.caret); } catch {} }
|
||
}
|
||
|
||
// Change a note's text by applying `transform` to its current text. The write only
|
||
// lands if the note is unchanged since it was read; if Hermes or another device changed
|
||
// it meanwhile, the newest copy is fetched and the change re-applied to that, so their
|
||
// edit is never overwritten. transform returns null when the change no longer fits.
|
||
async function updateNoteBody(note, transform) {
|
||
let cur = note;
|
||
for (let attempt = 0; attempt < 3; attempt++) {
|
||
const body = transform(cur.body);
|
||
if (body == null) { toast('This note changed on another device, so that change wasn\'t applied. It\'s been refreshed.'); replaceNote(cur); return false; }
|
||
const old = { body: note.body, tags: note.tags };
|
||
Object.assign(note, { body, tags: localTags(body) }); rerender();
|
||
let q = sb.from('notes').update({ body }).eq('id', note.id);
|
||
if (cur.updated_at) q = q.eq('updated_at', cur.updated_at);
|
||
const { data, error } = await q.select();
|
||
if (error) { Object.assign(note, old); rerender(); toast('Couldn\'t save: ' + error.message); return false; }
|
||
if (data.length) { replaceNote(data[0]); scheduleTagRefresh(); return true; }
|
||
const { data: fresh, error: e2 } = await sb.from('notes').select(NOTE_SELECT).eq('id', note.id).maybeSingle();
|
||
Object.assign(note, old);
|
||
if (e2 || !fresh) { rerender(); toast(e2 ? 'Couldn\'t save: ' + e2.message : 'This note was deleted on another device.'); if (!e2) loadNotes(true); return false; }
|
||
cur = fresh; Object.assign(note, fresh);
|
||
}
|
||
toast('This note kept changing; try again in a moment.'); return false;
|
||
}
|
||
// The line to change, found again in a possibly newer copy: same position if it still
|
||
// reads the same, otherwise the first line that matches it exactly.
|
||
function findLine(lines, index, text) {
|
||
if (lines[index] === text) return index;
|
||
return lines.indexOf(text);
|
||
}
|
||
|
||
document.addEventListener('change', async (e) => {
|
||
const cb = e.target.closest('[data-check]');
|
||
if (!cb) return;
|
||
const note = findNote(cb.closest('[data-id]')?.dataset.id);
|
||
if (!note) return;
|
||
const i = +cb.dataset.check, line = note.body.split('\n')[i];
|
||
if (!CHECK_RE.test(line || '')) return;
|
||
const ok = await updateNoteBody(note, (body) => {
|
||
const lines = body.split('\n'), k = findLine(lines, i, line);
|
||
if (k < 0) return null;
|
||
lines[k] = lines[k].replace(/\[[ xX]\]/, cb.checked ? '[x]' : '[ ]');
|
||
return lines.join('\n');
|
||
});
|
||
if (!ok) return;
|
||
const items = checklistItems(note.body);
|
||
if (cb.checked && items.length && items.every((x) => x.done) && !note.archived_at) {
|
||
toast('All done ✓', 'Archive list', () => archiveNote(note, true), 6000);
|
||
}
|
||
});
|
||
|
||
document.addEventListener('keydown', async (e) => {
|
||
const ap = e.target.closest?.('[data-append]');
|
||
if (ap) {
|
||
if (e.key === 'Escape') { state.appending = null; rerender(); return; }
|
||
if (e.key === 'Enter' && !e.shiftKey && !e.isComposing && (e.metaKey || e.ctrlKey || !matchMedia('(hover: none)').matches)) {
|
||
e.preventDefault();
|
||
const note = findNote(ap.closest('[data-id]').dataset.id);
|
||
if (note) appendToNote(note, ap.value);
|
||
}
|
||
return;
|
||
}
|
||
const inside = e.target.closest?.('[data-add-inside]');
|
||
if (inside && e.key === 'Enter' && !e.isComposing) {
|
||
e.preventDefault();
|
||
const body = inside.value.trim();
|
||
if (!body) return;
|
||
const parentId = inside.closest('[data-id]').dataset.id;
|
||
inside.value = '';
|
||
const { error } = await sb.from('notes').insert({ body, parent_id: parentId });
|
||
if (error) { toast('Couldn\'t add: ' + error.message); inside.value = body; return; }
|
||
await loadChildren(parentId); scheduleTagRefresh(); rerender();
|
||
return;
|
||
}
|
||
const input = e.target.closest?.('[data-add-after]');
|
||
if (!input || e.key !== 'Enter' || e.isComposing) return;
|
||
e.preventDefault();
|
||
const text = input.value.trim();
|
||
if (!text) return;
|
||
const id = input.closest('[data-id]').dataset.id;
|
||
const note = findNote(id);
|
||
if (!note) return;
|
||
const after = +input.dataset.addAfter, anchor = note.body.split('\n')[after];
|
||
input.value = '';
|
||
const ok = await updateNoteBody(note, (body) => {
|
||
const lines = body.split('\n'), k = findLine(lines, after, anchor);
|
||
lines.splice(k < 0 ? lines.length : k + 1, 0, '- [ ] ' + text);
|
||
return lines.join('\n');
|
||
});
|
||
if (!ok) {
|
||
// Keep what was typed: put it back in that note's "+ Add item" box.
|
||
const box = document.querySelector(`[data-id="${id}"] [data-add-after]`);
|
||
if (box) { box.value = text; box.focus(); }
|
||
}
|
||
});
|
||
|
||
// Enter on a checklist line continues the list; Enter on an empty item ends it.
|
||
function continueChecklist(ta, e) {
|
||
if (e.key !== 'Enter' || e.shiftKey || e.isComposing || e.metaKey || e.ctrlKey) return false;
|
||
const v = ta.value, pos = ta.selectionStart;
|
||
if (pos !== ta.selectionEnd) return false;
|
||
const start = v.lastIndexOf('\n', pos - 1) + 1;
|
||
const m = v.slice(start, pos).match(/^(\s*[-*] \[[ xX]\] ?)(.*)$/);
|
||
if (!m) return false;
|
||
e.preventDefault();
|
||
if (!m[2].trim()) {
|
||
ta.value = v.slice(0, start) + v.slice(pos);
|
||
ta.setSelectionRange(start, start);
|
||
} else {
|
||
const ins = '\n- [ ] ';
|
||
ta.value = v.slice(0, pos) + ins + v.slice(pos);
|
||
ta.setSelectionRange(pos + ins.length, pos + ins.length);
|
||
}
|
||
ta.dispatchEvent(new Event('input'));
|
||
return true;
|
||
}
|
||
|
||
// The "⋯" menu: everything except Pin and Edit. Items reuse the same data-act
|
||
// handlers as the old buttons; the menu lives inside the note card.
|
||
function noteMenuHtml(n, compact) {
|
||
const item = (act, icon, label, cls = '') => `<button role="menuitem" class="${cls}" data-act="${act}">${icon}<span>${label}</span></button>`;
|
||
return `<div class="note-menu" role="menu">
|
||
${item('copy', ICON.copy, 'Copy text')}
|
||
${compact ? '' : item('remind', ICON.bell, 'Remind me')}
|
||
${item('append', ICON.plus, 'Add to this note')}
|
||
${n.parent_id ? item('take-out', ICON.folderOut, 'Take out of folder note') : (compact || state.childCounts[n.id]) ? '' : item('move', ICON.folder, 'Move into a note…')}
|
||
${item('archive', ICON.archive, n.archived_at ? 'Unarchive' : 'Archive')}
|
||
${item('delete', ICON.trash, 'Delete', 'danger')}
|
||
</div>`;
|
||
}
|
||
function closeNoteMenu() {
|
||
document.querySelectorAll('.note-menu').forEach((m) => m.remove());
|
||
document.querySelectorAll('[data-act="menu"][aria-expanded="true"]').forEach((b) => b.setAttribute('aria-expanded', 'false'));
|
||
}
|
||
document.addEventListener('keydown', (e) => { if (e.key === 'Escape' && document.querySelector('.note-menu')) closeNoteMenu(); });
|
||
document.addEventListener('scroll', () => { if (document.querySelector('.note-menu')) closeNoteMenu(); }, { passive: true, capture: true });
|
||
|
||
function noteHtml(n, compact = false, child = false) {
|
||
if (state.editing === n.id) {
|
||
return `<div class="note edit-box" data-id="${n.id}">
|
||
<textarea class="field" id="edit-text">${esc(state.editDraft ?? n.body)}</textarea>
|
||
<div class="row"><button class="btn ghost small" data-act="cancel">Cancel</button><button class="btn small" data-act="save">Save</button></div>
|
||
</div>`;
|
||
}
|
||
const inBody = new Set(localTags(n.body));
|
||
const extra = (n.tags || []).filter((t) => !inBody.has(t));
|
||
const att = (n.attachments || []).map((a) => /^image\//.test(a.type)
|
||
? `<img data-path="${esc(a.path)}" alt="${esc(a.name)}" loading="lazy" data-act="zoom">`
|
||
: `<a class="file" data-path="${esc(a.path)}" target="_blank" rel="noopener">${ICON.file}${esc(a.name)}</a>`).join('');
|
||
return `<article class="note${n.pinned ? ' pinned' : ''}${n._queued ? ' queued' : ''}" data-id="${n.id}">
|
||
${(() => {
|
||
// Long notes fold to a preview (not while searching, so matches stay visible).
|
||
const compact = lsGet(LS.density, 'comfortable') === 'compact';
|
||
const long = !state.query && state.appending !== n.id && (compact ? n.body.length > 320 || n.body.split('\n').length > 5 : n.body.length > 900 || n.body.split('\n').length > 14);
|
||
const open = state.openBodies.has(n.id);
|
||
return `<div class="note-body${long && !open ? ' folded' : ''}">${highlight(renderBody(n.body))}</div>`
|
||
+ (long ? `<button class="more-btn" data-act="more">${open ? 'Show less' : 'Show more'}</button>` : '');
|
||
})()}
|
||
${state.appending === n.id ? `<div class="append-box">
|
||
<textarea class="field" data-append placeholder="Add to this note…">${esc(state.appendDraft || '')}</textarea>
|
||
<div class="row"><button class="btn ghost small" data-act="append-cancel">Cancel</button><button class="btn small" data-act="append-save">Add</button></div>
|
||
</div>` : ''}
|
||
${extra.length ? `<div class="extra-tags">${extra.map((t) => `<button class="hashtag" data-tag="${esc(t)}">#${esc(t)}</button>`).join('')}</div>` : ''}
|
||
${att ? `<div class="attach">${att}</div>` : ''}
|
||
<div class="note-meta">
|
||
<span>${compact ? dayLabel(n.created_at) + ' · ' : ''}${timeLabel(n.created_at)}</span>
|
||
${n.source && n.source !== 'web' ? `<span class="src">${esc(n.source)}</span>` : ''}
|
||
${n._queued ? '<span class="src">waiting to sync</span>' : ''}
|
||
${n.pinned ? `<span style="color:var(--accent)">${ICON.pin}</span>` : ''}
|
||
${n.archived_at ? '<span class="src">archived</span>' : ''}
|
||
${progressLabel(n.body)}
|
||
${n.parent_id && !child ? `<button class="in-parent" data-act="open-parent" data-parent="${n.parent_id}">in: ${esc(state.parentTitles[n.parent_id] || 'another note')}</button>` : ''}
|
||
${!child && !compact && state.childCounts[n.id] ? `<button class="kids-btn" data-act="toggle-kids">${state.expanded.has(n.id) ? '▾' : '▸'} ${state.childCounts[n.id]} inside</button>` : ''}
|
||
<span class="spacer"></span>
|
||
<span class="note-actions">
|
||
<button class="tool${n.pinned ? ' pin-on' : ''}" data-act="pin" title="${n.pinned ? 'Unpin' : 'Pin'}">${ICON.pin}</button>
|
||
<button class="tool" data-act="edit" title="Edit">${ICON.edit}</button>
|
||
<button class="tool" data-act="menu" title="More" aria-haspopup="menu" aria-expanded="false">${ICON.dots}</button>
|
||
</span>
|
||
</div>
|
||
${!child && !compact && state.expanded.has(n.id) ? `<div class="children">
|
||
${(state.children[n.id] || []).map((c) => noteHtml(c, true, true)).join('')}
|
||
<input class="field add-inside" data-add-inside placeholder="+ New note inside… (Enter to add)" enterkeyhint="done">
|
||
</div>` : ''}
|
||
</article>`;
|
||
}
|
||
|
||
// While a note is being edited, keep what's typed so a redraw can't wipe it.
|
||
function captureEditDraft() {
|
||
const et = document.getElementById('edit-text');
|
||
if (et && state.editing) state.editDraft = et.value;
|
||
}
|
||
|
||
function renderFeed() {
|
||
captureEditDraft();
|
||
const feed = $('#feed');
|
||
if (!state.notes.length) {
|
||
const filtered = state.tag || state.pinned || state.todo || state.query;
|
||
feed.innerHTML = state.loading ? '' : state.archived && !filtered
|
||
? '<div class="empty"><strong>No archived notes</strong>Use the box icon on a note to archive it. It leaves your feed but stays searchable.</div>'
|
||
: `<div class="empty"><strong>${filtered ? 'Nothing matches' : esc(currentSeason()?.empty || 'Your feed is empty')}</strong>${filtered ? 'Try a different search or tag.' : 'Type a thought above and hit Enter. Add #tags to file it.'}</div>`;
|
||
} else {
|
||
let html = '', lastDay = '';
|
||
for (const n of state.notes) {
|
||
const d = dayLabel(n.created_at);
|
||
if (d !== lastDay) { html += `<div class="day">${esc(d)}</div>`; lastDay = d; }
|
||
html += noteHtml(n);
|
||
}
|
||
withAddFocus(() => { feed.innerHTML = html; });
|
||
hydrateAttachments(feed);
|
||
}
|
||
$('#load-more').classList.toggle('hidden', !state.hasMore);
|
||
renderStatus();
|
||
}
|
||
|
||
function renderStatus(loading) {
|
||
const el = $('#status-line'); if (!el) return;
|
||
const bits = [];
|
||
if (loading) bits.push('<span class="spinner"></span>');
|
||
if (!navigator.onLine) bits.push('<span class="offline-pill">Offline</span>');
|
||
const q = lsGet(LS.queue, []).length;
|
||
if (q) bits.push(`${q} note${q > 1 ? 's' : ''} waiting to sync`);
|
||
if (state.tag) bits.push(`Showing <button class="hashtag" data-tag="${esc(state.tag)}">#${esc(state.tag)}</button> <button class="btn ghost small" data-act="clear">Clear</button>`);
|
||
else if (state.pinned) bits.push('Showing pinned notes <button class="btn ghost small" data-act="clear">Clear</button>');
|
||
else if (state.todo) bits.push('Showing to-dos: #todo notes and open checklists <button class="btn ghost small" data-act="clear">Clear</button>');
|
||
else if (state.archived) bits.push('Showing archived notes <button class="btn ghost small" data-act="clear">Clear</button>');
|
||
if (state.query && !loading) bits.push(`${state.notes.length}${state.hasMore ? '+' : ''} result${state.notes.length === 1 ? '' : 's'}`);
|
||
el.innerHTML = bits.join(' ');
|
||
el.classList.toggle('hidden', !bits.length);
|
||
}
|
||
|
||
// Tag bar: "full" (filters + every tag), "filters" (All / Pinned / To-do / Archived only)
|
||
// or "hidden" (no bar; the feed uses the full width). Per device, like the theme.
|
||
const TAGBAR_MODES = ['full', 'filters', 'hidden'];
|
||
const TAGBAR_LABELS = { full: 'Full', filters: 'Filters only', hidden: 'Hidden' };
|
||
function tagBarMode() { const m = lsGet(LS.tagbar, 'full'); return TAGBAR_MODES.includes(m) ? m : 'full'; }
|
||
// Layout density, per device: "comfortable" cards or a "compact" list.
|
||
function applyDensity() {
|
||
const c = lsGet(LS.density, 'comfortable') === 'compact';
|
||
document.documentElement.classList.toggle('compact', c);
|
||
const l = $('#density-label'); if (l) l.textContent = c ? 'Compact' : 'Comfortable';
|
||
}
|
||
|
||
function applyTagBar() {
|
||
const show = state.view === 'feed' && tagBarMode() !== 'hidden';
|
||
$('#aside').classList.toggle('hidden', !show);
|
||
$('#main').classList.toggle('wide', !show);
|
||
$('#aside h3').textContent = tagBarMode() === 'filters' ? 'Filters' : 'Tags';
|
||
const l = $('#tagbar-label'); if (l) l.textContent = TAGBAR_LABELS[tagBarMode()];
|
||
}
|
||
|
||
function renderTags() {
|
||
const total = state.tags.reduce((a, t) => a + Number(t.count), 0);
|
||
let html = `<button class="tag-item${!state.tag && !state.pinned && !state.archived && !state.todo ? ' active' : ''}" data-filter="all"><span>All notes</span></button>`;
|
||
html += `<button class="tag-item${state.pinned ? ' active' : ''}" data-filter="pinned"><span>Pinned</span></button>`;
|
||
html += `<button class="tag-item${state.todo ? ' active' : ''}" data-filter="todo"><span>To-do</span></button>`;
|
||
html += `<button class="tag-item${state.archived ? ' active' : ''}" data-filter="archived"><span>Archived</span>${state.archivedCount ? `<span class="n">${state.archivedCount}</span>` : ''}</button>`;
|
||
html += `<button class="tag-item" data-review><span>Review…</span></button>`;
|
||
for (const t of tagBarMode() === 'full' ? state.tags : []) {
|
||
html += `<button class="tag-item${state.tag === t.tag ? ' active' : ''}" data-tag="${esc(t.tag)}"><span>#${esc(t.tag)}</span><span class="n">${t.count}</span></button>`;
|
||
}
|
||
$('#tag-list').innerHTML = html;
|
||
if (state.view === 'board' && state.boardPicking) renderBoard();
|
||
}
|
||
|
||
// ------------------------------------------------------------------
|
||
// Tag suggestions: typing "#" in a note field lists matching tags,
|
||
// most-used first. Arrows move, Enter/Tab picks, Esc closes.
|
||
// ------------------------------------------------------------------
|
||
const TagAC = (() => {
|
||
const FIELDS = '#compose, #edit-text, [data-append], [data-add-after], [data-add-inside], #search';
|
||
let box = null, field = null, items = [], sel = 0, moved = false, start = 0;
|
||
|
||
function tokenAt(el) {
|
||
const pos = el.selectionStart, end = el.selectionEnd;
|
||
if (pos == null || pos !== end) return null;
|
||
const m = el.value.slice(0, pos).match(/(^|[^&\w])#([A-Za-z][\w-]*)?$/);
|
||
if (!m) return null;
|
||
const after = el.value.slice(pos);
|
||
if (/^[\w-]/.test(after)) return null; // caret is in the middle of a word
|
||
return { start: pos - (m[2] || '').length - 1, partial: (m[2] || '').toLowerCase() };
|
||
}
|
||
function matches(partial) {
|
||
const score = (t) => t.tag.startsWith(partial) ? 0 : t.tag.includes(partial) ? 1 : 2;
|
||
return (state.tags || []).filter((t) => score(t) < 2)
|
||
.sort((a, b) => score(a) - score(b) || Number(b.count) - Number(a.count) || a.tag.localeCompare(b.tag))
|
||
.slice(0, 6);
|
||
}
|
||
// Where the caret sits on screen, measured with a hidden copy of the field.
|
||
function caretRect(el, idx) {
|
||
const r = el.getBoundingClientRect();
|
||
if (el.tagName !== 'TEXTAREA') return { left: r.left + 8, top: r.bottom };
|
||
const cs = getComputedStyle(el), m = document.createElement('div');
|
||
for (const k of ['boxSizing', 'width', 'paddingTop', 'paddingRight', 'paddingBottom', 'paddingLeft', 'borderTopWidth', 'borderRightWidth', 'borderBottomWidth', 'borderLeftWidth', 'fontFamily', 'fontSize', 'fontWeight', 'lineHeight', 'letterSpacing', 'tabSize']) m.style[k] = cs[k];
|
||
Object.assign(m.style, { position: 'fixed', visibility: 'hidden', whiteSpace: 'pre-wrap', overflowWrap: 'break-word', left: r.left + 'px', top: r.top + 'px' });
|
||
m.textContent = el.value.slice(0, idx);
|
||
const mark = document.createElement('span'); mark.textContent = '#'; m.appendChild(mark);
|
||
document.body.appendChild(m);
|
||
const mr = mark.getBoundingClientRect(); m.remove();
|
||
return { left: mr.left, top: Math.min(mr.bottom - el.scrollTop, r.bottom) + 4 };
|
||
}
|
||
function close() { box?.remove(); box = null; field = null; items = []; }
|
||
function draw() {
|
||
if (!box) { box = document.createElement('div'); box.className = 'tag-ac'; box.setAttribute('role', 'listbox'); document.body.appendChild(box);
|
||
box.addEventListener('pointerdown', (e) => { e.preventDefault(); const b = e.target.closest('button'); if (b) pick(Number(b.dataset.i)); }); }
|
||
const tok = tokenAt(field);
|
||
box.innerHTML = items.map((t, i) => {
|
||
const k = t.tag.indexOf(tok.partial);
|
||
const label = tok.partial && k >= 0 ? esc(t.tag.slice(0, k)) + '<b>' + esc(t.tag.slice(k, k + tok.partial.length)) + '</b>' + esc(t.tag.slice(k + tok.partial.length)) : esc(t.tag);
|
||
return `<button type="button" role="option" data-i="${i}" class="${i === sel ? 'on' : ''}"><span class="t">#${label}</span><span class="n">${t.count}</span></button>`;
|
||
}).join('');
|
||
const c = caretRect(field, start);
|
||
const w = box.offsetWidth, h = box.offsetHeight;
|
||
const left = Math.max(8, Math.min(c.left, innerWidth - w - 8));
|
||
const top = c.top + h > innerHeight - 8 ? Math.max(8, c.top - h - 28) : c.top;
|
||
box.style.left = left + 'px'; box.style.top = top + 'px';
|
||
}
|
||
function update(el) {
|
||
const tok = el && el.matches?.(FIELDS) ? tokenAt(el) : null;
|
||
if (!tok) return close();
|
||
const found = matches(tok.partial);
|
||
if (!found.length) return close();
|
||
if (field !== el || start !== tok.start) { sel = 0; moved = false; }
|
||
field = el; start = tok.start; items = found; sel = Math.min(sel, items.length - 1);
|
||
draw();
|
||
}
|
||
function pick(i) {
|
||
const t = items[i]; if (!t || !field) return;
|
||
const el = field, pos = el.selectionStart, v = el.value;
|
||
const space = /^\s/.test(v.slice(pos)) ? '' : ' ';
|
||
el.value = v.slice(0, start) + '#' + t.tag + space + v.slice(pos);
|
||
const caret = start + 1 + t.tag.length + space.length;
|
||
el.setSelectionRange(caret, caret);
|
||
close();
|
||
el.dispatchEvent(new Event('input', { bubbles: true }));
|
||
}
|
||
document.addEventListener('input', (e) => { if (!e.isComposing) update(e.target); }, true);
|
||
document.addEventListener('click', (e) => { if (!box?.contains(e.target)) update(e.target); }, true);
|
||
document.addEventListener('focusout', (e) => { if (e.target === field) close(); }, true);
|
||
addEventListener('resize', close);
|
||
document.addEventListener('scroll', (e) => { if (box && e.target !== field) close(); }, true);
|
||
// Capture phase so these keys don't also save the note.
|
||
document.addEventListener('keydown', (e) => {
|
||
if (!box || e.target !== field || e.isComposing) return;
|
||
const stop = () => { e.preventDefault(); e.stopImmediatePropagation(); };
|
||
if (e.key === 'ArrowDown') { stop(); sel = (sel + 1) % items.length; moved = true; draw(); }
|
||
else if (e.key === 'ArrowUp') { stop(); sel = (sel - 1 + items.length) % items.length; moved = true; draw(); }
|
||
else if (e.key === 'Escape') { stop(); close(); }
|
||
// With only "#" typed, Enter keeps its normal job unless a tag was arrowed to.
|
||
else if (e.key === 'Tab' || (e.key === 'Enter' && !e.shiftKey && !e.metaKey && !e.ctrlKey && (tokenAt(field)?.partial || moved))) { stop(); pick(sel); }
|
||
else if (['ArrowLeft', 'ArrowRight', 'Home', 'End'].includes(e.key)) setTimeout(() => update(field), 0);
|
||
}, true);
|
||
return { close };
|
||
})();
|
||
|
||
// ------------------------------------------------------------------
|
||
// Composer
|
||
// ------------------------------------------------------------------
|
||
const compose = $('#compose');
|
||
function autosize() { compose.style.height = 'auto'; compose.style.height = Math.min(compose.scrollHeight, 320) + 'px'; }
|
||
compose.addEventListener('input', autosize);
|
||
compose.addEventListener('keydown', (e) => {
|
||
if (continueChecklist(compose, e)) return;
|
||
if (e.key === 'Enter' && (e.metaKey || e.ctrlKey)) { e.preventDefault(); submitCompose(); return; }
|
||
if (e.key === 'Enter' && !e.shiftKey && !e.isComposing && !matchMedia('(hover: none)').matches) { e.preventDefault(); submitCompose(); }
|
||
});
|
||
// Heading button: "# " on the current line; again for "## ", again to remove.
|
||
$('#heading-btn').onclick = () => {
|
||
const v = compose.value, pos = compose.selectionStart ?? v.length;
|
||
const start = v.lastIndexOf('\n', pos - 1) + 1;
|
||
const end = v.indexOf('\n', start) === -1 ? v.length : v.indexOf('\n', start);
|
||
const line = v.slice(start, end);
|
||
const next = /^# /.test(line) ? line.replace(/^# /, '## ') : /^## /.test(line) ? line.replace(/^## /, '') : '# ' + line;
|
||
compose.value = v.slice(0, start) + next + v.slice(end);
|
||
const caret = start + next.length;
|
||
compose.focus(); compose.setSelectionRange(caret, caret); autosize();
|
||
};
|
||
$('#list-btn').onclick = () => {
|
||
const v = compose.value;
|
||
const prefix = !v ? '- [ ] ' : (v.endsWith('\n') ? '' : '\n') + '- [ ] ';
|
||
compose.value = v + prefix;
|
||
compose.focus();
|
||
compose.setSelectionRange(compose.value.length, compose.value.length);
|
||
autosize();
|
||
};
|
||
if (matchMedia('(hover: none)').matches) $('#compose-hint').classList.add('hidden');
|
||
|
||
// Phones: keep the composer one line tall until it's used. It stays open while it has
|
||
// text, files, a reminder being set or dictation running.
|
||
const composerEl = $('#composer');
|
||
function composerIdle() { return !compose.value.trim() && !state.files.length && !state.remindMode && !Dictation.active; }
|
||
function collapseComposer() { if (composerIdle()) composerEl.classList.add('collapsed'); }
|
||
composerEl.addEventListener('focusin', () => composerEl.classList.remove('collapsed'));
|
||
composerEl.addEventListener('pointerdown', () => composerEl.classList.remove('collapsed'));
|
||
// Collapse when you tap somewhere else (not on blur: tapping a toolbar button blurs the box first).
|
||
document.addEventListener('pointerdown', (e) => { if (!composerEl.contains(e.target)) collapseComposer(); });
|
||
setTimeout(collapseComposer, 0); // after the rest of the script (Dictation) has loaded
|
||
|
||
// ------------------------------------------------------------------
|
||
// Dictation: the mic button types what you say into the composer, using the
|
||
// browser's own speech recognition (Chrome sends audio to Google, Safari to
|
||
// Apple). Nothing is recorded or stored; the words are yours to edit before
|
||
// saving. Say "hashtag groceries" for #groceries and "new line" for a line break.
|
||
// ------------------------------------------------------------------
|
||
const Dictation = (() => {
|
||
const SR = window.SpeechRecognition || window.webkitSpeechRecognition;
|
||
const btn = $('#mic-btn');
|
||
let rec = null, base = '', tail = '', active = false;
|
||
if (!SR) return { stop() {}, get active() { return false; } };
|
||
btn.classList.remove('hidden');
|
||
|
||
// Spoken commands and tidy-up for one chunk of recognized speech.
|
||
function clean(text, before) {
|
||
let t = text
|
||
.replace(/\b(?:hash ?tag|hash) ([A-Za-z][\w-]*)/gi, (_, w) => '#' + w.toLowerCase())
|
||
.replace(/\s*\bnew (?:line|paragraph)\b\s*/gi, '\n')
|
||
.replace(/[ \t]+/g, ' ');
|
||
const startOfSentence = !before.trim() || /[\n.!?]\s*$/.test(before);
|
||
if (startOfSentence) t = t.replace(/^\s*([a-z])/, (_, c) => c.toUpperCase());
|
||
return t.replace(/\n([a-z])/g, (_, c) => '\n' + c.toUpperCase());
|
||
}
|
||
function render(finals, interim) {
|
||
const sep = base && !/\s$/.test(base) ? ' ' : '';
|
||
const said = clean((finals + ' ' + interim).trim(), base);
|
||
compose.value = base + (said ? sep + said : '') + tail;
|
||
const caret = (base + sep + said).length;
|
||
compose.setSelectionRange(caret, caret);
|
||
autosize();
|
||
}
|
||
function setUi(on) {
|
||
active = on;
|
||
btn.classList.toggle('listening', on);
|
||
btn.title = on ? 'Stop dictating' : 'Dictate a note';
|
||
btn.setAttribute('aria-pressed', on ? 'true' : 'false');
|
||
compose.placeholder = on ? 'Listening… tap the mic to stop' : (state.remindMode ? 'Remind me to…' : 'What\'s on your mind? Use #tags to file it…');
|
||
}
|
||
function start() {
|
||
const pos = compose.selectionStart ?? compose.value.length;
|
||
base = compose.value.slice(0, pos); tail = compose.value.slice(pos);
|
||
rec = new SR();
|
||
rec.lang = navigator.language || 'en-US';
|
||
rec.continuous = true; rec.interimResults = true;
|
||
rec.onresult = (e) => {
|
||
let finals = '', interim = '';
|
||
for (let k = 0; k < e.results.length; k++) {
|
||
const r = e.results[k];
|
||
if (r.isFinal) finals += r[0].transcript + ' '; else interim += r[0].transcript;
|
||
}
|
||
render(finals, interim);
|
||
};
|
||
rec.onerror = (e) => {
|
||
const msg = {
|
||
'not-allowed': 'Microphone access is blocked. Allow it for this site in your browser settings.',
|
||
'service-not-allowed': 'Dictation isn\'t available here. On iPhone, tap the 🎤 on the keyboard instead.',
|
||
'no-speech': 'Didn\'t catch anything. Tap the mic and try again.',
|
||
'audio-capture': 'No microphone found.',
|
||
network: 'Dictation needs an internet connection.',
|
||
}[e.error];
|
||
if (msg) toast(msg);
|
||
};
|
||
rec.onend = () => { setUi(false); rec = null; compose.focus(); };
|
||
try { rec.start(); setUi(true); compose.focus(); } catch { toast('Couldn\'t start dictation.'); }
|
||
}
|
||
// stop(): finish the current phrase. stop(true): cut off now and ignore any late
|
||
// results (used when the note is being saved, so words can't reappear afterward).
|
||
function stop(now = false) {
|
||
if (!rec) return;
|
||
if (now) { rec.onresult = null; try { rec.abort(); } catch {} setUi(false); rec = null; return; }
|
||
try { rec.stop(); } catch {}
|
||
}
|
||
btn.onclick = () => (active ? stop() : start());
|
||
return { stop, get active() { return active; } };
|
||
})();
|
||
$('#send-btn').onclick = submitCompose;
|
||
$('#attach-btn').onclick = () => $('#file-input').click();
|
||
$('#file-input').onchange = (e) => { state.files.push(...e.target.files); e.target.value = ''; renderPendingFiles(); };
|
||
compose.addEventListener('paste', (e) => {
|
||
const files = [...(e.clipboardData?.files || [])];
|
||
if (files.length) { e.preventDefault(); state.files.push(...files); renderPendingFiles(); }
|
||
});
|
||
$('#composer').addEventListener('dragover', (e) => e.preventDefault());
|
||
$('#composer').addEventListener('drop', (e) => {
|
||
e.preventDefault();
|
||
const files = [...(e.dataTransfer?.files || [])];
|
||
if (files.length) { state.files.push(...files); renderPendingFiles(); }
|
||
});
|
||
function renderPendingFiles() {
|
||
$('#pending-files').innerHTML = state.files.map((f, i) => `<span class="chip">${ICON.file} ${esc(f.name)} <button data-rm="${i}" aria-label="Remove">×</button></span>`).join('');
|
||
}
|
||
$('#pending-files').onclick = (e) => { const i = e.target.dataset.rm; if (i != null) { state.files.splice(+i, 1); renderPendingFiles(); } };
|
||
|
||
$('#remind-btn').onclick = () => setRemindMode(!state.remindMode);
|
||
// ------------------------------------------------------------------
|
||
// Date picker for "Specific dates" reminders (composer and edit form)
|
||
// ------------------------------------------------------------------
|
||
function dpState(id, seed) {
|
||
if (!state.dp[id]) {
|
||
const days = new Set(seed?.days || []);
|
||
const first = seed?.days?.length ? keyToDate([...days].sort()[0]) : new Date();
|
||
state.dp[id] = { month: new Date(first.getFullYear(), first.getMonth(), 1), days, time: seed?.time || '09:00' };
|
||
}
|
||
return state.dp[id];
|
||
}
|
||
|
||
function datePickerHtml(id) {
|
||
const st = dpState(id), m = st.month, todayKey = dayKey(new Date());
|
||
const lead = new Date(m.getFullYear(), m.getMonth(), 1).getDay();
|
||
const days = new Date(m.getFullYear(), m.getMonth() + 1, 0).getDate();
|
||
let cells = ['S', 'M', 'T', 'W', 'T', 'F', 'S'].map((d) => `<span class="dow">${d}</span>`).join('');
|
||
for (let i = 0; i < lead; i++) cells += '<button class="blank" tabindex="-1"></button>';
|
||
for (let d = 1; d <= days; d++) {
|
||
const k = dayKey(new Date(m.getFullYear(), m.getMonth(), d));
|
||
cells += `<button type="button" data-dp-day="${k}" class="${st.days.has(k) ? 'on' : ''}${k < todayKey ? ' past' : ''}">${d}</button>`;
|
||
}
|
||
const picked = [...st.days].sort();
|
||
return `<div class="dp" data-dp="${id}">
|
||
<div class="dp-head"><button type="button" data-dp-nav="-1" aria-label="Previous month">‹</button><span>${esc(m.toLocaleDateString(undefined, { month: 'long', year: 'numeric' }))}</span><button type="button" data-dp-nav="1" aria-label="Next month">›</button></div>
|
||
<div class="dp-grid">${cells}</div>
|
||
<div class="dp-foot">at <input class="field" type="time" data-dp-time value="${esc(st.time)}">
|
||
<span>${picked.length ? `${picked.length} date${picked.length > 1 ? 's' : ''}: ${picked.map((k) => keyToDate(k).toLocaleDateString(undefined, { month: 'short', day: 'numeric' })).join(', ')}` : 'Tap days to pick them'}</span></div>
|
||
</div>`;
|
||
}
|
||
|
||
function datesFromPicker(id) {
|
||
const st = dpState(id);
|
||
const [hh, mm] = (st.time || '09:00').split(':').map(Number);
|
||
const dates = [...st.days].sort().map((k) => { const d = keyToDate(k); d.setHours(hh, mm, 0, 0); return d; });
|
||
if (!dates.length) return { error: 'Pick at least one date' };
|
||
const due = dates.find((d) => d > new Date());
|
||
if (!due) return { error: 'Pick at least one date in the future' };
|
||
return { dates, due };
|
||
}
|
||
|
||
function renderDatePicker(id) {
|
||
const host = id === 'compose' ? $('#compose-dates') : document.querySelector(`[data-dp-host="${id}"]`);
|
||
if (host) host.innerHTML = datePickerHtml(id);
|
||
}
|
||
|
||
document.addEventListener('click', (e) => {
|
||
const dp = e.target.closest('[data-dp]');
|
||
if (!dp) return;
|
||
const id = dp.dataset.dp, st = dpState(id);
|
||
const day = e.target.closest('[data-dp-day]');
|
||
const nav = e.target.closest('[data-dp-nav]');
|
||
if (day) { e.preventDefault(); const k = day.dataset.dpDay; st.days.has(k) ? st.days.delete(k) : st.days.add(k); renderDatePicker(id); }
|
||
else if (nav) { e.preventDefault(); st.month = new Date(st.month.getFullYear(), st.month.getMonth() + +nav.dataset.dpNav, 1); renderDatePicker(id); }
|
||
});
|
||
document.addEventListener('change', (e) => {
|
||
const t = e.target.closest('[data-dp-time]');
|
||
if (t) dpState(t.closest('[data-dp]').dataset.dp).time = t.value;
|
||
});
|
||
|
||
function syncRepeatUi() {
|
||
const dates = $('#remind-repeat').value === 'dates';
|
||
$('#remind-at').classList.toggle('hidden', dates);
|
||
document.querySelectorAll('#remind-row [data-quick]').forEach((b) => b.classList.toggle('hidden', dates));
|
||
$('#compose-dates').classList.toggle('hidden', !dates);
|
||
if (dates) renderDatePicker('compose');
|
||
}
|
||
$('#remind-repeat').addEventListener('change', syncRepeatUi);
|
||
|
||
function setRemindMode(on) {
|
||
state.remindMode = on;
|
||
$('#remind-btn').classList.toggle('on', on);
|
||
$('#remind-row').classList.toggle('hidden', !on);
|
||
$('#send-btn').textContent = on ? 'Set reminder' : 'Save';
|
||
compose.placeholder = on ? 'Remind me to…' : 'What\'s on your mind? Use #tags to file it…';
|
||
if (on && !$('#remind-at').value) setQuick('1h');
|
||
compose.focus();
|
||
}
|
||
function toLocalInput(d) {
|
||
const p = (x) => String(x).padStart(2, '0');
|
||
return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())}T${p(d.getHours())}:${p(d.getMinutes())}`;
|
||
}
|
||
function setQuick(k) {
|
||
const d = new Date();
|
||
if (k === '1h') { d.setHours(d.getHours() + 1); d.setSeconds(0); }
|
||
else if (k === 'tonight') { d.setHours(20, 0, 0, 0); if (d < new Date()) d.setDate(d.getDate() + 1); }
|
||
else if (k === 'tomorrow') { d.setDate(d.getDate() + 1); d.setHours(9, 0, 0, 0); }
|
||
else if (k === 'monday') { d.setDate(d.getDate() + ((8 - d.getDay()) % 7 || 7)); d.setHours(9, 0, 0, 0); }
|
||
$('#remind-at').value = toLocalInput(d);
|
||
}
|
||
$('#remind-row').addEventListener('click', (e) => { const k = e.target.dataset.quick; if (k) { e.preventDefault(); setQuick(k); } });
|
||
|
||
async function submitCompose() {
|
||
Dictation.stop(true);
|
||
const body = compose.value.trim();
|
||
if (!body && !state.files.length) return;
|
||
if (state.remindMode && $('#remind-repeat').value === 'dates') {
|
||
const r = datesFromPicker('compose');
|
||
if (r.error) { toast(r.error); return; }
|
||
const { error } = await sb.from('reminders').insert({ body: body || 'Reminder', due_at: r.due.toISOString(), repeat: 'dates', dates: r.dates.map((d) => d.toISOString()) });
|
||
if (error) { toast('Couldn\'t save reminder: ' + error.message); return; }
|
||
toast(`Reminder set for ${r.dates.length} date${r.dates.length > 1 ? 's' : ''}. Next: ${whenLabel(r.due)}`);
|
||
compose.value = ''; $('#remind-repeat').value = ''; delete state.dp.compose; syncRepeatUi(); setRemindMode(false); autosize();
|
||
loadReminders();
|
||
return;
|
||
}
|
||
if (state.remindMode) {
|
||
const at = $('#remind-at').value;
|
||
if (!at) { toast('Pick a time for the reminder.'); return; }
|
||
const due = new Date(at);
|
||
const { error } = await sb.from('reminders').insert({ body: body || 'Reminder', due_at: due.toISOString(), repeat: $('#remind-repeat').value || null });
|
||
if (error) { toast('Couldn\'t save reminder: ' + error.message); return; }
|
||
toast('Reminder set for ' + whenLabel(due));
|
||
compose.value = ''; $('#remind-repeat').value = ''; $('#remind-at').value = ''; setRemindMode(false); autosize();
|
||
loadReminders();
|
||
return;
|
||
}
|
||
if (!navigator.onLine && state.files.length) {
|
||
toast('You\'re offline. Notes with files wait here until you\'re back online (or remove the files to save just the text).');
|
||
return;
|
||
}
|
||
const files = state.files; state.files = []; renderPendingFiles();
|
||
compose.value = ''; autosize();
|
||
if (!(await addNote(body, files))) {
|
||
// Put the draft back, keeping anything typed since.
|
||
compose.value = compose.value.trim() ? body + '\n\n' + compose.value : body;
|
||
state.files = files.concat(state.files); renderPendingFiles(); autosize();
|
||
}
|
||
}
|
||
|
||
// ------------------------------------------------------------------
|
||
// Note actions (event delegation)
|
||
// ------------------------------------------------------------------
|
||
document.addEventListener('click', async (e) => {
|
||
const inMenu = e.target.closest('.note-menu');
|
||
const opener = e.target.closest('[data-act="menu"]');
|
||
// A click outside closes the menu now; a menu item's click is handled first (it needs to
|
||
// know which note it's in), then the menu closes.
|
||
if (!opener && document.querySelector('.note-menu')) { if (inMenu) setTimeout(closeNoteMenu, 0); else closeNoteMenu(); }
|
||
if (opener) {
|
||
const card = opener.closest('[data-id]'), wasOpen = opener.getAttribute('aria-expanded') === 'true';
|
||
closeNoteMenu();
|
||
if (!wasOpen) {
|
||
const n = findNote(card.dataset.id); if (!n) return;
|
||
card.insertAdjacentHTML('beforeend', noteMenuHtml(n, !!card.closest('#view-board, #view-calendar, .children')));
|
||
opener.setAttribute('aria-expanded', 'true');
|
||
const m = card.querySelector('.note-menu');
|
||
// Open downward unless that would run off the bottom of the screen.
|
||
if (m.getBoundingClientRect().bottom > innerHeight - 8) m.classList.add('up');
|
||
m.querySelector('button')?.focus({ preventScroll: true });
|
||
}
|
||
return;
|
||
}
|
||
if (inMenu && !e.target.closest('[data-act]')) return;
|
||
if (e.target.closest('[data-review]')) { openReview(); return; }
|
||
const tagBtn = e.target.closest('[data-tag]');
|
||
if (tagBtn && !e.target.closest('.board-picker')) { setFilter({ tag: tagBtn.dataset.tag }); return; }
|
||
const f = e.target.closest('[data-filter]');
|
||
if (f) { setFilter(f.dataset.filter === 'pinned' ? { pinned: true } : f.dataset.filter === 'archived' ? { archived: true } : f.dataset.filter === 'todo' ? { todo: true } : {}); return; }
|
||
const actEl = e.target.closest('[data-act]');
|
||
if (!actEl) return;
|
||
const act = actEl.dataset.act;
|
||
if (act === 'clear') { setFilter({}); return; }
|
||
const card = actEl.closest('[data-id]');
|
||
const id = card?.dataset.id;
|
||
const note = findNote(id);
|
||
if (act === 'zoom') { openLightbox(actEl.src); return; }
|
||
if (act === 'open-parent') { openParent(actEl.dataset.parent); return; }
|
||
if (!note) return;
|
||
if (act === 'pin') {
|
||
const pinned = !note.pinned;
|
||
note.pinned = pinned; rerender();
|
||
const { error } = await sb.from('notes').update({ pinned }).eq('id', id);
|
||
if (error) { note.pinned = !pinned; rerender(); toast('Couldn\'t update: ' + error.message); }
|
||
} else if (act === 'copy') {
|
||
try { await navigator.clipboard.writeText(note.body); toast('Copied'); } catch { toast('Copy failed'); }
|
||
} else if (act === 'remind') {
|
||
compose.value = note.body.replace(/(^|\s)#[A-Za-z][\w-]*/g, '').trim(); autosize();
|
||
setRemindMode(true); window.scrollTo({ top: 0, behavior: 'smooth' });
|
||
} else if (act === 'more') {
|
||
state.openBodies.has(id) ? state.openBodies.delete(id) : state.openBodies.add(id); rerender();
|
||
} else if (act === 'edit') {
|
||
state.editing = id; state.editBase = { id, updated_at: note.updated_at }; state.editDraft = null; rerender();
|
||
} else if (act === 'cancel') {
|
||
state.editing = null; state.editDraft = null; state.editBase = null; rerender();
|
||
} else if (act === 'save') {
|
||
await saveEdit(note);
|
||
} else if (act === 'append') {
|
||
state.appending = state.appending === id ? null : id; state.appendDraft = ''; state.appendFocus = !!state.appending; rerender();
|
||
} else if (act === 'append-cancel') {
|
||
state.appending = null; rerender();
|
||
} else if (act === 'append-save') {
|
||
appendToNote(note, card.querySelector('[data-append]').value);
|
||
} else if (act === 'toggle-kids') {
|
||
if (state.expanded.has(id)) state.expanded.delete(id);
|
||
else { await loadChildren(id); state.expanded.add(id); }
|
||
rerender();
|
||
} else if (act === 'move') {
|
||
openMovePicker(note);
|
||
} else if (act === 'take-out') {
|
||
moveNote(note, null);
|
||
} else if (act === 'archive') {
|
||
archiveNote(note, !note.archived_at);
|
||
} else if (act === 'delete') {
|
||
deleteNote(note);
|
||
}
|
||
});
|
||
|
||
// ------------------------------------------------------------------
|
||
// Review mode: go through notes one at a time (oldest-reviewed first) and
|
||
// Keep, Pin, Archive or set a reminder. reviewed_at is stored on the note, so
|
||
// a note reviewed on one device doesn't come up again on another for a week.
|
||
// ------------------------------------------------------------------
|
||
const REVIEW_AGAIN_DAYS = 7;
|
||
const REVIEW_MAX = 50;
|
||
function reviewQuery(scope, count = false) {
|
||
const since = new Date(Date.now() - REVIEW_AGAIN_DAYS * 864e5).toISOString();
|
||
let q = sb.from('notes').select(count ? 'id' : '*', count ? { count: 'exact', head: true } : undefined)
|
||
.is('archived_at', null).or(`reviewed_at.is.null,reviewed_at.lt.${since}`);
|
||
if (scope.tag) q = q.contains('tags', [scope.tag]);
|
||
if (scope.todo) q = q.or('tags.cs.{todo},body.like.*[ ]*');
|
||
if (!count) q = q.order('reviewed_at', { ascending: true, nullsFirst: true }).order('created_at', { ascending: true }).limit(REVIEW_MAX);
|
||
return q;
|
||
}
|
||
|
||
async function openReview() {
|
||
$('#menu').classList.add('hidden');
|
||
const scopes = [
|
||
{ key: 'idea', label: '💡 Ideas', sub: '#idea', tag: 'idea' },
|
||
{ key: 'todo', label: '✅ To-dos', sub: '#todo and open checklists', todo: true },
|
||
...(state.tag && !['idea', 'todo'].includes(state.tag) ? [{ key: 't', label: '#' + state.tag, sub: 'the tag you\'re viewing', tag: state.tag }] : []),
|
||
{ key: 'all', label: '🗂️ Everything', sub: 'all notes, oldest first' },
|
||
];
|
||
const back = document.createElement('div');
|
||
back.className = 'modal-back';
|
||
back.innerHTML = `<div class="modal review" role="dialog" aria-label="Review notes"><div id="rv"></div></div>`;
|
||
document.body.appendChild(back);
|
||
const box = back.querySelector('#rv');
|
||
let queue = [], i = 0, history = [], tally = { kept: 0, pinned: 0, archived: 0, reminded: 0 }, picking = false;
|
||
|
||
const close = () => { back.remove(); document.removeEventListener('keydown', onKey, true); if (history.length) { loadNotes(true); scheduleTagRefresh(); } };
|
||
back.addEventListener('click', (e) => { if (e.target === back) close(); });
|
||
|
||
// Step 1: choose what to review (with counts)
|
||
box.innerHTML = `<h2>Review notes<span class="spacer"></span><button class="tool" data-rv="close" aria-label="Close">✕</button></h2>
|
||
<p class="help">One note at a time: keep it, pin it, archive it or set a reminder. Notes you review won't come up again for ${REVIEW_AGAIN_DAYS} days.</p>
|
||
<div class="scopes">${scopes.map((sc) => `<button data-scope="${sc.key}" disabled><span><strong>${esc(sc.label)}</strong><br><span style="font-size:12px;color:var(--muted)">${esc(sc.sub)}</span></span><span class="n" data-count="${sc.key}">…</span></button>`).join('')}</div>`;
|
||
scopes.forEach(async (sc) => {
|
||
const { count, error } = await reviewQuery(sc, true);
|
||
const el = box.querySelector(`[data-count="${sc.key}"]`), btn = box.querySelector(`[data-scope="${sc.key}"]`);
|
||
if (!el) return;
|
||
el.textContent = error ? '–' : count ? `${count} to review` : 'all caught up';
|
||
btn.disabled = !!error || !count;
|
||
});
|
||
|
||
async function start(sc) {
|
||
box.innerHTML = '<p class="help">Loading…</p>';
|
||
const { data, error } = await reviewQuery(sc);
|
||
if (error) { box.innerHTML = `<p class="help">Couldn't load notes: ${esc(error.message)}</p>`; return; }
|
||
queue = data; i = 0; draw();
|
||
}
|
||
|
||
function draw() {
|
||
picking = false;
|
||
if (i >= queue.length) return finish();
|
||
const n = queue[i];
|
||
const age = Math.max(0, Math.round((Date.now() - new Date(n.created_at)) / 864e5));
|
||
box.innerHTML = `<h2>Review<span class="spacer"></span><span style="font-size:13px;color:var(--muted);font-weight:400;margin-right:8px">${i + 1} of ${queue.length}</span><button class="tool" data-rv="close" aria-label="Close">✕</button></h2>
|
||
<div class="review-progress"><span style="width:${(i / queue.length) * 100}%"></span></div>
|
||
<div class="review-card" id="rv-card"><div class="note-body">${renderBody(n.body)}</div>
|
||
<div class="review-meta"><span>${age === 0 ? 'Added today' : age === 1 ? 'Added yesterday' : `Added ${age} days ago`}</span>${n.pinned ? '<span>📌 Pinned</span>' : ''}${n.reviewed_at ? `<span>Last reviewed ${dayLabel(n.reviewed_at)}</span>` : ''}</div></div>
|
||
<div id="rv-when" class="review-when hidden">
|
||
<button class="chip" data-when="tonight">Tonight 8pm</button><button class="chip" data-when="tomorrow">Tomorrow 9am</button>
|
||
<button class="chip" data-when="monday">Monday 9am</button><button class="chip" data-when="week">In a week</button>
|
||
<input class="field" type="datetime-local" id="rv-at" style="flex:1;min-width:180px"><button class="btn small" data-when="pick">Set</button>
|
||
</div>
|
||
<div class="review-actions">
|
||
<button data-rv="archive">🗄️<span>Archive</span><kbd>A / ←</kbd></button>
|
||
<button data-rv="remind">⏰<span>Remind me</span><kbd>R</kbd></button>
|
||
<button data-rv="pin">📌<span>${n.pinned ? 'Unpin' : 'Pin'}</span><kbd>P</kbd></button>
|
||
<button data-rv="keep" class="primary">👍<span>Keep</span><kbd>K / →</kbd></button>
|
||
</div>
|
||
<div class="review-foot"><button class="btn ghost small" data-rv="undo" ${history.length ? '' : 'disabled'}>Undo</button><span class="review-keys">U undo · Esc done</span><span class="review-swipe">Swipe ← archive · → keep</span><span class="spacer"></span><button class="btn ghost small" data-rv="close">Done</button></div>`;
|
||
swipe(box.querySelector('#rv-card'));
|
||
}
|
||
|
||
function finish() {
|
||
const t = tally, total = t.kept + t.pinned + t.archived + t.reminded;
|
||
box.innerHTML = `<h2>${total ? 'Nice work 🎉' : 'All caught up'}<span class="spacer"></span><button class="tool" data-rv="close" aria-label="Close">✕</button></h2>
|
||
<p class="help">${total ? `Reviewed ${total} note${total > 1 ? 's' : ''}: ${[t.kept && `${t.kept} kept`, t.pinned && `${t.pinned} pinned`, t.archived && `${t.archived} archived`, t.reminded && `${t.reminded} with a reminder`].filter(Boolean).join(', ')}.` : 'Nothing left to review here.'}</p>
|
||
<div class="row" style="justify-content:flex-end;margin-top:12px">${history.length ? '<button class="btn ghost small" data-rv="undo">Undo last</button>' : ''}<button class="btn small" data-rv="close">Done</button></div>`;
|
||
}
|
||
|
||
// Each action saves, remembers how to undo, then moves on.
|
||
async function act(kind, extra) {
|
||
const n = queue[i]; if (!n) return;
|
||
const prev = { reviewed_at: n.reviewed_at, pinned: n.pinned, archived_at: n.archived_at };
|
||
const now = new Date().toISOString();
|
||
const patch = { reviewed_at: now };
|
||
if (kind === 'pin') patch.pinned = !n.pinned;
|
||
if (kind === 'archive') patch.archived_at = now;
|
||
let reminderId = null;
|
||
if (kind === 'remind') {
|
||
const body = (firstLine(n.body).replace(/(^|\s)#[A-Za-z][\w-]*/g, '').trim() || 'Review this note').slice(0, 2000);
|
||
const { data, error } = await sb.from('reminders').insert({ body, due_at: extra.toISOString() }).select('id').single();
|
||
if (error) { toast('Couldn\'t set the reminder: ' + error.message); return; }
|
||
reminderId = data.id;
|
||
}
|
||
const { error } = await sb.from('notes').update(patch).eq('id', n.id);
|
||
if (error) {
|
||
if (reminderId) await sb.from('reminders').delete().eq('id', reminderId);
|
||
toast('Couldn\'t save: ' + error.message); return;
|
||
}
|
||
Object.assign(n, patch);
|
||
const key = { keep: 'kept', pin: 'pinned', archive: 'archived', remind: 'reminded' }[kind];
|
||
tally[key]++;
|
||
history.push({ note: n, prev, key, reminderId, index: i });
|
||
if (kind === 'remind') { toast('Reminder set for ' + whenLabel(extra)); loadReminders(); }
|
||
const card = box.querySelector('#rv-card');
|
||
if (card) card.classList.add(kind === 'archive' ? 'gone-left' : 'gone-right');
|
||
setTimeout(() => { i++; draw(); }, card ? 160 : 0);
|
||
}
|
||
|
||
async function undo() {
|
||
const h = history.pop(); if (!h) return;
|
||
const { error } = await sb.from('notes').update(h.prev).eq('id', h.note.id);
|
||
if (error) { history.push(h); toast('Couldn\'t undo: ' + error.message); return; }
|
||
if (h.reminderId) { await sb.from('reminders').delete().eq('id', h.reminderId); loadReminders(); }
|
||
Object.assign(h.note, h.prev);
|
||
tally[h.key]--;
|
||
i = h.index; draw();
|
||
}
|
||
|
||
function remindAt(k) {
|
||
const d = new Date();
|
||
if (k === 'tonight') { d.setHours(20, 0, 0, 0); if (d < new Date()) d.setDate(d.getDate() + 1); }
|
||
else if (k === 'tomorrow') { d.setDate(d.getDate() + 1); d.setHours(9, 0, 0, 0); }
|
||
else if (k === 'monday') { d.setDate(d.getDate() + ((8 - d.getDay()) % 7 || 7)); d.setHours(9, 0, 0, 0); }
|
||
else if (k === 'week') { d.setDate(d.getDate() + 7); d.setHours(9, 0, 0, 0); }
|
||
else if (k === 'pick') { const v = box.querySelector('#rv-at').value; if (!v) { toast('Pick a date and time.'); return null; } return new Date(v); }
|
||
return d;
|
||
}
|
||
function showWhen() {
|
||
picking = true;
|
||
const w = box.querySelector('#rv-when'); w.classList.remove('hidden');
|
||
const d = new Date(); d.setDate(d.getDate() + 1); d.setHours(9, 0, 0, 0);
|
||
box.querySelector('#rv-at').value = toLocalInput(d);
|
||
}
|
||
|
||
// Swipe on touch screens: left = archive, right = keep.
|
||
function swipe(card) {
|
||
let x0 = null, dx = 0;
|
||
card.addEventListener('pointerdown', (e) => { if (e.pointerType === 'mouse') return; x0 = e.clientX; dx = 0; card.style.transition = 'none'; });
|
||
card.addEventListener('pointermove', (e) => { if (x0 === null) return; dx = e.clientX - x0; card.style.transform = `translateX(${dx}px) rotate(${dx / 40}deg)`; });
|
||
const end = () => {
|
||
if (x0 === null) return;
|
||
x0 = null; card.style.transition = ''; card.style.transform = '';
|
||
if (dx < -90) act('archive'); else if (dx > 90) act('keep');
|
||
};
|
||
card.addEventListener('pointerup', end); card.addEventListener('pointercancel', end);
|
||
}
|
||
|
||
box.addEventListener('click', (e) => {
|
||
const sc = e.target.closest('[data-scope]');
|
||
if (sc && !sc.disabled) { start(scopes.find((x) => x.key === sc.dataset.scope)); return; }
|
||
const w = e.target.closest('[data-when]');
|
||
if (w) { const d = remindAt(w.dataset.when); if (d) act('remind', d); return; }
|
||
const b = e.target.closest('[data-rv]'); if (!b || b.disabled) return;
|
||
const k = b.dataset.rv;
|
||
if (k === 'close') close();
|
||
else if (k === 'undo') undo();
|
||
else if (k === 'remind') showWhen();
|
||
else act(k);
|
||
});
|
||
// Keys work only while the review is open and you're not typing in a field.
|
||
function onKey(e) {
|
||
if (e.key === 'Escape') { e.preventDefault(); e.stopPropagation(); close(); return; }
|
||
if (/INPUT|TEXTAREA|SELECT/.test(document.activeElement?.tagName) || e.metaKey || e.ctrlKey || e.altKey) return;
|
||
if (!queue.length || i >= queue.length) { if (e.key.toLowerCase() === 'u') undo(); return; }
|
||
const k = e.key.toLowerCase();
|
||
const map = { a: 'archive', arrowleft: 'archive', k: 'keep', arrowright: 'keep', p: 'pin' };
|
||
if (map[k]) { e.preventDefault(); e.stopPropagation(); act(map[k]); }
|
||
else if (k === 'r') { e.preventDefault(); picking ? act('remind', remindAt('tomorrow')) : showWhen(); }
|
||
else if (k === 'u') { e.preventDefault(); undo(); }
|
||
}
|
||
document.addEventListener('keydown', onKey, true);
|
||
}
|
||
|
||
async function archiveNote(note, archive, quiet = false) {
|
||
const prev = note.archived_at;
|
||
const archived_at = archive ? new Date().toISOString() : null;
|
||
note.archived_at = archived_at;
|
||
const idx = state.notes.findIndex((n) => n.id === note.id);
|
||
if (idx >= 0 && !matchesFilter(note)) state.notes.splice(idx, 1);
|
||
if (archive) for (const k in state.boardNotes) state.boardNotes[k] = state.boardNotes[k].filter((n) => n.id !== note.id);
|
||
rerender();
|
||
const { error } = await sb.from('notes').update({ archived_at }).eq('id', note.id);
|
||
if (error) {
|
||
note.archived_at = prev;
|
||
toast('Couldn\'t ' + (archive ? 'archive' : 'unarchive') + ': ' + error.message);
|
||
loadNotes(true); if (state.view === 'board') loadBoard();
|
||
return;
|
||
}
|
||
scheduleTagRefresh();
|
||
if (state.view === 'board' && !archive) loadBoard();
|
||
if (!quiet) toast(archive ? 'Note archived' : 'Note moved back to your feed', 'Undo', async () => {
|
||
await archiveNote(note, !archive, true);
|
||
if (matchesFilter(note) && !state.notes.some((n) => n.id === note.id)) loadNotes(true);
|
||
});
|
||
}
|
||
|
||
document.addEventListener('keydown', (e) => {
|
||
if (e.target.id === 'edit-text') {
|
||
if (continueChecklist(e.target, e)) return;
|
||
if (e.key === 'Enter' && (e.metaKey || e.ctrlKey)) { e.preventDefault(); const n = findNote(state.editing); if (n) saveEdit(n); }
|
||
if (e.key === 'Escape') { state.editing = null; state.editDraft = null; state.editBase = null; rerender(); }
|
||
}
|
||
if (e.key === '/' && !/INPUT|TEXTAREA|SELECT/.test(document.activeElement.tagName)) { e.preventDefault(); $('#search').focus(); }
|
||
});
|
||
|
||
// Saves only if the note is unchanged since editing began (another device or Hermes may
|
||
// have changed it). On a conflict, nothing is overwritten and you choose what to keep.
|
||
async function saveEdit(note, force = false) {
|
||
const body = $('#edit-text')?.value.trim() ?? state.editDraft;
|
||
const base = state.editBase?.id === note.id ? state.editBase.updated_at : note.updated_at;
|
||
state.editing = null; state.editDraft = null;
|
||
if (!body || body === note.body) { state.editBase = null; rerender(); return; }
|
||
const old = note.body; note.body = body; note.tags = localTags(body); rerender();
|
||
let q = sb.from('notes').update({ body }).eq('id', note.id);
|
||
if (!force && base) q = q.eq('updated_at', base);
|
||
const { data, error } = await q.select();
|
||
const reopen = () => { note.body = old; note.tags = localTags(old); state.editing = note.id; state.editDraft = body; rerender(); };
|
||
if (error) { reopen(); toast('Couldn\'t save: ' + error.message + '. Your edit is still open.'); return; }
|
||
if (!data.length) { reopen(); return editConflict(note, body); }
|
||
state.editBase = null;
|
||
replaceNote(data[0]); scheduleTagRefresh();
|
||
if (state.view === 'board') loadBoard();
|
||
}
|
||
|
||
async function editConflict(note, mine) {
|
||
const { data: theirs } = await sb.from('notes').select(NOTE_SELECT).eq('id', note.id).maybeSingle();
|
||
const back = document.createElement('div');
|
||
back.className = 'modal-back';
|
||
back.innerHTML = `<div class="modal" role="dialog" aria-label="Edit conflict">
|
||
<h2>This note changed while you were editing</h2>
|
||
<p class="help">${theirs ? 'Another device or Hermes saved a newer version. Nothing has been overwritten. Here\'s the newer version:' : 'It was deleted somewhere else.'}</p>
|
||
${theirs ? `<pre style="white-space:pre-wrap;max-height:30vh;overflow:auto;background:var(--surface-2);border-radius:10px;padding:10px;font-family:inherit;font-size:13px;line-height:1.45">${esc(theirs.body)}</pre>` : ''}
|
||
<div class="row" style="justify-content:flex-end;margin-top:12px">
|
||
<button class="btn ghost small" data-c="edit">Keep editing</button>
|
||
${theirs ? '<button class="btn ghost small" data-c="theirs">Use theirs (copy mine)</button>' : '<button class="btn ghost small" data-c="copy">Copy my text</button>'}
|
||
${theirs ? '<button class="btn small" data-c="mine">Keep mine</button>' : ''}
|
||
</div></div>`;
|
||
document.body.appendChild(back);
|
||
back.addEventListener('click', async (e) => {
|
||
const c = e.target.closest('[data-c]')?.dataset.c; if (!c) return;
|
||
back.remove();
|
||
if (c === 'mine') { state.editing = null; await saveEdit(note, true); }
|
||
else if (c === 'theirs' || c === 'copy') {
|
||
try { await navigator.clipboard.writeText(mine); toast('Your version is copied to the clipboard'); } catch { toast('Couldn\'t copy your version'); }
|
||
state.editing = null; state.editDraft = null; state.editBase = null;
|
||
if (theirs) replaceNote(theirs); else { state.notes = state.notes.filter((n) => n.id !== note.id); rerender(); }
|
||
} else {
|
||
// Keep editing on top of the newer version: your text stays in the box.
|
||
if (theirs) { state.editBase = { id: note.id, updated_at: theirs.updated_at }; replaceNote(theirs); }
|
||
state.editing = note.id; state.editDraft = mine; rerender();
|
||
}
|
||
});
|
||
}
|
||
|
||
async function appendToNote(note, raw) {
|
||
const text = (raw || '').trim();
|
||
if (!text) return;
|
||
const stamp = '— ' + new Date().toLocaleString('en-US', { month: 'short', day: 'numeric', hour: 'numeric', minute: '2-digit' }).replace(/\s/g, ' ');
|
||
state.appending = null;
|
||
// Optimistic display, then one atomic UPDATE in the database (so an
|
||
// addition arriving from Hermes at the same moment isn't overwritten).
|
||
const old = note.body;
|
||
note.body = note.body.replace(/\s+$/, '') + '\n\n' + stamp + '\n' + text; rerender();
|
||
const { data, error } = await sb.rpc('append_to_note', { p_note: note.id, p_stamp: stamp, p_text: text });
|
||
if (error || !data?.length) {
|
||
// Reopen the box with what was typed, so nothing is lost.
|
||
note.body = old; state.appending = note.id; state.appendDraft = text; state.appendFocus = true; rerender();
|
||
toast('Couldn\'t add: ' + (error?.message || 'note not found') + '. Your text is still in the box.');
|
||
return;
|
||
}
|
||
state.appendDraft = '';
|
||
replaceNote(data[0]); scheduleTagRefresh();
|
||
}
|
||
|
||
async function moveNote(note, parentId) {
|
||
const prev = note.parent_id;
|
||
const { error } = await sb.from('notes').update({ parent_id: parentId }).eq('id', note.id);
|
||
if (error) { toast(/cannot/i.test(error.message) ? error.message : 'Couldn\'t move: ' + error.message); return; }
|
||
note.parent_id = parentId;
|
||
if (prev && state.children[prev]) state.children[prev] = state.children[prev].filter((n) => n.id !== note.id);
|
||
const i = state.notes.findIndex((n) => n.id === note.id);
|
||
if (i >= 0 && !matchesFilter(note)) state.notes.splice(i, 1);
|
||
if (!parentId && !state.notes.some((n) => n.id === note.id) && matchesFilter(note)) { state.notes.push(note); state.notes.sort((a, b) => b.created_at.localeCompare(a.created_at)); }
|
||
if (parentId) { state.expanded.add(parentId); await loadChildren(parentId); }
|
||
if (prev) await loadChildren(prev);
|
||
await loadNestingInfo(state.notes);
|
||
rerender();
|
||
toast(parentId ? `Moved into "${state.parentTitles[parentId] || firstLine((findNote(parentId) || {}).body || '')}"` : 'Moved back to your feed', 'Undo', () => moveNote(note, prev));
|
||
}
|
||
|
||
async function openParent(parentId) {
|
||
setFilter({});
|
||
state.expanded.add(parentId);
|
||
await loadChildren(parentId);
|
||
rerender();
|
||
setTimeout(() => document.querySelector(`#feed [data-id="${parentId}"]`)?.scrollIntoView({ behavior: 'smooth', block: 'center' }), 400);
|
||
}
|
||
|
||
function openMovePicker(note) {
|
||
const back = document.createElement('div');
|
||
back.className = 'modal-back';
|
||
back.innerHTML = `<div class="modal" role="dialog" aria-label="Move into a note">
|
||
<h2>Move into…<span class="spacer"></span><button class="tool" data-pick-close aria-label="Close">✕</button></h2>
|
||
<p class="help" style="margin:4px 0 10px;color:var(--muted);font-size:13px">Pick the note this one should live inside. It will leave your main feed and show under that note.</p>
|
||
<input class="field" id="pick-q" placeholder="Search your notes…" autocomplete="off">
|
||
<div class="picker-list" id="pick-list"></div>
|
||
</div>`;
|
||
document.body.appendChild(back);
|
||
const close = () => back.remove();
|
||
const load = async () => {
|
||
const qtext = back.querySelector('#pick-q').value.trim();
|
||
let q = sb.from('notes').select('id,body').is('parent_id', null).is('archived_at', null).neq('id', note.id).order('updated_at', { ascending: false }).limit(30);
|
||
if (qtext) q = q.ilike('body', `%${qtext.replace(/[%_\\]/g, '\\$&')}%`);
|
||
const { data } = await q;
|
||
back.querySelector('#pick-list').innerHTML = (data || []).map((p) => `<button data-pick="${p.id}">${esc(firstLine(p.body) || '(empty note)')}</button>`).join('') || '<p style="color:var(--muted)">No notes found.</p>';
|
||
};
|
||
let t; back.querySelector('#pick-q').addEventListener('input', () => { clearTimeout(t); t = setTimeout(load, 200); });
|
||
back.addEventListener('click', (e) => {
|
||
if (e.target === back || e.target.closest('[data-pick-close]')) { close(); return; }
|
||
const p = e.target.closest('[data-pick]');
|
||
if (p) { close(); moveNote(note, p.dataset.pick); }
|
||
});
|
||
load();
|
||
back.querySelector('#pick-q').focus();
|
||
}
|
||
|
||
function deleteNote(note) {
|
||
const idx = state.notes.findIndex((n) => n.id === note.id);
|
||
state.notes = state.notes.filter((n) => n.id !== note.id); renderFeed();
|
||
for (const k in state.boardNotes) state.boardNotes[k] = state.boardNotes[k].filter((n) => n.id !== note.id);
|
||
for (const k in state.children) state.children[k] = state.children[k].filter((n) => n.id !== note.id);
|
||
if (state.view === 'board') renderBoard(); else rerender();
|
||
let undone = false;
|
||
// Notes inside this one pop out when it's deleted; remember them so Undo can put them back.
|
||
const kidsP = sb.from('notes').select('id').eq('parent_id', note.id).then(({ data }) => (data || []).map((k) => k.id));
|
||
const del = kidsP.then(() => sb.from('notes').delete().eq('id', note.id));
|
||
del.then(({ error }) => { if (error) { toast('Couldn\'t delete: ' + error.message); loadNotes(true); } else scheduleTagRefresh(); });
|
||
toast('Note deleted', 'Undo', async () => {
|
||
undone = true;
|
||
await del;
|
||
const { _queued, ...row } = note;
|
||
const { data, error } = await sb.from('notes').insert({ id: row.id, body: row.body, tags: row.tags, source: row.source, pinned: row.pinned, attachments: row.attachments, archived_at: row.archived_at ?? null, parent_id: row.parent_id ?? null, created_at: row.created_at }).select().single();
|
||
if (error) { toast('Couldn\'t restore: ' + error.message); return; }
|
||
const kids = await kidsP;
|
||
if (kids.length) { await sb.from('notes').update({ parent_id: data.id }).in('id', kids); loadNotes(true); scheduleNestingRefresh(); }
|
||
state.notes.splice(Math.max(0, idx), 0, data); renderFeed(); scheduleTagRefresh();
|
||
if (state.view === 'board') loadBoard();
|
||
}, 7000);
|
||
// Files are removed only after the undo window closes
|
||
setTimeout(() => {
|
||
if (undone || !(note.attachments || []).length) return;
|
||
sb.storage.from(BUCKET).remove(note.attachments.map((a) => a.path));
|
||
}, 7500);
|
||
}
|
||
|
||
function openLightbox(src) {
|
||
const el = document.createElement('div');
|
||
el.className = 'lightbox'; el.innerHTML = `<img src="${esc(src)}" alt="">`;
|
||
el.onclick = () => el.remove();
|
||
document.body.appendChild(el);
|
||
}
|
||
|
||
// ------------------------------------------------------------------
|
||
// Filters, search, views
|
||
// ------------------------------------------------------------------
|
||
function setFilter({ tag = null, pinned = false, archived = false, todo = false }) {
|
||
state.tag = tag; state.pinned = pinned; state.archived = archived; state.todo = todo;
|
||
if (state.view !== 'feed') switchView('feed');
|
||
renderTags(); loadNotes(true);
|
||
window.scrollTo({ top: 0, behavior: 'smooth' });
|
||
}
|
||
|
||
let searchTimer;
|
||
$('#search').addEventListener('input', (e) => {
|
||
clearTimeout(searchTimer);
|
||
searchTimer = setTimeout(() => {
|
||
state.query = e.target.value.trim();
|
||
if (state.view !== 'feed') switchView('feed');
|
||
loadNotes(true);
|
||
}, 250);
|
||
});
|
||
|
||
$('#load-more').onclick = () => loadNotes(false);
|
||
|
||
document.querySelectorAll('.tab').forEach((t) => (t.onclick = () => switchView(t.dataset.view)));
|
||
function switchView(v) {
|
||
state.view = v;
|
||
document.querySelectorAll('.tab').forEach((t) => t.classList.toggle('active', t.dataset.view === v));
|
||
$('#view-feed').classList.toggle('hidden', v !== 'feed');
|
||
$('#view-board').classList.toggle('hidden', v !== 'board');
|
||
$('#view-reminders').classList.toggle('hidden', v !== 'reminders');
|
||
$('#view-calendar').classList.toggle('hidden', v !== 'calendar');
|
||
applyTagBar();
|
||
if (v === 'board') loadBoard();
|
||
if (v === 'reminders') renderReminders();
|
||
if (v === 'calendar') { renderCalendar(); loadCalendarNotes(); }
|
||
}
|
||
|
||
// Menu ---------------------------------------------------------------
|
||
$('#menu-btn').onclick = (e) => { e.stopPropagation(); $('#menu').classList.toggle('hidden'); };
|
||
document.addEventListener('click', (e) => { if (!e.target.closest('#menu')) $('#menu').classList.add('hidden'); });
|
||
$('#menu').addEventListener('click', async (e) => {
|
||
const a = e.target.closest('[data-action]')?.dataset.action; if (!a) return;
|
||
$('#menu').classList.add('hidden');
|
||
if (a === 'density') {
|
||
lsSet(LS.density, lsGet(LS.density, 'comfortable') === 'compact' ? 'comfortable' : 'compact');
|
||
applyDensity(); rerender();
|
||
} else if (a === 'review') {
|
||
openReview();
|
||
} else if (a === 'tagbar') {
|
||
const m = TAGBAR_MODES[(TAGBAR_MODES.indexOf(tagBarMode()) + 1) % TAGBAR_MODES.length];
|
||
lsSet(LS.tagbar, m); applyTagBar(); renderTags();
|
||
toast(m === 'hidden' ? 'Tag bar hidden. Search #tag or tap a tag in a note to filter.' : `Tag bar: ${TAGBAR_LABELS[m]}`);
|
||
} else if (a === 'theme') {
|
||
const order = ['auto', 'light', 'dark'];
|
||
lsSet(LS.theme, order[(order.indexOf(lsGet(LS.theme, 'auto')) + 1) % 3]); applyTheme();
|
||
} else if (a === 'signout') {
|
||
lsSet(LS.cache, null); await sb.auth.signOut();
|
||
} else if (a === 'settings') {
|
||
openSettings();
|
||
} else if (a === 'export') {
|
||
exportNotes();
|
||
} else if (a === 'notify') {
|
||
openSettings('push');
|
||
}
|
||
});
|
||
|
||
async function exportNotes() {
|
||
const all = []; let from = 0;
|
||
for (;;) {
|
||
const { data, error } = await sb.from('notes').select(NOTE_SELECT).order('created_at').range(from, from + 999);
|
||
if (error) { toast('Export failed: ' + error.message); return; }
|
||
all.push(...data); if (data.length < 1000) break; from += 1000;
|
||
}
|
||
const { data: reminders, error: remErr } = await sb.from('reminders').select('*').order('due_at');
|
||
if (remErr) { toast('Export failed (reminders): ' + remErr.message); return; }
|
||
const blob = new Blob([JSON.stringify({ exported_at: new Date().toISOString(), notes: all, reminders }, null, 2)], { type: 'application/json' });
|
||
const a = document.createElement('a');
|
||
a.href = URL.createObjectURL(blob); a.download = `brainfeed-${new Date().toISOString().slice(0, 10)}.json`; a.click();
|
||
setTimeout(() => URL.revokeObjectURL(a.href), 1000);
|
||
toast(`Exported ${all.length} notes`);
|
||
}
|
||
|
||
// ------------------------------------------------------------------
|
||
// Board
|
||
// ------------------------------------------------------------------
|
||
async function loadBoard() {
|
||
const cols = state.settings?.board_tags || [];
|
||
if (cols.length < 2) { state.boardPicking = true; state.pickTags = [...cols]; renderBoard(); return; }
|
||
const results = await Promise.all(cols.map((t) => sb.from('notes').select(NOTE_SELECT).contains('tags', [t]).is('archived_at', null).order('pinned', { ascending: false }).order('created_at', { ascending: false }).limit(100)));
|
||
cols.forEach((t, i) => { state.boardNotes[t] = results[i].data || []; });
|
||
const failed = cols.filter((_, i) => results[i].error);
|
||
if (failed.length) toast(`Couldn't load ${failed.map((t) => '#' + t).join(', ')}. Reload to try again.`);
|
||
renderBoard();
|
||
}
|
||
|
||
function renderBoard() {
|
||
captureEditDraft();
|
||
const el = $('#view-board');
|
||
const cols = state.settings?.board_tags || [];
|
||
let html = `<div class="board-head"><h2>Board</h2><span class="spacer" style="flex:1"></span>${state.boardPicking ? '' : '<button class="btn ghost small" data-board="edit">Change columns</button>'}</div>`;
|
||
if (state.boardPicking) {
|
||
html += `<div class="board-picker"><p>Choose 2–5 tags to become columns. Notes with that tag show up in the column, and anything you add there gets the tag.</p>
|
||
<div class="chips">${state.tags.length ? state.tags.map((t) => `<button class="chip${state.pickTags.includes(t.tag) ? ' on' : ''}" data-pick="${esc(t.tag)}">#${esc(t.tag)} <span style="opacity:.6">${t.count}</span></button>`).join('') : '<span style="color:var(--muted)">No tags yet. Add some #tags to notes first.</span>'}</div>
|
||
<button class="btn small" data-board="save" ${state.pickTags.length < 2 ? 'disabled' : ''}>Save columns (${state.pickTags.length}/5)</button>
|
||
${cols.length >= 2 ? '<button class="btn ghost small" data-board="cancel">Cancel</button>' : ''}</div>`;
|
||
} else {
|
||
const mv = state.boardMoving;
|
||
if (mv) html += `<div class="move-banner"><span>Tap a column to move "${esc(firstLine(mv.note.body).slice(0, 40))}" (or Archive)</span><button data-board="move-cancel">Cancel</button></div>`;
|
||
const card = (n, t) => noteHtml(n, true)
|
||
.replace('<article class="note', '<article draggable="true" class="note')
|
||
.replace('<button class="tool" data-act="archive"', `<button class="tool" data-act="board-move" data-from="${esc(t)}" title="Move to another column">${ICON.move}</button><button class="tool" data-act="archive"`);
|
||
html += `<div class="board${mv ? ' moving' : ''}">` + cols.map((t) => {
|
||
const notes = state.boardNotes[t] || [];
|
||
return `<div class="column" data-col="${esc(t)}"><h4>#${esc(t)} <span>${notes.length}</span></h4>
|
||
<input class="field quick" data-quickadd="${esc(t)}" placeholder="Add to #${esc(t)}…">
|
||
<div class="column-list">${notes.map((n) => card(n, t)).join('') || '<div class="empty" style="padding:24px 8px">Empty</div>'}</div></div>`;
|
||
}).join('') + `<div class="column archive-zone" data-col="__archive">${ICON.archive}<div><strong>Archive</strong><br>Drop a card here to archive it</div></div></div>`;
|
||
}
|
||
withAddFocus(() => { el.innerHTML = html; });
|
||
hydrateAttachments(el);
|
||
}
|
||
|
||
$('#view-board').addEventListener('click', async (e) => {
|
||
const pick = e.target.closest('[data-pick]');
|
||
if (pick) {
|
||
const t = pick.dataset.pick, i = state.pickTags.indexOf(t);
|
||
if (i >= 0) state.pickTags.splice(i, 1); else if (state.pickTags.length < 5) state.pickTags.push(t); else toast('Up to 5 columns');
|
||
renderBoard(); return;
|
||
}
|
||
const b = e.target.closest('[data-board]')?.dataset.board;
|
||
if (b === 'move-cancel') { state.boardMoving = null; renderBoard(); return; }
|
||
if (state.boardMoving && !b) {
|
||
const col = e.target.closest('[data-col]');
|
||
if (col) { const { note, from } = state.boardMoving; state.boardMoving = null; moveCardToColumn(note, from, col.dataset.col); return; }
|
||
}
|
||
const mvBtn = e.target.closest('[data-act="board-move"]');
|
||
if (mvBtn) {
|
||
const note = findNote(mvBtn.closest('[data-id]').dataset.id);
|
||
if (note) { state.boardMoving = { note, from: mvBtn.dataset.from }; renderBoard(); }
|
||
return;
|
||
}
|
||
if (b === 'edit') { state.boardPicking = true; state.pickTags = [...(state.settings.board_tags || [])]; renderBoard(); }
|
||
else if (b === 'cancel') { state.boardPicking = false; renderBoard(); }
|
||
else if (b === 'save') {
|
||
const { data, error } = await sb.from('settings').update({ board_tags: state.pickTags, updated_at: new Date().toISOString() }).eq('user_id', state.user.id).select().single();
|
||
if (error) { toast('Couldn\'t save columns: ' + error.message); return; }
|
||
state.settings = data; state.boardPicking = false; loadBoard();
|
||
}
|
||
});
|
||
// Move a board card from one tag column to another. If the old tag is
|
||
// written in the text (#grocery), swap it there so it stays changed after
|
||
// future edits; otherwise swap it in the tag list.
|
||
async function moveCardToColumn(note, from, to) {
|
||
if (to === '__archive') { await archiveNote(note, true); loadBoard(); return; }
|
||
if (!from || from === to) { renderBoard(); return; }
|
||
const before = { body: note.body, tags: [...note.tags] };
|
||
const esc_ = (x) => x.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
||
const re = new RegExp(`(^|[^&\\w])#${esc_(from)}(?![\\w-])`, 'gi');
|
||
let patch;
|
||
if (re.test(note.body)) {
|
||
const hasTo = new RegExp(`(^|[^&\\w])#${esc_(to)}(?![\\w-])`, 'i').test(note.body);
|
||
let first = true;
|
||
const body = note.body.replace(re, (m, pre) => { if (first && !hasTo) { first = false; return `${pre}#${to}`; } return pre; })
|
||
.replace(/[ \t]{2,}/g, ' ').replace(/[ \t]+$/gm, '').trim();
|
||
patch = { body };
|
||
} else {
|
||
patch = { tags: [...new Set(note.tags.filter((t) => t !== from).concat(to))] };
|
||
}
|
||
// Optimistic: move the card between columns right away
|
||
state.boardNotes[from] = (state.boardNotes[from] || []).filter((n) => n.id !== note.id);
|
||
if (!(state.boardNotes[to] || []).some((n) => n.id === note.id)) (state.boardNotes[to] ||= []).unshift({ ...note, ...patch, tags: [...new Set([...(patch.tags || note.tags.filter((t) => t !== from)), to])] });
|
||
renderBoard();
|
||
// Only if the note is unchanged since the board loaded, so a newer edit isn't overwritten.
|
||
let q = sb.from('notes').update(patch).eq('id', note.id);
|
||
if (note.updated_at) q = q.eq('updated_at', note.updated_at);
|
||
let { data: rows, error } = await q.select();
|
||
if (!error && !rows.length) { toast('That note just changed on another device. The board has been refreshed; try again.'); loadBoard(); return; }
|
||
let data = rows?.[0];
|
||
// A manual copy of the old tag can survive a text swap; drop it too.
|
||
if (!error && data.tags.includes(from) && patch.body) {
|
||
({ data, error } = await sb.from('notes').update({ tags: data.tags.filter((t) => t !== from).concat(data.tags.includes(to) ? [] : [to]) }).eq('id', note.id).select().single());
|
||
}
|
||
if (error) { toast('Couldn\'t move: ' + error.message); loadBoard(); return; }
|
||
replaceNote(data); scheduleTagRefresh(); loadBoard();
|
||
if (data.tags.includes(from)) {
|
||
toast(`Still under #${from}: the note starts with the word "${from}", which files it there automatically`);
|
||
} else {
|
||
toast(`Moved to #${to}`, 'Undo', async () => {
|
||
// Undo only if nothing else changed the note since the move.
|
||
const { data: r1, error: e1 } = await sb.from('notes').update({ body: before.body }).eq('id', note.id).eq('updated_at', data.updated_at).select();
|
||
if (e1 || !r1.length) { toast(e1 ? 'Couldn\'t undo: ' + e1.message : 'Can\'t undo: the note changed since the move.'); loadBoard(); return; }
|
||
await sb.from('notes').update({ tags: before.tags }).eq('id', note.id);
|
||
scheduleTagRefresh(); loadBoard(); loadNotes(true);
|
||
});
|
||
}
|
||
}
|
||
|
||
document.addEventListener('dragstart', (e) => {
|
||
const card = e.target.closest?.('#view-board article.note[draggable="true"]');
|
||
if (!card) return;
|
||
e.dataTransfer.setData('text/x-brainfeed-note', JSON.stringify({ id: card.dataset.id, from: card.closest('[data-col]')?.dataset.col }));
|
||
e.dataTransfer.effectAllowed = 'move';
|
||
card.classList.add('dragging');
|
||
});
|
||
document.addEventListener('dragend', (e) => { e.target.closest?.('article.note')?.classList.remove('dragging'); document.querySelectorAll('#view-board .drop').forEach((x) => x.classList.remove('drop')); });
|
||
document.addEventListener('dragover', (e) => {
|
||
const col = e.target.closest?.('#view-board [data-col]');
|
||
if (!col || !e.dataTransfer.types.includes('text/x-brainfeed-note')) return;
|
||
e.preventDefault();
|
||
document.querySelectorAll('#view-board .drop').forEach((x) => x !== col && x.classList.remove('drop'));
|
||
col.classList.add('drop');
|
||
});
|
||
document.addEventListener('drop', (e) => {
|
||
const col = e.target.closest?.('#view-board [data-col]');
|
||
const raw = e.dataTransfer?.getData('text/x-brainfeed-note');
|
||
if (!col || !raw) return;
|
||
e.preventDefault();
|
||
col.classList.remove('drop');
|
||
const { id, from } = JSON.parse(raw);
|
||
const note = findNote(id);
|
||
if (note) moveCardToColumn(note, from, col.dataset.col);
|
||
});
|
||
|
||
$('#view-board').addEventListener('keydown', async (e) => {
|
||
const t = e.target.dataset?.quickadd;
|
||
if (!t || e.key !== 'Enter' || e.isComposing) return;
|
||
const v = e.target.value.trim(); if (!v) return;
|
||
e.target.value = '';
|
||
const body = new RegExp(`(^|\\s)#${t}(\\b|$)`, 'i').test(v) ? v : `${v} #${t}`;
|
||
await addNote(body);
|
||
loadBoard();
|
||
});
|
||
|
||
// ------------------------------------------------------------------
|
||
// Reminders
|
||
// ------------------------------------------------------------------
|
||
async function loadAgents() {
|
||
const { data } = await sb.from('api_tokens').select('id,name,token_hash,created_at,last_used_at,revoked_at').order('created_at', { ascending: false });
|
||
state.agents = data || [];
|
||
}
|
||
|
||
function agoLabel(iso) {
|
||
const m = Math.round((Date.now() - new Date(iso)) / 60000);
|
||
if (m < 1) return 'just now';
|
||
if (m < 60) return `${m} min ago`;
|
||
if (m < 1440) return `${Math.round(m / 60)} h ago`;
|
||
return new Date(iso).toLocaleDateString();
|
||
}
|
||
|
||
async function loadReminders() {
|
||
loadAgents();
|
||
const { data, error } = await sb.from('reminders').select('*').order('due_at');
|
||
if (error) return;
|
||
state.reminders = data;
|
||
const overdue = data.filter((r) => !r.done && new Date(r.due_at) <= new Date()).length;
|
||
const b = $('#rem-badge'); b.textContent = overdue; b.classList.toggle('hidden', !overdue);
|
||
if (!state.remEditing) renderRemViews();
|
||
}
|
||
|
||
function renderRemViews() {
|
||
if (state.view === 'reminders') renderReminders();
|
||
if (state.view === 'calendar') renderCalendar();
|
||
}
|
||
|
||
function whenLabel(d) {
|
||
d = new Date(d);
|
||
const now = new Date(), t = timeLabel(d);
|
||
const day = dayLabel(d);
|
||
const diffDays = Math.round((new Date(d).setHours(0, 0, 0, 0) - new Date(now).setHours(0, 0, 0, 0)) / 864e5);
|
||
if (diffDays === 0) return `Today ${t}`;
|
||
if (diffDays === 1) return `Tomorrow ${t}`;
|
||
if (diffDays === -1) return `Yesterday ${t}`;
|
||
if (diffDays > 1 && diffDays < 7) return `${d.toLocaleDateString(undefined, { weekday: 'long' })} ${t}`;
|
||
return `${diffDays < 0 ? day : d.toLocaleDateString(undefined, { month: 'short', day: 'numeric', year: d.getFullYear() === now.getFullYear() ? undefined : 'numeric' })} ${t}`;
|
||
}
|
||
const REPEAT_LABEL = { daily: 'Every day', weekdays: 'Weekdays', weekly: 'Every week', monthly: 'Every month', yearly: 'Every year', dates: 'Specific dates' };
|
||
|
||
function nextOccurrence(due, repeat, dates) {
|
||
if (repeat === 'dates') {
|
||
const after = Math.max(Date.now(), new Date(due).getTime());
|
||
return (dates || []).map((d) => new Date(d)).sort((a, b) => a - b).find((d) => d.getTime() > after) || null;
|
||
}
|
||
const d = new Date(due), now = new Date();
|
||
do {
|
||
if (repeat === 'daily') d.setDate(d.getDate() + 1);
|
||
else if (repeat === 'weekdays') { do d.setDate(d.getDate() + 1); while (d.getDay() === 0 || d.getDay() === 6); }
|
||
else if (repeat === 'weekly') d.setDate(d.getDate() + 7);
|
||
else if (repeat === 'monthly') {
|
||
const day = new Date(due).getDate();
|
||
d.setDate(1); d.setMonth(d.getMonth() + 1);
|
||
d.setDate(Math.min(day, new Date(d.getFullYear(), d.getMonth() + 1, 0).getDate()));
|
||
} else if (repeat === 'yearly') d.setFullYear(d.getFullYear() + 1);
|
||
else break;
|
||
} while (d <= now);
|
||
return d;
|
||
}
|
||
|
||
function remHtml(r) {
|
||
const due = new Date(r.due_at), overdue = !r.done && due <= new Date();
|
||
if (state.remEditing === r.id) {
|
||
return `<div class="rem" data-rem="${r.id}"><div class="rem-edit">
|
||
<input class="field" data-rem-field="body" value="${esc(r.body)}">
|
||
<div class="row">
|
||
<input class="field${r.repeat === 'dates' ? ' hidden' : ''}" type="datetime-local" data-rem-field="at" value="${toLocalInput(due)}">
|
||
<select class="field" data-rem-field="repeat">
|
||
<option value="">Once</option>${Object.entries(REPEAT_LABEL).map(([k, v]) => `<option value="${k}"${r.repeat === k ? ' selected' : ''}>${v}${k === 'dates' ? '…' : ''}</option>`).join('')}
|
||
</select>
|
||
</div>
|
||
<div data-dp-host="${r.id}" class="${r.repeat === 'dates' ? '' : 'hidden'}">${r.repeat === 'dates' || state.dp[r.id] ? datePickerHtml(r.id) : ''}</div>
|
||
<div class="row" style="justify-content:flex-end"><button class="btn ghost small" data-rem-act="edit-cancel">Cancel</button><button class="btn small" data-rem-act="edit-save">Save</button></div>
|
||
</div></div>`;
|
||
}
|
||
return `<div class="rem${overdue ? ' overdue' : ''}${r.done ? ' done' : ''}" data-rem="${r.id}">
|
||
<button class="rem-check" data-rem-act="toggle" title="${r.done ? 'Mark not done' : r.repeat ? 'Done, schedule next' : 'Mark done'}">${r.done ? ICON.check : ''}</button>
|
||
<div class="rem-main">
|
||
<div class="rem-text">${formatBody(r.body)}</div>
|
||
<div class="rem-when"><span class="due">${overdue ? 'Overdue · ' : ''}${esc(whenLabel(due))}</span>
|
||
${r.repeat === 'dates' ? `<span class="src">${r.dates.length} date${r.dates.length > 1 ? 's' : ''}</span>` : r.repeat ? `<span class="src">${REPEAT_LABEL[r.repeat]}</span>` : ''}
|
||
${r.last_sent_at ? `<span class="src">sent ${esc(whenLabel(r.last_sent_at))}</span>` : ''}
|
||
${r.source !== 'web' ? `<span class="src">${esc(r.source)}</span>` : ''}
|
||
</div>
|
||
</div>
|
||
${r.done || r.repeat === 'dates' ? '' : '<button class="tool" data-rem-act="snooze" title="Snooze 1 hour">+1h</button>'}
|
||
${r.done || r.repeat === 'dates' ? '' : `<button class="tool" data-rem-act="move" title="Move to another day">${ICON.move}</button>`}
|
||
<button class="tool" data-rem-act="edit" title="Edit">${ICON.edit}</button>
|
||
<button class="tool" data-rem-act="delete" title="Delete">${ICON.trash}</button>
|
||
</div>`;
|
||
}
|
||
|
||
function renderReminders() {
|
||
const now = new Date();
|
||
const open = state.reminders.filter((r) => !r.done);
|
||
const overdue = open.filter((r) => new Date(r.due_at) <= now);
|
||
const upcoming = open.filter((r) => new Date(r.due_at) > now);
|
||
const done = state.reminders.filter((r) => r.done).sort((a, b) => new Date(b.due_at) - new Date(a.due_at)).slice(0, 25);
|
||
const agent = state.agents.find((t) => !t.revoked_at && t.last_used_at && Date.now() - new Date(t.last_used_at) < 15 * 60e3);
|
||
const notice = agent
|
||
? `<span class="pill-ok">● ${esc(agent.name)} is delivering reminders</span> (last check ${esc(agoLabel(agent.last_used_at))}).`
|
||
: 'Reminders show here and as browser alerts while BrainFeed is open (menu → Enable reminder alerts). Connect Hermes in menu → Settings to get them on Telegram.';
|
||
let html = `<div class="notice">${notice}</div>
|
||
<button class="btn small" data-rem-act="new" style="margin-bottom:6px">+ New reminder</button>`;
|
||
if (!state.reminders.length) html += '<div class="empty"><strong>No reminders</strong>Tap the bell in the composer, or the bell on any note.</div>';
|
||
if (overdue.length) html += `<div class="rem-section"><h3>Overdue</h3>${overdue.map(remHtml).join('')}</div>`;
|
||
if (upcoming.length) html += `<div class="rem-section"><h3>Upcoming</h3>${upcoming.map(remHtml).join('')}</div>`;
|
||
if (done.length) html += `<div class="rem-section"><h3>Done</h3>${done.map(remHtml).join('')}</div>`;
|
||
$('#view-reminders').innerHTML = html;
|
||
}
|
||
|
||
async function onReminderClick(e) {
|
||
const a = e.target.closest('[data-rem-act]')?.dataset.remAct; if (!a) return;
|
||
if (a === 'new') { switchView('feed'); setRemindMode(true); return; }
|
||
const card = e.target.closest('[data-rem]');
|
||
const id = card.dataset.rem;
|
||
const r = state.reminders.find((x) => x.id === id); if (!r) return;
|
||
let patch = null, okMsg = '';
|
||
if (a === 'move') { startMove(r); return; }
|
||
if (a === 'edit') {
|
||
delete state.dp[id];
|
||
if (r.repeat === 'dates') {
|
||
const t = new Date(r.due_at);
|
||
dpState(id, { days: r.dates.map((d) => dayKey(new Date(d))), time: `${pad2(t.getHours())}:${pad2(t.getMinutes())}` });
|
||
}
|
||
state.remEditing = id; renderRemViews(); card.parentElement.querySelector(`[data-rem="${id}"] [data-rem-field="body"]`)?.focus(); return; }
|
||
if (a === 'edit-cancel') { state.remEditing = null; renderRemViews(); return; }
|
||
if (a === 'edit-save') {
|
||
const body = card.querySelector('[data-rem-field="body"]').value.trim();
|
||
const repeat = card.querySelector('[data-rem-field="repeat"]').value || null;
|
||
if (!body) { toast('Text is required'); return; }
|
||
if (repeat === 'dates') {
|
||
const d = datesFromPicker(id);
|
||
if (d.error) { toast(d.error); return; }
|
||
patch = { body, repeat, dates: d.dates.map((x) => x.toISOString()), due_at: d.due.toISOString(), done: false };
|
||
} else {
|
||
const at = card.querySelector('[data-rem-field="at"]').value;
|
||
if (!at) { toast('Pick a time'); return; }
|
||
patch = { body, repeat, dates: null, due_at: new Date(at).toISOString() };
|
||
}
|
||
state.remEditing = null; delete state.dp[id];
|
||
} else if (a === 'toggle') {
|
||
if (!r.done && r.repeat) {
|
||
const next = nextOccurrence(r.due_at, r.repeat, r.dates);
|
||
if (next) { patch = { due_at: next.toISOString() }; okMsg = 'Next: ' + whenLabel(next); }
|
||
else { patch = { done: true }; okMsg = 'Last date done ✓'; }
|
||
}
|
||
else patch = { done: !r.done };
|
||
} else if (a === 'snooze') {
|
||
patch = { due_at: new Date(Math.max(Date.now(), new Date(r.due_at)) + 3600e3).toISOString() };
|
||
} else if (a === 'delete') {
|
||
state.reminders = state.reminders.filter((x) => x.id !== id); renderRemViews();
|
||
const { error } = await sb.from('reminders').delete().eq('id', id);
|
||
if (error) toast('Couldn\'t delete: ' + error.message);
|
||
loadReminders(); return;
|
||
}
|
||
const seen = { due_at: r.due_at, done: r.done };
|
||
Object.assign(r, patch); renderRemViews();
|
||
// Only if the reminder is as you saw it: if Hermes just delivered it (and moved it to its
|
||
// next time), checking it off again would skip an occurrence.
|
||
let q = sb.from('reminders').update(patch).eq('id', id);
|
||
if (a === 'toggle' || a === 'snooze') q = q.eq('due_at', seen.due_at).eq('done', seen.done);
|
||
const { data, error } = await q.select('id');
|
||
if (error) toast('Couldn\'t update: ' + error.message);
|
||
else if (!data.length) toast('That reminder just changed (it may have been delivered). It\'s been refreshed.');
|
||
else if (okMsg) toast(okMsg);
|
||
loadReminders();
|
||
}
|
||
$('#view-reminders').addEventListener('click', onReminderClick);
|
||
document.addEventListener('change', (e) => {
|
||
const sel = e.target.closest('.rem-edit [data-rem-field="repeat"]');
|
||
if (!sel) return;
|
||
const card = sel.closest('[data-rem]'), id = card.dataset.rem, dates = sel.value === 'dates';
|
||
card.querySelector('[data-rem-field="at"]').classList.toggle('hidden', dates);
|
||
const host = card.querySelector('[data-dp-host]');
|
||
host.classList.toggle('hidden', !dates);
|
||
if (dates) {
|
||
if (!state.dp[id]) { const at = new Date(card.querySelector('[data-rem-field="at"]').value || Date.now()); dpState(id, { days: [dayKey(at)], time: `${pad2(at.getHours())}:${pad2(at.getMinutes())}` }); }
|
||
host.innerHTML = datePickerHtml(id);
|
||
}
|
||
});
|
||
$('#view-reminders').addEventListener('keydown', (e) => {
|
||
if (e.target.closest('.rem-edit') && e.key === 'Escape') { state.remEditing = null; renderRemViews(); }
|
||
});
|
||
|
||
// ------------------------------------------------------------------
|
||
// Calendar: month grid of reminders (incl. future repeats) and notes
|
||
// ------------------------------------------------------------------
|
||
let calTimer = null;
|
||
|
||
// Move a reminder to another day, keeping its time of day. For repeating
|
||
// reminders this shifts the whole series to start from the new day.
|
||
async function moveReminderToDay(r, key) {
|
||
state.cal.moving = null;
|
||
const old = new Date(r.due_at), d = keyToDate(key);
|
||
d.setHours(old.getHours(), old.getMinutes(), 0, 0);
|
||
if (dayKey(old) === key) { renderCalendar(); return; }
|
||
const prev = r.due_at;
|
||
r.due_at = d.toISOString(); state.cal.selected = key; renderRemViews();
|
||
const { error } = await sb.from('reminders').update({ due_at: r.due_at }).eq('id', r.id);
|
||
if (error) { r.due_at = prev; renderRemViews(); toast('Couldn\'t move: ' + error.message); return; }
|
||
toast(`Moved to ${whenLabel(d)}${d <= new Date() ? ' (that time has passed, so it\'s due now)' : ''}`, 'Undo', async () => {
|
||
const { data, error } = await sb.from('reminders').update({ due_at: prev }).eq('id', r.id).eq('due_at', d.toISOString()).select('id');
|
||
if (error || !data.length) toast(error ? 'Couldn\'t undo: ' + error.message : 'Can\'t undo: the reminder changed since the move.');
|
||
loadReminders();
|
||
});
|
||
loadReminders();
|
||
}
|
||
|
||
function startMove(r) {
|
||
if (state.view !== 'calendar') {
|
||
state.cal.selected = dayKey(new Date(r.due_at));
|
||
const sel = keyToDate(state.cal.selected); state.cal.month = new Date(sel.getFullYear(), sel.getMonth(), 1);
|
||
state.cal.moving = r; switchView('calendar'); return;
|
||
}
|
||
state.cal.moving = r; renderCalendar();
|
||
$('#view-calendar').scrollIntoView({ behavior: 'smooth' });
|
||
}
|
||
|
||
// Drag & drop (desktop): drag a reminder from the day list onto a day.
|
||
document.addEventListener('dragstart', (e) => {
|
||
const card = e.target.closest?.('#view-calendar .rem[draggable="true"]');
|
||
if (!card) return;
|
||
e.dataTransfer.setData('text/x-brainfeed-rem', card.dataset.rem);
|
||
e.dataTransfer.effectAllowed = 'move';
|
||
});
|
||
document.addEventListener('dragover', (e) => {
|
||
const cell = e.target.closest?.('#view-calendar [data-day]');
|
||
if (!cell || !e.dataTransfer.types.includes('text/x-brainfeed-rem')) return;
|
||
e.preventDefault();
|
||
document.querySelectorAll('#view-calendar .drop').forEach((x) => x !== cell && x.classList.remove('drop'));
|
||
cell.classList.add('drop');
|
||
});
|
||
document.addEventListener('dragleave', (e) => { e.target.closest?.('#view-calendar [data-day]')?.classList.remove('drop'); });
|
||
document.addEventListener('drop', (e) => {
|
||
const cell = e.target.closest?.('#view-calendar [data-day]');
|
||
const id = e.dataTransfer?.getData('text/x-brainfeed-rem');
|
||
if (!cell || !id) return;
|
||
e.preventDefault();
|
||
const r = state.reminders.find((x) => x.id === id);
|
||
if (r) moveReminderToDay(r, cell.dataset.day);
|
||
});
|
||
const pad2 = (x) => String(x).padStart(2, '0');
|
||
const dayKey = (d) => `${d.getFullYear()}-${pad2(d.getMonth() + 1)}-${pad2(d.getDate())}`;
|
||
const keyToDate = (k) => { const [y, m, d] = k.split('-').map(Number); return new Date(y, m - 1, d); };
|
||
|
||
function calRange() {
|
||
if (state.cal.mode === 'week') {
|
||
const start = keyToDate(state.cal.selected); start.setDate(start.getDate() - start.getDay());
|
||
const end = new Date(start); end.setDate(end.getDate() + 7);
|
||
return { start, end };
|
||
}
|
||
const m = state.cal.month;
|
||
const start = new Date(m.getFullYear(), m.getMonth(), 1);
|
||
start.setDate(start.getDate() - start.getDay()); // back to Sunday
|
||
const end = new Date(start); end.setDate(end.getDate() + 42); // 6 weeks
|
||
return { start, end };
|
||
}
|
||
|
||
// Occurrences of a reminder between from and to, in local time, using the
|
||
// same rules as the server (anchored to the original date; month-end clamps).
|
||
function occurrences(r, from, to) {
|
||
if (r.repeat === 'dates') return (r.dates || []).map((d) => new Date(d)).filter((d) => d >= from && d < to);
|
||
const d0 = new Date(r.due_at);
|
||
if (!r.repeat || r.done) return d0 >= from && d0 < to ? [d0] : [];
|
||
const at = (k) => {
|
||
const y = d0.getFullYear(), mo = d0.getMonth(), d = d0.getDate(), h = d0.getHours(), mi = d0.getMinutes();
|
||
if (r.repeat === 'daily' || r.repeat === 'weekdays') {
|
||
const x = new Date(y, mo, d + k, h, mi);
|
||
return r.repeat === 'weekdays' && (x.getDay() === 0 || x.getDay() === 6) ? null : x;
|
||
}
|
||
if (r.repeat === 'weekly') return new Date(y, mo, d + 7 * k, h, mi);
|
||
const months = r.repeat === 'monthly' ? k : 12 * k;
|
||
const first = new Date(y, mo + months, 1, h, mi);
|
||
first.setDate(Math.min(d, new Date(first.getFullYear(), first.getMonth() + 1, 0).getDate()));
|
||
return first;
|
||
};
|
||
const days = Math.floor((from - d0) / 864e5);
|
||
let k = Math.max(0, r.repeat === 'weekly' ? Math.floor(days / 7) - 1
|
||
: r.repeat === 'monthly' ? Math.floor(days / 31) - 1
|
||
: r.repeat === 'yearly' ? Math.floor(days / 366) - 1 : days - 1);
|
||
const out = [];
|
||
for (let n = 0; n < 400; n++, k++) {
|
||
const x = at(k);
|
||
if (!x) continue;
|
||
if (x >= to) break;
|
||
if (x >= from && x >= d0) out.push(x);
|
||
}
|
||
return out;
|
||
}
|
||
|
||
let calSeq = 0;
|
||
async function loadCalendarNotes() {
|
||
if (!state.cal.month) return;
|
||
const seq = ++calSeq;
|
||
const { start, end } = calRange();
|
||
const { data, error } = await sb.from('notes').select(NOTE_SELECT).is('archived_at', null)
|
||
.gte('created_at', start.toISOString()).lt('created_at', end.toISOString()).order('created_at').limit(2000);
|
||
if (seq !== calSeq) return; // you've already moved to another month or week
|
||
if (error) { toast('Couldn\'t load notes for the calendar: ' + error.message); return; }
|
||
state.cal.notes = data || [];
|
||
if (state.view === 'calendar') renderCalendar();
|
||
}
|
||
|
||
function renderCalendar() {
|
||
if (!state.cal.month) { const t = new Date(); state.cal.month = new Date(t.getFullYear(), t.getMonth(), 1); state.cal.selected = dayKey(t); }
|
||
const { start, end } = calRange();
|
||
const now = new Date(), todayKey = dayKey(now), month = state.cal.month.getMonth();
|
||
const rems = {}, notes = {};
|
||
for (const r of state.reminders) {
|
||
for (const at of occurrences(r, start, end)) {
|
||
(rems[dayKey(at)] ||= []).push({ r, at, real: at.getTime() === new Date(r.due_at).getTime() });
|
||
}
|
||
}
|
||
for (const n of state.cal.notes) (notes[dayKey(new Date(n.created_at))] ||= []).push(n);
|
||
// A specific date is finished once the reminder has moved past it (sent or checked off).
|
||
const isPast = (x) => x.r.repeat === 'dates' && !x.real && (x.r.done || x.at < new Date(x.r.due_at));
|
||
|
||
let grid = '';
|
||
if (state.cal.mode === 'week') {
|
||
for (let i = 0; i < 7; i++) {
|
||
const d = new Date(start.getFullYear(), start.getMonth(), start.getDate() + i);
|
||
const k = dayKey(d), rs = (rems[k] || []).sort((a, b) => a.at - b.at), ns = notes[k] || [];
|
||
grid += `<div class="week-day${k === todayKey ? ' today' : ''}${k === state.cal.selected ? ' selected' : ''}" data-day="${k}">
|
||
<h5>${esc(d.toLocaleDateString(undefined, { weekday: 'short' }))}<b>${d.getDate()}</b></h5>
|
||
${rs.map((x) => `<div class="wk-item${x.r.done || isPast(x) ? ' done' : !x.real ? ' proj' : x.at <= now ? ' over' : ''}"><span class="t">${esc(timeLabel(x.at))}</span>${esc(x.r.body)}</div>`).join('')}
|
||
${ns.length ? `<div class="wk-notes">✎ ${ns.length} note${ns.length > 1 ? 's' : ''}</div>` : ''}
|
||
</div>`;
|
||
}
|
||
} else {
|
||
grid = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'].map((d) => `<div class="cal-dow">${d}</div>`).join('');
|
||
for (let i = 0; i < 42; i++) {
|
||
const d = new Date(start.getFullYear(), start.getMonth(), start.getDate() + i);
|
||
const k = dayKey(d), rs = rems[k] || [], ns = notes[k] || [];
|
||
const open = rs.filter((x) => !x.r.done), over = open.some((x) => x.real && x.at <= now);
|
||
const cls = ['cal-day', d.getMonth() !== month && 'other', k === todayKey && 'today', k === state.cal.selected && 'selected'].filter(Boolean).join(' ');
|
||
grid += `<button class="${cls}" data-day="${k}" aria-label="${esc(d.toDateString())}"><span class="num">${d.getDate()}</span><span class="cal-dots">`
|
||
+ (rs.length ? `<span class="cal-dot r${over ? ' over' : open.length ? '' : ' done'}" title="Reminders">⏰${rs.length}</span>` : '')
|
||
+ (ns.length ? `<span class="cal-dot n" title="Notes">✎${ns.length}</span>` : '')
|
||
+ '</span></button>';
|
||
}
|
||
}
|
||
|
||
const sel = state.cal.selected, selDate = keyToDate(sel);
|
||
const dayRems = (rems[sel] || []).sort((a, b) => a.at - b.at);
|
||
const dayNotes = notes[sel] || [];
|
||
const remRows = dayRems.map((x) => ({ ...x, past: isPast(x) })).map(({ r, at, real, past }) => real ? remHtml(r).replace('<div class="rem', `<div draggable="${!r.done && r.repeat !== 'dates'}" class="rem`)
|
||
: `<div class="rem projected"><div class="rem-main"><div class="rem-text">${formatBody(r.body)}</div>
|
||
<div class="rem-when"><span>${esc(timeLabel(at))}</span><span class="src">${r.repeat === 'dates' ? (past ? '✓ done' : 'scheduled date') : '↻ ' + REPEAT_LABEL[r.repeat]}</span></div></div></div>`).join('');
|
||
const label = selDate.toLocaleDateString(undefined, { weekday: 'long', month: 'long', day: 'numeric', year: selDate.getFullYear() === now.getFullYear() ? undefined : 'numeric' });
|
||
|
||
$('#view-calendar').innerHTML = `<div class="cal-wrap">
|
||
<div>
|
||
${state.cal.moving ? `<div class="move-banner"><span>Tap a day to move "${esc(state.cal.moving.body.slice(0, 40))}"</span><button data-cal="move-cancel">Cancel</button></div>` : ''}
|
||
<div class="cal-head">
|
||
<button class="icon-btn" data-cal="prev" aria-label="Previous">‹</button>
|
||
<h2>${esc(state.cal.mode === 'week'
|
||
? `${start.toLocaleDateString(undefined, { month: 'short', day: 'numeric' })} – ${new Date(end - 864e5).toLocaleDateString(undefined, { month: 'short', day: 'numeric', year: 'numeric' })}`
|
||
: state.cal.month.toLocaleDateString(undefined, { month: 'long', year: 'numeric' }))}</h2>
|
||
<span class="cal-modes"><button data-cal="mode-month" class="${state.cal.mode === 'month' ? 'on' : ''}">Month</button><button data-cal="mode-week" class="${state.cal.mode === 'week' ? 'on' : ''}">Week</button></span>
|
||
<button class="btn ghost small" data-cal="today">Today</button>
|
||
<button class="icon-btn" data-cal="next" aria-label="Next">›</button>
|
||
</div>
|
||
<div class="${state.cal.mode === 'week' ? 'week' : 'cal-grid'}">${grid}</div>
|
||
</div>
|
||
<div class="cal-agenda">
|
||
<h3>${esc(label)}<span class="spacer"></span><button class="btn small" data-cal="add">+ Reminder</button></h3>
|
||
<h4>Reminders</h4>
|
||
${remRows || '<p style="color:var(--muted);margin:0">Nothing scheduled.</p>'}
|
||
<h4>Notes</h4>
|
||
${dayNotes.map((n) => noteHtml(n, true)).join('') || '<p style="color:var(--muted);margin:0">No notes this day.</p>'}
|
||
</div>
|
||
</div>`;
|
||
hydrateAttachments($('#view-calendar'));
|
||
}
|
||
|
||
$('#view-calendar').addEventListener('click', (e) => {
|
||
const day = e.target.closest('[data-day]');
|
||
if (day && state.cal.moving) { moveReminderToDay(state.cal.moving, day.dataset.day); return; }
|
||
if (day) {
|
||
state.cal.selected = day.dataset.day;
|
||
const d = keyToDate(day.dataset.day);
|
||
if (d.getMonth() !== state.cal.month.getMonth()) { state.cal.month = new Date(d.getFullYear(), d.getMonth(), 1); loadCalendarNotes(); }
|
||
renderCalendar(); return;
|
||
}
|
||
const c = e.target.closest('[data-cal]')?.dataset.cal;
|
||
if (c === 'move-cancel') { state.cal.moving = null; renderCalendar(); return; }
|
||
if (c === 'mode-month' || c === 'mode-week') {
|
||
state.cal.mode = c === 'mode-week' ? 'week' : 'month';
|
||
const sel = keyToDate(state.cal.selected); state.cal.month = new Date(sel.getFullYear(), sel.getMonth(), 1);
|
||
renderCalendar(); loadCalendarNotes(); return;
|
||
}
|
||
if ((c === 'prev' || c === 'next') && state.cal.mode === 'week') {
|
||
const d = keyToDate(state.cal.selected); d.setDate(d.getDate() + (c === 'next' ? 7 : -7));
|
||
state.cal.selected = dayKey(d); state.cal.month = new Date(d.getFullYear(), d.getMonth(), 1);
|
||
renderCalendar(); loadCalendarNotes(); return;
|
||
}
|
||
if (c === 'prev' || c === 'next') {
|
||
const m = state.cal.month;
|
||
state.cal.month = new Date(m.getFullYear(), m.getMonth() + (c === 'next' ? 1 : -1), 1);
|
||
renderCalendar(); loadCalendarNotes(); return;
|
||
}
|
||
if (c === 'today') {
|
||
const t = new Date();
|
||
state.cal.month = new Date(t.getFullYear(), t.getMonth(), 1); state.cal.selected = dayKey(t);
|
||
renderCalendar(); loadCalendarNotes(); return;
|
||
}
|
||
if (c === 'add') {
|
||
const d = keyToDate(state.cal.selected), now = new Date();
|
||
d.setHours(9, 0, 0, 0);
|
||
if (d <= now) { d.setTime(now.getTime() + 3600e3); d.setMinutes(0, 0, 0); }
|
||
switchView('feed'); setRemindMode(true);
|
||
$('#remind-at').value = toLocalInput(d);
|
||
return;
|
||
}
|
||
if (e.target.closest('[data-rem-act]')) onReminderClick(e);
|
||
});
|
||
|
||
function checkDueReminders() {
|
||
const alerted = lsGet(LS.alerted, {});
|
||
const now = new Date();
|
||
let changed = false;
|
||
for (const r of state.reminders) {
|
||
if (r.done || new Date(r.due_at) > now) continue;
|
||
// Only alert for things that became due in the last 12 hours, once per occurrence
|
||
if (now - new Date(r.due_at) > 12 * 3600e3 || alerted[r.id] === r.due_at) continue;
|
||
alerted[r.id] = r.due_at; changed = true;
|
||
toast('⏰ ' + r.body, 'Open', () => switchView('reminders'), 10000);
|
||
try { if (!lsGet(LS.pushOn, false) && Notification?.permission === 'granted') new Notification('BrainFeed reminder', { body: r.body, icon: 'icon-192.png', tag: r.id }); } catch {}
|
||
}
|
||
if (changed) lsSet(LS.alerted, alerted);
|
||
loadReminders();
|
||
}
|
||
|
||
// ------------------------------------------------------------------
|
||
// Settings: time zone + connected agents (Hermes)
|
||
// ------------------------------------------------------------------
|
||
// ------------------------------------------------------------------
|
||
// Push notifications on this device (Web Push). The brainfeed-push function sends
|
||
// due reminders to every device saved in push_subscriptions. On iPhone this needs
|
||
// BrainFeed added to the Home Screen and opened from there (iOS 16.4+).
|
||
// ------------------------------------------------------------------
|
||
const VAPID_PUBLIC = 'BOUsYUcq3tG_W4WOxdnQg3lnjPT15AfqY33xzJw2d12NUdrjz1Kck3_Hj32rOJ2QgnZ5iH214gkNgX1dO5O7mQ4';
|
||
const Push = {
|
||
supported: () => 'serviceWorker' in navigator && 'PushManager' in window && 'Notification' in window,
|
||
isIOS: () => /iPhone|iPad|iPod/.test(navigator.userAgent) || (navigator.platform === 'MacIntel' && navigator.maxTouchPoints > 1),
|
||
standalone: () => matchMedia('(display-mode: standalone)').matches || navigator.standalone === true,
|
||
device() {
|
||
const ua = navigator.userAgent;
|
||
const os = /iPhone/.test(ua) ? 'iPhone' : /iPad/.test(ua) || Push.isIOS() ? 'iPad' : /Android/.test(ua) ? 'Android' : /Mac/.test(ua) ? 'Mac' : /Windows/.test(ua) ? 'Windows' : 'Device';
|
||
const br = /Edg\//.test(ua) ? 'Edge' : /Chrome\//.test(ua) ? 'Chrome' : /Firefox\//.test(ua) ? 'Firefox' : /Safari\//.test(ua) ? 'Safari' : 'browser';
|
||
return Push.standalone() ? `${os} (home-screen app)` : `${os} · ${br}`;
|
||
},
|
||
async current() {
|
||
if (!Push.supported()) return null;
|
||
const reg = await navigator.serviceWorker.getRegistration();
|
||
return reg ? reg.pushManager.getSubscription() : null;
|
||
},
|
||
key() {
|
||
const b = atob(VAPID_PUBLIC.replace(/-/g, '+').replace(/_/g, '/') + '='.repeat((4 - VAPID_PUBLIC.length % 4) % 4));
|
||
return Uint8Array.from(b, (c) => c.charCodeAt(0));
|
||
},
|
||
async enable() {
|
||
const perm = await Notification.requestPermission();
|
||
if (perm !== 'granted') throw new Error(perm === 'denied' ? 'Notifications are blocked for BrainFeed. Allow them in your browser or iPhone settings, then try again.' : 'Notifications weren\'t allowed.');
|
||
const reg = await navigator.serviceWorker.ready;
|
||
const sub = (await reg.pushManager.getSubscription()) || await reg.pushManager.subscribe({ userVisibleOnly: true, applicationServerKey: Push.key() });
|
||
const j = sub.toJSON();
|
||
const { error } = await sb.from('push_subscriptions').upsert(
|
||
{ endpoint: j.endpoint, p256dh: j.keys.p256dh, auth: j.keys.auth, device: Push.device() }, { onConflict: 'endpoint' });
|
||
if (error) { await sub.unsubscribe().catch(() => {}); throw new Error('Couldn\'t save this device: ' + error.message); }
|
||
lsSet(LS.pushOn, true);
|
||
return sub;
|
||
},
|
||
async disable() {
|
||
const sub = await Push.current();
|
||
if (sub) { await sb.from('push_subscriptions').delete().eq('endpoint', sub.endpoint); await sub.unsubscribe().catch(() => {}); }
|
||
lsSet(LS.pushOn, false);
|
||
},
|
||
async test() {
|
||
const sub = await Push.current();
|
||
const { data, error } = await sb.functions.invoke('brainfeed-push', { body: { test: true, endpoint: sub?.endpoint } });
|
||
if (error) throw new Error('The test couldn\'t be sent.');
|
||
return data;
|
||
},
|
||
};
|
||
|
||
// "Where should reminders go?" (settings.reminder_delivery). The server makes Telegram
|
||
// a backup for phone-only: anything a notification couldn't deliver within 10 minutes,
|
||
// or everything when no device has notifications on.
|
||
const DELIVERY = [
|
||
['both', 'Phone notifications and Telegram'],
|
||
['push', 'Phone notifications only (Telegram as backup)'],
|
||
['telegram', 'Telegram only'],
|
||
];
|
||
function deliveryHtml(deviceCount) {
|
||
const cur = state.settings?.reminder_delivery || 'both';
|
||
const note = cur === 'push' && !deviceCount ? 'No device has notifications on yet, so Telegram keeps delivering until you turn them on.'
|
||
: cur === 'push' ? 'If a notification can\'t be delivered, the reminder goes to Telegram after 10 minutes.'
|
||
: cur === 'telegram' ? 'Devices with notifications on won\'t get reminders until you change this.' : '';
|
||
return `<p class="help" style="margin:12px 0 6px"><strong>Where should reminders go?</strong></p>
|
||
<select class="field" id="set-delivery">${DELIVERY.map(([v, l]) => `<option value="${v}"${v === cur ? ' selected' : ''}>${l}</option>`).join('')}</select>
|
||
${note ? `<p class="help" style="margin-top:6px">${note}</p>` : ''}`;
|
||
}
|
||
|
||
// The Notifications section of Settings.
|
||
async function renderPushSection(el) {
|
||
if (!Push.supported() || location.protocol !== 'https:') {
|
||
const { count } = await sb.from('push_subscriptions').select('id', { count: 'exact', head: true });
|
||
el.innerHTML = (Push.isIOS() && !Push.standalone()
|
||
? '<p class="help">On iPhone, notifications need BrainFeed on your Home Screen: in Safari tap Share → <strong>Add to Home Screen</strong>, then open BrainFeed from that icon and come back here.</p>'
|
||
: '<p class="help">This browser can\'t receive push notifications. Telegram reminders through Hermes still work.</p>') + deliveryHtml(count || 0);
|
||
return;
|
||
}
|
||
const sub = await Push.current();
|
||
const { data: devices } = await sb.from('push_subscriptions').select('endpoint,device,last_ok_at,created_at').order('created_at');
|
||
const mine = sub && (devices || []).some((d) => d.endpoint === sub.endpoint);
|
||
lsSet(LS.pushOn, !!mine);
|
||
const others = (devices || []).filter((d) => !sub || d.endpoint !== sub.endpoint);
|
||
el.innerHTML = `<p class="help">Get a notification on this device when a reminder is due, even when BrainFeed is closed. Choose below whether Telegram gets them too.</p>
|
||
<div class="row">${mine
|
||
? '<span style="align-self:center;font-size:14px">🔔 On for this device</span><span class="spacer" style="flex:1"></span><button class="btn ghost small" data-set="push-test">Send test</button><button class="btn ghost small" data-set="push-off">Turn off</button>'
|
||
: '<button class="btn small" data-set="push-on">Turn on notifications</button>'}</div>
|
||
${others.length ? `<p class="help" style="margin-top:8px">Also on: ${others.map((d) => esc(d.device || 'another device')).join(', ')}</p>` : ''}
|
||
${deliveryHtml((devices || []).length)}`;
|
||
}
|
||
|
||
async function openSettings(focus) {
|
||
await loadAgents();
|
||
const tz = state.settings?.timezone || 'UTC';
|
||
let zones = [];
|
||
try { zones = Intl.supportedValuesOf('timeZone'); } catch {}
|
||
const back = document.createElement('div');
|
||
back.className = 'modal-back';
|
||
back.innerHTML = `<div class="modal" role="dialog" aria-label="Settings">
|
||
<h2>Settings<span class="spacer"></span><button class="tool" data-set="close" aria-label="Close">✕</button></h2>
|
||
<h3 id="set-push-h">Notifications</h3>
|
||
<div id="set-push"><p class="help">Checking…</p></div>
|
||
<h3>Seasonal theme</h3>
|
||
<p class="help">Colors, a header stripe and a little emoji that change on the 1st of each month. Applies on this device.</p>
|
||
<div class="row">
|
||
<select class="field" id="set-season">
|
||
<option value="auto">Seasonal (changes monthly)</option>
|
||
<option value="off">Off (classic purple)</option>
|
||
${MONTH_KEYS.map((k, i) => `<option value="${k}">Always ${esc(SEASONS[k].name)} ${SEASONS[k].emoji} (${new Date(2026, i, 1).toLocaleDateString(undefined, { month: 'short' })})</option>`).join('')}
|
||
</select>
|
||
</div>
|
||
<label style="display:flex;align-items:center;gap:8px;margin-top:8px;font-size:14px"><input type="checkbox" id="set-fx"> Seasonal effects (snow, leaves, bats)</label>
|
||
<h3>Time zone</h3>
|
||
<p class="help">Used for reminder times, recurring reminders and what Hermes means by "9am".</p>
|
||
<div class="row">
|
||
<input class="field" id="set-tz" list="tz-list" value="${esc(tz)}" autocomplete="off">
|
||
<datalist id="tz-list">${zones.map((z) => `<option value="${esc(z)}">`).join('')}</datalist>
|
||
<button class="btn small" data-set="tz">Save</button>
|
||
</div>
|
||
<h3>Connected agents</h3>
|
||
<p class="help">Paste the fingerprint Hermes gives you (it looks like <code>sha256:</code> followed by 64 characters). BrainFeed stores only the fingerprint; the real token never leaves your server.</p>
|
||
<div class="row">
|
||
<input class="field" id="agent-name" placeholder="Name" value="Hermes" style="flex:0 0 120px">
|
||
<input class="field" id="agent-fp" placeholder="sha256:…" autocomplete="off" spellcheck="false">
|
||
<button class="btn small" data-set="add">Connect</button>
|
||
</div>
|
||
<div id="agent-list" style="margin-top:12px"></div>
|
||
</div>`;
|
||
document.body.appendChild(back);
|
||
const pushEl = back.querySelector('#set-push');
|
||
pushEl.addEventListener('change', async (e) => {
|
||
if (e.target.id !== 'set-delivery') return;
|
||
const v = e.target.value, prev = state.settings?.reminder_delivery || 'both';
|
||
const { data, error } = await sb.from('settings').update({ reminder_delivery: v, updated_at: new Date().toISOString() }).eq('user_id', state.user.id).select().single();
|
||
if (error) { toast('Couldn\'t save: ' + error.message); e.target.value = prev; return; }
|
||
state.settings = data;
|
||
toast(v === 'push' ? 'Reminders will go to your phone (Telegram as backup)' : v === 'telegram' ? 'Reminders will go to Telegram only' : 'Reminders will go to your phone and Telegram');
|
||
renderPushSection(pushEl).catch(() => {});
|
||
});
|
||
renderPushSection(pushEl).catch(() => { pushEl.innerHTML = '<p class="help">Couldn\'t check notifications on this device.</p>'; });
|
||
if (focus === 'push') back.querySelector('#set-push-h').scrollIntoView({ block: 'start' });
|
||
back.querySelector('#set-season').value = lsGet(LS.season, 'auto');
|
||
back.querySelector('#set-fx').checked = lsGet(LS.seasonFx, true);
|
||
back.querySelector('#set-season').addEventListener('change', (e) => { lsSet(LS.season, e.target.value); applyTheme(); renderFeed(); });
|
||
back.querySelector('#set-fx').addEventListener('change', (e) => { lsSet(LS.seasonFx, e.target.checked); applySeason(); });
|
||
const render = () => {
|
||
back.querySelector('#agent-list').innerHTML = state.agents.length ? state.agents.map((t) => `
|
||
<div class="agent${t.revoked_at ? ' revoked' : ''}" data-agent="${t.id}">
|
||
<div class="info"><strong>${esc(t.name)}</strong> · ${t.revoked_at ? 'revoked' : t.last_used_at ? 'last used ' + esc(agoLabel(t.last_used_at)) : 'never used yet'}<br>
|
||
<code>${esc(t.token_hash.slice(0, 19))}…${esc(t.token_hash.slice(-6))}</code> · added ${esc(new Date(t.created_at).toLocaleDateString())}</div>
|
||
${t.revoked_at ? '<button class="btn ghost small" data-set="remove">Remove</button>' : '<button class="btn ghost small" data-set="revoke" style="color:var(--danger)">Revoke</button>'}
|
||
</div>`).join('') : '<p class="help">No agents connected.</p>';
|
||
};
|
||
render();
|
||
const close = () => { back.remove(); document.removeEventListener('keydown', onKey); if (state.view === 'reminders') renderReminders(); };
|
||
const onKey = (e) => { if (e.key === 'Escape') close(); };
|
||
document.addEventListener('keydown', onKey);
|
||
back.addEventListener('click', async (e) => {
|
||
if (e.target === back) { close(); return; }
|
||
const act = e.target.closest('[data-set]')?.dataset.set; if (!act) return;
|
||
if (act === 'close') close();
|
||
else if (act === 'push-on' || act === 'push-off' || act === 'push-test') {
|
||
const btn = e.target.closest('button'); btn.disabled = true;
|
||
try {
|
||
if (act === 'push-on') { await Push.enable(); toast('Notifications on for this device 🔔'); await Push.test().catch(() => {}); }
|
||
else if (act === 'push-off') { await Push.disable(); toast('Notifications off for this device'); }
|
||
else { const r = await Push.test(); toast(r?.sent ? 'Test sent. It should appear in a few seconds.' : (r?.message || 'No notification was delivered.')); }
|
||
} catch (err) { toast(err.message || 'Something went wrong'); }
|
||
btn.disabled = false;
|
||
renderPushSection(pushEl).catch(() => {});
|
||
}
|
||
else if (act === 'tz') {
|
||
const v = back.querySelector('#set-tz').value.trim();
|
||
try { new Intl.DateTimeFormat('en-US', { timeZone: v }); } catch { toast('That isn\'t a valid time zone'); return; }
|
||
const { data, error } = await sb.from('settings').update({ timezone: v, updated_at: new Date().toISOString() }).eq('user_id', state.user.id).select().single();
|
||
if (error) { toast('Couldn\'t save: ' + error.message); return; }
|
||
state.settings = data; toast('Time zone set to ' + v);
|
||
} else if (act === 'add') {
|
||
const fp = back.querySelector('#agent-fp').value.trim().toLowerCase();
|
||
const name = back.querySelector('#agent-name').value.trim() || 'Hermes';
|
||
if (!/^sha256:[0-9a-f]{64}$/.test(fp)) { toast('Fingerprint should be sha256: followed by 64 hex characters'); return; }
|
||
const { error } = await sb.from('api_tokens').insert({ name, token_hash: fp });
|
||
if (error) { toast(/duplicate/i.test(error.message) ? 'That fingerprint is already connected' : 'Couldn\'t connect: ' + error.message); return; }
|
||
back.querySelector('#agent-fp').value = '';
|
||
toast(name + ' connected. Tell Hermes to run its activation step.');
|
||
await loadAgents(); render();
|
||
} else if (act === 'revoke') {
|
||
const id = e.target.closest('[data-agent]').dataset.agent;
|
||
const { error } = await sb.from('api_tokens').update({ revoked_at: new Date().toISOString() }).eq('id', id);
|
||
if (error) { toast('Couldn\'t revoke: ' + error.message); return; }
|
||
toast('Revoked. That agent can no longer access BrainFeed.');
|
||
await loadAgents(); render();
|
||
} else if (act === 'remove') {
|
||
const id = e.target.closest('[data-agent]').dataset.agent;
|
||
await sb.from('api_tokens').delete().eq('id', id);
|
||
await loadAgents(); render();
|
||
}
|
||
});
|
||
}
|
||
|
||
// ------------------------------------------------------------------
|
||
// Incoming notes from URL: iOS Shortcuts (?add=...) and the Android
|
||
// share sheet (?title=&text=&url=). Saves once, then cleans the URL.
|
||
// ------------------------------------------------------------------
|
||
async function handleIncoming() {
|
||
const p = new URLSearchParams(location.search);
|
||
if (p.get('view') === 'reminders') { history.replaceState(null, '', location.pathname); switchView('reminders'); return; }
|
||
const add = p.get('add');
|
||
const shared = [p.get('title'), p.get('text'), p.get('url')].filter(Boolean);
|
||
const body = (add || [...new Set(shared)].join('\n')).trim();
|
||
if (!body) return;
|
||
history.replaceState(null, '', location.pathname);
|
||
await addNote(body, [], add ? (p.get('source') || 'shortcut') : 'share');
|
||
toast('Saved to BrainFeed');
|
||
}
|
||
|
||
// ------------------------------------------------------------------
|
||
// Service worker
|
||
// ------------------------------------------------------------------
|
||
if ('serviceWorker' in navigator && location.protocol === 'https:') {
|
||
navigator.serviceWorker.register('sw.js').catch(() => {});
|
||
// A tapped notification focuses an open BrainFeed window and tells it where to go.
|
||
navigator.serviceWorker.addEventListener('message', (e) => {
|
||
if (e.data?.type === 'open' && /[?&]view=reminders/.test(e.data.url || '') && state.user) switchView('reminders');
|
||
});
|
||
}
|
||
</script>
|
||
</body>
|
||
</html>
|