Files
cabinchat/www/index.html
T
Pascal SuterandClaude Opus 5.5 7e8d07e6c1 Add cabinchat: web chat for OpenWrt travel routers
Web app, uhttpd shell CGI backend, installer, build script and dev
server. README merged with the repository's project description.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 11:28:27 +01:00

1115 lines
51 KiB
HTML
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover, interactive-widget=resizes-content">
<meta name="theme-color" content="#14171d">
<meta name="color-scheme" content="dark">
<meta name="mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
<title>Cabin Chat</title>
<link rel="icon" href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 100 100'%3E%3Ctext y='.9em' font-size='90'%3E%E2%9C%88%EF%B8%8F%3C/text%3E%3C/svg%3E">
<style>
:root{
--bg:#0e1014; --panel:#14171d; --panel2:#1d2129; --line:#252a34;
--text:#e8ecf2; --muted:#8b93a5; --accent:#3d7bfd; --mine:#2f6be6; --theirs:#1e232c;
--ok:#22c55e; --bad:#f05252;
--emoji:"Apple Color Emoji","Segoe UI Emoji","Noto Color Emoji",sans-serif;
}
*{box-sizing:border-box;-webkit-tap-highlight-color:transparent}
[hidden]{display:none!important}
html,body{margin:0;height:100%;overflow:hidden;background:var(--bg);color:var(--text);
font:16px/1.38 -apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,"Helvetica Neue",Arial,sans-serif}
button{font:inherit;color:inherit;cursor:pointer}
#app{position:fixed;left:0;right:0;top:0;height:100dvh;display:flex;will-change:transform;overflow:hidden}
#chat{position:relative;flex:1;min-width:0;display:flex;flex-direction:column}
/* avatars */
.avatar{position:relative;flex:none;width:44px;height:44px;border-radius:50%;display:grid;place-items:center;
font-weight:600;font-size:18px;color:#fff}
.avatar.group{background:linear-gradient(135deg,#3d7bfd,#8b5cf6);font:20px var(--emoji)}
.avatar .on{position:absolute;right:-1px;bottom:-1px;width:13px;height:13px;border-radius:50%;
background:var(--ok);border:2.5px solid var(--panel)}
header .avatar{width:38px;height:38px;font-size:16px}
/* people drawer (sidebar on wide screens) */
#people{position:absolute;inset:0;z-index:6;display:flex;flex-direction:column;background:var(--panel);
transform:translateX(-100%);transition:transform .25s ease;visibility:hidden}
#app.people #people{transform:none;visibility:visible}
.phead{display:flex;align-items:center;gap:10px;padding:calc(env(safe-area-inset-top) + 12px) 12px 12px 18px;
border-bottom:1px solid var(--line)}
.phead b{flex:1;font-size:21px}
#plist{flex:1;overflow-y:auto;overscroll-behavior:contain;padding:6px}
.psec{padding:14px 12px 5px;font-size:12px;font-weight:600;letter-spacing:.6px;text-transform:uppercase;color:var(--muted)}
.pitem{display:flex;align-items:center;gap:12px;width:100%;padding:9px 10px;border:0;border-radius:14px;
background:none;text-align:left}
.pitem:active,.pitem.active{background:var(--panel2)}
.pmain{flex:1;min-width:0}
.pname,.psub{white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
.pname{font-weight:600;font-size:15.5px}
.psub{font-size:13.5px;color:var(--muted)}
.psub.typing{color:var(--accent)}
.pside{display:flex;flex-direction:column;align-items:flex-end;gap:5px;min-height:38px}
.ptime{font-size:11.5px;color:var(--muted)}
.pbadge{min-width:20px;height:20px;padding:0 6px;border-radius:10px;background:var(--accent);color:#fff;
font-size:12px;line-height:20px;text-align:center}
.pnone{padding:8px 12px;color:var(--muted);font-size:14px}
.pfoot{display:flex;align-items:center;gap:10px;padding:10px 14px calc(10px + env(safe-area-inset-bottom));
border-top:1px solid var(--line)}
.pfoot .ver{flex:1;text-align:right;font-size:11.5px;color:#596173}
.chip{max-width:60%;border:0;border-radius:999px;padding:8px 14px;background:var(--panel2);font-size:14px;
white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
@media (min-width:760px){
#people{position:relative;inset:auto;width:310px;flex:none;transform:none;visibility:visible;border-right:1px solid var(--line)}
#peopleBtn,#closePeople{display:none!important}
}
/* header */
header{flex:none;display:flex;align-items:center;gap:10px;
padding:calc(env(safe-area-inset-top) + 9px) 14px 9px 6px;
background:rgba(20,23,29,.92);-webkit-backdrop-filter:blur(14px);backdrop-filter:blur(14px);
border-bottom:1px solid var(--line);z-index:2}
@media (min-width:760px){ header{padding-left:16px} }
#peopleBtn{position:relative;width:42px;height:42px}
#peopleBadge{position:absolute;top:2px;right:0;min-width:18px;height:18px;padding:0 5px;border-radius:9px;
background:var(--accent);color:#fff;font-size:11px;line-height:18px;text-align:center}
.title{flex:1;min-width:0}
.title b{display:block;font-size:17px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
.status{display:flex;align-items:center;gap:6px;font-size:12.5px;color:var(--muted);white-space:nowrap;overflow:hidden}
.status.typing{color:var(--accent)}
.status.bad{color:var(--bad)}
/* messages */
#wrap{position:relative;flex:1;min-height:0}
#log{position:absolute;inset:0;overflow-y:auto;overscroll-behavior:contain;-webkit-overflow-scrolling:touch;
padding:10px 10px 8px}
.empty{color:var(--muted);text-align:center;margin-top:26vh;font-size:15px;line-height:1.6}
.row{display:flex;flex-direction:column;align-items:flex-start;margin-top:2px;touch-action:pan-y}
.row.first{margin-top:12px}
.row.mine{align-items:flex-end}
.name{font-size:12.5px;font-weight:600;margin:0 0 3px 12px}
.bubble{position:relative;max-width:min(80%,520px);padding:7px 12px 7px;border-radius:20px;
background:var(--theirs);overflow-wrap:anywhere;white-space:pre-wrap;transition:transform .2s,filter .2s}
.bubble.swiping{transition:none}
.bubble.sel{filter:brightness(1.3)}
.bubble.flash{animation:flash 1.4s ease}
@keyframes flash{0%,45%{box-shadow:0 0 0 3px var(--accent)}100%{box-shadow:0 0 0 3px transparent}}
@media (pointer:coarse){ .bubble,.bubble img{-webkit-user-select:none;user-select:none;-webkit-touch-callout:none} }
.mine .bubble{background:var(--mine);color:#fff}
.row:not(.mine).last .bubble{border-bottom-left-radius:6px}
.row.mine.last .bubble{border-bottom-right-radius:6px}
.meta{float:right;margin:7px 0 -3px 10px;font-size:11px;line-height:1;color:var(--muted);white-space:nowrap}
.mine .meta{color:rgba(255,255,255,.72)}
.bubble.jumbo{background:none!important;padding:0 2px;font:44px/1.15 var(--emoji)}
.bubble.jumbo .meta{display:block;float:none;text-align:right;margin:2px 4px 0;font:11px/1 -apple-system,sans-serif;color:var(--muted)}
.bubble.media{padding:3px;line-height:0}
.media img.photo{display:block;width:min(280px,64vw);height:auto;min-height:60px;border-radius:17px;background:#0006;cursor:zoom-in}
.row.mine.last .media img.photo{border-bottom-right-radius:4px}
.row:not(.mine).last .media img.photo{border-bottom-left-radius:4px}
.media .meta{position:absolute;right:10px;bottom:9px;float:none;margin:0;padding:4px 7px;border-radius:10px;
background:rgba(0,0,0,.55);color:#fff}
.pending img.photo{opacity:.45}
.spin{position:absolute;inset:0;margin:auto;width:34px;height:34px;border-radius:50%;
border:3px solid rgba(255,255,255,.3);border-top-color:#fff;animation:spin 1s linear infinite}
@keyframes spin{to{transform:rotate(360deg)}}
/* quotes */
.quote{display:flex;align-items:center;gap:8px;margin:1px 0 6px;padding:5px 9px;border-left:3px solid var(--accent);
border-radius:8px;background:rgba(255,255,255,.06);font-size:13.5px;line-height:1.3;white-space:normal;cursor:pointer}
.quote .qt{min-width:0}
.quote b{display:block;font-size:12.5px}
.quote span{display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical;overflow:hidden;color:var(--muted)}
.quote img{flex:none;width:36px;height:36px;object-fit:cover;border-radius:6px}
.quote.gone span{font-style:italic}
.mine .quote{background:rgba(255,255,255,.16);border-left-color:rgba(255,255,255,.8)}
.mine .quote b{color:#fff!important}
.mine .quote span{color:rgba(255,255,255,.82)}
.media .quote{margin:4px 4px 6px}
.bubble.hasq{min-width:min(200px,70vw)}
/* typing indicator */
#typingRow{display:flex;flex-direction:column;align-items:flex-start;margin-top:12px}
#typingRow .tn{font-size:12px;color:var(--muted);margin:0 0 3px 12px}
.dots{display:flex;gap:4px;padding:13px 14px;border-radius:20px;border-bottom-left-radius:6px;background:var(--theirs)}
.dots i{width:7px;height:7px;border-radius:50%;background:var(--muted);animation:blink 1.3s infinite}
.dots i:nth-child(2){animation-delay:.18s}
.dots i:nth-child(3){animation-delay:.36s}
@keyframes blink{0%,60%,100%{opacity:.35;transform:none}30%{opacity:1;transform:translateY(-3px)}}
#jump{position:absolute;right:14px;bottom:14px;width:44px;height:44px;border-radius:50%;
border:1px solid var(--line);background:var(--panel2);display:grid;place-items:center;
box-shadow:0 6px 20px rgba(0,0,0,.5)}
#jump svg{width:22px;height:22px}
#badge{position:absolute;top:-6px;right:-4px;min-width:20px;height:20px;padding:0 5px;border-radius:10px;
background:var(--accent);color:#fff;font-size:12px;line-height:20px;text-align:center}
/* composer */
footer{flex:none;background:var(--panel);border-top:1px solid var(--line);padding-bottom:env(safe-area-inset-bottom)}
#app.kb footer{padding-bottom:0}
#replyBar{display:flex;align-items:center;gap:8px;padding:8px 8px 0 14px}
#replyBar .rq{flex:1;min-width:0;padding:2px 10px;border-left:3px solid var(--accent);font-size:13.5px}
#replyBar b{display:block;font-size:13px;color:var(--accent)}
#replyBar span{display:block;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;color:var(--muted)}
#bar{display:flex;align-items:flex-end;gap:8px;padding:8px 10px}
.field{flex:1;min-width:0;display:flex;align-items:center;min-height:44px;padding:3px;border-radius:24px;
background:var(--panel2);border:1px solid transparent;transition:border-color .2s}
.field:focus-within{border-color:#34405a}
.field input{flex:1;min-width:0;border:0;outline:0;background:transparent;color:var(--text);font-size:16px;padding:8px 4px}
.field input::placeholder{color:var(--muted)}
.icon{flex:none;width:38px;height:38px;border:0;border-radius:50%;background:transparent;color:var(--muted);
display:grid;place-items:center;padding:0}
.icon:active{background:rgba(255,255,255,.08)}
.icon svg{width:24px;height:24px}
.send{flex:none;width:46px;height:46px;border:0;border-radius:50%;background:var(--accent);color:#fff;
display:grid;place-items:center;padding:0;transition:transform .15s,opacity .2s}
.send svg{width:22px;height:22px;margin-left:2px}
.send:disabled{opacity:.35}
.send:not(:disabled):active{transform:scale(.92)}
/* emoji panel */
#emoji{height:0;overflow:hidden;transition:height .2s ease}
#emoji.open{height:290px}
#egrid{height:244px;overflow-y:auto;display:grid;grid-template-columns:repeat(auto-fill,minmax(46px,1fr));
align-content:start;padding:4px 8px}
#egrid button{height:46px;border:0;border-radius:12px;background:none;font:28px/1 var(--emoji);padding:0}
#egrid button:active{background:rgba(255,255,255,.08)}
.enone{grid-column:1/-1;color:var(--muted);text-align:center;padding-top:80px;font-size:14px}
#etabs{height:46px;display:flex;border-top:1px solid var(--line)}
#etabs button{flex:1;border:0;background:none;font:21px/1 var(--emoji);opacity:.4;transition:opacity .2s}
#etabs button.on{opacity:1}
/* message menu */
#menuBack{position:fixed;inset:0;z-index:8}
#menu{position:fixed;z-index:9;min-width:180px;padding:5px;border:1px solid var(--line);border-radius:14px;
background:#232833;box-shadow:0 12px 36px rgba(0,0,0,.6)}
#menu button{display:flex;align-items:center;gap:12px;width:100%;padding:11px 12px;border:0;border-radius:10px;
background:none;font-size:15px;text-align:left}
#menu button:hover,#menu button:active{background:rgba(255,255,255,.07)}
#menu svg{width:20px;height:20px;color:var(--muted)}
/* overlays */
#viewer{position:fixed;inset:0;z-index:10;background:rgba(0,0,0,.94);display:flex;align-items:center;justify-content:center;
padding:env(safe-area-inset-top) 0 env(safe-area-inset-bottom)}
#viewer img{max-width:100%;max-height:100%;object-fit:contain}
#modal{position:fixed;inset:0;z-index:11;background:rgba(5,6,9,.7);-webkit-backdrop-filter:blur(6px);backdrop-filter:blur(6px);
display:flex;justify-content:center;align-items:flex-start;padding:16vh 20px 0}
.card{width:100%;max-width:360px;background:var(--panel);border:1px solid var(--line);border-radius:24px;padding:26px 22px 20px;
text-align:center;box-shadow:0 20px 60px rgba(0,0,0,.6)}
.card .avatar{margin:0 auto 14px;width:58px;height:58px;font-size:30px}
.card h2{margin:0 0 6px;font-size:21px}
.card p{margin:0 0 18px;color:var(--muted);font-size:14.5px}
.card input{width:100%;font-size:17px;padding:13px 16px;border-radius:14px;border:1px solid var(--line);
background:var(--panel2);color:var(--text);outline:0;text-align:center}
.card input:focus{border-color:var(--accent)}
.primary{width:100%;margin-top:12px;padding:13px;border:0;border-radius:14px;background:var(--accent);color:#fff;font-weight:600;font-size:16px}
#toast{position:fixed;left:50%;top:calc(env(safe-area-inset-top) + 70px);z-index:12;transform:translate(-50%,-10px);
max-width:86vw;padding:10px 16px;border-radius:14px;background:#2a303b;color:var(--text);font-size:14px;
white-space:nowrap;overflow:hidden;text-overflow:ellipsis;
box-shadow:0 8px 24px rgba(0,0,0,.5);opacity:0;pointer-events:none;transition:opacity .25s,transform .25s}
#toast.show{opacity:1;transform:translate(-50%,0)}
#toast.click{pointer-events:auto;cursor:pointer}
</style>
</head>
<body>
<div id="app">
<aside id="people">
<div class="phead">
<b>Chats</b>
<button class="icon" id="closePeople" aria-label="Close">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><path d="M6 6l12 12M18 6L6 18"/></svg>
</button>
</div>
<div id="plist"></div>
<div class="pfoot">
<button class="chip" id="me" title="Change your name"></button>
<span class="ver" id="ver"></span>
</div>
</aside>
<section id="chat">
<header>
<button class="icon" id="peopleBtn" aria-label="Chats and people">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round"><circle cx="9" cy="8.5" r="3.3"/><path d="M2.8 19.5c.6-3.3 3.1-5.3 6.2-5.3s5.6 2 6.2 5.3"/><path d="M15.5 5.6a3.2 3.2 0 0 1 0 6M17.6 14.6c1.9.6 3.2 2.3 3.6 4.9"/></svg>
<span id="peopleBadge" hidden></span>
</button>
<div id="hAvatar"></div>
<div class="title">
<b id="hTitle">Everyone</b>
<span class="status" id="hSub">Connecting…</span>
</div>
</header>
<main id="wrap">
<div id="log">
<div class="empty" id="empty"></div>
<div id="typingRow" hidden><span class="tn" id="typingName"></span><div class="dots"><i></i><i></i><i></i></div></div>
</div>
<button id="jump" hidden aria-label="Jump to newest">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 5v14M6 13l6 6 6-6"/></svg>
<span id="badge" hidden></span>
</button>
</main>
<footer>
<div id="replyBar" hidden>
<div class="rq"><b id="rName"></b><span id="rText"></span></div>
<button type="button" class="icon" id="rCancel" aria-label="Cancel reply">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><path d="M7 7l10 10M17 7L7 17"/></svg>
</button>
</div>
<form id="bar" autocomplete="off">
<div class="field">
<button type="button" class="icon" id="emojiBtn" aria-label="Emoji"></button>
<input id="msg" maxlength="1000" placeholder="Message" enterkeyhint="send" autocomplete="off" autocorrect="on">
<button type="button" class="icon" id="photoBtn" aria-label="Send a photo">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="5" width="18" height="14" rx="3.5"/><circle cx="9" cy="10.5" r="1.7"/><path d="M21 15.5l-4.6-4.6a1.2 1.2 0 0 0-1.7 0L7 18.6"/></svg>
</button>
</div>
<button class="send" id="send" aria-label="Send" disabled>
<svg viewBox="0 0 24 24" fill="currentColor"><path d="M3.4 20.4c-.7.3-1.4-.4-1.1-1.1L5 12 2.3 4.7c-.3-.7.4-1.4 1.1-1.1l17.5 7.5c.8.3.8 1.5 0 1.8L3.4 20.4zM6.6 12.9l-2 5.2 13.1-6.1L4.6 5.9l2 5.2H12v1.8H6.6z"/></svg>
</button>
</form>
<input type="file" id="file" accept="image/*" hidden>
<div id="emoji"><div id="egrid"></div><div id="etabs"></div></div>
</footer>
</section>
</div>
<div id="menuBack" hidden></div>
<div id="menu" hidden>
<button data-act="reply"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round"><path d="M9 7L4 12l5 5"/><path d="M4 12h10a6 6 0 0 1 6 6v1"/></svg>Reply</button>
<button data-act="copy"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.9" stroke-linejoin="round"><rect x="8" y="8" width="12" height="12" rx="2.5"/><path d="M16 8V6.5A2.5 2.5 0 0 0 13.5 4h-7A2.5 2.5 0 0 0 4 6.5v7A2.5 2.5 0 0 0 6.5 16H8"/></svg>Copy text</button>
</div>
<div id="viewer" hidden><img alt=""></div>
<div id="modal" hidden>
<form class="card" id="nameForm" autocomplete="off">
<div class="avatar group">✈️</div>
<h2 id="mTitle">Welcome aboard</h2>
<p>Pick a name your fellow passengers will see.</p>
<input id="nameIn" maxlength="24" placeholder="Your name" enterkeyhint="done">
<button class="primary">Join the chat</button>
</form>
</div>
<div id="toast"></div>
<script>
(() => {
'use strict';
/* ================================================================ basics */
const $ = id => document.getElementById(id);
const app = $('app'), log = $('log'), input = $('msg'), sendBtn = $('send'),
emojiPanel = $('emoji'), egrid = $('egrid'), etabs = $('etabs'), typingRow = $('typingRow');
const store = {
get(k) { try { return localStorage.getItem(k); } catch (e) { return null; } },
set(k, v) { try { localStorage.setItem(k, v); } catch (e) {} }
};
const enc = new TextEncoder(), dec = new TextDecoder();
const toHex = s => Array.from(enc.encode(s), b => b.toString(16).padStart(2, '0')).join('');
const fromHex = h => { try { return dec.decode(new Uint8Array((h.match(/../g) || []).map(x => parseInt(x, 16)))); } catch (e) { return '?'; } };
const randHex = n => Array.from(crypto.getRandomValues(new Uint8Array(n)), b => b.toString(16).padStart(2, '0')).join('');
const clean = s => s.replace(/[\t\r\n]+/g, ' ').trim();
const el = (tag, cls, text) => { const e = document.createElement(tag); if (cls) e.className = cls; if (text != null) e.textContent = text; return e; };
const touch = matchMedia('(pointer: coarse)').matches;
const wide = () => matchMedia('(min-width: 760px)').matches;
const KEEP = 86400, ONLINE = 70, TYPING_SHOW = 7;
const ALL = '*';
const ICON_SMILE = '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round"><circle cx="12" cy="12" r="9"/><path d="M8.3 14.2c.9 1.3 2.2 2 3.7 2s2.8-.7 3.7-2"/><circle cx="9" cy="9.8" r=".9" fill="currentColor" stroke="none"/><circle cx="15" cy="9.8" r=".9" fill="currentColor" stroke="none"/></svg>';
const ICON_KBD = '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round"><rect x="2.5" y="6" width="19" height="12" rx="2.5"/><path d="M6 10h.01M9 10h.01M12 10h.01M15 10h.01M18 10h.01M6 13h.01M18 13h.01M8.5 14.5h7"/></svg>';
// identity: a secret key stays in this browser; the server only ever shows a public id
let key = store.get('cc.key');
if (!/^[0-9a-f]{32}$/.test(key || '')) { key = randHex(16); store.set('cc.key', key); }
const legacyId = store.get('cc.uid'); // id used by version 2, to recognise own old messages
let nick = store.get('cc.nick') || '';
let me = ''; // public id, told by the server
/* ================================================================ state */
const msgs = new Map(); // id -> message (all conversations)
const convs = new Map(); // conversation key -> [messages]
const users = new Map(); // public id -> {nick, seen}
let typing = new Map(); // public id -> {to, ts}
let readMarks = {}; // conversation key -> last read id
try { readMarks = JSON.parse(store.get('cc.read') || '{}') || {}; } catch (e) {}
const firstVisit = !store.get('cc.read');
let conv = ALL; // the open conversation
let since = 0, ev = '', offset = 0, online = null, loaded = false;
let stick = true, unseen = 0, prev = null, replyTo = null;
/* ================================================================ time */
const serverNow = () => Date.now() / 1000 + offset;
function ago(ts) {
const s = Math.max(0, serverNow() - ts);
if (s < 45) return 'now';
const m = Math.round(s / 60);
if (m < 60) return m + 'm ago';
return Math.floor(m / 60) + 'h ' + String(m % 60).padStart(2, '0') + 'm ago';
}
const shortAgo = ts => ago(ts).replace(' ago', '');
/* ================================================================ people & conversations */
const isMine = m => m.from === me || (legacyId && m.from === legacyId);
const convOf = m => m.to === ALL ? ALL : (isMine(m) ? m.to : m.from);
const hue = u => { let h = 0; for (const c of u) h = (h * 31 + c.charCodeAt(0)) >>> 0; return h % 360; };
const nameColor = id => 'hsl(' + hue(id) + ' 75% 70%)';
const nickOf = id => (users.get(id) || {}).nick || '?';
const isOnline = id => { const u = users.get(id); return !!u && serverNow() - u.seen < ONLINE; };
const isTyping = (id, to) => { const t = typing.get(id); return !!t && t.to === to && serverNow() - t.ts < TYPING_SHOW; };
function avatar(id, small) {
const a = el('div', 'avatar');
if (id === ALL) { a.classList.add('group'); a.textContent = '👥'; return a; }
a.textContent = (Array.from(nickOf(id).trim())[0] || '?').toUpperCase();
a.style.background = 'hsl(' + hue(id) + ' 42% 34%)';
if (isOnline(id)) a.appendChild(el('span', 'on'));
return a;
}
function typersIn(c) { // names typing in conversation c
const out = [];
for (const [id, t] of typing) {
if (serverNow() - t.ts >= TYPING_SHOW) continue;
if (c === ALL ? t.to === ALL : (id === c && t.to === me)) out.push(nickOf(id));
}
return out;
}
function typingText(names) {
if (!names.length) return '';
if (names.length === 1) return names[0] + ' is typing…';
if (names.length === 2) return names[0] + ' and ' + names[1] + ' are typing…';
return names.length + ' people are typing…';
}
const lastOf = c => { const a = convs.get(c); return a && a.length ? a[a.length - 1] : null; };
function unreadIn(c) {
const a = convs.get(c); if (!a) return 0;
const mark = readMarks[c] || 0; let n = 0;
for (let i = a.length - 1; i >= 0 && a[i].id > mark; i--) if (!isMine(a[i])) n++;
return n;
}
let saveReadTimer = 0;
function markRead(c) {
const last = lastOf(c);
if (!last || (readMarks[c] || 0) >= last.id) return;
readMarks[c] = last.id;
clearTimeout(saveReadTimer);
saveReadTimer = setTimeout(() => store.set('cc.read', JSON.stringify(readMarks)), 500);
}
function markReadIfSeen() { if (!document.hidden && stick && loaded) markRead(conv); }
const snippet = m => m.type === 'i' ? '📷 Photo' : (m.text.length > 120 ? m.text.slice(0, 120) + '…' : m.text);
/* ================================================================ message rendering */
let emojiOnly = null;
try { emojiOnly = new RegExp('^(?:\\p{Extended_Pictographic}|\\p{Emoji_Modifier}|\\p{Regional_Indicator}|\\u200d|\\ufe0f|\\s)+$', 'u'); } catch (e) {}
function parse(line) {
const f = line.split('\t');
if (f.length !== 8) return null;
const m = { id: +f[0], ts: +f[1], type: f[2], from: f[3], to: f[4], re: +f[5] || 0, nick: fromHex(f[6]) };
if (!(m.id > 0)) return null;
if (m.type === 'i') {
const p = f[7].split(' ');
m.file = p[0]; m.w = +p[1] || 0; m.h = +p[2] || 0;
if (!/^\d+(-[0-9a-f]{16})?\.jpg$/.test(m.file)) return null;
} else m.text = f[7];
return m;
}
function metaEl(ts) { const s = el('span', 'meta', ago(ts)); s.dataset.ts = ts; return s; }
function photoEl(src, w, h, cls) {
const im = new Image();
im.alt = 'Photo'; im.decoding = 'async'; im.loading = 'lazy'; im.draggable = false;
if (cls) im.className = cls;
if (w && h) im.style.aspectRatio = w + ' / ' + h;
im.onload = () => { if (stick) toBottom(); };
im.src = src;
return im;
}
function quoteEl(reId) {
const q = msgs.get(reId), d = el('div', 'quote');
d.dataset.re = reId;
const t = el('div', 'qt');
if (!q) { d.classList.add('gone'); t.append(el('b', null, ''), el('span', null, 'Message no longer available')); }
else {
if (q.type === 'i') d.appendChild(photoEl('img/' + q.file, 0, 0));
const b = el('b', null, isMine(q) ? 'You' : q.nick);
b.style.color = isMine(q) ? 'var(--accent)' : nameColor(q.from);
t.append(b, el('span', null, snippet(q)));
}
d.appendChild(t);
return d;
}
function render(m) {
const mine = isMine(m);
const grouped = prev && prev.row.isConnected && prev.from === m.from && Math.abs(m.ts - prev.ts) < 300;
const row = el('div', 'row last' + (mine ? ' mine' : '') + (grouped ? '' : ' first'));
if (grouped) prev.row.classList.remove('last');
if (!grouped && !mine && conv === ALL) {
const n = el('div', 'name', m.nick);
n.style.color = nameColor(m.from);
row.appendChild(n);
}
const b = el('div', 'bubble');
b.dataset.id = m.id;
if (m.re) { b.classList.add('hasq'); b.appendChild(quoteEl(m.re)); }
if (m.type === 'i') {
b.classList.add('media');
b.append(photoEl('img/' + m.file, m.w, m.h, 'photo'), metaEl(m.ts));
} else {
if (!m.re && emojiOnly && m.text.length <= 16 && emojiOnly.test(m.text)) b.classList.add('jumbo');
b.append(el('span', null, m.text), metaEl(m.ts));
}
row.appendChild(b);
row.dataset.ts = m.ts;
log.insertBefore(row, typingRow);
prev = { from: m.from, ts: m.ts, row };
$('empty').hidden = true;
}
function emptyText() {
return conv === ALL ? 'No messages yet.\nSay hi to everyone 👋'
: 'This is your private chat with ' + nickOf(conv) + '.\nOnly the two of you can see it.';
}
function renderConv() {
for (const r of log.querySelectorAll('.row')) r.remove();
prev = null;
for (const m of convs.get(conv) || []) render(m);
const e = $('empty');
e.textContent = emptyText(); e.style.whiteSpace = 'pre-line';
e.hidden = !!log.querySelector('.row');
stick = true; unseen = 0; updateJump();
toBottom();
}
function updateAges() {
for (const m of log.querySelectorAll('.meta[data-ts]')) m.textContent = ago(+m.dataset.ts);
}
// rolling 24 h window on the client as well
function expire() {
const cut = serverNow() - KEEP;
let changed = false;
for (const [id, m] of msgs) {
if (m.ts >= cut) continue;
msgs.delete(id); changed = true;
const a = convs.get(convOf(m));
if (a) { const i = a.indexOf(m); if (i >= 0) a.splice(i, 1); }
}
if (changed) {
for (const row of log.querySelectorAll('.row[data-ts]')) { if (+row.dataset.ts < cut) row.remove(); else break; }
$('empty').hidden = !!log.querySelector('.row');
}
}
/* ================================================================ header, people list, typing */
let listSig = '';
function refreshUI() {
// header
const sub = $('hSub');
let text, cls = '';
if (online === false) { text = 'Reconnecting…'; cls = 'bad'; }
else if (conv === ALL) {
const t = typingText(typersIn(ALL));
if (t) { text = t; cls = 'typing'; }
else { let n = 1; for (const id of users.keys()) if (id !== me && isOnline(id)) n++; text = online ? n + ' online' : 'Connecting…'; }
} else if (isTyping(conv, me)) { text = 'typing…'; cls = 'typing'; }
else if (isOnline(conv)) text = 'online';
else { const u = users.get(conv); text = u && u.seen ? 'last seen ' + ago(u.seen) : 'offline'; }
sub.textContent = text; sub.className = 'status ' + cls;
$('hTitle').textContent = conv === ALL ? 'Everyone' : nickOf(conv);
const ha = $('hAvatar'); ha.textContent = ''; ha.appendChild(avatar(conv));
// typing bubble at the bottom of the open chat
const names = typersIn(conv);
const wasHidden = typingRow.hidden;
typingRow.hidden = !names.length;
$('typingName').textContent = conv === ALL && names.length ? names.join(', ') : '';
$('typingName').hidden = conv !== ALL;
if (wasHidden !== typingRow.hidden && stick) toBottom();
// unread badge on the people button: messages waiting in other chats
let others = 0, total = 0;
for (const c of convs.keys()) { const n = unreadIn(c); total += n; if (c !== conv) others += n; }
$('peopleBadge').hidden = !others;
$('peopleBadge').textContent = others > 99 ? '99+' : others;
document.title = document.hidden && total ? '(' + total + ') Cabin Chat' : 'Cabin Chat';
renderList();
}
function peopleIds() {
const ids = new Set();
for (const id of users.keys()) ids.add(id);
for (const c of convs.keys()) if (c !== ALL) ids.add(c);
for (const m of convs.get(ALL) || []) ids.add(m.from);
ids.delete(me); ids.delete(ALL); if (legacyId) ids.delete(legacyId);
return [...ids];
}
function activity(id) {
const u = users.get(id), l = lastOf(id);
return Math.max(u ? u.seen : 0, l ? l.ts : 0);
}
function renderList() {
const ids = peopleIds().sort((a, b) => (isOnline(b) - isOnline(a)) || (activity(b) - activity(a)));
const rows = [ALL, ...ids].map(c => {
const last = lastOf(c), n = unreadIn(c);
let sub, typ = false;
if (c === ALL) {
const t = typingText(typersIn(ALL));
if (t) { sub = t; typ = true; }
else sub = last ? (isMine(last) ? 'You' : last.nick) + ': ' + snippet(last) : 'Group chat with everyone';
} else if (isTyping(c, me)) { sub = 'typing…'; typ = true; }
else if (last) sub = (isMine(last) ? 'You: ' : '') + snippet(last);
else sub = isOnline(c) ? 'online' : (users.get(c) && users.get(c).seen ? 'last seen ' + ago(users.get(c).seen) : 'offline');
return { c, name: c === ALL ? 'Everyone' : nickOf(c), sub, typ, n, time: last ? shortAgo(last.ts) : '', on: c !== ALL && isOnline(c) };
});
const sig = conv + JSON.stringify(rows);
if (sig === listSig) return;
listSig = sig;
const list = $('plist'); list.textContent = '';
rows.forEach((r, i) => {
if (i === 1) list.appendChild(el('div', 'psec', 'People'));
const b = el('button', 'pitem' + (r.c === conv ? ' active' : ''));
b.type = 'button';
b.dataset.conv = r.c;
const main = el('div', 'pmain');
main.append(el('div', 'pname', r.name), el('div', 'psub' + (r.typ ? ' typing' : ''), r.sub));
const side = el('div', 'pside');
side.appendChild(el('span', 'ptime', r.time));
if (r.n) side.appendChild(el('span', 'pbadge', r.n > 99 ? '99+' : r.n));
b.append(avatar(r.c), main, side);
list.appendChild(b);
});
if (rows.length === 1) list.appendChild(el('div', 'pnone', 'Nobody else here yet. People show up as soon as they open the chat.'));
}
$('plist').addEventListener('click', e => {
const b = e.target.closest('.pitem');
if (b) openConv(b.dataset.conv);
});
function openConv(c) {
if (c !== conv) {
stopTyping();
conv = c;
store.set('cc.conv', c);
cancelReply();
renderConv();
input.placeholder = c === ALL ? 'Message everyone' : 'Message ' + nickOf(c);
listSig = '';
}
closePeople();
markReadIfSeen();
refreshUI();
}
/* drawer: on phones the people list slides over the chat; the back button closes it */
function openPeople() {
if (wide() || app.classList.contains('people')) return;
app.classList.add('people');
history.pushState({ cc: 'people' }, '');
}
function closePeople() {
if (!app.classList.contains('people')) return;
app.classList.remove('people');
if (history.state && history.state.cc === 'people') history.back();
}
addEventListener('popstate', () => app.classList.remove('people'));
$('peopleBtn').addEventListener('click', openPeople);
$('closePeople').addEventListener('click', closePeople);
/* ================================================================ scrolling & keyboard */
function toBottom() { log.scrollTop = log.scrollHeight; }
function updateJump() {
$('jump').hidden = stick;
$('badge').hidden = !unseen;
$('badge').textContent = unseen > 99 ? '99+' : unseen;
}
log.addEventListener('scroll', () => {
const s = log.scrollHeight - log.scrollTop - log.clientHeight < 70;
if (s !== stick) { stick = s; if (s) { unseen = 0; markReadIfSeen(); refreshUI(); } updateJump(); }
if (menuOpen) closeMenu();
}, { passive: true });
$('jump').addEventListener('click', () => { stick = true; unseen = 0; toBottom(); updateJump(); markReadIfSeen(); refreshUI(); });
// keep the layout above the soft keyboard (iOS ignores interactive-widget)
let fullH = 0;
function fit() {
const vv = window.visualViewport;
if (!vv) return;
fullH = Math.max(fullH, vv.height);
app.style.height = vv.height + 'px';
app.style.transform = vv.offsetTop ? 'translateY(' + vv.offsetTop + 'px)' : '';
app.classList.toggle('kb', vv.height < fullH - 120);
if (stick) toBottom();
}
if (window.visualViewport) {
visualViewport.addEventListener('resize', fit);
visualViewport.addEventListener('scroll', fit);
addEventListener('orientationchange', () => { fullH = 0; setTimeout(fit, 300); });
fit();
}
/* ================================================================ network: long poll */
let ctrl = null, kicked = false, wake = null, fails = 0;
const nap = ms => new Promise(r => { const t = setTimeout(r, ms); wake = () => { clearTimeout(t); r(); }; });
function kick() { // restart the long poll right now
kicked = true;
if (ctrl) ctrl.abort();
if (wake) wake();
}
function setOnline(v) { if (v !== online) { online = v; refreshUI(); } }
function resetAll() {
msgs.clear(); convs.clear(); since = 0; ev = '';
renderConv();
}
function addMessage(m) {
if (msgs.has(m.id)) return false;
msgs.set(m.id, m);
const c = convOf(m);
if (!convs.has(c)) convs.set(c, []);
convs.get(c).push(m);
if (!isMine(m) && !users.has(m.from)) users.set(m.from, { nick: m.nick, seen: 0 });
if (!isMine(m)) typing.delete(m.from);
return true;
}
function handle(text) {
const lines = text.split('\n');
lines.pop(); // '' or a half-written line
const h = (lines.shift() || '').split('\t');
if (h.length < 4 || h[0][0] !== '@') throw new Error('bad response');
offset = +h[0].slice(1) - Date.now() / 1000;
const last = +h[1];
me = h[3];
if (last < since) { resetAll(); return; } // chat was wiped on the router
ev = h[2];
const fresh = [];
typing = new Map();
for (const l of lines) {
if (l[0] === 'U') {
const [, id, n, s] = l.split('\t');
if (id !== me) users.set(id, { nick: fromHex(n) || '?', seen: +s });
} else if (l[0] === 'W') {
const [, id, to, ts] = l.split('\t');
typing.set(id, { to, ts: +ts });
} else {
const m = parse(l);
if (m && addMessage(m)) fresh.push(m);
}
}
since = last;
if (!loaded) { // first answer: build everything
loaded = true;
if (firstVisit) { for (const c of convs.keys()) markRead(c); }
if (conv !== ALL && !peopleIds().includes(conv)) conv = ALL;
input.placeholder = conv === ALL ? 'Message everyone' : 'Message ' + nickOf(conv);
renderConv();
} else if (fresh.length) {
let here = 0, theirs = 0;
for (const m of fresh) {
if (convOf(m) === conv) { render(m); here++; if (!isMine(m)) theirs++; }
else if (!isMine(m)) notify(m);
}
if (here) { if (stick) toBottom(); else { unseen += theirs; updateJump(); } }
}
markReadIfSeen();
}
async function pollOnce() {
ctrl = new AbortController();
kicked = false;
const watchdog = setTimeout(() => ctrl.abort(), 40000); // dead connection (router reboot, WiFi drop)
try {
const url = 'cgi-bin/chat?k=' + key + '&n=' + toHex(nick) + '&since=' + since + '&ev=' + ev + '&w=' + (ev ? 1 : 0);
const r = await fetch(url, { cache: 'no-store', signal: ctrl.signal });
if (!r.ok) throw new Error(r.status);
handle(await r.text());
fails = 0;
setOnline(true);
} catch (e) {
if (!kicked) { fails++; if (fails > 1) setOnline(false); }
} finally {
clearTimeout(watchdog);
}
updateAges(); refreshUI();
if (kicked) return 0;
if (fails) return Math.min(10000, 1000 * fails);
return document.hidden ? 3000 : 0; // background: fewer wake-ups
}
async function loop() {
for (;;) {
const d = await pollOnce();
if (d) await nap(d);
wake = null;
}
}
document.addEventListener('visibilitychange', () => {
if (!document.hidden) { markReadIfSeen(); refreshUI(); kick(); } // a frozen tab's request may be dead
});
const postUrl = (act, extra) =>
'cgi-bin/chat?a=' + act + '&k=' + key + '&n=' + toHex(nick) + '&to=' + encodeURIComponent(conv) + (extra || '');
/* ================================================================ typing notices */
let typingSent = 0, typingConv = null;
function sendTyping(to) {
fetch('cgi-bin/chat?a=typing&k=' + key + '&n=' + toHex(nick) + '&to=' + encodeURIComponent(to), { method: 'POST' }).catch(() => {});
}
function onTyping() {
const now = Date.now();
if (input.value.trim()) {
if (now - typingSent > 3000 || typingConv !== conv) { typingSent = now; typingConv = conv; sendTyping(conv); }
} else stopTyping();
}
function stopTyping() {
if (typingSent && Date.now() - typingSent < 9000) sendTyping('-');
typingSent = 0; typingConv = null;
}
/* ================================================================ sending */
async function sendText() {
const m = clean(input.value).slice(0, 1000);
if (!m) return;
const re = replyTo;
input.value = ''; updateSend(); cancelReply();
typingSent = 0; typingConv = null; // the server clears our typing notice
try {
const r = await fetch(postUrl('text', re ? '&re=' + re : ''), { method: 'POST', headers: { 'Content-Type': 'text/plain;charset=utf-8' }, body: m });
if (!r.ok) throw new Error();
} catch (e) {
if (!input.value) { input.value = m; updateSend(); if (re) setReply(re); }
toast('Message not sent – are you on the chat WiFi?');
}
stick = true;
}
function loadImage(file) {
return new Promise((res, rej) => {
const url = URL.createObjectURL(file), img = new Image();
img.onload = () => { URL.revokeObjectURL(url); res(img); };
img.onerror = () => { URL.revokeObjectURL(url); rej(new Error('Can’t read this image format')); };
img.src = url;
});
}
// scale down + re-encode as JPEG until it fits into ~100 kB
async function shrink(file, target = 100 * 1024) {
const img = await loadImage(file); // browsers apply EXIF rotation here
const W = img.naturalWidth, H = img.naturalHeight;
const c = document.createElement('canvas'), ctx = c.getContext('2d');
let max = 1280, q = 0.8, blob = null;
for (let i = 0; i < 12; i++) {
const s = Math.min(1, max / Math.max(W, H));
c.width = Math.max(1, Math.round(W * s)); c.height = Math.max(1, Math.round(H * s));
ctx.fillStyle = '#fff'; ctx.fillRect(0, 0, c.width, c.height);
ctx.drawImage(img, 0, 0, c.width, c.height);
blob = await new Promise(r => c.toBlob(r, 'image/jpeg', q));
if (!blob) throw new Error('Could not process the photo');
if (blob.size <= target) break;
if (q > 0.55) q -= 0.1; else max = Math.round(max * 0.8);
}
return { blob, w: c.width, h: c.height };
}
function pendingRow(blob, w, h) {
const row = el('div', 'row mine last first');
const b = el('div', 'bubble media pending');
const url = URL.createObjectURL(blob);
b.append(photoEl(url, w, h, 'photo'), el('div', 'spin'));
row.appendChild(b);
log.insertBefore(row, typingRow);
$('empty').hidden = true;
stick = true; toBottom();
return () => { row.remove(); URL.revokeObjectURL(url); };
}
async function sendPhoto(file) {
let done = null;
const re = replyTo;
cancelReply();
try {
const { blob, w, h } = await shrink(file);
done = pendingRow(blob, w, h);
const extra = '&w=' + w + '&h=' + h + '&r=' + randHex(8) + (re ? '&re=' + re : '');
const r = await fetch(postUrl('img', extra), { method: 'POST', headers: { 'Content-Type': 'image/jpeg' }, body: blob });
if (!r.ok) throw new Error(r.status === 507 ? 'Chat storage is full' : 'Photo upload failed (' + r.status + ')');
} catch (e) {
toast(e.message && !/fetch|network|load/i.test(e.message) ? e.message : 'Photo not sent – are you on the chat WiFi?');
}
if (done) setTimeout(done, 400); // the real message arrives through the long poll
stick = true;
}
$('photoBtn').addEventListener('click', () => $('file').click());
$('file').addEventListener('change', () => {
const f = $('file').files[0];
$('file').value = '';
if (f) sendPhoto(f);
});
function openViewer(src) { $('viewer').firstElementChild.src = src; $('viewer').hidden = false; }
$('viewer').addEventListener('click', () => { $('viewer').hidden = true; });
addEventListener('keydown', e => { if (e.key === 'Escape') { $('viewer').hidden = true; closeMenu(); cancelReply(); } });
/* ================================================================ replies (quotes) */
function setReply(id) {
const m = msgs.get(id);
if (!m) return;
replyTo = id;
$('rName').textContent = 'Reply to ' + (isMine(m) ? 'yourself' : m.nick);
$('rText').textContent = snippet(m);
$('replyBar').hidden = false;
input.focus();
if (stick) setTimeout(toBottom, 50);
}
function cancelReply() { replyTo = null; $('replyBar').hidden = true; }
$('rCancel').addEventListener('mousedown', e => e.preventDefault());
$('rCancel').addEventListener('click', cancelReply);
function jumpTo(id) {
const b = log.querySelector('.bubble[data-id="' + id + '"]');
if (!b) { toast('That message is no longer here'); return; }
b.scrollIntoView({ behavior: 'smooth', block: 'center' });
b.classList.remove('flash'); void b.offsetWidth; b.classList.add('flash');
}
// message menu: long press (touch), right click (mouse), swipe right = quick reply
let menuOpen = null, menuAt = 0, swipe = null, swallowClick = false;
function openMenu(b) {
const m = msgs.get(+b.dataset.id);
if (!m) return;
closeMenu();
menuOpen = b; menuAt = Date.now();
b.classList.add('sel');
if (navigator.vibrate) try { navigator.vibrate(12); } catch (e) {}
const menu = $('menu');
menu.querySelector('[data-act="copy"]').hidden = m.type !== 't';
$('menuBack').hidden = false; menu.hidden = false;
const r = b.getBoundingClientRect(), mw = menu.offsetWidth, mh = menu.offsetHeight;
let x = isMine(m) ? r.right - mw : r.left, y = r.bottom + 6;
if (y + mh > innerHeight - 10) y = r.top - mh - 6;
menu.style.left = Math.max(8, Math.min(x, innerWidth - mw - 8)) + 'px';
menu.style.top = Math.max(8, y) + 'px';
}
function closeMenu() {
if (!menuOpen) return;
menuOpen.classList.remove('sel');
menuOpen = null;
$('menu').hidden = true; $('menuBack').hidden = true;
}
$('menuBack').addEventListener('click', () => { if (Date.now() - menuAt > 450) closeMenu(); }); // ignore the finger lifting after a long press
$('menuBack').addEventListener('contextmenu', e => { e.preventDefault(); closeMenu(); });
$('menu').addEventListener('click', e => {
const b = e.target.closest('button');
if (!b || !menuOpen) return;
const m = msgs.get(+menuOpen.dataset.id);
closeMenu();
if (!m) return;
if (b.dataset.act === 'reply') setReply(m.id);
if (b.dataset.act === 'copy') copyText(m.text);
});
function copyText(t) {
const ta = el('textarea');
ta.value = t; ta.setAttribute('readonly', '');
ta.style.cssText = 'position:fixed;top:0;left:0;opacity:0';
document.body.appendChild(ta);
ta.select(); ta.setSelectionRange(0, t.length);
let ok = false;
try { ok = document.execCommand('copy'); } catch (e) {}
ta.remove();
if (!ok && navigator.clipboard) navigator.clipboard.writeText(t).then(() => toast('Copied'), () => toast('Copy not supported here'));
else toast(ok ? 'Copied' : 'Copy not supported here');
}
log.addEventListener('pointerdown', e => {
const b = e.target.closest('.bubble[data-id]');
swallowClick = false;
if (!b || e.button > 0) return;
swipe = { b, x: e.clientX, y: e.clientY, mode: null, dx: 0,
timer: e.pointerType === 'mouse' ? 0 : setTimeout(() => {
if (swipe && !swipe.mode) { swipe.mode = 'press'; swallowClick = true; openMenu(b); }
}, 480) };
});
log.addEventListener('pointermove', e => {
if (!swipe) return;
const dx = e.clientX - swipe.x, dy = e.clientY - swipe.y;
if (!swipe.mode) {
if (Math.abs(dy) > 10 || dx < -10) return endSwipe();
if (dx > 14 && e.pointerType !== 'mouse') { swipe.mode = 'swipe'; clearTimeout(swipe.timer); swipe.b.classList.add('swiping'); }
}
if (swipe.mode === 'swipe') {
swipe.dx = Math.max(0, Math.min(90, dx));
swipe.b.style.transform = 'translateX(' + swipe.dx + 'px)';
}
});
function endSwipe() {
if (!swipe) return;
clearTimeout(swipe.timer);
if (swipe.mode === 'swipe') {
swipe.b.classList.remove('swiping');
swipe.b.style.transform = '';
swallowClick = true;
if (swipe.dx > 60) setReply(+swipe.b.dataset.id);
}
swipe = null;
}
log.addEventListener('pointerup', endSwipe);
log.addEventListener('pointercancel', endSwipe);
log.addEventListener('contextmenu', e => {
const b = e.target.closest('.bubble[data-id]');
if (!b) return;
e.preventDefault();
if (!menuOpen) openMenu(b);
});
log.addEventListener('click', e => {
if (swallowClick) { swallowClick = false; e.preventDefault(); e.stopPropagation(); return; }
const q = e.target.closest('.quote[data-re]');
if (q) { jumpTo(+q.dataset.re); return; }
const im = e.target.closest('img.photo');
if (im && im.closest('.bubble[data-id]')) openViewer(im.src);
}, true);
/* ================================================================ notifications for other chats */
let toastTimer = 0;
function toast(t, onClick) {
const e = $('toast');
e.textContent = t;
e.classList.add('show');
e.classList.toggle('click', !!onClick);
e.onclick = onClick ? () => { e.classList.remove('show'); onClick(); } : null;
clearTimeout(toastTimer);
toastTimer = setTimeout(() => e.classList.remove('show'), onClick ? 4500 : 3200);
}
function notify(m) {
if (document.hidden) return;
const where = m.to === ALL ? m.nick + ' in Everyone' : m.nick;
const c = convOf(m);
toast('💬 ' + where + ': ' + snippet(m), () => openConv(c));
}
/* ================================================================ emoji */
const EMOJI = [
['🕘', ''],
['😀', '😀 😃 😄 😁 😆 😅 🤣 😂 🙂 🙃 😉 😊 😇 🥰 😍 🤩 😘 😗 😚 😋 😛 😜 🤪 😝 🤑 🤗 🤭 🤫 🤔 🤐 🤨 😐 😑 😶 😏 😒 🙄 😬 🤥 😌 😔 😪 🤤 😴 😷 🤒 🤕 🤢 🤮 🥵 🥶 🥴 😵 🤯 🤠 🥳 😎 🤓 🧐 😕 😟 🙁 😮 😯 😲 😳 🥺 😦 😧 😨 😰 😥 😢 😭 😱 😖 😣 😞 😓 😩 😫 🥱 😤 😡 😠 🤬 😈 💀 💩 🤡 👻 👽 🤖'],
['👍', '👋 🤚 ✋ 🖖 👌 🤏 ✌️ 🤞 🤟 🤘 🤙 👈 👉 👆 👇 ☝️ 👍 👎 ✊ 👊 🤛 🤜 👏 🙌 👐 🤲 🤝 🙏 💪 ❤️ 🧡 💛 💚 💙 💜 🖤 🤍 💔 ❣️ 💕 💞 💓 💗 💖 💘 💝 🙈 🙉 🙊'],
['✈️', '✈️ 🛫 🛬 🛩️ 💺 🚁 🧳 🛂 🛃 🌍 🌎 🌏 🗺️ 🏝️ 🏖️ 🏔️ 🌋 🗽 🗼 🏰 🚗 🚕 🚌 🚆 🚢 ⛵ 🚀 🛸 🌅 🌄 🌃 🌌 ☁️ ⛅ 🌤️ 🌧️ ⛈️ 🌩️ 🌈 ☀️ 🌙 ⭐ 🌟 ❄️ 🌊'],
['🍔', '☕ 🍵 🧃 🥤 🍺 🍻 🥂 🍷 🥃 🍸 🍹 🍾 🍔 🍟 🍕 🌭 🥪 🌮 🌯 🥗 🍝 🍜 🍣 🍱 🥟 🍩 🍪 🎂 🍰 🧁 🍫 🍬 🍭 🍿 🥨 🥐 🧀 🍎 🍌 🍇 🍓 🍉 🍒 🥑 🌶️'],
['🎉', '🎉 🎊 🎈 🎁 🏆 🥇 ⚽ 🏀 🎮 🎲 🎯 🎧 🎵 🎶 🎬 📸 📷 📱 💻 ⌚ 🔋 🔌 💡 📖 ✏️ 📝 📌 🔑 🛏️ 🧸 💤 🎤 🎸 🧩 ♟️'],
['✅', '✅ ❌ ❓ ❗ 💯 🔥 ✨ 💥 💫 💦 💨 🆗 🆒 🆕 🆘 ⚠️ 🚫 ⛔ 📵 🔇 🔔 ⏰ ⏳ ➡️ ⬅️ ⬆️ ⬇️ 🔁 ➕ ➖ ✖️ 💲 ♻️ 🟢 🟡 🔴']
];
let recent = (store.get('cc.recent') || '').split(' ').filter(Boolean);
let emojiTab = -1;
EMOJI.forEach(([icon], i) => {
const b = el('button', null, icon);
b.type = 'button';
b.setAttribute('aria-label', i ? 'Category' : 'Recently used');
b.addEventListener('click', () => showTab(i));
etabs.appendChild(b);
});
function showTab(i) {
emojiTab = i;
[...etabs.children].forEach((b, j) => b.classList.toggle('on', i === j));
egrid.textContent = '';
const list = i === 0 ? recent : EMOJI[i][1].split(' ');
if (!list.length) egrid.appendChild(el('div', 'enone', 'Emoji you use will show up here'));
for (const e of list) { const b = el('button', null, e); b.type = 'button'; egrid.appendChild(b); }
egrid.scrollTop = 0;
}
egrid.addEventListener('mousedown', e => e.preventDefault()); // keep the cursor
egrid.addEventListener('click', e => {
const b = e.target.closest('button');
if (!b) return;
const em = b.textContent;
const st = input.selectionStart ?? input.value.length, en = input.selectionEnd ?? st;
input.setRangeText(em, st, en, 'end');
updateSend(); onTyping();
recent = [em, ...recent.filter(x => x !== em)].slice(0, 40);
store.set('cc.recent', recent.join(' '));
});
function setEmoji(open) {
emojiPanel.classList.toggle('open', open);
$('emojiBtn').innerHTML = open ? ICON_KBD : ICON_SMILE;
$('emojiBtn').setAttribute('aria-label', open ? 'Keyboard' : 'Emoji');
if (open) {
if (touch) input.blur();
if (emojiTab < 0) showTab(recent.length ? 0 : 1);
}
setTimeout(() => { if (stick) toBottom(); }, 230);
}
$('emojiBtn').innerHTML = ICON_SMILE;
for (const id of ['emojiBtn', 'photoBtn', 'send']) $(id).addEventListener('mousedown', e => e.preventDefault());
$('emojiBtn').addEventListener('click', () => {
const open = !emojiPanel.classList.contains('open');
setEmoji(open);
if (!open || !touch) input.focus();
});
input.addEventListener('focus', () => { if (touch && emojiPanel.classList.contains('open')) setEmoji(false); });
/* ================================================================ composer */
function updateSend() { sendBtn.disabled = !input.value.trim(); }
input.addEventListener('input', () => { updateSend(); onTyping(); });
$('bar').addEventListener('submit', e => { e.preventDefault(); sendText(); });
/* ================================================================ name */
function askName(first) {
$('mTitle').textContent = first ? 'Welcome aboard' : 'Change your name';
$('nameForm').querySelector('.primary').textContent = first ? 'Join the chat' : 'Save';
$('nameIn').value = nick;
$('modal').hidden = false;
setTimeout(() => $('nameIn').focus(), 60);
}
$('nameForm').addEventListener('submit', e => {
e.preventDefault();
const n = clean($('nameIn').value).slice(0, 24);
if (!n) { $('nameIn').focus(); return; }
const first = !nick;
nick = n; store.set('cc.nick', n);
$('me').textContent = n;
$('modal').hidden = true;
$('nameIn').blur();
if (first) loop(); else kick(); // tell everybody the new name
});
$('modal').addEventListener('click', e => { if (e.target === $('modal') && nick) $('modal').hidden = true; });
$('me').addEventListener('click', () => askName(false));
fetch('VERSION', { cache: 'no-store' }).then(r => r.ok ? r.text() : '')
.then(v => { v = v.trim(); if (/^[\w.\-]{1,20}$/.test(v)) $('ver').textContent = 'Cabin Chat v' + v; }).catch(() => {});
/* ================================================================ start */
conv = store.get('cc.conv') || ALL;
renderConv();
refreshUI();
setInterval(() => { expire(); refreshUI(); }, 1000); // typing / online state expire on their own
setInterval(updateAges, 15000);
if (nick) { $('me').textContent = nick; loop(); } else askName(true);
})();
</script>
</body>
</html>