'use strict'; // ---- Chat: the family messenger (see chat.js on the server). It looks like the Signal screen on purpose and shares its styles (sg*) and helpers (sgTime, sgLink...). const ch = { convs: [], cur: null, curConv: null, root: null, es: null, unread: 0, reply: null, tray: [], names: {}, people: null, showArchived: false, sendQ: null, found: null, typing: null, typedAt: 0, pins: [] }; const chq = q => (ch.root || document).querySelector(q); const chApi = (p, o) => jfetch('/api/chat' + p, o); const chPost = (p, body) => chApi(p, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(body) }); const chOnView = () => location.hash.startsWith('#/chat'); const chMounted = () => !!ch.root && document.contains(ch.root); const chDraftKey = id => 'ch_draft:' + (ME ? ME.id : '') + ':' + id; const chGetDraft = id => { try { return localStorage.getItem(chDraftKey(id)) || ''; } catch { return ''; } }; const chSetDraft = (id, t) => { try { t ? localStorage.setItem(chDraftKey(id), t) : localStorage.removeItem(chDraftKey(id)); } catch {} }; // ---- live updates, kept running whatever screen is open (so the unread count on the menu is always right) async function chStart() { if (!allowed('chat') || ch.es) return; try { const st = await chApi('/status'); ch.unread = st.unread || 0; renderNav(activeTab); } catch { return; } ch.es = new EventSource('/api/chat/events'); ch.es.onmessage = e => { let ev; try { ev = JSON.parse(e.data); } catch { return; } chEvent(ev); }; } let chEvT = null; function chEvent(ev) { if (typeof ev.unread === 'number' && ev.unread !== ch.unread) { ch.unread = ev.unread; renderNav(activeTab); } if (ev.t === 'msg' && !ev.out) { const looking = chMounted() && ch.cur === ev.conv && document.visibilityState === 'visible' && document.hasFocus(); if (!looking) { toast((ev.name || 'Chat') + ': ' + (ev.preview || '')); if (typeof sgAlerts === 'function' && sgAlerts().sound && typeof sgChime === 'function') sgChime(); } } if (ev.t === 'announce' && typeof chAnnounceCard === 'function') chAnnounceCard(document.getElementById('annc')); if (ev.t === 'typing') { if (chMounted() && ch.cur === ev.conv) { ch.typing = { conv: ev.conv, name: ev.name, until: Date.now() + 4500 }; chPaintSub(); setTimeout(chPaintSub, 4600); } return; } if (!chMounted()) return; clearTimeout(chEvT); chEvT = setTimeout(chRefresh, 150); } function viewChat(args = []) { ch.cur = args[0] ? decodeURIComponent(args[0]) : null; return chMount($('#view')); } async function chMount(root) { ch.root = root; root.innerHTML = '

Chat

Loadingโ€ฆ

'; root.innerHTML = `

Chat

`; chq('#chnew').onclick = chNewChat; chq('#chset').onclick = chSettings; let t; chq('#chq').oninput = () => { chDrawList(); clearTimeout(t); t = setTimeout(chSearchMessages, 350); }; await chRefresh(true); } async function chRefresh(first) { try { const r = await chApi('/convs'); ch.convs = r.convs; ch.unread = r.unread; renderNav(activeTab); if (!chq('#chlist')) return; chDrawList(); if (ch.cur) await chDrawThread(first); else chq('#chm').innerHTML = '

Choose a chat, or start a new one.

'; } catch (e) { const l = chq('#chlist'); if (l) l.innerHTML = `

${esc(e.message)}

`; } } async function chSearchMessages() { const q = (chq('#chq') || {}).value ? chq('#chq').value.trim() : ''; if (q.length < 2) { ch.found = null; return chDrawList(); } try { const r = await chApi('/search?q=' + encodeURIComponent(q)); if ((chq('#chq') || {}).value.trim() === q) { ch.found = r.results; chDrawList(); } } catch { /* the list still works */ } } function chRow(c) { return `${c.type === 'group' ? icon('chat') : esc(sgInitial(c.name))} ${esc(c.name)}${c.muted ? ' ๐Ÿ”•' : ''}${esc(c.preview || '')}${c.preview || c.ts ? sgTime(c.ts) : ''}${c.unread ? `${c.unread}` : ''}`; } function chDrawList() { const q = (chq('#chq') || {}).value ? chq('#chq').value.toLowerCase().trim() : '', box = chq('#chlist'); if (!box) return; const match = c => !q || c.name.toLowerCase().includes(q) || (c.preview || '').toLowerCase().includes(q), live = ch.convs.filter(c => !c.archived && match(c)), arch = ch.convs.filter(c => c.archived && match(c)); const found = q.length >= 2 && ch.found ? ch.found : []; box.innerHTML = live.map(chRow).join('') + (arch.length ? `${ch.showArchived || q ? arch.map(chRow).join('') : ''}` : '') + (found.length ? `

In messages

${found.map(f => `${esc(f.convName)}${esc(f.msg.name)}: ${esc(f.msg.text)}${sgTime(f.msg.ts)}`).join('')}` : '') || ''; if (!box.innerHTML) box.innerHTML = `

