Files
cabinchat/www/index.html
T
Pascal SuterandClaude Opus 5.5 ba3b6a30c6 4.1.0: paste pictures from the clipboard
Pasting an image (e.g. a screenshot) opens a preview with Send/Cancel
before anything is sent. Pasted pictures keep up to 1600 px / ~300 kB so
text in screenshots stays readable. Clipboard contents with text (office
apps put a picture of the text alongside) still paste as text.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 05:05:13 +01:00

1712 lines
82 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">
<meta name="apple-mobile-web-app-title" content="Cabin Chat">
<title>Cabin Chat</title>
<link rel="icon" href="logo.svg" type="image/svg+xml">
<link rel="icon" href="icon-192.png" sizes="192x192" type="image/png">
<link rel="apple-touch-icon" href="apple-touch-icon.png">
<link rel="manifest" href="manifest.json">
<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}
/* profile pictures */
.avatar img{width:100%;height:100%;border-radius:50%;object-fit:cover;display:block}
.name{display:flex;align-items:center;gap:6px}
.name .avatar{width:20px;height:20px;font-size:11px}
.name .avatar .on{display:none}
.chip{display:flex;align-items:center;gap:8px;padding:5px 14px 5px 5px}
.chip .avatar{width:28px;height:28px;font-size:13px}
.chip span{overflow:hidden;text-overflow:ellipsis}
/* mentions */
.mention{color:#9cc0ff;font-weight:600}
.mine .mention{color:#fff;text-decoration:underline;text-underline-offset:2px}
.mention.me{background:rgba(250,204,21,.18);color:#fde68a;border-radius:5px;padding:0 2px}
.bubble.atme:not(.media){box-shadow:inset 3px 0 0 #facc15}
#mentions{position:absolute;left:10px;right:10px;bottom:100%;margin-bottom:6px;max-width:360px;padding:5px;
border:1px solid var(--line);border-radius:14px;background:#232833;box-shadow:0 12px 36px rgba(0,0,0,.6);z-index:5}
#mentions button{display:flex;align-items:center;gap:10px;width:100%;padding:7px 9px;border:0;border-radius:10px;
background:none;text-align:left;font-size:15px}
#mentions button.on{background:rgba(255,255,255,.09)}
#mentions .avatar{width:30px;height:30px;font-size:14px}
footer{position:relative}
/* login & profile */
.card .logo{width:72px;height:72px;margin:0 auto 12px;display:block}
.card input+input{margin-top:10px}
.err{min-height:20px;margin-top:8px;color:var(--bad);font-size:14px}
#sheetBack{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:max(6vh,env(safe-area-inset-top)) 16px 16px;overflow-y:auto}
#sheet{position:relative;padding-top:22px;text-align:left}
#sheet h2{text-align:center}
#sheet>p{text-align:center}
#sheet .avatar.big{width:86px;height:86px;font-size:38px;margin:0 auto 10px;cursor:pointer}
.xbtn{position:absolute;top:10px;right:10px}
.items{display:flex;flex-direction:column;gap:2px;margin-top:8px}
.items button{display:flex;align-items:center;gap:12px;width:100%;padding:12px;border:0;border-radius:12px;background:none;
text-align:left;font-size:15.5px}
.items button:active,.items button:hover{background:rgba(255,255,255,.06)}
.items button small{margin-left:auto;color:var(--muted);font-size:13px}
.items svg{flex:none;width:21px;height:21px;color:var(--muted)}
.items .danger,.items .danger svg{color:var(--bad)}
.primary.danger{background:var(--bad)}
.pasted{display:flex;flex-wrap:wrap;justify-content:center;gap:8px;margin:12px 0 4px}
.pasted img{display:block;max-width:100%;max-height:42vh;border-radius:12px;background:#fff}
.pasted.many img{max-width:calc(50% - 4px);max-height:24vh;object-fit:cover}
.ghost{width:100%;margin-top:8px;padding:11px;border:0;border-radius:14px;background:var(--panel2);font-size:15px}
#sheet input{text-align:left}
.qr{display:block;width:220px;height:220px;margin:4px auto 12px;border-radius:12px;background:#fff}
.linkbox{display:block;padding:10px 12px;border-radius:12px;background:var(--panel2);font:13px/1.4 ui-monospace,monospace;
color:var(--muted);overflow-wrap:anywhere;user-select:all;-webkit-user-select:all}
.note{margin-top:12px;color:var(--muted);font-size:13.5px;text-align:center}
</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="Your profile"></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="mentions" hidden></div>
<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="loginForm">
<img class="logo" src="logo.svg" alt="">
<h2>Welcome aboard</h2>
<p id="lHint">Pick a name and a password. Use the same name and password to join from your other devices.</p>
<input id="nameIn" name="username" autocomplete="username" maxlength="24" placeholder="Your name" autocapitalize="words" enterkeyhint="next">
<input id="pwIn" name="password" type="password" autocomplete="current-password" maxlength="100" placeholder="Password" enterkeyhint="go">
<div class="err" id="lErr"></div>
<button class="primary" id="lBtn">Join the chat</button>
</form>
</div>
<div id="sheetBack" hidden><div class="card" id="sheet"></div></div>
<input type="file" id="avatarFile" accept="image/*" hidden>
<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: logging in gives this device a session token; the server only ever shows user ids
let tok = store.get('cc.tok') || '';
if (!/^[0-9a-f]{32}$/.test(tok)) tok = '';
const oldKey = store.get('cc.key'); // 3.x browser key: lets the first login keep the old id
const legacyId = store.get('cc.uid'); // id used by version 2, to recognise own old messages
let me = store.get('cc.me') || ''; // user id
/* ================================================================ 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 = '', gen = '', 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; };
const avatarUrl = id => { const u = users.get(id); return u && u.ava && u.ava !== '-' ? 'cgi-bin/chat?a=avatar&u=' + id + '&v=' + u.ava : ''; };
function avatar(id) {
const a = el('div', 'avatar');
if (id === ALL) { a.classList.add('group'); a.textContent = '👥'; return a; }
const src = avatarUrl(id);
if (src) { const im = new Image(); im.alt = ''; im.src = src; a.appendChild(im); }
else a.textContent = (Array.from(nickOf(id).trim())[0] || '?').toUpperCase();
a.style.background = 'hsl(' + hue(id) + ' 42% 34%)';
if (id !== me && 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);
/* ================================================================ mentions */
// "@Name" where Name is a known user; names may contain spaces, so the longest match wins
let wordChar = /\w/;
try { wordChar = new RegExp('[\\p{L}\\p{N}_]', 'u'); } catch (e) {}
function knownNames() {
const s = new Set();
for (const u of users.values()) if (u.nick && u.nick !== '?') s.add(u.nick);
return [...s].sort((a, b) => b.length - a.length);
}
function mentionParts(text, names) { // -> strings and {name, text} pieces
const out = [], low = text.toLowerCase();
let last = 0;
for (let i = text.indexOf('@'); i >= 0; i = text.indexOf('@', i + 1)) {
if (i > 0 && wordChar.test(text[i - 1])) continue;
const n = names.find(n => low.startsWith(n.toLowerCase(), i + 1) && !wordChar.test(text.charAt(i + 1 + n.length)));
if (!n) continue;
if (i > last) out.push(text.slice(last, i));
out.push({ name: n, text: text.slice(i, i + 1 + n.length) });
i += n.length; last = i + 1;
}
if (last < text.length) out.push(text.slice(last));
return out;
}
const isMe = name => name.toLowerCase() === nickOf(me).toLowerCase();
const mentionsMe = m => m.type === 't' && !isMine(m) && m.text.includes('@') &&
mentionParts(m.text, knownNames()).some(p => typeof p === 'object' && isMe(p.name));
function textEl(text) {
const s = el('span');
for (const p of mentionParts(text, knownNames())) {
if (typeof p === 'string') s.appendChild(document.createTextNode(p));
else s.appendChild(el('span', 'mention' + (isMe(p.name) ? ' me' : ''), p.text));
}
return s;
}
/* ================================================================ 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');
n.append(avatar(m.from), el('span', null, 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');
if (mentionsMe(m)) b.classList.add('atme');
b.append(textEl(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 = '', headSig = '', meSig = '';
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 hsig = conv + avatarUrl(conv) + nickOf(conv) + isOnline(conv);
if (hsig !== headSig) { headSig = hsig; const ha = $('hAvatar'); ha.textContent = ''; ha.appendChild(avatar(conv)); }
const msig = nickOf(me) + avatarUrl(me);
if (me && msig !== meSig) { meSig = msig; $('me').textContent = ''; $('me').append(avatar(me), el('span', null, nickOf(me))); }
// 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, u] of users) if (serverNow() - u.seen < KEEP) ids.add(id); // accounts stay; show the recent ones
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), ava: avatarUrl(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() { // reload everything with the next poll (quietly, like the first load)
msgs.clear(); convs.clear(); users.clear(); since = 0; ev = ''; loaded = false;
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 < 5 || h[0][0] !== '@') throw new Error('bad response');
offset = +h[0].slice(1) - Date.now() / 1000;
const last = +h[1];
if (me !== h[3]) { me = h[3]; store.set('cc.me', me); }
if (gen && h[4] !== gen) { gen = h[4]; resetAll(); return; } // messages were deleted
gen = h[4];
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, ava] = l.split('\t');
users.set(id, { nick: fromHex(n) || '?', seen: +s, ava: ava || '-' });
} 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) {
const inView = convOf(m) === conv;
if (inView) { render(m); here++; if (!isMine(m)) theirs++; }
if (!isMine(m)) notify(m, inView);
}
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=' + tok + '&since=' + since + '&ev=' + ev + '&w=' + (ev ? 1 : 0);
const r = await fetch(url, { cache: 'no-store', signal: ctrl.signal });
if (r.status === 401) { signedOut(); return 0; }
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
}
let running = false;
async function loop() {
if (running) return;
running = true;
while (tok) {
const d = await pollOnce();
if (d && tok) await nap(d);
wake = null;
}
running = false;
}
// POST to the backend; resolves with the reply text, rejects with the server's message
async function api(act, body, extra) {
const r = await fetch('cgi-bin/chat?a=' + act + (tok ? '&k=' + tok : '') + (extra || ''), {
method: 'POST', body,
headers: { 'Content-Type': body instanceof Blob ? 'image/jpeg' : 'text/plain;charset=utf-8' }
});
const t = (await r.text()).trim();
if (r.status === 401 && tok) { signedOut(); throw new Error('Please log in again'); }
if (!r.ok) throw new Error(t || 'error ' + r.status);
return t;
}
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=' + tok + '&to=' + encodeURIComponent(conv) + (extra || '');
/* ================================================================ typing notices */
let typingSent = 0, typingConv = null;
function sendTyping(to) {
fetch('cgi-bin/chat?a=typing&k=' + tok + '&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(); hideMentions();
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, maxSide = 1280) {
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 = maxSide, 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); };
}
// screenshots (pasted) usually show text: give them more pixels and bytes
async function sendPhoto(file, sharp = false) {
let done = null;
const re = replyTo;
cancelReply();
try {
const { blob, w, h } = sharp ? await shrink(file, 300 * 1024, 1600) : 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);
});
/* paste a picture (e.g. a screenshot): preview first, a paste is easily done by accident */
function pastedImages(dt) {
if (!dt) return [];
let files = [...(dt.files || [])];
if (!files.length) files = [...(dt.items || [])].filter(i => i.kind === 'file').map(i => i.getAsFile()).filter(Boolean);
return files.filter(f => /^image\//.test(f.type));
}
let pasteUrls = [];
function confirmPhotos(files) {
sheet(s => {
const n = files.length;
s.appendChild(el('h2', null, n > 1 ? 'Send ' + n + ' pictures?' : 'Send this picture?'));
s.appendChild(el('p', null, 'To ' + (conv === ALL ? 'everyone' : nickOf(conv))
+ (replyTo && msgs.get(replyTo) ? ', as a reply' : '')));
const box = el('div', 'pasted' + (n > 1 ? ' many' : ''));
for (const f of files) {
const url = URL.createObjectURL(f);
pasteUrls.push(url);
const img = el('img'); img.src = url; img.alt = '';
box.appendChild(img);
}
const send = el('button', 'primary', 'Send'), cancel = el('button', 'ghost', 'Cancel');
send.type = cancel.type = 'button';
send.addEventListener('click', async () => {
closeSheet();
for (const f of files) await sendPhoto(f, true);
});
cancel.addEventListener('click', closeSheet);
s.append(box, send, cancel);
setTimeout(() => send.focus(), 60); // Enter sends, Escape cancels
});
}
document.addEventListener('paste', e => {
if (!me || !$('modal').hidden || !$('sheetBack').hidden) return;
const dt = e.clipboardData, files = pastedImages(dt);
if (!files.length) return;
// office apps copy text together with a picture of it: paste the text then
if (dt.types.includes('text/plain') && dt.getData('text/plain').trim()) return;
e.preventDefault();
confirmPhotos(files.slice(0, 10));
});
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(); closeSheet(); } });
/* ================================================================ 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);
}
// system notifications: shown while the chat runs in the background (another tab or app,
// screen on). Without internet there is no push service, so a closed chat can't be woken up.
// cc.notify: 'all' | 'direct' (private messages and mentions) | 'off'
let swReg = null;
const canNotify = () => 'Notification' in window && window.isSecureContext;
const notifyPref = () => store.get('cc.notify') || 'all';
function notify(m, inView) {
const c = convOf(m), where = m.to === ALL ? m.nick + ' in Everyone' : m.nick;
if (document.hidden || !document.hasFocus()) { sysNotify(m, c, where); return; }
if (!inView) toast((mentionsMe(m) ? '@ ' : '💬 ') + where + ': ' + snippet(m), () => openConv(c));
}
function sysNotify(m, c, where) {
if (!canNotify() || Notification.permission !== 'granted') return;
const pref = notifyPref();
if (pref === 'off' || (pref === 'direct' && m.to === ALL && !mentionsMe(m))) return;
const at = mentionsMe(m), title = (at ? '@ ' : '') + where;
// one notification per chat (newest replaces older ones); mentions stay
const opts = { body: snippet(m), tag: at ? 'cc-at-' + m.id : 'cc-' + c, renotify: true, icon: 'icon-192.png', data: { conv: c } };
if (swReg) { swReg.showNotification(title, opts).catch(() => {}); return; }
try {
const n = new Notification(title, opts);
n.onclick = () => { focus(); openConv(c); n.close(); };
} catch (e) {}
}
async function askNotify() {
if (!canNotify()) {
toast(window.isSecureContext ? 'This browser has no notifications' : 'Notifications need the https:// address');
return false;
}
let p = Notification.permission;
if (p === 'default') p = await Notification.requestPermission();
if (p !== 'granted') toast('Notifications are blocked – allow them in the browser’s site settings');
return p === 'granted';
}
if ('serviceWorker' in navigator && window.isSecureContext) {
navigator.serviceWorker.register('sw.js').then(r => { swReg = r; }).catch(() => {});
navigator.serviceWorker.addEventListener('message', e => {
if (e.data && e.data.cc === 'open' && e.data.conv) openConv(e.data.conv);
});
}
// "install as app": Chrome/Edge/Android offer a prompt, iOS needs Share → Add to Home Screen
let installPrompt = null;
addEventListener('beforeinstallprompt', e => { e.preventDefault(); installPrompt = e; });
const standalone = () => matchMedia('(display-mode: standalone)').matches || navigator.standalone === true;
const ios = /iPhone|iPad|iPod/.test(navigator.userAgent) || (navigator.platform === 'MacIntel' && navigator.maxTouchPoints > 1);
/* ================================================================ 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(); updateMentions(); });
$('bar').addEventListener('submit', e => { e.preventDefault(); sendText(); });
/* ================================================================ mention picker */
let pick = null; // {start, end, ids, sel}
function updateMentions() {
const pos = input.selectionStart ?? input.value.length;
const m = /(?:^|\s)@([^@]{0,24})$/.exec(input.value.slice(0, pos));
if (!m) return hideMentions();
const q = m[1].toLowerCase();
const ids = [...users.keys()].filter(id => {
const n = nickOf(id).toLowerCase();
return id !== me && n !== '?' && (n.startsWith(q) || n.split(/\s+/).some(w => w.startsWith(q)));
}).sort((a, b) => (isOnline(b) - isOnline(a)) || (activity(b) - activity(a))).slice(0, 6);
if (!ids.length) return hideMentions();
pick = { start: pos - m[1].length - 1, end: pos, ids, sel: 0 };
drawMentions();
}
function drawMentions() {
const box = $('mentions');
box.textContent = '';
pick.ids.forEach((id, i) => {
const b = el('button', i === pick.sel ? 'on' : '');
b.type = 'button'; b.dataset.id = id;
b.append(avatar(id), el('span', null, nickOf(id)));
box.appendChild(b);
});
box.hidden = false;
}
function hideMentions() { pick = null; $('mentions').hidden = true; }
function choose(id) {
if (!pick) return;
input.setRangeText('@' + nickOf(id) + ' ', pick.start, pick.end, 'end');
hideMentions(); updateSend(); onTyping(); input.focus();
}
$('mentions').addEventListener('mousedown', e => e.preventDefault());
$('mentions').addEventListener('click', e => { const b = e.target.closest('button'); if (b) choose(b.dataset.id); });
input.addEventListener('keydown', e => {
if (!pick) return;
if (e.key === 'ArrowDown' || e.key === 'ArrowUp') {
pick.sel = (pick.sel + (e.key === 'ArrowDown' ? 1 : pick.ids.length - 1)) % pick.ids.length;
drawMentions(); e.preventDefault();
} else if (e.key === 'Enter' || e.key === 'Tab') { choose(pick.ids[pick.sel]); e.preventDefault(); }
else if (e.key === 'Escape') { hideMentions(); e.stopPropagation(); }
});
input.addEventListener('blur', () => setTimeout(hideMentions, 150));
/* ================================================================ login */
const errMsg = e => /wrong password/.test(e.message) ? 'Wrong password'
: /expired|invalid link/.test(e.message) ? 'This link has expired or was already used'
: /fetch|network|load/i.test(e.message) ? 'Can’t reach the chat – are you on the chat WiFi?' : e.message;
const cleanName = s => clean(s).replace(/@/g, '').slice(0, 24);
let checkTimer = 0, nameTaken = null;
function showLogin(msg) {
$('modal').hidden = false;
$('lErr').textContent = msg || '';
setTimeout(() => ($('nameIn').value ? $('pwIn') : $('nameIn')).focus(), 60);
}
function setTaken(t) {
nameTaken = t;
$('lHint').textContent = t === true ? 'Welcome back! Enter the password for this name.'
: t === false ? 'New name: choose a password (at least 4 characters) to keep it yours.'
: 'Pick a name and a password. Use the same name and password to join from your other devices.';
$('lBtn').textContent = t === true ? 'Log in' : t === false ? 'Create account' : 'Join the chat';
$('pwIn').autocomplete = t === false ? 'new-password' : 'current-password';
}
$('nameIn').addEventListener('input', () => {
clearTimeout(checkTimer);
$('lErr').textContent = '';
const n = cleanName($('nameIn').value);
if (!n) return setTaken(null);
checkTimer = setTimeout(() => fetch('cgi-bin/chat?a=check&n=' + toHex(n), { cache: 'no-store' })
.then(r => r.ok ? r.text() : '')
.then(t => { t = t.trim(); if (cleanName($('nameIn').value) === n) setTaken(t === '1' ? true : t === '0' ? false : null); })
.catch(() => {}), 300);
});
$('loginForm').addEventListener('submit', async e => {
e.preventDefault();
const n = cleanName($('nameIn').value), pw = $('pwIn').value;
if (!n) return $('nameIn').focus();
if (!pw) return $('pwIn').focus();
if (nameTaken === false && pw.length < 4) { $('lErr').textContent = 'Please use at least 4 characters'; return; }
$('lBtn').disabled = true;
try {
const ok = /^[0-9a-f]{32}$/.test(oldKey || '') ? '&ok=' + oldKey : '';
const [k, uid] = (await api('login', pw, '&n=' + toHex(n) + ok)).split('\t');
if (!/^[0-9a-f]{32}$/.test(k)) throw new Error('Unexpected answer from the chat');
signedIn(k, uid);
} catch (err) {
$('lErr').textContent = /wrong password/.test(err.message) ? 'Wrong password for this name' : errMsg(err);
}
$('lBtn').disabled = false;
});
function signedIn(k, uid) {
tok = k; me = uid;
store.set('cc.tok', k); store.set('cc.me', uid);
try { localStorage.removeItem('cc.key'); localStorage.removeItem('cc.nick'); } catch (e) {}
$('modal').hidden = true;
$('pwIn').value = '';
if (document.activeElement) document.activeElement.blur();
loop();
setTimeout(offerNotify, 2500);
}
function signedOut() { // forget this device's session and start over
tok = '';
for (const k of ['cc.tok', 'cc.me', 'cc.read', 'cc.conv']) try { localStorage.removeItem(k); } catch (e) {}
location.replace(location.pathname);
}
function offerNotify() { // permission prompts need a tap, so offer one once per device
if (!canNotify() || Notification.permission !== 'default' || store.get('cc.asked')) return;
store.set('cc.asked', '1');
toast('🔔 Tap here to get notifications for new messages', askNotify);
}
// a "link another device" URL: chat/#link=CODE logs this browser in
async function redeemLink() {
const m = /^#link=([0-9a-f]{32})$/.exec(location.hash);
if (!m) return false;
history.replaceState(null, '', location.pathname + location.search);
try {
const [k, uid] = (await api('redeem', undefined, '&c=' + m[1])).split('\t');
if (!/^[0-9a-f]{32}$/.test(k)) throw new Error('Unexpected answer from the chat');
if (uid !== me) for (const x of ['cc.read', 'cc.conv']) try { localStorage.removeItem(x); } catch (e) {}
store.set('cc.tok', k); store.set('cc.me', uid);
location.replace(location.pathname);
return true;
} catch (e) { toast(errMsg(e)); return false; }
}
/* ================================================================ profile */
const SVG = p => '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round">' + p + '</svg>';
const ICONS = {
photo: '<rect x="3" y="5" width="18" height="14" rx="3.5"/><circle cx="12" cy="12" r="3.2"/>',
nophoto: '<rect x="3" y="5" width="18" height="14" rx="3.5"/><path d="M9 9l6 6M15 9l-6 6"/>',
link: '<rect x="7" y="2.5" width="10" height="19" rx="2.5"/><path d="M11 18.5h2"/>',
bell: '<path d="M6 16V11a6 6 0 0 1 12 0v5l1.5 2h-15z"/><path d="M10 20.5a2.2 2.2 0 0 0 4 0"/>',
install: '<path d="M12 4v11M7.5 10.5L12 15l4.5-4.5"/><path d="M5 19.5h14"/>',
key: '<circle cx="8" cy="15" r="4"/><path d="M11 12l8-8M16 7l2.5 2.5"/>',
out: '<path d="M14 4h4a2 2 0 0 1 2 2v12a2 2 0 0 1-2 2h-4"/><path d="M10 16l-4-4 4-4M6 12h10"/>',
trash: '<path d="M4 7h16M9 7V4.5h6V7M6.5 7l1 13h9l1-13"/>'
};
const CLOSE = SVG('<path d="M6 6l12 12M18 6L6 18"/>');
let linkTimer = 0;
function sheet(build) {
clearInterval(linkTimer);
const s = $('sheet');
s.textContent = '';
const x = el('button', 'icon xbtn'); x.type = 'button'; x.innerHTML = CLOSE; x.setAttribute('aria-label', 'Close');
x.addEventListener('click', closeSheet);
s.appendChild(x);
build(s);
$('sheetBack').hidden = false;
}
function closeSheet() {
clearInterval(linkTimer); $('sheetBack').hidden = true; $('sheet').textContent = '';
pasteUrls.forEach(u => URL.revokeObjectURL(u)); pasteUrls = [];
}
$('sheetBack').addEventListener('click', e => { if (e.target === $('sheetBack')) closeSheet(); });
function item(icon, label, fn, side, cls) {
const b = el('button', cls);
b.type = 'button';
b.innerHTML = SVG(ICONS[icon]);
b.appendChild(el('span', null, label));
if (side) b.appendChild(el('small', null, side));
b.addEventListener('click', fn);
return b;
}
function notifyLabel() {
if (!canNotify()) return 'not available';
if (Notification.permission === 'denied') return 'blocked';
if (Notification.permission !== 'granted') return 'off';
return { all: 'all messages', direct: 'private & @me', off: 'off' }[notifyPref()];
}
async function cycleNotify() {
if (!canNotify() || Notification.permission !== 'granted') {
if (await askNotify()) store.set('cc.notify', 'all');
} else store.set('cc.notify', { all: 'direct', direct: 'off', off: 'all' }[notifyPref()]);
profile();
}
function profile() {
sheet(s => {
const a = avatar(me);
a.classList.add('big'); a.title = 'Change profile picture';
a.addEventListener('click', () => $('avatarFile').click());
s.append(a, el('h2', null, nickOf(me)));
const list = el('div', 'items'), has = !!avatarUrl(me);
list.appendChild(item('photo', has ? 'Change profile picture' : 'Add a profile picture', () => $('avatarFile').click()));
if (has) list.appendChild(item('nophoto', 'Remove profile picture', setAvatar.bind(null, null)));
list.appendChild(item('link', 'Link another device', linkDevice));
list.appendChild(item('bell', 'Notifications', cycleNotify, notifyLabel()));
if (installPrompt || (ios && !standalone())) list.appendChild(item('install', 'Install as app', install));
list.appendChild(item('key', 'Change password', changePassword));
list.appendChild(item('out', 'Log out on this device', () => api('logout').catch(() => {}).then(signedOut)));
list.appendChild(item('trash', 'Delete account', deleteAccount, null, 'danger'));
s.appendChild(list);
});
}
$('me').addEventListener('click', profile);
async function install() {
if (installPrompt) {
installPrompt.prompt();
try { await installPrompt.userChoice; } catch (e) {}
installPrompt = null;
profile();
} else toast('Tap the Share button, then “Add to Home Screen”');
}
function pwField(ph, ac) {
const i = el('input'); i.type = 'password'; i.placeholder = ph; i.autocomplete = ac; i.maxLength = 100;
return i;
}
function formSheet(title, text, fields, btn, danger, run) {
sheet(s => {
s.appendChild(el('h2', null, title));
if (text) s.appendChild(el('p', null, text));
const f = el('form'), user = el('input'), err = el('div', 'err'), b = el('button', 'primary' + (danger ? ' danger' : ''), btn);
user.autocomplete = 'username'; user.value = nickOf(me); user.hidden = true; // for password managers
const back = el('button', 'ghost', 'Back'); back.type = 'button'; back.addEventListener('click', profile);
f.append(user, ...fields, err, b, back);
f.addEventListener('submit', async e => {
e.preventDefault();
err.textContent = ''; b.disabled = true;
try { await run(err); } catch (x) { err.textContent = errMsg(x); }
b.disabled = false;
});
s.appendChild(f);
setTimeout(() => fields[0].focus(), 60);
});
}
function changePassword() {
const o = pwField('Current password', 'current-password'), n1 = pwField('New password', 'new-password'), n2 = pwField('Repeat the new password', 'new-password');
formSheet('Change password', 'Your other devices stay logged in.', [o, n1, n2], 'Save', false, async err => {
if (n1.value.length < 4) { err.textContent = 'Please use at least 4 characters'; return; }
if (n1.value !== n2.value) { err.textContent = 'The new passwords don’t match'; return; }
await api('passwd', o.value + '\n' + n1.value);
closeSheet(); toast('Password changed');
});
}
function deleteAccount() {
const p = pwField('Your password', 'current-password');
formSheet('Delete account', 'This deletes your account, your profile picture and every message and photo you posted, for everyone, and logs out all your devices. Your name becomes free again.',
[p], 'Delete my account', true, async () => { await api('delete', p.value); signedOut(); });
}
// profile picture: square crop, 256 px JPEG (~20 kB); null removes it
async function setAvatar(file) {
try {
let ver;
if (file) {
const img = await loadImage(file);
const S = 256, w = img.naturalWidth, h = img.naturalHeight, m = Math.min(w, h);
const c = document.createElement('canvas'), ctx = c.getContext('2d');
c.width = c.height = S;
ctx.fillStyle = '#fff'; ctx.fillRect(0, 0, S, S);
ctx.drawImage(img, (w - m) / 2, (h - m) / 2, m, m, 0, 0, S, S);
const blob = await new Promise(r => c.toBlob(r, 'image/jpeg', 0.85));
if (!blob) throw new Error('Could not process the picture');
ver = await api('avatar', blob);
} else ver = await api('noavatar');
const u = users.get(me);
if (u) u.ava = ver;
listSig = ''; refreshUI(); renderConv();
if (!$('sheetBack').hidden) profile();
toast(file ? 'Profile picture updated' : 'Profile picture removed');
} catch (e) { toast(errMsg(e)); }
}
$('avatarFile').addEventListener('change', () => {
const f = $('avatarFile').files[0];
$('avatarFile').value = '';
if (f) setAvatar(f);
});
async function linkDevice() {
let t;
try { t = await api('link'); } catch (e) { toast(errMsg(e)); return; }
const [code, ttl] = t.split('\t');
const url = location.origin + location.pathname + '#link=' + code, until = Date.now() + (+ttl || 600) * 1000;
sheet(s => {
s.append(el('h2', null, 'Link another device'),
el('p', null, 'Scan this code with the other device’s camera or open the link there – it will be logged in as ' + nickOf(me) + '.'));
const q = qrSvg(url);
if (q) { const d = el('div'); d.innerHTML = q; d.firstChild.setAttribute('class', 'qr'); s.appendChild(d.firstChild); }
const copy = el('button', 'ghost', 'Copy link'); copy.type = 'button'; copy.addEventListener('click', () => copyText(url));
const back = el('button', 'ghost', 'Back'); back.type = 'button'; back.addEventListener('click', profile);
const note = el('div', 'note');
s.append(el('div', 'linkbox', url), copy, back, note);
const tick = () => {
const left = Math.max(0, Math.round((until - Date.now()) / 1000));
note.textContent = left ? 'Works once · valid for ' + Math.floor(left / 60) + ':' + String(left % 60).padStart(2, '0') : 'This link has expired.';
if (!left) clearInterval(linkTimer);
};
tick();
linkTimer = setInterval(tick, 1000);
});
}
/* ================================================================ QR code */
// byte mode, error correction level M, versions 1-10 (up to 213 bytes) -> SVG markup
function qrSvg(text) {
const RS = [0, [10, 1, 16], [16, 1, 28], [26, 1, 44], [18, 2, 32], [24, 2, 43], [16, 4, 27], [18, 4, 31],
[22, 2, 38, 2, 39], [22, 3, 36, 2, 37], [26, 4, 43, 1, 44]]; // ec per block, (blocks, data bytes)...
const AL = [0, [], [6, 18], [6, 22], [6, 26], [6, 30], [6, 34], [6, 22, 38], [6, 24, 42], [6, 26, 46], [6, 28, 50]];
const data = enc.encode(text);
let v = 1, cap = 0;
for (; v <= 10; v++) {
const t = RS[v]; cap = t[1] * t[2] + (t[3] || 0) * (t[4] || 0);
if (4 + (v < 10 ? 8 : 16) + data.length * 8 <= cap * 8) break;
}
if (v > 10) return '';
const bits = [], put = (x, n) => { for (let i = n - 1; i >= 0; i--) bits.push(x >>> i & 1); };
put(4, 4); put(data.length, v < 10 ? 8 : 16);
for (const b of data) put(b, 8);
put(0, Math.min(4, cap * 8 - bits.length));
while (bits.length % 8) bits.push(0);
const bytes = [];
for (let i = 0; i < bits.length; i += 8) bytes.push(parseInt(bits.slice(i, i + 8).join(''), 2));
for (let p = 0xec; bytes.length < cap; p ^= 0xec ^ 0x11) bytes.push(p);
// Reed-Solomon over GF(256)
const EXP = [], LOG = [];
for (let i = 0, x = 1; i < 255; i++) { EXP[i] = EXP[i + 255] = x; LOG[x] = i; x <<= 1; if (x & 256) x ^= 0x11d; }
const mul = (a, b) => a && b ? EXP[LOG[a] + LOG[b]] : 0;
const t = RS[v], ecn = t[0];
let g = [1];
for (let i = 0; i < ecn; i++) {
const n = Array(g.length + 1).fill(0);
g.forEach((c, j) => { n[j] ^= c; n[j + 1] ^= mul(c, EXP[i]); });
g = n;
}
const blocks = [], ecs = [];
for (let k = 1, pos = 0; k < t.length; k += 2) for (let b = 0; b < t[k]; b++) {
const blk = bytes.slice(pos, pos += t[k + 1]), r = blk.concat(Array(ecn).fill(0));
for (let i = 0; i < blk.length; i++) { const c = r[i]; if (c) g.forEach((x, j) => { r[i + j] ^= mul(x, c); }); }
blocks.push(blk); ecs.push(r.slice(blk.length));
}
const cw = [];
for (let i = 0; i < t[t.length - 1]; i++) for (const b of blocks) if (i < b.length) cw.push(b[i]);
for (let i = 0; i < ecn; i++) for (const e of ecs) cw.push(e[i]);
// matrix: M[y][x] dark?, F[y][x] function module?
const N = v * 4 + 17, M = [], F = [];
for (let i = 0; i < N; i++) { M.push(Array(N).fill(0)); F.push(Array(N).fill(false)); }
const set = (x, y, d) => { M[y][x] = d ? 1 : 0; F[y][x] = true; };
for (const [fx, fy] of [[3, 3], [N - 4, 3], [3, N - 4]])
for (let dy = -4; dy <= 4; dy++) for (let dx = -4; dx <= 4; dx++) {
const x = fx + dx, y = fy + dy, d = Math.max(Math.abs(dx), Math.abs(dy));
if (x >= 0 && y >= 0 && x < N && y < N) set(x, y, d !== 2 && d !== 4);
}
for (let i = 8; i < N - 8; i++) { set(6, i, i % 2 === 0); set(i, 6, i % 2 === 0); }
const al = AL[v], last = al.length - 1;
al.forEach((ay, i) => al.forEach((ax, j) => {
if ((i === 0 && j === 0) || (i === 0 && j === last) || (i === last && j === 0)) return;
for (let dy = -2; dy <= 2; dy++) for (let dx = -2; dx <= 2; dx++) set(ax + dx, ay + dy, Math.max(Math.abs(dx), Math.abs(dy)) !== 1);
}));
const format = mask => {
const d = mask; // level M = 00
let r = d; for (let i = 0; i < 10; i++) r = (r << 1) ^ ((r >>> 9) * 0x537);
const b = ((d << 10) | r) ^ 0x5412, bit = i => (b >>> i & 1) === 1;
for (let i = 0; i <= 5; i++) set(8, i, bit(i));
set(8, 7, bit(6)); set(8, 8, bit(7)); set(7, 8, bit(8));
for (let i = 9; i < 15; i++) set(14 - i, 8, bit(i));
for (let i = 0; i < 8; i++) set(N - 1 - i, 8, bit(i));
for (let i = 8; i < 15; i++) set(8, N - 15 + i, bit(i));
set(8, N - 8, true);
};
format(0);
if (v >= 7) {
let r = v; for (let i = 0; i < 12; i++) r = (r << 1) ^ ((r >>> 11) * 0x1f25);
const b = v << 12 | r;
for (let i = 0; i < 18; i++) { const d = b >>> i & 1, a = N - 11 + i % 3, c = Math.floor(i / 3); set(a, c, d); set(c, a, d); }
}
let k = 0;
for (let right = N - 1; right >= 1; right -= 2) {
if (right === 6) right = 5;
for (let vert = 0; vert < N; vert++) for (let j = 0; j < 2; j++) {
const x = right - j, y = ((right + 1) & 2) === 0 ? N - 1 - vert : vert;
if (!F[y][x] && k < cw.length * 8) { M[y][x] = cw[k >>> 3] >>> (7 - (k & 7)) & 1; k++; }
}
}
const MASKS = [(x, y) => (x + y) % 2, (x, y) => y % 2, (x, y) => x % 3, (x, y) => (x + y) % 3,
(x, y) => (Math.floor(x / 3) + Math.floor(y / 2)) % 2, (x, y) => x * y % 2 + x * y % 3,
(x, y) => (x * y % 2 + x * y % 3) % 2, (x, y) => ((x + y) % 2 + x * y % 3) % 2];
const flip = m => { for (let y = 0; y < N; y++) for (let x = 0; x < N; x++) if (!F[y][x] && !MASKS[m](x, y)) M[y][x] ^= 1; };
const penalty = () => { // the standard's 4 rules, slightly simplified
let p = 0, dark = 0;
const line = get => {
let run = 1, s = '';
for (let i = 0; i < N; i++) {
const c = get(i); s += c;
if (i && c === get(i - 1)) { run++; if (run === 5) p += 3; else if (run > 5) p++; } else run = 1;
}
for (const pat of ['10111010000', '00001011101']) for (let i = s.indexOf(pat); i >= 0; i = s.indexOf(pat, i + 1)) p += 40;
};
for (let i = 0; i < N; i++) { line(j => M[i][j]); line(j => M[j][i]); }
for (let y = 0; y < N; y++) for (let x = 0; x < N; x++) {
dark += M[y][x];
if (x < N - 1 && y < N - 1) { const c = M[y][x]; if (c === M[y][x + 1] && c === M[y + 1][x] && c === M[y + 1][x + 1]) p += 3; }
}
return p + 10 * Math.floor(Math.abs(dark * 20 - N * N * 10) / (N * N));
};
let best = 0, bestP = Infinity;
for (let m = 0; m < 8; m++) { flip(m); format(m); const p = penalty(); if (p < bestP) { bestP = p; best = m; } flip(m); }
flip(best); format(best);
let path = '';
for (let y = 0; y < N; y++) for (let x = 0; x < N; x++) if (M[y][x]) path += 'M' + (x + 4) + ' ' + (y + 4) + 'h1v1h-1z';
return '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ' + (N + 8) + ' ' + (N + 8) +
'" shape-rendering="crispEdges"><rect width="100%" height="100%" fill="#fff"/><path d="' + path + '" fill="#000"/></svg>';
}
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;
const hc = /^#c=([0-9a-f]{16}|\*)$/.exec(location.hash); // opened from a notification
if (hc) { conv = hc[1]; history.replaceState(null, '', location.pathname + location.search); }
renderConv();
refreshUI();
setInterval(() => { expire(); refreshUI(); }, 1000); // typing / online state expire on their own
setInterval(updateAges, 15000);
redeemLink().then(done => { if (done) return; if (tok) loop(); else showLogin(); });
})();
</script>
</body>
</html>