/**
* The room view inside a situation's sheet: presence, a pinned Known /
* Disputed / Unknown synthesis, open questions, evidence-first posts with
* earned badges, community notes with the bridging rule drawn in the open,
* anchors that fly the globe and scrub the ribbon, floating reactions, and
* a reply bar that offers Capture before text.
*/
import { icon } from './icons.js';
import { $, $$, h, esc, ago, haptic, toast, reducedMotion } from './dom.js';
import { KIND, badgesFor, noteStatus, BRIDGE } from './rooms.js';
import { avatar } from './cards.js';
import { llShort, utc, fmtKm } from './bands.js';
import { mediaUrl } from './witness.js';
const REACTIONS = [
{ id: 'seen', icon: 'eyes', label: 'Seeing it too' },
{ id: 'concern', icon: 'hazards', label: 'Concerned' },
{ id: 'thanks', icon: 'hand', label: 'Thanks' },
{ id: 'q', icon: 'question', label: 'Need answers' },
];
export function createRoomView({
rooms,
rt,
globe,
getChrome,
onCapture,
onCompose,
}) {
let cur = null; // { s, r, el }
let pinIds = [];
function clearPins() {
for (const id of pinIds) globe.removePin(id);
pinIds = [];
getChrome()?.setExtraPips([]);
}
function pinPosts(r) {
clearPins();
for (const p of r.posts) {
if (!p.anchor || !Number.isFinite(p.anchor.lat)) continue;
const kind = p.evidence?.live
? 'live'
: p.kind === 'witness'
? 'witness'
: 'post';
const id = globe.addPin({
id: `post:${p.id}`,
lon: p.anchor.lon,
lat: p.anchor.lat,
kind: p.hologram ? 'hologram' : kind,
label: `${r.numbering.get(p.id)} ${KIND[p.kind]?.name || ''}`,
headingDeg: p.evidence?.headingDeg,
});
if (id) pinIds.push(id);
}
getChrome()?.setExtraPips(
r.posts
.filter((p) => p.anchor?.t)
.map((p) => ({
at: p.anchor.t,
label: r.numbering.get(p.id),
color: p.kind === 'witness' ? '#ebc777' : '#f4f7fb',
})),
);
}
/* ---------------- rendering ---------------- */
function citeChip(c) {
if (!c) return '';
const label = /^O\d/.test(c)
? `OBS ${c.slice(1)}`
: c === 'O-cam'
? 'CAM'
: c;
return `${esc(label)} `;
}
function synthHtml(r) {
const sy = r.synth;
const sec = (id, title, list) =>
list.length
? `
${title}${list.length}
${list
.map(
(l) =>
`${esc(l.text)} ${l.cites
.filter(Boolean)
.map((c) => citeChip(c))
.join('')} `,
)
.join('')} `
: '';
return `
${icon('sparkles')}Local synthesis ${sy.n} posts · ${sy.obs} observations · ${esc(sy.hash.slice(0, 8))}
${sec('known', 'Known', sy.known)}${sec('disputed', 'Disputed', sy.disputed)}${sec('unknown', 'Unknown', sy.unknown)}
`;
}
function noteHtml(n, p) {
const st = noteStatus(n, n.mine);
const bar = (c) => {
const x = st.by[c];
const pct = x.n ? Math.round((x.h / x.n) * 100) : 0;
return `${c} ${x.h}/${x.n} `;
};
const why = st.shown
? 'Raters who usually disagree both found it helpful'
: st.status === 'not-bridged'
? `Not shown: one cluster rates it below ${Math.round(BRIDGE.minHelpful * 100)} %`
: `Not shown yet: needs ${BRIDGE.minPerCluster}+ raters from cluster ${st.status.replace('needs-', '').split('').join(' and ')}`;
return `
${icon('note')}${st.shown ? 'Community note' : 'Proposed note'}${p.example ? ' · example' : ''}
${st.shown ? `
${esc(n.text)}
` : `
Show the proposed note ${esc(n.text)}
`}
${icon('bridge')}Bridging ${bar('A')}${bar('B')}${esc(why)}
${n.mine ? `You rated ${n.mine.helpful ? 'helpful' : 'not helpful'} as cluster ${esc(n.mine.cluster)} ` : `Helpful Not helpful `}
`;
}
function postHtml(p, r, depth = 0) {
const s = r.situation;
const k = KIND[p.kind] || KIND.context;
const badges = badgesFor(p, s, rt.me);
const replies = r.repliesOf(p);
const num = r.numbering.get(p.id);
const anchor =
p.anchor && Number.isFinite(p.anchor.lat)
? `${icon('pin')}${esc(llShort(p.anchor.lat, p.anchor.lon, 3))}${p.anchor.t ? ` · ${esc(utc(new Date(p.anchor.t), { seconds: false }))}` : ''} `
: '';
const media =
p.evidence?.captureId || p.evidence?.uploadId
? `${p.evidence.unverified ? 'Unverified upload ' : `${icon('sealFill')} `}
`
: '';
return `
${icon(k.icon)}
${esc(k.name)} ${esc(p.author.handle)}${p.author.self ? ' (you)' : ''} ${esc(ago(p.at))} · ${esc(num)}
${p.example ? 'Example ' : ''}
${esc(p.text)}
${media}
${badges.length ? `${badges.map((b) => `${icon(b.id === 'there' ? 'location' : b.id === 'sealed' ? 'sealFill' : b.id === 'local' ? 'home' : b.id === 'unverified' ? 'hazards' : 'checkmark')}${esc(b.label)}${b.detail ? ` ${esc(b.detail)} ` : ''} `).join('')}
` : ''}
${anchor}
${icon('agree')}${p.votes.up}
${icon('dispute')}${p.votes.dn}
${icon('reply')}
${(p.notes || []).map((n) => noteHtml(n, p)).join('')}
${replies.length ? `${replies.map((x) => postHtml(x, r, depth + 1)).join('')}
` : ''}
`;
}
function presenceHtml(r) {
const here = rt.presence(r.id);
const ex = r.participants.filter((a) => a.example).slice(0, 4);
return `
${here.map((a, i) => avatar({ handle: a.handle, self: a.self }, i).replace('class="av', 'class="av live')).join('')}
${here.length} watching${here.length > 1 ? ' · live across your tabs' : ''}
${ex.map(avatar).join('')}
`;
}
async function render(s, el, { focusPost } = {}) {
const r = await rooms.room(s);
cur = { s, r, el };
rt.join(r.id);
el.innerHTML = `
${presenceHtml(r)}
${synthHtml(r)}
${r.hasExamples ? '
Example Fictional people (handles end in .example) show how a room works. Only the sensor numbers are live; your own posts are real and stay on this device.
' : ''}
${r.openQ.length ? `
${icon('question')}Open questions float until answered
${r.openQ.map((p) => postHtml(p, r)).join('')}` : ''}
${icon('sealFill')}Evidence first then recency, never followers
${r.ordered
.filter((p) => !r.openQ.includes(p))
.map((p) => postHtml(p, r))
.join('')}
${r.posts.length} posts · ledger ${esc(r.synth.hash.slice(0, 12))}
`;
hydrateMedia(el);
pinPosts(r);
if (focusPost) {
const pe = $(`[data-post="${CSS.escape(focusPost)}"]`, el);
pe?.scrollIntoView({ block: 'center' });
pe?.classList.add('flash');
}
return r;
}
async function hydrateMedia(el) {
for (const m of $$('.p-media[data-media]', el)) {
const u = await mediaUrl(m.dataset.media, m.dataset.store);
if (!u) continue;
m.insertAdjacentHTML(
'afterbegin',
m.dataset.video
? ` `
: ` `,
);
}
}
/* ---------------- reactions ---------------- */
function reactionRail() {
return `${REACTIONS.map((x) => `${icon(x.icon)} `).join('')}
`;
}
function floatReaction(host, kind) {
if (!host || reducedMotion()) return;
const x = REACTIONS.find((r) => r.id === kind) || REACTIONS[0];
const el = h(`${icon(x.icon)} `);
el.style.setProperty('--dx', `${Math.round(Math.random() * 24 - 12)}px`);
host.appendChild(el);
el.animate(
[
{ transform: 'translate(0, 0) scale(.6)', opacity: 0 },
{
transform: 'translate(var(--dx), -40px) scale(1.1)',
opacity: 1,
offset: 0.2,
},
{
transform: 'translate(calc(var(--dx) * -1), -190px) scale(.9)',
opacity: 0,
},
],
{ duration: 2200, easing: 'cubic-bezier(.2,.7,.3,1)' },
).finished.then(() => el.remove());
}
/* ---------------- events ---------------- */
async function rerender(keepScroll) {
if (!cur) return;
const sc = keepScroll?.scrollTop;
await render(cur.s, cur.el);
if (keepScroll) keepScroll.scrollTop = sc;
}
async function onClick(e, { scroller, flyTo, scrub }) {
if (!cur) return false;
const r = cur.r;
const postEl = e.target.closest('[data-post]');
const post = postEl
? r.posts.find((p) => p.id === postEl.dataset.post)
: null;
const anchor = e.target.closest('[data-anchor]');
if (anchor && post?.anchor) {
haptic('light');
flyTo(post.anchor, cur.s);
if (post.anchor.t) scrub(post.anchor.t);
return true;
}
const vote = e.target.closest('[data-vote]');
if (vote && post) {
haptic('tick');
await rooms.vote(post, vote.dataset.vote);
await rerender(scroller);
return true;
}
if (e.target.closest('[data-reply]') && post) {
onCompose(cur.s, { replyTo: post });
return true;
}
const rate = e.target.closest('[data-rate]');
if (rate && post) {
const nid = rate.closest('[data-note]').dataset.note;
const note = post.notes.find((n) => n.id === nid);
const mine = await rooms.rate(note, rate.dataset.rate === '1');
const { why } = await rooms.myCluster();
haptic('success');
const st = noteStatus(note, mine);
toast(
`Rated as cluster ${mine.cluster} (${why})${st.shown ? ' · note now bridged' : ''}`,
{ icon: icon('bridge') },
);
await rerender(scroller);
return true;
}
const cite = e.target.closest('[data-cite]');
if (cite) {
const id = cite.dataset.cite;
const target = [...r.numbering.entries()].find(([, v]) => v === id)?.[0];
const el = target
? $(`[data-post="${CSS.escape(target)}"]`, cur.el)
: null;
if (el) {
el.scrollIntoView({
block: 'center',
behavior: reducedMotion() ? 'auto' : 'smooth',
});
el.classList.remove('flash');
void el.offsetWidth;
el.classList.add('flash');
} else
toast(
`${id}: ${id.startsWith('O') ? 'sensor observation from the brief' : 'cited source'}`,
{ icon: icon('info') },
);
return true;
}
const react = e.target.closest('[data-react]');
if (react) {
haptic('tick');
rt.react(r.id, react.dataset.react);
floatReaction(react.closest('.sheet-dock'), react.dataset.react);
return true;
}
const tog = e.target.closest('[data-act="react-toggle"]');
if (tog) {
const dock = tog.closest('.sheet-dock');
const open = !dock.classList.contains('react-open');
dock.classList.toggle('react-open', open);
tog.setAttribute('aria-expanded', String(open));
haptic('tick');
return true;
}
if (e.target.closest('[data-act="capture-reply"]')) {
onCapture(cur.s);
return true;
}
if (e.target.closest('[data-act="write"]')) {
onCompose(cur.s, {});
return true;
}
return false;
}
rt.on('react', ({ room, kind }) => {
if (cur && room === cur.r.id)
floatReaction(document.querySelector('.brief-sheet .sheet-dock'), kind);
});
rt.on('presence', () => {
if (!cur) return;
const pr = $('.presence', cur.el);
if (pr) pr.outerHTML = presenceHtml(cur.r);
});
rooms.on('post', (p) => {
if (cur && p.room === cur.r.id) {
const sc = cur.el.closest('.sheet-body');
rerender(sc);
}
});
return {
render,
onClick,
reactionRail,
replyBar: () =>
`${icon('viewfinder')}Reply with evidence Seal what you see ${icon('note')}Write ${icon('hand')}
`,
close() {
clearPins();
cur = null;
rt.leave();
},
get current() {
return cur;
},
fmtKm,
};
}