${q ? 'Nothing matches' : 'No chats yet. Tap New to start one.'}

`; const a = box.querySelector('#charch'); if (a) a.onclick = () => { ch.showArchived = !ch.showArchived; chDrawList(); }; box.oncontextmenu = e => { const r = e.target.closest('[data-id]'); if (r) { e.preventDefault(); chChatMenu(r.dataset.id); } }; } /** @Name in a message stands out (and means that person gets an alert even if they muted the group). */ const chMention = html => { const names = Object.values(ch.names || {}).filter(Boolean).sort((a, b) => b.length - a.length); let out = html; for (const n of names) out = out.replace(new RegExp('(^|\\s)@' + esc(n).replace(/[.*+?^${}()|[\]\\]/g, '\\$&') + '(?![\\w])', 'gi'), (x, pre) => pre + '@' + esc(n) + ''); return out; }; const chDur = s => { s = Math.round(+s || 0); return Math.floor(s / 60) + ':' + String(s % 60).padStart(2, '0'); }; function chPoll(m) { const P = m.poll, votes = P.votes || {}, count = id => Object.values(votes).filter(v => v.includes(id)).length, total = Object.keys(votes).length, mine = (ME && votes[ME.id]) || []; return `
๐Ÿ“Š ${esc(P.q)}${P.multi ? 'Choose any' : 'Choose one'}${P.closed ? ' ยท closed' : ''} ${P.options.map(o => { const n = count(o.id); return ``; }).join('')} ${total} ${total === 1 ? 'person has' : 'people have'} voted
`; } function chBubble(m, c, prev) { const att = (m.att || []).map(a => { const u = '/api/chat/file/' + a.id; return /^image\//.test(a.type || '') ? `${esc(a.name || 'photo')}` : a.voice ? `
${(a.wave && a.wave.length ? a.wave : Array(28).fill(30)).map(v => ``).join('')}${chDur(a.dur)}
` : /^audio\//.test(a.type || '') ? `` : /^video\//.test(a.type || '') ? `` : `${icon('clip')}${esc(a.name || 'file')}${a.size ? ' ยท ' + sgSize(a.size) : ''}`; }).join(''); const reacts = {}; Object.values(m.react || {}).forEach(e => { reacts[e] = (reacts[e] || 0) + 1; }); const day = !prev || new Date(prev.ts).toDateString() !== new Date(m.ts).toDateString() ? `
${new Date(m.ts).toLocaleDateString([], { weekday: 'long', month: 'long', day: 'numeric' })}
` : ''; if (m.sys) return `${day}
${esc(m.text)}
`; const tick = m.out && m.status ? `${m.status === 'sent' ? 'โœ“' : 'โœ“โœ“'}` : ''; return `${day}
${m.fwd ? `โ†ช Forwarded from ${esc(m.fwd.name)}` : ''}${c.type === 'group' && !m.out ? `${esc(m.name)}` : ''} ${m.poll ? chPoll(m) : ''}${m.quote ? `
${esc(m.quote.name)}${esc(m.quote.text || 'Message')}
` : ''}${att} ${m.deleted ? 'This message was deleted' : m.text ? `
${chMention(sgLink(esc(m.text)).replace(/\n/g, '
'))}
` : ''} ${m.link && !m.deleted ? `${m.link.image ? `` : ''}${esc(m.link.site || new URL(m.link.url).hostname)}${esc(m.link.title)}${m.link.desc ? `${esc(m.link.desc)}` : ''}` : ''} ${m.exp ? 'โฑ ' : ''}${m.edited ? 'edited ยท ' : ''}${new Date(m.ts).toLocaleTimeString([], { hour: 'numeric', minute: '2-digit' })}${tick ? ' ' + tick : ''} ${Object.keys(reacts).length ? `${Object.entries(reacts).map(([e, n]) => e + (n > 1 ? ' ' + n : '')).join(' ')}` : ''}
`; } async function chDrawThread(first) { const box = chq('#chm'); if (!box) return; const id = ch.cur; let r; try { r = await chApi('/conv/' + encodeURIComponent(id)); } catch (e) { box.innerHTML = `

${esc(e.message)}

`; return; } if (ch.cur !== id || !chq('#chm')) return; ch.names = r.names || {}; const c = r.conv, old = box.querySelector('.sgmsgs'), stick = !old || old.scrollHeight - old.scrollTop - old.clientHeight < 80; if (!box.querySelector('.sgbar')) { box.innerHTML = `
${icon('back')}${c.type === 'group' ? icon('chat') : esc(sgInitial(c.name))}
`; chWireComposer(); chq('#chmore').onclick = () => chChatMenu(ch.cur); const ta = chq('#chtext'); ta.value = chGetDraft(id); ta.style.height = 'auto'; ta.style.height = Math.min(ta.scrollHeight, 140) + 'px'; } ch.curConv = c; ch.names = Object.fromEntries(c.members.map(x => [x.id, x.name])); ch.pins = r.pinned || []; chq('#chtitle').textContent = c.name; chPaintSub(); chDrawPin(); const list = r.msgs, el = chq('#chmsgs'); el.innerHTML = (r.more ? '

Older messages are not shown here

' : '') + list.map((m, i) => chBubble(m, c, list[i - 1])).join('') || '

No messages yet. Say hello.

'; if (first || stick) el.scrollTop = el.scrollHeight; el.onclick = e => { const b = e.target.closest('.sgb'), m0 = b && list.find(m => m.id === b.dataset.id), opt = e.target.closest('.sgopt'), vc = e.target.closest('.sgvoice'), pq = e.target.closest('.sgpq'); if (opt && m0) return chVote(m0, opt.dataset.o); if (vc) return chPlayVoice(vc); if (pq && m0) return chPollWho(m0); if (!b || e.target.closest('a, audio, video')) return; chMessageMenu(m0, c); }; if (c.unread) chPost('/read', { id }).then(() => { const x = ch.convs.find(q => q.id === id); if (x) x.unread = 0; chDrawList(); }).catch(() => {}); } function chMessageMenu(m, c) { if (!m || m.deleted) return; const mine = m.out, el = openSheet('', '', `
${['๐Ÿ‘', 'โค๏ธ', '๐Ÿ˜‚', '๐Ÿ˜ฎ', '๐Ÿ˜ข', '๐Ÿ™'].map(e => ``).join('')}
${m.text ? `` : ''} ${m.text && allowed('tasks') ? `` : ''}${m.text && allowed('recipes') ? `` : ''}${m.text && allowed('calendar') ? `` : ''} ${mine && m.text ? `` : ''}${mine ? `` : ''}
`); el.querySelectorAll('[data-e]').forEach(b => b.onclick = async () => { closeSheet(); try { await chPost('/react', { conv: c.id, msg: m.id, emoji: (m.react && ME && m.react[ME.id]) === b.dataset.e ? '' : b.dataset.e }); } catch (e) { toast(e.message); } }); el.querySelector('#chr').onclick = () => { closeSheet(); ch.reply = m; chDrawReply(); chq('#chtext').focus(); }; const tk = el.querySelector('#chtk'); if (tk) tk.onclick = async () => { closeSheet(); try { await jfetch('/api/tasks', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ list: 'local:inbox', fields: { title: m.text.slice(0, 200), notes: 'From Chat (' + m.name + ')', due: '', done: false } }) }); toast('Added to your tasks', { label: 'Open', run: () => { location.hash = '#/tasks'; } }); } catch (e) { toast(e.message); } }; const sh = el.querySelector('#chsh'); if (sh) sh.onclick = async () => { closeSheet(); try { await jfetch('/api/recipes/shopping/add', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ text: m.text.slice(0, 200) }) }); toast('Added to the shopping list', { label: 'Open', run: () => { location.hash = '#/recipes/shop'; } }); } catch (e) { toast(e.message); } }; const ev = el.querySelector('#chev'); if (ev) ev.onclick = () => { closeSheet(); chMakeEvent(m); }; el.querySelector('#chfw').onclick = () => { closeSheet(); chForward(m, c.id); }; el.querySelector('#chpn').onclick = async () => { closeSheet(); try { await chPost('/pin', { conv: c.id, msg: m.id, on: !ch.pins.some(p => p.id === m.id) }); } catch (e) { toast(e.message); } }; const cp = el.querySelector('#chcp'); if (cp) cp.onclick = async () => { closeSheet(); try { await navigator.clipboard.writeText(m.text); toast('Copied'); } catch { toast('Could not copy'); } }; const ed = el.querySelector('#ched'); if (ed) ed.onclick = () => { closeSheet(); textSheet('Edit message', 'Message', 'Save', async t => { try { await chPost('/edit', { conv: c.id, msg: m.id, text: t }); } catch (e) { toast(e.message); } }, m.text); }; const dl = el.querySelector('#chdl'); if (dl) dl.onclick = () => { closeSheet(); confirmSheet('Delete this message?', 'It disappears for everyone in the chat.', 'Delete', async () => { try { await chPost('/delete', { conv: c.id, msg: m.id }); } catch (e) { toast(e.message); } }); }; } function chDrawReply() { const b = chq('#chrep'); if (!b) return; if (!ch.reply) { b.hidden = true; return; } b.hidden = false; b.innerHTML = `${esc(ch.reply.out ? 'You' : ch.reply.name)}${esc(ch.reply.text || 'Attachment')}`; chq('#chrx').onclick = () => { ch.reply = null; chDrawReply(); }; } function chDrawTray() { const t = chq('#chtray'); if (!t) return; t.hidden = !ch.tray.length; t.innerHTML = ch.tray.map((f, i) => `${/^image\//.test(f.type) ? `` : icon('clip')}${esc(f.name)}`).join(''); t.querySelectorAll('[data-x]').forEach(b => b.onclick = () => { ch.tray.splice(+b.dataset.x, 1); chDrawTray(); }); } function chWireComposer() { const ta = chq('#chtext'), grow = () => { ta.style.height = 'auto'; ta.style.height = Math.min(ta.scrollHeight, 140) + 'px'; }; ta.oninput = () => { grow(); chSetDraft(ch.cur, ta.value); if (ta.value.trim() && Date.now() - ch.typedAt > 3000) { ch.typedAt = Date.now(); chPost('/typing', { conv: ch.cur }).catch(() => {}); } }; chMentionBox(ta); ta.onkeydown = e => { if (e.key === 'Enter' && !e.shiftKey && matchMedia('(pointer: fine)').matches) { e.preventDefault(); chq('#chform').requestSubmit(); } }; chq('#chat').onclick = () => actionSheet('Attach', '', [{ label: 'Photo or file', icon: 'clip', run: () => chq('#chfile').click() }, { label: 'Poll', icon: 'check', run: chNewPoll }]); chq('#chem').onclick = chEmojiPanel; chq('#chmic').onclick = chRecStart; const sw = () => { const has = !!ta.value.trim() || ch.tray.length; chq('#chmic').hidden = has; chq('#chsend').hidden = !has; }; ta.addEventListener('input', sw); sw(); ch.swSend = sw; chq('#chfile').onchange = e => { ch.tray.push(...e.target.files); e.target.value = ''; chDrawTray(); ch.swSend(); }; ta.addEventListener('paste', e => { const fs = [...(e.clipboardData && e.clipboardData.files || [])]; if (fs.length) { ch.tray.push(...fs); chDrawTray(); } }); // The message appears at once, dimmed as "Sendingโ€ฆ"; if it fails, the words and files go back into the box so nothing is lost. chq('#chform').onsubmit = e => { e.preventDefault(); const text = ta.value, files = [...ch.tray], reply = ch.reply, to = ch.cur; if (!text.trim() && !files.length) return; ta.value = ''; grow(); chSetDraft(to, ''); ch.tray = []; ch.reply = null; chDrawTray(); chDrawReply(); ta.focus(); ch.swSend(); const list = chq('#chmsgs'), tmp = document.createElement('div'); tmp.className = 'sgb out'; tmp.style.opacity = '.65'; tmp.innerHTML = `${esc(text) || 'Attachment'}
Sendingโ€ฆ
`; if (list) { list.appendChild(tmp); list.scrollTop = list.scrollHeight; } ch.sendQ = (ch.sendQ || Promise.resolve()).then(async () => { // one at a time, so quick messages arrive in the order you wrote them try { const ids = []; for (const f of files) { const up = await chApi('/upload?conv=' + encodeURIComponent(to) + '&name=' + encodeURIComponent(f.name), { method: 'POST', body: f, headers: { 'content-type': f.type || 'application/octet-stream' } }); ids.push(up.id); } await chPost('/send', { conv: to, text, files: ids, quote: reply ? reply.id : undefined }); tmp.remove(); await chRefresh(); const el = chq('#chmsgs'); if (el) el.scrollTop = el.scrollHeight; } catch (err) { tmp.remove(); toast(err.message || 'Could not send'); if (ch.cur === to && !ta.value) { ta.value = text; grow(); ch.tray = files; ch.reply = reply; chDrawTray(); chDrawReply(); } } }); }; } // ---- starting chats, groups and managing them async function chPeople() { if (!ch.people) ch.people = await chApi('/people'); return ch.people; } async function chNewChat() { let people = []; try { people = await chPeople(); } catch (e) { return toast(e.message); } const el = openSheet('New chat', 'Pick someone in the family', `
${people.map(p => ``).join('') || '

There is nobody else with Chat yet. An admin can turn it on for people in Settings.

'}
${people.length > 1 ? '
' : ''}`); el.querySelectorAll('[data-p]').forEach(b => b.onclick = async () => { try { const r = await chPost('/new', { type: 'direct', with: b.dataset.p }); closeSheet(); location.hash = '#/chat/' + encodeURIComponent(r.conv.id); } catch (e) { toast(e.message); } }); const g = el.querySelector('#chg'); if (g) g.onclick = () => { closeSheet(); chNewGroup(people); }; } function chNewGroup(people) { const el = openSheet('New group', '', `
${people.map(p => ``).join('')}
`); el.querySelector('#chgx').onclick = closeSheet; setTimeout(() => el.querySelector('#chgn').focus(), 60); el.querySelector('#chgf').onsubmit = async e => { e.preventDefault(); try { const r = await chPost('/new', { type: 'group', name: el.querySelector('#chgn').value, members: [...el.querySelectorAll('[data-p]:checked')].map(c => c.dataset.p) }); closeSheet(); location.hash = '#/chat/' + encodeURIComponent(r.conv.id); } catch (x) { el.querySelector('#chge').textContent = x.message; } }; } function chChatMenu(id) { const c = ch.convs.find(x => x.id === id); if (!c) return; const acts = []; acts.push({ label: c.muted ? 'Unmute' : 'Mute', icon: 'bell', run: async () => { try { await chPost('/conv/mute', { id, on: !c.muted }); toast(c.muted ? 'Unmuted' : 'Muted. No alerts from this chat.'); chRefresh(); } catch (e) { toast(e.message); } } }); acts.push({ label: c.archived ? 'Move out of the archive' : 'Archive', icon: 'files', run: async () => { try { await chPost('/conv/archive', { id, on: !c.archived }); if (!c.archived && ch.cur === id) location.hash = '#/chat'; chRefresh(); } catch (e) { toast(e.message); } } }); acts.push({ label: 'Disappearing messages' + (c.ttl ? ' ยท on' : ''), icon: 'clock', run: () => chTtlSheet(c) }); if (c.type === 'group') { acts.push({ label: 'Rename the group', icon: 'edit', run: () => textSheet('Rename group', 'Group name', 'Rename', async n => { try { await chPost('/conv/update', { id, name: n }); chRefresh(); } catch (e) { toast(e.message); } }, c.name) }); acts.push({ label: 'People in the group', icon: 'people', run: () => chMembers(c) }); acts.push({ label: 'Leave the group', icon: 'trash', danger: true, run: () => confirmSheet('Leave this group?', c.name, 'Leave', async () => { try { await chPost('/conv/update', { id, leave: true }); location.hash = '#/chat'; chRefresh(); } catch (e) { toast(e.message); } }) }); } actionSheet(c.name, c.type === 'group' ? c.members.length + ' people' : 'Chat', acts); } async function chMembers(c) { let people = []; try { people = await chPeople(); } catch (e) { return toast(e.message); } const owner = ME && (ME.role === 'admin' || c.by === ME.id), others = people.filter(p => !c.members.some(m => m.id === p.id)); const el = openSheet(c.name, 'People in the group', `
${c.members.map(m => `
${esc(sgInitial(m.name))}${esc(m.name)}${ME && m.id === ME.id ? ' (you)' : ''}${m.id === c.by ? ' ยท made it' : ''}${owner && !(ME && m.id === ME.id) ? `` : ''}
`).join('')}
${others.length ? `

Add someone

${others.map(p => ``).join('')}
` : ''}`); const act = async body => { try { await chPost('/conv/update', { id: c.id, ...body }); closeSheet(); chRefresh(); } catch (e) { toast(e.message); } }; el.querySelectorAll('[data-r]').forEach(b => b.onclick = () => act({ remove: [b.dataset.r] })); el.querySelectorAll('[data-a]').forEach(b => b.onclick = () => act({ add: [b.dataset.a] })); } /** The line under the chat's name: who is typing, or who is here, or (for a group) who is in it, and the disappearing-messages timer. */ function chPaintSub() { const el = chq('#chsub'), c = ch.curConv; if (!el || !c) return; const ty = ch.typing && ch.typing.conv === c.id && ch.typing.until > Date.now() ? ch.typing.name + ' is typingโ€ฆ' : ''; const ago = t => { const m = Math.round((Date.now() - t) / 60000); return m < 1 ? 'just now' : m < 60 ? m + ' min ago' : m < 1440 ? Math.round(m / 60) + ' h ago' : new Date(t).toLocaleDateString([], { month: 'short', day: 'numeric' }); }; const base = c.type === 'group' ? c.members.map(x => x.name).join(', ') : c.presence ? (c.presence.online ? 'โ— Online' : c.presence.seen ? 'Active ' + ago(c.presence.seen) : '') : ''; el.textContent = ty || (base + (c.ttl ? (base ? ' ยท ' : '') + 'โฑ ' + (c.ttl === 3600 ? '1 hour' : c.ttl === 86400 ? '1 day' : '1 week') : '')); el.style.color = ty ? 'var(--accent)' : ''; } function chDrawPin() { const b = chq('#chpin'); if (!b) return; if (!ch.pins.length) { b.hidden = true; return; } const last = ch.pins[ch.pins.length - 1]; b.hidden = false; b.innerHTML = `๐Ÿ“Œ${ch.pins.length > 1 ? ch.pins.length + ' pinned messages' : 'Pinned message'}${esc(last.text || (last.att && last.att[0] ? last.att[0].name : 'Attachment'))}`; b.onclick = () => { const el = openSheet('Pinned', '', `
${ch.pins.slice().reverse().map(m => `
`).join('')}
`); el.querySelectorAll('[data-go]').forEach(x => x.onclick = () => { closeSheet(); const t = chq(`.sgb[data-id="${CSS.escape(x.dataset.go)}"]`); if (t) { t.scrollIntoView({ block: 'center' }); t.classList.add('flash'); setTimeout(() => t.classList.remove('flash'), 1400); } }); el.querySelectorAll('[data-un]').forEach(x => x.onclick = async () => { closeSheet(); try { await chPost('/pin', { conv: ch.cur, msg: x.dataset.un, on: false }); } catch (e) { toast(e.message); } }); }; } function chTtlSheet(c) { actionSheet('Disappearing messages', 'New messages in this chat go after the time you pick', [[0, 'Off'], [3600, '1 hour'], [86400, '1 day'], [604800, '1 week']].map(([v, l]) => ({ label: l + ((c.ttl || 0) === v ? ' โœ“' : ''), icon: 'clock', run: async () => { try { await chPost('/conv/ttl', { id: c.id, ttl: v }); } catch (e) { toast(e.message); } } }))); } function chForward(m, from) { const el = openSheet('Forward toโ€ฆ', '', `
${ch.convs.map(c => ``).join('') || '

No chats yet.

'}
`); el.querySelectorAll('[data-t]').forEach(b => b.onclick = async () => { closeSheet(); try { await chPost('/forward', { from, to: b.dataset.t, msg: m.id }); toast('Forwarded'); } catch (e) { toast(e.message); } }); } /** Type @ in a group and the people in it are offered. */ function chMentionBox(ta) { let box; const close = () => { if (box) { box.remove(); box = null; } }; const show = () => { const c = ch.curConv; if (!c || c.type !== 'group') return close(); const before = ta.value.slice(0, ta.selectionStart), m = /(^|\s)@(\w*)$/.exec(before); if (!m) return close(); const rows = c.members.filter(x => ME && x.id !== ME.id && x.name.toLowerCase().startsWith(m[2].toLowerCase())).slice(0, 6); if (!rows.length) return close(); if (!box) { box = document.createElement('div'); box.className = 'ctsug'; box.style.cssText += ';bottom:100%;top:auto'; ta.closest('form').style.position = 'relative'; ta.closest('form').appendChild(box); } box.innerHTML = rows.map((r, i) => ``).join(''); box.querySelectorAll('button').forEach(b => b.onmousedown = e => { e.preventDefault(); const r = rows[+b.dataset.i], pos = ta.selectionStart - m[2].length; ta.value = ta.value.slice(0, pos) + r.name + ' ' + ta.value.slice(ta.selectionStart); ta.selectionStart = ta.selectionEnd = pos + r.name.length + 1; close(); ta.dispatchEvent(new Event('input')); }); }; ta.addEventListener('input', show); ta.addEventListener('blur', () => setTimeout(close, 120)); } async function chVote(m, opt) { const P = m.poll, mine = (ME && (P.votes || {})[ME.id]) || []; let opts; if (P.multi) opts = mine.includes(opt) ? mine.filter(x => x !== opt) : [...mine, opt]; else opts = mine.includes(opt) ? [] : [opt]; try { await chPost('/vote', { conv: ch.cur, msg: m.id, opts }); } catch (e) { toast(e.message); } } function chPollWho(m) { const P = m.poll, votes = P.votes || {}; const el = openSheet(P.q, P.multi ? 'Choose any' : 'Choose one', `
${P.options.map(o => { const who = Object.entries(votes).filter(([, v]) => v.includes(o.id)).map(([u]) => ch.names[u] || 'Someone'); return `
${esc(o.text)}${who.length ? esc(who.join(', ')) : 'No votes yet'}
`; }).join('')}
${m.out && !P.closed ? '
' : ''}`); const c = el.querySelector('#chpc'); if (c) c.onclick = async () => { closeSheet(); try { await chPost('/poll/close', { conv: ch.cur, msg: m.id }); } catch (e) { toast(e.message); } }; } function chNewPoll() { const el = openSheet('New poll', 'Ask the chat to vote', `
${[1, 2].map(i => ``).join('')}
`); el.querySelector('#chpx').onclick = closeSheet; setTimeout(() => el.querySelector('#chpq').focus(), 60); el.querySelector('#chpadd').onclick = () => { const box = el.querySelector('#chpo'); if (box.children.length >= 8) return; const i = document.createElement('input'); i.type = 'text'; i.className = 'chpopt'; i.maxLength = 100; i.placeholder = 'Choice ' + (box.children.length + 1); i.style.marginTop = '6px'; box.appendChild(i); i.focus(); }; el.querySelector('#chpf').onsubmit = async e => { e.preventDefault(); try { await chPost('/poll', { conv: ch.cur, question: el.querySelector('#chpq').value, options: [...el.querySelectorAll('.chpopt')].map(x => x.value), multi: el.querySelector('#chpm').checked }); closeSheet(); await chRefresh(); const l = chq('#chmsgs'); if (l) l.scrollTop = l.scrollHeight; } catch (x) { el.querySelector('#chpe').textContent = x.message; } }; } // ---- voice messages: play (one at a time) ... function chPlayVoice(box) { const a = ch.audio || (ch.audio = new Audio()), same = ch.playing === box; if (ch.playing && ch.playing !== box) chStopVoice(); if (same && !a.paused) { a.pause(); box.querySelector('.sgvp').innerHTML = icon('play'); return; } if (!same) { a.src = box.dataset.src; ch.playing = box; a.onended = chStopVoice; a.ontimeupdate = () => { const d = a.duration || +box.dataset.dur || 1, bars = box.querySelectorAll('.sgbars i'), k = Math.round(a.currentTime / d * bars.length); bars.forEach((b, i) => b.classList.toggle('on', i < k)); box.querySelector('.sgvt').textContent = chDur(a.currentTime); }; } a.play().then(() => { box.querySelector('.sgvp').innerHTML = icon('pause'); }).catch(() => toast('Could not play that')); } function chStopVoice() { const a = ch.audio, b = ch.playing; if (a) a.pause(); if (b) { b.querySelector('.sgvp').innerHTML = icon('play'); b.querySelectorAll('.sgbars i').forEach(x => x.classList.remove('on')); b.querySelector('.sgvt').textContent = chDur(b.dataset.dur); } ch.playing = null; } // ... and record async function chRecStart() { if (ch.rec) return; if (!navigator.mediaDevices || !window.MediaRecorder) return toast('This browser cannot record audio'); let stream; try { stream = await navigator.mediaDevices.getUserMedia({ audio: true }); } catch { return toast('Allow the microphone to record a voice message'); } const type = ['audio/mp4', 'audio/webm;codecs=opus', 'audio/webm', 'audio/ogg;codecs=opus'].find(t => MediaRecorder.isTypeSupported(t)) || '', mr = new MediaRecorder(stream, type ? { mimeType: type } : undefined), chunks = [], wave = []; let ac, an, tick; try { ac = new (window.AudioContext || window.webkitAudioContext)(); an = ac.createAnalyser(); an.fftSize = 256; ac.createMediaStreamSource(stream).connect(an); const buf = new Uint8Array(an.fftSize); tick = setInterval(() => { an.getByteTimeDomainData(buf); let mx = 0; for (const v of buf) mx = Math.max(mx, Math.abs(v - 128)); wave.push(Math.min(100, Math.round(mx / 128 * 140))); }, 200); } catch { /* no waveform: the message still works */ } mr.ondataavailable = e => { if (e.data.size) chunks.push(e.data); }; mr.start(); ch.rec = { mr, chunks, wave, stream, ac, tick, t0: Date.now(), type: mr.mimeType || type || 'audio/webm' }; chDrawRec(); ch.rec.timer = setInterval(chDrawRec, 500); } function chRecEnd() { const r = ch.rec; if (!r) return; clearInterval(r.timer); clearInterval(r.tick); try { r.mr.state !== 'inactive' && r.mr.stop(); } catch {} r.stream.getTracks().forEach(t => t.stop()); try { r.ac && r.ac.close(); } catch {} ch.rec = null; const f = chq('#chform'); if (f) f.classList.remove('rec'); const b = chq('#chrecbar'); if (b) b.remove(); } function chDrawRec() { const r = ch.rec, f = chq('#chform'); if (!r || !f) return; f.classList.add('rec'); let b = chq('#chrecbar'); if (!b) { b = document.createElement('div'); b.id = 'chrecbar'; b.className = 'chrecbar'; b.innerHTML = `0:00`; f.appendChild(b); b.querySelector('#chrx2').onclick = chRecEnd; b.querySelector('#chrs').onclick = chRecSend; } b.querySelector('#chrt').textContent = chDur((Date.now() - r.t0) / 1000); } async function chRecSend() { const r = ch.rec; if (!r) return; const to = ch.cur, secs = Math.round((Date.now() - r.t0) / 1000); if (secs < 1) return chRecEnd(); const done = new Promise(ok => { r.mr.onstop = ok; }); try { r.mr.stop(); } catch {} await done; const blob = new Blob(r.chunks, { type: r.type }), wave = r.wave.slice(); chRecEnd(); const bars = []; const n = 32; for (let i = 0; i < n; i++) { const seg = wave.slice(Math.floor(i * wave.length / n), Math.max(Math.floor(i * wave.length / n) + 1, Math.floor((i + 1) * wave.length / n))); bars.push(seg.length ? Math.max(...seg) : 20); } const ext = /mp4/.test(r.type) ? 'm4a' : /ogg/.test(r.type) ? 'ogg' : 'webm'; try { const up = await chApi(`/upload?conv=${encodeURIComponent(to)}&name=${encodeURIComponent('Voice message.' + ext)}&voice=1&dur=${secs}&wave=${bars.join(',')}`, { method: 'POST', body: blob, headers: { 'content-type': r.type.split(';')[0] } }); await chPost('/send', { conv: to, files: [up.id] }); await chRefresh(); const l = chq('#chmsgs'); if (l) l.scrollTop = l.scrollHeight; } catch (e) { toast(e.message || 'Could not send the voice message'); } } // ---- emoji const CH_EMOJI = '๐Ÿ˜€ ๐Ÿ˜ƒ ๐Ÿ˜„ ๐Ÿ˜ ๐Ÿ˜† ๐Ÿ˜… ๐Ÿ˜‚ ๐Ÿคฃ ๐Ÿ˜Š ๐Ÿ™‚ ๐Ÿ˜‰ ๐Ÿ˜ ๐Ÿฅฐ ๐Ÿ˜˜ ๐Ÿ˜‹ ๐Ÿ˜Ž ๐Ÿค— ๐Ÿค” ๐Ÿ˜ ๐Ÿ˜ด ๐Ÿ˜ข ๐Ÿ˜ญ ๐Ÿ˜ฎ ๐Ÿ˜ฑ ๐Ÿ˜ก ๐Ÿฅณ ๐Ÿ˜‡ ๐Ÿ™ ๐Ÿ‘ ๐Ÿ‘Ž ๐Ÿ‘ ๐Ÿ™Œ ๐Ÿ’ช ๐Ÿ‘‹ โค๏ธ ๐Ÿงก ๐Ÿ’› ๐Ÿ’š ๐Ÿ’™ ๐Ÿ’œ ๐Ÿ”ฅ โญ โœจ ๐ŸŽ‰ ๐ŸŽ‚ ๐ŸŽ ๐Ÿ• ๐Ÿ” ๐ŸŽ โ˜• ๐Ÿช ๐Ÿ  ๐Ÿš— โœˆ๏ธ โ˜€๏ธ ๐ŸŒง๏ธ โ„๏ธ ๐ŸŒˆ ๐Ÿถ ๐Ÿฑ ๐ŸŒธ โœ… โŒ โ“ ๐Ÿ’ฏ'.split(' '); function chEmojiPanel() { const f = chq('#chform'), old = chq('#chemo'); if (old) return old.remove(); const box = document.createElement('div'); box.id = 'chemo'; box.className = 'chemo'; box.innerHTML = CH_EMOJI.map(e => ``).join(''); f.appendChild(box); box.onclick = e => { const b = e.target.closest('[data-e]'); if (!b) return; const ta = chq('#chtext'), pos = ta.selectionStart || ta.value.length; ta.value = ta.value.slice(0, pos) + b.dataset.e + ta.value.slice(ta.selectionEnd || pos); ta.selectionStart = ta.selectionEnd = pos + b.dataset.e.length; ta.dispatchEvent(new Event('input')); ta.focus(); }; } // ---- from a message into the rest of the hub function chMakeEvent(m) { const today = new Date(), d = today.getFullYear() + '-' + String(today.getMonth() + 1).padStart(2, '0') + '-' + String(today.getDate()).padStart(2, '0'); const el = openSheet('Add to the calendar', 'From a message in Chat', `
`); el.querySelector('#chex').onclick = closeSheet; el.querySelector('#chef').onsubmit = async e => { e.preventDefault(); try { const cals = await jfetch('/api/cal/list'), c = cals.find(x => x.local && !x.shared); if (!c) throw new Error('There is no calendar to add to'); const day = el.querySelector('#ched2').value, tm = el.querySelector('#chetm').value, allDay = !tm, end = tm ? new Date(new Date(day + 'T' + tm).getTime() + 3600e3) : null; const endStr = allDay ? day : day + 'T' + String(end.getHours()).padStart(2, '0') + ':' + String(end.getMinutes()).padStart(2, '0'); await jfetch('/api/cal/event', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ cal: c.id, fields: { title: el.querySelector('#chet').value, location: '', notes: 'From Chat (' + m.name + ')', allDay, start: allDay ? day : day + 'T' + tm, end: endStr, tz: Intl.DateTimeFormat().resolvedOptions().timeZone, repeat: 'none' } }) }); closeSheet(); toast('Added to the calendar', { label: 'Open', run: () => { location.hash = '#/calendar'; } }); } catch (x) { el.querySelector('#chee').textContent = x.message; } }; } /** From anywhere in the hub: "Share to Chat". Picks a chat and sends the text (with a link back to the thing). */ async function shareToChat(text) { if (!allowed('chat')) return toast('Chat is not turned on for you'); let convs = []; try { convs = (await chApi('/convs')).convs.filter(c => !c.archived); } catch (e) { return toast(e.message); } const el = openSheet('Share to Chat', text.length > 90 ? text.slice(0, 90) + 'โ€ฆ' : text, `
${convs.map(c => ``).join('') || '

Start a chat first.

'}
`); el.querySelectorAll('[data-t]').forEach(b => b.onclick = async () => { closeSheet(); try { await chPost('/send', { conv: b.dataset.t, text }); toast('Shared', { label: 'Open', run: () => { location.hash = '#/chat/' + encodeURIComponent(b.dataset.t); } }); } catch (e) { toast(e.message); } }); } // ---- settings: quiet hours, and the family announcement (admin) async function chSettings() { let pr, an = null; try { [pr, an] = await Promise.all([chApi('/prefs'), chApi('/announcement')]); } catch (e) { return toast(e.message); } const q = pr.quiet, admin = ME && ME.role === 'admin'; const el = openSheet('Chat settings', '', `
${admin ? `

Family announcement

Shown at the top of everyone's Home. Leave it empty and save to take it down.

` : ''}
`); el.querySelector('#chsx').onclick = closeSheet; el.querySelector('#chsf').onsubmit = async e => { e.preventDefault(); try { await chPost('/prefs', { quiet: { on: el.querySelector('#chqo').checked, from: el.querySelector('#chqf').value, to: el.querySelector('#chqt').value } }); if (admin) await chPost('/announcement', { text: el.querySelector('#chan').value }); closeSheet(); toast('Saved'); } catch (x) { el.querySelector('#chse').textContent = x.message; } }; } /** Home: the family announcement, if there is one (each person can dismiss it). */ async function chAnnounceCard(el) { if (!el || !allowed('chat')) return; let a = null; try { a = await chApi('/announcement'); } catch { return; } let gone = ''; try { gone = localStorage.getItem('ch_ann_gone:' + (ME ? ME.id : '')) || ''; } catch {} if (!a || a.id === gone) { el.innerHTML = ''; return; } el.innerHTML = `
${icon('chat')}Family announcement ยท ${esc(a.by)}${esc(a.text)}
`; el.querySelector('#ancx').onclick = () => { try { localStorage.setItem('ch_ann_gone:' + (ME ? ME.id : ''), a.id); } catch {} el.innerHTML = ''; }; }